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 = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 /** @var BagOStuff APC cache */
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
79 /** @var resource Database connection */
80 protected $mConn = null;
82 protected $mOpened = false;
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var callable[] Map of (name => callable) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
96 protected $mTablePrefix;
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
114 protected $delimiter = ';';
117 * Either 1 if a transaction is active or 0 otherwise.
118 * The other Trx fields may not be meaningfull if this is 0.
122 protected $mTrxLevel = 0;
124 * Either a short hexidecimal string if a transaction is active or ""
127 * @see DatabaseBase::mTrxLevel
129 protected $mTrxShortId = '';
131 * The UNIX time that the transaction started. Callers can assume that if
132 * snapshot isolation is used, then the data is *at least* up to date to that
133 * point (possibly more up-to-date since the first SELECT defines the snapshot).
136 * @see DatabaseBase::mTrxLevel
138 private $mTrxTimestamp = null;
139 /** @var float Lag estimate at the time of BEGIN */
140 private $mTrxReplicaLag = null;
142 * Remembers the function name given for starting the most recent transaction via begin().
143 * Used to provide additional context for error reporting.
146 * @see DatabaseBase::mTrxLevel
148 private $mTrxFname = null;
150 * Record if possible write queries were done in the last transaction started
153 * @see DatabaseBase::mTrxLevel
155 private $mTrxDoneWrites = false;
157 * Record if the current transaction was started implicitly due to DBO_TRX being set.
160 * @see DatabaseBase::mTrxLevel
162 private $mTrxAutomatic = false;
164 * Array of levels of atomicity within transactions
168 private $mTrxAtomicLevels = [];
170 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
174 private $mTrxAutomaticAtomic = false;
176 * Track the write query callers of the current transaction
180 private $mTrxWriteCallers = [];
182 * @var float Seconds spent in write queries for the current transaction
184 private $mTrxWriteDuration = 0.0;
186 * @var integer Number of write queries for the current transaction
188 private $mTrxWriteQueryCount = 0;
190 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
192 private $mTrxWriteAdjDuration = 0.0;
194 * @var integer Number of write queries counted in mTrxWriteAdjDuration
196 private $mTrxWriteAdjQueryCount = 0;
198 * @var float RTT time estimate
200 private $mRTTEstimate = 0.0;
202 /** @var array Map of (name => 1) for locks obtained via lock() */
203 private $mNamedLocksHeld = [];
205 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
206 private $lazyMasterHandle;
210 * @var resource File handle for upgrade
212 protected $fileHandle = null;
216 * @var string[] Process cache of VIEWs names in the database
218 protected $allViews = null;
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
234 * FIXME: It is possible to construct a Database object with no associated
235 * connection object, by specifying no parameters to __construct(). This
236 * feature is deprecated and should be removed.
238 * IDatabase classes should not be constructed directly in external
239 * code. DatabaseBase::factory() should be used instead.
241 * @param array $params Parameters passed from DatabaseBase::factory()
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
248 $flags = $params['flags'];
250 $this->mSchema
= $params['schema'];
251 $this->mTablePrefix
= $params['tablePrefix'];
253 $this->cliMode
= isset( $params['cliMode'] )
255 : ( PHP_SAPI
=== 'cli' );
256 $this->agent
= isset( $params['agent'] )
257 ?
str_replace( '/', '-', $params['agent'] ) // escape for comment
260 $this->mFlags
= $flags;
261 if ( $this->mFlags
& DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~DBO_TRX
;
265 $this->mFlags |
= DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= isset( $params['profiler'] )
276 ?
$params['profiler']
277 : Profiler
::instance(); // @TODO: remove global state
278 $this->trxProfiler
= isset( $params['trxProfiler'] )
279 ?
$params['trxProfiler']
280 : new TransactionProfiler();
281 $this->connLogger
= isset( $params['connLogger'] )
282 ?
$params['connLogger']
283 : new \Psr\Log\
NullLogger();
284 $this->queryLogger
= isset( $params['queryLogger'] )
285 ?
$params['queryLogger']
286 : new \Psr\Log\
NullLogger();
289 $this->open( $server, $user, $password, $dbName );
294 * Given a DB type, construct the name of the appropriate child class of
295 * IDatabase. This is designed to replace all of the manual stuff like:
296 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
297 * as well as validate against the canonical list of DB types we have
299 * This factory function is mostly useful for when you need to connect to a
300 * database other than the MediaWiki default (such as for external auth,
301 * an extension, et cetera). Do not use this to connect to the MediaWiki
302 * database. Example uses in core:
303 * @see LoadBalancer::reallyOpenConnection()
304 * @see ForeignDBRepo::getMasterDB()
305 * @see WebInstallerDBConnect::execute()
309 * @param string $dbType A possible DB type
310 * @param array $p An array of options to pass to the constructor.
311 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
312 * @return IDatabase|null If the database driver or extension cannot be found
313 * @throws InvalidArgumentException If the database driver or extension cannot be found
315 final public static function factory( $dbType, $p = [] ) {
316 $canonicalDBTypes = [
317 'mysql' => [ 'mysqli', 'mysql' ],
325 $dbType = strtolower( $dbType );
326 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
327 $possibleDrivers = $canonicalDBTypes[$dbType];
328 if ( !empty( $p['driver'] ) ) {
329 if ( in_array( $p['driver'], $possibleDrivers ) ) {
330 $driver = $p['driver'];
332 throw new InvalidArgumentException( __METHOD__
.
333 " type '$dbType' does not support driver '{$p['driver']}'" );
336 foreach ( $possibleDrivers as $posDriver ) {
337 if ( extension_loaded( $posDriver ) ) {
338 $driver = $posDriver;
346 if ( $driver === false ) {
347 throw new InvalidArgumentException( __METHOD__
.
348 " no viable database extension found for type '$dbType'" );
351 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
352 // and everything else doesn't use a schema (e.g. null)
353 // Although postgres and oracle support schemas, we don't use them (yet)
354 // to maintain backwards compatibility
356 'mssql' => 'get from global',
359 $class = 'Database' . ucfirst( $driver );
360 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
361 // Resolve some defaults for b/c
362 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
363 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
364 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
365 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
366 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
367 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
368 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
369 if ( !isset( $p['schema'] ) ) {
370 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
372 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
374 $conn = new $class( $p );
375 if ( isset( $p['connLogger'] ) ) {
376 $conn->connLogger
= $p['connLogger'];
378 if ( isset( $p['queryLogger'] ) ) {
379 $conn->queryLogger
= $p['queryLogger'];
381 if ( isset( $p['errorLogger'] ) ) {
382 $conn->errorLogger
= $p['errorLogger'];
384 $conn->errorLogger
= function ( Exception
$e ) {
385 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
395 public function setLogger( LoggerInterface
$logger ) {
396 $this->queryLogger
= $logger;
399 public function getServerInfo() {
400 return $this->getServerVersion();
404 * @return string Command delimiter used by this database engine
406 public function getDelimiter() {
407 return $this->delimiter
;
411 * Boolean, controls output of large amounts of debug information.
412 * @param bool|null $debug
413 * - true to enable debugging
414 * - false to disable debugging
415 * - omitted or null to do nothing
417 * @return bool Previous value of the flag
418 * @deprecated since 1.28; use setFlag()
420 public function debug( $debug = null ) {
421 $res = $this->getFlag( DBO_DEBUG
);
422 if ( $debug !== null ) {
423 $debug ?
$this->setFlag( DBO_DEBUG
) : $this->clearFlag( DBO_DEBUG
);
429 public function bufferResults( $buffer = null ) {
430 $res = !$this->getFlag( DBO_NOBUFFER
);
431 if ( $buffer !== null ) {
432 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
439 * Turns on (false) or off (true) the automatic generation and sending
440 * of a "we're sorry, but there has been a database error" page on
441 * database errors. Default is on (false). When turned off, the
442 * code should use lastErrno() and lastError() to handle the
443 * situation as appropriate.
445 * Do not use this function outside of the Database classes.
447 * @param null|bool $ignoreErrors
448 * @return bool The previous value of the flag.
450 protected function ignoreErrors( $ignoreErrors = null ) {
451 $res = $this->getFlag( DBO_IGNORE
);
452 if ( $ignoreErrors !== null ) {
453 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
459 public function trxLevel() {
460 return $this->mTrxLevel
;
463 public function trxTimestamp() {
464 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
467 public function tablePrefix( $prefix = null ) {
468 $old = $this->mTablePrefix
;
469 $this->mTablePrefix
= $prefix;
474 public function dbSchema( $schema = null ) {
475 $old = $this->mSchema
;
476 $this->mSchema
= $schema;
482 * Set the filehandle to copy write statements to.
484 * @param resource $fh File handle
486 public function setFileHandle( $fh ) {
487 $this->fileHandle
= $fh;
490 public function getLBInfo( $name = null ) {
491 if ( is_null( $name ) ) {
492 return $this->mLBInfo
;
494 if ( array_key_exists( $name, $this->mLBInfo
) ) {
495 return $this->mLBInfo
[$name];
502 public function setLBInfo( $name, $value = null ) {
503 if ( is_null( $value ) ) {
504 $this->mLBInfo
= $name;
506 $this->mLBInfo
[$name] = $value;
510 public function setLazyMasterHandle( IDatabase
$conn ) {
511 $this->lazyMasterHandle
= $conn;
515 * @return IDatabase|null
516 * @see setLazyMasterHandle()
519 public function getLazyMasterHandle() {
520 return $this->lazyMasterHandle
;
524 * @param TransactionProfiler $profiler
527 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
528 $this->trxProfiler
= $profiler;
532 * Returns true if this database supports (and uses) cascading deletes
536 public function cascadingDeletes() {
541 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
545 public function cleanupTriggers() {
550 * Returns true if this database is strict about what can be put into an IP field.
551 * Specifically, it uses a NULL value instead of an empty string.
555 public function strictIPs() {
560 * Returns true if this database uses timestamps rather than integers
564 public function realTimestamps() {
568 public function implicitGroupby() {
572 public function implicitOrderby() {
577 * Returns true if this database can do a native search on IP columns
578 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
582 public function searchableIPs() {
587 * Returns true if this database can use functional indexes
591 public function functionalIndexes() {
595 public function lastQuery() {
596 return $this->mLastQuery
;
599 public function doneWrites() {
600 return (bool)$this->mDoneWrites
;
603 public function lastDoneWrites() {
604 return $this->mDoneWrites ?
: false;
607 public function writesPending() {
608 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
611 public function writesOrCallbacksPending() {
612 return $this->mTrxLevel
&& (
613 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
617 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
618 if ( !$this->mTrxLevel
) {
620 } elseif ( !$this->mTrxDoneWrites
) {
625 case self
::ESTIMATE_DB_APPLY
:
627 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
628 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
629 // For omitted queries, make them count as something at least
630 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
631 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
634 default: // everything
635 return $this->mTrxWriteDuration
;
639 public function pendingWriteCallers() {
640 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
643 public function isOpen() {
644 return $this->mOpened
;
647 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
648 if ( $remember === self
::REMEMBER_PRIOR
) {
649 array_push( $this->priorFlags
, $this->mFlags
);
651 $this->mFlags |
= $flag;
654 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
655 if ( $remember === self
::REMEMBER_PRIOR
) {
656 array_push( $this->priorFlags
, $this->mFlags
);
658 $this->mFlags
&= ~
$flag;
661 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
662 if ( !$this->priorFlags
) {
666 if ( $state === self
::RESTORE_INITIAL
) {
667 $this->mFlags
= reset( $this->priorFlags
);
668 $this->priorFlags
= [];
670 $this->mFlags
= array_pop( $this->priorFlags
);
674 public function getFlag( $flag ) {
675 return !!( $this->mFlags
& $flag );
678 public function getProperty( $name ) {
682 public function getWikiID() {
683 if ( $this->mTablePrefix
) {
684 return "{$this->mDBname}-{$this->mTablePrefix}";
686 return $this->mDBname
;
691 * Get information about an index into an object
692 * @param string $table Table name
693 * @param string $index Index name
694 * @param string $fname Calling function name
695 * @return mixed Database-specific index description class or false if the index does not exist
697 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
700 * Wrapper for addslashes()
702 * @param string $s String to be slashed.
703 * @return string Slashed string.
705 abstract function strencode( $s );
708 * Called by serialize. Throw an exception when DB connection is serialized.
709 * This causes problems on some database engines because the connection is
710 * not restored on unserialize.
712 public function __sleep() {
713 throw new RuntimeException( 'Database serialization may cause problems, since ' .
714 'the connection is not restored on wakeup.' );
717 protected function installErrorHandler() {
718 $this->mPHPError
= false;
719 $this->htmlErrors
= ini_set( 'html_errors', '0' );
720 set_error_handler( [ $this, 'connectionerrorLogger' ] );
724 * @return bool|string
726 protected function restoreErrorHandler() {
727 restore_error_handler();
728 if ( $this->htmlErrors
!== false ) {
729 ini_set( 'html_errors', $this->htmlErrors
);
731 if ( $this->mPHPError
) {
732 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
733 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
743 * @param string $errstr
745 public function connectionerrorLogger( $errno, $errstr ) {
746 $this->mPHPError
= $errstr;
750 * Create a log context to pass to PSR logging functions.
752 * @param array $extras Additional data to add to context
755 protected function getLogContext( array $extras = [] ) {
758 'db_server' => $this->mServer
,
759 'db_name' => $this->mDBname
,
760 'db_user' => $this->mUser
,
766 public function close() {
767 if ( $this->mConn
) {
768 if ( $this->trxLevel() ) {
769 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
772 $closed = $this->closeConnection();
773 $this->mConn
= false;
774 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
775 throw new RuntimeException( "Transaction callbacks still pending." );
779 $this->mOpened
= false;
785 * Make sure isOpen() returns true as a sanity check
787 * @throws DBUnexpectedError
789 protected function assertOpen() {
790 if ( !$this->isOpen() ) {
791 throw new DBUnexpectedError( $this, "DB connection was already closed." );
796 * Closes underlying database connection
798 * @return bool Whether connection was closed successfully
800 abstract protected function closeConnection();
802 function reportConnectionError( $error = 'Unknown error' ) {
803 $myError = $this->lastError();
809 throw new DBConnectionError( $this, $error );
813 * The DBMS-dependent part of query()
815 * @param string $sql SQL query.
816 * @return ResultWrapper|bool Result object to feed to fetchObject,
817 * fetchRow, ...; or false on failure
819 abstract protected function doQuery( $sql );
822 * Determine whether a query writes to the DB.
823 * Should return true if unsure.
828 protected function isWriteQuery( $sql ) {
830 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
835 * @return string|null
837 protected function getQueryVerb( $sql ) {
838 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
842 * Determine whether a SQL statement is sensitive to isolation level.
843 * A SQL statement is considered transactable if its result could vary
844 * depending on the transaction isolation level. Operational commands
845 * such as 'SET' and 'SHOW' are not considered to be transactable.
850 protected function isTransactableQuery( $sql ) {
851 $verb = $this->getQueryVerb( $sql );
852 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
855 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
856 $priorWritesPending = $this->writesOrCallbacksPending();
857 $this->mLastQuery
= $sql;
859 $isWrite = $this->isWriteQuery( $sql );
861 $reason = $this->getReadOnlyReason();
862 if ( $reason !== false ) {
863 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
865 # Set a flag indicating that writes have been done
866 $this->mDoneWrites
= microtime( true );
869 // Add trace comment to the begin of the sql string, right after the operator.
870 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
871 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
873 # Start implicit transactions that wrap the request if DBO_TRX is enabled
874 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
875 && $this->isTransactableQuery( $sql )
877 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
878 $this->mTrxAutomatic
= true;
881 # Keep track of whether the transaction has write queries pending
882 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
883 $this->mTrxDoneWrites
= true;
884 $this->trxProfiler
->transactionWritingIn(
885 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
888 if ( $this->debug() ) {
889 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
892 # Avoid fatals if close() was called
895 # Send the query to the server
896 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
898 # Try reconnecting if the connection was lost
899 if ( false === $ret && $this->wasErrorReissuable() ) {
900 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
901 # Stash the last error values before anything might clear them
902 $lastError = $this->lastError();
903 $lastErrno = $this->lastErrno();
904 # Update state tracking to reflect transaction loss due to disconnection
905 $this->handleTransactionLoss();
906 if ( $this->reconnect() ) {
907 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
908 $this->connLogger
->warning( $msg );
909 $this->queryLogger
->warning(
910 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
912 if ( !$recoverable ) {
913 # Callers may catch the exception and continue to use the DB
914 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
916 # Should be safe to silently retry the query
917 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
920 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
921 $this->connLogger
->error( $msg );
925 if ( false === $ret ) {
926 # Deadlocks cause the entire transaction to abort, not just the statement.
927 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
928 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
929 if ( $this->wasDeadlock() ) {
930 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
931 $tempIgnore = false; // not recoverable
933 # Update state tracking to reflect transaction loss
934 $this->handleTransactionLoss();
937 $this->reportQueryError(
938 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
941 $res = $this->resultObject( $ret );
946 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
947 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
948 # generalizeSQL() will probably cut down the query to reasonable
949 # logging size most of the time. The substr is really just a sanity check.
951 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
953 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
956 # Include query transaction state
957 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
959 $startTime = microtime( true );
960 $this->profiler
->profileIn( $queryProf );
961 $ret = $this->doQuery( $commentedSql );
962 $this->profiler
->profileOut( $queryProf );
963 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
965 unset( $queryProfSection ); // profile out (if set)
967 if ( $ret !== false ) {
968 $this->lastPing
= $startTime;
969 if ( $isWrite && $this->mTrxLevel
) {
970 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
971 $this->mTrxWriteCallers
[] = $fname;
975 if ( $sql === self
::PING_QUERY
) {
976 $this->mRTTEstimate
= $queryRuntime;
979 $this->trxProfiler
->recordQueryCompletion(
980 $queryProf, $startTime, $isWrite, $this->affectedRows()
982 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
988 * Update the estimated run-time of a query, not counting large row lock times
990 * LoadBalancer can be set to rollback transactions that will create huge replication
991 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
992 * queries, like inserting a row can take a long time due to row locking. This method
993 * uses some simple heuristics to discount those cases.
995 * @param string $sql A SQL write query
996 * @param float $runtime Total runtime, including RTT
998 private function updateTrxWriteQueryTime( $sql, $runtime ) {
999 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1000 $indicativeOfReplicaRuntime = true;
1001 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1002 $verb = $this->getQueryVerb( $sql );
1003 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1004 if ( $verb === 'INSERT' ) {
1005 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1006 } elseif ( $verb === 'REPLACE' ) {
1007 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1011 $this->mTrxWriteDuration +
= $runtime;
1012 $this->mTrxWriteQueryCount +
= 1;
1013 if ( $indicativeOfReplicaRuntime ) {
1014 $this->mTrxWriteAdjDuration +
= $runtime;
1015 $this->mTrxWriteAdjQueryCount +
= 1;
1019 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1020 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1021 # Dropped connections also mean that named locks are automatically released.
1022 # Only allow error suppression in autocommit mode or when the lost transaction
1023 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1024 if ( $this->mNamedLocksHeld
) {
1025 return false; // possible critical section violation
1026 } elseif ( $sql === 'COMMIT' ) {
1027 return !$priorWritesPending; // nothing written anyway? (T127428)
1028 } elseif ( $sql === 'ROLLBACK' ) {
1029 return true; // transaction lost...which is also what was requested :)
1030 } elseif ( $this->explicitTrxActive() ) {
1031 return false; // don't drop atomocity
1032 } elseif ( $priorWritesPending ) {
1033 return false; // prior writes lost from implicit transaction
1039 private function handleTransactionLoss() {
1040 $this->mTrxLevel
= 0;
1041 $this->mTrxIdleCallbacks
= []; // bug 65263
1042 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1044 // Handle callbacks in mTrxEndCallbacks
1045 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1046 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1048 } catch ( Exception
$e ) {
1049 // Already logged; move on...
1054 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1055 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1056 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1058 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1059 $this->queryLogger
->error(
1060 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1061 $this->getLogContext( [
1062 'method' => __METHOD__
,
1065 'sql1line' => $sql1line,
1069 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1070 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1075 * Intended to be compatible with the PEAR::DB wrapper functions.
1076 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1078 * ? = scalar value, quoted as necessary
1079 * ! = raw SQL bit (a function for instance)
1080 * & = filename; reads the file and inserts as a blob
1081 * (we don't use this though...)
1083 * @param string $sql
1084 * @param string $func
1088 protected function prepare( $sql, $func = __METHOD__
) {
1089 /* MySQL doesn't support prepared statements (yet), so just
1090 * pack up the query for reference. We'll manually replace
1093 return [ 'query' => $sql, 'func' => $func ];
1097 * Free a prepared query, generated by prepare().
1098 * @param string $prepared
1100 protected function freePrepared( $prepared ) {
1101 /* No-op by default */
1105 * Execute a prepared query with the various arguments
1106 * @param string $prepared The prepared sql
1107 * @param mixed $args Either an array here, or put scalars as varargs
1109 * @return ResultWrapper
1111 public function execute( $prepared, $args = null ) {
1112 if ( !is_array( $args ) ) {
1114 $args = func_get_args();
1115 array_shift( $args );
1118 $sql = $this->fillPrepared( $prepared['query'], $args );
1120 return $this->query( $sql, $prepared['func'] );
1124 * For faking prepared SQL statements on DBs that don't support it directly.
1126 * @param string $preparedQuery A 'preparable' SQL statement
1127 * @param array $args Array of Arguments to fill it with
1128 * @return string Executable SQL
1130 public function fillPrepared( $preparedQuery, $args ) {
1132 $this->preparedArgs
=& $args;
1134 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1135 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1139 * preg_callback func for fillPrepared()
1140 * The arguments should be in $this->preparedArgs and must not be touched
1141 * while we're doing this.
1143 * @param array $matches
1144 * @throws DBUnexpectedError
1147 protected function fillPreparedArg( $matches ) {
1148 switch ( $matches[1] ) {
1157 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1159 switch ( $matches[1] ) {
1161 return $this->addQuotes( $arg );
1165 # return $this->addQuotes( file_get_contents( $arg ) );
1166 throw new DBUnexpectedError(
1168 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1171 throw new DBUnexpectedError(
1173 'Received invalid match. This should never happen!'
1178 public function freeResult( $res ) {
1181 public function selectField(
1182 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1184 if ( $var === '*' ) { // sanity
1185 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1188 if ( !is_array( $options ) ) {
1189 $options = [ $options ];
1192 $options['LIMIT'] = 1;
1194 $res = $this->select( $table, $var, $cond, $fname, $options );
1195 if ( $res === false ||
!$this->numRows( $res ) ) {
1199 $row = $this->fetchRow( $res );
1201 if ( $row !== false ) {
1202 return reset( $row );
1208 public function selectFieldValues(
1209 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1211 if ( $var === '*' ) { // sanity
1212 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1213 } elseif ( !is_string( $var ) ) { // sanity
1214 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1217 if ( !is_array( $options ) ) {
1218 $options = [ $options ];
1221 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1222 if ( $res === false ) {
1227 foreach ( $res as $row ) {
1228 $values[] = $row->$var;
1235 * Returns an optional USE INDEX clause to go after the table, and a
1236 * string to go at the end of the query.
1238 * @param array $options Associative array of options to be turned into
1239 * an SQL query, valid keys are listed in the function.
1241 * @see DatabaseBase::select()
1243 public function makeSelectOptions( $options ) {
1244 $preLimitTail = $postLimitTail = '';
1249 foreach ( $options as $key => $option ) {
1250 if ( is_numeric( $key ) ) {
1251 $noKeyOptions[$option] = true;
1255 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1257 $preLimitTail .= $this->makeOrderBy( $options );
1259 // if (isset($options['LIMIT'])) {
1260 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1261 // isset($options['OFFSET']) ? $options['OFFSET']
1265 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1266 $postLimitTail .= ' FOR UPDATE';
1269 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1270 $postLimitTail .= ' LOCK IN SHARE MODE';
1273 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1274 $startOpts .= 'DISTINCT';
1277 # Various MySQL extensions
1278 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1279 $startOpts .= ' /*! STRAIGHT_JOIN */';
1282 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1283 $startOpts .= ' HIGH_PRIORITY';
1286 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1287 $startOpts .= ' SQL_BIG_RESULT';
1290 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1291 $startOpts .= ' SQL_BUFFER_RESULT';
1294 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1295 $startOpts .= ' SQL_SMALL_RESULT';
1298 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1299 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1302 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1303 $startOpts .= ' SQL_CACHE';
1306 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1307 $startOpts .= ' SQL_NO_CACHE';
1310 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1311 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1315 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1316 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1321 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1325 * Returns an optional GROUP BY with an optional HAVING
1327 * @param array $options Associative array of options
1329 * @see DatabaseBase::select()
1332 public function makeGroupByWithHaving( $options ) {
1334 if ( isset( $options['GROUP BY'] ) ) {
1335 $gb = is_array( $options['GROUP BY'] )
1336 ?
implode( ',', $options['GROUP BY'] )
1337 : $options['GROUP BY'];
1338 $sql .= ' GROUP BY ' . $gb;
1340 if ( isset( $options['HAVING'] ) ) {
1341 $having = is_array( $options['HAVING'] )
1342 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1343 : $options['HAVING'];
1344 $sql .= ' HAVING ' . $having;
1351 * Returns an optional ORDER BY
1353 * @param array $options Associative array of options
1355 * @see DatabaseBase::select()
1358 public function makeOrderBy( $options ) {
1359 if ( isset( $options['ORDER BY'] ) ) {
1360 $ob = is_array( $options['ORDER BY'] )
1361 ?
implode( ',', $options['ORDER BY'] )
1362 : $options['ORDER BY'];
1364 return ' ORDER BY ' . $ob;
1370 // See IDatabase::select for the docs for this function
1371 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1372 $options = [], $join_conds = [] ) {
1373 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1375 return $this->query( $sql, $fname );
1378 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1379 $options = [], $join_conds = []
1381 if ( is_array( $vars ) ) {
1382 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1385 $options = (array)$options;
1386 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1387 ?
$options['USE INDEX']
1389 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1390 ?
$options['IGNORE INDEX']
1393 if ( is_array( $table ) ) {
1395 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1396 } elseif ( $table != '' ) {
1397 if ( $table[0] == ' ' ) {
1398 $from = ' FROM ' . $table;
1401 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1407 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1408 $this->makeSelectOptions( $options );
1410 if ( !empty( $conds ) ) {
1411 if ( is_array( $conds ) ) {
1412 $conds = $this->makeList( $conds, LIST_AND
);
1414 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1416 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1419 if ( isset( $options['LIMIT'] ) ) {
1420 $sql = $this->limitResult( $sql, $options['LIMIT'],
1421 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1423 $sql = "$sql $postLimitTail";
1425 if ( isset( $options['EXPLAIN'] ) ) {
1426 $sql = 'EXPLAIN ' . $sql;
1432 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1433 $options = [], $join_conds = []
1435 $options = (array)$options;
1436 $options['LIMIT'] = 1;
1437 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1439 if ( $res === false ) {
1443 if ( !$this->numRows( $res ) ) {
1447 $obj = $this->fetchObject( $res );
1452 public function estimateRowCount(
1453 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1456 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1459 $row = $this->fetchRow( $res );
1460 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1466 public function selectRowCount(
1467 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1470 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1471 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1474 $row = $this->fetchRow( $res );
1475 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1482 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1483 * It's only slightly flawed. Don't use for anything important.
1485 * @param string $sql A SQL Query
1489 protected static function generalizeSQL( $sql ) {
1490 # This does the same as the regexp below would do, but in such a way
1491 # as to avoid crashing php on some large strings.
1492 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1494 $sql = str_replace( "\\\\", '', $sql );
1495 $sql = str_replace( "\\'", '', $sql );
1496 $sql = str_replace( "\\\"", '', $sql );
1497 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1498 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1500 # All newlines, tabs, etc replaced by single space
1501 $sql = preg_replace( '/\s+/', ' ', $sql );
1504 # except the ones surrounded by characters, e.g. l10n
1505 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1506 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1511 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1512 $info = $this->fieldInfo( $table, $field );
1517 public function indexExists( $table, $index, $fname = __METHOD__
) {
1518 if ( !$this->tableExists( $table ) ) {
1522 $info = $this->indexInfo( $table, $index, $fname );
1523 if ( is_null( $info ) ) {
1526 return $info !== false;
1530 public function tableExists( $table, $fname = __METHOD__
) {
1531 $table = $this->tableName( $table );
1532 $old = $this->ignoreErrors( true );
1533 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1534 $this->ignoreErrors( $old );
1539 public function indexUnique( $table, $index ) {
1540 $indexInfo = $this->indexInfo( $table, $index );
1542 if ( !$indexInfo ) {
1546 return !$indexInfo[0]->Non_unique
;
1550 * Helper for DatabaseBase::insert().
1552 * @param array $options
1555 protected function makeInsertOptions( $options ) {
1556 return implode( ' ', $options );
1559 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1560 # No rows to insert, easy just return now
1561 if ( !count( $a ) ) {
1565 $table = $this->tableName( $table );
1567 if ( !is_array( $options ) ) {
1568 $options = [ $options ];
1572 if ( isset( $options['fileHandle'] ) ) {
1573 $fh = $options['fileHandle'];
1575 $options = $this->makeInsertOptions( $options );
1577 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1579 $keys = array_keys( $a[0] );
1582 $keys = array_keys( $a );
1585 $sql = 'INSERT ' . $options .
1586 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1590 foreach ( $a as $row ) {
1596 $sql .= '(' . $this->makeList( $row ) . ')';
1599 $sql .= '(' . $this->makeList( $a ) . ')';
1602 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1604 } elseif ( $fh !== null ) {
1608 return (bool)$this->query( $sql, $fname );
1612 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1614 * @param array $options
1617 protected function makeUpdateOptionsArray( $options ) {
1618 if ( !is_array( $options ) ) {
1619 $options = [ $options ];
1624 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1625 $opts[] = $this->lowPriorityOption();
1628 if ( in_array( 'IGNORE', $options ) ) {
1636 * Make UPDATE options for the DatabaseBase::update function
1638 * @param array $options The options passed to DatabaseBase::update
1641 protected function makeUpdateOptions( $options ) {
1642 $opts = $this->makeUpdateOptionsArray( $options );
1644 return implode( ' ', $opts );
1647 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1648 $table = $this->tableName( $table );
1649 $opts = $this->makeUpdateOptions( $options );
1650 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1652 if ( $conds !== [] && $conds !== '*' ) {
1653 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1656 return $this->query( $sql, $fname );
1659 public function makeList( $a, $mode = LIST_COMMA
) {
1660 if ( !is_array( $a ) ) {
1661 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1667 foreach ( $a as $field => $value ) {
1669 if ( $mode == LIST_AND
) {
1671 } elseif ( $mode == LIST_OR
) {
1680 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1681 $list .= "($value)";
1682 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1684 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1685 // Remove null from array to be handled separately if found
1686 $includeNull = false;
1687 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1688 $includeNull = true;
1689 unset( $value[$nullKey] );
1691 if ( count( $value ) == 0 && !$includeNull ) {
1692 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1693 } elseif ( count( $value ) == 0 ) {
1694 // only check if $field is null
1695 $list .= "$field IS NULL";
1697 // IN clause contains at least one valid element
1698 if ( $includeNull ) {
1699 // Group subconditions to ensure correct precedence
1702 if ( count( $value ) == 1 ) {
1703 // Special-case single values, as IN isn't terribly efficient
1704 // Don't necessarily assume the single key is 0; we don't
1705 // enforce linear numeric ordering on other arrays here.
1706 $value = array_values( $value )[0];
1707 $list .= $field . " = " . $this->addQuotes( $value );
1709 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1711 // if null present in array, append IS NULL
1712 if ( $includeNull ) {
1713 $list .= " OR $field IS NULL)";
1716 } elseif ( $value === null ) {
1717 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1718 $list .= "$field IS ";
1719 } elseif ( $mode == LIST_SET
) {
1720 $list .= "$field = ";
1724 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1725 $list .= "$field = ";
1727 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1734 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1737 foreach ( $data as $base => $sub ) {
1738 if ( count( $sub ) ) {
1739 $conds[] = $this->makeList(
1740 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1746 return $this->makeList( $conds, LIST_OR
);
1748 // Nothing to search for...
1754 * Return aggregated value alias
1756 * @param array $valuedata
1757 * @param string $valuename
1761 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1765 public function bitNot( $field ) {
1769 public function bitAnd( $fieldLeft, $fieldRight ) {
1770 return "($fieldLeft & $fieldRight)";
1773 public function bitOr( $fieldLeft, $fieldRight ) {
1774 return "($fieldLeft | $fieldRight)";
1777 public function buildConcat( $stringList ) {
1778 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1781 public function buildGroupConcatField(
1782 $delim, $table, $field, $conds = '', $join_conds = []
1784 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1786 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1790 * @param string $field Field or column to cast
1794 public function buildStringCast( $field ) {
1798 public function selectDB( $db ) {
1799 # Stub. Shouldn't cause serious problems if it's not overridden, but
1800 # if your database engine supports a concept similar to MySQL's
1801 # databases you may as well.
1802 $this->mDBname
= $db;
1807 public function getDBname() {
1808 return $this->mDBname
;
1811 public function getServer() {
1812 return $this->mServer
;
1816 * Format a table name ready for use in constructing an SQL query
1818 * This does two important things: it quotes the table names to clean them up,
1819 * and it adds a table prefix if only given a table name with no quotes.
1821 * All functions of this object which require a table name call this function
1822 * themselves. Pass the canonical name to such functions. This is only needed
1823 * when calling query() directly.
1825 * @note This function does not sanitize user input. It is not safe to use
1826 * this function to escape user input.
1827 * @param string $name Database table name
1828 * @param string $format One of:
1829 * quoted - Automatically pass the table name through addIdentifierQuotes()
1830 * so that it can be used in a query.
1831 * raw - Do not add identifier quotes to the table name
1832 * @return string Full database name
1834 public function tableName( $name, $format = 'quoted' ) {
1835 # Skip the entire process when we have a string quoted on both ends.
1836 # Note that we check the end so that we will still quote any use of
1837 # use of `database`.table. But won't break things if someone wants
1838 # to query a database table with a dot in the name.
1839 if ( $this->isQuotedIdentifier( $name ) ) {
1843 # Lets test for any bits of text that should never show up in a table
1844 # name. Basically anything like JOIN or ON which are actually part of
1845 # SQL queries, but may end up inside of the table value to combine
1846 # sql. Such as how the API is doing.
1847 # Note that we use a whitespace test rather than a \b test to avoid
1848 # any remote case where a word like on may be inside of a table name
1849 # surrounded by symbols which may be considered word breaks.
1850 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1854 # Split database and table into proper variables.
1855 # We reverse the explode so that database.table and table both output
1856 # the correct table.
1857 $dbDetails = explode( '.', $name, 3 );
1858 if ( count( $dbDetails ) == 3 ) {
1859 list( $database, $schema, $table ) = $dbDetails;
1860 # We don't want any prefix added in this case
1862 } elseif ( count( $dbDetails ) == 2 ) {
1863 list( $database, $table ) = $dbDetails;
1864 # We don't want any prefix added in this case
1865 # In dbs that support it, $database may actually be the schema
1866 # but that doesn't affect any of the functionality here
1870 list( $table ) = $dbDetails;
1871 if ( isset( $this->tableAliases
[$table] ) ) {
1872 $database = $this->tableAliases
[$table]['dbname'];
1873 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1874 ?
$this->tableAliases
[$table]['schema']
1876 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1877 ?
$this->tableAliases
[$table]['prefix']
1878 : $this->mTablePrefix
;
1881 $schema = $this->mSchema
; # Default schema
1882 $prefix = $this->mTablePrefix
; # Default prefix
1886 # Quote $table and apply the prefix if not quoted.
1887 # $tableName might be empty if this is called from Database::replaceVars()
1888 $tableName = "{$prefix}{$table}";
1889 if ( $format == 'quoted'
1890 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1892 $tableName = $this->addIdentifierQuotes( $tableName );
1895 # Quote $schema and merge it with the table name if needed
1896 if ( strlen( $schema ) ) {
1897 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1898 $schema = $this->addIdentifierQuotes( $schema );
1900 $tableName = $schema . '.' . $tableName;
1903 # Quote $database and merge it with the table name if needed
1904 if ( $database !== null ) {
1905 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1906 $database = $this->addIdentifierQuotes( $database );
1908 $tableName = $database . '.' . $tableName;
1915 * Fetch a number of table names into an array
1916 * This is handy when you need to construct SQL for joins
1919 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1920 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1921 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1925 public function tableNames() {
1926 $inArray = func_get_args();
1929 foreach ( $inArray as $name ) {
1930 $retVal[$name] = $this->tableName( $name );
1937 * Fetch a number of table names into an zero-indexed numerical array
1938 * This is handy when you need to construct SQL for joins
1941 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1942 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1943 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1947 public function tableNamesN() {
1948 $inArray = func_get_args();
1951 foreach ( $inArray as $name ) {
1952 $retVal[] = $this->tableName( $name );
1959 * Get an aliased table name
1960 * e.g. tableName AS newTableName
1962 * @param string $name Table name, see tableName()
1963 * @param string|bool $alias Alias (optional)
1964 * @return string SQL name for aliased table. Will not alias a table to its own name
1966 public function tableNameWithAlias( $name, $alias = false ) {
1967 if ( !$alias ||
$alias == $name ) {
1968 return $this->tableName( $name );
1970 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1975 * Gets an array of aliased table names
1977 * @param array $tables [ [alias] => table ]
1978 * @return string[] See tableNameWithAlias()
1980 public function tableNamesWithAlias( $tables ) {
1982 foreach ( $tables as $alias => $table ) {
1983 if ( is_numeric( $alias ) ) {
1986 $retval[] = $this->tableNameWithAlias( $table, $alias );
1993 * Get an aliased field name
1994 * e.g. fieldName AS newFieldName
1996 * @param string $name Field name
1997 * @param string|bool $alias Alias (optional)
1998 * @return string SQL name for aliased field. Will not alias a field to its own name
2000 public function fieldNameWithAlias( $name, $alias = false ) {
2001 if ( !$alias ||
(string)$alias === (string)$name ) {
2004 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2009 * Gets an array of aliased field names
2011 * @param array $fields [ [alias] => field ]
2012 * @return string[] See fieldNameWithAlias()
2014 public function fieldNamesWithAlias( $fields ) {
2016 foreach ( $fields as $alias => $field ) {
2017 if ( is_numeric( $alias ) ) {
2020 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2027 * Get the aliased table name clause for a FROM clause
2028 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2030 * @param array $tables ( [alias] => table )
2031 * @param array $use_index Same as for select()
2032 * @param array $ignore_index Same as for select()
2033 * @param array $join_conds Same as for select()
2036 protected function tableNamesWithIndexClauseOrJOIN(
2037 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2041 $use_index = (array)$use_index;
2042 $ignore_index = (array)$ignore_index;
2043 $join_conds = (array)$join_conds;
2045 foreach ( $tables as $alias => $table ) {
2046 if ( !is_string( $alias ) ) {
2047 // No alias? Set it equal to the table name
2050 // Is there a JOIN clause for this table?
2051 if ( isset( $join_conds[$alias] ) ) {
2052 list( $joinType, $conds ) = $join_conds[$alias];
2053 $tableClause = $joinType;
2054 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2055 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2056 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2058 $tableClause .= ' ' . $use;
2061 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2062 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2063 if ( $ignore != '' ) {
2064 $tableClause .= ' ' . $ignore;
2067 $on = $this->makeList( (array)$conds, LIST_AND
);
2069 $tableClause .= ' ON (' . $on . ')';
2072 $retJOIN[] = $tableClause;
2073 } elseif ( isset( $use_index[$alias] ) ) {
2074 // Is there an INDEX clause for this table?
2075 $tableClause = $this->tableNameWithAlias( $table, $alias );
2076 $tableClause .= ' ' . $this->useIndexClause(
2077 implode( ',', (array)$use_index[$alias] )
2080 $ret[] = $tableClause;
2081 } elseif ( isset( $ignore_index[$alias] ) ) {
2082 // Is there an INDEX clause for this table?
2083 $tableClause = $this->tableNameWithAlias( $table, $alias );
2084 $tableClause .= ' ' . $this->ignoreIndexClause(
2085 implode( ',', (array)$ignore_index[$alias] )
2088 $ret[] = $tableClause;
2090 $tableClause = $this->tableNameWithAlias( $table, $alias );
2092 $ret[] = $tableClause;
2096 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2097 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2098 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2100 // Compile our final table clause
2101 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2105 * Get the name of an index in a given table.
2107 * @param string $index
2110 protected function indexName( $index ) {
2111 // Backwards-compatibility hack
2113 'ar_usertext_timestamp' => 'usertext_timestamp',
2114 'un_user_id' => 'user_id',
2115 'un_user_ip' => 'user_ip',
2118 if ( isset( $renamed[$index] ) ) {
2119 return $renamed[$index];
2125 public function addQuotes( $s ) {
2126 if ( $s instanceof Blob
) {
2129 if ( $s === null ) {
2132 # This will also quote numeric values. This should be harmless,
2133 # and protects against weird problems that occur when they really
2134 # _are_ strings such as article titles and string->number->string
2135 # conversion is not 1:1.
2136 return "'" . $this->strencode( $s ) . "'";
2141 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2142 * MySQL uses `backticks` while basically everything else uses double quotes.
2143 * Since MySQL is the odd one out here the double quotes are our generic
2144 * and we implement backticks in DatabaseMysql.
2149 public function addIdentifierQuotes( $s ) {
2150 return '"' . str_replace( '"', '""', $s ) . '"';
2154 * Returns if the given identifier looks quoted or not according to
2155 * the database convention for quoting identifiers .
2157 * @note Do not use this to determine if untrusted input is safe.
2158 * A malicious user can trick this function.
2159 * @param string $name
2162 public function isQuotedIdentifier( $name ) {
2163 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2170 protected function escapeLikeInternal( $s ) {
2171 return addcslashes( $s, '\%_' );
2174 public function buildLike() {
2175 $params = func_get_args();
2177 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2178 $params = $params[0];
2183 foreach ( $params as $value ) {
2184 if ( $value instanceof LikeMatch
) {
2185 $s .= $value->toString();
2187 $s .= $this->escapeLikeInternal( $value );
2191 return " LIKE {$this->addQuotes( $s )} ";
2194 public function anyChar() {
2195 return new LikeMatch( '_' );
2198 public function anyString() {
2199 return new LikeMatch( '%' );
2202 public function nextSequenceValue( $seqName ) {
2207 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2208 * is only needed because a) MySQL must be as efficient as possible due to
2209 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2210 * which index to pick. Anyway, other databases might have different
2211 * indexes on a given table. So don't bother overriding this unless you're
2213 * @param string $index
2216 public function useIndexClause( $index ) {
2221 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2222 * is only needed because a) MySQL must be as efficient as possible due to
2223 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2224 * which index to pick. Anyway, other databases might have different
2225 * indexes on a given table. So don't bother overriding this unless you're
2227 * @param string $index
2230 public function ignoreIndexClause( $index ) {
2234 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2235 $quotedTable = $this->tableName( $table );
2237 if ( count( $rows ) == 0 ) {
2242 if ( !is_array( reset( $rows ) ) ) {
2246 // @FXIME: this is not atomic, but a trx would break affectedRows()
2247 foreach ( $rows as $row ) {
2248 # Delete rows which collide
2249 if ( $uniqueIndexes ) {
2250 $sql = "DELETE FROM $quotedTable WHERE ";
2252 foreach ( $uniqueIndexes as $index ) {
2259 if ( is_array( $index ) ) {
2261 foreach ( $index as $col ) {
2267 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2270 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2274 $this->query( $sql, $fname );
2277 # Now insert the row
2278 $this->insert( $table, $row, $fname );
2283 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2286 * @param string $table Table name
2287 * @param array|string $rows Row(s) to insert
2288 * @param string $fname Caller function name
2290 * @return ResultWrapper
2292 protected function nativeReplace( $table, $rows, $fname ) {
2293 $table = $this->tableName( $table );
2296 if ( !is_array( reset( $rows ) ) ) {
2300 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2303 foreach ( $rows as $row ) {
2310 $sql .= '(' . $this->makeList( $row ) . ')';
2313 return $this->query( $sql, $fname );
2316 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2319 if ( !count( $rows ) ) {
2320 return true; // nothing to do
2323 if ( !is_array( reset( $rows ) ) ) {
2327 if ( count( $uniqueIndexes ) ) {
2328 $clauses = []; // list WHERE clauses that each identify a single row
2329 foreach ( $rows as $row ) {
2330 foreach ( $uniqueIndexes as $index ) {
2331 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2332 $rowKey = []; // unique key to this row
2333 foreach ( $index as $column ) {
2334 $rowKey[$column] = $row[$column];
2336 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2339 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2344 $useTrx = !$this->mTrxLevel
;
2346 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2349 # Update any existing conflicting row(s)
2350 if ( $where !== false ) {
2351 $ok = $this->update( $table, $set, $where, $fname );
2355 # Now insert any non-conflicting row(s)
2356 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2357 } catch ( Exception
$e ) {
2359 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2364 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2370 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2374 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2377 $delTable = $this->tableName( $delTable );
2378 $joinTable = $this->tableName( $joinTable );
2379 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2380 if ( $conds != '*' ) {
2381 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2385 $this->query( $sql, $fname );
2389 * Returns the size of a text field, or -1 for "unlimited"
2391 * @param string $table
2392 * @param string $field
2395 public function textFieldSize( $table, $field ) {
2396 $table = $this->tableName( $table );
2397 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2398 $res = $this->query( $sql, __METHOD__
);
2399 $row = $this->fetchObject( $res );
2403 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2413 * A string to insert into queries to show that they're low-priority, like
2414 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2415 * string and nothing bad should happen.
2417 * @return string Returns the text of the low priority option if it is
2418 * supported, or a blank string otherwise
2420 public function lowPriorityOption() {
2424 public function delete( $table, $conds, $fname = __METHOD__
) {
2426 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2429 $table = $this->tableName( $table );
2430 $sql = "DELETE FROM $table";
2432 if ( $conds != '*' ) {
2433 if ( is_array( $conds ) ) {
2434 $conds = $this->makeList( $conds, LIST_AND
);
2436 $sql .= ' WHERE ' . $conds;
2439 return $this->query( $sql, $fname );
2442 public function insertSelect(
2443 $destTable, $srcTable, $varMap, $conds,
2444 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2446 if ( $this->cliMode
) {
2447 // For massive migrations with downtime, we don't want to select everything
2448 // into memory and OOM, so do all this native on the server side if possible.
2449 return $this->nativeInsertSelect(
2460 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2461 // on only the master (without needing row-based-replication). It also makes it easy to
2462 // know how big the INSERT is going to be.
2464 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2465 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2467 $selectOptions[] = 'FOR UPDATE';
2468 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2474 foreach ( $res as $row ) {
2475 $rows[] = (array)$row;
2478 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2481 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2482 $fname = __METHOD__
,
2483 $insertOptions = [], $selectOptions = []
2485 $destTable = $this->tableName( $destTable );
2487 if ( !is_array( $insertOptions ) ) {
2488 $insertOptions = [ $insertOptions ];
2491 $insertOptions = $this->makeInsertOptions( $insertOptions );
2493 if ( !is_array( $selectOptions ) ) {
2494 $selectOptions = [ $selectOptions ];
2497 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2500 if ( is_array( $srcTable ) ) {
2501 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2503 $srcTable = $this->tableName( $srcTable );
2506 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2507 " SELECT $startOpts " . implode( ',', $varMap ) .
2508 " FROM $srcTable $useIndex $ignoreIndex ";
2510 if ( $conds != '*' ) {
2511 if ( is_array( $conds ) ) {
2512 $conds = $this->makeList( $conds, LIST_AND
);
2514 $sql .= " WHERE $conds";
2517 $sql .= " $tailOpts";
2519 return $this->query( $sql, $fname );
2523 * Construct a LIMIT query with optional offset. This is used for query
2524 * pages. The SQL should be adjusted so that only the first $limit rows
2525 * are returned. If $offset is provided as well, then the first $offset
2526 * rows should be discarded, and the next $limit rows should be returned.
2527 * If the result of the query is not ordered, then the rows to be returned
2528 * are theoretically arbitrary.
2530 * $sql is expected to be a SELECT, if that makes a difference.
2532 * The version provided by default works in MySQL and SQLite. It will very
2533 * likely need to be overridden for most other DBMSes.
2535 * @param string $sql SQL query we will append the limit too
2536 * @param int $limit The SQL limit
2537 * @param int|bool $offset The SQL offset (default false)
2538 * @throws DBUnexpectedError
2541 public function limitResult( $sql, $limit, $offset = false ) {
2542 if ( !is_numeric( $limit ) ) {
2543 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2546 return "$sql LIMIT "
2547 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2551 public function unionSupportsOrderAndLimit() {
2552 return true; // True for almost every DB supported
2555 public function unionQueries( $sqls, $all ) {
2556 $glue = $all ?
') UNION ALL (' : ') UNION (';
2558 return '(' . implode( $glue, $sqls ) . ')';
2561 public function conditional( $cond, $trueVal, $falseVal ) {
2562 if ( is_array( $cond ) ) {
2563 $cond = $this->makeList( $cond, LIST_AND
);
2566 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2569 public function strreplace( $orig, $old, $new ) {
2570 return "REPLACE({$orig}, {$old}, {$new})";
2573 public function getServerUptime() {
2577 public function wasDeadlock() {
2581 public function wasLockTimeout() {
2585 public function wasErrorReissuable() {
2589 public function wasReadOnlyError() {
2594 * Determines if the given query error was a connection drop
2597 * @param integer|string $errno
2600 public function wasConnectionError( $errno ) {
2605 * Perform a deadlock-prone transaction.
2607 * This function invokes a callback function to perform a set of write
2608 * queries. If a deadlock occurs during the processing, the transaction
2609 * will be rolled back and the callback function will be called again.
2611 * Avoid using this method outside of Job or Maintenance classes.
2614 * $dbw->deadlockLoop( callback, ... );
2616 * Extra arguments are passed through to the specified callback function.
2617 * This method requires that no transactions are already active to avoid
2618 * causing premature commits or exceptions.
2620 * Returns whatever the callback function returned on its successful,
2621 * iteration, or false on error, for example if the retry limit was
2625 * @throws DBUnexpectedError
2628 public function deadlockLoop() {
2629 $args = func_get_args();
2630 $function = array_shift( $args );
2631 $tries = self
::DEADLOCK_TRIES
;
2633 $this->begin( __METHOD__
);
2636 /** @var Exception $e */
2640 $retVal = call_user_func_array( $function, $args );
2642 } catch ( DBQueryError
$e ) {
2643 if ( $this->wasDeadlock() ) {
2644 // Retry after a randomized delay
2645 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2647 // Throw the error back up
2651 } while ( --$tries > 0 );
2653 if ( $tries <= 0 ) {
2654 // Too many deadlocks; give up
2655 $this->rollback( __METHOD__
);
2658 $this->commit( __METHOD__
);
2664 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2665 # Real waits are implemented in the subclass.
2669 public function getSlavePos() {
2674 public function getMasterPos() {
2679 public function serverIsReadOnly() {
2683 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2684 if ( !$this->mTrxLevel
) {
2685 throw new DBUnexpectedError( $this, "No transaction is active." );
2687 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2690 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2691 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2692 if ( !$this->mTrxLevel
) {
2693 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2697 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2698 if ( $this->mTrxLevel
) {
2699 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2701 // If no transaction is active, then make one for this callback
2702 $this->startAtomic( __METHOD__
);
2704 call_user_func( $callback );
2705 $this->endAtomic( __METHOD__
);
2706 } catch ( Exception
$e ) {
2707 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2713 final public function setTransactionListener( $name, callable
$callback = null ) {
2715 $this->mTrxRecurringCallbacks
[$name] = $callback;
2717 unset( $this->mTrxRecurringCallbacks
[$name] );
2722 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2724 * This method should not be used outside of Database/LoadBalancer
2726 * @param bool $suppress
2729 final public function setTrxEndCallbackSuppression( $suppress ) {
2730 $this->mTrxEndCallbacksSuppressed
= $suppress;
2734 * Actually run and consume any "on transaction idle/resolution" callbacks.
2736 * This method should not be used outside of Database/LoadBalancer
2738 * @param integer $trigger IDatabase::TRIGGER_* constant
2742 public function runOnTransactionIdleCallbacks( $trigger ) {
2743 if ( $this->mTrxEndCallbacksSuppressed
) {
2747 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2748 /** @var Exception $e */
2749 $e = null; // first exception
2750 do { // callbacks may add callbacks :)
2751 $callbacks = array_merge(
2752 $this->mTrxIdleCallbacks
,
2753 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2755 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2756 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2757 foreach ( $callbacks as $callback ) {
2759 list( $phpCallback ) = $callback;
2760 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2761 call_user_func_array( $phpCallback, [ $trigger ] );
2763 $this->setFlag( DBO_TRX
); // restore automatic begin()
2765 $this->clearFlag( DBO_TRX
); // restore auto-commit
2767 } catch ( Exception
$ex ) {
2768 call_user_func( $this->errorLogger
, $ex );
2770 // Some callbacks may use startAtomic/endAtomic, so make sure
2771 // their transactions are ended so other callbacks don't fail
2772 if ( $this->trxLevel() ) {
2773 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2777 } while ( count( $this->mTrxIdleCallbacks
) );
2779 if ( $e instanceof Exception
) {
2780 throw $e; // re-throw any first exception
2785 * Actually run and consume any "on transaction pre-commit" callbacks.
2787 * This method should not be used outside of Database/LoadBalancer
2792 public function runOnTransactionPreCommitCallbacks() {
2793 $e = null; // first exception
2794 do { // callbacks may add callbacks :)
2795 $callbacks = $this->mTrxPreCommitCallbacks
;
2796 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2797 foreach ( $callbacks as $callback ) {
2799 list( $phpCallback ) = $callback;
2800 call_user_func( $phpCallback );
2801 } catch ( Exception
$ex ) {
2802 call_user_func( $this->errorLogger
, $ex );
2806 } while ( count( $this->mTrxPreCommitCallbacks
) );
2808 if ( $e instanceof Exception
) {
2809 throw $e; // re-throw any first exception
2814 * Actually run any "transaction listener" callbacks.
2816 * This method should not be used outside of Database/LoadBalancer
2818 * @param integer $trigger IDatabase::TRIGGER_* constant
2822 public function runTransactionListenerCallbacks( $trigger ) {
2823 if ( $this->mTrxEndCallbacksSuppressed
) {
2827 /** @var Exception $e */
2828 $e = null; // first exception
2830 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2832 $phpCallback( $trigger, $this );
2833 } catch ( Exception
$ex ) {
2834 call_user_func( $this->errorLogger
, $ex );
2839 if ( $e instanceof Exception
) {
2840 throw $e; // re-throw any first exception
2844 final public function startAtomic( $fname = __METHOD__
) {
2845 if ( !$this->mTrxLevel
) {
2846 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2847 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2848 // in all changes being in one transaction to keep requests transactional.
2849 if ( !$this->getFlag( DBO_TRX
) ) {
2850 $this->mTrxAutomaticAtomic
= true;
2854 $this->mTrxAtomicLevels
[] = $fname;
2857 final public function endAtomic( $fname = __METHOD__
) {
2858 if ( !$this->mTrxLevel
) {
2859 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2861 if ( !$this->mTrxAtomicLevels ||
2862 array_pop( $this->mTrxAtomicLevels
) !== $fname
2864 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2867 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2868 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2872 final public function doAtomicSection( $fname, callable
$callback ) {
2873 $this->startAtomic( $fname );
2875 $res = call_user_func_array( $callback, [ $this, $fname ] );
2876 } catch ( Exception
$e ) {
2877 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2880 $this->endAtomic( $fname );
2885 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2886 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2887 if ( $this->mTrxLevel
) {
2888 if ( $this->mTrxAtomicLevels
) {
2889 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2890 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2891 throw new DBUnexpectedError( $this, $msg );
2892 } elseif ( !$this->mTrxAutomatic
) {
2893 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2894 throw new DBUnexpectedError( $this, $msg );
2896 // @TODO: make this an exception at some point
2897 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2898 $this->queryLogger
->error( $msg );
2899 return; // join the main transaction set
2901 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2902 // @TODO: make this an exception at some point
2903 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2904 $this->queryLogger
->error( $msg );
2905 return; // let any writes be in the main transaction
2908 // Avoid fatals if close() was called
2909 $this->assertOpen();
2911 $this->doBegin( $fname );
2912 $this->mTrxTimestamp
= microtime( true );
2913 $this->mTrxFname
= $fname;
2914 $this->mTrxDoneWrites
= false;
2915 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2916 $this->mTrxAutomaticAtomic
= false;
2917 $this->mTrxAtomicLevels
= [];
2918 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2919 $this->mTrxWriteDuration
= 0.0;
2920 $this->mTrxWriteQueryCount
= 0;
2921 $this->mTrxWriteAdjDuration
= 0.0;
2922 $this->mTrxWriteAdjQueryCount
= 0;
2923 $this->mTrxWriteCallers
= [];
2924 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2925 // Get an estimate of the replica DB lag before then, treating estimate staleness
2926 // as lag itself just to be safe
2927 $status = $this->getApproximateLagStatus();
2928 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2932 * Issues the BEGIN command to the database server.
2934 * @see DatabaseBase::begin()
2935 * @param string $fname
2937 protected function doBegin( $fname ) {
2938 $this->query( 'BEGIN', $fname );
2939 $this->mTrxLevel
= 1;
2942 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2943 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2944 // There are still atomic sections open. This cannot be ignored
2945 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2946 throw new DBUnexpectedError(
2948 "$fname: Got COMMIT while atomic sections $levels are still open."
2952 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2953 if ( !$this->mTrxLevel
) {
2954 return; // nothing to do
2955 } elseif ( !$this->mTrxAutomatic
) {
2956 throw new DBUnexpectedError(
2958 "$fname: Flushing an explicit transaction, getting out of sync."
2962 if ( !$this->mTrxLevel
) {
2963 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2964 return; // nothing to do
2965 } elseif ( $this->mTrxAutomatic
) {
2966 // @TODO: make this an exception at some point
2967 $msg = "$fname: Explicit commit of implicit transaction.";
2968 $this->queryLogger
->error( $msg );
2969 return; // wait for the main transaction set commit round
2973 // Avoid fatals if close() was called
2974 $this->assertOpen();
2976 $this->runOnTransactionPreCommitCallbacks();
2977 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2978 $this->doCommit( $fname );
2979 if ( $this->mTrxDoneWrites
) {
2980 $this->mDoneWrites
= microtime( true );
2981 $this->trxProfiler
->transactionWritingOut(
2982 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2985 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2986 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2990 * Issues the COMMIT command to the database server.
2992 * @see DatabaseBase::commit()
2993 * @param string $fname
2995 protected function doCommit( $fname ) {
2996 if ( $this->mTrxLevel
) {
2997 $this->query( 'COMMIT', $fname );
2998 $this->mTrxLevel
= 0;
3002 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3003 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3004 if ( !$this->mTrxLevel
) {
3005 return; // nothing to do
3008 if ( !$this->mTrxLevel
) {
3009 $this->queryLogger
->error(
3010 "$fname: No transaction to rollback, something got out of sync." );
3011 return; // nothing to do
3012 } elseif ( $this->getFlag( DBO_TRX
) ) {
3013 throw new DBUnexpectedError(
3015 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3020 // Avoid fatals if close() was called
3021 $this->assertOpen();
3023 $this->doRollback( $fname );
3024 $this->mTrxAtomicLevels
= [];
3025 if ( $this->mTrxDoneWrites
) {
3026 $this->trxProfiler
->transactionWritingOut(
3027 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3030 $this->mTrxIdleCallbacks
= []; // clear
3031 $this->mTrxPreCommitCallbacks
= []; // clear
3032 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3033 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3037 * Issues the ROLLBACK command to the database server.
3039 * @see DatabaseBase::rollback()
3040 * @param string $fname
3042 protected function doRollback( $fname ) {
3043 if ( $this->mTrxLevel
) {
3044 # Disconnects cause rollback anyway, so ignore those errors
3045 $ignoreErrors = true;
3046 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3047 $this->mTrxLevel
= 0;
3051 public function flushSnapshot( $fname = __METHOD__
) {
3052 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3053 // This only flushes transactions to clear snapshots, not to write data
3054 throw new DBUnexpectedError(
3056 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3060 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3063 public function explicitTrxActive() {
3064 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3068 * Creates a new table with structure copied from existing table
3069 * Note that unlike most database abstraction functions, this function does not
3070 * automatically append database prefix, because it works at a lower
3071 * abstraction level.
3072 * The table names passed to this function shall not be quoted (this
3073 * function calls addIdentifierQuotes when needed).
3075 * @param string $oldName Name of table whose structure should be copied
3076 * @param string $newName Name of table to be created
3077 * @param bool $temporary Whether the new table should be temporary
3078 * @param string $fname Calling function name
3079 * @throws RuntimeException
3080 * @return bool True if operation was successful
3082 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3085 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3088 function listTables( $prefix = null, $fname = __METHOD__
) {
3089 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3093 * Reset the views process cache set by listViews()
3096 final public function clearViewsCache() {
3097 $this->allViews
= null;
3101 * Lists all the VIEWs in the database
3103 * For caching purposes the list of all views should be stored in
3104 * $this->allViews. The process cache can be cleared with clearViewsCache()
3106 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3107 * @param string $fname Name of calling function
3108 * @throws RuntimeException
3112 public function listViews( $prefix = null, $fname = __METHOD__
) {
3113 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3117 * Differentiates between a TABLE and a VIEW
3119 * @param string $name Name of the database-structure to test.
3120 * @throws RuntimeException
3124 public function isView( $name ) {
3125 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3128 public function timestamp( $ts = 0 ) {
3129 return wfTimestamp( TS_MW
, $ts );
3132 public function timestampOrNull( $ts = null ) {
3133 if ( is_null( $ts ) ) {
3136 return $this->timestamp( $ts );
3141 * Take the result from a query, and wrap it in a ResultWrapper if
3142 * necessary. Boolean values are passed through as is, to indicate success
3143 * of write queries or failure.
3145 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3146 * resource, and it was necessary to call this function to convert it to
3147 * a wrapper. Nowadays, raw database objects are never exposed to external
3148 * callers, so this is unnecessary in external code.
3150 * @param bool|ResultWrapper|resource|object $result
3151 * @return bool|ResultWrapper
3153 protected function resultObject( $result ) {
3156 } elseif ( $result instanceof ResultWrapper
) {
3158 } elseif ( $result === true ) {
3159 // Successful write query
3162 return new ResultWrapper( $this, $result );
3166 public function ping( &$rtt = null ) {
3167 // Avoid hitting the server if it was hit recently
3168 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3169 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3170 $rtt = $this->mRTTEstimate
;
3171 return true; // don't care about $rtt
3175 // This will reconnect if possible or return false if not
3176 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3177 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3178 $this->restoreFlags( self
::RESTORE_PRIOR
);
3181 $rtt = $this->mRTTEstimate
;
3190 protected function reconnect() {
3191 $this->closeConnection();
3192 $this->mOpened
= false;
3193 $this->mConn
= false;
3195 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3196 $this->lastPing
= microtime( true );
3198 } catch ( DBConnectionError
$e ) {
3205 public function getSessionLagStatus() {
3206 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3210 * Get the replica DB lag when the current transaction started
3212 * This is useful when transactions might use snapshot isolation
3213 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3214 * is this lag plus transaction duration. If they don't, it is still
3215 * safe to be pessimistic. This returns null if there is no transaction.
3217 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3220 public function getTransactionLagStatus() {
3221 return $this->mTrxLevel
3222 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3227 * Get a replica DB lag estimate for this server
3229 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3232 public function getApproximateLagStatus() {
3234 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3235 'since' => microtime( true )
3240 * Merge the result of getSessionLagStatus() for several DBs
3241 * using the most pessimistic values to estimate the lag of
3242 * any data derived from them in combination
3244 * This is information is useful for caching modules
3246 * @see WANObjectCache::set()
3247 * @see WANObjectCache::getWithSetCallback()
3249 * @param IDatabase $db1
3250 * @param IDatabase ...
3251 * @return array Map of values:
3252 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3253 * - since: oldest UNIX timestamp of any of the DB lag estimates
3254 * - pending: whether any of the DBs have uncommitted changes
3257 public static function getCacheSetOptions( IDatabase
$db1 ) {
3258 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3259 foreach ( func_get_args() as $db ) {
3260 /** @var IDatabase $db */
3261 $status = $db->getSessionLagStatus();
3262 if ( $status['lag'] === false ) {
3263 $res['lag'] = false;
3264 } elseif ( $res['lag'] !== false ) {
3265 $res['lag'] = max( $res['lag'], $status['lag'] );
3267 $res['since'] = min( $res['since'], $status['since'] );
3268 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3274 public function getLag() {
3278 function maxListLen() {
3282 public function encodeBlob( $b ) {
3286 public function decodeBlob( $b ) {
3287 if ( $b instanceof Blob
) {
3293 public function setSessionOptions( array $options ) {
3297 * Read and execute SQL commands from a file.
3299 * Returns true on success, error string or exception on failure (depending
3300 * on object's error ignore settings).
3302 * @param string $filename File name to open
3303 * @param bool|callable $lineCallback Optional function called before reading each line
3304 * @param bool|callable $resultCallback Optional function called for each MySQL result
3305 * @param bool|string $fname Calling function name or false if name should be
3306 * generated dynamically using $filename
3307 * @param bool|callable $inputCallback Optional function called for each
3308 * complete line sent
3309 * @return bool|string
3312 public function sourceFile(
3313 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3315 MediaWiki\
suppressWarnings();
3316 $fp = fopen( $filename, 'r' );
3317 MediaWiki\restoreWarnings
();
3319 if ( false === $fp ) {
3320 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3324 $fname = __METHOD__
. "( $filename )";
3328 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3329 } catch ( Exception
$e ) {
3339 public function setSchemaVars( $vars ) {
3340 $this->mSchemaVars
= $vars;
3344 * Read and execute commands from an open file handle.
3346 * Returns true on success, error string or exception on failure (depending
3347 * on object's error ignore settings).
3349 * @param resource $fp File handle
3350 * @param bool|callable $lineCallback Optional function called before reading each query
3351 * @param bool|callable $resultCallback Optional function called for each MySQL result
3352 * @param string $fname Calling function name
3353 * @param bool|callable $inputCallback Optional function called for each complete query sent
3354 * @return bool|string
3356 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3357 $fname = __METHOD__
, $inputCallback = false
3361 while ( !feof( $fp ) ) {
3362 if ( $lineCallback ) {
3363 call_user_func( $lineCallback );
3366 $line = trim( fgets( $fp ) );
3368 if ( $line == '' ) {
3372 if ( '-' == $line[0] && '-' == $line[1] ) {
3380 $done = $this->streamStatementEnd( $cmd, $line );
3384 if ( $done ||
feof( $fp ) ) {
3385 $cmd = $this->replaceVars( $cmd );
3387 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3388 $res = $this->query( $cmd, $fname );
3390 if ( $resultCallback ) {
3391 call_user_func( $resultCallback, $res, $this );
3394 if ( false === $res ) {
3395 $err = $this->lastError();
3397 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3408 * Called by sourceStream() to check if we've reached a statement end
3410 * @param string $sql SQL assembled so far
3411 * @param string $newLine New line about to be added to $sql
3412 * @return bool Whether $newLine contains end of the statement
3414 public function streamStatementEnd( &$sql, &$newLine ) {
3415 if ( $this->delimiter
) {
3417 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3418 if ( $newLine != $prev ) {
3427 * Database independent variable replacement. Replaces a set of variables
3428 * in an SQL statement with their contents as given by $this->getSchemaVars().
3430 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3432 * - '{$var}' should be used for text and is passed through the database's
3434 * - `{$var}` should be used for identifiers (e.g. table and database names).
3435 * It is passed through the database's addIdentifierQuotes method which
3436 * can be overridden if the database uses something other than backticks.
3437 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3438 * database's tableName method.
3439 * - / *i* / passes the name that follows through the database's indexName method.
3440 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3441 * its use should be avoided. In 1.24 and older, string encoding was applied.
3443 * @param string $ins SQL statement to replace variables in
3444 * @return string The new SQL statement with variables replaced
3446 protected function replaceVars( $ins ) {
3447 $vars = $this->getSchemaVars();
3448 return preg_replace_callback(
3450 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3451 \'\{\$ (\w+) }\' | # 3. addQuotes
3452 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3453 /\*\$ (\w+) \*/ # 5. leave unencoded
3455 function ( $m ) use ( $vars ) {
3456 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3457 // check for both nonexistent keys *and* the empty string.
3458 if ( isset( $m[1] ) && $m[1] !== '' ) {
3459 if ( $m[1] === 'i' ) {
3460 return $this->indexName( $m[2] );
3462 return $this->tableName( $m[2] );
3464 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3465 return $this->addQuotes( $vars[$m[3]] );
3466 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3467 return $this->addIdentifierQuotes( $vars[$m[4]] );
3468 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3469 return $vars[$m[5]];
3479 * Get schema variables. If none have been set via setSchemaVars(), then
3480 * use some defaults from the current object.
3484 protected function getSchemaVars() {
3485 if ( $this->mSchemaVars
) {
3486 return $this->mSchemaVars
;
3488 return $this->getDefaultSchemaVars();
3493 * Get schema variables to use if none have been set via setSchemaVars().
3495 * Override this in derived classes to provide variables for tables.sql
3496 * and SQL patch files.
3500 protected function getDefaultSchemaVars() {
3504 public function lockIsFree( $lockName, $method ) {
3508 public function lock( $lockName, $method, $timeout = 5 ) {
3509 $this->mNamedLocksHeld
[$lockName] = 1;
3514 public function unlock( $lockName, $method ) {
3515 unset( $this->mNamedLocksHeld
[$lockName] );
3520 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3521 if ( $this->writesOrCallbacksPending() ) {
3522 // This only flushes transactions to clear snapshots, not to write data
3523 throw new DBUnexpectedError(
3525 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3529 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3533 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3534 if ( $this->trxLevel() ) {
3535 // There is a good chance an exception was thrown, causing any early return
3536 // from the caller. Let any error handler get a chance to issue rollback().
3537 // If there isn't one, let the error bubble up and trigger server-side rollback.
3538 $this->onTransactionResolution(
3539 function () use ( $lockKey, $fname ) {
3540 $this->unlock( $lockKey, $fname );
3545 $this->unlock( $lockKey, $fname );
3549 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3554 public function namedLocksEnqueue() {
3559 * Lock specific tables
3561 * @param array $read Array of tables to lock for read access
3562 * @param array $write Array of tables to lock for write access
3563 * @param string $method Name of caller
3564 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3567 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3572 * Unlock specific tables
3574 * @param string $method The caller
3577 public function unlockTables( $method ) {
3583 * @param string $tableName
3584 * @param string $fName
3585 * @return bool|ResultWrapper
3588 public function dropTable( $tableName, $fName = __METHOD__
) {
3589 if ( !$this->tableExists( $tableName, $fName ) ) {
3592 $sql = "DROP TABLE " . $this->tableName( $tableName );
3593 if ( $this->cascadingDeletes() ) {
3597 return $this->query( $sql, $fName );
3601 * Get search engine class. All subclasses of this need to implement this
3602 * if they wish to use searching.
3606 public function getSearchEngine() {
3607 return 'SearchEngineDummy';
3610 public function getInfinity() {
3614 public function encodeExpiry( $expiry ) {
3615 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3616 ?
$this->getInfinity()
3617 : $this->timestamp( $expiry );
3620 public function decodeExpiry( $expiry, $format = TS_MW
) {
3621 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3623 : wfTimestamp( $format, $expiry );
3626 public function setBigSelects( $value = true ) {
3630 public function isReadOnly() {
3631 return ( $this->getReadOnlyReason() !== false );
3635 * @return string|bool Reason this DB is read-only or false if it is not
3637 protected function getReadOnlyReason() {
3638 $reason = $this->getLBInfo( 'readOnlyReason' );
3640 return is_string( $reason ) ?
$reason : false;
3643 public function setTableAliases( array $aliases ) {
3644 $this->tableAliases
= $aliases;
3651 public function __toString() {
3652 return (string)$this->mConn
;
3656 * Run a few simple sanity checks
3658 public function __destruct() {
3659 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3660 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3662 $danglingCallbacks = array_merge(
3663 $this->mTrxIdleCallbacks
,
3664 $this->mTrxPreCommitCallbacks
,
3665 $this->mTrxEndCallbacks
3667 if ( $danglingCallbacks ) {
3669 foreach ( $danglingCallbacks as $callbackInfo ) {
3670 $callers[] = $callbackInfo[1];
3672 $callers = implode( ', ', $callers );
3673 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3681 abstract class Database
extends DatabaseBase
{
3682 // B/C until nothing type hints for DatabaseBase
3683 // @TODO: finish renaming DatabaseBase => Database