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
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
35 /** Minimum time to wait before retry, in microseconds */
36 const DEADLOCK_DELAY_MIN
= 500000;
37 /** Maximum time to wait before retry */
38 const DEADLOCK_DELAY_MAX
= 1500000;
40 /** How long before it is worth doing a dummy query to test the connection */
42 const PING_QUERY
= 'SELECT 1 AS ping';
44 const TINY_WRITE_SEC
= .010;
45 const SLOW_WRITE_SEC
= .500;
46 const SMALL_WRITE_ROWS
= 100;
48 /** @var string SQL query */
49 protected $mLastQuery = '';
51 protected $mDoneWrites = false;
52 /** @var string|bool */
53 protected $mPHPError = false;
65 /** @var BagOStuff APC cache */
68 /** @var resource Database connection */
69 protected $mConn = null;
71 protected $mOpened = false;
73 /** @var array[] List of (callable, method name) */
74 protected $mTrxIdleCallbacks = [];
75 /** @var array[] List of (callable, method name) */
76 protected $mTrxPreCommitCallbacks = [];
77 /** @var array[] List of (callable, method name) */
78 protected $mTrxEndCallbacks = [];
79 /** @var bool Whether to suppress triggering of post-commit callbacks */
80 protected $suppressPostCommitCallbacks = false;
83 protected $mTablePrefix;
91 protected $mLBInfo = [];
93 protected $mDefaultBigSelects = null;
94 /** @var array|bool */
95 protected $mSchemaVars = false;
97 protected $mSessionVars = [];
98 /** @var array|null */
99 protected $preparedArgs;
100 /** @var string|bool|null Stashed value of html_errors INI setting */
101 protected $htmlErrors;
103 protected $delimiter = ';';
106 * Either 1 if a transaction is active or 0 otherwise.
107 * The other Trx fields may not be meaningfull if this is 0.
111 protected $mTrxLevel = 0;
113 * Either a short hexidecimal string if a transaction is active or ""
116 * @see DatabaseBase::mTrxLevel
118 protected $mTrxShortId = '';
120 * The UNIX time that the transaction started. Callers can assume that if
121 * snapshot isolation is used, then the data is *at least* up to date to that
122 * point (possibly more up-to-date since the first SELECT defines the snapshot).
125 * @see DatabaseBase::mTrxLevel
127 private $mTrxTimestamp = null;
128 /** @var float Lag estimate at the time of BEGIN */
129 private $mTrxSlaveLag = null;
131 * Remembers the function name given for starting the most recent transaction via begin().
132 * Used to provide additional context for error reporting.
135 * @see DatabaseBase::mTrxLevel
137 private $mTrxFname = null;
139 * Record if possible write queries were done in the last transaction started
142 * @see DatabaseBase::mTrxLevel
144 private $mTrxDoneWrites = false;
146 * Record if the current transaction was started implicitly due to DBO_TRX being set.
149 * @see DatabaseBase::mTrxLevel
151 private $mTrxAutomatic = false;
153 * Array of levels of atomicity within transactions
157 private $mTrxAtomicLevels = [];
159 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
163 private $mTrxAutomaticAtomic = false;
165 * Track the write query callers of the current transaction
169 private $mTrxWriteCallers = [];
171 * @var float Seconds spent in write queries for the current transaction
173 private $mTrxWriteDuration = 0.0;
175 * @var integer Number of write queries for the current transaction
177 private $mTrxWriteQueryCount = 0;
179 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
181 private $mTrxWriteAdjDuration = 0.0;
183 * @var integer Number of write queries counted in mTrxWriteAdjDuration
185 private $mTrxWriteAdjQueryCount = 0;
187 * @var float RTT time estimate
189 private $mRTTEstimate = 0.0;
191 /** @var array Map of (name => 1) for locks obtained via lock() */
192 private $mNamedLocksHeld = [];
194 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
195 private $lazyMasterHandle;
199 * @var resource File handle for upgrade
201 protected $fileHandle = null;
205 * @var string[] Process cache of VIEWs names in the database
207 protected $allViews = null;
209 /** @var float UNIX timestamp */
210 protected $lastPing = 0.0;
212 /** @var int[] Prior mFlags values */
213 private $priorFlags = [];
217 /** @var TransactionProfiler */
218 protected $trxProfiler;
220 public function getServerInfo() {
221 return $this->getServerVersion();
225 * @return string Command delimiter used by this database engine
227 public function getDelimiter() {
228 return $this->delimiter
;
232 * Boolean, controls output of large amounts of debug information.
233 * @param bool|null $debug
234 * - true to enable debugging
235 * - false to disable debugging
236 * - omitted or null to do nothing
238 * @return bool|null Previous value of the flag
240 public function debug( $debug = null ) {
241 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
244 public function bufferResults( $buffer = null ) {
245 if ( is_null( $buffer ) ) {
246 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
248 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
253 * Turns on (false) or off (true) the automatic generation and sending
254 * of a "we're sorry, but there has been a database error" page on
255 * database errors. Default is on (false). When turned off, the
256 * code should use lastErrno() and lastError() to handle the
257 * situation as appropriate.
259 * Do not use this function outside of the Database classes.
261 * @param null|bool $ignoreErrors
262 * @return bool The previous value of the flag.
264 protected function ignoreErrors( $ignoreErrors = null ) {
265 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
268 public function trxLevel() {
269 return $this->mTrxLevel
;
272 public function trxTimestamp() {
273 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
276 public function tablePrefix( $prefix = null ) {
277 return wfSetVar( $this->mTablePrefix
, $prefix );
280 public function dbSchema( $schema = null ) {
281 return wfSetVar( $this->mSchema
, $schema );
285 * Set the filehandle to copy write statements to.
287 * @param resource $fh File handle
289 public function setFileHandle( $fh ) {
290 $this->fileHandle
= $fh;
293 public function getLBInfo( $name = null ) {
294 if ( is_null( $name ) ) {
295 return $this->mLBInfo
;
297 if ( array_key_exists( $name, $this->mLBInfo
) ) {
298 return $this->mLBInfo
[$name];
305 public function setLBInfo( $name, $value = null ) {
306 if ( is_null( $value ) ) {
307 $this->mLBInfo
= $name;
309 $this->mLBInfo
[$name] = $value;
314 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
316 * @param IDatabase $conn
319 public function setLazyMasterHandle( IDatabase
$conn ) {
320 $this->lazyMasterHandle
= $conn;
324 * @return IDatabase|null
325 * @see setLazyMasterHandle()
328 public function getLazyMasterHandle() {
329 return $this->lazyMasterHandle
;
333 * @return TransactionProfiler
335 protected function getTransactionProfiler() {
336 return $this->trxProfiler
;
340 * @param TransactionProfiler $profiler
343 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
344 $this->trxProfiler
= $profiler;
348 * Returns true if this database supports (and uses) cascading deletes
352 public function cascadingDeletes() {
357 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
361 public function cleanupTriggers() {
366 * Returns true if this database is strict about what can be put into an IP field.
367 * Specifically, it uses a NULL value instead of an empty string.
371 public function strictIPs() {
376 * Returns true if this database uses timestamps rather than integers
380 public function realTimestamps() {
384 public function implicitGroupby() {
388 public function implicitOrderby() {
393 * Returns true if this database can do a native search on IP columns
394 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
398 public function searchableIPs() {
403 * Returns true if this database can use functional indexes
407 public function functionalIndexes() {
411 public function lastQuery() {
412 return $this->mLastQuery
;
415 public function doneWrites() {
416 return (bool)$this->mDoneWrites
;
419 public function lastDoneWrites() {
420 return $this->mDoneWrites ?
: false;
423 public function writesPending() {
424 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
427 public function writesOrCallbacksPending() {
428 return $this->mTrxLevel
&& (
429 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
433 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
434 if ( !$this->mTrxLevel
) {
436 } elseif ( !$this->mTrxDoneWrites
) {
441 case self
::ESTIMATE_DB_APPLY
:
443 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
444 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
445 // For omitted queries, make them count as something at least
446 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
447 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
450 default: // everything
451 return $this->mTrxWriteDuration
;
455 public function pendingWriteCallers() {
456 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
459 public function isOpen() {
460 return $this->mOpened
;
463 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
464 if ( $remember === self
::REMEMBER_PRIOR
) {
465 array_push( $this->priorFlags
, $this->mFlags
);
467 $this->mFlags |
= $flag;
470 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
471 if ( $remember === self
::REMEMBER_PRIOR
) {
472 array_push( $this->priorFlags
, $this->mFlags
);
474 $this->mFlags
&= ~
$flag;
477 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
478 if ( !$this->priorFlags
) {
482 if ( $state === self
::RESTORE_INITIAL
) {
483 $this->mFlags
= reset( $this->priorFlags
);
484 $this->priorFlags
= [];
486 $this->mFlags
= array_pop( $this->priorFlags
);
490 public function getFlag( $flag ) {
491 return !!( $this->mFlags
& $flag );
494 public function getProperty( $name ) {
498 public function getWikiID() {
499 if ( $this->mTablePrefix
) {
500 return "{$this->mDBname}-{$this->mTablePrefix}";
502 return $this->mDBname
;
507 * Return a path to the DBMS-specific SQL file if it exists,
508 * otherwise default SQL file
510 * @param string $filename
513 private function getSqlFilePath( $filename ) {
515 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
516 if ( file_exists( $dbmsSpecificFilePath ) ) {
517 return $dbmsSpecificFilePath;
519 return "$IP/maintenance/$filename";
524 * Return a path to the DBMS-specific schema file,
525 * otherwise default to tables.sql
529 public function getSchemaPath() {
530 return $this->getSqlFilePath( 'tables.sql' );
534 * Return a path to the DBMS-specific update key file,
535 * otherwise default to update-keys.sql
539 public function getUpdateKeysPath() {
540 return $this->getSqlFilePath( 'update-keys.sql' );
544 * Get information about an index into an object
545 * @param string $table Table name
546 * @param string $index Index name
547 * @param string $fname Calling function name
548 * @return mixed Database-specific index description class or false if the index does not exist
550 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
553 * Wrapper for addslashes()
555 * @param string $s String to be slashed.
556 * @return string Slashed string.
558 abstract function strencode( $s );
563 * FIXME: It is possible to construct a Database object with no associated
564 * connection object, by specifying no parameters to __construct(). This
565 * feature is deprecated and should be removed.
567 * DatabaseBase subclasses should not be constructed directly in external
568 * code. DatabaseBase::factory() should be used instead.
570 * @param array $params Parameters passed from DatabaseBase::factory()
572 function __construct( array $params ) {
573 global $wgDBprefix, $wgDBmwschema;
575 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
577 $server = $params['host'];
578 $user = $params['user'];
579 $password = $params['password'];
580 $dbName = $params['dbname'];
581 $flags = $params['flags'];
582 $tablePrefix = $params['tablePrefix'];
583 $schema = $params['schema'];
584 $foreign = $params['foreign'];
586 $this->cliMode
= isset( $params['cliMode'] )
588 : ( PHP_SAPI
=== 'cli' );
590 $this->mFlags
= $flags;
591 if ( $this->mFlags
& DBO_DEFAULT
) {
592 if ( $this->cliMode
) {
593 $this->mFlags
&= ~DBO_TRX
;
595 $this->mFlags |
= DBO_TRX
;
599 $this->mSessionVars
= $params['variables'];
601 /** Get the default table prefix*/
602 if ( $tablePrefix === 'get from global' ) {
603 $this->mTablePrefix
= $wgDBprefix;
605 $this->mTablePrefix
= $tablePrefix;
608 /** Get the database schema*/
609 if ( $schema === 'get from global' ) {
610 $this->mSchema
= $wgDBmwschema;
612 $this->mSchema
= $schema;
615 $this->mForeign
= $foreign;
617 $this->profiler
= isset( $params['profiler'] )
618 ?
$params['profiler']
619 : Profiler
::instance(); // @TODO: remove global state
620 $this->trxProfiler
= isset( $params['trxProfiler'] )
621 ?
$params['trxProfiler']
622 : new TransactionProfiler();
625 $this->open( $server, $user, $password, $dbName );
631 * Called by serialize. Throw an exception when DB connection is serialized.
632 * This causes problems on some database engines because the connection is
633 * not restored on unserialize.
635 public function __sleep() {
636 throw new MWException( 'Database serialization may cause problems, since ' .
637 'the connection is not restored on wakeup.' );
641 * Given a DB type, construct the name of the appropriate child class of
642 * DatabaseBase. This is designed to replace all of the manual stuff like:
643 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
644 * as well as validate against the canonical list of DB types we have
646 * This factory function is mostly useful for when you need to connect to a
647 * database other than the MediaWiki default (such as for external auth,
648 * an extension, et cetera). Do not use this to connect to the MediaWiki
649 * database. Example uses in core:
650 * @see LoadBalancer::reallyOpenConnection()
651 * @see ForeignDBRepo::getMasterDB()
652 * @see WebInstallerDBConnect::execute()
656 * @param string $dbType A possible DB type
657 * @param array $p An array of options to pass to the constructor.
658 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
659 * @throws MWException If the database driver or extension cannot be found
660 * @return DatabaseBase|null DatabaseBase subclass or null
662 final public static function factory( $dbType, $p = [] ) {
663 global $wgCommandLineMode;
665 $canonicalDBTypes = [
666 'mysql' => [ 'mysqli', 'mysql' ],
674 $dbType = strtolower( $dbType );
675 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
676 $possibleDrivers = $canonicalDBTypes[$dbType];
677 if ( !empty( $p['driver'] ) ) {
678 if ( in_array( $p['driver'], $possibleDrivers ) ) {
679 $driver = $p['driver'];
681 throw new MWException( __METHOD__
.
682 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
685 foreach ( $possibleDrivers as $posDriver ) {
686 if ( extension_loaded( $posDriver ) ) {
687 $driver = $posDriver;
695 if ( $driver === false ) {
696 throw new MWException( __METHOD__
.
697 " no viable database extension found for type '$dbType'" );
700 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
701 // and everything else doesn't use a schema (e.g. null)
702 // Although postgres and oracle support schemas, we don't use them (yet)
703 // to maintain backwards compatibility
705 'mssql' => 'get from global',
708 $class = 'Database' . ucfirst( $driver );
709 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
710 // Resolve some defaults for b/c
711 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
712 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
713 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
714 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
715 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
716 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
717 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
718 if ( !isset( $p['schema'] ) ) {
719 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
721 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
722 $p['cliMode'] = $wgCommandLineMode;
724 return new $class( $p );
730 protected function installErrorHandler() {
731 $this->mPHPError
= false;
732 $this->htmlErrors
= ini_set( 'html_errors', '0' );
733 set_error_handler( [ $this, 'connectionErrorHandler' ] );
737 * @return bool|string
739 protected function restoreErrorHandler() {
740 restore_error_handler();
741 if ( $this->htmlErrors
!== false ) {
742 ini_set( 'html_errors', $this->htmlErrors
);
744 if ( $this->mPHPError
) {
745 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
746 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
756 * @param string $errstr
758 public function connectionErrorHandler( $errno, $errstr ) {
759 $this->mPHPError
= $errstr;
763 * Create a log context to pass to wfLogDBError or other logging functions.
765 * @param array $extras Additional data to add to context
768 protected function getLogContext( array $extras = [] ) {
771 'db_server' => $this->mServer
,
772 'db_name' => $this->mDBname
,
773 'db_user' => $this->mUser
,
779 public function close() {
780 if ( $this->mConn
) {
781 if ( $this->trxLevel() ) {
782 if ( !$this->mTrxAutomatic
) {
783 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
784 " performing implicit commit before closing connection!" );
787 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
790 $closed = $this->closeConnection();
791 $this->mConn
= false;
792 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
793 throw new MWException( "Transaction callbacks still pending." );
797 $this->mOpened
= false;
803 * Make sure isOpen() returns true as a sanity check
805 * @throws DBUnexpectedError
807 protected function assertOpen() {
808 if ( !$this->isOpen() ) {
809 throw new DBUnexpectedError( $this, "DB connection was already closed." );
814 * Closes underlying database connection
816 * @return bool Whether connection was closed successfully
818 abstract protected function closeConnection();
820 function reportConnectionError( $error = 'Unknown error' ) {
821 $myError = $this->lastError();
827 throw new DBConnectionError( $this, $error );
831 * The DBMS-dependent part of query()
833 * @param string $sql SQL query.
834 * @return ResultWrapper|bool Result object to feed to fetchObject,
835 * fetchRow, ...; or false on failure
837 abstract protected function doQuery( $sql );
840 * Determine whether a query writes to the DB.
841 * Should return true if unsure.
846 protected function isWriteQuery( $sql ) {
848 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
853 * @return string|null
855 protected function getQueryVerb( $sql ) {
856 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
860 * Determine whether a SQL statement is sensitive to isolation level.
861 * A SQL statement is considered transactable if its result could vary
862 * depending on the transaction isolation level. Operational commands
863 * such as 'SET' and 'SHOW' are not considered to be transactable.
868 protected function isTransactableQuery( $sql ) {
869 $verb = $this->getQueryVerb( $sql );
870 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
873 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
876 $priorWritesPending = $this->writesOrCallbacksPending();
877 $this->mLastQuery
= $sql;
879 $isWrite = $this->isWriteQuery( $sql );
881 $reason = $this->getReadOnlyReason();
882 if ( $reason !== false ) {
883 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
885 # Set a flag indicating that writes have been done
886 $this->mDoneWrites
= microtime( true );
889 # Add a comment for easy SHOW PROCESSLIST interpretation
890 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
891 $userName = $wgUser->getName();
892 if ( mb_strlen( $userName ) > 15 ) {
893 $userName = mb_substr( $userName, 0, 15 ) . '...';
895 $userName = str_replace( '/', '', $userName );
900 // Add trace comment to the begin of the sql string, right after the operator.
901 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
902 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
904 # Start implicit transactions that wrap the request if DBO_TRX is enabled
905 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
906 && $this->isTransactableQuery( $sql )
908 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
909 $this->mTrxAutomatic
= true;
912 # Keep track of whether the transaction has write queries pending
913 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
914 $this->mTrxDoneWrites
= true;
915 $this->getTransactionProfiler()->transactionWritingIn(
916 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
919 if ( $this->debug() ) {
920 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
923 # Avoid fatals if close() was called
926 # Send the query to the server
927 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
929 # Try reconnecting if the connection was lost
930 if ( false === $ret && $this->wasErrorReissuable() ) {
931 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
932 # Stash the last error values before anything might clear them
933 $lastError = $this->lastError();
934 $lastErrno = $this->lastErrno();
935 # Update state tracking to reflect transaction loss due to disconnection
936 $this->handleTransactionLoss();
937 wfDebug( "Connection lost, reconnecting...\n" );
938 if ( $this->reconnect() ) {
939 wfDebug( "Reconnected\n" );
940 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
941 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
943 if ( !$recoverable ) {
944 # Callers may catch the exception and continue to use the DB
945 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
947 # Should be safe to silently retry the query
948 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
951 wfDebug( "Failed\n" );
955 if ( false === $ret ) {
956 # Deadlocks cause the entire transaction to abort, not just the statement.
957 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
958 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
959 if ( $this->wasDeadlock() ) {
960 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
961 $tempIgnore = false; // not recoverable
963 # Update state tracking to reflect transaction loss
964 $this->handleTransactionLoss();
967 $this->reportQueryError(
968 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
971 $res = $this->resultObject( $ret );
976 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
977 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
978 # generalizeSQL() will probably cut down the query to reasonable
979 # logging size most of the time. The substr is really just a sanity check.
981 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
983 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
986 # Include query transaction state
987 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
989 $startTime = microtime( true );
990 $this->profiler
->profileIn( $queryProf );
991 $ret = $this->doQuery( $commentedSql );
992 $this->profiler
->profileOut( $queryProf );
993 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
995 unset( $queryProfSection ); // profile out (if set)
997 if ( $ret !== false ) {
998 $this->lastPing
= $startTime;
999 if ( $isWrite && $this->mTrxLevel
) {
1000 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1001 $this->mTrxWriteCallers
[] = $fname;
1005 if ( $sql === self
::PING_QUERY
) {
1006 $this->mRTTEstimate
= $queryRuntime;
1009 $this->getTransactionProfiler()->recordQueryCompletion(
1010 $queryProf, $startTime, $isWrite, $this->affectedRows()
1012 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
1018 * Update the estimated run-time of a query, not counting large row lock times
1020 * LoadBalancer can be set to rollback transactions that will create huge replication
1021 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1022 * queries, like inserting a row can take a long time due to row locking. This method
1023 * uses some simple heuristics to discount those cases.
1025 * @param string $sql A SQL write query
1026 * @param float $runtime Total runtime, including RTT
1028 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1029 $indicativeOfSlaveRuntime = true;
1030 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1031 $verb = $this->getQueryVerb( $sql );
1032 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1033 if ( $verb === 'INSERT' ) {
1034 $indicativeOfSlaveRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1035 } elseif ( $verb === 'REPLACE' ) {
1036 $indicativeOfSlaveRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1040 $this->mTrxWriteDuration +
= $runtime;
1041 $this->mTrxWriteQueryCount +
= 1;
1042 if ( $indicativeOfSlaveRuntime ) {
1043 $this->mTrxWriteAdjDuration +
= $runtime;
1044 $this->mTrxWriteAdjQueryCount +
= 1;
1048 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1049 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1050 # Dropped connections also mean that named locks are automatically released.
1051 # Only allow error suppression in autocommit mode or when the lost transaction
1052 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1053 if ( $this->mNamedLocksHeld
) {
1054 return false; // possible critical section violation
1055 } elseif ( $sql === 'COMMIT' ) {
1056 return !$priorWritesPending; // nothing written anyway? (T127428)
1057 } elseif ( $sql === 'ROLLBACK' ) {
1058 return true; // transaction lost...which is also what was requested :)
1059 } elseif ( $this->explicitTrxActive() ) {
1060 return false; // don't drop atomocity
1061 } elseif ( $priorWritesPending ) {
1062 return false; // prior writes lost from implicit transaction
1068 private function handleTransactionLoss() {
1069 $this->mTrxLevel
= 0;
1070 $this->mTrxIdleCallbacks
= []; // bug 65263
1071 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1073 // Handle callbacks in mTrxEndCallbacks
1074 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1076 } catch ( Exception
$e ) {
1077 // Already logged; move on...
1082 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1083 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1084 wfDebug( "SQL ERROR (ignored): $error\n" );
1086 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1088 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1089 $this->getLogContext( [
1090 'method' => __METHOD__
,
1093 'sql1line' => $sql1line,
1097 wfDebug( "SQL ERROR: " . $error . "\n" );
1098 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1103 * Intended to be compatible with the PEAR::DB wrapper functions.
1104 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1106 * ? = scalar value, quoted as necessary
1107 * ! = raw SQL bit (a function for instance)
1108 * & = filename; reads the file and inserts as a blob
1109 * (we don't use this though...)
1111 * @param string $sql
1112 * @param string $func
1116 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1117 /* MySQL doesn't support prepared statements (yet), so just
1118 * pack up the query for reference. We'll manually replace
1121 return [ 'query' => $sql, 'func' => $func ];
1125 * Free a prepared query, generated by prepare().
1126 * @param string $prepared
1128 protected function freePrepared( $prepared ) {
1129 /* No-op by default */
1133 * Execute a prepared query with the various arguments
1134 * @param string $prepared The prepared sql
1135 * @param mixed $args Either an array here, or put scalars as varargs
1137 * @return ResultWrapper
1139 public function execute( $prepared, $args = null ) {
1140 if ( !is_array( $args ) ) {
1142 $args = func_get_args();
1143 array_shift( $args );
1146 $sql = $this->fillPrepared( $prepared['query'], $args );
1148 return $this->query( $sql, $prepared['func'] );
1152 * For faking prepared SQL statements on DBs that don't support it directly.
1154 * @param string $preparedQuery A 'preparable' SQL statement
1155 * @param array $args Array of Arguments to fill it with
1156 * @return string Executable SQL
1158 public function fillPrepared( $preparedQuery, $args ) {
1160 $this->preparedArgs
=& $args;
1162 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1163 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1167 * preg_callback func for fillPrepared()
1168 * The arguments should be in $this->preparedArgs and must not be touched
1169 * while we're doing this.
1171 * @param array $matches
1172 * @throws DBUnexpectedError
1175 protected function fillPreparedArg( $matches ) {
1176 switch ( $matches[1] ) {
1185 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1187 switch ( $matches[1] ) {
1189 return $this->addQuotes( $arg );
1193 # return $this->addQuotes( file_get_contents( $arg ) );
1194 throw new DBUnexpectedError(
1196 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1199 throw new DBUnexpectedError(
1201 'Received invalid match. This should never happen!'
1206 public function freeResult( $res ) {
1209 public function selectField(
1210 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1212 if ( $var === '*' ) { // sanity
1213 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1216 if ( !is_array( $options ) ) {
1217 $options = [ $options ];
1220 $options['LIMIT'] = 1;
1222 $res = $this->select( $table, $var, $cond, $fname, $options );
1223 if ( $res === false ||
!$this->numRows( $res ) ) {
1227 $row = $this->fetchRow( $res );
1229 if ( $row !== false ) {
1230 return reset( $row );
1236 public function selectFieldValues(
1237 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1239 if ( $var === '*' ) { // sanity
1240 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1241 } elseif ( !is_string( $var ) ) { // sanity
1242 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1245 if ( !is_array( $options ) ) {
1246 $options = [ $options ];
1249 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1250 if ( $res === false ) {
1255 foreach ( $res as $row ) {
1256 $values[] = $row->$var;
1263 * Returns an optional USE INDEX clause to go after the table, and a
1264 * string to go at the end of the query.
1266 * @param array $options Associative array of options to be turned into
1267 * an SQL query, valid keys are listed in the function.
1269 * @see DatabaseBase::select()
1271 public function makeSelectOptions( $options ) {
1272 $preLimitTail = $postLimitTail = '';
1277 foreach ( $options as $key => $option ) {
1278 if ( is_numeric( $key ) ) {
1279 $noKeyOptions[$option] = true;
1283 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1285 $preLimitTail .= $this->makeOrderBy( $options );
1287 // if (isset($options['LIMIT'])) {
1288 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1289 // isset($options['OFFSET']) ? $options['OFFSET']
1293 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1294 $postLimitTail .= ' FOR UPDATE';
1297 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1298 $postLimitTail .= ' LOCK IN SHARE MODE';
1301 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1302 $startOpts .= 'DISTINCT';
1305 # Various MySQL extensions
1306 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1307 $startOpts .= ' /*! STRAIGHT_JOIN */';
1310 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1311 $startOpts .= ' HIGH_PRIORITY';
1314 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1315 $startOpts .= ' SQL_BIG_RESULT';
1318 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1319 $startOpts .= ' SQL_BUFFER_RESULT';
1322 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1323 $startOpts .= ' SQL_SMALL_RESULT';
1326 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1327 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1330 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1331 $startOpts .= ' SQL_CACHE';
1334 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1335 $startOpts .= ' SQL_NO_CACHE';
1338 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1339 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1344 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1348 * Returns an optional GROUP BY with an optional HAVING
1350 * @param array $options Associative array of options
1352 * @see DatabaseBase::select()
1355 public function makeGroupByWithHaving( $options ) {
1357 if ( isset( $options['GROUP BY'] ) ) {
1358 $gb = is_array( $options['GROUP BY'] )
1359 ?
implode( ',', $options['GROUP BY'] )
1360 : $options['GROUP BY'];
1361 $sql .= ' GROUP BY ' . $gb;
1363 if ( isset( $options['HAVING'] ) ) {
1364 $having = is_array( $options['HAVING'] )
1365 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1366 : $options['HAVING'];
1367 $sql .= ' HAVING ' . $having;
1374 * Returns an optional ORDER BY
1376 * @param array $options Associative array of options
1378 * @see DatabaseBase::select()
1381 public function makeOrderBy( $options ) {
1382 if ( isset( $options['ORDER BY'] ) ) {
1383 $ob = is_array( $options['ORDER BY'] )
1384 ?
implode( ',', $options['ORDER BY'] )
1385 : $options['ORDER BY'];
1387 return ' ORDER BY ' . $ob;
1393 // See IDatabase::select for the docs for this function
1394 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1395 $options = [], $join_conds = [] ) {
1396 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1398 return $this->query( $sql, $fname );
1401 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1402 $options = [], $join_conds = []
1404 if ( is_array( $vars ) ) {
1405 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1408 $options = (array)$options;
1409 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1410 ?
$options['USE INDEX']
1413 if ( is_array( $table ) ) {
1415 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1416 } elseif ( $table != '' ) {
1417 if ( $table[0] == ' ' ) {
1418 $from = ' FROM ' . $table;
1421 $this->tableNamesWithUseIndexOrJOIN( [ $table ], $useIndexes, [] );
1427 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1428 $this->makeSelectOptions( $options );
1430 if ( !empty( $conds ) ) {
1431 if ( is_array( $conds ) ) {
1432 $conds = $this->makeList( $conds, LIST_AND
);
1434 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1436 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1439 if ( isset( $options['LIMIT'] ) ) {
1440 $sql = $this->limitResult( $sql, $options['LIMIT'],
1441 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1443 $sql = "$sql $postLimitTail";
1445 if ( isset( $options['EXPLAIN'] ) ) {
1446 $sql = 'EXPLAIN ' . $sql;
1452 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1453 $options = [], $join_conds = []
1455 $options = (array)$options;
1456 $options['LIMIT'] = 1;
1457 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1459 if ( $res === false ) {
1463 if ( !$this->numRows( $res ) ) {
1467 $obj = $this->fetchObject( $res );
1472 public function estimateRowCount(
1473 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1476 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1479 $row = $this->fetchRow( $res );
1480 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1486 public function selectRowCount(
1487 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1490 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1491 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1494 $row = $this->fetchRow( $res );
1495 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1502 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1503 * It's only slightly flawed. Don't use for anything important.
1505 * @param string $sql A SQL Query
1509 protected static function generalizeSQL( $sql ) {
1510 # This does the same as the regexp below would do, but in such a way
1511 # as to avoid crashing php on some large strings.
1512 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1514 $sql = str_replace( "\\\\", '', $sql );
1515 $sql = str_replace( "\\'", '', $sql );
1516 $sql = str_replace( "\\\"", '', $sql );
1517 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1518 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1520 # All newlines, tabs, etc replaced by single space
1521 $sql = preg_replace( '/\s+/', ' ', $sql );
1524 # except the ones surrounded by characters, e.g. l10n
1525 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1526 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1531 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1532 $info = $this->fieldInfo( $table, $field );
1537 public function indexExists( $table, $index, $fname = __METHOD__
) {
1538 if ( !$this->tableExists( $table ) ) {
1542 $info = $this->indexInfo( $table, $index, $fname );
1543 if ( is_null( $info ) ) {
1546 return $info !== false;
1550 public function tableExists( $table, $fname = __METHOD__
) {
1551 $table = $this->tableName( $table );
1552 $old = $this->ignoreErrors( true );
1553 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1554 $this->ignoreErrors( $old );
1559 public function indexUnique( $table, $index ) {
1560 $indexInfo = $this->indexInfo( $table, $index );
1562 if ( !$indexInfo ) {
1566 return !$indexInfo[0]->Non_unique
;
1570 * Helper for DatabaseBase::insert().
1572 * @param array $options
1575 protected function makeInsertOptions( $options ) {
1576 return implode( ' ', $options );
1579 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1580 # No rows to insert, easy just return now
1581 if ( !count( $a ) ) {
1585 $table = $this->tableName( $table );
1587 if ( !is_array( $options ) ) {
1588 $options = [ $options ];
1592 if ( isset( $options['fileHandle'] ) ) {
1593 $fh = $options['fileHandle'];
1595 $options = $this->makeInsertOptions( $options );
1597 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1599 $keys = array_keys( $a[0] );
1602 $keys = array_keys( $a );
1605 $sql = 'INSERT ' . $options .
1606 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1610 foreach ( $a as $row ) {
1616 $sql .= '(' . $this->makeList( $row ) . ')';
1619 $sql .= '(' . $this->makeList( $a ) . ')';
1622 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1624 } elseif ( $fh !== null ) {
1628 return (bool)$this->query( $sql, $fname );
1632 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1634 * @param array $options
1637 protected function makeUpdateOptionsArray( $options ) {
1638 if ( !is_array( $options ) ) {
1639 $options = [ $options ];
1644 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1645 $opts[] = $this->lowPriorityOption();
1648 if ( in_array( 'IGNORE', $options ) ) {
1656 * Make UPDATE options for the DatabaseBase::update function
1658 * @param array $options The options passed to DatabaseBase::update
1661 protected function makeUpdateOptions( $options ) {
1662 $opts = $this->makeUpdateOptionsArray( $options );
1664 return implode( ' ', $opts );
1667 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1668 $table = $this->tableName( $table );
1669 $opts = $this->makeUpdateOptions( $options );
1670 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1672 if ( $conds !== [] && $conds !== '*' ) {
1673 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1676 return $this->query( $sql, $fname );
1679 public function makeList( $a, $mode = LIST_COMMA
) {
1680 if ( !is_array( $a ) ) {
1681 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1687 foreach ( $a as $field => $value ) {
1689 if ( $mode == LIST_AND
) {
1691 } elseif ( $mode == LIST_OR
) {
1700 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1701 $list .= "($value)";
1702 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1704 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1705 // Remove null from array to be handled separately if found
1706 $includeNull = false;
1707 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1708 $includeNull = true;
1709 unset( $value[$nullKey] );
1711 if ( count( $value ) == 0 && !$includeNull ) {
1712 throw new MWException( __METHOD__
. ": empty input for field $field" );
1713 } elseif ( count( $value ) == 0 ) {
1714 // only check if $field is null
1715 $list .= "$field IS NULL";
1717 // IN clause contains at least one valid element
1718 if ( $includeNull ) {
1719 // Group subconditions to ensure correct precedence
1722 if ( count( $value ) == 1 ) {
1723 // Special-case single values, as IN isn't terribly efficient
1724 // Don't necessarily assume the single key is 0; we don't
1725 // enforce linear numeric ordering on other arrays here.
1726 $value = array_values( $value )[0];
1727 $list .= $field . " = " . $this->addQuotes( $value );
1729 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1731 // if null present in array, append IS NULL
1732 if ( $includeNull ) {
1733 $list .= " OR $field IS NULL)";
1736 } elseif ( $value === null ) {
1737 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1738 $list .= "$field IS ";
1739 } elseif ( $mode == LIST_SET
) {
1740 $list .= "$field = ";
1744 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1745 $list .= "$field = ";
1747 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1754 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1757 foreach ( $data as $base => $sub ) {
1758 if ( count( $sub ) ) {
1759 $conds[] = $this->makeList(
1760 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1766 return $this->makeList( $conds, LIST_OR
);
1768 // Nothing to search for...
1774 * Return aggregated value alias
1776 * @param array $valuedata
1777 * @param string $valuename
1781 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1785 public function bitNot( $field ) {
1789 public function bitAnd( $fieldLeft, $fieldRight ) {
1790 return "($fieldLeft & $fieldRight)";
1793 public function bitOr( $fieldLeft, $fieldRight ) {
1794 return "($fieldLeft | $fieldRight)";
1797 public function buildConcat( $stringList ) {
1798 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1801 public function buildGroupConcatField(
1802 $delim, $table, $field, $conds = '', $join_conds = []
1804 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1806 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1809 public function selectDB( $db ) {
1810 # Stub. Shouldn't cause serious problems if it's not overridden, but
1811 # if your database engine supports a concept similar to MySQL's
1812 # databases you may as well.
1813 $this->mDBname
= $db;
1818 public function getDBname() {
1819 return $this->mDBname
;
1822 public function getServer() {
1823 return $this->mServer
;
1827 * Format a table name ready for use in constructing an SQL query
1829 * This does two important things: it quotes the table names to clean them up,
1830 * and it adds a table prefix if only given a table name with no quotes.
1832 * All functions of this object which require a table name call this function
1833 * themselves. Pass the canonical name to such functions. This is only needed
1834 * when calling query() directly.
1836 * @note This function does not sanitize user input. It is not safe to use
1837 * this function to escape user input.
1838 * @param string $name Database table name
1839 * @param string $format One of:
1840 * quoted - Automatically pass the table name through addIdentifierQuotes()
1841 * so that it can be used in a query.
1842 * raw - Do not add identifier quotes to the table name
1843 * @return string Full database name
1845 public function tableName( $name, $format = 'quoted' ) {
1846 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1847 # Skip the entire process when we have a string quoted on both ends.
1848 # Note that we check the end so that we will still quote any use of
1849 # use of `database`.table. But won't break things if someone wants
1850 # to query a database table with a dot in the name.
1851 if ( $this->isQuotedIdentifier( $name ) ) {
1855 # Lets test for any bits of text that should never show up in a table
1856 # name. Basically anything like JOIN or ON which are actually part of
1857 # SQL queries, but may end up inside of the table value to combine
1858 # sql. Such as how the API is doing.
1859 # Note that we use a whitespace test rather than a \b test to avoid
1860 # any remote case where a word like on may be inside of a table name
1861 # surrounded by symbols which may be considered word breaks.
1862 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1866 # Split database and table into proper variables.
1867 # We reverse the explode so that database.table and table both output
1868 # the correct table.
1869 $dbDetails = explode( '.', $name, 3 );
1870 if ( count( $dbDetails ) == 3 ) {
1871 list( $database, $schema, $table ) = $dbDetails;
1872 # We don't want any prefix added in this case
1874 } elseif ( count( $dbDetails ) == 2 ) {
1875 list( $database, $table ) = $dbDetails;
1876 # We don't want any prefix added in this case
1877 # In dbs that support it, $database may actually be the schema
1878 # but that doesn't affect any of the functionality here
1882 list( $table ) = $dbDetails;
1883 if ( $wgSharedDB !== null # We have a shared database
1884 && $this->mForeign
== false # We're not working on a foreign database
1885 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1886 && in_array( $table, $wgSharedTables ) # A shared table is selected
1888 $database = $wgSharedDB;
1889 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1890 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1893 $schema = $this->mSchema
; # Default schema
1894 $prefix = $this->mTablePrefix
; # Default prefix
1898 # Quote $table and apply the prefix if not quoted.
1899 # $tableName might be empty if this is called from Database::replaceVars()
1900 $tableName = "{$prefix}{$table}";
1901 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1902 $tableName = $this->addIdentifierQuotes( $tableName );
1905 # Quote $schema and merge it with the table name if needed
1906 if ( strlen( $schema ) ) {
1907 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1908 $schema = $this->addIdentifierQuotes( $schema );
1910 $tableName = $schema . '.' . $tableName;
1913 # Quote $database and merge it with the table name if needed
1914 if ( $database !== null ) {
1915 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1916 $database = $this->addIdentifierQuotes( $database );
1918 $tableName = $database . '.' . $tableName;
1925 * Fetch a number of table names into an array
1926 * This is handy when you need to construct SQL for joins
1929 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1930 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1931 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1935 public function tableNames() {
1936 $inArray = func_get_args();
1939 foreach ( $inArray as $name ) {
1940 $retVal[$name] = $this->tableName( $name );
1947 * Fetch a number of table names into an zero-indexed numerical array
1948 * This is handy when you need to construct SQL for joins
1951 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1952 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1953 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1957 public function tableNamesN() {
1958 $inArray = func_get_args();
1961 foreach ( $inArray as $name ) {
1962 $retVal[] = $this->tableName( $name );
1969 * Get an aliased table name
1970 * e.g. tableName AS newTableName
1972 * @param string $name Table name, see tableName()
1973 * @param string|bool $alias Alias (optional)
1974 * @return string SQL name for aliased table. Will not alias a table to its own name
1976 public function tableNameWithAlias( $name, $alias = false ) {
1977 if ( !$alias ||
$alias == $name ) {
1978 return $this->tableName( $name );
1980 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1985 * Gets an array of aliased table names
1987 * @param array $tables [ [alias] => table ]
1988 * @return string[] See tableNameWithAlias()
1990 public function tableNamesWithAlias( $tables ) {
1992 foreach ( $tables as $alias => $table ) {
1993 if ( is_numeric( $alias ) ) {
1996 $retval[] = $this->tableNameWithAlias( $table, $alias );
2003 * Get an aliased field name
2004 * e.g. fieldName AS newFieldName
2006 * @param string $name Field name
2007 * @param string|bool $alias Alias (optional)
2008 * @return string SQL name for aliased field. Will not alias a field to its own name
2010 public function fieldNameWithAlias( $name, $alias = false ) {
2011 if ( !$alias ||
(string)$alias === (string)$name ) {
2014 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2019 * Gets an array of aliased field names
2021 * @param array $fields [ [alias] => field ]
2022 * @return string[] See fieldNameWithAlias()
2024 public function fieldNamesWithAlias( $fields ) {
2026 foreach ( $fields as $alias => $field ) {
2027 if ( is_numeric( $alias ) ) {
2030 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2037 * Get the aliased table name clause for a FROM clause
2038 * which might have a JOIN and/or USE INDEX clause
2040 * @param array $tables ( [alias] => table )
2041 * @param array $use_index Same as for select()
2042 * @param array $join_conds Same as for select()
2045 protected function tableNamesWithUseIndexOrJOIN(
2046 $tables, $use_index = [], $join_conds = []
2050 $use_index = (array)$use_index;
2051 $join_conds = (array)$join_conds;
2053 foreach ( $tables as $alias => $table ) {
2054 if ( !is_string( $alias ) ) {
2055 // No alias? Set it equal to the table name
2058 // Is there a JOIN clause for this table?
2059 if ( isset( $join_conds[$alias] ) ) {
2060 list( $joinType, $conds ) = $join_conds[$alias];
2061 $tableClause = $joinType;
2062 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2063 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2064 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2066 $tableClause .= ' ' . $use;
2069 $on = $this->makeList( (array)$conds, LIST_AND
);
2071 $tableClause .= ' ON (' . $on . ')';
2074 $retJOIN[] = $tableClause;
2075 } elseif ( isset( $use_index[$alias] ) ) {
2076 // Is there an INDEX clause for this table?
2077 $tableClause = $this->tableNameWithAlias( $table, $alias );
2078 $tableClause .= ' ' . $this->useIndexClause(
2079 implode( ',', (array)$use_index[$alias] )
2082 $ret[] = $tableClause;
2084 $tableClause = $this->tableNameWithAlias( $table, $alias );
2086 $ret[] = $tableClause;
2090 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2091 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2092 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2094 // Compile our final table clause
2095 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2099 * Get the name of an index in a given table.
2101 * @param string $index
2104 protected function indexName( $index ) {
2105 // Backwards-compatibility hack
2107 'ar_usertext_timestamp' => 'usertext_timestamp',
2108 'un_user_id' => 'user_id',
2109 'un_user_ip' => 'user_ip',
2112 if ( isset( $renamed[$index] ) ) {
2113 return $renamed[$index];
2119 public function addQuotes( $s ) {
2120 if ( $s instanceof Blob
) {
2123 if ( $s === null ) {
2126 # This will also quote numeric values. This should be harmless,
2127 # and protects against weird problems that occur when they really
2128 # _are_ strings such as article titles and string->number->string
2129 # conversion is not 1:1.
2130 return "'" . $this->strencode( $s ) . "'";
2135 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2136 * MySQL uses `backticks` while basically everything else uses double quotes.
2137 * Since MySQL is the odd one out here the double quotes are our generic
2138 * and we implement backticks in DatabaseMysql.
2143 public function addIdentifierQuotes( $s ) {
2144 return '"' . str_replace( '"', '""', $s ) . '"';
2148 * Returns if the given identifier looks quoted or not according to
2149 * the database convention for quoting identifiers .
2151 * @note Do not use this to determine if untrusted input is safe.
2152 * A malicious user can trick this function.
2153 * @param string $name
2156 public function isQuotedIdentifier( $name ) {
2157 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2164 protected function escapeLikeInternal( $s ) {
2165 return addcslashes( $s, '\%_' );
2168 public function buildLike() {
2169 $params = func_get_args();
2171 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2172 $params = $params[0];
2177 foreach ( $params as $value ) {
2178 if ( $value instanceof LikeMatch
) {
2179 $s .= $value->toString();
2181 $s .= $this->escapeLikeInternal( $value );
2185 return " LIKE {$this->addQuotes( $s )} ";
2188 public function anyChar() {
2189 return new LikeMatch( '_' );
2192 public function anyString() {
2193 return new LikeMatch( '%' );
2196 public function nextSequenceValue( $seqName ) {
2201 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2202 * is only needed because a) MySQL must be as efficient as possible due to
2203 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2204 * which index to pick. Anyway, other databases might have different
2205 * indexes on a given table. So don't bother overriding this unless you're
2207 * @param string $index
2210 public function useIndexClause( $index ) {
2214 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2215 $quotedTable = $this->tableName( $table );
2217 if ( count( $rows ) == 0 ) {
2222 if ( !is_array( reset( $rows ) ) ) {
2226 // @FXIME: this is not atomic, but a trx would break affectedRows()
2227 foreach ( $rows as $row ) {
2228 # Delete rows which collide
2229 if ( $uniqueIndexes ) {
2230 $sql = "DELETE FROM $quotedTable WHERE ";
2232 foreach ( $uniqueIndexes as $index ) {
2239 if ( is_array( $index ) ) {
2241 foreach ( $index as $col ) {
2247 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2250 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2254 $this->query( $sql, $fname );
2257 # Now insert the row
2258 $this->insert( $table, $row, $fname );
2263 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2266 * @param string $table Table name
2267 * @param array|string $rows Row(s) to insert
2268 * @param string $fname Caller function name
2270 * @return ResultWrapper
2272 protected function nativeReplace( $table, $rows, $fname ) {
2273 $table = $this->tableName( $table );
2276 if ( !is_array( reset( $rows ) ) ) {
2280 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2283 foreach ( $rows as $row ) {
2290 $sql .= '(' . $this->makeList( $row ) . ')';
2293 return $this->query( $sql, $fname );
2296 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2299 if ( !count( $rows ) ) {
2300 return true; // nothing to do
2303 if ( !is_array( reset( $rows ) ) ) {
2307 if ( count( $uniqueIndexes ) ) {
2308 $clauses = []; // list WHERE clauses that each identify a single row
2309 foreach ( $rows as $row ) {
2310 foreach ( $uniqueIndexes as $index ) {
2311 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2312 $rowKey = []; // unique key to this row
2313 foreach ( $index as $column ) {
2314 $rowKey[$column] = $row[$column];
2316 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2319 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2324 $useTrx = !$this->mTrxLevel
;
2326 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2329 # Update any existing conflicting row(s)
2330 if ( $where !== false ) {
2331 $ok = $this->update( $table, $set, $where, $fname );
2335 # Now insert any non-conflicting row(s)
2336 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2337 } catch ( Exception
$e ) {
2339 $this->rollback( $fname );
2344 $this->commit( $fname, self
::TRANSACTION_INTERNAL
);
2350 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2354 throw new DBUnexpectedError( $this,
2355 'DatabaseBase::deleteJoin() called with empty $conds' );
2358 $delTable = $this->tableName( $delTable );
2359 $joinTable = $this->tableName( $joinTable );
2360 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2361 if ( $conds != '*' ) {
2362 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2366 $this->query( $sql, $fname );
2370 * Returns the size of a text field, or -1 for "unlimited"
2372 * @param string $table
2373 * @param string $field
2376 public function textFieldSize( $table, $field ) {
2377 $table = $this->tableName( $table );
2378 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2379 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2380 $row = $this->fetchObject( $res );
2384 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2394 * A string to insert into queries to show that they're low-priority, like
2395 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2396 * string and nothing bad should happen.
2398 * @return string Returns the text of the low priority option if it is
2399 * supported, or a blank string otherwise
2401 public function lowPriorityOption() {
2405 public function delete( $table, $conds, $fname = __METHOD__
) {
2407 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2410 $table = $this->tableName( $table );
2411 $sql = "DELETE FROM $table";
2413 if ( $conds != '*' ) {
2414 if ( is_array( $conds ) ) {
2415 $conds = $this->makeList( $conds, LIST_AND
);
2417 $sql .= ' WHERE ' . $conds;
2420 return $this->query( $sql, $fname );
2423 public function insertSelect(
2424 $destTable, $srcTable, $varMap, $conds,
2425 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2427 if ( $this->cliMode
) {
2428 // For massive migrations with downtime, we don't want to select everything
2429 // into memory and OOM, so do all this native on the server side if possible.
2430 return $this->nativeInsertSelect(
2441 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2442 // on only the master (without needing row-based-replication). It also makes it easy to
2443 // know how big the INSERT is going to be.
2445 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2446 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2448 $selectOptions[] = 'FOR UPDATE';
2449 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2455 foreach ( $res as $row ) {
2456 $rows[] = (array)$row;
2459 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2462 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2463 $fname = __METHOD__
,
2464 $insertOptions = [], $selectOptions = []
2466 $destTable = $this->tableName( $destTable );
2468 if ( !is_array( $insertOptions ) ) {
2469 $insertOptions = [ $insertOptions ];
2472 $insertOptions = $this->makeInsertOptions( $insertOptions );
2474 if ( !is_array( $selectOptions ) ) {
2475 $selectOptions = [ $selectOptions ];
2478 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2480 if ( is_array( $srcTable ) ) {
2481 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2483 $srcTable = $this->tableName( $srcTable );
2486 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2487 " SELECT $startOpts " . implode( ',', $varMap ) .
2488 " FROM $srcTable $useIndex ";
2490 if ( $conds != '*' ) {
2491 if ( is_array( $conds ) ) {
2492 $conds = $this->makeList( $conds, LIST_AND
);
2494 $sql .= " WHERE $conds";
2497 $sql .= " $tailOpts";
2499 return $this->query( $sql, $fname );
2503 * Construct a LIMIT query with optional offset. This is used for query
2504 * pages. The SQL should be adjusted so that only the first $limit rows
2505 * are returned. If $offset is provided as well, then the first $offset
2506 * rows should be discarded, and the next $limit rows should be returned.
2507 * If the result of the query is not ordered, then the rows to be returned
2508 * are theoretically arbitrary.
2510 * $sql is expected to be a SELECT, if that makes a difference.
2512 * The version provided by default works in MySQL and SQLite. It will very
2513 * likely need to be overridden for most other DBMSes.
2515 * @param string $sql SQL query we will append the limit too
2516 * @param int $limit The SQL limit
2517 * @param int|bool $offset The SQL offset (default false)
2518 * @throws DBUnexpectedError
2521 public function limitResult( $sql, $limit, $offset = false ) {
2522 if ( !is_numeric( $limit ) ) {
2523 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2526 return "$sql LIMIT "
2527 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2531 public function unionSupportsOrderAndLimit() {
2532 return true; // True for almost every DB supported
2535 public function unionQueries( $sqls, $all ) {
2536 $glue = $all ?
') UNION ALL (' : ') UNION (';
2538 return '(' . implode( $glue, $sqls ) . ')';
2541 public function conditional( $cond, $trueVal, $falseVal ) {
2542 if ( is_array( $cond ) ) {
2543 $cond = $this->makeList( $cond, LIST_AND
);
2546 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2549 public function strreplace( $orig, $old, $new ) {
2550 return "REPLACE({$orig}, {$old}, {$new})";
2553 public function getServerUptime() {
2557 public function wasDeadlock() {
2561 public function wasLockTimeout() {
2565 public function wasErrorReissuable() {
2569 public function wasReadOnlyError() {
2574 * Determines if the given query error was a connection drop
2577 * @param integer|string $errno
2580 public function wasConnectionError( $errno ) {
2585 * Perform a deadlock-prone transaction.
2587 * This function invokes a callback function to perform a set of write
2588 * queries. If a deadlock occurs during the processing, the transaction
2589 * will be rolled back and the callback function will be called again.
2591 * Avoid using this method outside of Job or Maintenance classes.
2594 * $dbw->deadlockLoop( callback, ... );
2596 * Extra arguments are passed through to the specified callback function.
2597 * This method requires that no transactions are already active to avoid
2598 * causing premature commits or exceptions.
2600 * Returns whatever the callback function returned on its successful,
2601 * iteration, or false on error, for example if the retry limit was
2605 * @throws DBUnexpectedError
2608 public function deadlockLoop() {
2609 $args = func_get_args();
2610 $function = array_shift( $args );
2611 $tries = self
::DEADLOCK_TRIES
;
2613 $this->begin( __METHOD__
);
2616 /** @var Exception $e */
2620 $retVal = call_user_func_array( $function, $args );
2622 } catch ( DBQueryError
$e ) {
2623 if ( $this->wasDeadlock() ) {
2624 // Retry after a randomized delay
2625 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2627 // Throw the error back up
2631 } while ( --$tries > 0 );
2633 if ( $tries <= 0 ) {
2634 // Too many deadlocks; give up
2635 $this->rollback( __METHOD__
);
2638 $this->commit( __METHOD__
);
2644 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2645 # Real waits are implemented in the subclass.
2649 public function getSlavePos() {
2654 public function getMasterPos() {
2659 public function serverIsReadOnly() {
2663 final public function onTransactionResolution( callable
$callback ) {
2664 if ( !$this->mTrxLevel
) {
2665 throw new DBUnexpectedError( $this, "No transaction is active." );
2667 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2670 final public function onTransactionIdle( callable
$callback ) {
2671 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2672 if ( !$this->mTrxLevel
) {
2673 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2677 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2678 if ( $this->mTrxLevel
) {
2679 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2681 // If no transaction is active, then make one for this callback
2682 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
2684 call_user_func( $callback );
2685 $this->commit( __METHOD__
);
2686 } catch ( Exception
$e ) {
2687 $this->rollback( __METHOD__
);
2694 * Whether to disable running of post-commit callbacks
2696 * This method should not be used outside of Database/LoadBalancer
2698 * @param bool $suppress
2701 final public function setPostCommitCallbackSupression( $suppress ) {
2702 $this->suppressPostCommitCallbacks
= $suppress;
2706 * Actually run and consume any "on transaction idle/resolution" callbacks.
2708 * This method should not be used outside of Database/LoadBalancer
2710 * @param integer $trigger IDatabase::TRIGGER_* constant
2714 public function runOnTransactionIdleCallbacks( $trigger ) {
2715 if ( $this->suppressPostCommitCallbacks
) {
2719 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2720 /** @var Exception $e */
2721 $e = null; // first exception
2722 do { // callbacks may add callbacks :)
2723 $callbacks = array_merge(
2724 $this->mTrxIdleCallbacks
,
2725 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2727 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2728 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2729 foreach ( $callbacks as $callback ) {
2731 list( $phpCallback ) = $callback;
2732 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2733 call_user_func_array( $phpCallback, [ $trigger ] );
2735 $this->setFlag( DBO_TRX
); // restore automatic begin()
2737 $this->clearFlag( DBO_TRX
); // restore auto-commit
2739 } catch ( Exception
$ex ) {
2740 MWExceptionHandler
::logException( $ex );
2742 // Some callbacks may use startAtomic/endAtomic, so make sure
2743 // their transactions are ended so other callbacks don't fail
2744 if ( $this->trxLevel() ) {
2745 $this->rollback( __METHOD__
);
2749 } while ( count( $this->mTrxIdleCallbacks
) );
2751 if ( $e instanceof Exception
) {
2752 throw $e; // re-throw any first exception
2757 * Actually run and consume any "on transaction pre-commit" callbacks.
2759 * This method should not be used outside of Database/LoadBalancer
2764 public function runOnTransactionPreCommitCallbacks() {
2765 $e = null; // first exception
2766 do { // callbacks may add callbacks :)
2767 $callbacks = $this->mTrxPreCommitCallbacks
;
2768 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2769 foreach ( $callbacks as $callback ) {
2771 list( $phpCallback ) = $callback;
2772 call_user_func( $phpCallback );
2773 } catch ( Exception
$ex ) {
2774 MWExceptionHandler
::logException( $ex );
2778 } while ( count( $this->mTrxPreCommitCallbacks
) );
2780 if ( $e instanceof Exception
) {
2781 throw $e; // re-throw any first exception
2785 final public function startAtomic( $fname = __METHOD__
) {
2786 if ( !$this->mTrxLevel
) {
2787 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2788 $this->mTrxAutomatic
= true;
2789 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2790 // in all changes being in one transaction to keep requests transactional.
2791 if ( !$this->getFlag( DBO_TRX
) ) {
2792 $this->mTrxAutomaticAtomic
= true;
2796 $this->mTrxAtomicLevels
[] = $fname;
2799 final public function endAtomic( $fname = __METHOD__
) {
2800 if ( !$this->mTrxLevel
) {
2801 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2803 if ( !$this->mTrxAtomicLevels ||
2804 array_pop( $this->mTrxAtomicLevels
) !== $fname
2806 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2809 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2810 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2814 final public function doAtomicSection( $fname, callable
$callback ) {
2815 $this->startAtomic( $fname );
2817 $res = call_user_func_array( $callback, [ $this, $fname ] );
2818 } catch ( Exception
$e ) {
2819 $this->rollback( $fname );
2822 $this->endAtomic( $fname );
2827 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2828 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2829 if ( $this->mTrxLevel
) {
2830 if ( $this->mTrxAtomicLevels
) {
2831 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2832 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2833 throw new DBUnexpectedError( $this, $msg );
2834 } elseif ( !$this->mTrxAutomatic
) {
2835 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2836 throw new DBUnexpectedError( $this, $msg );
2838 // @TODO: make this an exception at some point
2839 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2840 wfLogDBError( $msg );
2841 return; // join the main transaction set
2843 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2844 // @TODO: make this an exception at some point
2845 wfLogDBError( "$fname: Implicit transaction expected (DBO_TRX set)." );
2846 return; // let any writes be in the main transaction
2849 // Avoid fatals if close() was called
2850 $this->assertOpen();
2852 $this->doBegin( $fname );
2853 $this->mTrxTimestamp
= microtime( true );
2854 $this->mTrxFname
= $fname;
2855 $this->mTrxDoneWrites
= false;
2856 $this->mTrxAutomatic
= false;
2857 $this->mTrxAutomaticAtomic
= false;
2858 $this->mTrxAtomicLevels
= [];
2859 $this->mTrxShortId
= wfRandomString( 12 );
2860 $this->mTrxWriteDuration
= 0.0;
2861 $this->mTrxWriteQueryCount
= 0;
2862 $this->mTrxWriteAdjDuration
= 0.0;
2863 $this->mTrxWriteAdjQueryCount
= 0;
2864 $this->mTrxWriteCallers
= [];
2865 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2866 // Get an estimate of the slave lag before then, treating estimate staleness
2867 // as lag itself just to be safe
2868 $status = $this->getApproximateLagStatus();
2869 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2873 * Issues the BEGIN command to the database server.
2875 * @see DatabaseBase::begin()
2876 * @param string $fname
2878 protected function doBegin( $fname ) {
2879 $this->query( 'BEGIN', $fname );
2880 $this->mTrxLevel
= 1;
2883 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2884 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2885 // There are still atomic sections open. This cannot be ignored
2886 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2887 throw new DBUnexpectedError(
2889 "$fname: Got COMMIT while atomic sections $levels are still open."
2893 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2894 if ( !$this->mTrxLevel
) {
2895 return; // nothing to do
2896 } elseif ( !$this->mTrxAutomatic
) {
2897 throw new DBUnexpectedError(
2899 "$fname: Flushing an explicit transaction, getting out of sync."
2903 if ( !$this->mTrxLevel
) {
2904 wfWarn( "$fname: No transaction to commit, something got out of sync." );
2905 return; // nothing to do
2906 } elseif ( $this->mTrxAutomatic
) {
2907 // @TODO: make this an exception at some point
2908 wfLogDBError( "$fname: Explicit commit of implicit transaction." );
2909 return; // wait for the main transaction set commit round
2913 // Avoid fatals if close() was called
2914 $this->assertOpen();
2916 $this->runOnTransactionPreCommitCallbacks();
2917 $writeTime = $this->pendingWriteQueryDuration();
2918 $this->doCommit( $fname );
2919 if ( $this->mTrxDoneWrites
) {
2920 $this->mDoneWrites
= microtime( true );
2921 $this->getTransactionProfiler()->transactionWritingOut(
2922 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2925 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2929 * Issues the COMMIT command to the database server.
2931 * @see DatabaseBase::commit()
2932 * @param string $fname
2934 protected function doCommit( $fname ) {
2935 if ( $this->mTrxLevel
) {
2936 $this->query( 'COMMIT', $fname );
2937 $this->mTrxLevel
= 0;
2941 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2942 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2943 if ( !$this->mTrxLevel
) {
2944 return; // nothing to do
2947 if ( !$this->mTrxLevel
) {
2948 wfWarn( "$fname: No transaction to rollback, something got out of sync." );
2949 return; // nothing to do
2950 } elseif ( $this->getFlag( DBO_TRX
) ) {
2951 throw new DBUnexpectedError(
2953 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2958 // Avoid fatals if close() was called
2959 $this->assertOpen();
2961 $this->doRollback( $fname );
2962 $this->mTrxAtomicLevels
= [];
2963 if ( $this->mTrxDoneWrites
) {
2964 $this->getTransactionProfiler()->transactionWritingOut(
2965 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2968 $this->mTrxIdleCallbacks
= []; // clear
2969 $this->mTrxPreCommitCallbacks
= []; // clear
2970 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2974 * Issues the ROLLBACK command to the database server.
2976 * @see DatabaseBase::rollback()
2977 * @param string $fname
2979 protected function doRollback( $fname ) {
2980 if ( $this->mTrxLevel
) {
2981 # Disconnects cause rollback anyway, so ignore those errors
2982 $ignoreErrors = true;
2983 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2984 $this->mTrxLevel
= 0;
2988 public function explicitTrxActive() {
2989 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2993 * Creates a new table with structure copied from existing table
2994 * Note that unlike most database abstraction functions, this function does not
2995 * automatically append database prefix, because it works at a lower
2996 * abstraction level.
2997 * The table names passed to this function shall not be quoted (this
2998 * function calls addIdentifierQuotes when needed).
3000 * @param string $oldName Name of table whose structure should be copied
3001 * @param string $newName Name of table to be created
3002 * @param bool $temporary Whether the new table should be temporary
3003 * @param string $fname Calling function name
3004 * @throws MWException
3005 * @return bool True if operation was successful
3007 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3010 throw new MWException(
3011 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3014 function listTables( $prefix = null, $fname = __METHOD__
) {
3015 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3019 * Reset the views process cache set by listViews()
3022 final public function clearViewsCache() {
3023 $this->allViews
= null;
3027 * Lists all the VIEWs in the database
3029 * For caching purposes the list of all views should be stored in
3030 * $this->allViews. The process cache can be cleared with clearViewsCache()
3032 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3033 * @param string $fname Name of calling function
3034 * @throws MWException
3038 public function listViews( $prefix = null, $fname = __METHOD__
) {
3039 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3043 * Differentiates between a TABLE and a VIEW
3045 * @param string $name Name of the database-structure to test.
3046 * @throws MWException
3050 public function isView( $name ) {
3051 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3054 public function timestamp( $ts = 0 ) {
3055 return wfTimestamp( TS_MW
, $ts );
3058 public function timestampOrNull( $ts = null ) {
3059 if ( is_null( $ts ) ) {
3062 return $this->timestamp( $ts );
3067 * Take the result from a query, and wrap it in a ResultWrapper if
3068 * necessary. Boolean values are passed through as is, to indicate success
3069 * of write queries or failure.
3071 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3072 * resource, and it was necessary to call this function to convert it to
3073 * a wrapper. Nowadays, raw database objects are never exposed to external
3074 * callers, so this is unnecessary in external code.
3076 * @param bool|ResultWrapper|resource|object $result
3077 * @return bool|ResultWrapper
3079 protected function resultObject( $result ) {
3082 } elseif ( $result instanceof ResultWrapper
) {
3084 } elseif ( $result === true ) {
3085 // Successful write query
3088 return new ResultWrapper( $this, $result );
3092 public function ping( &$rtt = null ) {
3093 // Avoid hitting the server if it was hit recently
3094 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3095 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3096 $rtt = $this->mRTTEstimate
;
3097 return true; // don't care about $rtt
3101 // This will reconnect if possible or return false if not
3102 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3103 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3104 $this->restoreFlags( self
::RESTORE_PRIOR
);
3107 $rtt = $this->mRTTEstimate
;
3116 protected function reconnect() {
3117 $this->closeConnection();
3118 $this->mOpened
= false;
3119 $this->mConn
= false;
3121 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3122 $this->lastPing
= microtime( true );
3124 } catch ( DBConnectionError
$e ) {
3131 public function getSessionLagStatus() {
3132 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3136 * Get the slave lag when the current transaction started
3138 * This is useful when transactions might use snapshot isolation
3139 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3140 * is this lag plus transaction duration. If they don't, it is still
3141 * safe to be pessimistic. This returns null if there is no transaction.
3143 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3146 public function getTransactionLagStatus() {
3147 return $this->mTrxLevel
3148 ?
[ 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() ]
3153 * Get a slave lag estimate for this server
3155 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3158 public function getApproximateLagStatus() {
3160 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3161 'since' => microtime( true )
3166 * Merge the result of getSessionLagStatus() for several DBs
3167 * using the most pessimistic values to estimate the lag of
3168 * any data derived from them in combination
3170 * This is information is useful for caching modules
3172 * @see WANObjectCache::set()
3173 * @see WANObjectCache::getWithSetCallback()
3175 * @param IDatabase $db1
3176 * @param IDatabase ...
3177 * @return array Map of values:
3178 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3179 * - since: oldest UNIX timestamp of any of the DB lag estimates
3180 * - pending: whether any of the DBs have uncommitted changes
3183 public static function getCacheSetOptions( IDatabase
$db1 ) {
3184 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3185 foreach ( func_get_args() as $db ) {
3186 /** @var IDatabase $db */
3187 $status = $db->getSessionLagStatus();
3188 if ( $status['lag'] === false ) {
3189 $res['lag'] = false;
3190 } elseif ( $res['lag'] !== false ) {
3191 $res['lag'] = max( $res['lag'], $status['lag'] );
3193 $res['since'] = min( $res['since'], $status['since'] );
3194 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3200 public function getLag() {
3204 function maxListLen() {
3208 public function encodeBlob( $b ) {
3212 public function decodeBlob( $b ) {
3213 if ( $b instanceof Blob
) {
3219 public function setSessionOptions( array $options ) {
3223 * Read and execute SQL commands from a file.
3225 * Returns true on success, error string or exception on failure (depending
3226 * on object's error ignore settings).
3228 * @param string $filename File name to open
3229 * @param bool|callable $lineCallback Optional function called before reading each line
3230 * @param bool|callable $resultCallback Optional function called for each MySQL result
3231 * @param bool|string $fname Calling function name or false if name should be
3232 * generated dynamically using $filename
3233 * @param bool|callable $inputCallback Optional function called for each
3234 * complete line sent
3235 * @throws Exception|MWException
3236 * @return bool|string
3238 public function sourceFile(
3239 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3241 MediaWiki\
suppressWarnings();
3242 $fp = fopen( $filename, 'r' );
3243 MediaWiki\restoreWarnings
();
3245 if ( false === $fp ) {
3246 throw new MWException( "Could not open \"{$filename}\".\n" );
3250 $fname = __METHOD__
. "( $filename )";
3254 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3255 } catch ( Exception
$e ) {
3266 * Get the full path of a patch file. Originally based on archive()
3267 * from updaters.inc. Keep in mind this always returns a patch, as
3268 * it fails back to MySQL if no DB-specific patch can be found
3270 * @param string $patch The name of the patch, like patch-something.sql
3271 * @return string Full path to patch file
3273 public function patchPath( $patch ) {
3276 $dbType = $this->getType();
3277 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3278 return "$IP/maintenance/$dbType/archives/$patch";
3280 return "$IP/maintenance/archives/$patch";
3284 public function setSchemaVars( $vars ) {
3285 $this->mSchemaVars
= $vars;
3289 * Read and execute commands from an open file handle.
3291 * Returns true on success, error string or exception on failure (depending
3292 * on object's error ignore settings).
3294 * @param resource $fp File handle
3295 * @param bool|callable $lineCallback Optional function called before reading each query
3296 * @param bool|callable $resultCallback Optional function called for each MySQL result
3297 * @param string $fname Calling function name
3298 * @param bool|callable $inputCallback Optional function called for each complete query sent
3299 * @return bool|string
3301 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3302 $fname = __METHOD__
, $inputCallback = false
3306 while ( !feof( $fp ) ) {
3307 if ( $lineCallback ) {
3308 call_user_func( $lineCallback );
3311 $line = trim( fgets( $fp ) );
3313 if ( $line == '' ) {
3317 if ( '-' == $line[0] && '-' == $line[1] ) {
3325 $done = $this->streamStatementEnd( $cmd, $line );
3329 if ( $done ||
feof( $fp ) ) {
3330 $cmd = $this->replaceVars( $cmd );
3332 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3333 $res = $this->query( $cmd, $fname );
3335 if ( $resultCallback ) {
3336 call_user_func( $resultCallback, $res, $this );
3339 if ( false === $res ) {
3340 $err = $this->lastError();
3342 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3353 * Called by sourceStream() to check if we've reached a statement end
3355 * @param string $sql SQL assembled so far
3356 * @param string $newLine New line about to be added to $sql
3357 * @return bool Whether $newLine contains end of the statement
3359 public function streamStatementEnd( &$sql, &$newLine ) {
3360 if ( $this->delimiter
) {
3362 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3363 if ( $newLine != $prev ) {
3372 * Database independent variable replacement. Replaces a set of variables
3373 * in an SQL statement with their contents as given by $this->getSchemaVars().
3375 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3377 * - '{$var}' should be used for text and is passed through the database's
3379 * - `{$var}` should be used for identifiers (e.g. table and database names).
3380 * It is passed through the database's addIdentifierQuotes method which
3381 * can be overridden if the database uses something other than backticks.
3382 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3383 * database's tableName method.
3384 * - / *i* / passes the name that follows through the database's indexName method.
3385 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3386 * its use should be avoided. In 1.24 and older, string encoding was applied.
3388 * @param string $ins SQL statement to replace variables in
3389 * @return string The new SQL statement with variables replaced
3391 protected function replaceVars( $ins ) {
3392 $vars = $this->getSchemaVars();
3393 return preg_replace_callback(
3395 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3396 \'\{\$ (\w+) }\' | # 3. addQuotes
3397 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3398 /\*\$ (\w+) \*/ # 5. leave unencoded
3400 function ( $m ) use ( $vars ) {
3401 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3402 // check for both nonexistent keys *and* the empty string.
3403 if ( isset( $m[1] ) && $m[1] !== '' ) {
3404 if ( $m[1] === 'i' ) {
3405 return $this->indexName( $m[2] );
3407 return $this->tableName( $m[2] );
3409 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3410 return $this->addQuotes( $vars[$m[3]] );
3411 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3412 return $this->addIdentifierQuotes( $vars[$m[4]] );
3413 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3414 return $vars[$m[5]];
3424 * Get schema variables. If none have been set via setSchemaVars(), then
3425 * use some defaults from the current object.
3429 protected function getSchemaVars() {
3430 if ( $this->mSchemaVars
) {
3431 return $this->mSchemaVars
;
3433 return $this->getDefaultSchemaVars();
3438 * Get schema variables to use if none have been set via setSchemaVars().
3440 * Override this in derived classes to provide variables for tables.sql
3441 * and SQL patch files.
3445 protected function getDefaultSchemaVars() {
3449 public function lockIsFree( $lockName, $method ) {
3453 public function lock( $lockName, $method, $timeout = 5 ) {
3454 $this->mNamedLocksHeld
[$lockName] = 1;
3459 public function unlock( $lockName, $method ) {
3460 unset( $this->mNamedLocksHeld
[$lockName] );
3465 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3466 if ( $this->writesOrCallbacksPending() ) {
3467 // This only flushes transactions to clear snapshots, not to write data
3468 throw new DBUnexpectedError(
3470 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3474 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3478 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3479 if ( $this->trxLevel() ) {
3480 // There is a good chance an exception was thrown, causing any early return
3481 // from the caller. Let any error handler get a chance to issue rollback().
3482 // If there isn't one, let the error bubble up and trigger server-side rollback.
3483 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3484 $this->unlock( $lockKey, $fname );
3487 $this->unlock( $lockKey, $fname );
3491 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3496 public function namedLocksEnqueue() {
3501 * Lock specific tables
3503 * @param array $read Array of tables to lock for read access
3504 * @param array $write Array of tables to lock for write access
3505 * @param string $method Name of caller
3506 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3509 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3514 * Unlock specific tables
3516 * @param string $method The caller
3519 public function unlockTables( $method ) {
3525 * @param string $tableName
3526 * @param string $fName
3527 * @return bool|ResultWrapper
3530 public function dropTable( $tableName, $fName = __METHOD__
) {
3531 if ( !$this->tableExists( $tableName, $fName ) ) {
3534 $sql = "DROP TABLE " . $this->tableName( $tableName );
3535 if ( $this->cascadingDeletes() ) {
3539 return $this->query( $sql, $fName );
3543 * Get search engine class. All subclasses of this need to implement this
3544 * if they wish to use searching.
3548 public function getSearchEngine() {
3549 return 'SearchEngineDummy';
3552 public function getInfinity() {
3556 public function encodeExpiry( $expiry ) {
3557 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3558 ?
$this->getInfinity()
3559 : $this->timestamp( $expiry );
3562 public function decodeExpiry( $expiry, $format = TS_MW
) {
3563 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3565 : wfTimestamp( $format, $expiry );
3568 public function setBigSelects( $value = true ) {
3572 public function isReadOnly() {
3573 return ( $this->getReadOnlyReason() !== false );
3577 * @return string|bool Reason this DB is read-only or false if it is not
3579 protected function getReadOnlyReason() {
3580 $reason = $this->getLBInfo( 'readOnlyReason' );
3582 return is_string( $reason ) ?
$reason : false;
3589 public function __toString() {
3590 return (string)$this->mConn
;
3594 * Run a few simple sanity checks
3596 public function __destruct() {
3597 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3598 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3600 $danglingCallbacks = array_merge(
3601 $this->mTrxIdleCallbacks
,
3602 $this->mTrxPreCommitCallbacks
,
3603 $this->mTrxEndCallbacks
3605 if ( $danglingCallbacks ) {
3607 foreach ( $danglingCallbacks as $callbackInfo ) {
3608 $callers[] = $callbackInfo[1];
3610 $callers = implode( ', ', $callers );
3611 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3619 abstract class Database
extends DatabaseBase
{
3620 // B/C until nothing type hints for DatabaseBase
3621 // @TODO: finish renaming DatabaseBase => Database