PHPSessionHandler: Implement SessionHandlerInterface
[mediawiki.git] / includes / db / Database.php
bloba4d0ad0532f432eeac7af19f2a411c31abbe2f1a
1 <?php
3 /**
4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
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.
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.
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
24 * @file
25 * @ingroup Database
28 /**
29 * Database abstraction object
30 * @ingroup Database
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var BagOStuff APC cache */
49 protected $srvCache;
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
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();
70 protected $preparedArgs;
72 protected $htmlErrors;
74 protected $delimiter = ';';
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.
80 * @var int
82 protected $mTrxLevel = 0;
84 /**
85 * Either a short hexidecimal string if a transaction is active or ""
87 * @var string
88 * @see DatabaseBase::mTrxLevel
90 protected $mTrxShortId = '';
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).
97 * @var float|null
98 * @see DatabaseBase::mTrxLevel
100 private $mTrxTimestamp = null;
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
109 * @var string
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
117 * @var bool
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
125 * @var bool
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
133 * @var array
135 private $mTrxAtomicLevels = array();
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
140 * @var bool
142 private $mTrxAutomaticAtomic = false;
145 * Track the write query callers of the current transaction
147 * @var string[]
149 private $mTrxWriteCallers = array();
152 * Track the seconds spent in write queries for the current transaction
154 * @var float
156 private $mTrxWriteDuration = 0.0;
158 /** @var array Map of (name => 1) for locks obtained via lock() */
159 private $mNamedLocksHeld = array();
161 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
162 private $lazyMasterHandle;
165 * @since 1.21
166 * @var resource File handle for upgrade
168 protected $fileHandle = null;
171 * @since 1.22
172 * @var string[] Process cache of VIEWs names in the database
174 protected $allViews = null;
176 /** @var TransactionProfiler */
177 protected $trxProfiler;
179 public function getServerInfo() {
180 return $this->getServerVersion();
184 * @return string Command delimiter used by this database engine
186 public function getDelimiter() {
187 return $this->delimiter;
191 * Boolean, controls output of large amounts of debug information.
192 * @param bool|null $debug
193 * - true to enable debugging
194 * - false to disable debugging
195 * - omitted or null to do nothing
197 * @return bool|null Previous value of the flag
199 public function debug( $debug = null ) {
200 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
203 public function bufferResults( $buffer = null ) {
204 if ( is_null( $buffer ) ) {
205 return !(bool)( $this->mFlags & DBO_NOBUFFER );
206 } else {
207 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
212 * Turns on (false) or off (true) the automatic generation and sending
213 * of a "we're sorry, but there has been a database error" page on
214 * database errors. Default is on (false). When turned off, the
215 * code should use lastErrno() and lastError() to handle the
216 * situation as appropriate.
218 * Do not use this function outside of the Database classes.
220 * @param null|bool $ignoreErrors
221 * @return bool The previous value of the flag.
223 protected function ignoreErrors( $ignoreErrors = null ) {
224 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
227 public function trxLevel() {
228 return $this->mTrxLevel;
231 public function trxTimestamp() {
232 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
235 public function tablePrefix( $prefix = null ) {
236 return wfSetVar( $this->mTablePrefix, $prefix );
239 public function dbSchema( $schema = null ) {
240 return wfSetVar( $this->mSchema, $schema );
244 * Set the filehandle to copy write statements to.
246 * @param resource $fh File handle
248 public function setFileHandle( $fh ) {
249 $this->fileHandle = $fh;
252 public function getLBInfo( $name = null ) {
253 if ( is_null( $name ) ) {
254 return $this->mLBInfo;
255 } else {
256 if ( array_key_exists( $name, $this->mLBInfo ) ) {
257 return $this->mLBInfo[$name];
258 } else {
259 return null;
264 public function setLBInfo( $name, $value = null ) {
265 if ( is_null( $value ) ) {
266 $this->mLBInfo = $name;
267 } else {
268 $this->mLBInfo[$name] = $value;
273 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
275 * @param IDatabase $conn
276 * @since 1.27
278 public function setLazyMasterHandle( IDatabase $conn ) {
279 $this->lazyMasterHandle = $conn;
283 * @return IDatabase|null
284 * @see setLazyMasterHandle()
285 * @since 1.27
287 public function getLazyMasterHandle() {
288 return $this->lazyMasterHandle;
292 * @return TransactionProfiler
294 protected function getTransactionProfiler() {
295 if ( !$this->trxProfiler ) {
296 $this->trxProfiler = new TransactionProfiler();
299 return $this->trxProfiler;
303 * @param TransactionProfiler $profiler
304 * @since 1.27
306 public function setTransactionProfiler( TransactionProfiler $profiler ) {
307 $this->trxProfiler = $profiler;
311 * Returns true if this database supports (and uses) cascading deletes
313 * @return bool
315 public function cascadingDeletes() {
316 return false;
320 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
322 * @return bool
324 public function cleanupTriggers() {
325 return false;
329 * Returns true if this database is strict about what can be put into an IP field.
330 * Specifically, it uses a NULL value instead of an empty string.
332 * @return bool
334 public function strictIPs() {
335 return false;
339 * Returns true if this database uses timestamps rather than integers
341 * @return bool
343 public function realTimestamps() {
344 return false;
347 public function implicitGroupby() {
348 return true;
351 public function implicitOrderby() {
352 return true;
356 * Returns true if this database can do a native search on IP columns
357 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
359 * @return bool
361 public function searchableIPs() {
362 return false;
366 * Returns true if this database can use functional indexes
368 * @return bool
370 public function functionalIndexes() {
371 return false;
374 public function lastQuery() {
375 return $this->mLastQuery;
378 public function doneWrites() {
379 return (bool)$this->mDoneWrites;
382 public function lastDoneWrites() {
383 return $this->mDoneWrites ?: false;
386 public function writesPending() {
387 return $this->mTrxLevel && $this->mTrxDoneWrites;
390 public function writesOrCallbacksPending() {
391 return $this->mTrxLevel && (
392 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
396 public function pendingWriteQueryDuration() {
397 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
400 public function pendingWriteCallers() {
401 return $this->mTrxLevel ? $this->mTrxWriteCallers : array();
404 public function isOpen() {
405 return $this->mOpened;
408 public function setFlag( $flag ) {
409 $this->mFlags |= $flag;
412 public function clearFlag( $flag ) {
413 $this->mFlags &= ~$flag;
416 public function getFlag( $flag ) {
417 return !!( $this->mFlags & $flag );
420 public function getProperty( $name ) {
421 return $this->$name;
424 public function getWikiID() {
425 if ( $this->mTablePrefix ) {
426 return "{$this->mDBname}-{$this->mTablePrefix}";
427 } else {
428 return $this->mDBname;
433 * Return a path to the DBMS-specific SQL file if it exists,
434 * otherwise default SQL file
436 * @param string $filename
437 * @return string
439 private function getSqlFilePath( $filename ) {
440 global $IP;
441 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
442 if ( file_exists( $dbmsSpecificFilePath ) ) {
443 return $dbmsSpecificFilePath;
444 } else {
445 return "$IP/maintenance/$filename";
450 * Return a path to the DBMS-specific schema file,
451 * otherwise default to tables.sql
453 * @return string
455 public function getSchemaPath() {
456 return $this->getSqlFilePath( 'tables.sql' );
460 * Return a path to the DBMS-specific update key file,
461 * otherwise default to update-keys.sql
463 * @return string
465 public function getUpdateKeysPath() {
466 return $this->getSqlFilePath( 'update-keys.sql' );
470 * Get information about an index into an object
471 * @param string $table Table name
472 * @param string $index Index name
473 * @param string $fname Calling function name
474 * @return mixed Database-specific index description class or false if the index does not exist
476 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
479 * Wrapper for addslashes()
481 * @param string $s String to be slashed.
482 * @return string Slashed string.
484 abstract function strencode( $s );
487 * Constructor.
489 * FIXME: It is possible to construct a Database object with no associated
490 * connection object, by specifying no parameters to __construct(). This
491 * feature is deprecated and should be removed.
493 * DatabaseBase subclasses should not be constructed directly in external
494 * code. DatabaseBase::factory() should be used instead.
496 * @param array $params Parameters passed from DatabaseBase::factory()
498 function __construct( array $params ) {
499 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
501 $this->srvCache = ObjectCache::getLocalServerInstance( 'hash' );
503 $server = $params['host'];
504 $user = $params['user'];
505 $password = $params['password'];
506 $dbName = $params['dbname'];
507 $flags = $params['flags'];
508 $tablePrefix = $params['tablePrefix'];
509 $schema = $params['schema'];
510 $foreign = $params['foreign'];
512 $this->mFlags = $flags;
513 if ( $this->mFlags & DBO_DEFAULT ) {
514 if ( $wgCommandLineMode ) {
515 $this->mFlags &= ~DBO_TRX;
516 } else {
517 $this->mFlags |= DBO_TRX;
521 $this->mSessionVars = $params['variables'];
523 /** Get the default table prefix*/
524 if ( $tablePrefix === 'get from global' ) {
525 $this->mTablePrefix = $wgDBprefix;
526 } else {
527 $this->mTablePrefix = $tablePrefix;
530 /** Get the database schema*/
531 if ( $schema === 'get from global' ) {
532 $this->mSchema = $wgDBmwschema;
533 } else {
534 $this->mSchema = $schema;
537 $this->mForeign = $foreign;
539 if ( isset( $params['trxProfiler'] ) ) {
540 $this->trxProfiler = $params['trxProfiler']; // override
543 if ( $user ) {
544 $this->open( $server, $user, $password, $dbName );
549 * Called by serialize. Throw an exception when DB connection is serialized.
550 * This causes problems on some database engines because the connection is
551 * not restored on unserialize.
553 public function __sleep() {
554 throw new MWException( 'Database serialization may cause problems, since ' .
555 'the connection is not restored on wakeup.' );
559 * Given a DB type, construct the name of the appropriate child class of
560 * DatabaseBase. This is designed to replace all of the manual stuff like:
561 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
562 * as well as validate against the canonical list of DB types we have
564 * This factory function is mostly useful for when you need to connect to a
565 * database other than the MediaWiki default (such as for external auth,
566 * an extension, et cetera). Do not use this to connect to the MediaWiki
567 * database. Example uses in core:
568 * @see LoadBalancer::reallyOpenConnection()
569 * @see ForeignDBRepo::getMasterDB()
570 * @see WebInstallerDBConnect::execute()
572 * @since 1.18
574 * @param string $dbType A possible DB type
575 * @param array $p An array of options to pass to the constructor.
576 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
577 * @throws MWException If the database driver or extension cannot be found
578 * @return DatabaseBase|null DatabaseBase subclass or null
580 final public static function factory( $dbType, $p = array() ) {
581 $canonicalDBTypes = array(
582 'mysql' => array( 'mysqli', 'mysql' ),
583 'postgres' => array(),
584 'sqlite' => array(),
585 'oracle' => array(),
586 'mssql' => array(),
589 $driver = false;
590 $dbType = strtolower( $dbType );
591 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
592 $possibleDrivers = $canonicalDBTypes[$dbType];
593 if ( !empty( $p['driver'] ) ) {
594 if ( in_array( $p['driver'], $possibleDrivers ) ) {
595 $driver = $p['driver'];
596 } else {
597 throw new MWException( __METHOD__ .
598 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
600 } else {
601 foreach ( $possibleDrivers as $posDriver ) {
602 if ( extension_loaded( $posDriver ) ) {
603 $driver = $posDriver;
604 break;
608 } else {
609 $driver = $dbType;
611 if ( $driver === false ) {
612 throw new MWException( __METHOD__ .
613 " no viable database extension found for type '$dbType'" );
616 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
617 // and everything else doesn't use a schema (e.g. null)
618 // Although postgres and oracle support schemas, we don't use them (yet)
619 // to maintain backwards compatibility
620 $defaultSchemas = array(
621 'mssql' => 'get from global',
624 $class = 'Database' . ucfirst( $driver );
625 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
626 // Resolve some defaults for b/c
627 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
628 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
629 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
630 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
631 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
632 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
633 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
634 if ( !isset( $p['schema'] ) ) {
635 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
637 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
639 return new $class( $p );
640 } else {
641 return null;
645 protected function installErrorHandler() {
646 $this->mPHPError = false;
647 $this->htmlErrors = ini_set( 'html_errors', '0' );
648 set_error_handler( array( $this, 'connectionErrorHandler' ) );
652 * @return bool|string
654 protected function restoreErrorHandler() {
655 restore_error_handler();
656 if ( $this->htmlErrors !== false ) {
657 ini_set( 'html_errors', $this->htmlErrors );
659 if ( $this->mPHPError ) {
660 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
661 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
663 return $error;
664 } else {
665 return false;
670 * @param int $errno
671 * @param string $errstr
673 public function connectionErrorHandler( $errno, $errstr ) {
674 $this->mPHPError = $errstr;
678 * Create a log context to pass to wfLogDBError or other logging functions.
680 * @param array $extras Additional data to add to context
681 * @return array
683 protected function getLogContext( array $extras = array() ) {
684 return array_merge(
685 array(
686 'db_server' => $this->mServer,
687 'db_name' => $this->mDBname,
688 'db_user' => $this->mUser,
690 $extras
694 public function close() {
695 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
696 throw new MWException( "Transaction idle callbacks still pending." );
698 if ( $this->mConn ) {
699 if ( $this->trxLevel() ) {
700 if ( !$this->mTrxAutomatic ) {
701 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
702 " performing implicit commit before closing connection!" );
705 $this->commit( __METHOD__, 'flush' );
708 $closed = $this->closeConnection();
709 $this->mConn = false;
710 } else {
711 $closed = true;
713 $this->mOpened = false;
715 return $closed;
719 * Make sure isOpen() returns true as a sanity check
721 * @throws DBUnexpectedError
723 protected function assertOpen() {
724 if ( !$this->isOpen() ) {
725 throw new DBUnexpectedError( $this, "DB connection was already closed." );
730 * Closes underlying database connection
731 * @since 1.20
732 * @return bool Whether connection was closed successfully
734 abstract protected function closeConnection();
736 function reportConnectionError( $error = 'Unknown error' ) {
737 $myError = $this->lastError();
738 if ( $myError ) {
739 $error = $myError;
742 # New method
743 throw new DBConnectionError( $this, $error );
747 * The DBMS-dependent part of query()
749 * @param string $sql SQL query.
750 * @return ResultWrapper|bool Result object to feed to fetchObject,
751 * fetchRow, ...; or false on failure
753 abstract protected function doQuery( $sql );
756 * Determine whether a query writes to the DB.
757 * Should return true if unsure.
759 * @param string $sql
760 * @return bool
762 protected function isWriteQuery( $sql ) {
763 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
767 * Determine whether a SQL statement is sensitive to isolation level.
768 * A SQL statement is considered transactable if its result could vary
769 * depending on the transaction isolation level. Operational commands
770 * such as 'SET' and 'SHOW' are not considered to be transactable.
772 * @param string $sql
773 * @return bool
775 protected function isTransactableQuery( $sql ) {
776 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
777 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
780 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
781 global $wgUser;
783 $this->mLastQuery = $sql;
785 $isWriteQuery = $this->isWriteQuery( $sql );
786 if ( $isWriteQuery ) {
787 $reason = $this->getReadOnlyReason();
788 if ( $reason !== false ) {
789 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
791 # Set a flag indicating that writes have been done
792 $this->mDoneWrites = microtime( true );
795 # Add a comment for easy SHOW PROCESSLIST interpretation
796 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
797 $userName = $wgUser->getName();
798 if ( mb_strlen( $userName ) > 15 ) {
799 $userName = mb_substr( $userName, 0, 15 ) . '...';
801 $userName = str_replace( '/', '', $userName );
802 } else {
803 $userName = '';
806 // Add trace comment to the begin of the sql string, right after the operator.
807 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
808 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
810 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
811 $this->begin( __METHOD__ . " ($fname)" );
812 $this->mTrxAutomatic = true;
815 # Keep track of whether the transaction has write queries pending
816 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
817 $this->mTrxDoneWrites = true;
818 $this->getTransactionProfiler()->transactionWritingIn(
819 $this->mServer, $this->mDBname, $this->mTrxShortId );
822 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
823 # generalizeSQL will probably cut down the query to reasonable
824 # logging size most of the time. The substr is really just a sanity check.
825 if ( $isMaster ) {
826 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
827 $totalProf = 'DatabaseBase::query-master';
828 } else {
829 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
830 $totalProf = 'DatabaseBase::query';
832 # Include query transaction state
833 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
835 $profiler = Profiler::instance();
836 if ( !$profiler instanceof ProfilerStub ) {
837 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
838 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
841 if ( $this->debug() ) {
842 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname, $commentedSql ) );
845 $queryId = MWDebug::query( $sql, $fname, $isMaster );
847 # Avoid fatals if close() was called
848 $this->assertOpen();
850 # Do the query and handle errors
851 $startTime = microtime( true );
852 $ret = $this->doQuery( $commentedSql );
853 $queryRuntime = microtime( true ) - $startTime;
854 # Log the query time and feed it into the DB trx profiler
855 $this->getTransactionProfiler()->recordQueryCompletion(
856 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
858 MWDebug::queryTime( $queryId );
860 # Try reconnecting if the connection was lost
861 if ( false === $ret && $this->wasErrorReissuable() ) {
862 # Transaction is gone, like it or not
863 $hadTrx = $this->mTrxLevel; // possible lost transaction
864 $this->mTrxLevel = 0;
865 $this->mTrxIdleCallbacks = array(); // bug 65263
866 $this->mTrxPreCommitCallbacks = array(); // bug 65263
867 wfDebug( "Connection lost, reconnecting...\n" );
868 # Stash the last error values since ping() might clear them
869 $lastError = $this->lastError();
870 $lastErrno = $this->lastErrno();
871 if ( $this->ping() ) {
872 wfDebug( "Reconnected\n" );
873 $server = $this->getServer();
874 $msg = __METHOD__ . ": lost connection to $server; reconnected";
875 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
877 if ( $hadTrx || $this->mNamedLocksHeld ) {
878 # Leave $ret as false and let an error be reported.
879 # Callers may catch the exception and continue to use the DB.
880 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
881 } else {
882 # Should be safe to silently retry (no trx and thus no callbacks)
883 $startTime = microtime( true );
884 $ret = $this->doQuery( $commentedSql );
885 $queryRuntime = microtime( true ) - $startTime;
886 # Log the query time and feed it into the DB trx profiler
887 $this->getTransactionProfiler()->recordQueryCompletion(
888 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
890 } else {
891 wfDebug( "Failed\n" );
895 if ( false === $ret ) {
896 $this->reportQueryError(
897 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
900 $res = $this->resultObject( $ret );
902 // Destroy profile sections in the opposite order to their creation
903 ScopedCallback::consume( $queryProfSection );
904 ScopedCallback::consume( $totalProfSection );
906 if ( $isWriteQuery && $this->mTrxLevel ) {
907 $this->mTrxWriteDuration += $queryRuntime;
908 $this->mTrxWriteCallers[] = $fname;
911 return $res;
914 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
915 if ( $this->ignoreErrors() || $tempIgnore ) {
916 wfDebug( "SQL ERROR (ignored): $error\n" );
917 } else {
918 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
919 wfLogDBError(
920 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
921 $this->getLogContext( array(
922 'method' => __METHOD__,
923 'errno' => $errno,
924 'error' => $error,
925 'sql1line' => $sql1line,
926 'fname' => $fname,
929 wfDebug( "SQL ERROR: " . $error . "\n" );
930 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
935 * Intended to be compatible with the PEAR::DB wrapper functions.
936 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
938 * ? = scalar value, quoted as necessary
939 * ! = raw SQL bit (a function for instance)
940 * & = filename; reads the file and inserts as a blob
941 * (we don't use this though...)
943 * @param string $sql
944 * @param string $func
946 * @return array
948 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
949 /* MySQL doesn't support prepared statements (yet), so just
950 * pack up the query for reference. We'll manually replace
951 * the bits later.
953 return array( 'query' => $sql, 'func' => $func );
957 * Free a prepared query, generated by prepare().
958 * @param string $prepared
960 protected function freePrepared( $prepared ) {
961 /* No-op by default */
965 * Execute a prepared query with the various arguments
966 * @param string $prepared The prepared sql
967 * @param mixed $args Either an array here, or put scalars as varargs
969 * @return ResultWrapper
971 public function execute( $prepared, $args = null ) {
972 if ( !is_array( $args ) ) {
973 # Pull the var args
974 $args = func_get_args();
975 array_shift( $args );
978 $sql = $this->fillPrepared( $prepared['query'], $args );
980 return $this->query( $sql, $prepared['func'] );
984 * For faking prepared SQL statements on DBs that don't support it directly.
986 * @param string $preparedQuery A 'preparable' SQL statement
987 * @param array $args Array of Arguments to fill it with
988 * @return string Executable SQL
990 public function fillPrepared( $preparedQuery, $args ) {
991 reset( $args );
992 $this->preparedArgs =& $args;
994 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
995 array( &$this, 'fillPreparedArg' ), $preparedQuery );
999 * preg_callback func for fillPrepared()
1000 * The arguments should be in $this->preparedArgs and must not be touched
1001 * while we're doing this.
1003 * @param array $matches
1004 * @throws DBUnexpectedError
1005 * @return string
1007 protected function fillPreparedArg( $matches ) {
1008 switch ( $matches[1] ) {
1009 case '\\?':
1010 return '?';
1011 case '\\!':
1012 return '!';
1013 case '\\&':
1014 return '&';
1017 list( /* $n */, $arg ) = each( $this->preparedArgs );
1019 switch ( $matches[1] ) {
1020 case '?':
1021 return $this->addQuotes( $arg );
1022 case '!':
1023 return $arg;
1024 case '&':
1025 # return $this->addQuotes( file_get_contents( $arg ) );
1026 throw new DBUnexpectedError(
1027 $this,
1028 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1030 default:
1031 throw new DBUnexpectedError(
1032 $this,
1033 'Received invalid match. This should never happen!'
1038 public function freeResult( $res ) {
1041 public function selectField(
1042 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1044 if ( $var === '*' ) { // sanity
1045 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1048 if ( !is_array( $options ) ) {
1049 $options = array( $options );
1052 $options['LIMIT'] = 1;
1054 $res = $this->select( $table, $var, $cond, $fname, $options );
1055 if ( $res === false || !$this->numRows( $res ) ) {
1056 return false;
1059 $row = $this->fetchRow( $res );
1061 if ( $row !== false ) {
1062 return reset( $row );
1063 } else {
1064 return false;
1068 public function selectFieldValues(
1069 $table, $var, $cond = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1071 if ( $var === '*' ) { // sanity
1072 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1075 if ( !is_array( $options ) ) {
1076 $options = array( $options );
1079 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1080 if ( $res === false ) {
1081 return false;
1084 $values = array();
1085 foreach ( $res as $row ) {
1086 $values[] = $row->$var;
1089 return $values;
1093 * Returns an optional USE INDEX clause to go after the table, and a
1094 * string to go at the end of the query.
1096 * @param array $options Associative array of options to be turned into
1097 * an SQL query, valid keys are listed in the function.
1098 * @return array
1099 * @see DatabaseBase::select()
1101 public function makeSelectOptions( $options ) {
1102 $preLimitTail = $postLimitTail = '';
1103 $startOpts = '';
1105 $noKeyOptions = array();
1107 foreach ( $options as $key => $option ) {
1108 if ( is_numeric( $key ) ) {
1109 $noKeyOptions[$option] = true;
1113 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1115 $preLimitTail .= $this->makeOrderBy( $options );
1117 // if (isset($options['LIMIT'])) {
1118 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1119 // isset($options['OFFSET']) ? $options['OFFSET']
1120 // : false);
1121 // }
1123 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1124 $postLimitTail .= ' FOR UPDATE';
1127 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1128 $postLimitTail .= ' LOCK IN SHARE MODE';
1131 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1132 $startOpts .= 'DISTINCT';
1135 # Various MySQL extensions
1136 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1137 $startOpts .= ' /*! STRAIGHT_JOIN */';
1140 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1141 $startOpts .= ' HIGH_PRIORITY';
1144 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1145 $startOpts .= ' SQL_BIG_RESULT';
1148 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1149 $startOpts .= ' SQL_BUFFER_RESULT';
1152 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1153 $startOpts .= ' SQL_SMALL_RESULT';
1156 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1157 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1160 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1161 $startOpts .= ' SQL_CACHE';
1164 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1165 $startOpts .= ' SQL_NO_CACHE';
1168 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1169 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1170 } else {
1171 $useIndex = '';
1174 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1178 * Returns an optional GROUP BY with an optional HAVING
1180 * @param array $options Associative array of options
1181 * @return string
1182 * @see DatabaseBase::select()
1183 * @since 1.21
1185 public function makeGroupByWithHaving( $options ) {
1186 $sql = '';
1187 if ( isset( $options['GROUP BY'] ) ) {
1188 $gb = is_array( $options['GROUP BY'] )
1189 ? implode( ',', $options['GROUP BY'] )
1190 : $options['GROUP BY'];
1191 $sql .= ' GROUP BY ' . $gb;
1193 if ( isset( $options['HAVING'] ) ) {
1194 $having = is_array( $options['HAVING'] )
1195 ? $this->makeList( $options['HAVING'], LIST_AND )
1196 : $options['HAVING'];
1197 $sql .= ' HAVING ' . $having;
1200 return $sql;
1204 * Returns an optional ORDER BY
1206 * @param array $options Associative array of options
1207 * @return string
1208 * @see DatabaseBase::select()
1209 * @since 1.21
1211 public function makeOrderBy( $options ) {
1212 if ( isset( $options['ORDER BY'] ) ) {
1213 $ob = is_array( $options['ORDER BY'] )
1214 ? implode( ',', $options['ORDER BY'] )
1215 : $options['ORDER BY'];
1217 return ' ORDER BY ' . $ob;
1220 return '';
1223 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1224 $options = array(), $join_conds = array() ) {
1225 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1227 return $this->query( $sql, $fname );
1230 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1231 $options = array(), $join_conds = array()
1233 if ( is_array( $vars ) ) {
1234 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1237 $options = (array)$options;
1238 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1239 ? $options['USE INDEX']
1240 : array();
1242 if ( is_array( $table ) ) {
1243 $from = ' FROM ' .
1244 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1245 } elseif ( $table != '' ) {
1246 if ( $table[0] == ' ' ) {
1247 $from = ' FROM ' . $table;
1248 } else {
1249 $from = ' FROM ' .
1250 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1252 } else {
1253 $from = '';
1256 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1257 $this->makeSelectOptions( $options );
1259 if ( !empty( $conds ) ) {
1260 if ( is_array( $conds ) ) {
1261 $conds = $this->makeList( $conds, LIST_AND );
1263 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1264 } else {
1265 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1268 if ( isset( $options['LIMIT'] ) ) {
1269 $sql = $this->limitResult( $sql, $options['LIMIT'],
1270 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1272 $sql = "$sql $postLimitTail";
1274 if ( isset( $options['EXPLAIN'] ) ) {
1275 $sql = 'EXPLAIN ' . $sql;
1278 return $sql;
1281 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1282 $options = array(), $join_conds = array()
1284 $options = (array)$options;
1285 $options['LIMIT'] = 1;
1286 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1288 if ( $res === false ) {
1289 return false;
1292 if ( !$this->numRows( $res ) ) {
1293 return false;
1296 $obj = $this->fetchObject( $res );
1298 return $obj;
1301 public function estimateRowCount(
1302 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1304 $rows = 0;
1305 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1307 if ( $res ) {
1308 $row = $this->fetchRow( $res );
1309 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1312 return $rows;
1315 public function selectRowCount(
1316 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = array(), $join_conds = array()
1318 $rows = 0;
1319 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1320 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1322 if ( $res ) {
1323 $row = $this->fetchRow( $res );
1324 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1327 return $rows;
1331 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1332 * It's only slightly flawed. Don't use for anything important.
1334 * @param string $sql A SQL Query
1336 * @return string
1338 protected static function generalizeSQL( $sql ) {
1339 # This does the same as the regexp below would do, but in such a way
1340 # as to avoid crashing php on some large strings.
1341 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1343 $sql = str_replace( "\\\\", '', $sql );
1344 $sql = str_replace( "\\'", '', $sql );
1345 $sql = str_replace( "\\\"", '', $sql );
1346 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1347 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1349 # All newlines, tabs, etc replaced by single space
1350 $sql = preg_replace( '/\s+/', ' ', $sql );
1352 # All numbers => N,
1353 # except the ones surrounded by characters, e.g. l10n
1354 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1355 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1357 return $sql;
1360 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1361 $info = $this->fieldInfo( $table, $field );
1363 return (bool)$info;
1366 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1367 if ( !$this->tableExists( $table ) ) {
1368 return null;
1371 $info = $this->indexInfo( $table, $index, $fname );
1372 if ( is_null( $info ) ) {
1373 return null;
1374 } else {
1375 return $info !== false;
1379 public function tableExists( $table, $fname = __METHOD__ ) {
1380 $table = $this->tableName( $table );
1381 $old = $this->ignoreErrors( true );
1382 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1383 $this->ignoreErrors( $old );
1385 return (bool)$res;
1388 public function indexUnique( $table, $index ) {
1389 $indexInfo = $this->indexInfo( $table, $index );
1391 if ( !$indexInfo ) {
1392 return null;
1395 return !$indexInfo[0]->Non_unique;
1399 * Helper for DatabaseBase::insert().
1401 * @param array $options
1402 * @return string
1404 protected function makeInsertOptions( $options ) {
1405 return implode( ' ', $options );
1408 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1409 # No rows to insert, easy just return now
1410 if ( !count( $a ) ) {
1411 return true;
1414 $table = $this->tableName( $table );
1416 if ( !is_array( $options ) ) {
1417 $options = array( $options );
1420 $fh = null;
1421 if ( isset( $options['fileHandle'] ) ) {
1422 $fh = $options['fileHandle'];
1424 $options = $this->makeInsertOptions( $options );
1426 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1427 $multi = true;
1428 $keys = array_keys( $a[0] );
1429 } else {
1430 $multi = false;
1431 $keys = array_keys( $a );
1434 $sql = 'INSERT ' . $options .
1435 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1437 if ( $multi ) {
1438 $first = true;
1439 foreach ( $a as $row ) {
1440 if ( $first ) {
1441 $first = false;
1442 } else {
1443 $sql .= ',';
1445 $sql .= '(' . $this->makeList( $row ) . ')';
1447 } else {
1448 $sql .= '(' . $this->makeList( $a ) . ')';
1451 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1452 return false;
1453 } elseif ( $fh !== null ) {
1454 return true;
1457 return (bool)$this->query( $sql, $fname );
1461 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1463 * @param array $options
1464 * @return array
1466 protected function makeUpdateOptionsArray( $options ) {
1467 if ( !is_array( $options ) ) {
1468 $options = array( $options );
1471 $opts = array();
1473 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1474 $opts[] = $this->lowPriorityOption();
1477 if ( in_array( 'IGNORE', $options ) ) {
1478 $opts[] = 'IGNORE';
1481 return $opts;
1485 * Make UPDATE options for the DatabaseBase::update function
1487 * @param array $options The options passed to DatabaseBase::update
1488 * @return string
1490 protected function makeUpdateOptions( $options ) {
1491 $opts = $this->makeUpdateOptionsArray( $options );
1493 return implode( ' ', $opts );
1496 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
1497 $table = $this->tableName( $table );
1498 $opts = $this->makeUpdateOptions( $options );
1499 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1501 if ( $conds !== array() && $conds !== '*' ) {
1502 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1505 return $this->query( $sql, $fname );
1508 public function makeList( $a, $mode = LIST_COMMA ) {
1509 if ( !is_array( $a ) ) {
1510 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1513 $first = true;
1514 $list = '';
1516 foreach ( $a as $field => $value ) {
1517 if ( !$first ) {
1518 if ( $mode == LIST_AND ) {
1519 $list .= ' AND ';
1520 } elseif ( $mode == LIST_OR ) {
1521 $list .= ' OR ';
1522 } else {
1523 $list .= ',';
1525 } else {
1526 $first = false;
1529 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
1530 $list .= "($value)";
1531 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
1532 $list .= "$value";
1533 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
1534 // Remove null from array to be handled separately if found
1535 $includeNull = false;
1536 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1537 $includeNull = true;
1538 unset( $value[$nullKey] );
1540 if ( count( $value ) == 0 && !$includeNull ) {
1541 throw new MWException( __METHOD__ . ": empty input for field $field" );
1542 } elseif ( count( $value ) == 0 ) {
1543 // only check if $field is null
1544 $list .= "$field IS NULL";
1545 } else {
1546 // IN clause contains at least one valid element
1547 if ( $includeNull ) {
1548 // Group subconditions to ensure correct precedence
1549 $list .= '(';
1551 if ( count( $value ) == 1 ) {
1552 // Special-case single values, as IN isn't terribly efficient
1553 // Don't necessarily assume the single key is 0; we don't
1554 // enforce linear numeric ordering on other arrays here.
1555 $value = array_values( $value );
1556 $list .= $field . " = " . $this->addQuotes( $value[0] );
1557 } else {
1558 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1560 // if null present in array, append IS NULL
1561 if ( $includeNull ) {
1562 $list .= " OR $field IS NULL)";
1565 } elseif ( $value === null ) {
1566 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1567 $list .= "$field IS ";
1568 } elseif ( $mode == LIST_SET ) {
1569 $list .= "$field = ";
1571 $list .= 'NULL';
1572 } else {
1573 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1574 $list .= "$field = ";
1576 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1580 return $list;
1583 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1584 $conds = array();
1586 foreach ( $data as $base => $sub ) {
1587 if ( count( $sub ) ) {
1588 $conds[] = $this->makeList(
1589 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1590 LIST_AND );
1594 if ( $conds ) {
1595 return $this->makeList( $conds, LIST_OR );
1596 } else {
1597 // Nothing to search for...
1598 return false;
1603 * Return aggregated value alias
1605 * @param array $valuedata
1606 * @param string $valuename
1608 * @return string
1610 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1611 return $valuename;
1614 public function bitNot( $field ) {
1615 return "(~$field)";
1618 public function bitAnd( $fieldLeft, $fieldRight ) {
1619 return "($fieldLeft & $fieldRight)";
1622 public function bitOr( $fieldLeft, $fieldRight ) {
1623 return "($fieldLeft | $fieldRight)";
1626 public function buildConcat( $stringList ) {
1627 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1630 public function buildGroupConcatField(
1631 $delim, $table, $field, $conds = '', $join_conds = array()
1633 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1635 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1638 public function selectDB( $db ) {
1639 # Stub. Shouldn't cause serious problems if it's not overridden, but
1640 # if your database engine supports a concept similar to MySQL's
1641 # databases you may as well.
1642 $this->mDBname = $db;
1644 return true;
1647 public function getDBname() {
1648 return $this->mDBname;
1651 public function getServer() {
1652 return $this->mServer;
1656 * Format a table name ready for use in constructing an SQL query
1658 * This does two important things: it quotes the table names to clean them up,
1659 * and it adds a table prefix if only given a table name with no quotes.
1661 * All functions of this object which require a table name call this function
1662 * themselves. Pass the canonical name to such functions. This is only needed
1663 * when calling query() directly.
1665 * @param string $name Database table name
1666 * @param string $format One of:
1667 * quoted - Automatically pass the table name through addIdentifierQuotes()
1668 * so that it can be used in a query.
1669 * raw - Do not add identifier quotes to the table name
1670 * @return string Full database name
1672 public function tableName( $name, $format = 'quoted' ) {
1673 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1674 # Skip the entire process when we have a string quoted on both ends.
1675 # Note that we check the end so that we will still quote any use of
1676 # use of `database`.table. But won't break things if someone wants
1677 # to query a database table with a dot in the name.
1678 if ( $this->isQuotedIdentifier( $name ) ) {
1679 return $name;
1682 # Lets test for any bits of text that should never show up in a table
1683 # name. Basically anything like JOIN or ON which are actually part of
1684 # SQL queries, but may end up inside of the table value to combine
1685 # sql. Such as how the API is doing.
1686 # Note that we use a whitespace test rather than a \b test to avoid
1687 # any remote case where a word like on may be inside of a table name
1688 # surrounded by symbols which may be considered word breaks.
1689 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1690 return $name;
1693 # Split database and table into proper variables.
1694 # We reverse the explode so that database.table and table both output
1695 # the correct table.
1696 $dbDetails = explode( '.', $name, 3 );
1697 if ( count( $dbDetails ) == 3 ) {
1698 list( $database, $schema, $table ) = $dbDetails;
1699 # We don't want any prefix added in this case
1700 $prefix = '';
1701 } elseif ( count( $dbDetails ) == 2 ) {
1702 list( $database, $table ) = $dbDetails;
1703 # We don't want any prefix added in this case
1704 # In dbs that support it, $database may actually be the schema
1705 # but that doesn't affect any of the functionality here
1706 $prefix = '';
1707 $schema = null;
1708 } else {
1709 list( $table ) = $dbDetails;
1710 if ( $wgSharedDB !== null # We have a shared database
1711 && $this->mForeign == false # We're not working on a foreign database
1712 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1713 && in_array( $table, $wgSharedTables ) # A shared table is selected
1715 $database = $wgSharedDB;
1716 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
1717 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
1718 } else {
1719 $database = null;
1720 $schema = $this->mSchema; # Default schema
1721 $prefix = $this->mTablePrefix; # Default prefix
1725 # Quote $table and apply the prefix if not quoted.
1726 # $tableName might be empty if this is called from Database::replaceVars()
1727 $tableName = "{$prefix}{$table}";
1728 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1729 $tableName = $this->addIdentifierQuotes( $tableName );
1732 # Quote $schema and merge it with the table name if needed
1733 if ( strlen( $schema ) ) {
1734 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1735 $schema = $this->addIdentifierQuotes( $schema );
1737 $tableName = $schema . '.' . $tableName;
1740 # Quote $database and merge it with the table name if needed
1741 if ( $database !== null ) {
1742 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1743 $database = $this->addIdentifierQuotes( $database );
1745 $tableName = $database . '.' . $tableName;
1748 return $tableName;
1752 * Fetch a number of table names into an array
1753 * This is handy when you need to construct SQL for joins
1755 * Example:
1756 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1757 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1758 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1760 * @return array
1762 public function tableNames() {
1763 $inArray = func_get_args();
1764 $retVal = array();
1766 foreach ( $inArray as $name ) {
1767 $retVal[$name] = $this->tableName( $name );
1770 return $retVal;
1774 * Fetch a number of table names into an zero-indexed numerical array
1775 * This is handy when you need to construct SQL for joins
1777 * Example:
1778 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1779 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1780 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1782 * @return array
1784 public function tableNamesN() {
1785 $inArray = func_get_args();
1786 $retVal = array();
1788 foreach ( $inArray as $name ) {
1789 $retVal[] = $this->tableName( $name );
1792 return $retVal;
1796 * Get an aliased table name
1797 * e.g. tableName AS newTableName
1799 * @param string $name Table name, see tableName()
1800 * @param string|bool $alias Alias (optional)
1801 * @return string SQL name for aliased table. Will not alias a table to its own name
1803 public function tableNameWithAlias( $name, $alias = false ) {
1804 if ( !$alias || $alias == $name ) {
1805 return $this->tableName( $name );
1806 } else {
1807 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1812 * Gets an array of aliased table names
1814 * @param array $tables Array( [alias] => table )
1815 * @return string[] See tableNameWithAlias()
1817 public function tableNamesWithAlias( $tables ) {
1818 $retval = array();
1819 foreach ( $tables as $alias => $table ) {
1820 if ( is_numeric( $alias ) ) {
1821 $alias = $table;
1823 $retval[] = $this->tableNameWithAlias( $table, $alias );
1826 return $retval;
1830 * Get an aliased field name
1831 * e.g. fieldName AS newFieldName
1833 * @param string $name Field name
1834 * @param string|bool $alias Alias (optional)
1835 * @return string SQL name for aliased field. Will not alias a field to its own name
1837 public function fieldNameWithAlias( $name, $alias = false ) {
1838 if ( !$alias || (string)$alias === (string)$name ) {
1839 return $name;
1840 } else {
1841 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1846 * Gets an array of aliased field names
1848 * @param array $fields Array( [alias] => field )
1849 * @return string[] See fieldNameWithAlias()
1851 public function fieldNamesWithAlias( $fields ) {
1852 $retval = array();
1853 foreach ( $fields as $alias => $field ) {
1854 if ( is_numeric( $alias ) ) {
1855 $alias = $field;
1857 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1860 return $retval;
1864 * Get the aliased table name clause for a FROM clause
1865 * which might have a JOIN and/or USE INDEX clause
1867 * @param array $tables ( [alias] => table )
1868 * @param array $use_index Same as for select()
1869 * @param array $join_conds Same as for select()
1870 * @return string
1872 protected function tableNamesWithUseIndexOrJOIN(
1873 $tables, $use_index = array(), $join_conds = array()
1875 $ret = array();
1876 $retJOIN = array();
1877 $use_index = (array)$use_index;
1878 $join_conds = (array)$join_conds;
1880 foreach ( $tables as $alias => $table ) {
1881 if ( !is_string( $alias ) ) {
1882 // No alias? Set it equal to the table name
1883 $alias = $table;
1885 // Is there a JOIN clause for this table?
1886 if ( isset( $join_conds[$alias] ) ) {
1887 list( $joinType, $conds ) = $join_conds[$alias];
1888 $tableClause = $joinType;
1889 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1890 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1891 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1892 if ( $use != '' ) {
1893 $tableClause .= ' ' . $use;
1896 $on = $this->makeList( (array)$conds, LIST_AND );
1897 if ( $on != '' ) {
1898 $tableClause .= ' ON (' . $on . ')';
1901 $retJOIN[] = $tableClause;
1902 } elseif ( isset( $use_index[$alias] ) ) {
1903 // Is there an INDEX clause for this table?
1904 $tableClause = $this->tableNameWithAlias( $table, $alias );
1905 $tableClause .= ' ' . $this->useIndexClause(
1906 implode( ',', (array)$use_index[$alias] )
1909 $ret[] = $tableClause;
1910 } else {
1911 $tableClause = $this->tableNameWithAlias( $table, $alias );
1913 $ret[] = $tableClause;
1917 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1918 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1919 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1921 // Compile our final table clause
1922 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1926 * Get the name of an index in a given table.
1928 * @protected Don't use outside of DatabaseBase and childs
1929 * @param string $index
1930 * @return string
1932 public function indexName( $index ) {
1933 // @FIXME: Make this protected once we move away from PHP 5.3
1934 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
1936 // Backwards-compatibility hack
1937 $renamed = array(
1938 'ar_usertext_timestamp' => 'usertext_timestamp',
1939 'un_user_id' => 'user_id',
1940 'un_user_ip' => 'user_ip',
1943 if ( isset( $renamed[$index] ) ) {
1944 return $renamed[$index];
1945 } else {
1946 return $index;
1950 public function addQuotes( $s ) {
1951 if ( $s instanceof Blob ) {
1952 $s = $s->fetch();
1954 if ( $s === null ) {
1955 return 'NULL';
1956 } else {
1957 # This will also quote numeric values. This should be harmless,
1958 # and protects against weird problems that occur when they really
1959 # _are_ strings such as article titles and string->number->string
1960 # conversion is not 1:1.
1961 return "'" . $this->strencode( $s ) . "'";
1966 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1967 * MySQL uses `backticks` while basically everything else uses double quotes.
1968 * Since MySQL is the odd one out here the double quotes are our generic
1969 * and we implement backticks in DatabaseMysql.
1971 * @param string $s
1972 * @return string
1974 public function addIdentifierQuotes( $s ) {
1975 return '"' . str_replace( '"', '""', $s ) . '"';
1979 * Returns if the given identifier looks quoted or not according to
1980 * the database convention for quoting identifiers .
1982 * @param string $name
1983 * @return bool
1985 public function isQuotedIdentifier( $name ) {
1986 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1990 * @param string $s
1991 * @return string
1993 protected function escapeLikeInternal( $s ) {
1994 return addcslashes( $s, '\%_' );
1997 public function buildLike() {
1998 $params = func_get_args();
2000 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2001 $params = $params[0];
2004 $s = '';
2006 foreach ( $params as $value ) {
2007 if ( $value instanceof LikeMatch ) {
2008 $s .= $value->toString();
2009 } else {
2010 $s .= $this->escapeLikeInternal( $value );
2014 return " LIKE {$this->addQuotes( $s )} ";
2017 public function anyChar() {
2018 return new LikeMatch( '_' );
2021 public function anyString() {
2022 return new LikeMatch( '%' );
2025 public function nextSequenceValue( $seqName ) {
2026 return null;
2030 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2031 * is only needed because a) MySQL must be as efficient as possible due to
2032 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2033 * which index to pick. Anyway, other databases might have different
2034 * indexes on a given table. So don't bother overriding this unless you're
2035 * MySQL.
2036 * @param string $index
2037 * @return string
2039 public function useIndexClause( $index ) {
2040 return '';
2043 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2044 $quotedTable = $this->tableName( $table );
2046 if ( count( $rows ) == 0 ) {
2047 return;
2050 # Single row case
2051 if ( !is_array( reset( $rows ) ) ) {
2052 $rows = array( $rows );
2055 // @FXIME: this is not atomic, but a trx would break affectedRows()
2056 foreach ( $rows as $row ) {
2057 # Delete rows which collide
2058 if ( $uniqueIndexes ) {
2059 $sql = "DELETE FROM $quotedTable WHERE ";
2060 $first = true;
2061 foreach ( $uniqueIndexes as $index ) {
2062 if ( $first ) {
2063 $first = false;
2064 $sql .= '( ';
2065 } else {
2066 $sql .= ' ) OR ( ';
2068 if ( is_array( $index ) ) {
2069 $first2 = true;
2070 foreach ( $index as $col ) {
2071 if ( $first2 ) {
2072 $first2 = false;
2073 } else {
2074 $sql .= ' AND ';
2076 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2078 } else {
2079 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2082 $sql .= ' )';
2083 $this->query( $sql, $fname );
2086 # Now insert the row
2087 $this->insert( $table, $row, $fname );
2092 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2093 * statement.
2095 * @param string $table Table name
2096 * @param array|string $rows Row(s) to insert
2097 * @param string $fname Caller function name
2099 * @return ResultWrapper
2101 protected function nativeReplace( $table, $rows, $fname ) {
2102 $table = $this->tableName( $table );
2104 # Single row case
2105 if ( !is_array( reset( $rows ) ) ) {
2106 $rows = array( $rows );
2109 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2110 $first = true;
2112 foreach ( $rows as $row ) {
2113 if ( $first ) {
2114 $first = false;
2115 } else {
2116 $sql .= ',';
2119 $sql .= '(' . $this->makeList( $row ) . ')';
2122 return $this->query( $sql, $fname );
2125 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2126 $fname = __METHOD__
2128 if ( !count( $rows ) ) {
2129 return true; // nothing to do
2132 if ( !is_array( reset( $rows ) ) ) {
2133 $rows = array( $rows );
2136 if ( count( $uniqueIndexes ) ) {
2137 $clauses = array(); // list WHERE clauses that each identify a single row
2138 foreach ( $rows as $row ) {
2139 foreach ( $uniqueIndexes as $index ) {
2140 $index = is_array( $index ) ? $index : array( $index ); // columns
2141 $rowKey = array(); // unique key to this row
2142 foreach ( $index as $column ) {
2143 $rowKey[$column] = $row[$column];
2145 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2148 $where = array( $this->makeList( $clauses, LIST_OR ) );
2149 } else {
2150 $where = false;
2153 $useTrx = !$this->mTrxLevel;
2154 if ( $useTrx ) {
2155 $this->begin( $fname );
2157 try {
2158 # Update any existing conflicting row(s)
2159 if ( $where !== false ) {
2160 $ok = $this->update( $table, $set, $where, $fname );
2161 } else {
2162 $ok = true;
2164 # Now insert any non-conflicting row(s)
2165 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2166 } catch ( Exception $e ) {
2167 if ( $useTrx ) {
2168 $this->rollback( $fname );
2170 throw $e;
2172 if ( $useTrx ) {
2173 $this->commit( $fname );
2176 return $ok;
2179 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2180 $fname = __METHOD__
2182 if ( !$conds ) {
2183 throw new DBUnexpectedError( $this,
2184 'DatabaseBase::deleteJoin() called with empty $conds' );
2187 $delTable = $this->tableName( $delTable );
2188 $joinTable = $this->tableName( $joinTable );
2189 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2190 if ( $conds != '*' ) {
2191 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2193 $sql .= ')';
2195 $this->query( $sql, $fname );
2199 * Returns the size of a text field, or -1 for "unlimited"
2201 * @param string $table
2202 * @param string $field
2203 * @return int
2205 public function textFieldSize( $table, $field ) {
2206 $table = $this->tableName( $table );
2207 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2208 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2209 $row = $this->fetchObject( $res );
2211 $m = array();
2213 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2214 $size = $m[1];
2215 } else {
2216 $size = -1;
2219 return $size;
2223 * A string to insert into queries to show that they're low-priority, like
2224 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2225 * string and nothing bad should happen.
2227 * @return string Returns the text of the low priority option if it is
2228 * supported, or a blank string otherwise
2230 public function lowPriorityOption() {
2231 return '';
2234 public function delete( $table, $conds, $fname = __METHOD__ ) {
2235 if ( !$conds ) {
2236 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2239 $table = $this->tableName( $table );
2240 $sql = "DELETE FROM $table";
2242 if ( $conds != '*' ) {
2243 if ( is_array( $conds ) ) {
2244 $conds = $this->makeList( $conds, LIST_AND );
2246 $sql .= ' WHERE ' . $conds;
2249 return $this->query( $sql, $fname );
2252 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2253 $fname = __METHOD__,
2254 $insertOptions = array(), $selectOptions = array()
2256 $destTable = $this->tableName( $destTable );
2258 if ( !is_array( $insertOptions ) ) {
2259 $insertOptions = array( $insertOptions );
2262 $insertOptions = $this->makeInsertOptions( $insertOptions );
2264 if ( !is_array( $selectOptions ) ) {
2265 $selectOptions = array( $selectOptions );
2268 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2270 if ( is_array( $srcTable ) ) {
2271 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2272 } else {
2273 $srcTable = $this->tableName( $srcTable );
2276 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2277 " SELECT $startOpts " . implode( ',', $varMap ) .
2278 " FROM $srcTable $useIndex ";
2280 if ( $conds != '*' ) {
2281 if ( is_array( $conds ) ) {
2282 $conds = $this->makeList( $conds, LIST_AND );
2284 $sql .= " WHERE $conds";
2287 $sql .= " $tailOpts";
2289 return $this->query( $sql, $fname );
2293 * Construct a LIMIT query with optional offset. This is used for query
2294 * pages. The SQL should be adjusted so that only the first $limit rows
2295 * are returned. If $offset is provided as well, then the first $offset
2296 * rows should be discarded, and the next $limit rows should be returned.
2297 * If the result of the query is not ordered, then the rows to be returned
2298 * are theoretically arbitrary.
2300 * $sql is expected to be a SELECT, if that makes a difference.
2302 * The version provided by default works in MySQL and SQLite. It will very
2303 * likely need to be overridden for most other DBMSes.
2305 * @param string $sql SQL query we will append the limit too
2306 * @param int $limit The SQL limit
2307 * @param int|bool $offset The SQL offset (default false)
2308 * @throws DBUnexpectedError
2309 * @return string
2311 public function limitResult( $sql, $limit, $offset = false ) {
2312 if ( !is_numeric( $limit ) ) {
2313 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2316 return "$sql LIMIT "
2317 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2318 . "{$limit} ";
2321 public function unionSupportsOrderAndLimit() {
2322 return true; // True for almost every DB supported
2325 public function unionQueries( $sqls, $all ) {
2326 $glue = $all ? ') UNION ALL (' : ') UNION (';
2328 return '(' . implode( $glue, $sqls ) . ')';
2331 public function conditional( $cond, $trueVal, $falseVal ) {
2332 if ( is_array( $cond ) ) {
2333 $cond = $this->makeList( $cond, LIST_AND );
2336 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2339 public function strreplace( $orig, $old, $new ) {
2340 return "REPLACE({$orig}, {$old}, {$new})";
2343 public function getServerUptime() {
2344 return 0;
2347 public function wasDeadlock() {
2348 return false;
2351 public function wasLockTimeout() {
2352 return false;
2355 public function wasErrorReissuable() {
2356 return false;
2359 public function wasReadOnlyError() {
2360 return false;
2364 * Determines if the given query error was a connection drop
2365 * STUB
2367 * @param integer|string $errno
2368 * @return bool
2370 public function wasConnectionError( $errno ) {
2371 return false;
2375 * Perform a deadlock-prone transaction.
2377 * This function invokes a callback function to perform a set of write
2378 * queries. If a deadlock occurs during the processing, the transaction
2379 * will be rolled back and the callback function will be called again.
2381 * Usage:
2382 * $dbw->deadlockLoop( callback, ... );
2384 * Extra arguments are passed through to the specified callback function.
2386 * Returns whatever the callback function returned on its successful,
2387 * iteration, or false on error, for example if the retry limit was
2388 * reached.
2389 * @return mixed
2390 * @throws DBUnexpectedError
2391 * @throws Exception
2393 public function deadlockLoop() {
2394 $args = func_get_args();
2395 $function = array_shift( $args );
2396 $tries = self::DEADLOCK_TRIES;
2398 $this->begin( __METHOD__ );
2400 $retVal = null;
2401 /** @var Exception $e */
2402 $e = null;
2403 do {
2404 try {
2405 $retVal = call_user_func_array( $function, $args );
2406 break;
2407 } catch ( DBQueryError $e ) {
2408 if ( $this->wasDeadlock() ) {
2409 // Retry after a randomized delay
2410 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2411 } else {
2412 // Throw the error back up
2413 throw $e;
2416 } while ( --$tries > 0 );
2418 if ( $tries <= 0 ) {
2419 // Too many deadlocks; give up
2420 $this->rollback( __METHOD__ );
2421 throw $e;
2422 } else {
2423 $this->commit( __METHOD__ );
2425 return $retVal;
2429 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2430 # Real waits are implemented in the subclass.
2431 return 0;
2434 public function getSlavePos() {
2435 # Stub
2436 return false;
2439 public function getMasterPos() {
2440 # Stub
2441 return false;
2444 final public function onTransactionIdle( $callback ) {
2445 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
2446 if ( !$this->mTrxLevel ) {
2447 $this->runOnTransactionIdleCallbacks();
2451 final public function onTransactionPreCommitOrIdle( $callback ) {
2452 if ( $this->mTrxLevel ) {
2453 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
2454 } else {
2455 $this->onTransactionIdle( $callback ); // this will trigger immediately
2460 * Actually any "on transaction idle" callbacks.
2462 * @since 1.20
2464 protected function runOnTransactionIdleCallbacks() {
2465 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
2467 $e = $ePrior = null; // last exception
2468 do { // callbacks may add callbacks :)
2469 $callbacks = $this->mTrxIdleCallbacks;
2470 $this->mTrxIdleCallbacks = array(); // recursion guard
2471 foreach ( $callbacks as $callback ) {
2472 try {
2473 list( $phpCallback ) = $callback;
2474 $this->clearFlag( DBO_TRX ); // make each query its own transaction
2475 call_user_func( $phpCallback );
2476 if ( $autoTrx ) {
2477 $this->setFlag( DBO_TRX ); // restore automatic begin()
2478 } else {
2479 $this->clearFlag( DBO_TRX ); // restore auto-commit
2481 } catch ( Exception $e ) {
2482 if ( $ePrior ) {
2483 MWExceptionHandler::logException( $ePrior );
2485 $ePrior = $e;
2486 // Some callbacks may use startAtomic/endAtomic, so make sure
2487 // their transactions are ended so other callbacks don't fail
2488 if ( $this->trxLevel() ) {
2489 $this->rollback( __METHOD__ );
2493 } while ( count( $this->mTrxIdleCallbacks ) );
2495 if ( $e instanceof Exception ) {
2496 throw $e; // re-throw any last exception
2501 * Actually any "on transaction pre-commit" callbacks.
2503 * @since 1.22
2505 protected function runOnTransactionPreCommitCallbacks() {
2506 $e = $ePrior = null; // last exception
2507 do { // callbacks may add callbacks :)
2508 $callbacks = $this->mTrxPreCommitCallbacks;
2509 $this->mTrxPreCommitCallbacks = array(); // recursion guard
2510 foreach ( $callbacks as $callback ) {
2511 try {
2512 list( $phpCallback ) = $callback;
2513 call_user_func( $phpCallback );
2514 } catch ( Exception $e ) {
2515 if ( $ePrior ) {
2516 MWExceptionHandler::logException( $ePrior );
2518 $ePrior = $e;
2521 } while ( count( $this->mTrxPreCommitCallbacks ) );
2523 if ( $e instanceof Exception ) {
2524 throw $e; // re-throw any last exception
2528 final public function startAtomic( $fname = __METHOD__ ) {
2529 if ( !$this->mTrxLevel ) {
2530 $this->begin( $fname );
2531 $this->mTrxAutomatic = true;
2532 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2533 // in all changes being in one transaction to keep requests transactional.
2534 if ( !$this->getFlag( DBO_TRX ) ) {
2535 $this->mTrxAutomaticAtomic = true;
2539 $this->mTrxAtomicLevels[] = $fname;
2542 final public function endAtomic( $fname = __METHOD__ ) {
2543 if ( !$this->mTrxLevel ) {
2544 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2546 if ( !$this->mTrxAtomicLevels ||
2547 array_pop( $this->mTrxAtomicLevels ) !== $fname
2549 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2552 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2553 $this->commit( $fname, 'flush' );
2557 final public function doAtomicSection( $fname, $callback ) {
2558 if ( !is_callable( $callback ) ) {
2559 throw new UnexpectedValueException( "Invalid callback." );
2562 $this->startAtomic( $fname );
2563 try {
2564 call_user_func_array( $callback, array( $this, $fname ) );
2565 } catch ( Exception $e ) {
2566 $this->rollback( $fname );
2567 throw $e;
2569 $this->endAtomic( $fname );
2572 final public function begin( $fname = __METHOD__ ) {
2573 if ( $this->mTrxLevel ) { // implicit commit
2574 if ( $this->mTrxAtomicLevels ) {
2575 // If the current transaction was an automatic atomic one, then we definitely have
2576 // a problem. Same if there is any unclosed atomic level.
2577 $levels = implode( ', ', $this->mTrxAtomicLevels );
2578 throw new DBUnexpectedError(
2579 $this,
2580 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2582 } elseif ( !$this->mTrxAutomatic ) {
2583 // We want to warn about inadvertently nested begin/commit pairs, but not about
2584 // auto-committing implicit transactions that were started by query() via DBO_TRX
2585 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2586 " performing implicit commit!";
2587 wfWarn( $msg );
2588 wfLogDBError( $msg,
2589 $this->getLogContext( array(
2590 'method' => __METHOD__,
2591 'fname' => $fname,
2594 } else {
2595 // if the transaction was automatic and has done write operations
2596 if ( $this->mTrxDoneWrites ) {
2597 wfDebug( "$fname: Automatic transaction with writes in progress" .
2598 " (from {$this->mTrxFname}), performing implicit commit!\n"
2603 $this->runOnTransactionPreCommitCallbacks();
2604 $writeTime = $this->pendingWriteQueryDuration();
2605 $this->doCommit( $fname );
2606 if ( $this->mTrxDoneWrites ) {
2607 $this->mDoneWrites = microtime( true );
2608 $this->getTransactionProfiler()->transactionWritingOut(
2609 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2611 $this->runOnTransactionIdleCallbacks();
2614 # Avoid fatals if close() was called
2615 $this->assertOpen();
2617 $this->doBegin( $fname );
2618 $this->mTrxTimestamp = microtime( true );
2619 $this->mTrxFname = $fname;
2620 $this->mTrxDoneWrites = false;
2621 $this->mTrxAutomatic = false;
2622 $this->mTrxAutomaticAtomic = false;
2623 $this->mTrxAtomicLevels = array();
2624 $this->mTrxIdleCallbacks = array();
2625 $this->mTrxPreCommitCallbacks = array();
2626 $this->mTrxShortId = wfRandomString( 12 );
2627 $this->mTrxWriteDuration = 0.0;
2628 $this->mTrxWriteCallers = array();
2629 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2630 // Get an estimate of the slave lag before then, treating estimate staleness
2631 // as lag itself just to be safe
2632 $status = $this->getApproximateLagStatus();
2633 $this->mTrxSlaveLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2637 * Issues the BEGIN command to the database server.
2639 * @see DatabaseBase::begin()
2640 * @param string $fname
2642 protected function doBegin( $fname ) {
2643 $this->query( 'BEGIN', $fname );
2644 $this->mTrxLevel = 1;
2647 final public function commit( $fname = __METHOD__, $flush = '' ) {
2648 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2649 // There are still atomic sections open. This cannot be ignored
2650 $levels = implode( ', ', $this->mTrxAtomicLevels );
2651 throw new DBUnexpectedError(
2652 $this,
2653 "Got COMMIT while atomic sections $levels are still open"
2657 if ( $flush === 'flush' ) {
2658 if ( !$this->mTrxLevel ) {
2659 return; // nothing to do
2660 } elseif ( !$this->mTrxAutomatic ) {
2661 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
2663 } else {
2664 if ( !$this->mTrxLevel ) {
2665 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2666 return; // nothing to do
2667 } elseif ( $this->mTrxAutomatic ) {
2668 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2672 # Avoid fatals if close() was called
2673 $this->assertOpen();
2675 $this->runOnTransactionPreCommitCallbacks();
2676 $writeTime = $this->pendingWriteQueryDuration();
2677 $this->doCommit( $fname );
2678 if ( $this->mTrxDoneWrites ) {
2679 $this->mDoneWrites = microtime( true );
2680 $this->getTransactionProfiler()->transactionWritingOut(
2681 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2683 $this->runOnTransactionIdleCallbacks();
2687 * Issues the COMMIT command to the database server.
2689 * @see DatabaseBase::commit()
2690 * @param string $fname
2692 protected function doCommit( $fname ) {
2693 if ( $this->mTrxLevel ) {
2694 $this->query( 'COMMIT', $fname );
2695 $this->mTrxLevel = 0;
2699 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2700 if ( $flush !== 'flush' ) {
2701 if ( !$this->mTrxLevel ) {
2702 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2703 return; // nothing to do
2705 } else {
2706 if ( !$this->mTrxLevel ) {
2707 return; // nothing to do
2711 # Avoid fatals if close() was called
2712 $this->assertOpen();
2714 $this->doRollback( $fname );
2715 $this->mTrxIdleCallbacks = array(); // cancel
2716 $this->mTrxPreCommitCallbacks = array(); // cancel
2717 $this->mTrxAtomicLevels = array();
2718 if ( $this->mTrxDoneWrites ) {
2719 $this->getTransactionProfiler()->transactionWritingOut(
2720 $this->mServer, $this->mDBname, $this->mTrxShortId );
2725 * Issues the ROLLBACK command to the database server.
2727 * @see DatabaseBase::rollback()
2728 * @param string $fname
2730 protected function doRollback( $fname ) {
2731 if ( $this->mTrxLevel ) {
2732 $this->query( 'ROLLBACK', $fname, true );
2733 $this->mTrxLevel = 0;
2738 * Creates a new table with structure copied from existing table
2739 * Note that unlike most database abstraction functions, this function does not
2740 * automatically append database prefix, because it works at a lower
2741 * abstraction level.
2742 * The table names passed to this function shall not be quoted (this
2743 * function calls addIdentifierQuotes when needed).
2745 * @param string $oldName Name of table whose structure should be copied
2746 * @param string $newName Name of table to be created
2747 * @param bool $temporary Whether the new table should be temporary
2748 * @param string $fname Calling function name
2749 * @throws MWException
2750 * @return bool True if operation was successful
2752 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2753 $fname = __METHOD__
2755 throw new MWException(
2756 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2759 function listTables( $prefix = null, $fname = __METHOD__ ) {
2760 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2764 * Reset the views process cache set by listViews()
2765 * @since 1.22
2767 final public function clearViewsCache() {
2768 $this->allViews = null;
2772 * Lists all the VIEWs in the database
2774 * For caching purposes the list of all views should be stored in
2775 * $this->allViews. The process cache can be cleared with clearViewsCache()
2777 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2778 * @param string $fname Name of calling function
2779 * @throws MWException
2780 * @return array
2781 * @since 1.22
2783 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2784 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2788 * Differentiates between a TABLE and a VIEW
2790 * @param string $name Name of the database-structure to test.
2791 * @throws MWException
2792 * @return bool
2793 * @since 1.22
2795 public function isView( $name ) {
2796 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2799 public function timestamp( $ts = 0 ) {
2800 return wfTimestamp( TS_MW, $ts );
2803 public function timestampOrNull( $ts = null ) {
2804 if ( is_null( $ts ) ) {
2805 return null;
2806 } else {
2807 return $this->timestamp( $ts );
2812 * Take the result from a query, and wrap it in a ResultWrapper if
2813 * necessary. Boolean values are passed through as is, to indicate success
2814 * of write queries or failure.
2816 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2817 * resource, and it was necessary to call this function to convert it to
2818 * a wrapper. Nowadays, raw database objects are never exposed to external
2819 * callers, so this is unnecessary in external code.
2821 * @param bool|ResultWrapper|resource|object $result
2822 * @return bool|ResultWrapper
2824 protected function resultObject( $result ) {
2825 if ( !$result ) {
2826 return false;
2827 } elseif ( $result instanceof ResultWrapper ) {
2828 return $result;
2829 } elseif ( $result === true ) {
2830 // Successful write query
2831 return $result;
2832 } else {
2833 return new ResultWrapper( $this, $result );
2837 public function ping() {
2838 # Stub. Not essential to override.
2839 return true;
2842 public function getSessionLagStatus() {
2843 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2847 * Get the slave lag when the current transaction started
2849 * This is useful when transactions might use snapshot isolation
2850 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2851 * is this lag plus transaction duration. If they don't, it is still
2852 * safe to be pessimistic. This returns null if there is no transaction.
2854 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2855 * @since 1.27
2857 public function getTransactionLagStatus() {
2858 return $this->mTrxLevel
2859 ? array( 'lag' => $this->mTrxSlaveLag, 'since' => $this->trxTimestamp() )
2860 : null;
2864 * Get a slave lag estimate for this server
2866 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2867 * @since 1.27
2869 public function getApproximateLagStatus() {
2870 return array(
2871 'lag' => $this->getLBInfo( 'slave' ) ? $this->getLag() : 0,
2872 'since' => microtime( true )
2877 * Merge the result of getSessionLagStatus() for several DBs
2878 * using the most pessimistic values to estimate the lag of
2879 * any data derived from them in combination
2881 * This is information is useful for caching modules
2883 * @see WANObjectCache::set()
2884 * @see WANObjectCache::getWithSetCallback()
2886 * @param IDatabase $db1
2887 * @param IDatabase ...
2888 * @return array Map of values:
2889 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2890 * - since: oldest UNIX timestamp of any of the DB lag estimates
2891 * - pending: whether any of the DBs have uncommitted changes
2892 * @since 1.27
2894 public static function getCacheSetOptions( IDatabase $db1 ) {
2895 $res = array( 'lag' => 0, 'since' => INF, 'pending' => false );
2896 foreach ( func_get_args() as $db ) {
2897 /** @var IDatabase $db */
2898 $status = $db->getSessionLagStatus();
2899 if ( $status['lag'] === false ) {
2900 $res['lag'] = false;
2901 } elseif ( $res['lag'] !== false ) {
2902 $res['lag'] = max( $res['lag'], $status['lag'] );
2904 $res['since'] = min( $res['since'], $status['since'] );
2905 $res['pending'] = $res['pending'] ?: $db->writesPending();
2908 return $res;
2911 public function getLag() {
2912 return 0;
2915 function maxListLen() {
2916 return 0;
2919 public function encodeBlob( $b ) {
2920 return $b;
2923 public function decodeBlob( $b ) {
2924 if ( $b instanceof Blob ) {
2925 $b = $b->fetch();
2927 return $b;
2930 public function setSessionOptions( array $options ) {
2934 * Read and execute SQL commands from a file.
2936 * Returns true on success, error string or exception on failure (depending
2937 * on object's error ignore settings).
2939 * @param string $filename File name to open
2940 * @param bool|callable $lineCallback Optional function called before reading each line
2941 * @param bool|callable $resultCallback Optional function called for each MySQL result
2942 * @param bool|string $fname Calling function name or false if name should be
2943 * generated dynamically using $filename
2944 * @param bool|callable $inputCallback Optional function called for each
2945 * complete line sent
2946 * @throws Exception|MWException
2947 * @return bool|string
2949 public function sourceFile(
2950 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2952 MediaWiki\suppressWarnings();
2953 $fp = fopen( $filename, 'r' );
2954 MediaWiki\restoreWarnings();
2956 if ( false === $fp ) {
2957 throw new MWException( "Could not open \"{$filename}\".\n" );
2960 if ( !$fname ) {
2961 $fname = __METHOD__ . "( $filename )";
2964 try {
2965 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2966 } catch ( Exception $e ) {
2967 fclose( $fp );
2968 throw $e;
2971 fclose( $fp );
2973 return $error;
2977 * Get the full path of a patch file. Originally based on archive()
2978 * from updaters.inc. Keep in mind this always returns a patch, as
2979 * it fails back to MySQL if no DB-specific patch can be found
2981 * @param string $patch The name of the patch, like patch-something.sql
2982 * @return string Full path to patch file
2984 public function patchPath( $patch ) {
2985 global $IP;
2987 $dbType = $this->getType();
2988 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2989 return "$IP/maintenance/$dbType/archives/$patch";
2990 } else {
2991 return "$IP/maintenance/archives/$patch";
2995 public function setSchemaVars( $vars ) {
2996 $this->mSchemaVars = $vars;
3000 * Read and execute commands from an open file handle.
3002 * Returns true on success, error string or exception on failure (depending
3003 * on object's error ignore settings).
3005 * @param resource $fp File handle
3006 * @param bool|callable $lineCallback Optional function called before reading each query
3007 * @param bool|callable $resultCallback Optional function called for each MySQL result
3008 * @param string $fname Calling function name
3009 * @param bool|callable $inputCallback Optional function called for each complete query sent
3010 * @return bool|string
3012 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3013 $fname = __METHOD__, $inputCallback = false
3015 $cmd = '';
3017 while ( !feof( $fp ) ) {
3018 if ( $lineCallback ) {
3019 call_user_func( $lineCallback );
3022 $line = trim( fgets( $fp ) );
3024 if ( $line == '' ) {
3025 continue;
3028 if ( '-' == $line[0] && '-' == $line[1] ) {
3029 continue;
3032 if ( $cmd != '' ) {
3033 $cmd .= ' ';
3036 $done = $this->streamStatementEnd( $cmd, $line );
3038 $cmd .= "$line\n";
3040 if ( $done || feof( $fp ) ) {
3041 $cmd = $this->replaceVars( $cmd );
3043 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3044 $res = $this->query( $cmd, $fname );
3046 if ( $resultCallback ) {
3047 call_user_func( $resultCallback, $res, $this );
3050 if ( false === $res ) {
3051 $err = $this->lastError();
3053 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3056 $cmd = '';
3060 return true;
3064 * Called by sourceStream() to check if we've reached a statement end
3066 * @param string $sql SQL assembled so far
3067 * @param string $newLine New line about to be added to $sql
3068 * @return bool Whether $newLine contains end of the statement
3070 public function streamStatementEnd( &$sql, &$newLine ) {
3071 if ( $this->delimiter ) {
3072 $prev = $newLine;
3073 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3074 if ( $newLine != $prev ) {
3075 return true;
3079 return false;
3083 * Database independent variable replacement. Replaces a set of variables
3084 * in an SQL statement with their contents as given by $this->getSchemaVars().
3086 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3088 * - '{$var}' should be used for text and is passed through the database's
3089 * addQuotes method.
3090 * - `{$var}` should be used for identifiers (e.g. table and database names).
3091 * It is passed through the database's addIdentifierQuotes method which
3092 * can be overridden if the database uses something other than backticks.
3093 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3094 * database's tableName method.
3095 * - / *i* / passes the name that follows through the database's indexName method.
3096 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3097 * its use should be avoided. In 1.24 and older, string encoding was applied.
3099 * @param string $ins SQL statement to replace variables in
3100 * @return string The new SQL statement with variables replaced
3102 protected function replaceVars( $ins ) {
3103 $that = $this;
3104 $vars = $this->getSchemaVars();
3105 return preg_replace_callback(
3107 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3108 \'\{\$ (\w+) }\' | # 3. addQuotes
3109 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3110 /\*\$ (\w+) \*/ # 5. leave unencoded
3111 !x',
3112 function ( $m ) use ( $that, $vars ) {
3113 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3114 // check for both nonexistent keys *and* the empty string.
3115 if ( isset( $m[1] ) && $m[1] !== '' ) {
3116 if ( $m[1] === 'i' ) {
3117 return $that->indexName( $m[2] );
3118 } else {
3119 return $that->tableName( $m[2] );
3121 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3122 return $that->addQuotes( $vars[$m[3]] );
3123 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3124 return $that->addIdentifierQuotes( $vars[$m[4]] );
3125 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3126 return $vars[$m[5]];
3127 } else {
3128 return $m[0];
3131 $ins
3136 * Get schema variables. If none have been set via setSchemaVars(), then
3137 * use some defaults from the current object.
3139 * @return array
3141 protected function getSchemaVars() {
3142 if ( $this->mSchemaVars ) {
3143 return $this->mSchemaVars;
3144 } else {
3145 return $this->getDefaultSchemaVars();
3150 * Get schema variables to use if none have been set via setSchemaVars().
3152 * Override this in derived classes to provide variables for tables.sql
3153 * and SQL patch files.
3155 * @return array
3157 protected function getDefaultSchemaVars() {
3158 return array();
3161 public function lockIsFree( $lockName, $method ) {
3162 return true;
3165 public function lock( $lockName, $method, $timeout = 5 ) {
3166 $this->mNamedLocksHeld[$lockName] = 1;
3168 return true;
3171 public function unlock( $lockName, $method ) {
3172 unset( $this->mNamedLocksHeld[$lockName] );
3174 return true;
3177 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3178 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3179 return null;
3182 $that = $this;
3183 $unlocker = new ScopedCallback( function () use ( $that, $lockKey, $fname ) {
3184 $that->commit( __METHOD__, 'flush' );
3185 $that->unlock( $lockKey, $fname );
3186 } );
3188 $this->commit( __METHOD__, 'flush' );
3190 return $unlocker;
3193 public function namedLocksEnqueue() {
3194 return false;
3198 * Lock specific tables
3200 * @param array $read Array of tables to lock for read access
3201 * @param array $write Array of tables to lock for write access
3202 * @param string $method Name of caller
3203 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3204 * @return bool
3206 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3207 return true;
3211 * Unlock specific tables
3213 * @param string $method The caller
3214 * @return bool
3216 public function unlockTables( $method ) {
3217 return true;
3221 * Delete a table
3222 * @param string $tableName
3223 * @param string $fName
3224 * @return bool|ResultWrapper
3225 * @since 1.18
3227 public function dropTable( $tableName, $fName = __METHOD__ ) {
3228 if ( !$this->tableExists( $tableName, $fName ) ) {
3229 return false;
3231 $sql = "DROP TABLE " . $this->tableName( $tableName );
3232 if ( $this->cascadingDeletes() ) {
3233 $sql .= " CASCADE";
3236 return $this->query( $sql, $fName );
3240 * Get search engine class. All subclasses of this need to implement this
3241 * if they wish to use searching.
3243 * @return string
3245 public function getSearchEngine() {
3246 return 'SearchEngineDummy';
3249 public function getInfinity() {
3250 return 'infinity';
3253 public function encodeExpiry( $expiry ) {
3254 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3255 ? $this->getInfinity()
3256 : $this->timestamp( $expiry );
3259 public function decodeExpiry( $expiry, $format = TS_MW ) {
3260 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3261 ? 'infinity'
3262 : wfTimestamp( $format, $expiry );
3265 public function setBigSelects( $value = true ) {
3266 // no-op
3269 public function isReadOnly() {
3270 return ( $this->getReadOnlyReason() !== false );
3274 * @return string|bool Reason this DB is read-only or false if it is not
3276 protected function getReadOnlyReason() {
3277 $reason = $this->getLBInfo( 'readOnlyReason' );
3279 return is_string( $reason ) ? $reason : false;
3283 * @since 1.19
3284 * @return string
3286 public function __toString() {
3287 return (string)$this->mConn;
3291 * Run a few simple sanity checks
3293 public function __destruct() {
3294 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3295 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3297 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
3298 $callers = array();
3299 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
3300 $callers[] = $callbackInfo[1];
3302 $callers = implode( ', ', $callers );
3303 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3309 * @since 1.27
3311 abstract class Database extends DatabaseBase {
3312 // B/C until nothing type hints for DatabaseBase
3313 // @TODO: finish renaming DatabaseBase => Database