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|null Previous value of the flag
415 public function debug( $debug = null ) {
416 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
419 public function bufferResults( $buffer = null ) {
420 if ( is_null( $buffer ) ) {
421 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
423 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
428 * Turns on (false) or off (true) the automatic generation and sending
429 * of a "we're sorry, but there has been a database error" page on
430 * database errors. Default is on (false). When turned off, the
431 * code should use lastErrno() and lastError() to handle the
432 * situation as appropriate.
434 * Do not use this function outside of the Database classes.
436 * @param null|bool $ignoreErrors
437 * @return bool The previous value of the flag.
439 protected function ignoreErrors( $ignoreErrors = null ) {
440 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
443 public function trxLevel() {
444 return $this->mTrxLevel
;
447 public function trxTimestamp() {
448 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
451 public function tablePrefix( $prefix = null ) {
452 return wfSetVar( $this->mTablePrefix
, $prefix );
455 public function dbSchema( $schema = null ) {
456 return wfSetVar( $this->mSchema
, $schema );
460 * Set the filehandle to copy write statements to.
462 * @param resource $fh File handle
464 public function setFileHandle( $fh ) {
465 $this->fileHandle
= $fh;
468 public function getLBInfo( $name = null ) {
469 if ( is_null( $name ) ) {
470 return $this->mLBInfo
;
472 if ( array_key_exists( $name, $this->mLBInfo
) ) {
473 return $this->mLBInfo
[$name];
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo
= $name;
484 $this->mLBInfo
[$name] = $value;
488 public function setLazyMasterHandle( IDatabase
$conn ) {
489 $this->lazyMasterHandle
= $conn;
493 * @return IDatabase|null
494 * @see setLazyMasterHandle()
497 public function getLazyMasterHandle() {
498 return $this->lazyMasterHandle
;
502 * @param TransactionProfiler $profiler
505 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
506 $this->trxProfiler
= $profiler;
510 * Returns true if this database supports (and uses) cascading deletes
514 public function cascadingDeletes() {
519 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
523 public function cleanupTriggers() {
528 * Returns true if this database is strict about what can be put into an IP field.
529 * Specifically, it uses a NULL value instead of an empty string.
533 public function strictIPs() {
538 * Returns true if this database uses timestamps rather than integers
542 public function realTimestamps() {
546 public function implicitGroupby() {
550 public function implicitOrderby() {
555 * Returns true if this database can do a native search on IP columns
556 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
560 public function searchableIPs() {
565 * Returns true if this database can use functional indexes
569 public function functionalIndexes() {
573 public function lastQuery() {
574 return $this->mLastQuery
;
577 public function doneWrites() {
578 return (bool)$this->mDoneWrites
;
581 public function lastDoneWrites() {
582 return $this->mDoneWrites ?
: false;
585 public function writesPending() {
586 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
589 public function writesOrCallbacksPending() {
590 return $this->mTrxLevel
&& (
591 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
595 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
596 if ( !$this->mTrxLevel
) {
598 } elseif ( !$this->mTrxDoneWrites
) {
603 case self
::ESTIMATE_DB_APPLY
:
605 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
606 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
607 // For omitted queries, make them count as something at least
608 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
609 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
612 default: // everything
613 return $this->mTrxWriteDuration
;
617 public function pendingWriteCallers() {
618 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
621 protected function pendingWriteAndCallbackCallers() {
622 if ( !$this->mTrxLevel
) {
626 $fnames = $this->mTrxWriteCallers
;
628 $this->mTrxIdleCallbacks
,
629 $this->mTrxPreCommitCallbacks
,
630 $this->mTrxEndCallbacks
632 foreach ( $callbacks as $callback ) {
633 $fnames[] = $callback[1];
640 public function isOpen() {
641 return $this->mOpened
;
644 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
645 if ( $remember === self
::REMEMBER_PRIOR
) {
646 array_push( $this->priorFlags
, $this->mFlags
);
648 $this->mFlags |
= $flag;
651 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
652 if ( $remember === self
::REMEMBER_PRIOR
) {
653 array_push( $this->priorFlags
, $this->mFlags
);
655 $this->mFlags
&= ~
$flag;
658 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
659 if ( !$this->priorFlags
) {
663 if ( $state === self
::RESTORE_INITIAL
) {
664 $this->mFlags
= reset( $this->priorFlags
);
665 $this->priorFlags
= [];
667 $this->mFlags
= array_pop( $this->priorFlags
);
671 public function getFlag( $flag ) {
672 return !!( $this->mFlags
& $flag );
675 public function getProperty( $name ) {
679 public function getWikiID() {
680 if ( $this->mTablePrefix
) {
681 return "{$this->mDBname}-{$this->mTablePrefix}";
683 return $this->mDBname
;
688 * Get information about an index into an object
689 * @param string $table Table name
690 * @param string $index Index name
691 * @param string $fname Calling function name
692 * @return mixed Database-specific index description class or false if the index does not exist
694 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
697 * Wrapper for addslashes()
699 * @param string $s String to be slashed.
700 * @return string Slashed string.
702 abstract function strencode( $s );
705 * Called by serialize. Throw an exception when DB connection is serialized.
706 * This causes problems on some database engines because the connection is
707 * not restored on unserialize.
709 public function __sleep() {
710 throw new RuntimeException( 'Database serialization may cause problems, since ' .
711 'the connection is not restored on wakeup.' );
714 protected function installErrorHandler() {
715 $this->mPHPError
= false;
716 $this->htmlErrors
= ini_set( 'html_errors', '0' );
717 set_error_handler( [ $this, 'connectionerrorLogger' ] );
721 * @return bool|string
723 protected function restoreErrorHandler() {
724 restore_error_handler();
725 if ( $this->htmlErrors
!== false ) {
726 ini_set( 'html_errors', $this->htmlErrors
);
728 if ( $this->mPHPError
) {
729 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
730 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
740 * @param string $errstr
742 public function connectionerrorLogger( $errno, $errstr ) {
743 $this->mPHPError
= $errstr;
747 * Create a log context to pass to PSR logging functions.
749 * @param array $extras Additional data to add to context
752 protected function getLogContext( array $extras = [] ) {
755 'db_server' => $this->mServer
,
756 'db_name' => $this->mDBname
,
757 'db_user' => $this->mUser
,
763 public function close() {
764 if ( $this->mConn
) {
765 if ( $this->trxLevel() ) {
766 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
769 $closed = $this->closeConnection();
770 $this->mConn
= false;
771 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
772 throw new RuntimeException( "Transaction callbacks still pending." );
776 $this->mOpened
= false;
782 * Make sure isOpen() returns true as a sanity check
784 * @throws DBUnexpectedError
786 protected function assertOpen() {
787 if ( !$this->isOpen() ) {
788 throw new DBUnexpectedError( $this, "DB connection was already closed." );
793 * Closes underlying database connection
795 * @return bool Whether connection was closed successfully
797 abstract protected function closeConnection();
799 function reportConnectionError( $error = 'Unknown error' ) {
800 $myError = $this->lastError();
806 throw new DBConnectionError( $this, $error );
810 * The DBMS-dependent part of query()
812 * @param string $sql SQL query.
813 * @return ResultWrapper|bool Result object to feed to fetchObject,
814 * fetchRow, ...; or false on failure
816 abstract protected function doQuery( $sql );
819 * Determine whether a query writes to the DB.
820 * Should return true if unsure.
825 protected function isWriteQuery( $sql ) {
827 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
832 * @return string|null
834 protected function getQueryVerb( $sql ) {
835 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
839 * Determine whether a SQL statement is sensitive to isolation level.
840 * A SQL statement is considered transactable if its result could vary
841 * depending on the transaction isolation level. Operational commands
842 * such as 'SET' and 'SHOW' are not considered to be transactable.
847 protected function isTransactableQuery( $sql ) {
848 $verb = $this->getQueryVerb( $sql );
849 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
852 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
855 $priorWritesPending = $this->writesOrCallbacksPending();
856 $this->mLastQuery
= $sql;
858 $isWrite = $this->isWriteQuery( $sql );
860 $reason = $this->getReadOnlyReason();
861 if ( $reason !== false ) {
862 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
864 # Set a flag indicating that writes have been done
865 $this->mDoneWrites
= microtime( true );
868 # Add a comment for easy SHOW PROCESSLIST interpretation
869 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
870 $userName = $wgUser->getName();
871 if ( mb_strlen( $userName ) > 15 ) {
872 $userName = mb_substr( $userName, 0, 15 ) . '...';
874 $userName = str_replace( '/', '', $userName );
879 // Add trace comment to the begin of the sql string, right after the operator.
880 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
881 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
883 # Start implicit transactions that wrap the request if DBO_TRX is enabled
884 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
885 && $this->isTransactableQuery( $sql )
887 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
888 $this->mTrxAutomatic
= true;
891 # Keep track of whether the transaction has write queries pending
892 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
893 $this->mTrxDoneWrites
= true;
894 $this->trxProfiler
->transactionWritingIn(
895 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
898 if ( $this->debug() ) {
899 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
902 # Avoid fatals if close() was called
905 # Send the query to the server
906 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
908 # Try reconnecting if the connection was lost
909 if ( false === $ret && $this->wasErrorReissuable() ) {
910 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
911 # Stash the last error values before anything might clear them
912 $lastError = $this->lastError();
913 $lastErrno = $this->lastErrno();
914 # Update state tracking to reflect transaction loss due to disconnection
915 $this->handleTransactionLoss();
916 if ( $this->reconnect() ) {
917 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
918 $this->connLogger
->warning( $msg );
919 $this->queryLogger
->warning(
920 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
922 if ( !$recoverable ) {
923 # Callers may catch the exception and continue to use the DB
924 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
926 # Should be safe to silently retry the query
927 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
930 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
931 $this->connLogger
->error( $msg );
935 if ( false === $ret ) {
936 # Deadlocks cause the entire transaction to abort, not just the statement.
937 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
938 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
939 if ( $this->wasDeadlock() ) {
940 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
941 $tempIgnore = false; // not recoverable
943 # Update state tracking to reflect transaction loss
944 $this->handleTransactionLoss();
947 $this->reportQueryError(
948 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
951 $res = $this->resultObject( $ret );
956 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
957 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
958 # generalizeSQL() will probably cut down the query to reasonable
959 # logging size most of the time. The substr is really just a sanity check.
961 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
963 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
966 # Include query transaction state
967 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
969 $startTime = microtime( true );
970 $this->profiler
->profileIn( $queryProf );
971 $ret = $this->doQuery( $commentedSql );
972 $this->profiler
->profileOut( $queryProf );
973 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
975 unset( $queryProfSection ); // profile out (if set)
977 if ( $ret !== false ) {
978 $this->lastPing
= $startTime;
979 if ( $isWrite && $this->mTrxLevel
) {
980 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
981 $this->mTrxWriteCallers
[] = $fname;
985 if ( $sql === self
::PING_QUERY
) {
986 $this->mRTTEstimate
= $queryRuntime;
989 $this->trxProfiler
->recordQueryCompletion(
990 $queryProf, $startTime, $isWrite, $this->affectedRows()
992 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
998 * Update the estimated run-time of a query, not counting large row lock times
1000 * LoadBalancer can be set to rollback transactions that will create huge replication
1001 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1002 * queries, like inserting a row can take a long time due to row locking. This method
1003 * uses some simple heuristics to discount those cases.
1005 * @param string $sql A SQL write query
1006 * @param float $runtime Total runtime, including RTT
1008 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1009 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1010 $indicativeOfReplicaRuntime = true;
1011 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1012 $verb = $this->getQueryVerb( $sql );
1013 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1014 if ( $verb === 'INSERT' ) {
1015 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1016 } elseif ( $verb === 'REPLACE' ) {
1017 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1021 $this->mTrxWriteDuration +
= $runtime;
1022 $this->mTrxWriteQueryCount +
= 1;
1023 if ( $indicativeOfReplicaRuntime ) {
1024 $this->mTrxWriteAdjDuration +
= $runtime;
1025 $this->mTrxWriteAdjQueryCount +
= 1;
1029 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1030 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1031 # Dropped connections also mean that named locks are automatically released.
1032 # Only allow error suppression in autocommit mode or when the lost transaction
1033 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1034 if ( $this->mNamedLocksHeld
) {
1035 return false; // possible critical section violation
1036 } elseif ( $sql === 'COMMIT' ) {
1037 return !$priorWritesPending; // nothing written anyway? (T127428)
1038 } elseif ( $sql === 'ROLLBACK' ) {
1039 return true; // transaction lost...which is also what was requested :)
1040 } elseif ( $this->explicitTrxActive() ) {
1041 return false; // don't drop atomocity
1042 } elseif ( $priorWritesPending ) {
1043 return false; // prior writes lost from implicit transaction
1049 private function handleTransactionLoss() {
1050 $this->mTrxLevel
= 0;
1051 $this->mTrxIdleCallbacks
= []; // bug 65263
1052 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1054 // Handle callbacks in mTrxEndCallbacks
1055 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1056 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1058 } catch ( Exception
$e ) {
1059 // Already logged; move on...
1064 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1065 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1066 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1068 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1069 $this->queryLogger
->error(
1070 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1071 $this->getLogContext( [
1072 'method' => __METHOD__
,
1075 'sql1line' => $sql1line,
1079 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1080 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1085 * Intended to be compatible with the PEAR::DB wrapper functions.
1086 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1088 * ? = scalar value, quoted as necessary
1089 * ! = raw SQL bit (a function for instance)
1090 * & = filename; reads the file and inserts as a blob
1091 * (we don't use this though...)
1093 * @param string $sql
1094 * @param string $func
1098 protected function prepare( $sql, $func = __METHOD__
) {
1099 /* MySQL doesn't support prepared statements (yet), so just
1100 * pack up the query for reference. We'll manually replace
1103 return [ 'query' => $sql, 'func' => $func ];
1107 * Free a prepared query, generated by prepare().
1108 * @param string $prepared
1110 protected function freePrepared( $prepared ) {
1111 /* No-op by default */
1115 * Execute a prepared query with the various arguments
1116 * @param string $prepared The prepared sql
1117 * @param mixed $args Either an array here, or put scalars as varargs
1119 * @return ResultWrapper
1121 public function execute( $prepared, $args = null ) {
1122 if ( !is_array( $args ) ) {
1124 $args = func_get_args();
1125 array_shift( $args );
1128 $sql = $this->fillPrepared( $prepared['query'], $args );
1130 return $this->query( $sql, $prepared['func'] );
1134 * For faking prepared SQL statements on DBs that don't support it directly.
1136 * @param string $preparedQuery A 'preparable' SQL statement
1137 * @param array $args Array of Arguments to fill it with
1138 * @return string Executable SQL
1140 public function fillPrepared( $preparedQuery, $args ) {
1142 $this->preparedArgs
=& $args;
1144 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1145 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1149 * preg_callback func for fillPrepared()
1150 * The arguments should be in $this->preparedArgs and must not be touched
1151 * while we're doing this.
1153 * @param array $matches
1154 * @throws DBUnexpectedError
1157 protected function fillPreparedArg( $matches ) {
1158 switch ( $matches[1] ) {
1167 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1169 switch ( $matches[1] ) {
1171 return $this->addQuotes( $arg );
1175 # return $this->addQuotes( file_get_contents( $arg ) );
1176 throw new DBUnexpectedError(
1178 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1181 throw new DBUnexpectedError(
1183 'Received invalid match. This should never happen!'
1188 public function freeResult( $res ) {
1191 public function selectField(
1192 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1194 if ( $var === '*' ) { // sanity
1195 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1198 if ( !is_array( $options ) ) {
1199 $options = [ $options ];
1202 $options['LIMIT'] = 1;
1204 $res = $this->select( $table, $var, $cond, $fname, $options );
1205 if ( $res === false ||
!$this->numRows( $res ) ) {
1209 $row = $this->fetchRow( $res );
1211 if ( $row !== false ) {
1212 return reset( $row );
1218 public function selectFieldValues(
1219 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1221 if ( $var === '*' ) { // sanity
1222 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1223 } elseif ( !is_string( $var ) ) { // sanity
1224 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1227 if ( !is_array( $options ) ) {
1228 $options = [ $options ];
1231 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1232 if ( $res === false ) {
1237 foreach ( $res as $row ) {
1238 $values[] = $row->$var;
1245 * Returns an optional USE INDEX clause to go after the table, and a
1246 * string to go at the end of the query.
1248 * @param array $options Associative array of options to be turned into
1249 * an SQL query, valid keys are listed in the function.
1251 * @see DatabaseBase::select()
1253 public function makeSelectOptions( $options ) {
1254 $preLimitTail = $postLimitTail = '';
1259 foreach ( $options as $key => $option ) {
1260 if ( is_numeric( $key ) ) {
1261 $noKeyOptions[$option] = true;
1265 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1267 $preLimitTail .= $this->makeOrderBy( $options );
1269 // if (isset($options['LIMIT'])) {
1270 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1271 // isset($options['OFFSET']) ? $options['OFFSET']
1275 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1276 $postLimitTail .= ' FOR UPDATE';
1279 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1280 $postLimitTail .= ' LOCK IN SHARE MODE';
1283 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1284 $startOpts .= 'DISTINCT';
1287 # Various MySQL extensions
1288 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1289 $startOpts .= ' /*! STRAIGHT_JOIN */';
1292 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1293 $startOpts .= ' HIGH_PRIORITY';
1296 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1297 $startOpts .= ' SQL_BIG_RESULT';
1300 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1301 $startOpts .= ' SQL_BUFFER_RESULT';
1304 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1305 $startOpts .= ' SQL_SMALL_RESULT';
1308 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1309 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1312 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1313 $startOpts .= ' SQL_CACHE';
1316 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1317 $startOpts .= ' SQL_NO_CACHE';
1320 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1321 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1325 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1326 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1331 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1335 * Returns an optional GROUP BY with an optional HAVING
1337 * @param array $options Associative array of options
1339 * @see DatabaseBase::select()
1342 public function makeGroupByWithHaving( $options ) {
1344 if ( isset( $options['GROUP BY'] ) ) {
1345 $gb = is_array( $options['GROUP BY'] )
1346 ?
implode( ',', $options['GROUP BY'] )
1347 : $options['GROUP BY'];
1348 $sql .= ' GROUP BY ' . $gb;
1350 if ( isset( $options['HAVING'] ) ) {
1351 $having = is_array( $options['HAVING'] )
1352 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1353 : $options['HAVING'];
1354 $sql .= ' HAVING ' . $having;
1361 * Returns an optional ORDER BY
1363 * @param array $options Associative array of options
1365 * @see DatabaseBase::select()
1368 public function makeOrderBy( $options ) {
1369 if ( isset( $options['ORDER BY'] ) ) {
1370 $ob = is_array( $options['ORDER BY'] )
1371 ?
implode( ',', $options['ORDER BY'] )
1372 : $options['ORDER BY'];
1374 return ' ORDER BY ' . $ob;
1380 // See IDatabase::select for the docs for this function
1381 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1382 $options = [], $join_conds = [] ) {
1383 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1385 return $this->query( $sql, $fname );
1388 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1389 $options = [], $join_conds = []
1391 if ( is_array( $vars ) ) {
1392 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1395 $options = (array)$options;
1396 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1397 ?
$options['USE INDEX']
1399 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1400 ?
$options['IGNORE INDEX']
1403 if ( is_array( $table ) ) {
1405 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1406 } elseif ( $table != '' ) {
1407 if ( $table[0] == ' ' ) {
1408 $from = ' FROM ' . $table;
1411 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1417 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1418 $this->makeSelectOptions( $options );
1420 if ( !empty( $conds ) ) {
1421 if ( is_array( $conds ) ) {
1422 $conds = $this->makeList( $conds, LIST_AND
);
1424 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1426 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1429 if ( isset( $options['LIMIT'] ) ) {
1430 $sql = $this->limitResult( $sql, $options['LIMIT'],
1431 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1433 $sql = "$sql $postLimitTail";
1435 if ( isset( $options['EXPLAIN'] ) ) {
1436 $sql = 'EXPLAIN ' . $sql;
1442 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1443 $options = [], $join_conds = []
1445 $options = (array)$options;
1446 $options['LIMIT'] = 1;
1447 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1449 if ( $res === false ) {
1453 if ( !$this->numRows( $res ) ) {
1457 $obj = $this->fetchObject( $res );
1462 public function estimateRowCount(
1463 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1466 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1469 $row = $this->fetchRow( $res );
1470 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1476 public function selectRowCount(
1477 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1480 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1481 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1484 $row = $this->fetchRow( $res );
1485 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1492 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1493 * It's only slightly flawed. Don't use for anything important.
1495 * @param string $sql A SQL Query
1499 protected static function generalizeSQL( $sql ) {
1500 # This does the same as the regexp below would do, but in such a way
1501 # as to avoid crashing php on some large strings.
1502 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1504 $sql = str_replace( "\\\\", '', $sql );
1505 $sql = str_replace( "\\'", '', $sql );
1506 $sql = str_replace( "\\\"", '', $sql );
1507 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1508 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1510 # All newlines, tabs, etc replaced by single space
1511 $sql = preg_replace( '/\s+/', ' ', $sql );
1514 # except the ones surrounded by characters, e.g. l10n
1515 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1516 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1521 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1522 $info = $this->fieldInfo( $table, $field );
1527 public function indexExists( $table, $index, $fname = __METHOD__
) {
1528 if ( !$this->tableExists( $table ) ) {
1532 $info = $this->indexInfo( $table, $index, $fname );
1533 if ( is_null( $info ) ) {
1536 return $info !== false;
1540 public function tableExists( $table, $fname = __METHOD__
) {
1541 $table = $this->tableName( $table );
1542 $old = $this->ignoreErrors( true );
1543 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1544 $this->ignoreErrors( $old );
1549 public function indexUnique( $table, $index ) {
1550 $indexInfo = $this->indexInfo( $table, $index );
1552 if ( !$indexInfo ) {
1556 return !$indexInfo[0]->Non_unique
;
1560 * Helper for DatabaseBase::insert().
1562 * @param array $options
1565 protected function makeInsertOptions( $options ) {
1566 return implode( ' ', $options );
1569 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1570 # No rows to insert, easy just return now
1571 if ( !count( $a ) ) {
1575 $table = $this->tableName( $table );
1577 if ( !is_array( $options ) ) {
1578 $options = [ $options ];
1582 if ( isset( $options['fileHandle'] ) ) {
1583 $fh = $options['fileHandle'];
1585 $options = $this->makeInsertOptions( $options );
1587 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1589 $keys = array_keys( $a[0] );
1592 $keys = array_keys( $a );
1595 $sql = 'INSERT ' . $options .
1596 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1600 foreach ( $a as $row ) {
1606 $sql .= '(' . $this->makeList( $row ) . ')';
1609 $sql .= '(' . $this->makeList( $a ) . ')';
1612 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1614 } elseif ( $fh !== null ) {
1618 return (bool)$this->query( $sql, $fname );
1622 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1624 * @param array $options
1627 protected function makeUpdateOptionsArray( $options ) {
1628 if ( !is_array( $options ) ) {
1629 $options = [ $options ];
1634 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1635 $opts[] = $this->lowPriorityOption();
1638 if ( in_array( 'IGNORE', $options ) ) {
1646 * Make UPDATE options for the DatabaseBase::update function
1648 * @param array $options The options passed to DatabaseBase::update
1651 protected function makeUpdateOptions( $options ) {
1652 $opts = $this->makeUpdateOptionsArray( $options );
1654 return implode( ' ', $opts );
1657 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1658 $table = $this->tableName( $table );
1659 $opts = $this->makeUpdateOptions( $options );
1660 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1662 if ( $conds !== [] && $conds !== '*' ) {
1663 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1666 return $this->query( $sql, $fname );
1669 public function makeList( $a, $mode = LIST_COMMA
) {
1670 if ( !is_array( $a ) ) {
1671 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1677 foreach ( $a as $field => $value ) {
1679 if ( $mode == LIST_AND
) {
1681 } elseif ( $mode == LIST_OR
) {
1690 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1691 $list .= "($value)";
1692 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1694 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1695 // Remove null from array to be handled separately if found
1696 $includeNull = false;
1697 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1698 $includeNull = true;
1699 unset( $value[$nullKey] );
1701 if ( count( $value ) == 0 && !$includeNull ) {
1702 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1703 } elseif ( count( $value ) == 0 ) {
1704 // only check if $field is null
1705 $list .= "$field IS NULL";
1707 // IN clause contains at least one valid element
1708 if ( $includeNull ) {
1709 // Group subconditions to ensure correct precedence
1712 if ( count( $value ) == 1 ) {
1713 // Special-case single values, as IN isn't terribly efficient
1714 // Don't necessarily assume the single key is 0; we don't
1715 // enforce linear numeric ordering on other arrays here.
1716 $value = array_values( $value )[0];
1717 $list .= $field . " = " . $this->addQuotes( $value );
1719 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1721 // if null present in array, append IS NULL
1722 if ( $includeNull ) {
1723 $list .= " OR $field IS NULL)";
1726 } elseif ( $value === null ) {
1727 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1728 $list .= "$field IS ";
1729 } elseif ( $mode == LIST_SET
) {
1730 $list .= "$field = ";
1734 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1735 $list .= "$field = ";
1737 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1744 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1747 foreach ( $data as $base => $sub ) {
1748 if ( count( $sub ) ) {
1749 $conds[] = $this->makeList(
1750 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1756 return $this->makeList( $conds, LIST_OR
);
1758 // Nothing to search for...
1764 * Return aggregated value alias
1766 * @param array $valuedata
1767 * @param string $valuename
1771 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1775 public function bitNot( $field ) {
1779 public function bitAnd( $fieldLeft, $fieldRight ) {
1780 return "($fieldLeft & $fieldRight)";
1783 public function bitOr( $fieldLeft, $fieldRight ) {
1784 return "($fieldLeft | $fieldRight)";
1787 public function buildConcat( $stringList ) {
1788 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1791 public function buildGroupConcatField(
1792 $delim, $table, $field, $conds = '', $join_conds = []
1794 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1796 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1800 * @param string $field Field or column to cast
1804 public function buildStringCast( $field ) {
1808 public function selectDB( $db ) {
1809 # Stub. Shouldn't cause serious problems if it's not overridden, but
1810 # if your database engine supports a concept similar to MySQL's
1811 # databases you may as well.
1812 $this->mDBname
= $db;
1817 public function getDBname() {
1818 return $this->mDBname
;
1821 public function getServer() {
1822 return $this->mServer
;
1826 * Format a table name ready for use in constructing an SQL query
1828 * This does two important things: it quotes the table names to clean them up,
1829 * and it adds a table prefix if only given a table name with no quotes.
1831 * All functions of this object which require a table name call this function
1832 * themselves. Pass the canonical name to such functions. This is only needed
1833 * when calling query() directly.
1835 * @note This function does not sanitize user input. It is not safe to use
1836 * this function to escape user input.
1837 * @param string $name Database table name
1838 * @param string $format One of:
1839 * quoted - Automatically pass the table name through addIdentifierQuotes()
1840 * so that it can be used in a query.
1841 * raw - Do not add identifier quotes to the table name
1842 * @return string Full database name
1844 public function tableName( $name, $format = 'quoted' ) {
1845 # Skip the entire process when we have a string quoted on both ends.
1846 # Note that we check the end so that we will still quote any use of
1847 # use of `database`.table. But won't break things if someone wants
1848 # to query a database table with a dot in the name.
1849 if ( $this->isQuotedIdentifier( $name ) ) {
1853 # Lets test for any bits of text that should never show up in a table
1854 # name. Basically anything like JOIN or ON which are actually part of
1855 # SQL queries, but may end up inside of the table value to combine
1856 # sql. Such as how the API is doing.
1857 # Note that we use a whitespace test rather than a \b test to avoid
1858 # any remote case where a word like on may be inside of a table name
1859 # surrounded by symbols which may be considered word breaks.
1860 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1864 # Split database and table into proper variables.
1865 # We reverse the explode so that database.table and table both output
1866 # the correct table.
1867 $dbDetails = explode( '.', $name, 3 );
1868 if ( count( $dbDetails ) == 3 ) {
1869 list( $database, $schema, $table ) = $dbDetails;
1870 # We don't want any prefix added in this case
1872 } elseif ( count( $dbDetails ) == 2 ) {
1873 list( $database, $table ) = $dbDetails;
1874 # We don't want any prefix added in this case
1875 # In dbs that support it, $database may actually be the schema
1876 # but that doesn't affect any of the functionality here
1880 list( $table ) = $dbDetails;
1881 if ( isset( $this->tableAliases
[$table] ) ) {
1882 $database = $this->tableAliases
[$table]['dbname'];
1883 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1884 ?
$this->tableAliases
[$table]['schema']
1886 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1887 ?
$this->tableAliases
[$table]['prefix']
1888 : $this->mTablePrefix
;
1891 $schema = $this->mSchema
; # Default schema
1892 $prefix = $this->mTablePrefix
; # Default prefix
1896 # Quote $table and apply the prefix if not quoted.
1897 # $tableName might be empty if this is called from Database::replaceVars()
1898 $tableName = "{$prefix}{$table}";
1899 if ( $format == 'quoted'
1900 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1902 $tableName = $this->addIdentifierQuotes( $tableName );
1905 # Quote $schema and merge it with the table name if needed
1906 if ( strlen( $schema ) ) {
1907 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1908 $schema = $this->addIdentifierQuotes( $schema );
1910 $tableName = $schema . '.' . $tableName;
1913 # Quote $database and merge it with the table name if needed
1914 if ( $database !== null ) {
1915 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1916 $database = $this->addIdentifierQuotes( $database );
1918 $tableName = $database . '.' . $tableName;
1925 * Fetch a number of table names into an array
1926 * This is handy when you need to construct SQL for joins
1929 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1930 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1931 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1935 public function tableNames() {
1936 $inArray = func_get_args();
1939 foreach ( $inArray as $name ) {
1940 $retVal[$name] = $this->tableName( $name );
1947 * Fetch a number of table names into an zero-indexed numerical array
1948 * This is handy when you need to construct SQL for joins
1951 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1952 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1953 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1957 public function tableNamesN() {
1958 $inArray = func_get_args();
1961 foreach ( $inArray as $name ) {
1962 $retVal[] = $this->tableName( $name );
1969 * Get an aliased table name
1970 * e.g. tableName AS newTableName
1972 * @param string $name Table name, see tableName()
1973 * @param string|bool $alias Alias (optional)
1974 * @return string SQL name for aliased table. Will not alias a table to its own name
1976 public function tableNameWithAlias( $name, $alias = false ) {
1977 if ( !$alias ||
$alias == $name ) {
1978 return $this->tableName( $name );
1980 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1985 * Gets an array of aliased table names
1987 * @param array $tables [ [alias] => table ]
1988 * @return string[] See tableNameWithAlias()
1990 public function tableNamesWithAlias( $tables ) {
1992 foreach ( $tables as $alias => $table ) {
1993 if ( is_numeric( $alias ) ) {
1996 $retval[] = $this->tableNameWithAlias( $table, $alias );
2003 * Get an aliased field name
2004 * e.g. fieldName AS newFieldName
2006 * @param string $name Field name
2007 * @param string|bool $alias Alias (optional)
2008 * @return string SQL name for aliased field. Will not alias a field to its own name
2010 public function fieldNameWithAlias( $name, $alias = false ) {
2011 if ( !$alias ||
(string)$alias === (string)$name ) {
2014 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2019 * Gets an array of aliased field names
2021 * @param array $fields [ [alias] => field ]
2022 * @return string[] See fieldNameWithAlias()
2024 public function fieldNamesWithAlias( $fields ) {
2026 foreach ( $fields as $alias => $field ) {
2027 if ( is_numeric( $alias ) ) {
2030 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2037 * Get the aliased table name clause for a FROM clause
2038 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2040 * @param array $tables ( [alias] => table )
2041 * @param array $use_index Same as for select()
2042 * @param array $ignore_index Same as for select()
2043 * @param array $join_conds Same as for select()
2046 protected function tableNamesWithIndexClauseOrJOIN(
2047 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2051 $use_index = (array)$use_index;
2052 $ignore_index = (array)$ignore_index;
2053 $join_conds = (array)$join_conds;
2055 foreach ( $tables as $alias => $table ) {
2056 if ( !is_string( $alias ) ) {
2057 // No alias? Set it equal to the table name
2060 // Is there a JOIN clause for this table?
2061 if ( isset( $join_conds[$alias] ) ) {
2062 list( $joinType, $conds ) = $join_conds[$alias];
2063 $tableClause = $joinType;
2064 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2065 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2066 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2068 $tableClause .= ' ' . $use;
2071 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2072 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2073 if ( $ignore != '' ) {
2074 $tableClause .= ' ' . $ignore;
2077 $on = $this->makeList( (array)$conds, LIST_AND
);
2079 $tableClause .= ' ON (' . $on . ')';
2082 $retJOIN[] = $tableClause;
2083 } elseif ( isset( $use_index[$alias] ) ) {
2084 // Is there an INDEX clause for this table?
2085 $tableClause = $this->tableNameWithAlias( $table, $alias );
2086 $tableClause .= ' ' . $this->useIndexClause(
2087 implode( ',', (array)$use_index[$alias] )
2090 $ret[] = $tableClause;
2091 } elseif ( isset( $ignore_index[$alias] ) ) {
2092 // Is there an INDEX clause for this table?
2093 $tableClause = $this->tableNameWithAlias( $table, $alias );
2094 $tableClause .= ' ' . $this->ignoreIndexClause(
2095 implode( ',', (array)$ignore_index[$alias] )
2098 $ret[] = $tableClause;
2100 $tableClause = $this->tableNameWithAlias( $table, $alias );
2102 $ret[] = $tableClause;
2106 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2107 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2108 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2110 // Compile our final table clause
2111 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2115 * Get the name of an index in a given table.
2117 * @param string $index
2120 protected function indexName( $index ) {
2121 // Backwards-compatibility hack
2123 'ar_usertext_timestamp' => 'usertext_timestamp',
2124 'un_user_id' => 'user_id',
2125 'un_user_ip' => 'user_ip',
2128 if ( isset( $renamed[$index] ) ) {
2129 return $renamed[$index];
2135 public function addQuotes( $s ) {
2136 if ( $s instanceof Blob
) {
2139 if ( $s === null ) {
2142 # This will also quote numeric values. This should be harmless,
2143 # and protects against weird problems that occur when they really
2144 # _are_ strings such as article titles and string->number->string
2145 # conversion is not 1:1.
2146 return "'" . $this->strencode( $s ) . "'";
2151 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2152 * MySQL uses `backticks` while basically everything else uses double quotes.
2153 * Since MySQL is the odd one out here the double quotes are our generic
2154 * and we implement backticks in DatabaseMysql.
2159 public function addIdentifierQuotes( $s ) {
2160 return '"' . str_replace( '"', '""', $s ) . '"';
2164 * Returns if the given identifier looks quoted or not according to
2165 * the database convention for quoting identifiers .
2167 * @note Do not use this to determine if untrusted input is safe.
2168 * A malicious user can trick this function.
2169 * @param string $name
2172 public function isQuotedIdentifier( $name ) {
2173 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2180 protected function escapeLikeInternal( $s ) {
2181 return addcslashes( $s, '\%_' );
2184 public function buildLike() {
2185 $params = func_get_args();
2187 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2188 $params = $params[0];
2193 foreach ( $params as $value ) {
2194 if ( $value instanceof LikeMatch
) {
2195 $s .= $value->toString();
2197 $s .= $this->escapeLikeInternal( $value );
2201 return " LIKE {$this->addQuotes( $s )} ";
2204 public function anyChar() {
2205 return new LikeMatch( '_' );
2208 public function anyString() {
2209 return new LikeMatch( '%' );
2212 public function nextSequenceValue( $seqName ) {
2217 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2218 * is only needed because a) MySQL must be as efficient as possible due to
2219 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2220 * which index to pick. Anyway, other databases might have different
2221 * indexes on a given table. So don't bother overriding this unless you're
2223 * @param string $index
2226 public function useIndexClause( $index ) {
2231 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2232 * is only needed because a) MySQL must be as efficient as possible due to
2233 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2234 * which index to pick. Anyway, other databases might have different
2235 * indexes on a given table. So don't bother overriding this unless you're
2237 * @param string $index
2240 public function ignoreIndexClause( $index ) {
2244 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2245 $quotedTable = $this->tableName( $table );
2247 if ( count( $rows ) == 0 ) {
2252 if ( !is_array( reset( $rows ) ) ) {
2256 // @FXIME: this is not atomic, but a trx would break affectedRows()
2257 foreach ( $rows as $row ) {
2258 # Delete rows which collide
2259 if ( $uniqueIndexes ) {
2260 $sql = "DELETE FROM $quotedTable WHERE ";
2262 foreach ( $uniqueIndexes as $index ) {
2269 if ( is_array( $index ) ) {
2271 foreach ( $index as $col ) {
2277 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2280 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2284 $this->query( $sql, $fname );
2287 # Now insert the row
2288 $this->insert( $table, $row, $fname );
2293 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2296 * @param string $table Table name
2297 * @param array|string $rows Row(s) to insert
2298 * @param string $fname Caller function name
2300 * @return ResultWrapper
2302 protected function nativeReplace( $table, $rows, $fname ) {
2303 $table = $this->tableName( $table );
2306 if ( !is_array( reset( $rows ) ) ) {
2310 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2313 foreach ( $rows as $row ) {
2320 $sql .= '(' . $this->makeList( $row ) . ')';
2323 return $this->query( $sql, $fname );
2326 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2329 if ( !count( $rows ) ) {
2330 return true; // nothing to do
2333 if ( !is_array( reset( $rows ) ) ) {
2337 if ( count( $uniqueIndexes ) ) {
2338 $clauses = []; // list WHERE clauses that each identify a single row
2339 foreach ( $rows as $row ) {
2340 foreach ( $uniqueIndexes as $index ) {
2341 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2342 $rowKey = []; // unique key to this row
2343 foreach ( $index as $column ) {
2344 $rowKey[$column] = $row[$column];
2346 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2349 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2354 $useTrx = !$this->mTrxLevel
;
2356 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2359 # Update any existing conflicting row(s)
2360 if ( $where !== false ) {
2361 $ok = $this->update( $table, $set, $where, $fname );
2365 # Now insert any non-conflicting row(s)
2366 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2367 } catch ( Exception
$e ) {
2369 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2374 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2380 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2384 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2387 $delTable = $this->tableName( $delTable );
2388 $joinTable = $this->tableName( $joinTable );
2389 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2390 if ( $conds != '*' ) {
2391 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2395 $this->query( $sql, $fname );
2399 * Returns the size of a text field, or -1 for "unlimited"
2401 * @param string $table
2402 * @param string $field
2405 public function textFieldSize( $table, $field ) {
2406 $table = $this->tableName( $table );
2407 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2408 $res = $this->query( $sql, __METHOD__
);
2409 $row = $this->fetchObject( $res );
2413 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2423 * A string to insert into queries to show that they're low-priority, like
2424 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2425 * string and nothing bad should happen.
2427 * @return string Returns the text of the low priority option if it is
2428 * supported, or a blank string otherwise
2430 public function lowPriorityOption() {
2434 public function delete( $table, $conds, $fname = __METHOD__
) {
2436 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2439 $table = $this->tableName( $table );
2440 $sql = "DELETE FROM $table";
2442 if ( $conds != '*' ) {
2443 if ( is_array( $conds ) ) {
2444 $conds = $this->makeList( $conds, LIST_AND
);
2446 $sql .= ' WHERE ' . $conds;
2449 return $this->query( $sql, $fname );
2452 public function insertSelect(
2453 $destTable, $srcTable, $varMap, $conds,
2454 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2456 if ( $this->cliMode
) {
2457 // For massive migrations with downtime, we don't want to select everything
2458 // into memory and OOM, so do all this native on the server side if possible.
2459 return $this->nativeInsertSelect(
2470 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2471 // on only the master (without needing row-based-replication). It also makes it easy to
2472 // know how big the INSERT is going to be.
2474 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2475 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2477 $selectOptions[] = 'FOR UPDATE';
2478 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2484 foreach ( $res as $row ) {
2485 $rows[] = (array)$row;
2488 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2491 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2492 $fname = __METHOD__
,
2493 $insertOptions = [], $selectOptions = []
2495 $destTable = $this->tableName( $destTable );
2497 if ( !is_array( $insertOptions ) ) {
2498 $insertOptions = [ $insertOptions ];
2501 $insertOptions = $this->makeInsertOptions( $insertOptions );
2503 if ( !is_array( $selectOptions ) ) {
2504 $selectOptions = [ $selectOptions ];
2507 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2510 if ( is_array( $srcTable ) ) {
2511 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2513 $srcTable = $this->tableName( $srcTable );
2516 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2517 " SELECT $startOpts " . implode( ',', $varMap ) .
2518 " FROM $srcTable $useIndex $ignoreIndex ";
2520 if ( $conds != '*' ) {
2521 if ( is_array( $conds ) ) {
2522 $conds = $this->makeList( $conds, LIST_AND
);
2524 $sql .= " WHERE $conds";
2527 $sql .= " $tailOpts";
2529 return $this->query( $sql, $fname );
2533 * Construct a LIMIT query with optional offset. This is used for query
2534 * pages. The SQL should be adjusted so that only the first $limit rows
2535 * are returned. If $offset is provided as well, then the first $offset
2536 * rows should be discarded, and the next $limit rows should be returned.
2537 * If the result of the query is not ordered, then the rows to be returned
2538 * are theoretically arbitrary.
2540 * $sql is expected to be a SELECT, if that makes a difference.
2542 * The version provided by default works in MySQL and SQLite. It will very
2543 * likely need to be overridden for most other DBMSes.
2545 * @param string $sql SQL query we will append the limit too
2546 * @param int $limit The SQL limit
2547 * @param int|bool $offset The SQL offset (default false)
2548 * @throws DBUnexpectedError
2551 public function limitResult( $sql, $limit, $offset = false ) {
2552 if ( !is_numeric( $limit ) ) {
2553 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2556 return "$sql LIMIT "
2557 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2561 public function unionSupportsOrderAndLimit() {
2562 return true; // True for almost every DB supported
2565 public function unionQueries( $sqls, $all ) {
2566 $glue = $all ?
') UNION ALL (' : ') UNION (';
2568 return '(' . implode( $glue, $sqls ) . ')';
2571 public function conditional( $cond, $trueVal, $falseVal ) {
2572 if ( is_array( $cond ) ) {
2573 $cond = $this->makeList( $cond, LIST_AND
);
2576 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2579 public function strreplace( $orig, $old, $new ) {
2580 return "REPLACE({$orig}, {$old}, {$new})";
2583 public function getServerUptime() {
2587 public function wasDeadlock() {
2591 public function wasLockTimeout() {
2595 public function wasErrorReissuable() {
2599 public function wasReadOnlyError() {
2604 * Determines if the given query error was a connection drop
2607 * @param integer|string $errno
2610 public function wasConnectionError( $errno ) {
2615 * Perform a deadlock-prone transaction.
2617 * This function invokes a callback function to perform a set of write
2618 * queries. If a deadlock occurs during the processing, the transaction
2619 * will be rolled back and the callback function will be called again.
2621 * Avoid using this method outside of Job or Maintenance classes.
2624 * $dbw->deadlockLoop( callback, ... );
2626 * Extra arguments are passed through to the specified callback function.
2627 * This method requires that no transactions are already active to avoid
2628 * causing premature commits or exceptions.
2630 * Returns whatever the callback function returned on its successful,
2631 * iteration, or false on error, for example if the retry limit was
2635 * @throws DBUnexpectedError
2638 public function deadlockLoop() {
2639 $args = func_get_args();
2640 $function = array_shift( $args );
2641 $tries = self
::DEADLOCK_TRIES
;
2643 $this->begin( __METHOD__
);
2646 /** @var Exception $e */
2650 $retVal = call_user_func_array( $function, $args );
2652 } catch ( DBQueryError
$e ) {
2653 if ( $this->wasDeadlock() ) {
2654 // Retry after a randomized delay
2655 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2657 // Throw the error back up
2661 } while ( --$tries > 0 );
2663 if ( $tries <= 0 ) {
2664 // Too many deadlocks; give up
2665 $this->rollback( __METHOD__
);
2668 $this->commit( __METHOD__
);
2674 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2675 # Real waits are implemented in the subclass.
2679 public function getSlavePos() {
2684 public function getMasterPos() {
2689 public function serverIsReadOnly() {
2693 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2694 if ( !$this->mTrxLevel
) {
2695 throw new DBUnexpectedError( $this, "No transaction is active." );
2697 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2700 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2701 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2702 if ( !$this->mTrxLevel
) {
2703 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2707 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2708 if ( $this->mTrxLevel
) {
2709 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2711 // If no transaction is active, then make one for this callback
2712 $this->startAtomic( __METHOD__
);
2714 call_user_func( $callback );
2715 $this->endAtomic( __METHOD__
);
2716 } catch ( Exception
$e ) {
2717 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2723 final public function setTransactionListener( $name, callable
$callback = null ) {
2725 $this->mTrxRecurringCallbacks
[$name] = $callback;
2727 unset( $this->mTrxRecurringCallbacks
[$name] );
2732 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2734 * This method should not be used outside of Database/LoadBalancer
2736 * @param bool $suppress
2739 final public function setTrxEndCallbackSuppression( $suppress ) {
2740 $this->mTrxEndCallbacksSuppressed
= $suppress;
2744 * Actually run and consume any "on transaction idle/resolution" callbacks.
2746 * This method should not be used outside of Database/LoadBalancer
2748 * @param integer $trigger IDatabase::TRIGGER_* constant
2752 public function runOnTransactionIdleCallbacks( $trigger ) {
2753 if ( $this->mTrxEndCallbacksSuppressed
) {
2757 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2758 /** @var Exception $e */
2759 $e = null; // first exception
2760 do { // callbacks may add callbacks :)
2761 $callbacks = array_merge(
2762 $this->mTrxIdleCallbacks
,
2763 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2765 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2766 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2767 foreach ( $callbacks as $callback ) {
2769 list( $phpCallback ) = $callback;
2770 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2771 call_user_func_array( $phpCallback, [ $trigger ] );
2773 $this->setFlag( DBO_TRX
); // restore automatic begin()
2775 $this->clearFlag( DBO_TRX
); // restore auto-commit
2777 } catch ( Exception
$ex ) {
2778 call_user_func( $this->errorLogger
, $ex );
2780 // Some callbacks may use startAtomic/endAtomic, so make sure
2781 // their transactions are ended so other callbacks don't fail
2782 if ( $this->trxLevel() ) {
2783 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2787 } while ( count( $this->mTrxIdleCallbacks
) );
2789 if ( $e instanceof Exception
) {
2790 throw $e; // re-throw any first exception
2795 * Actually run and consume any "on transaction pre-commit" callbacks.
2797 * This method should not be used outside of Database/LoadBalancer
2802 public function runOnTransactionPreCommitCallbacks() {
2803 $e = null; // first exception
2804 do { // callbacks may add callbacks :)
2805 $callbacks = $this->mTrxPreCommitCallbacks
;
2806 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2807 foreach ( $callbacks as $callback ) {
2809 list( $phpCallback ) = $callback;
2810 call_user_func( $phpCallback );
2811 } catch ( Exception
$ex ) {
2812 call_user_func( $this->errorLogger
, $ex );
2816 } while ( count( $this->mTrxPreCommitCallbacks
) );
2818 if ( $e instanceof Exception
) {
2819 throw $e; // re-throw any first exception
2824 * Actually run any "transaction listener" callbacks.
2826 * This method should not be used outside of Database/LoadBalancer
2828 * @param integer $trigger IDatabase::TRIGGER_* constant
2832 public function runTransactionListenerCallbacks( $trigger ) {
2833 if ( $this->mTrxEndCallbacksSuppressed
) {
2837 /** @var Exception $e */
2838 $e = null; // first exception
2840 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2842 $phpCallback( $trigger, $this );
2843 } catch ( Exception
$ex ) {
2844 call_user_func( $this->errorLogger
, $ex );
2849 if ( $e instanceof Exception
) {
2850 throw $e; // re-throw any first exception
2854 final public function startAtomic( $fname = __METHOD__
) {
2855 if ( !$this->mTrxLevel
) {
2856 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2857 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2858 // in all changes being in one transaction to keep requests transactional.
2859 if ( !$this->getFlag( DBO_TRX
) ) {
2860 $this->mTrxAutomaticAtomic
= true;
2864 $this->mTrxAtomicLevels
[] = $fname;
2867 final public function endAtomic( $fname = __METHOD__
) {
2868 if ( !$this->mTrxLevel
) {
2869 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2871 if ( !$this->mTrxAtomicLevels ||
2872 array_pop( $this->mTrxAtomicLevels
) !== $fname
2874 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2877 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2878 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2882 final public function doAtomicSection( $fname, callable
$callback ) {
2883 $this->startAtomic( $fname );
2885 $res = call_user_func_array( $callback, [ $this, $fname ] );
2886 } catch ( Exception
$e ) {
2887 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2890 $this->endAtomic( $fname );
2895 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2896 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2897 if ( $this->mTrxLevel
) {
2898 if ( $this->mTrxAtomicLevels
) {
2899 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2900 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2901 throw new DBUnexpectedError( $this, $msg );
2902 } elseif ( !$this->mTrxAutomatic
) {
2903 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2904 throw new DBUnexpectedError( $this, $msg );
2906 // @TODO: make this an exception at some point
2907 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2908 $this->queryLogger
->error( $msg );
2909 return; // join the main transaction set
2911 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2912 // @TODO: make this an exception at some point
2913 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2914 $this->queryLogger
->error( $msg );
2915 return; // let any writes be in the main transaction
2918 // Avoid fatals if close() was called
2919 $this->assertOpen();
2921 $this->doBegin( $fname );
2922 $this->mTrxTimestamp
= microtime( true );
2923 $this->mTrxFname
= $fname;
2924 $this->mTrxDoneWrites
= false;
2925 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2926 $this->mTrxAutomaticAtomic
= false;
2927 $this->mTrxAtomicLevels
= [];
2928 $this->mTrxShortId
= wfRandomString( 12 );
2929 $this->mTrxWriteDuration
= 0.0;
2930 $this->mTrxWriteQueryCount
= 0;
2931 $this->mTrxWriteAdjDuration
= 0.0;
2932 $this->mTrxWriteAdjQueryCount
= 0;
2933 $this->mTrxWriteCallers
= [];
2934 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2935 // Get an estimate of the replica DB lag before then, treating estimate staleness
2936 // as lag itself just to be safe
2937 $status = $this->getApproximateLagStatus();
2938 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2942 * Issues the BEGIN command to the database server.
2944 * @see DatabaseBase::begin()
2945 * @param string $fname
2947 protected function doBegin( $fname ) {
2948 $this->query( 'BEGIN', $fname );
2949 $this->mTrxLevel
= 1;
2952 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2953 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2954 // There are still atomic sections open. This cannot be ignored
2955 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2956 throw new DBUnexpectedError(
2958 "$fname: Got COMMIT while atomic sections $levels are still open."
2962 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2963 if ( !$this->mTrxLevel
) {
2964 return; // nothing to do
2965 } elseif ( !$this->mTrxAutomatic
) {
2966 throw new DBUnexpectedError(
2968 "$fname: Flushing an explicit transaction, getting out of sync."
2972 if ( !$this->mTrxLevel
) {
2973 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2974 return; // nothing to do
2975 } elseif ( $this->mTrxAutomatic
) {
2976 // @TODO: make this an exception at some point
2977 $msg = "$fname: Explicit commit of implicit transaction.";
2978 $this->queryLogger
->error( $msg );
2979 return; // wait for the main transaction set commit round
2983 // Avoid fatals if close() was called
2984 $this->assertOpen();
2986 $this->runOnTransactionPreCommitCallbacks();
2987 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2988 $this->doCommit( $fname );
2989 if ( $this->mTrxDoneWrites
) {
2990 $this->mDoneWrites
= microtime( true );
2991 $this->trxProfiler
->transactionWritingOut(
2992 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2995 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2996 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3000 * Issues the COMMIT command to the database server.
3002 * @see DatabaseBase::commit()
3003 * @param string $fname
3005 protected function doCommit( $fname ) {
3006 if ( $this->mTrxLevel
) {
3007 $this->query( 'COMMIT', $fname );
3008 $this->mTrxLevel
= 0;
3012 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3013 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3014 if ( !$this->mTrxLevel
) {
3015 return; // nothing to do
3018 if ( !$this->mTrxLevel
) {
3019 $this->queryLogger
->error(
3020 "$fname: No transaction to rollback, something got out of sync." );
3021 return; // nothing to do
3022 } elseif ( $this->getFlag( DBO_TRX
) ) {
3023 throw new DBUnexpectedError(
3025 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3030 // Avoid fatals if close() was called
3031 $this->assertOpen();
3033 $this->doRollback( $fname );
3034 $this->mTrxAtomicLevels
= [];
3035 if ( $this->mTrxDoneWrites
) {
3036 $this->trxProfiler
->transactionWritingOut(
3037 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3040 $this->mTrxIdleCallbacks
= []; // clear
3041 $this->mTrxPreCommitCallbacks
= []; // clear
3042 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3043 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3047 * Issues the ROLLBACK command to the database server.
3049 * @see DatabaseBase::rollback()
3050 * @param string $fname
3052 protected function doRollback( $fname ) {
3053 if ( $this->mTrxLevel
) {
3054 # Disconnects cause rollback anyway, so ignore those errors
3055 $ignoreErrors = true;
3056 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3057 $this->mTrxLevel
= 0;
3061 public function flushSnapshot( $fname = __METHOD__
) {
3062 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3063 // This only flushes transactions to clear snapshots, not to write data
3064 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3065 throw new DBUnexpectedError(
3067 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3071 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3074 public function explicitTrxActive() {
3075 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3079 * Creates a new table with structure copied from existing table
3080 * Note that unlike most database abstraction functions, this function does not
3081 * automatically append database prefix, because it works at a lower
3082 * abstraction level.
3083 * The table names passed to this function shall not be quoted (this
3084 * function calls addIdentifierQuotes when needed).
3086 * @param string $oldName Name of table whose structure should be copied
3087 * @param string $newName Name of table to be created
3088 * @param bool $temporary Whether the new table should be temporary
3089 * @param string $fname Calling function name
3090 * @throws RuntimeException
3091 * @return bool True if operation was successful
3093 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3096 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3099 function listTables( $prefix = null, $fname = __METHOD__
) {
3100 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3104 * Reset the views process cache set by listViews()
3107 final public function clearViewsCache() {
3108 $this->allViews
= null;
3112 * Lists all the VIEWs in the database
3114 * For caching purposes the list of all views should be stored in
3115 * $this->allViews. The process cache can be cleared with clearViewsCache()
3117 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3118 * @param string $fname Name of calling function
3119 * @throws RuntimeException
3123 public function listViews( $prefix = null, $fname = __METHOD__
) {
3124 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3128 * Differentiates between a TABLE and a VIEW
3130 * @param string $name Name of the database-structure to test.
3131 * @throws RuntimeException
3135 public function isView( $name ) {
3136 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3139 public function timestamp( $ts = 0 ) {
3140 return wfTimestamp( TS_MW
, $ts );
3143 public function timestampOrNull( $ts = null ) {
3144 if ( is_null( $ts ) ) {
3147 return $this->timestamp( $ts );
3152 * Take the result from a query, and wrap it in a ResultWrapper if
3153 * necessary. Boolean values are passed through as is, to indicate success
3154 * of write queries or failure.
3156 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3157 * resource, and it was necessary to call this function to convert it to
3158 * a wrapper. Nowadays, raw database objects are never exposed to external
3159 * callers, so this is unnecessary in external code.
3161 * @param bool|ResultWrapper|resource|object $result
3162 * @return bool|ResultWrapper
3164 protected function resultObject( $result ) {
3167 } elseif ( $result instanceof ResultWrapper
) {
3169 } elseif ( $result === true ) {
3170 // Successful write query
3173 return new ResultWrapper( $this, $result );
3177 public function ping( &$rtt = null ) {
3178 // Avoid hitting the server if it was hit recently
3179 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3180 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3181 $rtt = $this->mRTTEstimate
;
3182 return true; // don't care about $rtt
3186 // This will reconnect if possible or return false if not
3187 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3188 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3189 $this->restoreFlags( self
::RESTORE_PRIOR
);
3192 $rtt = $this->mRTTEstimate
;
3201 protected function reconnect() {
3202 $this->closeConnection();
3203 $this->mOpened
= false;
3204 $this->mConn
= false;
3206 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3207 $this->lastPing
= microtime( true );
3209 } catch ( DBConnectionError
$e ) {
3216 public function getSessionLagStatus() {
3217 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3221 * Get the replica DB lag when the current transaction started
3223 * This is useful when transactions might use snapshot isolation
3224 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3225 * is this lag plus transaction duration. If they don't, it is still
3226 * safe to be pessimistic. This returns null if there is no transaction.
3228 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3231 public function getTransactionLagStatus() {
3232 return $this->mTrxLevel
3233 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3238 * Get a replica DB lag estimate for this server
3240 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3243 public function getApproximateLagStatus() {
3245 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3246 'since' => microtime( true )
3251 * Merge the result of getSessionLagStatus() for several DBs
3252 * using the most pessimistic values to estimate the lag of
3253 * any data derived from them in combination
3255 * This is information is useful for caching modules
3257 * @see WANObjectCache::set()
3258 * @see WANObjectCache::getWithSetCallback()
3260 * @param IDatabase $db1
3261 * @param IDatabase ...
3262 * @return array Map of values:
3263 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3264 * - since: oldest UNIX timestamp of any of the DB lag estimates
3265 * - pending: whether any of the DBs have uncommitted changes
3268 public static function getCacheSetOptions( IDatabase
$db1 ) {
3269 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3270 foreach ( func_get_args() as $db ) {
3271 /** @var IDatabase $db */
3272 $status = $db->getSessionLagStatus();
3273 if ( $status['lag'] === false ) {
3274 $res['lag'] = false;
3275 } elseif ( $res['lag'] !== false ) {
3276 $res['lag'] = max( $res['lag'], $status['lag'] );
3278 $res['since'] = min( $res['since'], $status['since'] );
3279 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3285 public function getLag() {
3289 function maxListLen() {
3293 public function encodeBlob( $b ) {
3297 public function decodeBlob( $b ) {
3298 if ( $b instanceof Blob
) {
3304 public function setSessionOptions( array $options ) {
3308 * Read and execute SQL commands from a file.
3310 * Returns true on success, error string or exception on failure (depending
3311 * on object's error ignore settings).
3313 * @param string $filename File name to open
3314 * @param bool|callable $lineCallback Optional function called before reading each line
3315 * @param bool|callable $resultCallback Optional function called for each MySQL result
3316 * @param bool|string $fname Calling function name or false if name should be
3317 * generated dynamically using $filename
3318 * @param bool|callable $inputCallback Optional function called for each
3319 * complete line sent
3320 * @return bool|string
3323 public function sourceFile(
3324 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3326 MediaWiki\
suppressWarnings();
3327 $fp = fopen( $filename, 'r' );
3328 MediaWiki\restoreWarnings
();
3330 if ( false === $fp ) {
3331 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3335 $fname = __METHOD__
. "( $filename )";
3339 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3340 } catch ( Exception
$e ) {
3350 public function setSchemaVars( $vars ) {
3351 $this->mSchemaVars
= $vars;
3355 * Read and execute commands from an open file handle.
3357 * Returns true on success, error string or exception on failure (depending
3358 * on object's error ignore settings).
3360 * @param resource $fp File handle
3361 * @param bool|callable $lineCallback Optional function called before reading each query
3362 * @param bool|callable $resultCallback Optional function called for each MySQL result
3363 * @param string $fname Calling function name
3364 * @param bool|callable $inputCallback Optional function called for each complete query sent
3365 * @return bool|string
3367 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3368 $fname = __METHOD__
, $inputCallback = false
3372 while ( !feof( $fp ) ) {
3373 if ( $lineCallback ) {
3374 call_user_func( $lineCallback );
3377 $line = trim( fgets( $fp ) );
3379 if ( $line == '' ) {
3383 if ( '-' == $line[0] && '-' == $line[1] ) {
3391 $done = $this->streamStatementEnd( $cmd, $line );
3395 if ( $done ||
feof( $fp ) ) {
3396 $cmd = $this->replaceVars( $cmd );
3398 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3399 $res = $this->query( $cmd, $fname );
3401 if ( $resultCallback ) {
3402 call_user_func( $resultCallback, $res, $this );
3405 if ( false === $res ) {
3406 $err = $this->lastError();
3408 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3419 * Called by sourceStream() to check if we've reached a statement end
3421 * @param string $sql SQL assembled so far
3422 * @param string $newLine New line about to be added to $sql
3423 * @return bool Whether $newLine contains end of the statement
3425 public function streamStatementEnd( &$sql, &$newLine ) {
3426 if ( $this->delimiter
) {
3428 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3429 if ( $newLine != $prev ) {
3438 * Database independent variable replacement. Replaces a set of variables
3439 * in an SQL statement with their contents as given by $this->getSchemaVars().
3441 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3443 * - '{$var}' should be used for text and is passed through the database's
3445 * - `{$var}` should be used for identifiers (e.g. table and database names).
3446 * It is passed through the database's addIdentifierQuotes method which
3447 * can be overridden if the database uses something other than backticks.
3448 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3449 * database's tableName method.
3450 * - / *i* / passes the name that follows through the database's indexName method.
3451 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3452 * its use should be avoided. In 1.24 and older, string encoding was applied.
3454 * @param string $ins SQL statement to replace variables in
3455 * @return string The new SQL statement with variables replaced
3457 protected function replaceVars( $ins ) {
3458 $vars = $this->getSchemaVars();
3459 return preg_replace_callback(
3461 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3462 \'\{\$ (\w+) }\' | # 3. addQuotes
3463 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3464 /\*\$ (\w+) \*/ # 5. leave unencoded
3466 function ( $m ) use ( $vars ) {
3467 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3468 // check for both nonexistent keys *and* the empty string.
3469 if ( isset( $m[1] ) && $m[1] !== '' ) {
3470 if ( $m[1] === 'i' ) {
3471 return $this->indexName( $m[2] );
3473 return $this->tableName( $m[2] );
3475 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3476 return $this->addQuotes( $vars[$m[3]] );
3477 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3478 return $this->addIdentifierQuotes( $vars[$m[4]] );
3479 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3480 return $vars[$m[5]];
3490 * Get schema variables. If none have been set via setSchemaVars(), then
3491 * use some defaults from the current object.
3495 protected function getSchemaVars() {
3496 if ( $this->mSchemaVars
) {
3497 return $this->mSchemaVars
;
3499 return $this->getDefaultSchemaVars();
3504 * Get schema variables to use if none have been set via setSchemaVars().
3506 * Override this in derived classes to provide variables for tables.sql
3507 * and SQL patch files.
3511 protected function getDefaultSchemaVars() {
3515 public function lockIsFree( $lockName, $method ) {
3519 public function lock( $lockName, $method, $timeout = 5 ) {
3520 $this->mNamedLocksHeld
[$lockName] = 1;
3525 public function unlock( $lockName, $method ) {
3526 unset( $this->mNamedLocksHeld
[$lockName] );
3531 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3532 if ( $this->writesOrCallbacksPending() ) {
3533 // This only flushes transactions to clear snapshots, not to write data
3534 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3535 throw new DBUnexpectedError(
3537 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3541 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3545 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3546 if ( $this->trxLevel() ) {
3547 // There is a good chance an exception was thrown, causing any early return
3548 // from the caller. Let any error handler get a chance to issue rollback().
3549 // If there isn't one, let the error bubble up and trigger server-side rollback.
3550 $this->onTransactionResolution(
3551 function () use ( $lockKey, $fname ) {
3552 $this->unlock( $lockKey, $fname );
3557 $this->unlock( $lockKey, $fname );
3561 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3566 public function namedLocksEnqueue() {
3571 * Lock specific tables
3573 * @param array $read Array of tables to lock for read access
3574 * @param array $write Array of tables to lock for write access
3575 * @param string $method Name of caller
3576 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3579 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3584 * Unlock specific tables
3586 * @param string $method The caller
3589 public function unlockTables( $method ) {
3595 * @param string $tableName
3596 * @param string $fName
3597 * @return bool|ResultWrapper
3600 public function dropTable( $tableName, $fName = __METHOD__
) {
3601 if ( !$this->tableExists( $tableName, $fName ) ) {
3604 $sql = "DROP TABLE " . $this->tableName( $tableName );
3605 if ( $this->cascadingDeletes() ) {
3609 return $this->query( $sql, $fName );
3613 * Get search engine class. All subclasses of this need to implement this
3614 * if they wish to use searching.
3618 public function getSearchEngine() {
3619 return 'SearchEngineDummy';
3622 public function getInfinity() {
3626 public function encodeExpiry( $expiry ) {
3627 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3628 ?
$this->getInfinity()
3629 : $this->timestamp( $expiry );
3632 public function decodeExpiry( $expiry, $format = TS_MW
) {
3633 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3635 : wfTimestamp( $format, $expiry );
3638 public function setBigSelects( $value = true ) {
3642 public function isReadOnly() {
3643 return ( $this->getReadOnlyReason() !== false );
3647 * @return string|bool Reason this DB is read-only or false if it is not
3649 protected function getReadOnlyReason() {
3650 $reason = $this->getLBInfo( 'readOnlyReason' );
3652 return is_string( $reason ) ?
$reason : false;
3655 public function setTableAliases( array $aliases ) {
3656 $this->tableAliases
= $aliases;
3663 public function __toString() {
3664 return (string)$this->mConn
;
3668 * Run a few simple sanity checks
3670 public function __destruct() {
3671 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3672 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3675 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3676 if ( $danglingWriters ) {
3677 $fnames = implode( ', ', $danglingWriters );
3678 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3686 abstract class Database
extends DatabaseBase
{
3687 // B/C until nothing type hints for DatabaseBase
3688 // @TODO: finish renaming DatabaseBase => Database