Followup a88df43d: make $wgDebugDumpSql log commented queries again
[lhc/web/wiklou.git] / includes / db / Database.php
1 <?php
2
3 /**
4 * @defgroup Database Database
5 *
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
8 *
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
23 *
24 * @file
25 * @ingroup Database
26 */
27
28 /**
29 * Database abstraction object
30 * @ingroup Database
31 */
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
35
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
38
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
41
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
45
46 protected $mServer, $mUser, $mPassword, $mDBname;
47
48 /** @var BagOStuff APC cache */
49 protected $srvCache;
50
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
54
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
59
60 protected $mTablePrefix;
61 protected $mSchema;
62 protected $mFlags;
63 protected $mForeign;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
67 /** @var array */
68 protected $mSessionVars = array();
69
70 protected $preparedArgs;
71
72 protected $htmlErrors;
73
74 protected $delimiter = ';';
75
76 /**
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
79 *
80 * @var int
81 */
82 protected $mTrxLevel = 0;
83
84 /**
85 * Either a short hexidecimal string if a transaction is active or ""
86 *
87 * @var string
88 * @see DatabaseBase::mTrxLevel
89 */
90 protected $mTrxShortId = '';
91
92 /**
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
96 *
97 * @var float|null
98 * @see DatabaseBase::mTrxLevel
99 */
100 private $mTrxTimestamp = null;
101
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
104
105 /**
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
108 *
109 * @var string
110 * @see DatabaseBase::mTrxLevel
111 */
112 private $mTrxFname = null;
113
114 /**
115 * Record if possible write queries were done in the last transaction started
116 *
117 * @var bool
118 * @see DatabaseBase::mTrxLevel
119 */
120 private $mTrxDoneWrites = false;
121
122 /**
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
124 *
125 * @var bool
126 * @see DatabaseBase::mTrxLevel
127 */
128 private $mTrxAutomatic = false;
129
130 /**
131 * Array of levels of atomicity within transactions
132 *
133 * @var array
134 */
135 private $mTrxAtomicLevels = array();
136
137 /**
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
139 *
140 * @var bool
141 */
142 private $mTrxAutomaticAtomic = false;
143
144 /**
145 * Track the seconds spent in write queries for the current transaction
146 *
147 * @var float
148 */
149 private $mTrxWriteDuration = 0.0;
150
151 /**
152 * @since 1.21
153 * @var resource File handle for upgrade
154 */
155 protected $fileHandle = null;
156
157 /**
158 * @since 1.22
159 * @var string[] Process cache of VIEWs names in the database
160 */
161 protected $allViews = null;
162
163 /** @var TransactionProfiler */
164 protected $trxProfiler;
165
166 /**
167 * A string describing the current software version, and possibly
168 * other details in a user-friendly way. Will be listed on Special:Version, etc.
169 * Use getServerVersion() to get machine-friendly information.
170 *
171 * @return string Version information from the database server
172 */
173 public function getServerInfo() {
174 return $this->getServerVersion();
175 }
176
177 /**
178 * @return string Command delimiter used by this database engine
179 */
180 public function getDelimiter() {
181 return $this->delimiter;
182 }
183
184 /**
185 * Boolean, controls output of large amounts of debug information.
186 * @param bool|null $debug
187 * - true to enable debugging
188 * - false to disable debugging
189 * - omitted or null to do nothing
190 *
191 * @return bool|null Previous value of the flag
192 */
193 public function debug( $debug = null ) {
194 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
195 }
196
197 /**
198 * Turns buffering of SQL result sets on (true) or off (false). Default is
199 * "on".
200 *
201 * Unbuffered queries are very troublesome in MySQL:
202 *
203 * - If another query is executed while the first query is being read
204 * out, the first query is killed. This means you can't call normal
205 * MediaWiki functions while you are reading an unbuffered query result
206 * from a normal wfGetDB() connection.
207 *
208 * - Unbuffered queries cause the MySQL server to use large amounts of
209 * memory and to hold broad locks which block other queries.
210 *
211 * If you want to limit client-side memory, it's almost always better to
212 * split up queries into batches using a LIMIT clause than to switch off
213 * buffering.
214 *
215 * @param null|bool $buffer
216 * @return null|bool The previous value of the flag
217 */
218 public function bufferResults( $buffer = null ) {
219 if ( is_null( $buffer ) ) {
220 return !(bool)( $this->mFlags & DBO_NOBUFFER );
221 } else {
222 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
223 }
224 }
225
226 /**
227 * Turns on (false) or off (true) the automatic generation and sending
228 * of a "we're sorry, but there has been a database error" page on
229 * database errors. Default is on (false). When turned off, the
230 * code should use lastErrno() and lastError() to handle the
231 * situation as appropriate.
232 *
233 * Do not use this function outside of the Database classes.
234 *
235 * @param null|bool $ignoreErrors
236 * @return bool The previous value of the flag.
237 */
238 protected function ignoreErrors( $ignoreErrors = null ) {
239 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
240 }
241
242 /**
243 * Gets the current transaction level.
244 *
245 * Historically, transactions were allowed to be "nested". This is no
246 * longer supported, so this function really only returns a boolean.
247 *
248 * @return int The previous value
249 */
250 public function trxLevel() {
251 return $this->mTrxLevel;
252 }
253
254 /**
255 * Get the UNIX timestamp of the time that the transaction was established
256 *
257 * This can be used to reason about the staleness of SELECT data
258 * in REPEATABLE-READ transaction isolation level.
259 *
260 * @return float|null Returns null if there is not active transaction
261 * @since 1.25
262 */
263 public function trxTimestamp() {
264 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
265 }
266
267 /**
268 * Get/set the table prefix.
269 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
270 * @return string The previous table prefix.
271 */
272 public function tablePrefix( $prefix = null ) {
273 return wfSetVar( $this->mTablePrefix, $prefix );
274 }
275
276 /**
277 * Get/set the db schema.
278 * @param string $schema The database schema to set, or omitted to leave it unchanged.
279 * @return string The previous db schema.
280 */
281 public function dbSchema( $schema = null ) {
282 return wfSetVar( $this->mSchema, $schema );
283 }
284
285 /**
286 * Set the filehandle to copy write statements to.
287 *
288 * @param resource $fh File handle
289 */
290 public function setFileHandle( $fh ) {
291 $this->fileHandle = $fh;
292 }
293
294 /**
295 * Get properties passed down from the server info array of the load
296 * balancer.
297 *
298 * @param string $name The entry of the info array to get, or null to get the
299 * whole array
300 *
301 * @return array|mixed|null
302 */
303 public function getLBInfo( $name = null ) {
304 if ( is_null( $name ) ) {
305 return $this->mLBInfo;
306 } else {
307 if ( array_key_exists( $name, $this->mLBInfo ) ) {
308 return $this->mLBInfo[$name];
309 } else {
310 return null;
311 }
312 }
313 }
314
315 /**
316 * Set the LB info array, or a member of it. If called with one parameter,
317 * the LB info array is set to that parameter. If it is called with two
318 * parameters, the member with the given name is set to the given value.
319 *
320 * @param string $name
321 * @param array $value
322 */
323 public function setLBInfo( $name, $value = null ) {
324 if ( is_null( $value ) ) {
325 $this->mLBInfo = $name;
326 } else {
327 $this->mLBInfo[$name] = $value;
328 }
329 }
330
331 /**
332 * @return TransactionProfiler
333 */
334 protected function getTransactionProfiler() {
335 return $this->trxProfiler
336 ? $this->trxProfiler
337 : Profiler::instance()->getTransactionProfiler();
338 }
339
340 /**
341 * Returns true if this database supports (and uses) cascading deletes
342 *
343 * @return bool
344 */
345 public function cascadingDeletes() {
346 return false;
347 }
348
349 /**
350 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
351 *
352 * @return bool
353 */
354 public function cleanupTriggers() {
355 return false;
356 }
357
358 /**
359 * Returns true if this database is strict about what can be put into an IP field.
360 * Specifically, it uses a NULL value instead of an empty string.
361 *
362 * @return bool
363 */
364 public function strictIPs() {
365 return false;
366 }
367
368 /**
369 * Returns true if this database uses timestamps rather than integers
370 *
371 * @return bool
372 */
373 public function realTimestamps() {
374 return false;
375 }
376
377 /**
378 * Returns true if this database does an implicit sort when doing GROUP BY
379 *
380 * @return bool
381 */
382 public function implicitGroupby() {
383 return true;
384 }
385
386 /**
387 * Returns true if this database does an implicit order by when the column has an index
388 * For example: SELECT page_title FROM page LIMIT 1
389 *
390 * @return bool
391 */
392 public function implicitOrderby() {
393 return true;
394 }
395
396 /**
397 * Returns true if this database can do a native search on IP columns
398 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
399 *
400 * @return bool
401 */
402 public function searchableIPs() {
403 return false;
404 }
405
406 /**
407 * Returns true if this database can use functional indexes
408 *
409 * @return bool
410 */
411 public function functionalIndexes() {
412 return false;
413 }
414
415 /**
416 * Return the last query that went through DatabaseBase::query()
417 * @return string
418 */
419 public function lastQuery() {
420 return $this->mLastQuery;
421 }
422
423 /**
424 * Returns true if the connection may have been used for write queries.
425 * Should return true if unsure.
426 *
427 * @return bool
428 */
429 public function doneWrites() {
430 return (bool)$this->mDoneWrites;
431 }
432
433 /**
434 * Returns the last time the connection may have been used for write queries.
435 * Should return a timestamp if unsure.
436 *
437 * @return int|float UNIX timestamp or false
438 * @since 1.24
439 */
440 public function lastDoneWrites() {
441 return $this->mDoneWrites ?: false;
442 }
443
444 /**
445 * @return bool Whether there is a transaction open with possible write queries
446 * @since 1.27
447 */
448 public function writesPending() {
449 return $this->mTrxLevel && $this->mTrxDoneWrites;
450 }
451
452 /**
453 * Returns true if there is a transaction open with possible write
454 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
455 *
456 * @return bool
457 */
458 public function writesOrCallbacksPending() {
459 return $this->mTrxLevel && (
460 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
461 );
462 }
463
464 /**
465 * Get the time spend running write queries for this
466 *
467 * High times could be due to scanning, updates, locking, and such
468 *
469 * @return float|bool Returns false if not transaction is active
470 * @since 1.26
471 */
472 public function pendingWriteQueryDuration() {
473 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
474 }
475
476 /**
477 * Is a connection to the database open?
478 * @return bool
479 */
480 public function isOpen() {
481 return $this->mOpened;
482 }
483
484 /**
485 * Set a flag for this connection
486 *
487 * @param int $flag DBO_* constants from Defines.php:
488 * - DBO_DEBUG: output some debug info (same as debug())
489 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
490 * - DBO_TRX: automatically start transactions
491 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
492 * and removes it in command line mode
493 * - DBO_PERSISTENT: use persistant database connection
494 */
495 public function setFlag( $flag ) {
496 $this->mFlags |= $flag;
497 }
498
499 /**
500 * Clear a flag for this connection
501 *
502 * @param int $flag DBO_* constants from Defines.php:
503 * - DBO_DEBUG: output some debug info (same as debug())
504 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
505 * - DBO_TRX: automatically start transactions
506 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
507 * and removes it in command line mode
508 * - DBO_PERSISTENT: use persistant database connection
509 */
510 public function clearFlag( $flag ) {
511 $this->mFlags &= ~$flag;
512 }
513
514 /**
515 * Returns a boolean whether the flag $flag is set for this connection
516 *
517 * @param int $flag DBO_* constants from Defines.php:
518 * - DBO_DEBUG: output some debug info (same as debug())
519 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
520 * - DBO_TRX: automatically start transactions
521 * - DBO_PERSISTENT: use persistant database connection
522 * @return bool
523 */
524 public function getFlag( $flag ) {
525 return !!( $this->mFlags & $flag );
526 }
527
528 /**
529 * General read-only accessor
530 *
531 * @param string $name
532 * @return string
533 */
534 public function getProperty( $name ) {
535 return $this->$name;
536 }
537
538 /**
539 * @return string
540 */
541 public function getWikiID() {
542 if ( $this->mTablePrefix ) {
543 return "{$this->mDBname}-{$this->mTablePrefix}";
544 } else {
545 return $this->mDBname;
546 }
547 }
548
549 /**
550 * Return a path to the DBMS-specific SQL file if it exists,
551 * otherwise default SQL file
552 *
553 * @param string $filename
554 * @return string
555 */
556 private function getSqlFilePath( $filename ) {
557 global $IP;
558 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
559 if ( file_exists( $dbmsSpecificFilePath ) ) {
560 return $dbmsSpecificFilePath;
561 } else {
562 return "$IP/maintenance/$filename";
563 }
564 }
565
566 /**
567 * Return a path to the DBMS-specific schema file,
568 * otherwise default to tables.sql
569 *
570 * @return string
571 */
572 public function getSchemaPath() {
573 return $this->getSqlFilePath( 'tables.sql' );
574 }
575
576 /**
577 * Return a path to the DBMS-specific update key file,
578 * otherwise default to update-keys.sql
579 *
580 * @return string
581 */
582 public function getUpdateKeysPath() {
583 return $this->getSqlFilePath( 'update-keys.sql' );
584 }
585
586 /**
587 * Get information about an index into an object
588 * @param string $table Table name
589 * @param string $index Index name
590 * @param string $fname Calling function name
591 * @return mixed Database-specific index description class or false if the index does not exist
592 */
593 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
594
595 /**
596 * Wrapper for addslashes()
597 *
598 * @param string $s String to be slashed.
599 * @return string Slashed string.
600 */
601 abstract function strencode( $s );
602
603 /**
604 * Constructor.
605 *
606 * FIXME: It is possible to construct a Database object with no associated
607 * connection object, by specifying no parameters to __construct(). This
608 * feature is deprecated and should be removed.
609 *
610 * DatabaseBase subclasses should not be constructed directly in external
611 * code. DatabaseBase::factory() should be used instead.
612 *
613 * @param array $params Parameters passed from DatabaseBase::factory()
614 */
615 function __construct( array $params ) {
616 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
617
618 $this->srvCache = ObjectCache::getLocalServerInstance( 'hash' );
619
620 $server = $params['host'];
621 $user = $params['user'];
622 $password = $params['password'];
623 $dbName = $params['dbname'];
624 $flags = $params['flags'];
625 $tablePrefix = $params['tablePrefix'];
626 $schema = $params['schema'];
627 $foreign = $params['foreign'];
628
629 $this->mFlags = $flags;
630 if ( $this->mFlags & DBO_DEFAULT ) {
631 if ( $wgCommandLineMode ) {
632 $this->mFlags &= ~DBO_TRX;
633 } else {
634 $this->mFlags |= DBO_TRX;
635 }
636 }
637
638 $this->mSessionVars = $params['variables'];
639
640 /** Get the default table prefix*/
641 if ( $tablePrefix === 'get from global' ) {
642 $this->mTablePrefix = $wgDBprefix;
643 } else {
644 $this->mTablePrefix = $tablePrefix;
645 }
646
647 /** Get the database schema*/
648 if ( $schema === 'get from global' ) {
649 $this->mSchema = $wgDBmwschema;
650 } else {
651 $this->mSchema = $schema;
652 }
653
654 $this->mForeign = $foreign;
655
656 if ( isset( $params['trxProfiler'] ) ) {
657 $this->trxProfiler = $params['trxProfiler']; // override
658 }
659
660 if ( $user ) {
661 $this->open( $server, $user, $password, $dbName );
662 }
663 }
664
665 /**
666 * Called by serialize. Throw an exception when DB connection is serialized.
667 * This causes problems on some database engines because the connection is
668 * not restored on unserialize.
669 */
670 public function __sleep() {
671 throw new MWException( 'Database serialization may cause problems, since ' .
672 'the connection is not restored on wakeup.' );
673 }
674
675 /**
676 * Given a DB type, construct the name of the appropriate child class of
677 * DatabaseBase. This is designed to replace all of the manual stuff like:
678 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
679 * as well as validate against the canonical list of DB types we have
680 *
681 * This factory function is mostly useful for when you need to connect to a
682 * database other than the MediaWiki default (such as for external auth,
683 * an extension, et cetera). Do not use this to connect to the MediaWiki
684 * database. Example uses in core:
685 * @see LoadBalancer::reallyOpenConnection()
686 * @see ForeignDBRepo::getMasterDB()
687 * @see WebInstallerDBConnect::execute()
688 *
689 * @since 1.18
690 *
691 * @param string $dbType A possible DB type
692 * @param array $p An array of options to pass to the constructor.
693 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
694 * @throws MWException If the database driver or extension cannot be found
695 * @return DatabaseBase|null DatabaseBase subclass or null
696 */
697 final public static function factory( $dbType, $p = array() ) {
698 $canonicalDBTypes = array(
699 'mysql' => array( 'mysqli', 'mysql' ),
700 'postgres' => array(),
701 'sqlite' => array(),
702 'oracle' => array(),
703 'mssql' => array(),
704 );
705
706 $driver = false;
707 $dbType = strtolower( $dbType );
708 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
709 $possibleDrivers = $canonicalDBTypes[$dbType];
710 if ( !empty( $p['driver'] ) ) {
711 if ( in_array( $p['driver'], $possibleDrivers ) ) {
712 $driver = $p['driver'];
713 } else {
714 throw new MWException( __METHOD__ .
715 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
716 }
717 } else {
718 foreach ( $possibleDrivers as $posDriver ) {
719 if ( extension_loaded( $posDriver ) ) {
720 $driver = $posDriver;
721 break;
722 }
723 }
724 }
725 } else {
726 $driver = $dbType;
727 }
728 if ( $driver === false ) {
729 throw new MWException( __METHOD__ .
730 " no viable database extension found for type '$dbType'" );
731 }
732
733 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
734 // and everything else doesn't use a schema (e.g. null)
735 // Although postgres and oracle support schemas, we don't use them (yet)
736 // to maintain backwards compatibility
737 $defaultSchemas = array(
738 'mssql' => 'get from global',
739 );
740
741 $class = 'Database' . ucfirst( $driver );
742 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
743 // Resolve some defaults for b/c
744 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
745 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
746 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
747 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
748 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
749 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
750 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
751 if ( !isset( $p['schema'] ) ) {
752 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
753 }
754 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
755
756 return new $class( $p );
757 } else {
758 return null;
759 }
760 }
761
762 protected function installErrorHandler() {
763 $this->mPHPError = false;
764 $this->htmlErrors = ini_set( 'html_errors', '0' );
765 set_error_handler( array( $this, 'connectionErrorHandler' ) );
766 }
767
768 /**
769 * @return bool|string
770 */
771 protected function restoreErrorHandler() {
772 restore_error_handler();
773 if ( $this->htmlErrors !== false ) {
774 ini_set( 'html_errors', $this->htmlErrors );
775 }
776 if ( $this->mPHPError ) {
777 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
778 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
779
780 return $error;
781 } else {
782 return false;
783 }
784 }
785
786 /**
787 * @param int $errno
788 * @param string $errstr
789 */
790 public function connectionErrorHandler( $errno, $errstr ) {
791 $this->mPHPError = $errstr;
792 }
793
794 /**
795 * Create a log context to pass to wfLogDBError or other logging functions.
796 *
797 * @param array $extras Additional data to add to context
798 * @return array
799 */
800 protected function getLogContext( array $extras = array() ) {
801 return array_merge(
802 array(
803 'db_server' => $this->mServer,
804 'db_name' => $this->mDBname,
805 'db_user' => $this->mUser,
806 ),
807 $extras
808 );
809 }
810
811 /**
812 * Closes a database connection.
813 * if it is open : commits any open transactions
814 *
815 * @throws MWException
816 * @return bool Operation success. true if already closed.
817 */
818 public function close() {
819 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
820 throw new MWException( "Transaction idle callbacks still pending." );
821 }
822 if ( $this->mConn ) {
823 if ( $this->trxLevel() ) {
824 if ( !$this->mTrxAutomatic ) {
825 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
826 " performing implicit commit before closing connection!" );
827 }
828
829 $this->commit( __METHOD__, 'flush' );
830 }
831
832 $closed = $this->closeConnection();
833 $this->mConn = false;
834 } else {
835 $closed = true;
836 }
837 $this->mOpened = false;
838
839 return $closed;
840 }
841
842 /**
843 * Make sure isOpen() returns true as a sanity check
844 *
845 * @throws DBUnexpectedError
846 */
847 protected function assertOpen() {
848 if ( !$this->isOpen() ) {
849 throw new DBUnexpectedError( $this, "DB connection was already closed." );
850 }
851 }
852
853 /**
854 * Closes underlying database connection
855 * @since 1.20
856 * @return bool Whether connection was closed successfully
857 */
858 abstract protected function closeConnection();
859
860 /**
861 * @param string $error Fallback error message, used if none is given by DB
862 * @throws DBConnectionError
863 */
864 function reportConnectionError( $error = 'Unknown error' ) {
865 $myError = $this->lastError();
866 if ( $myError ) {
867 $error = $myError;
868 }
869
870 # New method
871 throw new DBConnectionError( $this, $error );
872 }
873
874 /**
875 * The DBMS-dependent part of query()
876 *
877 * @param string $sql SQL query.
878 * @return ResultWrapper|bool Result object to feed to fetchObject,
879 * fetchRow, ...; or false on failure
880 */
881 abstract protected function doQuery( $sql );
882
883 /**
884 * Determine whether a query writes to the DB.
885 * Should return true if unsure.
886 *
887 * @param string $sql
888 * @return bool
889 */
890 protected function isWriteQuery( $sql ) {
891 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
892 }
893
894 /**
895 * Determine whether a SQL statement is sensitive to isolation level.
896 * A SQL statement is considered transactable if its result could vary
897 * depending on the transaction isolation level. Operational commands
898 * such as 'SET' and 'SHOW' are not considered to be transactable.
899 *
900 * @param string $sql
901 * @return bool
902 */
903 protected function isTransactableQuery( $sql ) {
904 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
905 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
906 }
907
908 /**
909 * Run an SQL query and return the result. Normally throws a DBQueryError
910 * on failure. If errors are ignored, returns false instead.
911 *
912 * In new code, the query wrappers select(), insert(), update(), delete(),
913 * etc. should be used where possible, since they give much better DBMS
914 * independence and automatically quote or validate user input in a variety
915 * of contexts. This function is generally only useful for queries which are
916 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
917 * as CREATE TABLE.
918 *
919 * However, the query wrappers themselves should call this function.
920 *
921 * @param string $sql SQL query
922 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
923 * comment (you can use __METHOD__ or add some extra info)
924 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
925 * maybe best to catch the exception instead?
926 * @throws MWException
927 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
928 * for a successful read query, or false on failure if $tempIgnore set
929 */
930 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
931 global $wgUser;
932
933 $this->mLastQuery = $sql;
934
935 $isWriteQuery = $this->isWriteQuery( $sql );
936 if ( $isWriteQuery ) {
937 $reason = $this->getReadOnlyReason();
938 if ( $reason !== false ) {
939 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
940 }
941 # Set a flag indicating that writes have been done
942 $this->mDoneWrites = microtime( true );
943 }
944
945 # Add a comment for easy SHOW PROCESSLIST interpretation
946 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
947 $userName = $wgUser->getName();
948 if ( mb_strlen( $userName ) > 15 ) {
949 $userName = mb_substr( $userName, 0, 15 ) . '...';
950 }
951 $userName = str_replace( '/', '', $userName );
952 } else {
953 $userName = '';
954 }
955
956 // Add trace comment to the begin of the sql string, right after the operator.
957 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
958 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
959
960 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
961 $this->begin( __METHOD__ . " ($fname)" );
962 $this->mTrxAutomatic = true;
963 }
964
965 # Keep track of whether the transaction has write queries pending
966 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
967 $this->mTrxDoneWrites = true;
968 $this->getTransactionProfiler()->transactionWritingIn(
969 $this->mServer, $this->mDBname, $this->mTrxShortId );
970 }
971
972 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
973 # generalizeSQL will probably cut down the query to reasonable
974 # logging size most of the time. The substr is really just a sanity check.
975 if ( $isMaster ) {
976 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
977 $totalProf = 'DatabaseBase::query-master';
978 } else {
979 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
980 $totalProf = 'DatabaseBase::query';
981 }
982 # Include query transaction state
983 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
984
985 $profiler = Profiler::instance();
986 if ( !$profiler instanceof ProfilerStub ) {
987 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
988 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
989 }
990
991 if ( $this->debug() ) {
992 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname, $commentedSql ) );
993 }
994
995 $queryId = MWDebug::query( $sql, $fname, $isMaster );
996
997 # Avoid fatals if close() was called
998 $this->assertOpen();
999
1000 # Do the query and handle errors
1001 $startTime = microtime( true );
1002 $ret = $this->doQuery( $commentedSql );
1003 $queryRuntime = microtime( true ) - $startTime;
1004 # Log the query time and feed it into the DB trx profiler
1005 $this->getTransactionProfiler()->recordQueryCompletion(
1006 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1007
1008 MWDebug::queryTime( $queryId );
1009
1010 # Try reconnecting if the connection was lost
1011 if ( false === $ret && $this->wasErrorReissuable() ) {
1012 # Transaction is gone, like it or not
1013 $hadTrx = $this->mTrxLevel; // possible lost transaction
1014 $this->mTrxLevel = 0;
1015 $this->mTrxIdleCallbacks = array(); // bug 65263
1016 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1017 wfDebug( "Connection lost, reconnecting...\n" );
1018 # Stash the last error values since ping() might clear them
1019 $lastError = $this->lastError();
1020 $lastErrno = $this->lastErrno();
1021 if ( $this->ping() ) {
1022 wfDebug( "Reconnected\n" );
1023 $server = $this->getServer();
1024 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1025 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1026
1027 if ( $hadTrx ) {
1028 # Leave $ret as false and let an error be reported.
1029 # Callers may catch the exception and continue to use the DB.
1030 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1031 } else {
1032 # Should be safe to silently retry (no trx and thus no callbacks)
1033 $startTime = microtime( true );
1034 $ret = $this->doQuery( $commentedSql );
1035 $queryRuntime = microtime( true ) - $startTime;
1036 # Log the query time and feed it into the DB trx profiler
1037 $this->getTransactionProfiler()->recordQueryCompletion(
1038 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1039 }
1040 } else {
1041 wfDebug( "Failed\n" );
1042 }
1043 }
1044
1045 if ( false === $ret ) {
1046 $this->reportQueryError(
1047 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1048 }
1049
1050 $res = $this->resultObject( $ret );
1051
1052 // Destroy profile sections in the opposite order to their creation
1053 ScopedCallback::consume( $queryProfSection );
1054 ScopedCallback::consume( $totalProfSection );
1055
1056 if ( $isWriteQuery && $this->mTrxLevel ) {
1057 $this->mTrxWriteDuration += $queryRuntime;
1058 }
1059
1060 return $res;
1061 }
1062
1063 /**
1064 * Report a query error. Log the error, and if neither the object ignore
1065 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1066 *
1067 * @param string $error
1068 * @param int $errno
1069 * @param string $sql
1070 * @param string $fname
1071 * @param bool $tempIgnore
1072 * @throws DBQueryError
1073 */
1074 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1075 if ( $this->ignoreErrors() || $tempIgnore ) {
1076 wfDebug( "SQL ERROR (ignored): $error\n" );
1077 } else {
1078 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1079 wfLogDBError(
1080 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1081 $this->getLogContext( array(
1082 'method' => __METHOD__,
1083 'errno' => $errno,
1084 'error' => $error,
1085 'sql1line' => $sql1line,
1086 'fname' => $fname,
1087 ) )
1088 );
1089 wfDebug( "SQL ERROR: " . $error . "\n" );
1090 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1091 }
1092 }
1093
1094 /**
1095 * Intended to be compatible with the PEAR::DB wrapper functions.
1096 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1097 *
1098 * ? = scalar value, quoted as necessary
1099 * ! = raw SQL bit (a function for instance)
1100 * & = filename; reads the file and inserts as a blob
1101 * (we don't use this though...)
1102 *
1103 * @param string $sql
1104 * @param string $func
1105 *
1106 * @return array
1107 */
1108 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1109 /* MySQL doesn't support prepared statements (yet), so just
1110 * pack up the query for reference. We'll manually replace
1111 * the bits later.
1112 */
1113 return array( 'query' => $sql, 'func' => $func );
1114 }
1115
1116 /**
1117 * Free a prepared query, generated by prepare().
1118 * @param string $prepared
1119 */
1120 protected function freePrepared( $prepared ) {
1121 /* No-op by default */
1122 }
1123
1124 /**
1125 * Execute a prepared query with the various arguments
1126 * @param string $prepared The prepared sql
1127 * @param mixed $args Either an array here, or put scalars as varargs
1128 *
1129 * @return ResultWrapper
1130 */
1131 public function execute( $prepared, $args = null ) {
1132 if ( !is_array( $args ) ) {
1133 # Pull the var args
1134 $args = func_get_args();
1135 array_shift( $args );
1136 }
1137
1138 $sql = $this->fillPrepared( $prepared['query'], $args );
1139
1140 return $this->query( $sql, $prepared['func'] );
1141 }
1142
1143 /**
1144 * For faking prepared SQL statements on DBs that don't support it directly.
1145 *
1146 * @param string $preparedQuery A 'preparable' SQL statement
1147 * @param array $args Array of Arguments to fill it with
1148 * @return string Executable SQL
1149 */
1150 public function fillPrepared( $preparedQuery, $args ) {
1151 reset( $args );
1152 $this->preparedArgs =& $args;
1153
1154 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1155 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1156 }
1157
1158 /**
1159 * preg_callback func for fillPrepared()
1160 * The arguments should be in $this->preparedArgs and must not be touched
1161 * while we're doing this.
1162 *
1163 * @param array $matches
1164 * @throws DBUnexpectedError
1165 * @return string
1166 */
1167 protected function fillPreparedArg( $matches ) {
1168 switch ( $matches[1] ) {
1169 case '\\?':
1170 return '?';
1171 case '\\!':
1172 return '!';
1173 case '\\&':
1174 return '&';
1175 }
1176
1177 list( /* $n */, $arg ) = each( $this->preparedArgs );
1178
1179 switch ( $matches[1] ) {
1180 case '?':
1181 return $this->addQuotes( $arg );
1182 case '!':
1183 return $arg;
1184 case '&':
1185 # return $this->addQuotes( file_get_contents( $arg ) );
1186 throw new DBUnexpectedError(
1187 $this,
1188 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1189 );
1190 default:
1191 throw new DBUnexpectedError(
1192 $this,
1193 'Received invalid match. This should never happen!'
1194 );
1195 }
1196 }
1197
1198 /**
1199 * Free a result object returned by query() or select(). It's usually not
1200 * necessary to call this, just use unset() or let the variable holding
1201 * the result object go out of scope.
1202 *
1203 * @param mixed $res A SQL result
1204 */
1205 public function freeResult( $res ) {
1206 }
1207
1208 /**
1209 * A SELECT wrapper which returns a single field from a single result row.
1210 *
1211 * Usually throws a DBQueryError on failure. If errors are explicitly
1212 * ignored, returns false on failure.
1213 *
1214 * If no result rows are returned from the query, false is returned.
1215 *
1216 * @param string|array $table Table name. See DatabaseBase::select() for details.
1217 * @param string $var The field name to select. This must be a valid SQL
1218 * fragment: do not use unvalidated user input.
1219 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1220 * @param string $fname The function name of the caller.
1221 * @param string|array $options The query options. See DatabaseBase::select() for details.
1222 *
1223 * @return bool|mixed The value from the field, or false on failure.
1224 * @throws DBUnexpectedError
1225 */
1226 public function selectField(
1227 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1228 ) {
1229 if ( $var === '*' ) { // sanity
1230 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1231 }
1232
1233 if ( !is_array( $options ) ) {
1234 $options = array( $options );
1235 }
1236
1237 $options['LIMIT'] = 1;
1238
1239 $res = $this->select( $table, $var, $cond, $fname, $options );
1240 if ( $res === false || !$this->numRows( $res ) ) {
1241 return false;
1242 }
1243
1244 $row = $this->fetchRow( $res );
1245
1246 if ( $row !== false ) {
1247 return reset( $row );
1248 } else {
1249 return false;
1250 }
1251 }
1252
1253 /**
1254 * A SELECT wrapper which returns a list of single field values from result rows.
1255 *
1256 * Usually throws a DBQueryError on failure. If errors are explicitly
1257 * ignored, returns false on failure.
1258 *
1259 * If no result rows are returned from the query, false is returned.
1260 *
1261 * @param string|array $table Table name. See DatabaseBase::select() for details.
1262 * @param string $var The field name to select. This must be a valid SQL
1263 * fragment: do not use unvalidated user input.
1264 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1265 * @param string $fname The function name of the caller.
1266 * @param string|array $options The query options. See DatabaseBase::select() for details.
1267 *
1268 * @return bool|array The values from the field, or false on failure
1269 * @throws DBUnexpectedError
1270 * @since 1.25
1271 */
1272 public function selectFieldValues(
1273 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1274 ) {
1275 if ( $var === '*' ) { // sanity
1276 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1277 }
1278
1279 if ( !is_array( $options ) ) {
1280 $options = array( $options );
1281 }
1282
1283 $res = $this->select( $table, $var, $cond, $fname, $options );
1284 if ( $res === false ) {
1285 return false;
1286 }
1287
1288 $values = array();
1289 foreach ( $res as $row ) {
1290 $values[] = $row->$var;
1291 }
1292
1293 return $values;
1294 }
1295
1296 /**
1297 * Returns an optional USE INDEX clause to go after the table, and a
1298 * string to go at the end of the query.
1299 *
1300 * @param array $options Associative array of options to be turned into
1301 * an SQL query, valid keys are listed in the function.
1302 * @return array
1303 * @see DatabaseBase::select()
1304 */
1305 public function makeSelectOptions( $options ) {
1306 $preLimitTail = $postLimitTail = '';
1307 $startOpts = '';
1308
1309 $noKeyOptions = array();
1310
1311 foreach ( $options as $key => $option ) {
1312 if ( is_numeric( $key ) ) {
1313 $noKeyOptions[$option] = true;
1314 }
1315 }
1316
1317 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1318
1319 $preLimitTail .= $this->makeOrderBy( $options );
1320
1321 // if (isset($options['LIMIT'])) {
1322 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1323 // isset($options['OFFSET']) ? $options['OFFSET']
1324 // : false);
1325 // }
1326
1327 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1328 $postLimitTail .= ' FOR UPDATE';
1329 }
1330
1331 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1332 $postLimitTail .= ' LOCK IN SHARE MODE';
1333 }
1334
1335 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1336 $startOpts .= 'DISTINCT';
1337 }
1338
1339 # Various MySQL extensions
1340 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1341 $startOpts .= ' /*! STRAIGHT_JOIN */';
1342 }
1343
1344 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1345 $startOpts .= ' HIGH_PRIORITY';
1346 }
1347
1348 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1349 $startOpts .= ' SQL_BIG_RESULT';
1350 }
1351
1352 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1353 $startOpts .= ' SQL_BUFFER_RESULT';
1354 }
1355
1356 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1357 $startOpts .= ' SQL_SMALL_RESULT';
1358 }
1359
1360 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1361 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1362 }
1363
1364 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1365 $startOpts .= ' SQL_CACHE';
1366 }
1367
1368 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1369 $startOpts .= ' SQL_NO_CACHE';
1370 }
1371
1372 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1373 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1374 } else {
1375 $useIndex = '';
1376 }
1377
1378 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1379 }
1380
1381 /**
1382 * Returns an optional GROUP BY with an optional HAVING
1383 *
1384 * @param array $options Associative array of options
1385 * @return string
1386 * @see DatabaseBase::select()
1387 * @since 1.21
1388 */
1389 public function makeGroupByWithHaving( $options ) {
1390 $sql = '';
1391 if ( isset( $options['GROUP BY'] ) ) {
1392 $gb = is_array( $options['GROUP BY'] )
1393 ? implode( ',', $options['GROUP BY'] )
1394 : $options['GROUP BY'];
1395 $sql .= ' GROUP BY ' . $gb;
1396 }
1397 if ( isset( $options['HAVING'] ) ) {
1398 $having = is_array( $options['HAVING'] )
1399 ? $this->makeList( $options['HAVING'], LIST_AND )
1400 : $options['HAVING'];
1401 $sql .= ' HAVING ' . $having;
1402 }
1403
1404 return $sql;
1405 }
1406
1407 /**
1408 * Returns an optional ORDER BY
1409 *
1410 * @param array $options Associative array of options
1411 * @return string
1412 * @see DatabaseBase::select()
1413 * @since 1.21
1414 */
1415 public function makeOrderBy( $options ) {
1416 if ( isset( $options['ORDER BY'] ) ) {
1417 $ob = is_array( $options['ORDER BY'] )
1418 ? implode( ',', $options['ORDER BY'] )
1419 : $options['ORDER BY'];
1420
1421 return ' ORDER BY ' . $ob;
1422 }
1423
1424 return '';
1425 }
1426
1427 /**
1428 * Execute a SELECT query constructed using the various parameters provided.
1429 * See below for full details of the parameters.
1430 *
1431 * @param string|array $table Table name
1432 * @param string|array $vars Field names
1433 * @param string|array $conds Conditions
1434 * @param string $fname Caller function name
1435 * @param array $options Query options
1436 * @param array $join_conds Join conditions
1437 *
1438 *
1439 * @param string|array $table
1440 *
1441 * May be either an array of table names, or a single string holding a table
1442 * name. If an array is given, table aliases can be specified, for example:
1443 *
1444 * array( 'a' => 'user' )
1445 *
1446 * This includes the user table in the query, with the alias "a" available
1447 * for use in field names (e.g. a.user_name).
1448 *
1449 * All of the table names given here are automatically run through
1450 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1451 * added, and various other table name mappings to be performed.
1452 *
1453 *
1454 * @param string|array $vars
1455 *
1456 * May be either a field name or an array of field names. The field names
1457 * can be complete fragments of SQL, for direct inclusion into the SELECT
1458 * query. If an array is given, field aliases can be specified, for example:
1459 *
1460 * array( 'maxrev' => 'MAX(rev_id)' )
1461 *
1462 * This includes an expression with the alias "maxrev" in the query.
1463 *
1464 * If an expression is given, care must be taken to ensure that it is
1465 * DBMS-independent.
1466 *
1467 *
1468 * @param string|array $conds
1469 *
1470 * May be either a string containing a single condition, or an array of
1471 * conditions. If an array is given, the conditions constructed from each
1472 * element are combined with AND.
1473 *
1474 * Array elements may take one of two forms:
1475 *
1476 * - Elements with a numeric key are interpreted as raw SQL fragments.
1477 * - Elements with a string key are interpreted as equality conditions,
1478 * where the key is the field name.
1479 * - If the value of such an array element is a scalar (such as a
1480 * string), it will be treated as data and thus quoted appropriately.
1481 * If it is null, an IS NULL clause will be added.
1482 * - If the value is an array, an IN (...) clause will be constructed
1483 * from its non-null elements, and an IS NULL clause will be added
1484 * if null is present, such that the field may match any of the
1485 * elements in the array. The non-null elements will be quoted.
1486 *
1487 * Note that expressions are often DBMS-dependent in their syntax.
1488 * DBMS-independent wrappers are provided for constructing several types of
1489 * expression commonly used in condition queries. See:
1490 * - DatabaseBase::buildLike()
1491 * - DatabaseBase::conditional()
1492 *
1493 *
1494 * @param string|array $options
1495 *
1496 * Optional: Array of query options. Boolean options are specified by
1497 * including them in the array as a string value with a numeric key, for
1498 * example:
1499 *
1500 * array( 'FOR UPDATE' )
1501 *
1502 * The supported options are:
1503 *
1504 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1505 * with LIMIT can theoretically be used for paging through a result set,
1506 * but this is discouraged in MediaWiki for performance reasons.
1507 *
1508 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1509 * and then the first rows are taken until the limit is reached. LIMIT
1510 * is applied to a result set after OFFSET.
1511 *
1512 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1513 * changed until the next COMMIT.
1514 *
1515 * - DISTINCT: Boolean: return only unique result rows.
1516 *
1517 * - GROUP BY: May be either an SQL fragment string naming a field or
1518 * expression to group by, or an array of such SQL fragments.
1519 *
1520 * - HAVING: May be either an string containing a HAVING clause or an array of
1521 * conditions building the HAVING clause. If an array is given, the conditions
1522 * constructed from each element are combined with AND.
1523 *
1524 * - ORDER BY: May be either an SQL fragment giving a field name or
1525 * expression to order by, or an array of such SQL fragments.
1526 *
1527 * - USE INDEX: This may be either a string giving the index name to use
1528 * for the query, or an array. If it is an associative array, each key
1529 * gives the table name (or alias), each value gives the index name to
1530 * use for that table. All strings are SQL fragments and so should be
1531 * validated by the caller.
1532 *
1533 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1534 * instead of SELECT.
1535 *
1536 * And also the following boolean MySQL extensions, see the MySQL manual
1537 * for documentation:
1538 *
1539 * - LOCK IN SHARE MODE
1540 * - STRAIGHT_JOIN
1541 * - HIGH_PRIORITY
1542 * - SQL_BIG_RESULT
1543 * - SQL_BUFFER_RESULT
1544 * - SQL_SMALL_RESULT
1545 * - SQL_CALC_FOUND_ROWS
1546 * - SQL_CACHE
1547 * - SQL_NO_CACHE
1548 *
1549 *
1550 * @param string|array $join_conds
1551 *
1552 * Optional associative array of table-specific join conditions. In the
1553 * most common case, this is unnecessary, since the join condition can be
1554 * in $conds. However, it is useful for doing a LEFT JOIN.
1555 *
1556 * The key of the array contains the table name or alias. The value is an
1557 * array with two elements, numbered 0 and 1. The first gives the type of
1558 * join, the second is an SQL fragment giving the join condition for that
1559 * table. For example:
1560 *
1561 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1562 *
1563 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1564 * with no rows in it will be returned. If there was a query error, a
1565 * DBQueryError exception will be thrown, except if the "ignore errors"
1566 * option was set, in which case false will be returned.
1567 */
1568 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1569 $options = array(), $join_conds = array() ) {
1570 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1571
1572 return $this->query( $sql, $fname );
1573 }
1574
1575 /**
1576 * The equivalent of DatabaseBase::select() except that the constructed SQL
1577 * is returned, instead of being immediately executed. This can be useful for
1578 * doing UNION queries, where the SQL text of each query is needed. In general,
1579 * however, callers outside of Database classes should just use select().
1580 *
1581 * @param string|array $table Table name
1582 * @param string|array $vars Field names
1583 * @param string|array $conds Conditions
1584 * @param string $fname Caller function name
1585 * @param string|array $options Query options
1586 * @param string|array $join_conds Join conditions
1587 *
1588 * @return string SQL query string.
1589 * @see DatabaseBase::select()
1590 */
1591 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1592 $options = array(), $join_conds = array()
1593 ) {
1594 if ( is_array( $vars ) ) {
1595 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1596 }
1597
1598 $options = (array)$options;
1599 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1600 ? $options['USE INDEX']
1601 : array();
1602
1603 if ( is_array( $table ) ) {
1604 $from = ' FROM ' .
1605 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1606 } elseif ( $table != '' ) {
1607 if ( $table[0] == ' ' ) {
1608 $from = ' FROM ' . $table;
1609 } else {
1610 $from = ' FROM ' .
1611 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1612 }
1613 } else {
1614 $from = '';
1615 }
1616
1617 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1618 $this->makeSelectOptions( $options );
1619
1620 if ( !empty( $conds ) ) {
1621 if ( is_array( $conds ) ) {
1622 $conds = $this->makeList( $conds, LIST_AND );
1623 }
1624 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1625 } else {
1626 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1627 }
1628
1629 if ( isset( $options['LIMIT'] ) ) {
1630 $sql = $this->limitResult( $sql, $options['LIMIT'],
1631 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1632 }
1633 $sql = "$sql $postLimitTail";
1634
1635 if ( isset( $options['EXPLAIN'] ) ) {
1636 $sql = 'EXPLAIN ' . $sql;
1637 }
1638
1639 return $sql;
1640 }
1641
1642 /**
1643 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1644 * that a single row object is returned. If the query returns no rows,
1645 * false is returned.
1646 *
1647 * @param string|array $table Table name
1648 * @param string|array $vars Field names
1649 * @param array $conds Conditions
1650 * @param string $fname Caller function name
1651 * @param string|array $options Query options
1652 * @param array|string $join_conds Join conditions
1653 *
1654 * @return stdClass|bool
1655 */
1656 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1657 $options = array(), $join_conds = array()
1658 ) {
1659 $options = (array)$options;
1660 $options['LIMIT'] = 1;
1661 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1662
1663 if ( $res === false ) {
1664 return false;
1665 }
1666
1667 if ( !$this->numRows( $res ) ) {
1668 return false;
1669 }
1670
1671 $obj = $this->fetchObject( $res );
1672
1673 return $obj;
1674 }
1675
1676 /**
1677 * Estimate the number of rows in dataset
1678 *
1679 * MySQL allows you to estimate the number of rows that would be returned
1680 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1681 * index cardinality statistics, and is notoriously inaccurate, especially
1682 * when large numbers of rows have recently been added or deleted.
1683 *
1684 * For DBMSs that don't support fast result size estimation, this function
1685 * will actually perform the SELECT COUNT(*).
1686 *
1687 * Takes the same arguments as DatabaseBase::select().
1688 *
1689 * @param string $table Table name
1690 * @param string $vars Unused
1691 * @param array|string $conds Filters on the table
1692 * @param string $fname Function name for profiling
1693 * @param array $options Options for select
1694 * @return int Row count
1695 */
1696 public function estimateRowCount(
1697 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1698 ) {
1699 $rows = 0;
1700 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1701
1702 if ( $res ) {
1703 $row = $this->fetchRow( $res );
1704 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1705 }
1706
1707 return $rows;
1708 }
1709
1710 /**
1711 * Get the number of rows in dataset
1712 *
1713 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1714 *
1715 * Takes the same arguments as DatabaseBase::select().
1716 *
1717 * @since 1.27 Added $join_conds parameter
1718 *
1719 * @param array|string $tables Table names
1720 * @param string $vars Unused
1721 * @param array|string $conds Filters on the table
1722 * @param string $fname Function name for profiling
1723 * @param array $options Options for select
1724 * @param array $join_conds Join conditions (since 1.27)
1725 * @return int Row count
1726 */
1727 public function selectRowCount(
1728 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1729 ) {
1730 $rows = 0;
1731 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1732 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1733
1734 if ( $res ) {
1735 $row = $this->fetchRow( $res );
1736 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1737 }
1738
1739 return $rows;
1740 }
1741
1742 /**
1743 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1744 * It's only slightly flawed. Don't use for anything important.
1745 *
1746 * @param string $sql A SQL Query
1747 *
1748 * @return string
1749 */
1750 protected static function generalizeSQL( $sql ) {
1751 # This does the same as the regexp below would do, but in such a way
1752 # as to avoid crashing php on some large strings.
1753 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1754
1755 $sql = str_replace( "\\\\", '', $sql );
1756 $sql = str_replace( "\\'", '', $sql );
1757 $sql = str_replace( "\\\"", '', $sql );
1758 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1759 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1760
1761 # All newlines, tabs, etc replaced by single space
1762 $sql = preg_replace( '/\s+/', ' ', $sql );
1763
1764 # All numbers => N,
1765 # except the ones surrounded by characters, e.g. l10n
1766 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1767 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1768
1769 return $sql;
1770 }
1771
1772 /**
1773 * Determines whether a field exists in a table
1774 *
1775 * @param string $table Table name
1776 * @param string $field Filed to check on that table
1777 * @param string $fname Calling function name (optional)
1778 * @return bool Whether $table has filed $field
1779 */
1780 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1781 $info = $this->fieldInfo( $table, $field );
1782
1783 return (bool)$info;
1784 }
1785
1786 /**
1787 * Determines whether an index exists
1788 * Usually throws a DBQueryError on failure
1789 * If errors are explicitly ignored, returns NULL on failure
1790 *
1791 * @param string $table
1792 * @param string $index
1793 * @param string $fname
1794 * @return bool|null
1795 */
1796 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1797 if ( !$this->tableExists( $table ) ) {
1798 return null;
1799 }
1800
1801 $info = $this->indexInfo( $table, $index, $fname );
1802 if ( is_null( $info ) ) {
1803 return null;
1804 } else {
1805 return $info !== false;
1806 }
1807 }
1808
1809 /**
1810 * Query whether a given table exists
1811 *
1812 * @param string $table
1813 * @param string $fname
1814 * @return bool
1815 */
1816 public function tableExists( $table, $fname = __METHOD__ ) {
1817 $table = $this->tableName( $table );
1818 $old = $this->ignoreErrors( true );
1819 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1820 $this->ignoreErrors( $old );
1821
1822 return (bool)$res;
1823 }
1824
1825 /**
1826 * Determines if a given index is unique
1827 *
1828 * @param string $table
1829 * @param string $index
1830 *
1831 * @return bool
1832 */
1833 public function indexUnique( $table, $index ) {
1834 $indexInfo = $this->indexInfo( $table, $index );
1835
1836 if ( !$indexInfo ) {
1837 return null;
1838 }
1839
1840 return !$indexInfo[0]->Non_unique;
1841 }
1842
1843 /**
1844 * Helper for DatabaseBase::insert().
1845 *
1846 * @param array $options
1847 * @return string
1848 */
1849 protected function makeInsertOptions( $options ) {
1850 return implode( ' ', $options );
1851 }
1852
1853 /**
1854 * INSERT wrapper, inserts an array into a table.
1855 *
1856 * $a may be either:
1857 *
1858 * - A single associative array. The array keys are the field names, and
1859 * the values are the values to insert. The values are treated as data
1860 * and will be quoted appropriately. If NULL is inserted, this will be
1861 * converted to a database NULL.
1862 * - An array with numeric keys, holding a list of associative arrays.
1863 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1864 * each subarray must be identical to each other, and in the same order.
1865 *
1866 * $options is an array of options, with boolean options encoded as values
1867 * with numeric keys, in the same style as $options in
1868 * DatabaseBase::select(). Supported options are:
1869 *
1870 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1871 * any rows which cause duplicate key errors are not inserted. It's
1872 * possible to determine how many rows were successfully inserted using
1873 * DatabaseBase::affectedRows().
1874 *
1875 * @param string $table Table name. This will be passed through
1876 * DatabaseBase::tableName().
1877 * @param array $a Array of rows to insert
1878 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1879 * @param array $options Array of options
1880 *
1881 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1882 * returns success.
1883 *
1884 * @return bool
1885 */
1886 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1887 # No rows to insert, easy just return now
1888 if ( !count( $a ) ) {
1889 return true;
1890 }
1891
1892 $table = $this->tableName( $table );
1893
1894 if ( !is_array( $options ) ) {
1895 $options = array( $options );
1896 }
1897
1898 $fh = null;
1899 if ( isset( $options['fileHandle'] ) ) {
1900 $fh = $options['fileHandle'];
1901 }
1902 $options = $this->makeInsertOptions( $options );
1903
1904 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1905 $multi = true;
1906 $keys = array_keys( $a[0] );
1907 } else {
1908 $multi = false;
1909 $keys = array_keys( $a );
1910 }
1911
1912 $sql = 'INSERT ' . $options .
1913 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1914
1915 if ( $multi ) {
1916 $first = true;
1917 foreach ( $a as $row ) {
1918 if ( $first ) {
1919 $first = false;
1920 } else {
1921 $sql .= ',';
1922 }
1923 $sql .= '(' . $this->makeList( $row ) . ')';
1924 }
1925 } else {
1926 $sql .= '(' . $this->makeList( $a ) . ')';
1927 }
1928
1929 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1930 return false;
1931 } elseif ( $fh !== null ) {
1932 return true;
1933 }
1934
1935 return (bool)$this->query( $sql, $fname );
1936 }
1937
1938 /**
1939 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1940 *
1941 * @param array $options
1942 * @return array
1943 */
1944 protected function makeUpdateOptionsArray( $options ) {
1945 if ( !is_array( $options ) ) {
1946 $options = array( $options );
1947 }
1948
1949 $opts = array();
1950
1951 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1952 $opts[] = $this->lowPriorityOption();
1953 }
1954
1955 if ( in_array( 'IGNORE', $options ) ) {
1956 $opts[] = 'IGNORE';
1957 }
1958
1959 return $opts;
1960 }
1961
1962 /**
1963 * Make UPDATE options for the DatabaseBase::update function
1964 *
1965 * @param array $options The options passed to DatabaseBase::update
1966 * @return string
1967 */
1968 protected function makeUpdateOptions( $options ) {
1969 $opts = $this->makeUpdateOptionsArray( $options );
1970
1971 return implode( ' ', $opts );
1972 }
1973
1974 /**
1975 * UPDATE wrapper. Takes a condition array and a SET array.
1976 *
1977 * @param string $table Name of the table to UPDATE. This will be passed through
1978 * DatabaseBase::tableName().
1979 * @param array $values An array of values to SET. For each array element,
1980 * the key gives the field name, and the value gives the data to set
1981 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1982 * @param array $conds An array of conditions (WHERE). See
1983 * DatabaseBase::select() for the details of the format of condition
1984 * arrays. Use '*' to update all rows.
1985 * @param string $fname The function name of the caller (from __METHOD__),
1986 * for logging and profiling.
1987 * @param array $options An array of UPDATE options, can be:
1988 * - IGNORE: Ignore unique key conflicts
1989 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1990 * @return bool
1991 */
1992 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1993 $table = $this->tableName( $table );
1994 $opts = $this->makeUpdateOptions( $options );
1995 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1996
1997 if ( $conds !== array() && $conds !== '*' ) {
1998 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1999 }
2000
2001 return $this->query( $sql, $fname );
2002 }
2003
2004 /**
2005 * Makes an encoded list of strings from an array
2006 *
2007 * @param array $a Containing the data
2008 * @param int $mode Constant
2009 * - LIST_COMMA: Comma separated, no field names
2010 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2011 * documentation for $conds in DatabaseBase::select().
2012 * - LIST_OR: ORed WHERE clause (without the WHERE)
2013 * - LIST_SET: Comma separated with field names, like a SET clause
2014 * - LIST_NAMES: Comma separated field names
2015 * @throws MWException|DBUnexpectedError
2016 * @return string
2017 */
2018 public function makeList( $a, $mode = LIST_COMMA ) {
2019 if ( !is_array( $a ) ) {
2020 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2021 }
2022
2023 $first = true;
2024 $list = '';
2025
2026 foreach ( $a as $field => $value ) {
2027 if ( !$first ) {
2028 if ( $mode == LIST_AND ) {
2029 $list .= ' AND ';
2030 } elseif ( $mode == LIST_OR ) {
2031 $list .= ' OR ';
2032 } else {
2033 $list .= ',';
2034 }
2035 } else {
2036 $first = false;
2037 }
2038
2039 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2040 $list .= "($value)";
2041 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2042 $list .= "$value";
2043 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2044 // Remove null from array to be handled separately if found
2045 $includeNull = false;
2046 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2047 $includeNull = true;
2048 unset( $value[$nullKey] );
2049 }
2050 if ( count( $value ) == 0 && !$includeNull ) {
2051 throw new MWException( __METHOD__ . ": empty input for field $field" );
2052 } elseif ( count( $value ) == 0 ) {
2053 // only check if $field is null
2054 $list .= "$field IS NULL";
2055 } else {
2056 // IN clause contains at least one valid element
2057 if ( $includeNull ) {
2058 // Group subconditions to ensure correct precedence
2059 $list .= '(';
2060 }
2061 if ( count( $value ) == 1 ) {
2062 // Special-case single values, as IN isn't terribly efficient
2063 // Don't necessarily assume the single key is 0; we don't
2064 // enforce linear numeric ordering on other arrays here.
2065 $value = array_values( $value );
2066 $list .= $field . " = " . $this->addQuotes( $value[0] );
2067 } else {
2068 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2069 }
2070 // if null present in array, append IS NULL
2071 if ( $includeNull ) {
2072 $list .= " OR $field IS NULL)";
2073 }
2074 }
2075 } elseif ( $value === null ) {
2076 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2077 $list .= "$field IS ";
2078 } elseif ( $mode == LIST_SET ) {
2079 $list .= "$field = ";
2080 }
2081 $list .= 'NULL';
2082 } else {
2083 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2084 $list .= "$field = ";
2085 }
2086 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2087 }
2088 }
2089
2090 return $list;
2091 }
2092
2093 /**
2094 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2095 * The keys on each level may be either integers or strings.
2096 *
2097 * @param array $data Organized as 2-d
2098 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2099 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2100 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2101 * @return string|bool SQL fragment, or false if no items in array
2102 */
2103 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2104 $conds = array();
2105
2106 foreach ( $data as $base => $sub ) {
2107 if ( count( $sub ) ) {
2108 $conds[] = $this->makeList(
2109 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2110 LIST_AND );
2111 }
2112 }
2113
2114 if ( $conds ) {
2115 return $this->makeList( $conds, LIST_OR );
2116 } else {
2117 // Nothing to search for...
2118 return false;
2119 }
2120 }
2121
2122 /**
2123 * Return aggregated value alias
2124 *
2125 * @param array $valuedata
2126 * @param string $valuename
2127 *
2128 * @return string
2129 */
2130 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2131 return $valuename;
2132 }
2133
2134 /**
2135 * @param string $field
2136 * @return string
2137 */
2138 public function bitNot( $field ) {
2139 return "(~$field)";
2140 }
2141
2142 /**
2143 * @param string $fieldLeft
2144 * @param string $fieldRight
2145 * @return string
2146 */
2147 public function bitAnd( $fieldLeft, $fieldRight ) {
2148 return "($fieldLeft & $fieldRight)";
2149 }
2150
2151 /**
2152 * @param string $fieldLeft
2153 * @param string $fieldRight
2154 * @return string
2155 */
2156 public function bitOr( $fieldLeft, $fieldRight ) {
2157 return "($fieldLeft | $fieldRight)";
2158 }
2159
2160 /**
2161 * Build a concatenation list to feed into a SQL query
2162 * @param array $stringList List of raw SQL expressions; caller is
2163 * responsible for any quoting
2164 * @return string
2165 */
2166 public function buildConcat( $stringList ) {
2167 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2168 }
2169
2170 /**
2171 * Build a GROUP_CONCAT or equivalent statement for a query.
2172 *
2173 * This is useful for combining a field for several rows into a single string.
2174 * NULL values will not appear in the output, duplicated values will appear,
2175 * and the resulting delimiter-separated values have no defined sort order.
2176 * Code using the results may need to use the PHP unique() or sort() methods.
2177 *
2178 * @param string $delim Glue to bind the results together
2179 * @param string|array $table Table name
2180 * @param string $field Field name
2181 * @param string|array $conds Conditions
2182 * @param string|array $join_conds Join conditions
2183 * @return string SQL text
2184 * @since 1.23
2185 */
2186 public function buildGroupConcatField(
2187 $delim, $table, $field, $conds = '', $join_conds = array()
2188 ) {
2189 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2190
2191 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2192 }
2193
2194 /**
2195 * Change the current database
2196 *
2197 * @todo Explain what exactly will fail if this is not overridden.
2198 *
2199 * @param string $db
2200 *
2201 * @return bool Success or failure
2202 */
2203 public function selectDB( $db ) {
2204 # Stub. Shouldn't cause serious problems if it's not overridden, but
2205 # if your database engine supports a concept similar to MySQL's
2206 # databases you may as well.
2207 $this->mDBname = $db;
2208
2209 return true;
2210 }
2211
2212 /**
2213 * Get the current DB name
2214 * @return string
2215 */
2216 public function getDBname() {
2217 return $this->mDBname;
2218 }
2219
2220 /**
2221 * Get the server hostname or IP address
2222 * @return string
2223 */
2224 public function getServer() {
2225 return $this->mServer;
2226 }
2227
2228 /**
2229 * Format a table name ready for use in constructing an SQL query
2230 *
2231 * This does two important things: it quotes the table names to clean them up,
2232 * and it adds a table prefix if only given a table name with no quotes.
2233 *
2234 * All functions of this object which require a table name call this function
2235 * themselves. Pass the canonical name to such functions. This is only needed
2236 * when calling query() directly.
2237 *
2238 * @param string $name Database table name
2239 * @param string $format One of:
2240 * quoted - Automatically pass the table name through addIdentifierQuotes()
2241 * so that it can be used in a query.
2242 * raw - Do not add identifier quotes to the table name
2243 * @return string Full database name
2244 */
2245 public function tableName( $name, $format = 'quoted' ) {
2246 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2247 # Skip the entire process when we have a string quoted on both ends.
2248 # Note that we check the end so that we will still quote any use of
2249 # use of `database`.table. But won't break things if someone wants
2250 # to query a database table with a dot in the name.
2251 if ( $this->isQuotedIdentifier( $name ) ) {
2252 return $name;
2253 }
2254
2255 # Lets test for any bits of text that should never show up in a table
2256 # name. Basically anything like JOIN or ON which are actually part of
2257 # SQL queries, but may end up inside of the table value to combine
2258 # sql. Such as how the API is doing.
2259 # Note that we use a whitespace test rather than a \b test to avoid
2260 # any remote case where a word like on may be inside of a table name
2261 # surrounded by symbols which may be considered word breaks.
2262 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2263 return $name;
2264 }
2265
2266 # Split database and table into proper variables.
2267 # We reverse the explode so that database.table and table both output
2268 # the correct table.
2269 $dbDetails = explode( '.', $name, 3 );
2270 if ( count( $dbDetails ) == 3 ) {
2271 list( $database, $schema, $table ) = $dbDetails;
2272 # We don't want any prefix added in this case
2273 $prefix = '';
2274 } elseif ( count( $dbDetails ) == 2 ) {
2275 list( $database, $table ) = $dbDetails;
2276 # We don't want any prefix added in this case
2277 # In dbs that support it, $database may actually be the schema
2278 # but that doesn't affect any of the functionality here
2279 $prefix = '';
2280 $schema = null;
2281 } else {
2282 list( $table ) = $dbDetails;
2283 if ( $wgSharedDB !== null # We have a shared database
2284 && $this->mForeign == false # We're not working on a foreign database
2285 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2286 && in_array( $table, $wgSharedTables ) # A shared table is selected
2287 ) {
2288 $database = $wgSharedDB;
2289 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2290 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2291 } else {
2292 $database = null;
2293 $schema = $this->mSchema; # Default schema
2294 $prefix = $this->mTablePrefix; # Default prefix
2295 }
2296 }
2297
2298 # Quote $table and apply the prefix if not quoted.
2299 # $tableName might be empty if this is called from Database::replaceVars()
2300 $tableName = "{$prefix}{$table}";
2301 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2302 $tableName = $this->addIdentifierQuotes( $tableName );
2303 }
2304
2305 # Quote $schema and merge it with the table name if needed
2306 if ( strlen( $schema ) ) {
2307 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2308 $schema = $this->addIdentifierQuotes( $schema );
2309 }
2310 $tableName = $schema . '.' . $tableName;
2311 }
2312
2313 # Quote $database and merge it with the table name if needed
2314 if ( $database !== null ) {
2315 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2316 $database = $this->addIdentifierQuotes( $database );
2317 }
2318 $tableName = $database . '.' . $tableName;
2319 }
2320
2321 return $tableName;
2322 }
2323
2324 /**
2325 * Fetch a number of table names into an array
2326 * This is handy when you need to construct SQL for joins
2327 *
2328 * Example:
2329 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2330 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2331 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2332 *
2333 * @return array
2334 */
2335 public function tableNames() {
2336 $inArray = func_get_args();
2337 $retVal = array();
2338
2339 foreach ( $inArray as $name ) {
2340 $retVal[$name] = $this->tableName( $name );
2341 }
2342
2343 return $retVal;
2344 }
2345
2346 /**
2347 * Fetch a number of table names into an zero-indexed numerical array
2348 * This is handy when you need to construct SQL for joins
2349 *
2350 * Example:
2351 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2352 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2353 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2354 *
2355 * @return array
2356 */
2357 public function tableNamesN() {
2358 $inArray = func_get_args();
2359 $retVal = array();
2360
2361 foreach ( $inArray as $name ) {
2362 $retVal[] = $this->tableName( $name );
2363 }
2364
2365 return $retVal;
2366 }
2367
2368 /**
2369 * Get an aliased table name
2370 * e.g. tableName AS newTableName
2371 *
2372 * @param string $name Table name, see tableName()
2373 * @param string|bool $alias Alias (optional)
2374 * @return string SQL name for aliased table. Will not alias a table to its own name
2375 */
2376 public function tableNameWithAlias( $name, $alias = false ) {
2377 if ( !$alias || $alias == $name ) {
2378 return $this->tableName( $name );
2379 } else {
2380 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2381 }
2382 }
2383
2384 /**
2385 * Gets an array of aliased table names
2386 *
2387 * @param array $tables Array( [alias] => table )
2388 * @return string[] See tableNameWithAlias()
2389 */
2390 public function tableNamesWithAlias( $tables ) {
2391 $retval = array();
2392 foreach ( $tables as $alias => $table ) {
2393 if ( is_numeric( $alias ) ) {
2394 $alias = $table;
2395 }
2396 $retval[] = $this->tableNameWithAlias( $table, $alias );
2397 }
2398
2399 return $retval;
2400 }
2401
2402 /**
2403 * Get an aliased field name
2404 * e.g. fieldName AS newFieldName
2405 *
2406 * @param string $name Field name
2407 * @param string|bool $alias Alias (optional)
2408 * @return string SQL name for aliased field. Will not alias a field to its own name
2409 */
2410 public function fieldNameWithAlias( $name, $alias = false ) {
2411 if ( !$alias || (string)$alias === (string)$name ) {
2412 return $name;
2413 } else {
2414 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2415 }
2416 }
2417
2418 /**
2419 * Gets an array of aliased field names
2420 *
2421 * @param array $fields Array( [alias] => field )
2422 * @return string[] See fieldNameWithAlias()
2423 */
2424 public function fieldNamesWithAlias( $fields ) {
2425 $retval = array();
2426 foreach ( $fields as $alias => $field ) {
2427 if ( is_numeric( $alias ) ) {
2428 $alias = $field;
2429 }
2430 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2431 }
2432
2433 return $retval;
2434 }
2435
2436 /**
2437 * Get the aliased table name clause for a FROM clause
2438 * which might have a JOIN and/or USE INDEX clause
2439 *
2440 * @param array $tables ( [alias] => table )
2441 * @param array $use_index Same as for select()
2442 * @param array $join_conds Same as for select()
2443 * @return string
2444 */
2445 protected function tableNamesWithUseIndexOrJOIN(
2446 $tables, $use_index = array(), $join_conds = array()
2447 ) {
2448 $ret = array();
2449 $retJOIN = array();
2450 $use_index = (array)$use_index;
2451 $join_conds = (array)$join_conds;
2452
2453 foreach ( $tables as $alias => $table ) {
2454 if ( !is_string( $alias ) ) {
2455 // No alias? Set it equal to the table name
2456 $alias = $table;
2457 }
2458 // Is there a JOIN clause for this table?
2459 if ( isset( $join_conds[$alias] ) ) {
2460 list( $joinType, $conds ) = $join_conds[$alias];
2461 $tableClause = $joinType;
2462 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2463 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2464 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2465 if ( $use != '' ) {
2466 $tableClause .= ' ' . $use;
2467 }
2468 }
2469 $on = $this->makeList( (array)$conds, LIST_AND );
2470 if ( $on != '' ) {
2471 $tableClause .= ' ON (' . $on . ')';
2472 }
2473
2474 $retJOIN[] = $tableClause;
2475 } elseif ( isset( $use_index[$alias] ) ) {
2476 // Is there an INDEX clause for this table?
2477 $tableClause = $this->tableNameWithAlias( $table, $alias );
2478 $tableClause .= ' ' . $this->useIndexClause(
2479 implode( ',', (array)$use_index[$alias] )
2480 );
2481
2482 $ret[] = $tableClause;
2483 } else {
2484 $tableClause = $this->tableNameWithAlias( $table, $alias );
2485
2486 $ret[] = $tableClause;
2487 }
2488 }
2489
2490 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2491 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2492 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2493
2494 // Compile our final table clause
2495 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2496 }
2497
2498 /**
2499 * Get the name of an index in a given table.
2500 *
2501 * @protected Don't use outside of DatabaseBase and childs
2502 * @param string $index
2503 * @return string
2504 */
2505 public function indexName( $index ) {
2506 // @FIXME: Make this protected once we move away from PHP 5.3
2507 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2508
2509 // Backwards-compatibility hack
2510 $renamed = array(
2511 'ar_usertext_timestamp' => 'usertext_timestamp',
2512 'un_user_id' => 'user_id',
2513 'un_user_ip' => 'user_ip',
2514 );
2515
2516 if ( isset( $renamed[$index] ) ) {
2517 return $renamed[$index];
2518 } else {
2519 return $index;
2520 }
2521 }
2522
2523 /**
2524 * Adds quotes and backslashes.
2525 *
2526 * @param string|Blob $s
2527 * @return string
2528 */
2529 public function addQuotes( $s ) {
2530 if ( $s instanceof Blob ) {
2531 $s = $s->fetch();
2532 }
2533 if ( $s === null ) {
2534 return 'NULL';
2535 } else {
2536 # This will also quote numeric values. This should be harmless,
2537 # and protects against weird problems that occur when they really
2538 # _are_ strings such as article titles and string->number->string
2539 # conversion is not 1:1.
2540 return "'" . $this->strencode( $s ) . "'";
2541 }
2542 }
2543
2544 /**
2545 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2546 * MySQL uses `backticks` while basically everything else uses double quotes.
2547 * Since MySQL is the odd one out here the double quotes are our generic
2548 * and we implement backticks in DatabaseMysql.
2549 *
2550 * @param string $s
2551 * @return string
2552 */
2553 public function addIdentifierQuotes( $s ) {
2554 return '"' . str_replace( '"', '""', $s ) . '"';
2555 }
2556
2557 /**
2558 * Returns if the given identifier looks quoted or not according to
2559 * the database convention for quoting identifiers .
2560 *
2561 * @param string $name
2562 * @return bool
2563 */
2564 public function isQuotedIdentifier( $name ) {
2565 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2566 }
2567
2568 /**
2569 * @param string $s
2570 * @return string
2571 */
2572 protected function escapeLikeInternal( $s ) {
2573 return addcslashes( $s, '\%_' );
2574 }
2575
2576 /**
2577 * LIKE statement wrapper, receives a variable-length argument list with
2578 * parts of pattern to match containing either string literals that will be
2579 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2580 * the function could be provided with an array of aforementioned
2581 * parameters.
2582 *
2583 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2584 * a LIKE clause that searches for subpages of 'My page title'.
2585 * Alternatively:
2586 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2587 * $query .= $dbr->buildLike( $pattern );
2588 *
2589 * @since 1.16
2590 * @return string Fully built LIKE statement
2591 */
2592 public function buildLike() {
2593 $params = func_get_args();
2594
2595 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2596 $params = $params[0];
2597 }
2598
2599 $s = '';
2600
2601 foreach ( $params as $value ) {
2602 if ( $value instanceof LikeMatch ) {
2603 $s .= $value->toString();
2604 } else {
2605 $s .= $this->escapeLikeInternal( $value );
2606 }
2607 }
2608
2609 return " LIKE {$this->addQuotes( $s )} ";
2610 }
2611
2612 /**
2613 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2614 *
2615 * @return LikeMatch
2616 */
2617 public function anyChar() {
2618 return new LikeMatch( '_' );
2619 }
2620
2621 /**
2622 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2623 *
2624 * @return LikeMatch
2625 */
2626 public function anyString() {
2627 return new LikeMatch( '%' );
2628 }
2629
2630 /**
2631 * Returns an appropriately quoted sequence value for inserting a new row.
2632 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2633 * subclass will return an integer, and save the value for insertId()
2634 *
2635 * Any implementation of this function should *not* involve reusing
2636 * sequence numbers created for rolled-back transactions.
2637 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2638 * @param string $seqName
2639 * @return null|int
2640 */
2641 public function nextSequenceValue( $seqName ) {
2642 return null;
2643 }
2644
2645 /**
2646 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2647 * is only needed because a) MySQL must be as efficient as possible due to
2648 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2649 * which index to pick. Anyway, other databases might have different
2650 * indexes on a given table. So don't bother overriding this unless you're
2651 * MySQL.
2652 * @param string $index
2653 * @return string
2654 */
2655 public function useIndexClause( $index ) {
2656 return '';
2657 }
2658
2659 /**
2660 * REPLACE query wrapper.
2661 *
2662 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2663 * except that when there is a duplicate key error, the old row is deleted
2664 * and the new row is inserted in its place.
2665 *
2666 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2667 * perform the delete, we need to know what the unique indexes are so that
2668 * we know how to find the conflicting rows.
2669 *
2670 * It may be more efficient to leave off unique indexes which are unlikely
2671 * to collide. However if you do this, you run the risk of encountering
2672 * errors which wouldn't have occurred in MySQL.
2673 *
2674 * @param string $table The table to replace the row(s) in.
2675 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2676 * a field name or an array of field names
2677 * @param array $rows Can be either a single row to insert, or multiple rows,
2678 * in the same format as for DatabaseBase::insert()
2679 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2680 */
2681 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2682 $quotedTable = $this->tableName( $table );
2683
2684 if ( count( $rows ) == 0 ) {
2685 return;
2686 }
2687
2688 # Single row case
2689 if ( !is_array( reset( $rows ) ) ) {
2690 $rows = array( $rows );
2691 }
2692
2693 // @FXIME: this is not atomic, but a trx would break affectedRows()
2694 foreach ( $rows as $row ) {
2695 # Delete rows which collide
2696 if ( $uniqueIndexes ) {
2697 $sql = "DELETE FROM $quotedTable WHERE ";
2698 $first = true;
2699 foreach ( $uniqueIndexes as $index ) {
2700 if ( $first ) {
2701 $first = false;
2702 $sql .= '( ';
2703 } else {
2704 $sql .= ' ) OR ( ';
2705 }
2706 if ( is_array( $index ) ) {
2707 $first2 = true;
2708 foreach ( $index as $col ) {
2709 if ( $first2 ) {
2710 $first2 = false;
2711 } else {
2712 $sql .= ' AND ';
2713 }
2714 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2715 }
2716 } else {
2717 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2718 }
2719 }
2720 $sql .= ' )';
2721 $this->query( $sql, $fname );
2722 }
2723
2724 # Now insert the row
2725 $this->insert( $table, $row, $fname );
2726 }
2727 }
2728
2729 /**
2730 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2731 * statement.
2732 *
2733 * @param string $table Table name
2734 * @param array|string $rows Row(s) to insert
2735 * @param string $fname Caller function name
2736 *
2737 * @return ResultWrapper
2738 */
2739 protected function nativeReplace( $table, $rows, $fname ) {
2740 $table = $this->tableName( $table );
2741
2742 # Single row case
2743 if ( !is_array( reset( $rows ) ) ) {
2744 $rows = array( $rows );
2745 }
2746
2747 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2748 $first = true;
2749
2750 foreach ( $rows as $row ) {
2751 if ( $first ) {
2752 $first = false;
2753 } else {
2754 $sql .= ',';
2755 }
2756
2757 $sql .= '(' . $this->makeList( $row ) . ')';
2758 }
2759
2760 return $this->query( $sql, $fname );
2761 }
2762
2763 /**
2764 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2765 *
2766 * This updates any conflicting rows (according to the unique indexes) using
2767 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2768 *
2769 * $rows may be either:
2770 * - A single associative array. The array keys are the field names, and
2771 * the values are the values to insert. The values are treated as data
2772 * and will be quoted appropriately. If NULL is inserted, this will be
2773 * converted to a database NULL.
2774 * - An array with numeric keys, holding a list of associative arrays.
2775 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2776 * each subarray must be identical to each other, and in the same order.
2777 *
2778 * It may be more efficient to leave off unique indexes which are unlikely
2779 * to collide. However if you do this, you run the risk of encountering
2780 * errors which wouldn't have occurred in MySQL.
2781 *
2782 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2783 * returns success.
2784 *
2785 * @since 1.22
2786 *
2787 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2788 * @param array $rows A single row or list of rows to insert
2789 * @param array $uniqueIndexes List of single field names or field name tuples
2790 * @param array $set An array of values to SET. For each array element, the
2791 * key gives the field name, and the value gives the data to set that
2792 * field to. The data will be quoted by DatabaseBase::addQuotes().
2793 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2794 * @throws Exception
2795 * @return bool
2796 */
2797 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2798 $fname = __METHOD__
2799 ) {
2800 if ( !count( $rows ) ) {
2801 return true; // nothing to do
2802 }
2803
2804 if ( !is_array( reset( $rows ) ) ) {
2805 $rows = array( $rows );
2806 }
2807
2808 if ( count( $uniqueIndexes ) ) {
2809 $clauses = array(); // list WHERE clauses that each identify a single row
2810 foreach ( $rows as $row ) {
2811 foreach ( $uniqueIndexes as $index ) {
2812 $index = is_array( $index ) ? $index : array( $index ); // columns
2813 $rowKey = array(); // unique key to this row
2814 foreach ( $index as $column ) {
2815 $rowKey[$column] = $row[$column];
2816 }
2817 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2818 }
2819 }
2820 $where = array( $this->makeList( $clauses, LIST_OR ) );
2821 } else {
2822 $where = false;
2823 }
2824
2825 $useTrx = !$this->mTrxLevel;
2826 if ( $useTrx ) {
2827 $this->begin( $fname );
2828 }
2829 try {
2830 # Update any existing conflicting row(s)
2831 if ( $where !== false ) {
2832 $ok = $this->update( $table, $set, $where, $fname );
2833 } else {
2834 $ok = true;
2835 }
2836 # Now insert any non-conflicting row(s)
2837 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2838 } catch ( Exception $e ) {
2839 if ( $useTrx ) {
2840 $this->rollback( $fname );
2841 }
2842 throw $e;
2843 }
2844 if ( $useTrx ) {
2845 $this->commit( $fname );
2846 }
2847
2848 return $ok;
2849 }
2850
2851 /**
2852 * DELETE where the condition is a join.
2853 *
2854 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2855 * we use sub-selects
2856 *
2857 * For safety, an empty $conds will not delete everything. If you want to
2858 * delete all rows where the join condition matches, set $conds='*'.
2859 *
2860 * DO NOT put the join condition in $conds.
2861 *
2862 * @param string $delTable The table to delete from.
2863 * @param string $joinTable The other table.
2864 * @param string $delVar The variable to join on, in the first table.
2865 * @param string $joinVar The variable to join on, in the second table.
2866 * @param array $conds Condition array of field names mapped to variables,
2867 * ANDed together in the WHERE clause
2868 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2869 * @throws DBUnexpectedError
2870 */
2871 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2872 $fname = __METHOD__
2873 ) {
2874 if ( !$conds ) {
2875 throw new DBUnexpectedError( $this,
2876 'DatabaseBase::deleteJoin() called with empty $conds' );
2877 }
2878
2879 $delTable = $this->tableName( $delTable );
2880 $joinTable = $this->tableName( $joinTable );
2881 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2882 if ( $conds != '*' ) {
2883 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2884 }
2885 $sql .= ')';
2886
2887 $this->query( $sql, $fname );
2888 }
2889
2890 /**
2891 * Returns the size of a text field, or -1 for "unlimited"
2892 *
2893 * @param string $table
2894 * @param string $field
2895 * @return int
2896 */
2897 public function textFieldSize( $table, $field ) {
2898 $table = $this->tableName( $table );
2899 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2900 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2901 $row = $this->fetchObject( $res );
2902
2903 $m = array();
2904
2905 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2906 $size = $m[1];
2907 } else {
2908 $size = -1;
2909 }
2910
2911 return $size;
2912 }
2913
2914 /**
2915 * A string to insert into queries to show that they're low-priority, like
2916 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2917 * string and nothing bad should happen.
2918 *
2919 * @return string Returns the text of the low priority option if it is
2920 * supported, or a blank string otherwise
2921 */
2922 public function lowPriorityOption() {
2923 return '';
2924 }
2925
2926 /**
2927 * DELETE query wrapper.
2928 *
2929 * @param array $table Table name
2930 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2931 * for the format. Use $conds == "*" to delete all rows
2932 * @param string $fname Name of the calling function
2933 * @throws DBUnexpectedError
2934 * @return bool|ResultWrapper
2935 */
2936 public function delete( $table, $conds, $fname = __METHOD__ ) {
2937 if ( !$conds ) {
2938 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2939 }
2940
2941 $table = $this->tableName( $table );
2942 $sql = "DELETE FROM $table";
2943
2944 if ( $conds != '*' ) {
2945 if ( is_array( $conds ) ) {
2946 $conds = $this->makeList( $conds, LIST_AND );
2947 }
2948 $sql .= ' WHERE ' . $conds;
2949 }
2950
2951 return $this->query( $sql, $fname );
2952 }
2953
2954 /**
2955 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2956 * into another table.
2957 *
2958 * @param string $destTable The table name to insert into
2959 * @param string|array $srcTable May be either a table name, or an array of table names
2960 * to include in a join.
2961 *
2962 * @param array $varMap Must be an associative array of the form
2963 * array( 'dest1' => 'source1', ...). Source items may be literals
2964 * rather than field names, but strings should be quoted with
2965 * DatabaseBase::addQuotes()
2966 *
2967 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2968 * the details of the format of condition arrays. May be "*" to copy the
2969 * whole table.
2970 *
2971 * @param string $fname The function name of the caller, from __METHOD__
2972 *
2973 * @param array $insertOptions Options for the INSERT part of the query, see
2974 * DatabaseBase::insert() for details.
2975 * @param array $selectOptions Options for the SELECT part of the query, see
2976 * DatabaseBase::select() for details.
2977 *
2978 * @return ResultWrapper
2979 */
2980 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2981 $fname = __METHOD__,
2982 $insertOptions = array(), $selectOptions = array()
2983 ) {
2984 $destTable = $this->tableName( $destTable );
2985
2986 if ( !is_array( $insertOptions ) ) {
2987 $insertOptions = array( $insertOptions );
2988 }
2989
2990 $insertOptions = $this->makeInsertOptions( $insertOptions );
2991
2992 if ( !is_array( $selectOptions ) ) {
2993 $selectOptions = array( $selectOptions );
2994 }
2995
2996 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2997
2998 if ( is_array( $srcTable ) ) {
2999 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3000 } else {
3001 $srcTable = $this->tableName( $srcTable );
3002 }
3003
3004 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3005 " SELECT $startOpts " . implode( ',', $varMap ) .
3006 " FROM $srcTable $useIndex ";
3007
3008 if ( $conds != '*' ) {
3009 if ( is_array( $conds ) ) {
3010 $conds = $this->makeList( $conds, LIST_AND );
3011 }
3012 $sql .= " WHERE $conds";
3013 }
3014
3015 $sql .= " $tailOpts";
3016
3017 return $this->query( $sql, $fname );
3018 }
3019
3020 /**
3021 * Construct a LIMIT query with optional offset. This is used for query
3022 * pages. The SQL should be adjusted so that only the first $limit rows
3023 * are returned. If $offset is provided as well, then the first $offset
3024 * rows should be discarded, and the next $limit rows should be returned.
3025 * If the result of the query is not ordered, then the rows to be returned
3026 * are theoretically arbitrary.
3027 *
3028 * $sql is expected to be a SELECT, if that makes a difference.
3029 *
3030 * The version provided by default works in MySQL and SQLite. It will very
3031 * likely need to be overridden for most other DBMSes.
3032 *
3033 * @param string $sql SQL query we will append the limit too
3034 * @param int $limit The SQL limit
3035 * @param int|bool $offset The SQL offset (default false)
3036 * @throws DBUnexpectedError
3037 * @return string
3038 */
3039 public function limitResult( $sql, $limit, $offset = false ) {
3040 if ( !is_numeric( $limit ) ) {
3041 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3042 }
3043
3044 return "$sql LIMIT "
3045 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3046 . "{$limit} ";
3047 }
3048
3049 /**
3050 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3051 * within the UNION construct.
3052 * @return bool
3053 */
3054 public function unionSupportsOrderAndLimit() {
3055 return true; // True for almost every DB supported
3056 }
3057
3058 /**
3059 * Construct a UNION query
3060 * This is used for providing overload point for other DB abstractions
3061 * not compatible with the MySQL syntax.
3062 * @param array $sqls SQL statements to combine
3063 * @param bool $all Use UNION ALL
3064 * @return string SQL fragment
3065 */
3066 public function unionQueries( $sqls, $all ) {
3067 $glue = $all ? ') UNION ALL (' : ') UNION (';
3068
3069 return '(' . implode( $glue, $sqls ) . ')';
3070 }
3071
3072 /**
3073 * Returns an SQL expression for a simple conditional. This doesn't need
3074 * to be overridden unless CASE isn't supported in your DBMS.
3075 *
3076 * @param string|array $cond SQL expression which will result in a boolean value
3077 * @param string $trueVal SQL expression to return if true
3078 * @param string $falseVal SQL expression to return if false
3079 * @return string SQL fragment
3080 */
3081 public function conditional( $cond, $trueVal, $falseVal ) {
3082 if ( is_array( $cond ) ) {
3083 $cond = $this->makeList( $cond, LIST_AND );
3084 }
3085
3086 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3087 }
3088
3089 /**
3090 * Returns a comand for str_replace function in SQL query.
3091 * Uses REPLACE() in MySQL
3092 *
3093 * @param string $orig Column to modify
3094 * @param string $old Column to seek
3095 * @param string $new Column to replace with
3096 *
3097 * @return string
3098 */
3099 public function strreplace( $orig, $old, $new ) {
3100 return "REPLACE({$orig}, {$old}, {$new})";
3101 }
3102
3103 /**
3104 * Determines how long the server has been up
3105 * STUB
3106 *
3107 * @return int
3108 */
3109 public function getServerUptime() {
3110 return 0;
3111 }
3112
3113 /**
3114 * Determines if the last failure was due to a deadlock
3115 * STUB
3116 *
3117 * @return bool
3118 */
3119 public function wasDeadlock() {
3120 return false;
3121 }
3122
3123 /**
3124 * Determines if the last failure was due to a lock timeout
3125 * STUB
3126 *
3127 * @return bool
3128 */
3129 public function wasLockTimeout() {
3130 return false;
3131 }
3132
3133 /**
3134 * Determines if the last query error was something that should be dealt
3135 * with by pinging the connection and reissuing the query.
3136 * STUB
3137 *
3138 * @return bool
3139 */
3140 public function wasErrorReissuable() {
3141 return false;
3142 }
3143
3144 /**
3145 * Determines if the last failure was due to the database being read-only.
3146 * STUB
3147 *
3148 * @return bool
3149 */
3150 public function wasReadOnlyError() {
3151 return false;
3152 }
3153
3154 /**
3155 * Determines if the given query error was a connection drop
3156 * STUB
3157 *
3158 * @param integer|string $errno
3159 * @return bool
3160 */
3161 public function wasConnectionError( $errno ) {
3162 return false;
3163 }
3164
3165 /**
3166 * Perform a deadlock-prone transaction.
3167 *
3168 * This function invokes a callback function to perform a set of write
3169 * queries. If a deadlock occurs during the processing, the transaction
3170 * will be rolled back and the callback function will be called again.
3171 *
3172 * Usage:
3173 * $dbw->deadlockLoop( callback, ... );
3174 *
3175 * Extra arguments are passed through to the specified callback function.
3176 *
3177 * Returns whatever the callback function returned on its successful,
3178 * iteration, or false on error, for example if the retry limit was
3179 * reached.
3180 *
3181 * @return mixed
3182 * @throws DBQueryError
3183 */
3184 public function deadlockLoop() {
3185 $args = func_get_args();
3186 $function = array_shift( $args );
3187 $tries = self::DEADLOCK_TRIES;
3188
3189 $this->begin( __METHOD__ );
3190
3191 $retVal = null;
3192 $e = null;
3193 do {
3194 try {
3195 $retVal = call_user_func_array( $function, $args );
3196 break;
3197 } catch ( DBQueryError $e ) {
3198 if ( $this->wasDeadlock() ) {
3199 // Retry after a randomized delay
3200 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3201 } else {
3202 // Throw the error back up
3203 throw $e;
3204 }
3205 }
3206 } while ( --$tries > 0 );
3207
3208 if ( $tries <= 0 ) {
3209 // Too many deadlocks; give up
3210 $this->rollback( __METHOD__ );
3211 throw $e;
3212 } else {
3213 $this->commit( __METHOD__ );
3214
3215 return $retVal;
3216 }
3217 }
3218
3219 /**
3220 * Wait for the slave to catch up to a given master position.
3221 *
3222 * @param DBMasterPos $pos
3223 * @param int $timeout The maximum number of seconds to wait for
3224 * synchronisation
3225 * @return int Zero if the slave was past that position already,
3226 * greater than zero if we waited for some period of time, less than
3227 * zero if we timed out.
3228 */
3229 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3230 # Real waits are implemented in the subclass.
3231 return 0;
3232 }
3233
3234 /**
3235 * Get the replication position of this slave
3236 *
3237 * @return DBMasterPos|bool False if this is not a slave.
3238 */
3239 public function getSlavePos() {
3240 # Stub
3241 return false;
3242 }
3243
3244 /**
3245 * Get the position of this master
3246 *
3247 * @return DBMasterPos|bool False if this is not a master
3248 */
3249 public function getMasterPos() {
3250 # Stub
3251 return false;
3252 }
3253
3254 /**
3255 * Run an anonymous function as soon as there is no transaction pending.
3256 * If there is a transaction and it is rolled back, then the callback is cancelled.
3257 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3258 * Callbacks must commit any transactions that they begin.
3259 *
3260 * This is useful for updates to different systems or when separate transactions are needed.
3261 * For example, one might want to enqueue jobs into a system outside the database, but only
3262 * after the database is updated so that the jobs will see the data when they actually run.
3263 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3264 *
3265 * @param callable $callback
3266 * @since 1.20
3267 */
3268 final public function onTransactionIdle( $callback ) {
3269 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3270 if ( !$this->mTrxLevel ) {
3271 $this->runOnTransactionIdleCallbacks();
3272 }
3273 }
3274
3275 /**
3276 * Run an anonymous function before the current transaction commits or now if there is none.
3277 * If there is a transaction and it is rolled back, then the callback is cancelled.
3278 * Callbacks must not start nor commit any transactions.
3279 *
3280 * This is useful for updates that easily cause deadlocks if locks are held too long
3281 * but where atomicity is strongly desired for these updates and some related updates.
3282 *
3283 * @param callable $callback
3284 * @since 1.22
3285 */
3286 final public function onTransactionPreCommitOrIdle( $callback ) {
3287 if ( $this->mTrxLevel ) {
3288 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3289 } else {
3290 $this->onTransactionIdle( $callback ); // this will trigger immediately
3291 }
3292 }
3293
3294 /**
3295 * Actually any "on transaction idle" callbacks.
3296 *
3297 * @since 1.20
3298 */
3299 protected function runOnTransactionIdleCallbacks() {
3300 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3301
3302 $e = $ePrior = null; // last exception
3303 do { // callbacks may add callbacks :)
3304 $callbacks = $this->mTrxIdleCallbacks;
3305 $this->mTrxIdleCallbacks = array(); // recursion guard
3306 foreach ( $callbacks as $callback ) {
3307 try {
3308 list( $phpCallback ) = $callback;
3309 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3310 call_user_func( $phpCallback );
3311 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3312 } catch ( Exception $e ) {
3313 if ( $ePrior ) {
3314 MWExceptionHandler::logException( $ePrior );
3315 }
3316 $ePrior = $e;
3317 }
3318 }
3319 } while ( count( $this->mTrxIdleCallbacks ) );
3320
3321 if ( $e instanceof Exception ) {
3322 throw $e; // re-throw any last exception
3323 }
3324 }
3325
3326 /**
3327 * Actually any "on transaction pre-commit" callbacks.
3328 *
3329 * @since 1.22
3330 */
3331 protected function runOnTransactionPreCommitCallbacks() {
3332 $e = $ePrior = null; // last exception
3333 do { // callbacks may add callbacks :)
3334 $callbacks = $this->mTrxPreCommitCallbacks;
3335 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3336 foreach ( $callbacks as $callback ) {
3337 try {
3338 list( $phpCallback ) = $callback;
3339 call_user_func( $phpCallback );
3340 } catch ( Exception $e ) {
3341 if ( $ePrior ) {
3342 MWExceptionHandler::logException( $ePrior );
3343 }
3344 $ePrior = $e;
3345 }
3346 }
3347 } while ( count( $this->mTrxPreCommitCallbacks ) );
3348
3349 if ( $e instanceof Exception ) {
3350 throw $e; // re-throw any last exception
3351 }
3352 }
3353
3354 /**
3355 * Begin an atomic section of statements
3356 *
3357 * If a transaction has been started already, just keep track of the given
3358 * section name to make sure the transaction is not committed pre-maturely.
3359 * This function can be used in layers (with sub-sections), so use a stack
3360 * to keep track of the different atomic sections. If there is no transaction,
3361 * start one implicitly.
3362 *
3363 * The goal of this function is to create an atomic section of SQL queries
3364 * without having to start a new transaction if it already exists.
3365 *
3366 * Atomic sections are more strict than transactions. With transactions,
3367 * attempting to begin a new transaction when one is already running results
3368 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3369 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3370 * and any database transactions cannot be began or committed until all atomic
3371 * levels are closed. There is no such thing as implicitly opening or closing
3372 * an atomic section.
3373 *
3374 * @since 1.23
3375 * @param string $fname
3376 * @throws DBError
3377 */
3378 final public function startAtomic( $fname = __METHOD__ ) {
3379 if ( !$this->mTrxLevel ) {
3380 $this->begin( $fname );
3381 $this->mTrxAutomatic = true;
3382 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3383 // in all changes being in one transaction to keep requests transactional.
3384 if ( !$this->getFlag( DBO_TRX ) ) {
3385 $this->mTrxAutomaticAtomic = true;
3386 }
3387 }
3388
3389 $this->mTrxAtomicLevels[] = $fname;
3390 }
3391
3392 /**
3393 * Ends an atomic section of SQL statements
3394 *
3395 * Ends the next section of atomic SQL statements and commits the transaction
3396 * if necessary.
3397 *
3398 * @since 1.23
3399 * @see DatabaseBase::startAtomic
3400 * @param string $fname
3401 * @throws DBError
3402 */
3403 final public function endAtomic( $fname = __METHOD__ ) {
3404 if ( !$this->mTrxLevel ) {
3405 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3406 }
3407 if ( !$this->mTrxAtomicLevels ||
3408 array_pop( $this->mTrxAtomicLevels ) !== $fname
3409 ) {
3410 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3411 }
3412
3413 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
3414 $this->commit( $fname, 'flush' );
3415 }
3416 }
3417
3418 /**
3419 * Begin a transaction. If a transaction is already in progress,
3420 * that transaction will be committed before the new transaction is started.
3421 *
3422 * Note that when the DBO_TRX flag is set (which is usually the case for web
3423 * requests, but not for maintenance scripts), any previous database query
3424 * will have started a transaction automatically.
3425 *
3426 * Nesting of transactions is not supported. Attempts to nest transactions
3427 * will cause a warning, unless the current transaction was started
3428 * automatically because of the DBO_TRX flag.
3429 *
3430 * @param string $fname
3431 * @throws DBError
3432 */
3433 final public function begin( $fname = __METHOD__ ) {
3434 if ( $this->mTrxLevel ) { // implicit commit
3435 if ( $this->mTrxAtomicLevels ) {
3436 // If the current transaction was an automatic atomic one, then we definitely have
3437 // a problem. Same if there is any unclosed atomic level.
3438 $levels = implode( ', ', $this->mTrxAtomicLevels );
3439 throw new DBUnexpectedError(
3440 $this,
3441 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
3442 );
3443 } elseif ( !$this->mTrxAutomatic ) {
3444 // We want to warn about inadvertently nested begin/commit pairs, but not about
3445 // auto-committing implicit transactions that were started by query() via DBO_TRX
3446 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3447 " performing implicit commit!";
3448 wfWarn( $msg );
3449 wfLogDBError( $msg,
3450 $this->getLogContext( array(
3451 'method' => __METHOD__,
3452 'fname' => $fname,
3453 ) )
3454 );
3455 } else {
3456 // if the transaction was automatic and has done write operations
3457 if ( $this->mTrxDoneWrites ) {
3458 wfDebug( "$fname: Automatic transaction with writes in progress" .
3459 " (from {$this->mTrxFname}), performing implicit commit!\n"
3460 );
3461 }
3462 }
3463
3464 $this->runOnTransactionPreCommitCallbacks();
3465 $writeTime = $this->pendingWriteQueryDuration();
3466 $this->doCommit( $fname );
3467 if ( $this->mTrxDoneWrites ) {
3468 $this->mDoneWrites = microtime( true );
3469 $this->getTransactionProfiler()->transactionWritingOut(
3470 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3471 }
3472 $this->runOnTransactionIdleCallbacks();
3473 }
3474
3475 # Avoid fatals if close() was called
3476 $this->assertOpen();
3477
3478 $this->doBegin( $fname );
3479 $this->mTrxTimestamp = microtime( true );
3480 $this->mTrxFname = $fname;
3481 $this->mTrxDoneWrites = false;
3482 $this->mTrxAutomatic = false;
3483 $this->mTrxAutomaticAtomic = false;
3484 $this->mTrxAtomicLevels = array();
3485 $this->mTrxIdleCallbacks = array();
3486 $this->mTrxPreCommitCallbacks = array();
3487 $this->mTrxShortId = wfRandomString( 12 );
3488 $this->mTrxWriteDuration = 0.0;
3489 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3490 // Get an estimate of the slave lag before then, treating estimate staleness
3491 // as lag itself just to be safe
3492 $status = $this->getApproximateLagStatus();
3493 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
3494 }
3495
3496 /**
3497 * Issues the BEGIN command to the database server.
3498 *
3499 * @see DatabaseBase::begin()
3500 * @param string $fname
3501 */
3502 protected function doBegin( $fname ) {
3503 $this->query( 'BEGIN', $fname );
3504 $this->mTrxLevel = 1;
3505 }
3506
3507 /**
3508 * Commits a transaction previously started using begin().
3509 * If no transaction is in progress, a warning is issued.
3510 *
3511 * Nesting of transactions is not supported.
3512 *
3513 * @param string $fname
3514 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3515 * explicitly committing implicit transactions, or calling commit when no
3516 * transaction is in progress. This will silently break any ongoing
3517 * explicit transaction. Only set the flush flag if you are sure that it
3518 * is safe to ignore these warnings in your context.
3519 * @throws DBUnexpectedError
3520 */
3521 final public function commit( $fname = __METHOD__, $flush = '' ) {
3522 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
3523 // There are still atomic sections open. This cannot be ignored
3524 $levels = implode( ', ', $this->mTrxAtomicLevels );
3525 throw new DBUnexpectedError(
3526 $this,
3527 "Got COMMIT while atomic sections $levels are still open"
3528 );
3529 }
3530
3531 if ( $flush === 'flush' ) {
3532 if ( !$this->mTrxLevel ) {
3533 return; // nothing to do
3534 } elseif ( !$this->mTrxAutomatic ) {
3535 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3536 }
3537 } else {
3538 if ( !$this->mTrxLevel ) {
3539 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3540 return; // nothing to do
3541 } elseif ( $this->mTrxAutomatic ) {
3542 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3543 }
3544 }
3545
3546 # Avoid fatals if close() was called
3547 $this->assertOpen();
3548
3549 $this->runOnTransactionPreCommitCallbacks();
3550 $writeTime = $this->pendingWriteQueryDuration();
3551 $this->doCommit( $fname );
3552 if ( $this->mTrxDoneWrites ) {
3553 $this->mDoneWrites = microtime( true );
3554 $this->getTransactionProfiler()->transactionWritingOut(
3555 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3556 }
3557 $this->runOnTransactionIdleCallbacks();
3558 }
3559
3560 /**
3561 * Issues the COMMIT command to the database server.
3562 *
3563 * @see DatabaseBase::commit()
3564 * @param string $fname
3565 */
3566 protected function doCommit( $fname ) {
3567 if ( $this->mTrxLevel ) {
3568 $this->query( 'COMMIT', $fname );
3569 $this->mTrxLevel = 0;
3570 }
3571 }
3572
3573 /**
3574 * Rollback a transaction previously started using begin().
3575 * If no transaction is in progress, a warning is issued.
3576 *
3577 * No-op on non-transactional databases.
3578 *
3579 * @param string $fname
3580 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3581 * calling rollback when no transaction is in progress. This will silently
3582 * break any ongoing explicit transaction. Only set the flush flag if you
3583 * are sure that it is safe to ignore these warnings in your context.
3584 * @throws DBUnexpectedError
3585 * @since 1.23 Added $flush parameter
3586 */
3587 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3588 if ( $flush !== 'flush' ) {
3589 if ( !$this->mTrxLevel ) {
3590 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3591 return; // nothing to do
3592 } elseif ( $this->mTrxAutomatic ) {
3593 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3594 }
3595 } else {
3596 if ( !$this->mTrxLevel ) {
3597 return; // nothing to do
3598 } elseif ( !$this->mTrxAutomatic ) {
3599 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3600 }
3601 }
3602
3603 # Avoid fatals if close() was called
3604 $this->assertOpen();
3605
3606 $this->doRollback( $fname );
3607 $this->mTrxIdleCallbacks = array(); // cancel
3608 $this->mTrxPreCommitCallbacks = array(); // cancel
3609 $this->mTrxAtomicLevels = array();
3610 if ( $this->mTrxDoneWrites ) {
3611 $this->getTransactionProfiler()->transactionWritingOut(
3612 $this->mServer, $this->mDBname, $this->mTrxShortId );
3613 }
3614 }
3615
3616 /**
3617 * Issues the ROLLBACK command to the database server.
3618 *
3619 * @see DatabaseBase::rollback()
3620 * @param string $fname
3621 */
3622 protected function doRollback( $fname ) {
3623 if ( $this->mTrxLevel ) {
3624 $this->query( 'ROLLBACK', $fname, true );
3625 $this->mTrxLevel = 0;
3626 }
3627 }
3628
3629 /**
3630 * Creates a new table with structure copied from existing table
3631 * Note that unlike most database abstraction functions, this function does not
3632 * automatically append database prefix, because it works at a lower
3633 * abstraction level.
3634 * The table names passed to this function shall not be quoted (this
3635 * function calls addIdentifierQuotes when needed).
3636 *
3637 * @param string $oldName Name of table whose structure should be copied
3638 * @param string $newName Name of table to be created
3639 * @param bool $temporary Whether the new table should be temporary
3640 * @param string $fname Calling function name
3641 * @throws MWException
3642 * @return bool True if operation was successful
3643 */
3644 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3645 $fname = __METHOD__
3646 ) {
3647 throw new MWException(
3648 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3649 }
3650
3651 /**
3652 * List all tables on the database
3653 *
3654 * @param string $prefix Only show tables with this prefix, e.g. mw_
3655 * @param string $fname Calling function name
3656 * @throws MWException
3657 * @return array
3658 */
3659 function listTables( $prefix = null, $fname = __METHOD__ ) {
3660 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3661 }
3662
3663 /**
3664 * Reset the views process cache set by listViews()
3665 * @since 1.22
3666 */
3667 final public function clearViewsCache() {
3668 $this->allViews = null;
3669 }
3670
3671 /**
3672 * Lists all the VIEWs in the database
3673 *
3674 * For caching purposes the list of all views should be stored in
3675 * $this->allViews. The process cache can be cleared with clearViewsCache()
3676 *
3677 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3678 * @param string $fname Name of calling function
3679 * @throws MWException
3680 * @return array
3681 * @since 1.22
3682 */
3683 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3684 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3685 }
3686
3687 /**
3688 * Differentiates between a TABLE and a VIEW
3689 *
3690 * @param string $name Name of the database-structure to test.
3691 * @throws MWException
3692 * @return bool
3693 * @since 1.22
3694 */
3695 public function isView( $name ) {
3696 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3697 }
3698
3699 /**
3700 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3701 * to the format used for inserting into timestamp fields in this DBMS.
3702 *
3703 * The result is unquoted, and needs to be passed through addQuotes()
3704 * before it can be included in raw SQL.
3705 *
3706 * @param string|int $ts
3707 *
3708 * @return string
3709 */
3710 public function timestamp( $ts = 0 ) {
3711 return wfTimestamp( TS_MW, $ts );
3712 }
3713
3714 /**
3715 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3716 * to the format used for inserting into timestamp fields in this DBMS. If
3717 * NULL is input, it is passed through, allowing NULL values to be inserted
3718 * into timestamp fields.
3719 *
3720 * The result is unquoted, and needs to be passed through addQuotes()
3721 * before it can be included in raw SQL.
3722 *
3723 * @param string|int $ts
3724 *
3725 * @return string
3726 */
3727 public function timestampOrNull( $ts = null ) {
3728 if ( is_null( $ts ) ) {
3729 return null;
3730 } else {
3731 return $this->timestamp( $ts );
3732 }
3733 }
3734
3735 /**
3736 * Take the result from a query, and wrap it in a ResultWrapper if
3737 * necessary. Boolean values are passed through as is, to indicate success
3738 * of write queries or failure.
3739 *
3740 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3741 * resource, and it was necessary to call this function to convert it to
3742 * a wrapper. Nowadays, raw database objects are never exposed to external
3743 * callers, so this is unnecessary in external code.
3744 *
3745 * @param bool|ResultWrapper|resource|object $result
3746 * @return bool|ResultWrapper
3747 */
3748 protected function resultObject( $result ) {
3749 if ( !$result ) {
3750 return false;
3751 } elseif ( $result instanceof ResultWrapper ) {
3752 return $result;
3753 } elseif ( $result === true ) {
3754 // Successful write query
3755 return $result;
3756 } else {
3757 return new ResultWrapper( $this, $result );
3758 }
3759 }
3760
3761 /**
3762 * Ping the server and try to reconnect if it there is no connection
3763 *
3764 * @return bool Success or failure
3765 */
3766 public function ping() {
3767 # Stub. Not essential to override.
3768 return true;
3769 }
3770
3771 /**
3772 * Get the slave lag when the current transaction started
3773 * or a general lag estimate if not transaction is active
3774 *
3775 * This is useful when transactions might use snapshot isolation
3776 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3777 * is this lag plus transaction duration. If they don't, it is still
3778 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
3779 * indication of the staleness of subsequent reads.
3780 *
3781 * @return array ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3782 * @since 1.27
3783 */
3784 public function getSessionLagStatus() {
3785 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
3786 }
3787
3788 /**
3789 * Get the slave lag when the current transaction started
3790 *
3791 * This is useful when transactions might use snapshot isolation
3792 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3793 * is this lag plus transaction duration. If they don't, it is still
3794 * safe to be pessimistic. This returns null if there is no transaction.
3795 *
3796 * @return array|null ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3797 * @since 1.27
3798 */
3799 public function getTransactionLagStatus() {
3800 return $this->mTrxLevel
3801 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
3802 : null;
3803 }
3804
3805 /**
3806 * Get a slave lag estimate for this server
3807 *
3808 * @return array ('lag': seconds, 'since': UNIX timestamp of estimate)
3809 * @since 1.27
3810 */
3811 public function getApproximateLagStatus() {
3812 return array(
3813 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
3814 'since' => microtime( true )
3815 );
3816 }
3817
3818 /**
3819 * Merge the result of getSessionLagStatus() for several DBs
3820 * using the most pessimistic values to estimate the lag of
3821 * any data derived from them in combination
3822 *
3823 * This is information is useful for caching modules
3824 *
3825 * @see WANObjectCache::set()
3826 * @see WANObjectCache::getWithSetCallback()
3827 *
3828 * @param IDatabase $db1
3829 * @param IDatabase ...
3830 * @return array Map of values:
3831 * - lag: highest lag of any of the DBs
3832 * - since: oldest UNIX timestamp of any of the DB lag estimates
3833 * - pending: whether any of the DBs have uncommitted changes
3834 * @since 1.27
3835 */
3836 public static function getCacheSetOptions( IDatabase $db1 ) {
3837 $res = array( 'lag' => 0, 'since' => INF, 'pending' => false );
3838 foreach ( func_get_args() as $db ) {
3839 /** @var IDatabase $db */
3840 $status = $db->getSessionLagStatus();
3841 $res['lag'] = max( $res['lag'], $status['lag'] );
3842 $res['since'] = min( $res['since'], $status['since'] );
3843 $res['pending'] = $res['pending'] ?: $db->writesPending();
3844 }
3845
3846 return $res;
3847 }
3848
3849 /**
3850 * Get slave lag. Currently supported only by MySQL.
3851 *
3852 * Note that this function will generate a fatal error on many
3853 * installations. Most callers should use LoadBalancer::safeGetLag()
3854 * instead.
3855 *
3856 * @return int Database replication lag in seconds
3857 */
3858 public function getLag() {
3859 return 0;
3860 }
3861
3862 /**
3863 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3864 *
3865 * @return int
3866 */
3867 function maxListLen() {
3868 return 0;
3869 }
3870
3871 /**
3872 * Some DBMSs have a special format for inserting into blob fields, they
3873 * don't allow simple quoted strings to be inserted. To insert into such
3874 * a field, pass the data through this function before passing it to
3875 * DatabaseBase::insert().
3876 *
3877 * @param string $b
3878 * @return string
3879 */
3880 public function encodeBlob( $b ) {
3881 return $b;
3882 }
3883
3884 /**
3885 * Some DBMSs return a special placeholder object representing blob fields
3886 * in result objects. Pass the object through this function to return the
3887 * original string.
3888 *
3889 * @param string|Blob $b
3890 * @return string
3891 */
3892 public function decodeBlob( $b ) {
3893 if ( $b instanceof Blob ) {
3894 $b = $b->fetch();
3895 }
3896 return $b;
3897 }
3898
3899 /**
3900 * Override database's default behavior. $options include:
3901 * 'connTimeout' : Set the connection timeout value in seconds.
3902 * May be useful for very long batch queries such as
3903 * full-wiki dumps, where a single query reads out over
3904 * hours or days.
3905 *
3906 * @param array $options
3907 * @return void
3908 */
3909 public function setSessionOptions( array $options ) {
3910 }
3911
3912 /**
3913 * Read and execute SQL commands from a file.
3914 *
3915 * Returns true on success, error string or exception on failure (depending
3916 * on object's error ignore settings).
3917 *
3918 * @param string $filename File name to open
3919 * @param bool|callable $lineCallback Optional function called before reading each line
3920 * @param bool|callable $resultCallback Optional function called for each MySQL result
3921 * @param bool|string $fname Calling function name or false if name should be
3922 * generated dynamically using $filename
3923 * @param bool|callable $inputCallback Optional function called for each
3924 * complete line sent
3925 * @throws Exception|MWException
3926 * @return bool|string
3927 */
3928 public function sourceFile(
3929 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3930 ) {
3931 MediaWiki\suppressWarnings();
3932 $fp = fopen( $filename, 'r' );
3933 MediaWiki\restoreWarnings();
3934
3935 if ( false === $fp ) {
3936 throw new MWException( "Could not open \"{$filename}\".\n" );
3937 }
3938
3939 if ( !$fname ) {
3940 $fname = __METHOD__ . "( $filename )";
3941 }
3942
3943 try {
3944 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3945 } catch ( Exception $e ) {
3946 fclose( $fp );
3947 throw $e;
3948 }
3949
3950 fclose( $fp );
3951
3952 return $error;
3953 }
3954
3955 /**
3956 * Get the full path of a patch file. Originally based on archive()
3957 * from updaters.inc. Keep in mind this always returns a patch, as
3958 * it fails back to MySQL if no DB-specific patch can be found
3959 *
3960 * @param string $patch The name of the patch, like patch-something.sql
3961 * @return string Full path to patch file
3962 */
3963 public function patchPath( $patch ) {
3964 global $IP;
3965
3966 $dbType = $this->getType();
3967 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3968 return "$IP/maintenance/$dbType/archives/$patch";
3969 } else {
3970 return "$IP/maintenance/archives/$patch";
3971 }
3972 }
3973
3974 /**
3975 * Set variables to be used in sourceFile/sourceStream, in preference to the
3976 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3977 * all. If it's set to false, $GLOBALS will be used.
3978 *
3979 * @param bool|array $vars Mapping variable name to value.
3980 */
3981 public function setSchemaVars( $vars ) {
3982 $this->mSchemaVars = $vars;
3983 }
3984
3985 /**
3986 * Read and execute commands from an open file handle.
3987 *
3988 * Returns true on success, error string or exception on failure (depending
3989 * on object's error ignore settings).
3990 *
3991 * @param resource $fp File handle
3992 * @param bool|callable $lineCallback Optional function called before reading each query
3993 * @param bool|callable $resultCallback Optional function called for each MySQL result
3994 * @param string $fname Calling function name
3995 * @param bool|callable $inputCallback Optional function called for each complete query sent
3996 * @return bool|string
3997 */
3998 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3999 $fname = __METHOD__, $inputCallback = false
4000 ) {
4001 $cmd = '';
4002
4003 while ( !feof( $fp ) ) {
4004 if ( $lineCallback ) {
4005 call_user_func( $lineCallback );
4006 }
4007
4008 $line = trim( fgets( $fp ) );
4009
4010 if ( $line == '' ) {
4011 continue;
4012 }
4013
4014 if ( '-' == $line[0] && '-' == $line[1] ) {
4015 continue;
4016 }
4017
4018 if ( $cmd != '' ) {
4019 $cmd .= ' ';
4020 }
4021
4022 $done = $this->streamStatementEnd( $cmd, $line );
4023
4024 $cmd .= "$line\n";
4025
4026 if ( $done || feof( $fp ) ) {
4027 $cmd = $this->replaceVars( $cmd );
4028
4029 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4030 $res = $this->query( $cmd, $fname );
4031
4032 if ( $resultCallback ) {
4033 call_user_func( $resultCallback, $res, $this );
4034 }
4035
4036 if ( false === $res ) {
4037 $err = $this->lastError();
4038
4039 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4040 }
4041 }
4042 $cmd = '';
4043 }
4044 }
4045
4046 return true;
4047 }
4048
4049 /**
4050 * Called by sourceStream() to check if we've reached a statement end
4051 *
4052 * @param string $sql SQL assembled so far
4053 * @param string $newLine New line about to be added to $sql
4054 * @return bool Whether $newLine contains end of the statement
4055 */
4056 public function streamStatementEnd( &$sql, &$newLine ) {
4057 if ( $this->delimiter ) {
4058 $prev = $newLine;
4059 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4060 if ( $newLine != $prev ) {
4061 return true;
4062 }
4063 }
4064
4065 return false;
4066 }
4067
4068 /**
4069 * Database independent variable replacement. Replaces a set of variables
4070 * in an SQL statement with their contents as given by $this->getSchemaVars().
4071 *
4072 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4073 *
4074 * - '{$var}' should be used for text and is passed through the database's
4075 * addQuotes method.
4076 * - `{$var}` should be used for identifiers (e.g. table and database names).
4077 * It is passed through the database's addIdentifierQuotes method which
4078 * can be overridden if the database uses something other than backticks.
4079 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4080 * database's tableName method.
4081 * - / *i* / passes the name that follows through the database's indexName method.
4082 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4083 * its use should be avoided. In 1.24 and older, string encoding was applied.
4084 *
4085 * @param string $ins SQL statement to replace variables in
4086 * @return string The new SQL statement with variables replaced
4087 */
4088 protected function replaceVars( $ins ) {
4089 $that = $this;
4090 $vars = $this->getSchemaVars();
4091 return preg_replace_callback(
4092 '!
4093 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4094 \'\{\$ (\w+) }\' | # 3. addQuotes
4095 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4096 /\*\$ (\w+) \*/ # 5. leave unencoded
4097 !x',
4098 function ( $m ) use ( $that, $vars ) {
4099 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4100 // check for both nonexistent keys *and* the empty string.
4101 if ( isset( $m[1] ) && $m[1] !== '' ) {
4102 if ( $m[1] === 'i' ) {
4103 return $that->indexName( $m[2] );
4104 } else {
4105 return $that->tableName( $m[2] );
4106 }
4107 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4108 return $that->addQuotes( $vars[$m[3]] );
4109 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4110 return $that->addIdentifierQuotes( $vars[$m[4]] );
4111 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4112 return $vars[$m[5]];
4113 } else {
4114 return $m[0];
4115 }
4116 },
4117 $ins
4118 );
4119 }
4120
4121 /**
4122 * Get schema variables. If none have been set via setSchemaVars(), then
4123 * use some defaults from the current object.
4124 *
4125 * @return array
4126 */
4127 protected function getSchemaVars() {
4128 if ( $this->mSchemaVars ) {
4129 return $this->mSchemaVars;
4130 } else {
4131 return $this->getDefaultSchemaVars();
4132 }
4133 }
4134
4135 /**
4136 * Get schema variables to use if none have been set via setSchemaVars().
4137 *
4138 * Override this in derived classes to provide variables for tables.sql
4139 * and SQL patch files.
4140 *
4141 * @return array
4142 */
4143 protected function getDefaultSchemaVars() {
4144 return array();
4145 }
4146
4147 /**
4148 * Check to see if a named lock is available (non-blocking)
4149 *
4150 * @param string $lockName Name of lock to poll
4151 * @param string $method Name of method calling us
4152 * @return bool
4153 * @since 1.20
4154 */
4155 public function lockIsFree( $lockName, $method ) {
4156 return true;
4157 }
4158
4159 /**
4160 * Acquire a named lock
4161 *
4162 * Named locks are not related to transactions
4163 *
4164 * @param string $lockName Name of lock to aquire
4165 * @param string $method Name of method calling us
4166 * @param int $timeout
4167 * @return bool
4168 */
4169 public function lock( $lockName, $method, $timeout = 5 ) {
4170 return true;
4171 }
4172
4173 /**
4174 * Release a lock
4175 *
4176 * Named locks are not related to transactions
4177 *
4178 * @param string $lockName Name of lock to release
4179 * @param string $method Name of method calling us
4180 *
4181 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4182 * by this thread (in which case the lock is not released), and NULL if the named
4183 * lock did not exist
4184 */
4185 public function unlock( $lockName, $method ) {
4186 return true;
4187 }
4188
4189 /**
4190 * Check to see if a named lock used by lock() use blocking queues
4191 *
4192 * @return bool
4193 * @since 1.26
4194 */
4195 public function namedLocksEnqueue() {
4196 return false;
4197 }
4198
4199 /**
4200 * Lock specific tables
4201 *
4202 * @param array $read Array of tables to lock for read access
4203 * @param array $write Array of tables to lock for write access
4204 * @param string $method Name of caller
4205 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4206 * @return bool
4207 */
4208 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4209 return true;
4210 }
4211
4212 /**
4213 * Unlock specific tables
4214 *
4215 * @param string $method The caller
4216 * @return bool
4217 */
4218 public function unlockTables( $method ) {
4219 return true;
4220 }
4221
4222 /**
4223 * Delete a table
4224 * @param string $tableName
4225 * @param string $fName
4226 * @return bool|ResultWrapper
4227 * @since 1.18
4228 */
4229 public function dropTable( $tableName, $fName = __METHOD__ ) {
4230 if ( !$this->tableExists( $tableName, $fName ) ) {
4231 return false;
4232 }
4233 $sql = "DROP TABLE " . $this->tableName( $tableName );
4234 if ( $this->cascadingDeletes() ) {
4235 $sql .= " CASCADE";
4236 }
4237
4238 return $this->query( $sql, $fName );
4239 }
4240
4241 /**
4242 * Get search engine class. All subclasses of this need to implement this
4243 * if they wish to use searching.
4244 *
4245 * @return string
4246 */
4247 public function getSearchEngine() {
4248 return 'SearchEngineDummy';
4249 }
4250
4251 /**
4252 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4253 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4254 * because "i" sorts after all numbers.
4255 *
4256 * @return string
4257 */
4258 public function getInfinity() {
4259 return 'infinity';
4260 }
4261
4262 /**
4263 * Encode an expiry time into the DBMS dependent format
4264 *
4265 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4266 * @return string
4267 */
4268 public function encodeExpiry( $expiry ) {
4269 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4270 ? $this->getInfinity()
4271 : $this->timestamp( $expiry );
4272 }
4273
4274 /**
4275 * Decode an expiry time into a DBMS independent format
4276 *
4277 * @param string $expiry DB timestamp field value for expiry
4278 * @param int $format TS_* constant, defaults to TS_MW
4279 * @return string
4280 */
4281 public function decodeExpiry( $expiry, $format = TS_MW ) {
4282 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4283 ? 'infinity'
4284 : wfTimestamp( $format, $expiry );
4285 }
4286
4287 /**
4288 * Allow or deny "big selects" for this session only. This is done by setting
4289 * the sql_big_selects session variable.
4290 *
4291 * This is a MySQL-specific feature.
4292 *
4293 * @param bool|string $value True for allow, false for deny, or "default" to
4294 * restore the initial value
4295 */
4296 public function setBigSelects( $value = true ) {
4297 // no-op
4298 }
4299
4300 public function isReadOnly() {
4301 return ( $this->getReadOnlyReason() !== false );
4302 }
4303
4304 /**
4305 * @return string|bool Reason this DB is read-only or false if it is not
4306 */
4307 protected function getReadOnlyReason() {
4308 $reason = $this->getLBInfo( 'readOnlyReason' );
4309
4310 return is_string( $reason ) ? $reason : false;
4311 }
4312
4313 /**
4314 * @since 1.19
4315 * @return string
4316 */
4317 public function __toString() {
4318 return (string)$this->mConn;
4319 }
4320
4321 /**
4322 * Run a few simple sanity checks
4323 */
4324 public function __destruct() {
4325 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4326 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4327 }
4328 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4329 $callers = array();
4330 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4331 $callers[] = $callbackInfo[1];
4332 }
4333 $callers = implode( ', ', $callers );
4334 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4335 }
4336 }
4337 }
4338
4339 /**
4340 * @since 1.27
4341 */
4342 abstract class Database extends DatabaseBase {
4343 // B/C until nothing type hints for DatabaseBase
4344 // @TODO: finish renaming DatabaseBase => Database
4345 }