3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
30 * Database abstraction object
33 abstract class DatabaseBase
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
68 /** @var BagOStuff APC cache */
70 /** @var LoggerInterface */
71 protected $connLogger;
72 /** @var LoggerInterface */
73 protected $queryLogger;
74 /** @var callback Error logging callback */
75 protected $errorLogger;
77 /** @var resource Database connection */
78 protected $mConn = null;
80 protected $mOpened = false;
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxIdleCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxPreCommitCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxEndCallbacks = [];
88 /** @var callable[] Map of (name => callable) */
89 protected $mTrxRecurringCallbacks = [];
90 /** @var bool Whether to suppress triggering of transaction end callbacks */
91 protected $mTrxEndCallbacksSuppressed = false;
94 protected $mTablePrefix;
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
112 protected $delimiter = ';';
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
120 protected $mTrxLevel = 0;
122 * Either a short hexidecimal string if a transaction is active or ""
125 * @see DatabaseBase::mTrxLevel
127 protected $mTrxShortId = '';
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
134 * @see DatabaseBase::mTrxLevel
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
144 * @see DatabaseBase::mTrxLevel
146 private $mTrxFname = null;
148 * Record if possible write queries were done in the last transaction started
151 * @see DatabaseBase::mTrxLevel
153 private $mTrxDoneWrites = false;
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
158 * @see DatabaseBase::mTrxLevel
160 private $mTrxAutomatic = false;
162 * Array of levels of atomicity within transactions
166 private $mTrxAtomicLevels = [];
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
172 private $mTrxAutomaticAtomic = false;
174 * Track the write query callers of the current transaction
178 private $mTrxWriteCallers = [];
180 * @var float Seconds spent in write queries for the current transaction
182 private $mTrxWriteDuration = 0.0;
184 * @var integer Number of write queries for the current transaction
186 private $mTrxWriteQueryCount = 0;
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
190 private $mTrxWriteAdjDuration = 0.0;
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
194 private $mTrxWriteAdjQueryCount = 0;
196 * @var float RTT time estimate
198 private $mRTTEstimate = 0.0;
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
208 * @var resource File handle for upgrade
210 protected $fileHandle = null;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
239 * @param array $params Parameters passed from DatabaseBase::factory()
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
246 $flags = $params['flags'];
248 $this->mSchema
= $params['schema'];
249 $this->mTablePrefix
= $params['tablePrefix'];
251 $this->cliMode
= isset( $params['cliMode'] )
253 : ( PHP_SAPI
=== 'cli' );
255 $this->mFlags
= $flags;
256 if ( $this->mFlags
& DBO_DEFAULT
) {
257 if ( $this->cliMode
) {
258 $this->mFlags
&= ~DBO_TRX
;
260 $this->mFlags |
= DBO_TRX
;
264 $this->mSessionVars
= $params['variables'];
266 $this->srvCache
= isset( $params['srvCache'] )
267 ?
$params['srvCache']
268 : new HashBagOStuff();
270 $this->profiler
= isset( $params['profiler'] )
271 ?
$params['profiler']
272 : Profiler
::instance(); // @TODO: remove global state
273 $this->trxProfiler
= isset( $params['trxProfiler'] )
274 ?
$params['trxProfiler']
275 : new TransactionProfiler();
276 $this->connLogger
= isset( $params['connLogger'] )
277 ?
$params['connLogger']
278 : new \Psr\Log\
NullLogger();
279 $this->queryLogger
= isset( $params['queryLogger'] )
280 ?
$params['queryLogger']
281 : new \Psr\Log\
NullLogger();
284 $this->open( $server, $user, $password, $dbName );
289 * Given a DB type, construct the name of the appropriate child class of
290 * IDatabase. This is designed to replace all of the manual stuff like:
291 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
292 * as well as validate against the canonical list of DB types we have
294 * This factory function is mostly useful for when you need to connect to a
295 * database other than the MediaWiki default (such as for external auth,
296 * an extension, et cetera). Do not use this to connect to the MediaWiki
297 * database. Example uses in core:
298 * @see LoadBalancer::reallyOpenConnection()
299 * @see ForeignDBRepo::getMasterDB()
300 * @see WebInstallerDBConnect::execute()
304 * @param string $dbType A possible DB type
305 * @param array $p An array of options to pass to the constructor.
306 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
307 * @return IDatabase|null If the database driver or extension cannot be found
308 * @throws InvalidArgumentException If the database driver or extension cannot be found
310 final public static function factory( $dbType, $p = [] ) {
311 global $wgCommandLineMode;
313 $canonicalDBTypes = [
314 'mysql' => [ 'mysqli', 'mysql' ],
322 $dbType = strtolower( $dbType );
323 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
324 $possibleDrivers = $canonicalDBTypes[$dbType];
325 if ( !empty( $p['driver'] ) ) {
326 if ( in_array( $p['driver'], $possibleDrivers ) ) {
327 $driver = $p['driver'];
329 throw new InvalidArgumentException( __METHOD__
.
330 " type '$dbType' does not support driver '{$p['driver']}'" );
333 foreach ( $possibleDrivers as $posDriver ) {
334 if ( extension_loaded( $posDriver ) ) {
335 $driver = $posDriver;
343 if ( $driver === false ) {
344 throw new InvalidArgumentException( __METHOD__
.
345 " no viable database extension found for type '$dbType'" );
348 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
349 // and everything else doesn't use a schema (e.g. null)
350 // Although postgres and oracle support schemas, we don't use them (yet)
351 // to maintain backwards compatibility
353 'mssql' => 'get from global',
356 $class = 'Database' . ucfirst( $driver );
357 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
358 // Resolve some defaults for b/c
359 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
360 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
361 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
362 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
363 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
364 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
365 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
366 if ( !isset( $p['schema'] ) ) {
367 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
369 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
370 $p['cliMode'] = $wgCommandLineMode;
372 $conn = new $class( $p );
373 if ( isset( $p['connLogger'] ) ) {
374 $conn->connLogger
= $p['connLogger'];
376 if ( isset( $p['queryLogger'] ) ) {
377 $conn->queryLogger
= $p['queryLogger'];
379 if ( isset( $p['errorLogger'] ) ) {
380 $conn->errorLogger
= $p['errorLogger'];
382 $conn->errorLogger
= [ MWExceptionHandler
::class, 'logException' ];
391 public function setLogger( LoggerInterface
$logger ) {
392 $this->queryLogger
= $logger;
395 public function getServerInfo() {
396 return $this->getServerVersion();
400 * @return string Command delimiter used by this database engine
402 public function getDelimiter() {
403 return $this->delimiter
;
407 * Boolean, controls output of large amounts of debug information.
408 * @param bool|null $debug
409 * - true to enable debugging
410 * - false to disable debugging
411 * - omitted or null to do nothing
413 * @return bool Previous value of the flag
414 * @deprecated since 1.28; use setFlag()
416 public function debug( $debug = null ) {
417 $res = $this->getFlag( DBO_DEBUG
);
418 if ( $debug !== null ) {
419 $debug ?
$this->setFlag( DBO_DEBUG
) : $this->clearFlag( DBO_DEBUG
);
425 public function bufferResults( $buffer = null ) {
426 $res = !$this->getFlag( DBO_NOBUFFER
);
427 if ( $buffer !== null ) {
428 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
435 * Turns on (false) or off (true) the automatic generation and sending
436 * of a "we're sorry, but there has been a database error" page on
437 * database errors. Default is on (false). When turned off, the
438 * code should use lastErrno() and lastError() to handle the
439 * situation as appropriate.
441 * Do not use this function outside of the Database classes.
443 * @param null|bool $ignoreErrors
444 * @return bool The previous value of the flag.
446 protected function ignoreErrors( $ignoreErrors = null ) {
447 $res = $this->getFlag( DBO_IGNORE
);
448 if ( $ignoreErrors !== null ) {
449 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
455 public function trxLevel() {
456 return $this->mTrxLevel
;
459 public function trxTimestamp() {
460 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
463 public function tablePrefix( $prefix = null ) {
464 $old = $this->mTablePrefix
;
465 $this->mTablePrefix
= $prefix;
470 public function dbSchema( $schema = null ) {
471 $old = $this->mSchema
;
472 $this->mSchema
= $schema;
478 * Set the filehandle to copy write statements to.
480 * @param resource $fh File handle
482 public function setFileHandle( $fh ) {
483 $this->fileHandle
= $fh;
486 public function getLBInfo( $name = null ) {
487 if ( is_null( $name ) ) {
488 return $this->mLBInfo
;
490 if ( array_key_exists( $name, $this->mLBInfo
) ) {
491 return $this->mLBInfo
[$name];
498 public function setLBInfo( $name, $value = null ) {
499 if ( is_null( $value ) ) {
500 $this->mLBInfo
= $name;
502 $this->mLBInfo
[$name] = $value;
506 public function setLazyMasterHandle( IDatabase
$conn ) {
507 $this->lazyMasterHandle
= $conn;
511 * @return IDatabase|null
512 * @see setLazyMasterHandle()
515 public function getLazyMasterHandle() {
516 return $this->lazyMasterHandle
;
520 * @param TransactionProfiler $profiler
523 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
524 $this->trxProfiler
= $profiler;
528 * Returns true if this database supports (and uses) cascading deletes
532 public function cascadingDeletes() {
537 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
541 public function cleanupTriggers() {
546 * Returns true if this database is strict about what can be put into an IP field.
547 * Specifically, it uses a NULL value instead of an empty string.
551 public function strictIPs() {
556 * Returns true if this database uses timestamps rather than integers
560 public function realTimestamps() {
564 public function implicitGroupby() {
568 public function implicitOrderby() {
573 * Returns true if this database can do a native search on IP columns
574 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
578 public function searchableIPs() {
583 * Returns true if this database can use functional indexes
587 public function functionalIndexes() {
591 public function lastQuery() {
592 return $this->mLastQuery
;
595 public function doneWrites() {
596 return (bool)$this->mDoneWrites
;
599 public function lastDoneWrites() {
600 return $this->mDoneWrites ?
: false;
603 public function writesPending() {
604 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
607 public function writesOrCallbacksPending() {
608 return $this->mTrxLevel
&& (
609 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
613 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
614 if ( !$this->mTrxLevel
) {
616 } elseif ( !$this->mTrxDoneWrites
) {
621 case self
::ESTIMATE_DB_APPLY
:
623 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
624 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
625 // For omitted queries, make them count as something at least
626 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
627 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
630 default: // everything
631 return $this->mTrxWriteDuration
;
635 public function pendingWriteCallers() {
636 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
639 public function isOpen() {
640 return $this->mOpened
;
643 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
644 if ( $remember === self
::REMEMBER_PRIOR
) {
645 array_push( $this->priorFlags
, $this->mFlags
);
647 $this->mFlags |
= $flag;
650 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
651 if ( $remember === self
::REMEMBER_PRIOR
) {
652 array_push( $this->priorFlags
, $this->mFlags
);
654 $this->mFlags
&= ~
$flag;
657 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
658 if ( !$this->priorFlags
) {
662 if ( $state === self
::RESTORE_INITIAL
) {
663 $this->mFlags
= reset( $this->priorFlags
);
664 $this->priorFlags
= [];
666 $this->mFlags
= array_pop( $this->priorFlags
);
670 public function getFlag( $flag ) {
671 return !!( $this->mFlags
& $flag );
674 public function getProperty( $name ) {
678 public function getWikiID() {
679 if ( $this->mTablePrefix
) {
680 return "{$this->mDBname}-{$this->mTablePrefix}";
682 return $this->mDBname
;
687 * Get information about an index into an object
688 * @param string $table Table name
689 * @param string $index Index name
690 * @param string $fname Calling function name
691 * @return mixed Database-specific index description class or false if the index does not exist
693 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
696 * Wrapper for addslashes()
698 * @param string $s String to be slashed.
699 * @return string Slashed string.
701 abstract function strencode( $s );
704 * Called by serialize. Throw an exception when DB connection is serialized.
705 * This causes problems on some database engines because the connection is
706 * not restored on unserialize.
708 public function __sleep() {
709 throw new RuntimeException( 'Database serialization may cause problems, since ' .
710 'the connection is not restored on wakeup.' );
713 protected function installErrorHandler() {
714 $this->mPHPError
= false;
715 $this->htmlErrors
= ini_set( 'html_errors', '0' );
716 set_error_handler( [ $this, 'connectionerrorLogger' ] );
720 * @return bool|string
722 protected function restoreErrorHandler() {
723 restore_error_handler();
724 if ( $this->htmlErrors
!== false ) {
725 ini_set( 'html_errors', $this->htmlErrors
);
727 if ( $this->mPHPError
) {
728 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
729 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
739 * @param string $errstr
741 public function connectionerrorLogger( $errno, $errstr ) {
742 $this->mPHPError
= $errstr;
746 * Create a log context to pass to PSR logging functions.
748 * @param array $extras Additional data to add to context
751 protected function getLogContext( array $extras = [] ) {
754 'db_server' => $this->mServer
,
755 'db_name' => $this->mDBname
,
756 'db_user' => $this->mUser
,
762 public function close() {
763 if ( $this->mConn
) {
764 if ( $this->trxLevel() ) {
765 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
768 $closed = $this->closeConnection();
769 $this->mConn
= false;
770 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
771 throw new RuntimeException( "Transaction callbacks still pending." );
775 $this->mOpened
= false;
781 * Make sure isOpen() returns true as a sanity check
783 * @throws DBUnexpectedError
785 protected function assertOpen() {
786 if ( !$this->isOpen() ) {
787 throw new DBUnexpectedError( $this, "DB connection was already closed." );
792 * Closes underlying database connection
794 * @return bool Whether connection was closed successfully
796 abstract protected function closeConnection();
798 function reportConnectionError( $error = 'Unknown error' ) {
799 $myError = $this->lastError();
805 throw new DBConnectionError( $this, $error );
809 * The DBMS-dependent part of query()
811 * @param string $sql SQL query.
812 * @return ResultWrapper|bool Result object to feed to fetchObject,
813 * fetchRow, ...; or false on failure
815 abstract protected function doQuery( $sql );
818 * Determine whether a query writes to the DB.
819 * Should return true if unsure.
824 protected function isWriteQuery( $sql ) {
826 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
831 * @return string|null
833 protected function getQueryVerb( $sql ) {
834 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
838 * Determine whether a SQL statement is sensitive to isolation level.
839 * A SQL statement is considered transactable if its result could vary
840 * depending on the transaction isolation level. Operational commands
841 * such as 'SET' and 'SHOW' are not considered to be transactable.
846 protected function isTransactableQuery( $sql ) {
847 $verb = $this->getQueryVerb( $sql );
848 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
851 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
854 $priorWritesPending = $this->writesOrCallbacksPending();
855 $this->mLastQuery
= $sql;
857 $isWrite = $this->isWriteQuery( $sql );
859 $reason = $this->getReadOnlyReason();
860 if ( $reason !== false ) {
861 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
863 # Set a flag indicating that writes have been done
864 $this->mDoneWrites
= microtime( true );
867 # Add a comment for easy SHOW PROCESSLIST interpretation
868 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
869 $userName = $wgUser->getName();
870 if ( mb_strlen( $userName ) > 15 ) {
871 $userName = mb_substr( $userName, 0, 15 ) . '...';
873 $userName = str_replace( '/', '', $userName );
878 // Add trace comment to the begin of the sql string, right after the operator.
879 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
880 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
882 # Start implicit transactions that wrap the request if DBO_TRX is enabled
883 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
884 && $this->isTransactableQuery( $sql )
886 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
887 $this->mTrxAutomatic
= true;
890 # Keep track of whether the transaction has write queries pending
891 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
892 $this->mTrxDoneWrites
= true;
893 $this->trxProfiler
->transactionWritingIn(
894 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
897 if ( $this->debug() ) {
898 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
901 # Avoid fatals if close() was called
904 # Send the query to the server
905 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
907 # Try reconnecting if the connection was lost
908 if ( false === $ret && $this->wasErrorReissuable() ) {
909 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
910 # Stash the last error values before anything might clear them
911 $lastError = $this->lastError();
912 $lastErrno = $this->lastErrno();
913 # Update state tracking to reflect transaction loss due to disconnection
914 $this->handleTransactionLoss();
915 if ( $this->reconnect() ) {
916 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
917 $this->connLogger
->warning( $msg );
918 $this->queryLogger
->warning(
919 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
921 if ( !$recoverable ) {
922 # Callers may catch the exception and continue to use the DB
923 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
925 # Should be safe to silently retry the query
926 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
929 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
930 $this->connLogger
->error( $msg );
934 if ( false === $ret ) {
935 # Deadlocks cause the entire transaction to abort, not just the statement.
936 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
937 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
938 if ( $this->wasDeadlock() ) {
939 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
940 $tempIgnore = false; // not recoverable
942 # Update state tracking to reflect transaction loss
943 $this->handleTransactionLoss();
946 $this->reportQueryError(
947 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
950 $res = $this->resultObject( $ret );
955 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
956 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
957 # generalizeSQL() will probably cut down the query to reasonable
958 # logging size most of the time. The substr is really just a sanity check.
960 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
962 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
965 # Include query transaction state
966 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
968 $startTime = microtime( true );
969 $this->profiler
->profileIn( $queryProf );
970 $ret = $this->doQuery( $commentedSql );
971 $this->profiler
->profileOut( $queryProf );
972 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
974 unset( $queryProfSection ); // profile out (if set)
976 if ( $ret !== false ) {
977 $this->lastPing
= $startTime;
978 if ( $isWrite && $this->mTrxLevel
) {
979 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
980 $this->mTrxWriteCallers
[] = $fname;
984 if ( $sql === self
::PING_QUERY
) {
985 $this->mRTTEstimate
= $queryRuntime;
988 $this->trxProfiler
->recordQueryCompletion(
989 $queryProf, $startTime, $isWrite, $this->affectedRows()
991 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
997 * Update the estimated run-time of a query, not counting large row lock times
999 * LoadBalancer can be set to rollback transactions that will create huge replication
1000 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1001 * queries, like inserting a row can take a long time due to row locking. This method
1002 * uses some simple heuristics to discount those cases.
1004 * @param string $sql A SQL write query
1005 * @param float $runtime Total runtime, including RTT
1007 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1008 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1009 $indicativeOfReplicaRuntime = true;
1010 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1011 $verb = $this->getQueryVerb( $sql );
1012 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1013 if ( $verb === 'INSERT' ) {
1014 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1015 } elseif ( $verb === 'REPLACE' ) {
1016 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1020 $this->mTrxWriteDuration +
= $runtime;
1021 $this->mTrxWriteQueryCount +
= 1;
1022 if ( $indicativeOfReplicaRuntime ) {
1023 $this->mTrxWriteAdjDuration +
= $runtime;
1024 $this->mTrxWriteAdjQueryCount +
= 1;
1028 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1029 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1030 # Dropped connections also mean that named locks are automatically released.
1031 # Only allow error suppression in autocommit mode or when the lost transaction
1032 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1033 if ( $this->mNamedLocksHeld
) {
1034 return false; // possible critical section violation
1035 } elseif ( $sql === 'COMMIT' ) {
1036 return !$priorWritesPending; // nothing written anyway? (T127428)
1037 } elseif ( $sql === 'ROLLBACK' ) {
1038 return true; // transaction lost...which is also what was requested :)
1039 } elseif ( $this->explicitTrxActive() ) {
1040 return false; // don't drop atomocity
1041 } elseif ( $priorWritesPending ) {
1042 return false; // prior writes lost from implicit transaction
1048 private function handleTransactionLoss() {
1049 $this->mTrxLevel
= 0;
1050 $this->mTrxIdleCallbacks
= []; // bug 65263
1051 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1053 // Handle callbacks in mTrxEndCallbacks
1054 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1055 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1057 } catch ( Exception
$e ) {
1058 // Already logged; move on...
1063 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1064 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1065 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1067 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1068 $this->queryLogger
->error(
1069 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1070 $this->getLogContext( [
1071 'method' => __METHOD__
,
1074 'sql1line' => $sql1line,
1078 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1079 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1084 * Intended to be compatible with the PEAR::DB wrapper functions.
1085 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1087 * ? = scalar value, quoted as necessary
1088 * ! = raw SQL bit (a function for instance)
1089 * & = filename; reads the file and inserts as a blob
1090 * (we don't use this though...)
1092 * @param string $sql
1093 * @param string $func
1097 protected function prepare( $sql, $func = __METHOD__
) {
1098 /* MySQL doesn't support prepared statements (yet), so just
1099 * pack up the query for reference. We'll manually replace
1102 return [ 'query' => $sql, 'func' => $func ];
1106 * Free a prepared query, generated by prepare().
1107 * @param string $prepared
1109 protected function freePrepared( $prepared ) {
1110 /* No-op by default */
1114 * Execute a prepared query with the various arguments
1115 * @param string $prepared The prepared sql
1116 * @param mixed $args Either an array here, or put scalars as varargs
1118 * @return ResultWrapper
1120 public function execute( $prepared, $args = null ) {
1121 if ( !is_array( $args ) ) {
1123 $args = func_get_args();
1124 array_shift( $args );
1127 $sql = $this->fillPrepared( $prepared['query'], $args );
1129 return $this->query( $sql, $prepared['func'] );
1133 * For faking prepared SQL statements on DBs that don't support it directly.
1135 * @param string $preparedQuery A 'preparable' SQL statement
1136 * @param array $args Array of Arguments to fill it with
1137 * @return string Executable SQL
1139 public function fillPrepared( $preparedQuery, $args ) {
1141 $this->preparedArgs
=& $args;
1143 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1144 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1148 * preg_callback func for fillPrepared()
1149 * The arguments should be in $this->preparedArgs and must not be touched
1150 * while we're doing this.
1152 * @param array $matches
1153 * @throws DBUnexpectedError
1156 protected function fillPreparedArg( $matches ) {
1157 switch ( $matches[1] ) {
1166 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1168 switch ( $matches[1] ) {
1170 return $this->addQuotes( $arg );
1174 # return $this->addQuotes( file_get_contents( $arg ) );
1175 throw new DBUnexpectedError(
1177 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1180 throw new DBUnexpectedError(
1182 'Received invalid match. This should never happen!'
1187 public function freeResult( $res ) {
1190 public function selectField(
1191 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1193 if ( $var === '*' ) { // sanity
1194 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1197 if ( !is_array( $options ) ) {
1198 $options = [ $options ];
1201 $options['LIMIT'] = 1;
1203 $res = $this->select( $table, $var, $cond, $fname, $options );
1204 if ( $res === false ||
!$this->numRows( $res ) ) {
1208 $row = $this->fetchRow( $res );
1210 if ( $row !== false ) {
1211 return reset( $row );
1217 public function selectFieldValues(
1218 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1220 if ( $var === '*' ) { // sanity
1221 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1222 } elseif ( !is_string( $var ) ) { // sanity
1223 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1226 if ( !is_array( $options ) ) {
1227 $options = [ $options ];
1230 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1231 if ( $res === false ) {
1236 foreach ( $res as $row ) {
1237 $values[] = $row->$var;
1244 * Returns an optional USE INDEX clause to go after the table, and a
1245 * string to go at the end of the query.
1247 * @param array $options Associative array of options to be turned into
1248 * an SQL query, valid keys are listed in the function.
1250 * @see DatabaseBase::select()
1252 public function makeSelectOptions( $options ) {
1253 $preLimitTail = $postLimitTail = '';
1258 foreach ( $options as $key => $option ) {
1259 if ( is_numeric( $key ) ) {
1260 $noKeyOptions[$option] = true;
1264 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1266 $preLimitTail .= $this->makeOrderBy( $options );
1268 // if (isset($options['LIMIT'])) {
1269 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1270 // isset($options['OFFSET']) ? $options['OFFSET']
1274 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1275 $postLimitTail .= ' FOR UPDATE';
1278 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1279 $postLimitTail .= ' LOCK IN SHARE MODE';
1282 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1283 $startOpts .= 'DISTINCT';
1286 # Various MySQL extensions
1287 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1288 $startOpts .= ' /*! STRAIGHT_JOIN */';
1291 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1292 $startOpts .= ' HIGH_PRIORITY';
1295 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1296 $startOpts .= ' SQL_BIG_RESULT';
1299 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1300 $startOpts .= ' SQL_BUFFER_RESULT';
1303 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1304 $startOpts .= ' SQL_SMALL_RESULT';
1307 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1308 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1311 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1312 $startOpts .= ' SQL_CACHE';
1315 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1316 $startOpts .= ' SQL_NO_CACHE';
1319 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1320 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1324 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1325 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1330 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1334 * Returns an optional GROUP BY with an optional HAVING
1336 * @param array $options Associative array of options
1338 * @see DatabaseBase::select()
1341 public function makeGroupByWithHaving( $options ) {
1343 if ( isset( $options['GROUP BY'] ) ) {
1344 $gb = is_array( $options['GROUP BY'] )
1345 ?
implode( ',', $options['GROUP BY'] )
1346 : $options['GROUP BY'];
1347 $sql .= ' GROUP BY ' . $gb;
1349 if ( isset( $options['HAVING'] ) ) {
1350 $having = is_array( $options['HAVING'] )
1351 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1352 : $options['HAVING'];
1353 $sql .= ' HAVING ' . $having;
1360 * Returns an optional ORDER BY
1362 * @param array $options Associative array of options
1364 * @see DatabaseBase::select()
1367 public function makeOrderBy( $options ) {
1368 if ( isset( $options['ORDER BY'] ) ) {
1369 $ob = is_array( $options['ORDER BY'] )
1370 ?
implode( ',', $options['ORDER BY'] )
1371 : $options['ORDER BY'];
1373 return ' ORDER BY ' . $ob;
1379 // See IDatabase::select for the docs for this function
1380 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1381 $options = [], $join_conds = [] ) {
1382 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1384 return $this->query( $sql, $fname );
1387 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1388 $options = [], $join_conds = []
1390 if ( is_array( $vars ) ) {
1391 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1394 $options = (array)$options;
1395 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1396 ?
$options['USE INDEX']
1398 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1399 ?
$options['IGNORE INDEX']
1402 if ( is_array( $table ) ) {
1404 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1405 } elseif ( $table != '' ) {
1406 if ( $table[0] == ' ' ) {
1407 $from = ' FROM ' . $table;
1410 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1416 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1417 $this->makeSelectOptions( $options );
1419 if ( !empty( $conds ) ) {
1420 if ( is_array( $conds ) ) {
1421 $conds = $this->makeList( $conds, LIST_AND
);
1423 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1425 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1428 if ( isset( $options['LIMIT'] ) ) {
1429 $sql = $this->limitResult( $sql, $options['LIMIT'],
1430 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1432 $sql = "$sql $postLimitTail";
1434 if ( isset( $options['EXPLAIN'] ) ) {
1435 $sql = 'EXPLAIN ' . $sql;
1441 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1442 $options = [], $join_conds = []
1444 $options = (array)$options;
1445 $options['LIMIT'] = 1;
1446 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1448 if ( $res === false ) {
1452 if ( !$this->numRows( $res ) ) {
1456 $obj = $this->fetchObject( $res );
1461 public function estimateRowCount(
1462 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1465 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1468 $row = $this->fetchRow( $res );
1469 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1475 public function selectRowCount(
1476 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1479 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1480 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1483 $row = $this->fetchRow( $res );
1484 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1491 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1492 * It's only slightly flawed. Don't use for anything important.
1494 * @param string $sql A SQL Query
1498 protected static function generalizeSQL( $sql ) {
1499 # This does the same as the regexp below would do, but in such a way
1500 # as to avoid crashing php on some large strings.
1501 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1503 $sql = str_replace( "\\\\", '', $sql );
1504 $sql = str_replace( "\\'", '', $sql );
1505 $sql = str_replace( "\\\"", '', $sql );
1506 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1507 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1509 # All newlines, tabs, etc replaced by single space
1510 $sql = preg_replace( '/\s+/', ' ', $sql );
1513 # except the ones surrounded by characters, e.g. l10n
1514 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1515 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1520 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1521 $info = $this->fieldInfo( $table, $field );
1526 public function indexExists( $table, $index, $fname = __METHOD__
) {
1527 if ( !$this->tableExists( $table ) ) {
1531 $info = $this->indexInfo( $table, $index, $fname );
1532 if ( is_null( $info ) ) {
1535 return $info !== false;
1539 public function tableExists( $table, $fname = __METHOD__
) {
1540 $table = $this->tableName( $table );
1541 $old = $this->ignoreErrors( true );
1542 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1543 $this->ignoreErrors( $old );
1548 public function indexUnique( $table, $index ) {
1549 $indexInfo = $this->indexInfo( $table, $index );
1551 if ( !$indexInfo ) {
1555 return !$indexInfo[0]->Non_unique
;
1559 * Helper for DatabaseBase::insert().
1561 * @param array $options
1564 protected function makeInsertOptions( $options ) {
1565 return implode( ' ', $options );
1568 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1569 # No rows to insert, easy just return now
1570 if ( !count( $a ) ) {
1574 $table = $this->tableName( $table );
1576 if ( !is_array( $options ) ) {
1577 $options = [ $options ];
1581 if ( isset( $options['fileHandle'] ) ) {
1582 $fh = $options['fileHandle'];
1584 $options = $this->makeInsertOptions( $options );
1586 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1588 $keys = array_keys( $a[0] );
1591 $keys = array_keys( $a );
1594 $sql = 'INSERT ' . $options .
1595 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1599 foreach ( $a as $row ) {
1605 $sql .= '(' . $this->makeList( $row ) . ')';
1608 $sql .= '(' . $this->makeList( $a ) . ')';
1611 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1613 } elseif ( $fh !== null ) {
1617 return (bool)$this->query( $sql, $fname );
1621 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1623 * @param array $options
1626 protected function makeUpdateOptionsArray( $options ) {
1627 if ( !is_array( $options ) ) {
1628 $options = [ $options ];
1633 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1634 $opts[] = $this->lowPriorityOption();
1637 if ( in_array( 'IGNORE', $options ) ) {
1645 * Make UPDATE options for the DatabaseBase::update function
1647 * @param array $options The options passed to DatabaseBase::update
1650 protected function makeUpdateOptions( $options ) {
1651 $opts = $this->makeUpdateOptionsArray( $options );
1653 return implode( ' ', $opts );
1656 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1657 $table = $this->tableName( $table );
1658 $opts = $this->makeUpdateOptions( $options );
1659 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1661 if ( $conds !== [] && $conds !== '*' ) {
1662 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1665 return $this->query( $sql, $fname );
1668 public function makeList( $a, $mode = LIST_COMMA
) {
1669 if ( !is_array( $a ) ) {
1670 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1676 foreach ( $a as $field => $value ) {
1678 if ( $mode == LIST_AND
) {
1680 } elseif ( $mode == LIST_OR
) {
1689 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1690 $list .= "($value)";
1691 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1693 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1694 // Remove null from array to be handled separately if found
1695 $includeNull = false;
1696 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1697 $includeNull = true;
1698 unset( $value[$nullKey] );
1700 if ( count( $value ) == 0 && !$includeNull ) {
1701 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1702 } elseif ( count( $value ) == 0 ) {
1703 // only check if $field is null
1704 $list .= "$field IS NULL";
1706 // IN clause contains at least one valid element
1707 if ( $includeNull ) {
1708 // Group subconditions to ensure correct precedence
1711 if ( count( $value ) == 1 ) {
1712 // Special-case single values, as IN isn't terribly efficient
1713 // Don't necessarily assume the single key is 0; we don't
1714 // enforce linear numeric ordering on other arrays here.
1715 $value = array_values( $value )[0];
1716 $list .= $field . " = " . $this->addQuotes( $value );
1718 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1720 // if null present in array, append IS NULL
1721 if ( $includeNull ) {
1722 $list .= " OR $field IS NULL)";
1725 } elseif ( $value === null ) {
1726 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1727 $list .= "$field IS ";
1728 } elseif ( $mode == LIST_SET
) {
1729 $list .= "$field = ";
1733 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1734 $list .= "$field = ";
1736 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1743 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1746 foreach ( $data as $base => $sub ) {
1747 if ( count( $sub ) ) {
1748 $conds[] = $this->makeList(
1749 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1755 return $this->makeList( $conds, LIST_OR
);
1757 // Nothing to search for...
1763 * Return aggregated value alias
1765 * @param array $valuedata
1766 * @param string $valuename
1770 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1774 public function bitNot( $field ) {
1778 public function bitAnd( $fieldLeft, $fieldRight ) {
1779 return "($fieldLeft & $fieldRight)";
1782 public function bitOr( $fieldLeft, $fieldRight ) {
1783 return "($fieldLeft | $fieldRight)";
1786 public function buildConcat( $stringList ) {
1787 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1790 public function buildGroupConcatField(
1791 $delim, $table, $field, $conds = '', $join_conds = []
1793 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1795 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1799 * @param string $field Field or column to cast
1803 public function buildStringCast( $field ) {
1807 public function selectDB( $db ) {
1808 # Stub. Shouldn't cause serious problems if it's not overridden, but
1809 # if your database engine supports a concept similar to MySQL's
1810 # databases you may as well.
1811 $this->mDBname
= $db;
1816 public function getDBname() {
1817 return $this->mDBname
;
1820 public function getServer() {
1821 return $this->mServer
;
1825 * Format a table name ready for use in constructing an SQL query
1827 * This does two important things: it quotes the table names to clean them up,
1828 * and it adds a table prefix if only given a table name with no quotes.
1830 * All functions of this object which require a table name call this function
1831 * themselves. Pass the canonical name to such functions. This is only needed
1832 * when calling query() directly.
1834 * @note This function does not sanitize user input. It is not safe to use
1835 * this function to escape user input.
1836 * @param string $name Database table name
1837 * @param string $format One of:
1838 * quoted - Automatically pass the table name through addIdentifierQuotes()
1839 * so that it can be used in a query.
1840 * raw - Do not add identifier quotes to the table name
1841 * @return string Full database name
1843 public function tableName( $name, $format = 'quoted' ) {
1844 # Skip the entire process when we have a string quoted on both ends.
1845 # Note that we check the end so that we will still quote any use of
1846 # use of `database`.table. But won't break things if someone wants
1847 # to query a database table with a dot in the name.
1848 if ( $this->isQuotedIdentifier( $name ) ) {
1852 # Lets test for any bits of text that should never show up in a table
1853 # name. Basically anything like JOIN or ON which are actually part of
1854 # SQL queries, but may end up inside of the table value to combine
1855 # sql. Such as how the API is doing.
1856 # Note that we use a whitespace test rather than a \b test to avoid
1857 # any remote case where a word like on may be inside of a table name
1858 # surrounded by symbols which may be considered word breaks.
1859 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1863 # Split database and table into proper variables.
1864 # We reverse the explode so that database.table and table both output
1865 # the correct table.
1866 $dbDetails = explode( '.', $name, 3 );
1867 if ( count( $dbDetails ) == 3 ) {
1868 list( $database, $schema, $table ) = $dbDetails;
1869 # We don't want any prefix added in this case
1871 } elseif ( count( $dbDetails ) == 2 ) {
1872 list( $database, $table ) = $dbDetails;
1873 # We don't want any prefix added in this case
1874 # In dbs that support it, $database may actually be the schema
1875 # but that doesn't affect any of the functionality here
1879 list( $table ) = $dbDetails;
1880 if ( isset( $this->tableAliases
[$table] ) ) {
1881 $database = $this->tableAliases
[$table]['dbname'];
1882 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1883 ?
$this->tableAliases
[$table]['schema']
1885 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1886 ?
$this->tableAliases
[$table]['prefix']
1887 : $this->mTablePrefix
;
1890 $schema = $this->mSchema
; # Default schema
1891 $prefix = $this->mTablePrefix
; # Default prefix
1895 # Quote $table and apply the prefix if not quoted.
1896 # $tableName might be empty if this is called from Database::replaceVars()
1897 $tableName = "{$prefix}{$table}";
1898 if ( $format == 'quoted'
1899 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1901 $tableName = $this->addIdentifierQuotes( $tableName );
1904 # Quote $schema and merge it with the table name if needed
1905 if ( strlen( $schema ) ) {
1906 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1907 $schema = $this->addIdentifierQuotes( $schema );
1909 $tableName = $schema . '.' . $tableName;
1912 # Quote $database and merge it with the table name if needed
1913 if ( $database !== null ) {
1914 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1915 $database = $this->addIdentifierQuotes( $database );
1917 $tableName = $database . '.' . $tableName;
1924 * Fetch a number of table names into an array
1925 * This is handy when you need to construct SQL for joins
1928 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1929 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1930 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1934 public function tableNames() {
1935 $inArray = func_get_args();
1938 foreach ( $inArray as $name ) {
1939 $retVal[$name] = $this->tableName( $name );
1946 * Fetch a number of table names into an zero-indexed numerical array
1947 * This is handy when you need to construct SQL for joins
1950 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1951 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1952 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1956 public function tableNamesN() {
1957 $inArray = func_get_args();
1960 foreach ( $inArray as $name ) {
1961 $retVal[] = $this->tableName( $name );
1968 * Get an aliased table name
1969 * e.g. tableName AS newTableName
1971 * @param string $name Table name, see tableName()
1972 * @param string|bool $alias Alias (optional)
1973 * @return string SQL name for aliased table. Will not alias a table to its own name
1975 public function tableNameWithAlias( $name, $alias = false ) {
1976 if ( !$alias ||
$alias == $name ) {
1977 return $this->tableName( $name );
1979 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1984 * Gets an array of aliased table names
1986 * @param array $tables [ [alias] => table ]
1987 * @return string[] See tableNameWithAlias()
1989 public function tableNamesWithAlias( $tables ) {
1991 foreach ( $tables as $alias => $table ) {
1992 if ( is_numeric( $alias ) ) {
1995 $retval[] = $this->tableNameWithAlias( $table, $alias );
2002 * Get an aliased field name
2003 * e.g. fieldName AS newFieldName
2005 * @param string $name Field name
2006 * @param string|bool $alias Alias (optional)
2007 * @return string SQL name for aliased field. Will not alias a field to its own name
2009 public function fieldNameWithAlias( $name, $alias = false ) {
2010 if ( !$alias ||
(string)$alias === (string)$name ) {
2013 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2018 * Gets an array of aliased field names
2020 * @param array $fields [ [alias] => field ]
2021 * @return string[] See fieldNameWithAlias()
2023 public function fieldNamesWithAlias( $fields ) {
2025 foreach ( $fields as $alias => $field ) {
2026 if ( is_numeric( $alias ) ) {
2029 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2036 * Get the aliased table name clause for a FROM clause
2037 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2039 * @param array $tables ( [alias] => table )
2040 * @param array $use_index Same as for select()
2041 * @param array $ignore_index Same as for select()
2042 * @param array $join_conds Same as for select()
2045 protected function tableNamesWithIndexClauseOrJOIN(
2046 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2050 $use_index = (array)$use_index;
2051 $ignore_index = (array)$ignore_index;
2052 $join_conds = (array)$join_conds;
2054 foreach ( $tables as $alias => $table ) {
2055 if ( !is_string( $alias ) ) {
2056 // No alias? Set it equal to the table name
2059 // Is there a JOIN clause for this table?
2060 if ( isset( $join_conds[$alias] ) ) {
2061 list( $joinType, $conds ) = $join_conds[$alias];
2062 $tableClause = $joinType;
2063 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2064 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2065 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2067 $tableClause .= ' ' . $use;
2070 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2071 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2072 if ( $ignore != '' ) {
2073 $tableClause .= ' ' . $ignore;
2076 $on = $this->makeList( (array)$conds, LIST_AND
);
2078 $tableClause .= ' ON (' . $on . ')';
2081 $retJOIN[] = $tableClause;
2082 } elseif ( isset( $use_index[$alias] ) ) {
2083 // Is there an INDEX clause for this table?
2084 $tableClause = $this->tableNameWithAlias( $table, $alias );
2085 $tableClause .= ' ' . $this->useIndexClause(
2086 implode( ',', (array)$use_index[$alias] )
2089 $ret[] = $tableClause;
2090 } elseif ( isset( $ignore_index[$alias] ) ) {
2091 // Is there an INDEX clause for this table?
2092 $tableClause = $this->tableNameWithAlias( $table, $alias );
2093 $tableClause .= ' ' . $this->ignoreIndexClause(
2094 implode( ',', (array)$ignore_index[$alias] )
2097 $ret[] = $tableClause;
2099 $tableClause = $this->tableNameWithAlias( $table, $alias );
2101 $ret[] = $tableClause;
2105 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2106 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2107 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2109 // Compile our final table clause
2110 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2114 * Get the name of an index in a given table.
2116 * @param string $index
2119 protected function indexName( $index ) {
2120 // Backwards-compatibility hack
2122 'ar_usertext_timestamp' => 'usertext_timestamp',
2123 'un_user_id' => 'user_id',
2124 'un_user_ip' => 'user_ip',
2127 if ( isset( $renamed[$index] ) ) {
2128 return $renamed[$index];
2134 public function addQuotes( $s ) {
2135 if ( $s instanceof Blob
) {
2138 if ( $s === null ) {
2141 # This will also quote numeric values. This should be harmless,
2142 # and protects against weird problems that occur when they really
2143 # _are_ strings such as article titles and string->number->string
2144 # conversion is not 1:1.
2145 return "'" . $this->strencode( $s ) . "'";
2150 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2151 * MySQL uses `backticks` while basically everything else uses double quotes.
2152 * Since MySQL is the odd one out here the double quotes are our generic
2153 * and we implement backticks in DatabaseMysql.
2158 public function addIdentifierQuotes( $s ) {
2159 return '"' . str_replace( '"', '""', $s ) . '"';
2163 * Returns if the given identifier looks quoted or not according to
2164 * the database convention for quoting identifiers .
2166 * @note Do not use this to determine if untrusted input is safe.
2167 * A malicious user can trick this function.
2168 * @param string $name
2171 public function isQuotedIdentifier( $name ) {
2172 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2179 protected function escapeLikeInternal( $s ) {
2180 return addcslashes( $s, '\%_' );
2183 public function buildLike() {
2184 $params = func_get_args();
2186 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2187 $params = $params[0];
2192 foreach ( $params as $value ) {
2193 if ( $value instanceof LikeMatch
) {
2194 $s .= $value->toString();
2196 $s .= $this->escapeLikeInternal( $value );
2200 return " LIKE {$this->addQuotes( $s )} ";
2203 public function anyChar() {
2204 return new LikeMatch( '_' );
2207 public function anyString() {
2208 return new LikeMatch( '%' );
2211 public function nextSequenceValue( $seqName ) {
2216 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2217 * is only needed because a) MySQL must be as efficient as possible due to
2218 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2219 * which index to pick. Anyway, other databases might have different
2220 * indexes on a given table. So don't bother overriding this unless you're
2222 * @param string $index
2225 public function useIndexClause( $index ) {
2230 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2231 * is only needed because a) MySQL must be as efficient as possible due to
2232 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2233 * which index to pick. Anyway, other databases might have different
2234 * indexes on a given table. So don't bother overriding this unless you're
2236 * @param string $index
2239 public function ignoreIndexClause( $index ) {
2243 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2244 $quotedTable = $this->tableName( $table );
2246 if ( count( $rows ) == 0 ) {
2251 if ( !is_array( reset( $rows ) ) ) {
2255 // @FXIME: this is not atomic, but a trx would break affectedRows()
2256 foreach ( $rows as $row ) {
2257 # Delete rows which collide
2258 if ( $uniqueIndexes ) {
2259 $sql = "DELETE FROM $quotedTable WHERE ";
2261 foreach ( $uniqueIndexes as $index ) {
2268 if ( is_array( $index ) ) {
2270 foreach ( $index as $col ) {
2276 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2279 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2283 $this->query( $sql, $fname );
2286 # Now insert the row
2287 $this->insert( $table, $row, $fname );
2292 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2295 * @param string $table Table name
2296 * @param array|string $rows Row(s) to insert
2297 * @param string $fname Caller function name
2299 * @return ResultWrapper
2301 protected function nativeReplace( $table, $rows, $fname ) {
2302 $table = $this->tableName( $table );
2305 if ( !is_array( reset( $rows ) ) ) {
2309 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2312 foreach ( $rows as $row ) {
2319 $sql .= '(' . $this->makeList( $row ) . ')';
2322 return $this->query( $sql, $fname );
2325 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2328 if ( !count( $rows ) ) {
2329 return true; // nothing to do
2332 if ( !is_array( reset( $rows ) ) ) {
2336 if ( count( $uniqueIndexes ) ) {
2337 $clauses = []; // list WHERE clauses that each identify a single row
2338 foreach ( $rows as $row ) {
2339 foreach ( $uniqueIndexes as $index ) {
2340 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2341 $rowKey = []; // unique key to this row
2342 foreach ( $index as $column ) {
2343 $rowKey[$column] = $row[$column];
2345 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2348 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2353 $useTrx = !$this->mTrxLevel
;
2355 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2358 # Update any existing conflicting row(s)
2359 if ( $where !== false ) {
2360 $ok = $this->update( $table, $set, $where, $fname );
2364 # Now insert any non-conflicting row(s)
2365 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2366 } catch ( Exception
$e ) {
2368 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2373 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2379 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2383 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2386 $delTable = $this->tableName( $delTable );
2387 $joinTable = $this->tableName( $joinTable );
2388 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2389 if ( $conds != '*' ) {
2390 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2394 $this->query( $sql, $fname );
2398 * Returns the size of a text field, or -1 for "unlimited"
2400 * @param string $table
2401 * @param string $field
2404 public function textFieldSize( $table, $field ) {
2405 $table = $this->tableName( $table );
2406 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2407 $res = $this->query( $sql, __METHOD__
);
2408 $row = $this->fetchObject( $res );
2412 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2422 * A string to insert into queries to show that they're low-priority, like
2423 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2424 * string and nothing bad should happen.
2426 * @return string Returns the text of the low priority option if it is
2427 * supported, or a blank string otherwise
2429 public function lowPriorityOption() {
2433 public function delete( $table, $conds, $fname = __METHOD__
) {
2435 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2438 $table = $this->tableName( $table );
2439 $sql = "DELETE FROM $table";
2441 if ( $conds != '*' ) {
2442 if ( is_array( $conds ) ) {
2443 $conds = $this->makeList( $conds, LIST_AND
);
2445 $sql .= ' WHERE ' . $conds;
2448 return $this->query( $sql, $fname );
2451 public function insertSelect(
2452 $destTable, $srcTable, $varMap, $conds,
2453 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2455 if ( $this->cliMode
) {
2456 // For massive migrations with downtime, we don't want to select everything
2457 // into memory and OOM, so do all this native on the server side if possible.
2458 return $this->nativeInsertSelect(
2469 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2470 // on only the master (without needing row-based-replication). It also makes it easy to
2471 // know how big the INSERT is going to be.
2473 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2474 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2476 $selectOptions[] = 'FOR UPDATE';
2477 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2483 foreach ( $res as $row ) {
2484 $rows[] = (array)$row;
2487 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2490 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2491 $fname = __METHOD__
,
2492 $insertOptions = [], $selectOptions = []
2494 $destTable = $this->tableName( $destTable );
2496 if ( !is_array( $insertOptions ) ) {
2497 $insertOptions = [ $insertOptions ];
2500 $insertOptions = $this->makeInsertOptions( $insertOptions );
2502 if ( !is_array( $selectOptions ) ) {
2503 $selectOptions = [ $selectOptions ];
2506 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2509 if ( is_array( $srcTable ) ) {
2510 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2512 $srcTable = $this->tableName( $srcTable );
2515 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2516 " SELECT $startOpts " . implode( ',', $varMap ) .
2517 " FROM $srcTable $useIndex $ignoreIndex ";
2519 if ( $conds != '*' ) {
2520 if ( is_array( $conds ) ) {
2521 $conds = $this->makeList( $conds, LIST_AND
);
2523 $sql .= " WHERE $conds";
2526 $sql .= " $tailOpts";
2528 return $this->query( $sql, $fname );
2532 * Construct a LIMIT query with optional offset. This is used for query
2533 * pages. The SQL should be adjusted so that only the first $limit rows
2534 * are returned. If $offset is provided as well, then the first $offset
2535 * rows should be discarded, and the next $limit rows should be returned.
2536 * If the result of the query is not ordered, then the rows to be returned
2537 * are theoretically arbitrary.
2539 * $sql is expected to be a SELECT, if that makes a difference.
2541 * The version provided by default works in MySQL and SQLite. It will very
2542 * likely need to be overridden for most other DBMSes.
2544 * @param string $sql SQL query we will append the limit too
2545 * @param int $limit The SQL limit
2546 * @param int|bool $offset The SQL offset (default false)
2547 * @throws DBUnexpectedError
2550 public function limitResult( $sql, $limit, $offset = false ) {
2551 if ( !is_numeric( $limit ) ) {
2552 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2555 return "$sql LIMIT "
2556 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2560 public function unionSupportsOrderAndLimit() {
2561 return true; // True for almost every DB supported
2564 public function unionQueries( $sqls, $all ) {
2565 $glue = $all ?
') UNION ALL (' : ') UNION (';
2567 return '(' . implode( $glue, $sqls ) . ')';
2570 public function conditional( $cond, $trueVal, $falseVal ) {
2571 if ( is_array( $cond ) ) {
2572 $cond = $this->makeList( $cond, LIST_AND
);
2575 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2578 public function strreplace( $orig, $old, $new ) {
2579 return "REPLACE({$orig}, {$old}, {$new})";
2582 public function getServerUptime() {
2586 public function wasDeadlock() {
2590 public function wasLockTimeout() {
2594 public function wasErrorReissuable() {
2598 public function wasReadOnlyError() {
2603 * Determines if the given query error was a connection drop
2606 * @param integer|string $errno
2609 public function wasConnectionError( $errno ) {
2614 * Perform a deadlock-prone transaction.
2616 * This function invokes a callback function to perform a set of write
2617 * queries. If a deadlock occurs during the processing, the transaction
2618 * will be rolled back and the callback function will be called again.
2620 * Avoid using this method outside of Job or Maintenance classes.
2623 * $dbw->deadlockLoop( callback, ... );
2625 * Extra arguments are passed through to the specified callback function.
2626 * This method requires that no transactions are already active to avoid
2627 * causing premature commits or exceptions.
2629 * Returns whatever the callback function returned on its successful,
2630 * iteration, or false on error, for example if the retry limit was
2634 * @throws DBUnexpectedError
2637 public function deadlockLoop() {
2638 $args = func_get_args();
2639 $function = array_shift( $args );
2640 $tries = self
::DEADLOCK_TRIES
;
2642 $this->begin( __METHOD__
);
2645 /** @var Exception $e */
2649 $retVal = call_user_func_array( $function, $args );
2651 } catch ( DBQueryError
$e ) {
2652 if ( $this->wasDeadlock() ) {
2653 // Retry after a randomized delay
2654 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2656 // Throw the error back up
2660 } while ( --$tries > 0 );
2662 if ( $tries <= 0 ) {
2663 // Too many deadlocks; give up
2664 $this->rollback( __METHOD__
);
2667 $this->commit( __METHOD__
);
2673 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2674 # Real waits are implemented in the subclass.
2678 public function getSlavePos() {
2683 public function getMasterPos() {
2688 public function serverIsReadOnly() {
2692 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2693 if ( !$this->mTrxLevel
) {
2694 throw new DBUnexpectedError( $this, "No transaction is active." );
2696 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2699 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2700 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2701 if ( !$this->mTrxLevel
) {
2702 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2706 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2707 if ( $this->mTrxLevel
) {
2708 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2710 // If no transaction is active, then make one for this callback
2711 $this->startAtomic( __METHOD__
);
2713 call_user_func( $callback );
2714 $this->endAtomic( __METHOD__
);
2715 } catch ( Exception
$e ) {
2716 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2722 final public function setTransactionListener( $name, callable
$callback = null ) {
2724 $this->mTrxRecurringCallbacks
[$name] = $callback;
2726 unset( $this->mTrxRecurringCallbacks
[$name] );
2731 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2733 * This method should not be used outside of Database/LoadBalancer
2735 * @param bool $suppress
2738 final public function setTrxEndCallbackSuppression( $suppress ) {
2739 $this->mTrxEndCallbacksSuppressed
= $suppress;
2743 * Actually run and consume any "on transaction idle/resolution" callbacks.
2745 * This method should not be used outside of Database/LoadBalancer
2747 * @param integer $trigger IDatabase::TRIGGER_* constant
2751 public function runOnTransactionIdleCallbacks( $trigger ) {
2752 if ( $this->mTrxEndCallbacksSuppressed
) {
2756 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2757 /** @var Exception $e */
2758 $e = null; // first exception
2759 do { // callbacks may add callbacks :)
2760 $callbacks = array_merge(
2761 $this->mTrxIdleCallbacks
,
2762 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2764 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2765 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2766 foreach ( $callbacks as $callback ) {
2768 list( $phpCallback ) = $callback;
2769 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2770 call_user_func_array( $phpCallback, [ $trigger ] );
2772 $this->setFlag( DBO_TRX
); // restore automatic begin()
2774 $this->clearFlag( DBO_TRX
); // restore auto-commit
2776 } catch ( Exception
$ex ) {
2777 call_user_func( $this->errorLogger
, $ex );
2779 // Some callbacks may use startAtomic/endAtomic, so make sure
2780 // their transactions are ended so other callbacks don't fail
2781 if ( $this->trxLevel() ) {
2782 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2786 } while ( count( $this->mTrxIdleCallbacks
) );
2788 if ( $e instanceof Exception
) {
2789 throw $e; // re-throw any first exception
2794 * Actually run and consume any "on transaction pre-commit" callbacks.
2796 * This method should not be used outside of Database/LoadBalancer
2801 public function runOnTransactionPreCommitCallbacks() {
2802 $e = null; // first exception
2803 do { // callbacks may add callbacks :)
2804 $callbacks = $this->mTrxPreCommitCallbacks
;
2805 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2806 foreach ( $callbacks as $callback ) {
2808 list( $phpCallback ) = $callback;
2809 call_user_func( $phpCallback );
2810 } catch ( Exception
$ex ) {
2811 call_user_func( $this->errorLogger
, $ex );
2815 } while ( count( $this->mTrxPreCommitCallbacks
) );
2817 if ( $e instanceof Exception
) {
2818 throw $e; // re-throw any first exception
2823 * Actually run any "transaction listener" callbacks.
2825 * This method should not be used outside of Database/LoadBalancer
2827 * @param integer $trigger IDatabase::TRIGGER_* constant
2831 public function runTransactionListenerCallbacks( $trigger ) {
2832 if ( $this->mTrxEndCallbacksSuppressed
) {
2836 /** @var Exception $e */
2837 $e = null; // first exception
2839 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2841 $phpCallback( $trigger, $this );
2842 } catch ( Exception
$ex ) {
2843 call_user_func( $this->errorLogger
, $ex );
2848 if ( $e instanceof Exception
) {
2849 throw $e; // re-throw any first exception
2853 final public function startAtomic( $fname = __METHOD__
) {
2854 if ( !$this->mTrxLevel
) {
2855 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2856 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2857 // in all changes being in one transaction to keep requests transactional.
2858 if ( !$this->getFlag( DBO_TRX
) ) {
2859 $this->mTrxAutomaticAtomic
= true;
2863 $this->mTrxAtomicLevels
[] = $fname;
2866 final public function endAtomic( $fname = __METHOD__
) {
2867 if ( !$this->mTrxLevel
) {
2868 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2870 if ( !$this->mTrxAtomicLevels ||
2871 array_pop( $this->mTrxAtomicLevels
) !== $fname
2873 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2876 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2877 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2881 final public function doAtomicSection( $fname, callable
$callback ) {
2882 $this->startAtomic( $fname );
2884 $res = call_user_func_array( $callback, [ $this, $fname ] );
2885 } catch ( Exception
$e ) {
2886 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2889 $this->endAtomic( $fname );
2894 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2895 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2896 if ( $this->mTrxLevel
) {
2897 if ( $this->mTrxAtomicLevels
) {
2898 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2899 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2900 throw new DBUnexpectedError( $this, $msg );
2901 } elseif ( !$this->mTrxAutomatic
) {
2902 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2903 throw new DBUnexpectedError( $this, $msg );
2905 // @TODO: make this an exception at some point
2906 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2907 $this->queryLogger
->error( $msg );
2908 return; // join the main transaction set
2910 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2911 // @TODO: make this an exception at some point
2912 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2913 $this->queryLogger
->error( $msg );
2914 return; // let any writes be in the main transaction
2917 // Avoid fatals if close() was called
2918 $this->assertOpen();
2920 $this->doBegin( $fname );
2921 $this->mTrxTimestamp
= microtime( true );
2922 $this->mTrxFname
= $fname;
2923 $this->mTrxDoneWrites
= false;
2924 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2925 $this->mTrxAutomaticAtomic
= false;
2926 $this->mTrxAtomicLevels
= [];
2927 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2928 $this->mTrxWriteDuration
= 0.0;
2929 $this->mTrxWriteQueryCount
= 0;
2930 $this->mTrxWriteAdjDuration
= 0.0;
2931 $this->mTrxWriteAdjQueryCount
= 0;
2932 $this->mTrxWriteCallers
= [];
2933 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2934 // Get an estimate of the replica DB lag before then, treating estimate staleness
2935 // as lag itself just to be safe
2936 $status = $this->getApproximateLagStatus();
2937 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2941 * Issues the BEGIN command to the database server.
2943 * @see DatabaseBase::begin()
2944 * @param string $fname
2946 protected function doBegin( $fname ) {
2947 $this->query( 'BEGIN', $fname );
2948 $this->mTrxLevel
= 1;
2951 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2952 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2953 // There are still atomic sections open. This cannot be ignored
2954 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2955 throw new DBUnexpectedError(
2957 "$fname: Got COMMIT while atomic sections $levels are still open."
2961 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2962 if ( !$this->mTrxLevel
) {
2963 return; // nothing to do
2964 } elseif ( !$this->mTrxAutomatic
) {
2965 throw new DBUnexpectedError(
2967 "$fname: Flushing an explicit transaction, getting out of sync."
2971 if ( !$this->mTrxLevel
) {
2972 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2973 return; // nothing to do
2974 } elseif ( $this->mTrxAutomatic
) {
2975 // @TODO: make this an exception at some point
2976 $msg = "$fname: Explicit commit of implicit transaction.";
2977 $this->queryLogger
->error( $msg );
2978 return; // wait for the main transaction set commit round
2982 // Avoid fatals if close() was called
2983 $this->assertOpen();
2985 $this->runOnTransactionPreCommitCallbacks();
2986 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2987 $this->doCommit( $fname );
2988 if ( $this->mTrxDoneWrites
) {
2989 $this->mDoneWrites
= microtime( true );
2990 $this->trxProfiler
->transactionWritingOut(
2991 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2994 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2995 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2999 * Issues the COMMIT command to the database server.
3001 * @see DatabaseBase::commit()
3002 * @param string $fname
3004 protected function doCommit( $fname ) {
3005 if ( $this->mTrxLevel
) {
3006 $this->query( 'COMMIT', $fname );
3007 $this->mTrxLevel
= 0;
3011 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3012 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3013 if ( !$this->mTrxLevel
) {
3014 return; // nothing to do
3017 if ( !$this->mTrxLevel
) {
3018 $this->queryLogger
->error(
3019 "$fname: No transaction to rollback, something got out of sync." );
3020 return; // nothing to do
3021 } elseif ( $this->getFlag( DBO_TRX
) ) {
3022 throw new DBUnexpectedError(
3024 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3029 // Avoid fatals if close() was called
3030 $this->assertOpen();
3032 $this->doRollback( $fname );
3033 $this->mTrxAtomicLevels
= [];
3034 if ( $this->mTrxDoneWrites
) {
3035 $this->trxProfiler
->transactionWritingOut(
3036 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3039 $this->mTrxIdleCallbacks
= []; // clear
3040 $this->mTrxPreCommitCallbacks
= []; // clear
3041 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3042 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3046 * Issues the ROLLBACK command to the database server.
3048 * @see DatabaseBase::rollback()
3049 * @param string $fname
3051 protected function doRollback( $fname ) {
3052 if ( $this->mTrxLevel
) {
3053 # Disconnects cause rollback anyway, so ignore those errors
3054 $ignoreErrors = true;
3055 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3056 $this->mTrxLevel
= 0;
3060 public function flushSnapshot( $fname = __METHOD__
) {
3061 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3062 // This only flushes transactions to clear snapshots, not to write data
3063 throw new DBUnexpectedError(
3065 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3069 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3072 public function explicitTrxActive() {
3073 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3077 * Creates a new table with structure copied from existing table
3078 * Note that unlike most database abstraction functions, this function does not
3079 * automatically append database prefix, because it works at a lower
3080 * abstraction level.
3081 * The table names passed to this function shall not be quoted (this
3082 * function calls addIdentifierQuotes when needed).
3084 * @param string $oldName Name of table whose structure should be copied
3085 * @param string $newName Name of table to be created
3086 * @param bool $temporary Whether the new table should be temporary
3087 * @param string $fname Calling function name
3088 * @throws RuntimeException
3089 * @return bool True if operation was successful
3091 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3094 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3097 function listTables( $prefix = null, $fname = __METHOD__
) {
3098 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3102 * Reset the views process cache set by listViews()
3105 final public function clearViewsCache() {
3106 $this->allViews
= null;
3110 * Lists all the VIEWs in the database
3112 * For caching purposes the list of all views should be stored in
3113 * $this->allViews. The process cache can be cleared with clearViewsCache()
3115 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3116 * @param string $fname Name of calling function
3117 * @throws RuntimeException
3121 public function listViews( $prefix = null, $fname = __METHOD__
) {
3122 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3126 * Differentiates between a TABLE and a VIEW
3128 * @param string $name Name of the database-structure to test.
3129 * @throws RuntimeException
3133 public function isView( $name ) {
3134 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3137 public function timestamp( $ts = 0 ) {
3138 return wfTimestamp( TS_MW
, $ts );
3141 public function timestampOrNull( $ts = null ) {
3142 if ( is_null( $ts ) ) {
3145 return $this->timestamp( $ts );
3150 * Take the result from a query, and wrap it in a ResultWrapper if
3151 * necessary. Boolean values are passed through as is, to indicate success
3152 * of write queries or failure.
3154 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3155 * resource, and it was necessary to call this function to convert it to
3156 * a wrapper. Nowadays, raw database objects are never exposed to external
3157 * callers, so this is unnecessary in external code.
3159 * @param bool|ResultWrapper|resource|object $result
3160 * @return bool|ResultWrapper
3162 protected function resultObject( $result ) {
3165 } elseif ( $result instanceof ResultWrapper
) {
3167 } elseif ( $result === true ) {
3168 // Successful write query
3171 return new ResultWrapper( $this, $result );
3175 public function ping( &$rtt = null ) {
3176 // Avoid hitting the server if it was hit recently
3177 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3178 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3179 $rtt = $this->mRTTEstimate
;
3180 return true; // don't care about $rtt
3184 // This will reconnect if possible or return false if not
3185 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3186 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3187 $this->restoreFlags( self
::RESTORE_PRIOR
);
3190 $rtt = $this->mRTTEstimate
;
3199 protected function reconnect() {
3200 $this->closeConnection();
3201 $this->mOpened
= false;
3202 $this->mConn
= false;
3204 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3205 $this->lastPing
= microtime( true );
3207 } catch ( DBConnectionError
$e ) {
3214 public function getSessionLagStatus() {
3215 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3219 * Get the replica DB lag when the current transaction started
3221 * This is useful when transactions might use snapshot isolation
3222 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3223 * is this lag plus transaction duration. If they don't, it is still
3224 * safe to be pessimistic. This returns null if there is no transaction.
3226 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3229 public function getTransactionLagStatus() {
3230 return $this->mTrxLevel
3231 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3236 * Get a replica DB lag estimate for this server
3238 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3241 public function getApproximateLagStatus() {
3243 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3244 'since' => microtime( true )
3249 * Merge the result of getSessionLagStatus() for several DBs
3250 * using the most pessimistic values to estimate the lag of
3251 * any data derived from them in combination
3253 * This is information is useful for caching modules
3255 * @see WANObjectCache::set()
3256 * @see WANObjectCache::getWithSetCallback()
3258 * @param IDatabase $db1
3259 * @param IDatabase ...
3260 * @return array Map of values:
3261 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3262 * - since: oldest UNIX timestamp of any of the DB lag estimates
3263 * - pending: whether any of the DBs have uncommitted changes
3266 public static function getCacheSetOptions( IDatabase
$db1 ) {
3267 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3268 foreach ( func_get_args() as $db ) {
3269 /** @var IDatabase $db */
3270 $status = $db->getSessionLagStatus();
3271 if ( $status['lag'] === false ) {
3272 $res['lag'] = false;
3273 } elseif ( $res['lag'] !== false ) {
3274 $res['lag'] = max( $res['lag'], $status['lag'] );
3276 $res['since'] = min( $res['since'], $status['since'] );
3277 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3283 public function getLag() {
3287 function maxListLen() {
3291 public function encodeBlob( $b ) {
3295 public function decodeBlob( $b ) {
3296 if ( $b instanceof Blob
) {
3302 public function setSessionOptions( array $options ) {
3306 * Read and execute SQL commands from a file.
3308 * Returns true on success, error string or exception on failure (depending
3309 * on object's error ignore settings).
3311 * @param string $filename File name to open
3312 * @param bool|callable $lineCallback Optional function called before reading each line
3313 * @param bool|callable $resultCallback Optional function called for each MySQL result
3314 * @param bool|string $fname Calling function name or false if name should be
3315 * generated dynamically using $filename
3316 * @param bool|callable $inputCallback Optional function called for each
3317 * complete line sent
3318 * @return bool|string
3321 public function sourceFile(
3322 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3324 MediaWiki\
suppressWarnings();
3325 $fp = fopen( $filename, 'r' );
3326 MediaWiki\restoreWarnings
();
3328 if ( false === $fp ) {
3329 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3333 $fname = __METHOD__
. "( $filename )";
3337 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3338 } catch ( Exception
$e ) {
3348 public function setSchemaVars( $vars ) {
3349 $this->mSchemaVars
= $vars;
3353 * Read and execute commands from an open file handle.
3355 * Returns true on success, error string or exception on failure (depending
3356 * on object's error ignore settings).
3358 * @param resource $fp File handle
3359 * @param bool|callable $lineCallback Optional function called before reading each query
3360 * @param bool|callable $resultCallback Optional function called for each MySQL result
3361 * @param string $fname Calling function name
3362 * @param bool|callable $inputCallback Optional function called for each complete query sent
3363 * @return bool|string
3365 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3366 $fname = __METHOD__
, $inputCallback = false
3370 while ( !feof( $fp ) ) {
3371 if ( $lineCallback ) {
3372 call_user_func( $lineCallback );
3375 $line = trim( fgets( $fp ) );
3377 if ( $line == '' ) {
3381 if ( '-' == $line[0] && '-' == $line[1] ) {
3389 $done = $this->streamStatementEnd( $cmd, $line );
3393 if ( $done ||
feof( $fp ) ) {
3394 $cmd = $this->replaceVars( $cmd );
3396 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3397 $res = $this->query( $cmd, $fname );
3399 if ( $resultCallback ) {
3400 call_user_func( $resultCallback, $res, $this );
3403 if ( false === $res ) {
3404 $err = $this->lastError();
3406 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3417 * Called by sourceStream() to check if we've reached a statement end
3419 * @param string $sql SQL assembled so far
3420 * @param string $newLine New line about to be added to $sql
3421 * @return bool Whether $newLine contains end of the statement
3423 public function streamStatementEnd( &$sql, &$newLine ) {
3424 if ( $this->delimiter
) {
3426 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3427 if ( $newLine != $prev ) {
3436 * Database independent variable replacement. Replaces a set of variables
3437 * in an SQL statement with their contents as given by $this->getSchemaVars().
3439 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3441 * - '{$var}' should be used for text and is passed through the database's
3443 * - `{$var}` should be used for identifiers (e.g. table and database names).
3444 * It is passed through the database's addIdentifierQuotes method which
3445 * can be overridden if the database uses something other than backticks.
3446 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3447 * database's tableName method.
3448 * - / *i* / passes the name that follows through the database's indexName method.
3449 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3450 * its use should be avoided. In 1.24 and older, string encoding was applied.
3452 * @param string $ins SQL statement to replace variables in
3453 * @return string The new SQL statement with variables replaced
3455 protected function replaceVars( $ins ) {
3456 $vars = $this->getSchemaVars();
3457 return preg_replace_callback(
3459 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3460 \'\{\$ (\w+) }\' | # 3. addQuotes
3461 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3462 /\*\$ (\w+) \*/ # 5. leave unencoded
3464 function ( $m ) use ( $vars ) {
3465 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3466 // check for both nonexistent keys *and* the empty string.
3467 if ( isset( $m[1] ) && $m[1] !== '' ) {
3468 if ( $m[1] === 'i' ) {
3469 return $this->indexName( $m[2] );
3471 return $this->tableName( $m[2] );
3473 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3474 return $this->addQuotes( $vars[$m[3]] );
3475 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3476 return $this->addIdentifierQuotes( $vars[$m[4]] );
3477 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3478 return $vars[$m[5]];
3488 * Get schema variables. If none have been set via setSchemaVars(), then
3489 * use some defaults from the current object.
3493 protected function getSchemaVars() {
3494 if ( $this->mSchemaVars
) {
3495 return $this->mSchemaVars
;
3497 return $this->getDefaultSchemaVars();
3502 * Get schema variables to use if none have been set via setSchemaVars().
3504 * Override this in derived classes to provide variables for tables.sql
3505 * and SQL patch files.
3509 protected function getDefaultSchemaVars() {
3513 public function lockIsFree( $lockName, $method ) {
3517 public function lock( $lockName, $method, $timeout = 5 ) {
3518 $this->mNamedLocksHeld
[$lockName] = 1;
3523 public function unlock( $lockName, $method ) {
3524 unset( $this->mNamedLocksHeld
[$lockName] );
3529 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3530 if ( $this->writesOrCallbacksPending() ) {
3531 // This only flushes transactions to clear snapshots, not to write data
3532 throw new DBUnexpectedError(
3534 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3538 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3542 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3543 if ( $this->trxLevel() ) {
3544 // There is a good chance an exception was thrown, causing any early return
3545 // from the caller. Let any error handler get a chance to issue rollback().
3546 // If there isn't one, let the error bubble up and trigger server-side rollback.
3547 $this->onTransactionResolution(
3548 function () use ( $lockKey, $fname ) {
3549 $this->unlock( $lockKey, $fname );
3554 $this->unlock( $lockKey, $fname );
3558 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3563 public function namedLocksEnqueue() {
3568 * Lock specific tables
3570 * @param array $read Array of tables to lock for read access
3571 * @param array $write Array of tables to lock for write access
3572 * @param string $method Name of caller
3573 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3576 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3581 * Unlock specific tables
3583 * @param string $method The caller
3586 public function unlockTables( $method ) {
3592 * @param string $tableName
3593 * @param string $fName
3594 * @return bool|ResultWrapper
3597 public function dropTable( $tableName, $fName = __METHOD__
) {
3598 if ( !$this->tableExists( $tableName, $fName ) ) {
3601 $sql = "DROP TABLE " . $this->tableName( $tableName );
3602 if ( $this->cascadingDeletes() ) {
3606 return $this->query( $sql, $fName );
3610 * Get search engine class. All subclasses of this need to implement this
3611 * if they wish to use searching.
3615 public function getSearchEngine() {
3616 return 'SearchEngineDummy';
3619 public function getInfinity() {
3623 public function encodeExpiry( $expiry ) {
3624 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3625 ?
$this->getInfinity()
3626 : $this->timestamp( $expiry );
3629 public function decodeExpiry( $expiry, $format = TS_MW
) {
3630 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3632 : wfTimestamp( $format, $expiry );
3635 public function setBigSelects( $value = true ) {
3639 public function isReadOnly() {
3640 return ( $this->getReadOnlyReason() !== false );
3644 * @return string|bool Reason this DB is read-only or false if it is not
3646 protected function getReadOnlyReason() {
3647 $reason = $this->getLBInfo( 'readOnlyReason' );
3649 return is_string( $reason ) ?
$reason : false;
3652 public function setTableAliases( array $aliases ) {
3653 $this->tableAliases
= $aliases;
3660 public function __toString() {
3661 return (string)$this->mConn
;
3665 * Run a few simple sanity checks
3667 public function __destruct() {
3668 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3669 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3671 $danglingCallbacks = array_merge(
3672 $this->mTrxIdleCallbacks
,
3673 $this->mTrxPreCommitCallbacks
,
3674 $this->mTrxEndCallbacks
3676 if ( $danglingCallbacks ) {
3678 foreach ( $danglingCallbacks as $callbackInfo ) {
3679 $callers[] = $callbackInfo[1];
3681 $callers = implode( ', ', $callers );
3682 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3690 abstract class Database
extends DatabaseBase
{
3691 // B/C until nothing type hints for DatabaseBase
3692 // @TODO: finish renaming DatabaseBase => Database