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 protected function pendingWriteAndCallbackCallers() {
644 if ( !$this->mTrxLevel
) {
648 $fnames = $this->mTrxWriteCallers
;
650 $this->mTrxIdleCallbacks
,
651 $this->mTrxPreCommitCallbacks
,
652 $this->mTrxEndCallbacks
654 foreach ( $callbacks as $callback ) {
655 $fnames[] = $callback[1];
662 public function isOpen() {
663 return $this->mOpened
;
666 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
667 if ( $remember === self
::REMEMBER_PRIOR
) {
668 array_push( $this->priorFlags
, $this->mFlags
);
670 $this->mFlags |
= $flag;
673 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
674 if ( $remember === self
::REMEMBER_PRIOR
) {
675 array_push( $this->priorFlags
, $this->mFlags
);
677 $this->mFlags
&= ~
$flag;
680 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
681 if ( !$this->priorFlags
) {
685 if ( $state === self
::RESTORE_INITIAL
) {
686 $this->mFlags
= reset( $this->priorFlags
);
687 $this->priorFlags
= [];
689 $this->mFlags
= array_pop( $this->priorFlags
);
693 public function getFlag( $flag ) {
694 return !!( $this->mFlags
& $flag );
697 public function getProperty( $name ) {
701 public function getWikiID() {
702 if ( $this->mTablePrefix
) {
703 return "{$this->mDBname}-{$this->mTablePrefix}";
705 return $this->mDBname
;
710 * Get information about an index into an object
711 * @param string $table Table name
712 * @param string $index Index name
713 * @param string $fname Calling function name
714 * @return mixed Database-specific index description class or false if the index does not exist
716 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
719 * Wrapper for addslashes()
721 * @param string $s String to be slashed.
722 * @return string Slashed string.
724 abstract function strencode( $s );
727 * Called by serialize. Throw an exception when DB connection is serialized.
728 * This causes problems on some database engines because the connection is
729 * not restored on unserialize.
731 public function __sleep() {
732 throw new RuntimeException( 'Database serialization may cause problems, since ' .
733 'the connection is not restored on wakeup.' );
736 protected function installErrorHandler() {
737 $this->mPHPError
= false;
738 $this->htmlErrors
= ini_set( 'html_errors', '0' );
739 set_error_handler( [ $this, 'connectionerrorLogger' ] );
743 * @return bool|string
745 protected function restoreErrorHandler() {
746 restore_error_handler();
747 if ( $this->htmlErrors
!== false ) {
748 ini_set( 'html_errors', $this->htmlErrors
);
750 if ( $this->mPHPError
) {
751 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
752 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
762 * @param string $errstr
764 public function connectionerrorLogger( $errno, $errstr ) {
765 $this->mPHPError
= $errstr;
769 * Create a log context to pass to PSR logging functions.
771 * @param array $extras Additional data to add to context
774 protected function getLogContext( array $extras = [] ) {
777 'db_server' => $this->mServer
,
778 'db_name' => $this->mDBname
,
779 'db_user' => $this->mUser
,
785 public function close() {
786 if ( $this->mConn
) {
787 if ( $this->trxLevel() ) {
788 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
791 $closed = $this->closeConnection();
792 $this->mConn
= false;
793 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
794 throw new RuntimeException( "Transaction callbacks still pending." );
798 $this->mOpened
= false;
804 * Make sure isOpen() returns true as a sanity check
806 * @throws DBUnexpectedError
808 protected function assertOpen() {
809 if ( !$this->isOpen() ) {
810 throw new DBUnexpectedError( $this, "DB connection was already closed." );
815 * Closes underlying database connection
817 * @return bool Whether connection was closed successfully
819 abstract protected function closeConnection();
821 function reportConnectionError( $error = 'Unknown error' ) {
822 $myError = $this->lastError();
828 throw new DBConnectionError( $this, $error );
832 * The DBMS-dependent part of query()
834 * @param string $sql SQL query.
835 * @return ResultWrapper|bool Result object to feed to fetchObject,
836 * fetchRow, ...; or false on failure
838 abstract protected function doQuery( $sql );
841 * Determine whether a query writes to the DB.
842 * Should return true if unsure.
847 protected function isWriteQuery( $sql ) {
849 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
854 * @return string|null
856 protected function getQueryVerb( $sql ) {
857 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
861 * Determine whether a SQL statement is sensitive to isolation level.
862 * A SQL statement is considered transactable if its result could vary
863 * depending on the transaction isolation level. Operational commands
864 * such as 'SET' and 'SHOW' are not considered to be transactable.
869 protected function isTransactableQuery( $sql ) {
870 $verb = $this->getQueryVerb( $sql );
871 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
874 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
875 $priorWritesPending = $this->writesOrCallbacksPending();
876 $this->mLastQuery
= $sql;
878 $isWrite = $this->isWriteQuery( $sql );
880 $reason = $this->getReadOnlyReason();
881 if ( $reason !== false ) {
882 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
884 # Set a flag indicating that writes have been done
885 $this->mDoneWrites
= microtime( true );
888 // Add trace comment to the begin of the sql string, right after the operator.
889 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
890 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
892 # Start implicit transactions that wrap the request if DBO_TRX is enabled
893 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
894 && $this->isTransactableQuery( $sql )
896 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
897 $this->mTrxAutomatic
= true;
900 # Keep track of whether the transaction has write queries pending
901 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
902 $this->mTrxDoneWrites
= true;
903 $this->trxProfiler
->transactionWritingIn(
904 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
907 if ( $this->debug() ) {
908 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
911 # Avoid fatals if close() was called
914 # Send the query to the server
915 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
917 # Try reconnecting if the connection was lost
918 if ( false === $ret && $this->wasErrorReissuable() ) {
919 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
920 # Stash the last error values before anything might clear them
921 $lastError = $this->lastError();
922 $lastErrno = $this->lastErrno();
923 # Update state tracking to reflect transaction loss due to disconnection
924 $this->handleTransactionLoss();
925 if ( $this->reconnect() ) {
926 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
927 $this->connLogger
->warning( $msg );
928 $this->queryLogger
->warning(
929 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
931 if ( !$recoverable ) {
932 # Callers may catch the exception and continue to use the DB
933 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
935 # Should be safe to silently retry the query
936 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
939 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
940 $this->connLogger
->error( $msg );
944 if ( false === $ret ) {
945 # Deadlocks cause the entire transaction to abort, not just the statement.
946 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
947 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
948 if ( $this->wasDeadlock() ) {
949 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
950 $tempIgnore = false; // not recoverable
952 # Update state tracking to reflect transaction loss
953 $this->handleTransactionLoss();
956 $this->reportQueryError(
957 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
960 $res = $this->resultObject( $ret );
965 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
966 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
967 # generalizeSQL() will probably cut down the query to reasonable
968 # logging size most of the time. The substr is really just a sanity check.
970 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
972 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
975 # Include query transaction state
976 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
978 $startTime = microtime( true );
979 $this->profiler
->profileIn( $queryProf );
980 $ret = $this->doQuery( $commentedSql );
981 $this->profiler
->profileOut( $queryProf );
982 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
984 unset( $queryProfSection ); // profile out (if set)
986 if ( $ret !== false ) {
987 $this->lastPing
= $startTime;
988 if ( $isWrite && $this->mTrxLevel
) {
989 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
990 $this->mTrxWriteCallers
[] = $fname;
994 if ( $sql === self
::PING_QUERY
) {
995 $this->mRTTEstimate
= $queryRuntime;
998 $this->trxProfiler
->recordQueryCompletion(
999 $queryProf, $startTime, $isWrite, $this->affectedRows()
1001 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
1007 * Update the estimated run-time of a query, not counting large row lock times
1009 * LoadBalancer can be set to rollback transactions that will create huge replication
1010 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1011 * queries, like inserting a row can take a long time due to row locking. This method
1012 * uses some simple heuristics to discount those cases.
1014 * @param string $sql A SQL write query
1015 * @param float $runtime Total runtime, including RTT
1017 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1018 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1019 $indicativeOfReplicaRuntime = true;
1020 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1021 $verb = $this->getQueryVerb( $sql );
1022 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1023 if ( $verb === 'INSERT' ) {
1024 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1025 } elseif ( $verb === 'REPLACE' ) {
1026 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1030 $this->mTrxWriteDuration +
= $runtime;
1031 $this->mTrxWriteQueryCount +
= 1;
1032 if ( $indicativeOfReplicaRuntime ) {
1033 $this->mTrxWriteAdjDuration +
= $runtime;
1034 $this->mTrxWriteAdjQueryCount +
= 1;
1038 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1039 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1040 # Dropped connections also mean that named locks are automatically released.
1041 # Only allow error suppression in autocommit mode or when the lost transaction
1042 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1043 if ( $this->mNamedLocksHeld
) {
1044 return false; // possible critical section violation
1045 } elseif ( $sql === 'COMMIT' ) {
1046 return !$priorWritesPending; // nothing written anyway? (T127428)
1047 } elseif ( $sql === 'ROLLBACK' ) {
1048 return true; // transaction lost...which is also what was requested :)
1049 } elseif ( $this->explicitTrxActive() ) {
1050 return false; // don't drop atomocity
1051 } elseif ( $priorWritesPending ) {
1052 return false; // prior writes lost from implicit transaction
1058 private function handleTransactionLoss() {
1059 $this->mTrxLevel
= 0;
1060 $this->mTrxIdleCallbacks
= []; // bug 65263
1061 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1063 // Handle callbacks in mTrxEndCallbacks
1064 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1065 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1067 } catch ( Exception
$e ) {
1068 // Already logged; move on...
1073 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1074 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1075 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1077 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1078 $this->queryLogger
->error(
1079 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1080 $this->getLogContext( [
1081 'method' => __METHOD__
,
1084 'sql1line' => $sql1line,
1088 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1089 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1094 * Intended to be compatible with the PEAR::DB wrapper functions.
1095 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1097 * ? = scalar value, quoted as necessary
1098 * ! = raw SQL bit (a function for instance)
1099 * & = filename; reads the file and inserts as a blob
1100 * (we don't use this though...)
1102 * @param string $sql
1103 * @param string $func
1107 protected function prepare( $sql, $func = __METHOD__
) {
1108 /* MySQL doesn't support prepared statements (yet), so just
1109 * pack up the query for reference. We'll manually replace
1112 return [ 'query' => $sql, 'func' => $func ];
1116 * Free a prepared query, generated by prepare().
1117 * @param string $prepared
1119 protected function freePrepared( $prepared ) {
1120 /* No-op by default */
1124 * Execute a prepared query with the various arguments
1125 * @param string $prepared The prepared sql
1126 * @param mixed $args Either an array here, or put scalars as varargs
1128 * @return ResultWrapper
1130 public function execute( $prepared, $args = null ) {
1131 if ( !is_array( $args ) ) {
1133 $args = func_get_args();
1134 array_shift( $args );
1137 $sql = $this->fillPrepared( $prepared['query'], $args );
1139 return $this->query( $sql, $prepared['func'] );
1143 * For faking prepared SQL statements on DBs that don't support it directly.
1145 * @param string $preparedQuery A 'preparable' SQL statement
1146 * @param array $args Array of Arguments to fill it with
1147 * @return string Executable SQL
1149 public function fillPrepared( $preparedQuery, $args ) {
1151 $this->preparedArgs
=& $args;
1153 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1154 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1158 * preg_callback func for fillPrepared()
1159 * The arguments should be in $this->preparedArgs and must not be touched
1160 * while we're doing this.
1162 * @param array $matches
1163 * @throws DBUnexpectedError
1166 protected function fillPreparedArg( $matches ) {
1167 switch ( $matches[1] ) {
1176 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1178 switch ( $matches[1] ) {
1180 return $this->addQuotes( $arg );
1184 # return $this->addQuotes( file_get_contents( $arg ) );
1185 throw new DBUnexpectedError(
1187 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1190 throw new DBUnexpectedError(
1192 'Received invalid match. This should never happen!'
1197 public function freeResult( $res ) {
1200 public function selectField(
1201 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1203 if ( $var === '*' ) { // sanity
1204 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1207 if ( !is_array( $options ) ) {
1208 $options = [ $options ];
1211 $options['LIMIT'] = 1;
1213 $res = $this->select( $table, $var, $cond, $fname, $options );
1214 if ( $res === false ||
!$this->numRows( $res ) ) {
1218 $row = $this->fetchRow( $res );
1220 if ( $row !== false ) {
1221 return reset( $row );
1227 public function selectFieldValues(
1228 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1230 if ( $var === '*' ) { // sanity
1231 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1232 } elseif ( !is_string( $var ) ) { // sanity
1233 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1236 if ( !is_array( $options ) ) {
1237 $options = [ $options ];
1240 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1241 if ( $res === false ) {
1246 foreach ( $res as $row ) {
1247 $values[] = $row->$var;
1254 * Returns an optional USE INDEX clause to go after the table, and a
1255 * string to go at the end of the query.
1257 * @param array $options Associative array of options to be turned into
1258 * an SQL query, valid keys are listed in the function.
1260 * @see DatabaseBase::select()
1262 public function makeSelectOptions( $options ) {
1263 $preLimitTail = $postLimitTail = '';
1268 foreach ( $options as $key => $option ) {
1269 if ( is_numeric( $key ) ) {
1270 $noKeyOptions[$option] = true;
1274 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1276 $preLimitTail .= $this->makeOrderBy( $options );
1278 // if (isset($options['LIMIT'])) {
1279 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1280 // isset($options['OFFSET']) ? $options['OFFSET']
1284 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1285 $postLimitTail .= ' FOR UPDATE';
1288 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1289 $postLimitTail .= ' LOCK IN SHARE MODE';
1292 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1293 $startOpts .= 'DISTINCT';
1296 # Various MySQL extensions
1297 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1298 $startOpts .= ' /*! STRAIGHT_JOIN */';
1301 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1302 $startOpts .= ' HIGH_PRIORITY';
1305 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1306 $startOpts .= ' SQL_BIG_RESULT';
1309 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1310 $startOpts .= ' SQL_BUFFER_RESULT';
1313 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1314 $startOpts .= ' SQL_SMALL_RESULT';
1317 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1318 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1321 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1322 $startOpts .= ' SQL_CACHE';
1325 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1326 $startOpts .= ' SQL_NO_CACHE';
1329 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1330 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1334 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1335 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1340 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1344 * Returns an optional GROUP BY with an optional HAVING
1346 * @param array $options Associative array of options
1348 * @see DatabaseBase::select()
1351 public function makeGroupByWithHaving( $options ) {
1353 if ( isset( $options['GROUP BY'] ) ) {
1354 $gb = is_array( $options['GROUP BY'] )
1355 ?
implode( ',', $options['GROUP BY'] )
1356 : $options['GROUP BY'];
1357 $sql .= ' GROUP BY ' . $gb;
1359 if ( isset( $options['HAVING'] ) ) {
1360 $having = is_array( $options['HAVING'] )
1361 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1362 : $options['HAVING'];
1363 $sql .= ' HAVING ' . $having;
1370 * Returns an optional ORDER BY
1372 * @param array $options Associative array of options
1374 * @see DatabaseBase::select()
1377 public function makeOrderBy( $options ) {
1378 if ( isset( $options['ORDER BY'] ) ) {
1379 $ob = is_array( $options['ORDER BY'] )
1380 ?
implode( ',', $options['ORDER BY'] )
1381 : $options['ORDER BY'];
1383 return ' ORDER BY ' . $ob;
1389 // See IDatabase::select for the docs for this function
1390 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1391 $options = [], $join_conds = [] ) {
1392 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1394 return $this->query( $sql, $fname );
1397 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1398 $options = [], $join_conds = []
1400 if ( is_array( $vars ) ) {
1401 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1404 $options = (array)$options;
1405 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1406 ?
$options['USE INDEX']
1408 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1409 ?
$options['IGNORE INDEX']
1412 if ( is_array( $table ) ) {
1414 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1415 } elseif ( $table != '' ) {
1416 if ( $table[0] == ' ' ) {
1417 $from = ' FROM ' . $table;
1420 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1426 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1427 $this->makeSelectOptions( $options );
1429 if ( !empty( $conds ) ) {
1430 if ( is_array( $conds ) ) {
1431 $conds = $this->makeList( $conds, LIST_AND
);
1433 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1435 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1438 if ( isset( $options['LIMIT'] ) ) {
1439 $sql = $this->limitResult( $sql, $options['LIMIT'],
1440 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1442 $sql = "$sql $postLimitTail";
1444 if ( isset( $options['EXPLAIN'] ) ) {
1445 $sql = 'EXPLAIN ' . $sql;
1451 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1452 $options = [], $join_conds = []
1454 $options = (array)$options;
1455 $options['LIMIT'] = 1;
1456 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1458 if ( $res === false ) {
1462 if ( !$this->numRows( $res ) ) {
1466 $obj = $this->fetchObject( $res );
1471 public function estimateRowCount(
1472 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1475 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1478 $row = $this->fetchRow( $res );
1479 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1485 public function selectRowCount(
1486 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1489 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1490 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1493 $row = $this->fetchRow( $res );
1494 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1501 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1502 * It's only slightly flawed. Don't use for anything important.
1504 * @param string $sql A SQL Query
1508 protected static function generalizeSQL( $sql ) {
1509 # This does the same as the regexp below would do, but in such a way
1510 # as to avoid crashing php on some large strings.
1511 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1513 $sql = str_replace( "\\\\", '', $sql );
1514 $sql = str_replace( "\\'", '', $sql );
1515 $sql = str_replace( "\\\"", '', $sql );
1516 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1517 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1519 # All newlines, tabs, etc replaced by single space
1520 $sql = preg_replace( '/\s+/', ' ', $sql );
1523 # except the ones surrounded by characters, e.g. l10n
1524 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1525 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1530 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1531 $info = $this->fieldInfo( $table, $field );
1536 public function indexExists( $table, $index, $fname = __METHOD__
) {
1537 if ( !$this->tableExists( $table ) ) {
1541 $info = $this->indexInfo( $table, $index, $fname );
1542 if ( is_null( $info ) ) {
1545 return $info !== false;
1549 public function tableExists( $table, $fname = __METHOD__
) {
1550 $table = $this->tableName( $table );
1551 $old = $this->ignoreErrors( true );
1552 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1553 $this->ignoreErrors( $old );
1558 public function indexUnique( $table, $index ) {
1559 $indexInfo = $this->indexInfo( $table, $index );
1561 if ( !$indexInfo ) {
1565 return !$indexInfo[0]->Non_unique
;
1569 * Helper for DatabaseBase::insert().
1571 * @param array $options
1574 protected function makeInsertOptions( $options ) {
1575 return implode( ' ', $options );
1578 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1579 # No rows to insert, easy just return now
1580 if ( !count( $a ) ) {
1584 $table = $this->tableName( $table );
1586 if ( !is_array( $options ) ) {
1587 $options = [ $options ];
1591 if ( isset( $options['fileHandle'] ) ) {
1592 $fh = $options['fileHandle'];
1594 $options = $this->makeInsertOptions( $options );
1596 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1598 $keys = array_keys( $a[0] );
1601 $keys = array_keys( $a );
1604 $sql = 'INSERT ' . $options .
1605 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1609 foreach ( $a as $row ) {
1615 $sql .= '(' . $this->makeList( $row ) . ')';
1618 $sql .= '(' . $this->makeList( $a ) . ')';
1621 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1623 } elseif ( $fh !== null ) {
1627 return (bool)$this->query( $sql, $fname );
1631 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1633 * @param array $options
1636 protected function makeUpdateOptionsArray( $options ) {
1637 if ( !is_array( $options ) ) {
1638 $options = [ $options ];
1643 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1644 $opts[] = $this->lowPriorityOption();
1647 if ( in_array( 'IGNORE', $options ) ) {
1655 * Make UPDATE options for the DatabaseBase::update function
1657 * @param array $options The options passed to DatabaseBase::update
1660 protected function makeUpdateOptions( $options ) {
1661 $opts = $this->makeUpdateOptionsArray( $options );
1663 return implode( ' ', $opts );
1666 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1667 $table = $this->tableName( $table );
1668 $opts = $this->makeUpdateOptions( $options );
1669 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1671 if ( $conds !== [] && $conds !== '*' ) {
1672 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1675 return $this->query( $sql, $fname );
1678 public function makeList( $a, $mode = LIST_COMMA
) {
1679 if ( !is_array( $a ) ) {
1680 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1686 foreach ( $a as $field => $value ) {
1688 if ( $mode == LIST_AND
) {
1690 } elseif ( $mode == LIST_OR
) {
1699 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1700 $list .= "($value)";
1701 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1703 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1704 // Remove null from array to be handled separately if found
1705 $includeNull = false;
1706 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1707 $includeNull = true;
1708 unset( $value[$nullKey] );
1710 if ( count( $value ) == 0 && !$includeNull ) {
1711 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1712 } elseif ( count( $value ) == 0 ) {
1713 // only check if $field is null
1714 $list .= "$field IS NULL";
1716 // IN clause contains at least one valid element
1717 if ( $includeNull ) {
1718 // Group subconditions to ensure correct precedence
1721 if ( count( $value ) == 1 ) {
1722 // Special-case single values, as IN isn't terribly efficient
1723 // Don't necessarily assume the single key is 0; we don't
1724 // enforce linear numeric ordering on other arrays here.
1725 $value = array_values( $value )[0];
1726 $list .= $field . " = " . $this->addQuotes( $value );
1728 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1730 // if null present in array, append IS NULL
1731 if ( $includeNull ) {
1732 $list .= " OR $field IS NULL)";
1735 } elseif ( $value === null ) {
1736 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1737 $list .= "$field IS ";
1738 } elseif ( $mode == LIST_SET
) {
1739 $list .= "$field = ";
1743 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1744 $list .= "$field = ";
1746 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1753 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1756 foreach ( $data as $base => $sub ) {
1757 if ( count( $sub ) ) {
1758 $conds[] = $this->makeList(
1759 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1765 return $this->makeList( $conds, LIST_OR
);
1767 // Nothing to search for...
1773 * Return aggregated value alias
1775 * @param array $valuedata
1776 * @param string $valuename
1780 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1784 public function bitNot( $field ) {
1788 public function bitAnd( $fieldLeft, $fieldRight ) {
1789 return "($fieldLeft & $fieldRight)";
1792 public function bitOr( $fieldLeft, $fieldRight ) {
1793 return "($fieldLeft | $fieldRight)";
1796 public function buildConcat( $stringList ) {
1797 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1800 public function buildGroupConcatField(
1801 $delim, $table, $field, $conds = '', $join_conds = []
1803 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1805 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1809 * @param string $field Field or column to cast
1813 public function buildStringCast( $field ) {
1817 public function selectDB( $db ) {
1818 # Stub. Shouldn't cause serious problems if it's not overridden, but
1819 # if your database engine supports a concept similar to MySQL's
1820 # databases you may as well.
1821 $this->mDBname
= $db;
1826 public function getDBname() {
1827 return $this->mDBname
;
1830 public function getServer() {
1831 return $this->mServer
;
1835 * Format a table name ready for use in constructing an SQL query
1837 * This does two important things: it quotes the table names to clean them up,
1838 * and it adds a table prefix if only given a table name with no quotes.
1840 * All functions of this object which require a table name call this function
1841 * themselves. Pass the canonical name to such functions. This is only needed
1842 * when calling query() directly.
1844 * @note This function does not sanitize user input. It is not safe to use
1845 * this function to escape user input.
1846 * @param string $name Database table name
1847 * @param string $format One of:
1848 * quoted - Automatically pass the table name through addIdentifierQuotes()
1849 * so that it can be used in a query.
1850 * raw - Do not add identifier quotes to the table name
1851 * @return string Full database name
1853 public function tableName( $name, $format = 'quoted' ) {
1854 # Skip the entire process when we have a string quoted on both ends.
1855 # Note that we check the end so that we will still quote any use of
1856 # use of `database`.table. But won't break things if someone wants
1857 # to query a database table with a dot in the name.
1858 if ( $this->isQuotedIdentifier( $name ) ) {
1862 # Lets test for any bits of text that should never show up in a table
1863 # name. Basically anything like JOIN or ON which are actually part of
1864 # SQL queries, but may end up inside of the table value to combine
1865 # sql. Such as how the API is doing.
1866 # Note that we use a whitespace test rather than a \b test to avoid
1867 # any remote case where a word like on may be inside of a table name
1868 # surrounded by symbols which may be considered word breaks.
1869 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1873 # Split database and table into proper variables.
1874 # We reverse the explode so that database.table and table both output
1875 # the correct table.
1876 $dbDetails = explode( '.', $name, 3 );
1877 if ( count( $dbDetails ) == 3 ) {
1878 list( $database, $schema, $table ) = $dbDetails;
1879 # We don't want any prefix added in this case
1881 } elseif ( count( $dbDetails ) == 2 ) {
1882 list( $database, $table ) = $dbDetails;
1883 # We don't want any prefix added in this case
1884 # In dbs that support it, $database may actually be the schema
1885 # but that doesn't affect any of the functionality here
1889 list( $table ) = $dbDetails;
1890 if ( isset( $this->tableAliases
[$table] ) ) {
1891 $database = $this->tableAliases
[$table]['dbname'];
1892 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1893 ?
$this->tableAliases
[$table]['schema']
1895 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1896 ?
$this->tableAliases
[$table]['prefix']
1897 : $this->mTablePrefix
;
1900 $schema = $this->mSchema
; # Default schema
1901 $prefix = $this->mTablePrefix
; # Default prefix
1905 # Quote $table and apply the prefix if not quoted.
1906 # $tableName might be empty if this is called from Database::replaceVars()
1907 $tableName = "{$prefix}{$table}";
1908 if ( $format == 'quoted'
1909 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1911 $tableName = $this->addIdentifierQuotes( $tableName );
1914 # Quote $schema and merge it with the table name if needed
1915 if ( strlen( $schema ) ) {
1916 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1917 $schema = $this->addIdentifierQuotes( $schema );
1919 $tableName = $schema . '.' . $tableName;
1922 # Quote $database and merge it with the table name if needed
1923 if ( $database !== null ) {
1924 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1925 $database = $this->addIdentifierQuotes( $database );
1927 $tableName = $database . '.' . $tableName;
1934 * Fetch a number of table names into an array
1935 * This is handy when you need to construct SQL for joins
1938 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1939 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1940 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1944 public function tableNames() {
1945 $inArray = func_get_args();
1948 foreach ( $inArray as $name ) {
1949 $retVal[$name] = $this->tableName( $name );
1956 * Fetch a number of table names into an zero-indexed numerical array
1957 * This is handy when you need to construct SQL for joins
1960 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1961 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1962 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1966 public function tableNamesN() {
1967 $inArray = func_get_args();
1970 foreach ( $inArray as $name ) {
1971 $retVal[] = $this->tableName( $name );
1978 * Get an aliased table name
1979 * e.g. tableName AS newTableName
1981 * @param string $name Table name, see tableName()
1982 * @param string|bool $alias Alias (optional)
1983 * @return string SQL name for aliased table. Will not alias a table to its own name
1985 public function tableNameWithAlias( $name, $alias = false ) {
1986 if ( !$alias ||
$alias == $name ) {
1987 return $this->tableName( $name );
1989 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1994 * Gets an array of aliased table names
1996 * @param array $tables [ [alias] => table ]
1997 * @return string[] See tableNameWithAlias()
1999 public function tableNamesWithAlias( $tables ) {
2001 foreach ( $tables as $alias => $table ) {
2002 if ( is_numeric( $alias ) ) {
2005 $retval[] = $this->tableNameWithAlias( $table, $alias );
2012 * Get an aliased field name
2013 * e.g. fieldName AS newFieldName
2015 * @param string $name Field name
2016 * @param string|bool $alias Alias (optional)
2017 * @return string SQL name for aliased field. Will not alias a field to its own name
2019 public function fieldNameWithAlias( $name, $alias = false ) {
2020 if ( !$alias ||
(string)$alias === (string)$name ) {
2023 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2028 * Gets an array of aliased field names
2030 * @param array $fields [ [alias] => field ]
2031 * @return string[] See fieldNameWithAlias()
2033 public function fieldNamesWithAlias( $fields ) {
2035 foreach ( $fields as $alias => $field ) {
2036 if ( is_numeric( $alias ) ) {
2039 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2046 * Get the aliased table name clause for a FROM clause
2047 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2049 * @param array $tables ( [alias] => table )
2050 * @param array $use_index Same as for select()
2051 * @param array $ignore_index Same as for select()
2052 * @param array $join_conds Same as for select()
2055 protected function tableNamesWithIndexClauseOrJOIN(
2056 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2060 $use_index = (array)$use_index;
2061 $ignore_index = (array)$ignore_index;
2062 $join_conds = (array)$join_conds;
2064 foreach ( $tables as $alias => $table ) {
2065 if ( !is_string( $alias ) ) {
2066 // No alias? Set it equal to the table name
2069 // Is there a JOIN clause for this table?
2070 if ( isset( $join_conds[$alias] ) ) {
2071 list( $joinType, $conds ) = $join_conds[$alias];
2072 $tableClause = $joinType;
2073 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2074 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2075 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2077 $tableClause .= ' ' . $use;
2080 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2081 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2082 if ( $ignore != '' ) {
2083 $tableClause .= ' ' . $ignore;
2086 $on = $this->makeList( (array)$conds, LIST_AND
);
2088 $tableClause .= ' ON (' . $on . ')';
2091 $retJOIN[] = $tableClause;
2092 } elseif ( isset( $use_index[$alias] ) ) {
2093 // Is there an INDEX clause for this table?
2094 $tableClause = $this->tableNameWithAlias( $table, $alias );
2095 $tableClause .= ' ' . $this->useIndexClause(
2096 implode( ',', (array)$use_index[$alias] )
2099 $ret[] = $tableClause;
2100 } elseif ( isset( $ignore_index[$alias] ) ) {
2101 // Is there an INDEX clause for this table?
2102 $tableClause = $this->tableNameWithAlias( $table, $alias );
2103 $tableClause .= ' ' . $this->ignoreIndexClause(
2104 implode( ',', (array)$ignore_index[$alias] )
2107 $ret[] = $tableClause;
2109 $tableClause = $this->tableNameWithAlias( $table, $alias );
2111 $ret[] = $tableClause;
2115 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2116 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2117 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2119 // Compile our final table clause
2120 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2124 * Get the name of an index in a given table.
2126 * @param string $index
2129 protected function indexName( $index ) {
2130 // Backwards-compatibility hack
2132 'ar_usertext_timestamp' => 'usertext_timestamp',
2133 'un_user_id' => 'user_id',
2134 'un_user_ip' => 'user_ip',
2137 if ( isset( $renamed[$index] ) ) {
2138 return $renamed[$index];
2144 public function addQuotes( $s ) {
2145 if ( $s instanceof Blob
) {
2148 if ( $s === null ) {
2151 # This will also quote numeric values. This should be harmless,
2152 # and protects against weird problems that occur when they really
2153 # _are_ strings such as article titles and string->number->string
2154 # conversion is not 1:1.
2155 return "'" . $this->strencode( $s ) . "'";
2160 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2161 * MySQL uses `backticks` while basically everything else uses double quotes.
2162 * Since MySQL is the odd one out here the double quotes are our generic
2163 * and we implement backticks in DatabaseMysql.
2168 public function addIdentifierQuotes( $s ) {
2169 return '"' . str_replace( '"', '""', $s ) . '"';
2173 * Returns if the given identifier looks quoted or not according to
2174 * the database convention for quoting identifiers .
2176 * @note Do not use this to determine if untrusted input is safe.
2177 * A malicious user can trick this function.
2178 * @param string $name
2181 public function isQuotedIdentifier( $name ) {
2182 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2189 protected function escapeLikeInternal( $s ) {
2190 return addcslashes( $s, '\%_' );
2193 public function buildLike() {
2194 $params = func_get_args();
2196 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2197 $params = $params[0];
2202 foreach ( $params as $value ) {
2203 if ( $value instanceof LikeMatch
) {
2204 $s .= $value->toString();
2206 $s .= $this->escapeLikeInternal( $value );
2210 return " LIKE {$this->addQuotes( $s )} ";
2213 public function anyChar() {
2214 return new LikeMatch( '_' );
2217 public function anyString() {
2218 return new LikeMatch( '%' );
2221 public function nextSequenceValue( $seqName ) {
2226 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2227 * is only needed because a) MySQL must be as efficient as possible due to
2228 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2229 * which index to pick. Anyway, other databases might have different
2230 * indexes on a given table. So don't bother overriding this unless you're
2232 * @param string $index
2235 public function useIndexClause( $index ) {
2240 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2241 * is only needed because a) MySQL must be as efficient as possible due to
2242 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2243 * which index to pick. Anyway, other databases might have different
2244 * indexes on a given table. So don't bother overriding this unless you're
2246 * @param string $index
2249 public function ignoreIndexClause( $index ) {
2253 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2254 $quotedTable = $this->tableName( $table );
2256 if ( count( $rows ) == 0 ) {
2261 if ( !is_array( reset( $rows ) ) ) {
2265 // @FXIME: this is not atomic, but a trx would break affectedRows()
2266 foreach ( $rows as $row ) {
2267 # Delete rows which collide
2268 if ( $uniqueIndexes ) {
2269 $sql = "DELETE FROM $quotedTable WHERE ";
2271 foreach ( $uniqueIndexes as $index ) {
2278 if ( is_array( $index ) ) {
2280 foreach ( $index as $col ) {
2286 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2289 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2293 $this->query( $sql, $fname );
2296 # Now insert the row
2297 $this->insert( $table, $row, $fname );
2302 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2305 * @param string $table Table name
2306 * @param array|string $rows Row(s) to insert
2307 * @param string $fname Caller function name
2309 * @return ResultWrapper
2311 protected function nativeReplace( $table, $rows, $fname ) {
2312 $table = $this->tableName( $table );
2315 if ( !is_array( reset( $rows ) ) ) {
2319 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2322 foreach ( $rows as $row ) {
2329 $sql .= '(' . $this->makeList( $row ) . ')';
2332 return $this->query( $sql, $fname );
2335 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2338 if ( !count( $rows ) ) {
2339 return true; // nothing to do
2342 if ( !is_array( reset( $rows ) ) ) {
2346 if ( count( $uniqueIndexes ) ) {
2347 $clauses = []; // list WHERE clauses that each identify a single row
2348 foreach ( $rows as $row ) {
2349 foreach ( $uniqueIndexes as $index ) {
2350 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2351 $rowKey = []; // unique key to this row
2352 foreach ( $index as $column ) {
2353 $rowKey[$column] = $row[$column];
2355 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2358 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2363 $useTrx = !$this->mTrxLevel
;
2365 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2368 # Update any existing conflicting row(s)
2369 if ( $where !== false ) {
2370 $ok = $this->update( $table, $set, $where, $fname );
2374 # Now insert any non-conflicting row(s)
2375 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2376 } catch ( Exception
$e ) {
2378 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2383 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2389 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2393 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2396 $delTable = $this->tableName( $delTable );
2397 $joinTable = $this->tableName( $joinTable );
2398 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2399 if ( $conds != '*' ) {
2400 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2404 $this->query( $sql, $fname );
2408 * Returns the size of a text field, or -1 for "unlimited"
2410 * @param string $table
2411 * @param string $field
2414 public function textFieldSize( $table, $field ) {
2415 $table = $this->tableName( $table );
2416 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2417 $res = $this->query( $sql, __METHOD__
);
2418 $row = $this->fetchObject( $res );
2422 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2432 * A string to insert into queries to show that they're low-priority, like
2433 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2434 * string and nothing bad should happen.
2436 * @return string Returns the text of the low priority option if it is
2437 * supported, or a blank string otherwise
2439 public function lowPriorityOption() {
2443 public function delete( $table, $conds, $fname = __METHOD__
) {
2445 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2448 $table = $this->tableName( $table );
2449 $sql = "DELETE FROM $table";
2451 if ( $conds != '*' ) {
2452 if ( is_array( $conds ) ) {
2453 $conds = $this->makeList( $conds, LIST_AND
);
2455 $sql .= ' WHERE ' . $conds;
2458 return $this->query( $sql, $fname );
2461 public function insertSelect(
2462 $destTable, $srcTable, $varMap, $conds,
2463 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2465 if ( $this->cliMode
) {
2466 // For massive migrations with downtime, we don't want to select everything
2467 // into memory and OOM, so do all this native on the server side if possible.
2468 return $this->nativeInsertSelect(
2479 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2480 // on only the master (without needing row-based-replication). It also makes it easy to
2481 // know how big the INSERT is going to be.
2483 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2484 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2486 $selectOptions[] = 'FOR UPDATE';
2487 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2493 foreach ( $res as $row ) {
2494 $rows[] = (array)$row;
2497 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2500 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2501 $fname = __METHOD__
,
2502 $insertOptions = [], $selectOptions = []
2504 $destTable = $this->tableName( $destTable );
2506 if ( !is_array( $insertOptions ) ) {
2507 $insertOptions = [ $insertOptions ];
2510 $insertOptions = $this->makeInsertOptions( $insertOptions );
2512 if ( !is_array( $selectOptions ) ) {
2513 $selectOptions = [ $selectOptions ];
2516 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2519 if ( is_array( $srcTable ) ) {
2520 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2522 $srcTable = $this->tableName( $srcTable );
2525 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2526 " SELECT $startOpts " . implode( ',', $varMap ) .
2527 " FROM $srcTable $useIndex $ignoreIndex ";
2529 if ( $conds != '*' ) {
2530 if ( is_array( $conds ) ) {
2531 $conds = $this->makeList( $conds, LIST_AND
);
2533 $sql .= " WHERE $conds";
2536 $sql .= " $tailOpts";
2538 return $this->query( $sql, $fname );
2542 * Construct a LIMIT query with optional offset. This is used for query
2543 * pages. The SQL should be adjusted so that only the first $limit rows
2544 * are returned. If $offset is provided as well, then the first $offset
2545 * rows should be discarded, and the next $limit rows should be returned.
2546 * If the result of the query is not ordered, then the rows to be returned
2547 * are theoretically arbitrary.
2549 * $sql is expected to be a SELECT, if that makes a difference.
2551 * The version provided by default works in MySQL and SQLite. It will very
2552 * likely need to be overridden for most other DBMSes.
2554 * @param string $sql SQL query we will append the limit too
2555 * @param int $limit The SQL limit
2556 * @param int|bool $offset The SQL offset (default false)
2557 * @throws DBUnexpectedError
2560 public function limitResult( $sql, $limit, $offset = false ) {
2561 if ( !is_numeric( $limit ) ) {
2562 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2565 return "$sql LIMIT "
2566 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2570 public function unionSupportsOrderAndLimit() {
2571 return true; // True for almost every DB supported
2574 public function unionQueries( $sqls, $all ) {
2575 $glue = $all ?
') UNION ALL (' : ') UNION (';
2577 return '(' . implode( $glue, $sqls ) . ')';
2580 public function conditional( $cond, $trueVal, $falseVal ) {
2581 if ( is_array( $cond ) ) {
2582 $cond = $this->makeList( $cond, LIST_AND
);
2585 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2588 public function strreplace( $orig, $old, $new ) {
2589 return "REPLACE({$orig}, {$old}, {$new})";
2592 public function getServerUptime() {
2596 public function wasDeadlock() {
2600 public function wasLockTimeout() {
2604 public function wasErrorReissuable() {
2608 public function wasReadOnlyError() {
2613 * Determines if the given query error was a connection drop
2616 * @param integer|string $errno
2619 public function wasConnectionError( $errno ) {
2624 * Perform a deadlock-prone transaction.
2626 * This function invokes a callback function to perform a set of write
2627 * queries. If a deadlock occurs during the processing, the transaction
2628 * will be rolled back and the callback function will be called again.
2630 * Avoid using this method outside of Job or Maintenance classes.
2633 * $dbw->deadlockLoop( callback, ... );
2635 * Extra arguments are passed through to the specified callback function.
2636 * This method requires that no transactions are already active to avoid
2637 * causing premature commits or exceptions.
2639 * Returns whatever the callback function returned on its successful,
2640 * iteration, or false on error, for example if the retry limit was
2644 * @throws DBUnexpectedError
2647 public function deadlockLoop() {
2648 $args = func_get_args();
2649 $function = array_shift( $args );
2650 $tries = self
::DEADLOCK_TRIES
;
2652 $this->begin( __METHOD__
);
2655 /** @var Exception $e */
2659 $retVal = call_user_func_array( $function, $args );
2661 } catch ( DBQueryError
$e ) {
2662 if ( $this->wasDeadlock() ) {
2663 // Retry after a randomized delay
2664 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2666 // Throw the error back up
2670 } while ( --$tries > 0 );
2672 if ( $tries <= 0 ) {
2673 // Too many deadlocks; give up
2674 $this->rollback( __METHOD__
);
2677 $this->commit( __METHOD__
);
2683 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2684 # Real waits are implemented in the subclass.
2688 public function getSlavePos() {
2693 public function getMasterPos() {
2698 public function serverIsReadOnly() {
2702 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2703 if ( !$this->mTrxLevel
) {
2704 throw new DBUnexpectedError( $this, "No transaction is active." );
2706 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2709 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2710 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2711 if ( !$this->mTrxLevel
) {
2712 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2716 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2717 if ( $this->mTrxLevel
) {
2718 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2720 // If no transaction is active, then make one for this callback
2721 $this->startAtomic( __METHOD__
);
2723 call_user_func( $callback );
2724 $this->endAtomic( __METHOD__
);
2725 } catch ( Exception
$e ) {
2726 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2732 final public function setTransactionListener( $name, callable
$callback = null ) {
2734 $this->mTrxRecurringCallbacks
[$name] = $callback;
2736 unset( $this->mTrxRecurringCallbacks
[$name] );
2741 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2743 * This method should not be used outside of Database/LoadBalancer
2745 * @param bool $suppress
2748 final public function setTrxEndCallbackSuppression( $suppress ) {
2749 $this->mTrxEndCallbacksSuppressed
= $suppress;
2753 * Actually run and consume any "on transaction idle/resolution" callbacks.
2755 * This method should not be used outside of Database/LoadBalancer
2757 * @param integer $trigger IDatabase::TRIGGER_* constant
2761 public function runOnTransactionIdleCallbacks( $trigger ) {
2762 if ( $this->mTrxEndCallbacksSuppressed
) {
2766 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2767 /** @var Exception $e */
2768 $e = null; // first exception
2769 do { // callbacks may add callbacks :)
2770 $callbacks = array_merge(
2771 $this->mTrxIdleCallbacks
,
2772 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2774 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2775 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2776 foreach ( $callbacks as $callback ) {
2778 list( $phpCallback ) = $callback;
2779 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2780 call_user_func_array( $phpCallback, [ $trigger ] );
2782 $this->setFlag( DBO_TRX
); // restore automatic begin()
2784 $this->clearFlag( DBO_TRX
); // restore auto-commit
2786 } catch ( Exception
$ex ) {
2787 call_user_func( $this->errorLogger
, $ex );
2789 // Some callbacks may use startAtomic/endAtomic, so make sure
2790 // their transactions are ended so other callbacks don't fail
2791 if ( $this->trxLevel() ) {
2792 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2796 } while ( count( $this->mTrxIdleCallbacks
) );
2798 if ( $e instanceof Exception
) {
2799 throw $e; // re-throw any first exception
2804 * Actually run and consume any "on transaction pre-commit" callbacks.
2806 * This method should not be used outside of Database/LoadBalancer
2811 public function runOnTransactionPreCommitCallbacks() {
2812 $e = null; // first exception
2813 do { // callbacks may add callbacks :)
2814 $callbacks = $this->mTrxPreCommitCallbacks
;
2815 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2816 foreach ( $callbacks as $callback ) {
2818 list( $phpCallback ) = $callback;
2819 call_user_func( $phpCallback );
2820 } catch ( Exception
$ex ) {
2821 call_user_func( $this->errorLogger
, $ex );
2825 } while ( count( $this->mTrxPreCommitCallbacks
) );
2827 if ( $e instanceof Exception
) {
2828 throw $e; // re-throw any first exception
2833 * Actually run any "transaction listener" callbacks.
2835 * This method should not be used outside of Database/LoadBalancer
2837 * @param integer $trigger IDatabase::TRIGGER_* constant
2841 public function runTransactionListenerCallbacks( $trigger ) {
2842 if ( $this->mTrxEndCallbacksSuppressed
) {
2846 /** @var Exception $e */
2847 $e = null; // first exception
2849 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2851 $phpCallback( $trigger, $this );
2852 } catch ( Exception
$ex ) {
2853 call_user_func( $this->errorLogger
, $ex );
2858 if ( $e instanceof Exception
) {
2859 throw $e; // re-throw any first exception
2863 final public function startAtomic( $fname = __METHOD__
) {
2864 if ( !$this->mTrxLevel
) {
2865 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2866 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2867 // in all changes being in one transaction to keep requests transactional.
2868 if ( !$this->getFlag( DBO_TRX
) ) {
2869 $this->mTrxAutomaticAtomic
= true;
2873 $this->mTrxAtomicLevels
[] = $fname;
2876 final public function endAtomic( $fname = __METHOD__
) {
2877 if ( !$this->mTrxLevel
) {
2878 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2880 if ( !$this->mTrxAtomicLevels ||
2881 array_pop( $this->mTrxAtomicLevels
) !== $fname
2883 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2886 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2887 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2891 final public function doAtomicSection( $fname, callable
$callback ) {
2892 $this->startAtomic( $fname );
2894 $res = call_user_func_array( $callback, [ $this, $fname ] );
2895 } catch ( Exception
$e ) {
2896 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2899 $this->endAtomic( $fname );
2904 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2905 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2906 if ( $this->mTrxLevel
) {
2907 if ( $this->mTrxAtomicLevels
) {
2908 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2909 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2910 throw new DBUnexpectedError( $this, $msg );
2911 } elseif ( !$this->mTrxAutomatic
) {
2912 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2913 throw new DBUnexpectedError( $this, $msg );
2915 // @TODO: make this an exception at some point
2916 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2917 $this->queryLogger
->error( $msg );
2918 return; // join the main transaction set
2920 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2921 // @TODO: make this an exception at some point
2922 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2923 $this->queryLogger
->error( $msg );
2924 return; // let any writes be in the main transaction
2927 // Avoid fatals if close() was called
2928 $this->assertOpen();
2930 $this->doBegin( $fname );
2931 $this->mTrxTimestamp
= microtime( true );
2932 $this->mTrxFname
= $fname;
2933 $this->mTrxDoneWrites
= false;
2934 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2935 $this->mTrxAutomaticAtomic
= false;
2936 $this->mTrxAtomicLevels
= [];
2937 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2938 $this->mTrxWriteDuration
= 0.0;
2939 $this->mTrxWriteQueryCount
= 0;
2940 $this->mTrxWriteAdjDuration
= 0.0;
2941 $this->mTrxWriteAdjQueryCount
= 0;
2942 $this->mTrxWriteCallers
= [];
2943 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2944 // Get an estimate of the replica DB lag before then, treating estimate staleness
2945 // as lag itself just to be safe
2946 $status = $this->getApproximateLagStatus();
2947 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2951 * Issues the BEGIN command to the database server.
2953 * @see DatabaseBase::begin()
2954 * @param string $fname
2956 protected function doBegin( $fname ) {
2957 $this->query( 'BEGIN', $fname );
2958 $this->mTrxLevel
= 1;
2961 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2962 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2963 // There are still atomic sections open. This cannot be ignored
2964 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2965 throw new DBUnexpectedError(
2967 "$fname: Got COMMIT while atomic sections $levels are still open."
2971 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2972 if ( !$this->mTrxLevel
) {
2973 return; // nothing to do
2974 } elseif ( !$this->mTrxAutomatic
) {
2975 throw new DBUnexpectedError(
2977 "$fname: Flushing an explicit transaction, getting out of sync."
2981 if ( !$this->mTrxLevel
) {
2982 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2983 return; // nothing to do
2984 } elseif ( $this->mTrxAutomatic
) {
2985 // @TODO: make this an exception at some point
2986 $msg = "$fname: Explicit commit of implicit transaction.";
2987 $this->queryLogger
->error( $msg );
2988 return; // wait for the main transaction set commit round
2992 // Avoid fatals if close() was called
2993 $this->assertOpen();
2995 $this->runOnTransactionPreCommitCallbacks();
2996 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2997 $this->doCommit( $fname );
2998 if ( $this->mTrxDoneWrites
) {
2999 $this->mDoneWrites
= microtime( true );
3000 $this->trxProfiler
->transactionWritingOut(
3001 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3004 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3005 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3009 * Issues the COMMIT command to the database server.
3011 * @see DatabaseBase::commit()
3012 * @param string $fname
3014 protected function doCommit( $fname ) {
3015 if ( $this->mTrxLevel
) {
3016 $this->query( 'COMMIT', $fname );
3017 $this->mTrxLevel
= 0;
3021 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3022 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3023 if ( !$this->mTrxLevel
) {
3024 return; // nothing to do
3027 if ( !$this->mTrxLevel
) {
3028 $this->queryLogger
->error(
3029 "$fname: No transaction to rollback, something got out of sync." );
3030 return; // nothing to do
3031 } elseif ( $this->getFlag( DBO_TRX
) ) {
3032 throw new DBUnexpectedError(
3034 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3039 // Avoid fatals if close() was called
3040 $this->assertOpen();
3042 $this->doRollback( $fname );
3043 $this->mTrxAtomicLevels
= [];
3044 if ( $this->mTrxDoneWrites
) {
3045 $this->trxProfiler
->transactionWritingOut(
3046 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3049 $this->mTrxIdleCallbacks
= []; // clear
3050 $this->mTrxPreCommitCallbacks
= []; // clear
3051 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3052 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3056 * Issues the ROLLBACK command to the database server.
3058 * @see DatabaseBase::rollback()
3059 * @param string $fname
3061 protected function doRollback( $fname ) {
3062 if ( $this->mTrxLevel
) {
3063 # Disconnects cause rollback anyway, so ignore those errors
3064 $ignoreErrors = true;
3065 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3066 $this->mTrxLevel
= 0;
3070 public function flushSnapshot( $fname = __METHOD__
) {
3071 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3072 // This only flushes transactions to clear snapshots, not to write data
3073 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3074 throw new DBUnexpectedError(
3076 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3080 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3083 public function explicitTrxActive() {
3084 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3088 * Creates a new table with structure copied from existing table
3089 * Note that unlike most database abstraction functions, this function does not
3090 * automatically append database prefix, because it works at a lower
3091 * abstraction level.
3092 * The table names passed to this function shall not be quoted (this
3093 * function calls addIdentifierQuotes when needed).
3095 * @param string $oldName Name of table whose structure should be copied
3096 * @param string $newName Name of table to be created
3097 * @param bool $temporary Whether the new table should be temporary
3098 * @param string $fname Calling function name
3099 * @throws RuntimeException
3100 * @return bool True if operation was successful
3102 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3105 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3108 function listTables( $prefix = null, $fname = __METHOD__
) {
3109 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3113 * Reset the views process cache set by listViews()
3116 final public function clearViewsCache() {
3117 $this->allViews
= null;
3121 * Lists all the VIEWs in the database
3123 * For caching purposes the list of all views should be stored in
3124 * $this->allViews. The process cache can be cleared with clearViewsCache()
3126 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3127 * @param string $fname Name of calling function
3128 * @throws RuntimeException
3132 public function listViews( $prefix = null, $fname = __METHOD__
) {
3133 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3137 * Differentiates between a TABLE and a VIEW
3139 * @param string $name Name of the database-structure to test.
3140 * @throws RuntimeException
3144 public function isView( $name ) {
3145 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3148 public function timestamp( $ts = 0 ) {
3149 $t = new ConvertableTimestamp( $ts );
3150 // Let errors bubble up to avoid putting garbage in the DB
3151 return $t->getTimestamp( TS_MW
);
3154 public function timestampOrNull( $ts = null ) {
3155 if ( is_null( $ts ) ) {
3158 return $this->timestamp( $ts );
3163 * Take the result from a query, and wrap it in a ResultWrapper if
3164 * necessary. Boolean values are passed through as is, to indicate success
3165 * of write queries or failure.
3167 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3168 * resource, and it was necessary to call this function to convert it to
3169 * a wrapper. Nowadays, raw database objects are never exposed to external
3170 * callers, so this is unnecessary in external code.
3172 * @param bool|ResultWrapper|resource|object $result
3173 * @return bool|ResultWrapper
3175 protected function resultObject( $result ) {
3178 } elseif ( $result instanceof ResultWrapper
) {
3180 } elseif ( $result === true ) {
3181 // Successful write query
3184 return new ResultWrapper( $this, $result );
3188 public function ping( &$rtt = null ) {
3189 // Avoid hitting the server if it was hit recently
3190 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3191 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3192 $rtt = $this->mRTTEstimate
;
3193 return true; // don't care about $rtt
3197 // This will reconnect if possible or return false if not
3198 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3199 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3200 $this->restoreFlags( self
::RESTORE_PRIOR
);
3203 $rtt = $this->mRTTEstimate
;
3212 protected function reconnect() {
3213 $this->closeConnection();
3214 $this->mOpened
= false;
3215 $this->mConn
= false;
3217 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3218 $this->lastPing
= microtime( true );
3220 } catch ( DBConnectionError
$e ) {
3227 public function getSessionLagStatus() {
3228 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3232 * Get the replica DB lag when the current transaction started
3234 * This is useful when transactions might use snapshot isolation
3235 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3236 * is this lag plus transaction duration. If they don't, it is still
3237 * safe to be pessimistic. This returns null if there is no transaction.
3239 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3242 public function getTransactionLagStatus() {
3243 return $this->mTrxLevel
3244 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3249 * Get a replica DB lag estimate for this server
3251 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3254 public function getApproximateLagStatus() {
3256 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3257 'since' => microtime( true )
3262 * Merge the result of getSessionLagStatus() for several DBs
3263 * using the most pessimistic values to estimate the lag of
3264 * any data derived from them in combination
3266 * This is information is useful for caching modules
3268 * @see WANObjectCache::set()
3269 * @see WANObjectCache::getWithSetCallback()
3271 * @param IDatabase $db1
3272 * @param IDatabase ...
3273 * @return array Map of values:
3274 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3275 * - since: oldest UNIX timestamp of any of the DB lag estimates
3276 * - pending: whether any of the DBs have uncommitted changes
3279 public static function getCacheSetOptions( IDatabase
$db1 ) {
3280 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3281 foreach ( func_get_args() as $db ) {
3282 /** @var IDatabase $db */
3283 $status = $db->getSessionLagStatus();
3284 if ( $status['lag'] === false ) {
3285 $res['lag'] = false;
3286 } elseif ( $res['lag'] !== false ) {
3287 $res['lag'] = max( $res['lag'], $status['lag'] );
3289 $res['since'] = min( $res['since'], $status['since'] );
3290 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3296 public function getLag() {
3300 function maxListLen() {
3304 public function encodeBlob( $b ) {
3308 public function decodeBlob( $b ) {
3309 if ( $b instanceof Blob
) {
3315 public function setSessionOptions( array $options ) {
3319 * Read and execute SQL commands from a file.
3321 * Returns true on success, error string or exception on failure (depending
3322 * on object's error ignore settings).
3324 * @param string $filename File name to open
3325 * @param bool|callable $lineCallback Optional function called before reading each line
3326 * @param bool|callable $resultCallback Optional function called for each MySQL result
3327 * @param bool|string $fname Calling function name or false if name should be
3328 * generated dynamically using $filename
3329 * @param bool|callable $inputCallback Optional function called for each
3330 * complete line sent
3331 * @return bool|string
3334 public function sourceFile(
3335 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3337 MediaWiki\
suppressWarnings();
3338 $fp = fopen( $filename, 'r' );
3339 MediaWiki\restoreWarnings
();
3341 if ( false === $fp ) {
3342 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3346 $fname = __METHOD__
. "( $filename )";
3350 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3351 } catch ( Exception
$e ) {
3361 public function setSchemaVars( $vars ) {
3362 $this->mSchemaVars
= $vars;
3366 * Read and execute commands from an open file handle.
3368 * Returns true on success, error string or exception on failure (depending
3369 * on object's error ignore settings).
3371 * @param resource $fp File handle
3372 * @param bool|callable $lineCallback Optional function called before reading each query
3373 * @param bool|callable $resultCallback Optional function called for each MySQL result
3374 * @param string $fname Calling function name
3375 * @param bool|callable $inputCallback Optional function called for each complete query sent
3376 * @return bool|string
3378 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3379 $fname = __METHOD__
, $inputCallback = false
3383 while ( !feof( $fp ) ) {
3384 if ( $lineCallback ) {
3385 call_user_func( $lineCallback );
3388 $line = trim( fgets( $fp ) );
3390 if ( $line == '' ) {
3394 if ( '-' == $line[0] && '-' == $line[1] ) {
3402 $done = $this->streamStatementEnd( $cmd, $line );
3406 if ( $done ||
feof( $fp ) ) {
3407 $cmd = $this->replaceVars( $cmd );
3409 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3410 $res = $this->query( $cmd, $fname );
3412 if ( $resultCallback ) {
3413 call_user_func( $resultCallback, $res, $this );
3416 if ( false === $res ) {
3417 $err = $this->lastError();
3419 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3430 * Called by sourceStream() to check if we've reached a statement end
3432 * @param string $sql SQL assembled so far
3433 * @param string $newLine New line about to be added to $sql
3434 * @return bool Whether $newLine contains end of the statement
3436 public function streamStatementEnd( &$sql, &$newLine ) {
3437 if ( $this->delimiter
) {
3439 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3440 if ( $newLine != $prev ) {
3449 * Database independent variable replacement. Replaces a set of variables
3450 * in an SQL statement with their contents as given by $this->getSchemaVars().
3452 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3454 * - '{$var}' should be used for text and is passed through the database's
3456 * - `{$var}` should be used for identifiers (e.g. table and database names).
3457 * It is passed through the database's addIdentifierQuotes method which
3458 * can be overridden if the database uses something other than backticks.
3459 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3460 * database's tableName method.
3461 * - / *i* / passes the name that follows through the database's indexName method.
3462 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3463 * its use should be avoided. In 1.24 and older, string encoding was applied.
3465 * @param string $ins SQL statement to replace variables in
3466 * @return string The new SQL statement with variables replaced
3468 protected function replaceVars( $ins ) {
3469 $vars = $this->getSchemaVars();
3470 return preg_replace_callback(
3472 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3473 \'\{\$ (\w+) }\' | # 3. addQuotes
3474 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3475 /\*\$ (\w+) \*/ # 5. leave unencoded
3477 function ( $m ) use ( $vars ) {
3478 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3479 // check for both nonexistent keys *and* the empty string.
3480 if ( isset( $m[1] ) && $m[1] !== '' ) {
3481 if ( $m[1] === 'i' ) {
3482 return $this->indexName( $m[2] );
3484 return $this->tableName( $m[2] );
3486 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3487 return $this->addQuotes( $vars[$m[3]] );
3488 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3489 return $this->addIdentifierQuotes( $vars[$m[4]] );
3490 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3491 return $vars[$m[5]];
3501 * Get schema variables. If none have been set via setSchemaVars(), then
3502 * use some defaults from the current object.
3506 protected function getSchemaVars() {
3507 if ( $this->mSchemaVars
) {
3508 return $this->mSchemaVars
;
3510 return $this->getDefaultSchemaVars();
3515 * Get schema variables to use if none have been set via setSchemaVars().
3517 * Override this in derived classes to provide variables for tables.sql
3518 * and SQL patch files.
3522 protected function getDefaultSchemaVars() {
3526 public function lockIsFree( $lockName, $method ) {
3530 public function lock( $lockName, $method, $timeout = 5 ) {
3531 $this->mNamedLocksHeld
[$lockName] = 1;
3536 public function unlock( $lockName, $method ) {
3537 unset( $this->mNamedLocksHeld
[$lockName] );
3542 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3543 if ( $this->writesOrCallbacksPending() ) {
3544 // This only flushes transactions to clear snapshots, not to write data
3545 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3546 throw new DBUnexpectedError(
3548 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3552 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3556 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3557 if ( $this->trxLevel() ) {
3558 // There is a good chance an exception was thrown, causing any early return
3559 // from the caller. Let any error handler get a chance to issue rollback().
3560 // If there isn't one, let the error bubble up and trigger server-side rollback.
3561 $this->onTransactionResolution(
3562 function () use ( $lockKey, $fname ) {
3563 $this->unlock( $lockKey, $fname );
3568 $this->unlock( $lockKey, $fname );
3572 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3577 public function namedLocksEnqueue() {
3582 * Lock specific tables
3584 * @param array $read Array of tables to lock for read access
3585 * @param array $write Array of tables to lock for write access
3586 * @param string $method Name of caller
3587 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3590 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3595 * Unlock specific tables
3597 * @param string $method The caller
3600 public function unlockTables( $method ) {
3606 * @param string $tableName
3607 * @param string $fName
3608 * @return bool|ResultWrapper
3611 public function dropTable( $tableName, $fName = __METHOD__
) {
3612 if ( !$this->tableExists( $tableName, $fName ) ) {
3615 $sql = "DROP TABLE " . $this->tableName( $tableName );
3616 if ( $this->cascadingDeletes() ) {
3620 return $this->query( $sql, $fName );
3624 * Get search engine class. All subclasses of this need to implement this
3625 * if they wish to use searching.
3629 public function getSearchEngine() {
3630 return 'SearchEngineDummy';
3633 public function getInfinity() {
3637 public function encodeExpiry( $expiry ) {
3638 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3639 ?
$this->getInfinity()
3640 : $this->timestamp( $expiry );
3643 public function decodeExpiry( $expiry, $format = TS_MW
) {
3644 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3649 $t = new ConvertableTimestamp( $expiry );
3651 return $t->getTimestamp( $format );
3652 } catch ( TimestampException
$e ) {
3657 public function setBigSelects( $value = true ) {
3661 public function isReadOnly() {
3662 return ( $this->getReadOnlyReason() !== false );
3666 * @return string|bool Reason this DB is read-only or false if it is not
3668 protected function getReadOnlyReason() {
3669 $reason = $this->getLBInfo( 'readOnlyReason' );
3671 return is_string( $reason ) ?
$reason : false;
3674 public function setTableAliases( array $aliases ) {
3675 $this->tableAliases
= $aliases;
3682 public function __toString() {
3683 return (string)$this->mConn
;
3687 * Run a few simple sanity checks
3689 public function __destruct() {
3690 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3691 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3694 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3695 if ( $danglingWriters ) {
3696 $fnames = implode( ', ', $danglingWriters );
3697 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3705 abstract class Database
extends DatabaseBase
{
3706 // B/C until nothing type hints for DatabaseBase
3707 // @TODO: finish renaming DatabaseBase => Database