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;
66 /** @var BagOStuff APC cache */
68 /** @var LoggerInterface */
69 protected $connLogger;
70 /** @var LoggerInterface */
71 protected $queryLogger;
72 /** @var callback Error logging callback */
73 protected $errorLogger;
75 /** @var resource Database connection */
76 protected $mConn = null;
78 protected $mOpened = false;
80 /** @var array[] List of (callable, method name) */
81 protected $mTrxIdleCallbacks = [];
82 /** @var array[] List of (callable, method name) */
83 protected $mTrxPreCommitCallbacks = [];
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxEndCallbacks = [];
86 /** @var array[] Map of (name => (callable, method name)) */
87 protected $mTrxRecurringCallbacks = [];
88 /** @var bool Whether to suppress triggering of transaction end callbacks */
89 protected $mTrxEndCallbacksSuppressed = false;
92 protected $mTablePrefix;
100 protected $mLBInfo = [];
101 /** @var bool|null */
102 protected $mDefaultBigSelects = null;
103 /** @var array|bool */
104 protected $mSchemaVars = false;
106 protected $mSessionVars = [];
107 /** @var array|null */
108 protected $preparedArgs;
109 /** @var string|bool|null Stashed value of html_errors INI setting */
110 protected $htmlErrors;
112 protected $delimiter = ';';
115 * Either 1 if a transaction is active or 0 otherwise.
116 * The other Trx fields may not be meaningfull if this is 0.
120 protected $mTrxLevel = 0;
122 * Either a short hexidecimal string if a transaction is active or ""
125 * @see DatabaseBase::mTrxLevel
127 protected $mTrxShortId = '';
129 * The UNIX time that the transaction started. Callers can assume that if
130 * snapshot isolation is used, then the data is *at least* up to date to that
131 * point (possibly more up-to-date since the first SELECT defines the snapshot).
134 * @see DatabaseBase::mTrxLevel
136 private $mTrxTimestamp = null;
137 /** @var float Lag estimate at the time of BEGIN */
138 private $mTrxReplicaLag = null;
140 * Remembers the function name given for starting the most recent transaction via begin().
141 * Used to provide additional context for error reporting.
144 * @see DatabaseBase::mTrxLevel
146 private $mTrxFname = null;
148 * Record if possible write queries were done in the last transaction started
151 * @see DatabaseBase::mTrxLevel
153 private $mTrxDoneWrites = false;
155 * Record if the current transaction was started implicitly due to DBO_TRX being set.
158 * @see DatabaseBase::mTrxLevel
160 private $mTrxAutomatic = false;
162 * Array of levels of atomicity within transactions
166 private $mTrxAtomicLevels = [];
168 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
172 private $mTrxAutomaticAtomic = false;
174 * Track the write query callers of the current transaction
178 private $mTrxWriteCallers = [];
180 * @var float Seconds spent in write queries for the current transaction
182 private $mTrxWriteDuration = 0.0;
184 * @var integer Number of write queries for the current transaction
186 private $mTrxWriteQueryCount = 0;
188 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
190 private $mTrxWriteAdjDuration = 0.0;
192 * @var integer Number of write queries counted in mTrxWriteAdjDuration
194 private $mTrxWriteAdjQueryCount = 0;
196 * @var float RTT time estimate
198 private $mRTTEstimate = 0.0;
200 /** @var array Map of (name => 1) for locks obtained via lock() */
201 private $mNamedLocksHeld = [];
203 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
204 private $lazyMasterHandle;
208 * @var resource File handle for upgrade
210 protected $fileHandle = null;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
232 * FIXME: It is possible to construct a Database object with no associated
233 * connection object, by specifying no parameters to __construct(). This
234 * feature is deprecated and should be removed.
236 * IDatabase classes should not be constructed directly in external
237 * code. DatabaseBase::factory() should be used instead.
239 * @param array $params Parameters passed from DatabaseBase::factory()
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
246 $flags = $params['flags'];
248 $this->mSchema
= $params['schema'];
249 $this->mTablePrefix
= $params['tablePrefix'];
251 $this->cliMode
= isset( $params['cliMode'] )
253 : ( PHP_SAPI
=== 'cli' );
255 $this->mFlags
= $flags;
256 if ( $this->mFlags
& DBO_DEFAULT
) {
257 if ( $this->cliMode
) {
258 $this->mFlags
&= ~DBO_TRX
;
260 $this->mFlags |
= DBO_TRX
;
264 $this->mSessionVars
= $params['variables'];
266 $this->mForeign
= $params['foreign'];
268 $this->srvCache
= isset( $params['srvCache'] )
269 ?
$params['srvCache']
270 : new HashBagOStuff();
272 $this->profiler
= isset( $params['profiler'] )
273 ?
$params['profiler']
274 : Profiler
::instance(); // @TODO: remove global state
275 $this->trxProfiler
= isset( $params['trxProfiler'] )
276 ?
$params['trxProfiler']
277 : new TransactionProfiler();
278 $this->connLogger
= isset( $params['connLogger'] )
279 ?
$params['connLogger']
280 : new \Psr\Log\
NullLogger();
281 $this->queryLogger
= isset( $params['queryLogger'] )
282 ?
$params['queryLogger']
283 : new \Psr\Log\
NullLogger();
286 $this->open( $server, $user, $password, $dbName );
291 * Given a DB type, construct the name of the appropriate child class of
292 * IDatabase. This is designed to replace all of the manual stuff like:
293 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
294 * as well as validate against the canonical list of DB types we have
296 * This factory function is mostly useful for when you need to connect to a
297 * database other than the MediaWiki default (such as for external auth,
298 * an extension, et cetera). Do not use this to connect to the MediaWiki
299 * database. Example uses in core:
300 * @see LoadBalancer::reallyOpenConnection()
301 * @see ForeignDBRepo::getMasterDB()
302 * @see WebInstallerDBConnect::execute()
306 * @param string $dbType A possible DB type
307 * @param array $p An array of options to pass to the constructor.
308 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
309 * @return IDatabase|null If the database driver or extension cannot be found
310 * @throws InvalidArgumentException If the database driver or extension cannot be found
312 final public static function factory( $dbType, $p = [] ) {
313 global $wgCommandLineMode;
315 $canonicalDBTypes = [
316 'mysql' => [ 'mysqli', 'mysql' ],
324 $dbType = strtolower( $dbType );
325 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
326 $possibleDrivers = $canonicalDBTypes[$dbType];
327 if ( !empty( $p['driver'] ) ) {
328 if ( in_array( $p['driver'], $possibleDrivers ) ) {
329 $driver = $p['driver'];
331 throw new InvalidArgumentException( __METHOD__
.
332 " type '$dbType' does not support driver '{$p['driver']}'" );
335 foreach ( $possibleDrivers as $posDriver ) {
336 if ( extension_loaded( $posDriver ) ) {
337 $driver = $posDriver;
345 if ( $driver === false ) {
346 throw new InvalidArgumentException( __METHOD__
.
347 " no viable database extension found for type '$dbType'" );
350 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
351 // and everything else doesn't use a schema (e.g. null)
352 // Although postgres and oracle support schemas, we don't use them (yet)
353 // to maintain backwards compatibility
355 'mssql' => 'get from global',
358 $class = 'Database' . ucfirst( $driver );
359 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
360 // Resolve some defaults for b/c
361 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
362 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
363 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
364 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
365 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
366 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
367 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
368 if ( !isset( $p['schema'] ) ) {
369 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
371 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
372 $p['cliMode'] = $wgCommandLineMode;
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
= [ MWExceptionHandler
::class, 'logException' ];
393 public function setLogger( LoggerInterface
$logger ) {
394 $this->queryLogger
= $logger;
397 public function getServerInfo() {
398 return $this->getServerVersion();
402 * @return string Command delimiter used by this database engine
404 public function getDelimiter() {
405 return $this->delimiter
;
409 * Boolean, controls output of large amounts of debug information.
410 * @param bool|null $debug
411 * - true to enable debugging
412 * - false to disable debugging
413 * - omitted or null to do nothing
415 * @return bool|null Previous value of the flag
417 public function debug( $debug = null ) {
418 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
421 public function bufferResults( $buffer = null ) {
422 if ( is_null( $buffer ) ) {
423 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
425 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
430 * Turns on (false) or off (true) the automatic generation and sending
431 * of a "we're sorry, but there has been a database error" page on
432 * database errors. Default is on (false). When turned off, the
433 * code should use lastErrno() and lastError() to handle the
434 * situation as appropriate.
436 * Do not use this function outside of the Database classes.
438 * @param null|bool $ignoreErrors
439 * @return bool The previous value of the flag.
441 protected function ignoreErrors( $ignoreErrors = null ) {
442 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
445 public function trxLevel() {
446 return $this->mTrxLevel
;
449 public function trxTimestamp() {
450 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
453 public function tablePrefix( $prefix = null ) {
454 return wfSetVar( $this->mTablePrefix
, $prefix );
457 public function dbSchema( $schema = null ) {
458 return wfSetVar( $this->mSchema
, $schema );
462 * Set the filehandle to copy write statements to.
464 * @param resource $fh File handle
466 public function setFileHandle( $fh ) {
467 $this->fileHandle
= $fh;
470 public function getLBInfo( $name = null ) {
471 if ( is_null( $name ) ) {
472 return $this->mLBInfo
;
474 if ( array_key_exists( $name, $this->mLBInfo
) ) {
475 return $this->mLBInfo
[$name];
482 public function setLBInfo( $name, $value = null ) {
483 if ( is_null( $value ) ) {
484 $this->mLBInfo
= $name;
486 $this->mLBInfo
[$name] = $value;
490 public function setLazyMasterHandle( IDatabase
$conn ) {
491 $this->lazyMasterHandle
= $conn;
495 * @return IDatabase|null
496 * @see setLazyMasterHandle()
499 public function getLazyMasterHandle() {
500 return $this->lazyMasterHandle
;
504 * @param TransactionProfiler $profiler
507 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
508 $this->trxProfiler
= $profiler;
512 * Returns true if this database supports (and uses) cascading deletes
516 public function cascadingDeletes() {
521 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
525 public function cleanupTriggers() {
530 * Returns true if this database is strict about what can be put into an IP field.
531 * Specifically, it uses a NULL value instead of an empty string.
535 public function strictIPs() {
540 * Returns true if this database uses timestamps rather than integers
544 public function realTimestamps() {
548 public function implicitGroupby() {
552 public function implicitOrderby() {
557 * Returns true if this database can do a native search on IP columns
558 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
562 public function searchableIPs() {
567 * Returns true if this database can use functional indexes
571 public function functionalIndexes() {
575 public function lastQuery() {
576 return $this->mLastQuery
;
579 public function doneWrites() {
580 return (bool)$this->mDoneWrites
;
583 public function lastDoneWrites() {
584 return $this->mDoneWrites ?
: false;
587 public function writesPending() {
588 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
591 public function writesOrCallbacksPending() {
592 return $this->mTrxLevel
&& (
593 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
597 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
598 if ( !$this->mTrxLevel
) {
600 } elseif ( !$this->mTrxDoneWrites
) {
605 case self
::ESTIMATE_DB_APPLY
:
607 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
608 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
609 // For omitted queries, make them count as something at least
610 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
611 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
614 default: // everything
615 return $this->mTrxWriteDuration
;
619 public function pendingWriteCallers() {
620 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
623 public function isOpen() {
624 return $this->mOpened
;
627 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
628 if ( $remember === self
::REMEMBER_PRIOR
) {
629 array_push( $this->priorFlags
, $this->mFlags
);
631 $this->mFlags |
= $flag;
634 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
635 if ( $remember === self
::REMEMBER_PRIOR
) {
636 array_push( $this->priorFlags
, $this->mFlags
);
638 $this->mFlags
&= ~
$flag;
641 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
642 if ( !$this->priorFlags
) {
646 if ( $state === self
::RESTORE_INITIAL
) {
647 $this->mFlags
= reset( $this->priorFlags
);
648 $this->priorFlags
= [];
650 $this->mFlags
= array_pop( $this->priorFlags
);
654 public function getFlag( $flag ) {
655 return !!( $this->mFlags
& $flag );
658 public function getProperty( $name ) {
662 public function getWikiID() {
663 if ( $this->mTablePrefix
) {
664 return "{$this->mDBname}-{$this->mTablePrefix}";
666 return $this->mDBname
;
671 * Return a path to the DBMS-specific SQL file if it exists,
672 * otherwise default SQL file
674 * @param string $filename
677 private function getSqlFilePath( $filename ) {
679 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
680 if ( file_exists( $dbmsSpecificFilePath ) ) {
681 return $dbmsSpecificFilePath;
683 return "$IP/maintenance/$filename";
688 * Return a path to the DBMS-specific schema file,
689 * otherwise default to tables.sql
693 public function getSchemaPath() {
694 return $this->getSqlFilePath( 'tables.sql' );
698 * Return a path to the DBMS-specific update key file,
699 * otherwise default to update-keys.sql
703 public function getUpdateKeysPath() {
704 return $this->getSqlFilePath( 'update-keys.sql' );
708 * Get information about an index into an object
709 * @param string $table Table name
710 * @param string $index Index name
711 * @param string $fname Calling function name
712 * @return mixed Database-specific index description class or false if the index does not exist
714 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
717 * Wrapper for addslashes()
719 * @param string $s String to be slashed.
720 * @return string Slashed string.
722 abstract function strencode( $s );
725 * Called by serialize. Throw an exception when DB connection is serialized.
726 * This causes problems on some database engines because the connection is
727 * not restored on unserialize.
729 public function __sleep() {
730 throw new RuntimeException( 'Database serialization may cause problems, since ' .
731 'the connection is not restored on wakeup.' );
734 protected function installErrorHandler() {
735 $this->mPHPError
= false;
736 $this->htmlErrors
= ini_set( 'html_errors', '0' );
737 set_error_handler( [ $this, 'connectionerrorLogger' ] );
741 * @return bool|string
743 protected function restoreErrorHandler() {
744 restore_error_handler();
745 if ( $this->htmlErrors
!== false ) {
746 ini_set( 'html_errors', $this->htmlErrors
);
748 if ( $this->mPHPError
) {
749 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
750 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
760 * @param string $errstr
762 public function connectionerrorLogger( $errno, $errstr ) {
763 $this->mPHPError
= $errstr;
767 * Create a log context to pass to PSR logging functions.
769 * @param array $extras Additional data to add to context
772 protected function getLogContext( array $extras = [] ) {
775 'db_server' => $this->mServer
,
776 'db_name' => $this->mDBname
,
777 'db_user' => $this->mUser
,
783 public function close() {
784 if ( $this->mConn
) {
785 if ( $this->trxLevel() ) {
786 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
789 $closed = $this->closeConnection();
790 $this->mConn
= false;
791 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
792 throw new RuntimeException( "Transaction callbacks still pending." );
796 $this->mOpened
= false;
802 * Make sure isOpen() returns true as a sanity check
804 * @throws DBUnexpectedError
806 protected function assertOpen() {
807 if ( !$this->isOpen() ) {
808 throw new DBUnexpectedError( $this, "DB connection was already closed." );
813 * Closes underlying database connection
815 * @return bool Whether connection was closed successfully
817 abstract protected function closeConnection();
819 function reportConnectionError( $error = 'Unknown error' ) {
820 $myError = $this->lastError();
826 throw new DBConnectionError( $this, $error );
830 * The DBMS-dependent part of query()
832 * @param string $sql SQL query.
833 * @return ResultWrapper|bool Result object to feed to fetchObject,
834 * fetchRow, ...; or false on failure
836 abstract protected function doQuery( $sql );
839 * Determine whether a query writes to the DB.
840 * Should return true if unsure.
845 protected function isWriteQuery( $sql ) {
847 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
852 * @return string|null
854 protected function getQueryVerb( $sql ) {
855 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
859 * Determine whether a SQL statement is sensitive to isolation level.
860 * A SQL statement is considered transactable if its result could vary
861 * depending on the transaction isolation level. Operational commands
862 * such as 'SET' and 'SHOW' are not considered to be transactable.
867 protected function isTransactableQuery( $sql ) {
868 $verb = $this->getQueryVerb( $sql );
869 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
872 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 a comment for easy SHOW PROCESSLIST interpretation
889 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
890 $userName = $wgUser->getName();
891 if ( mb_strlen( $userName ) > 15 ) {
892 $userName = mb_substr( $userName, 0, 15 ) . '...';
894 $userName = str_replace( '/', '', $userName );
899 // Add trace comment to the begin of the sql string, right after the operator.
900 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
901 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
903 # Start implicit transactions that wrap the request if DBO_TRX is enabled
904 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
905 && $this->isTransactableQuery( $sql )
907 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
908 $this->mTrxAutomatic
= true;
911 # Keep track of whether the transaction has write queries pending
912 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
913 $this->mTrxDoneWrites
= true;
914 $this->trxProfiler
->transactionWritingIn(
915 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
918 if ( $this->debug() ) {
919 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
922 # Avoid fatals if close() was called
925 # Send the query to the server
926 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
928 # Try reconnecting if the connection was lost
929 if ( false === $ret && $this->wasErrorReissuable() ) {
930 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
931 # Stash the last error values before anything might clear them
932 $lastError = $this->lastError();
933 $lastErrno = $this->lastErrno();
934 # Update state tracking to reflect transaction loss due to disconnection
935 $this->handleTransactionLoss();
936 if ( $this->reconnect() ) {
937 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
938 $this->connLogger
->warning( $msg );
939 $this->queryLogger
->warning(
940 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
942 if ( !$recoverable ) {
943 # Callers may catch the exception and continue to use the DB
944 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
946 # Should be safe to silently retry the query
947 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
950 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
951 $this->connLogger
->error( $msg );
955 if ( false === $ret ) {
956 # Deadlocks cause the entire transaction to abort, not just the statement.
957 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
958 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
959 if ( $this->wasDeadlock() ) {
960 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
961 $tempIgnore = false; // not recoverable
963 # Update state tracking to reflect transaction loss
964 $this->handleTransactionLoss();
967 $this->reportQueryError(
968 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
971 $res = $this->resultObject( $ret );
976 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
977 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
978 # generalizeSQL() will probably cut down the query to reasonable
979 # logging size most of the time. The substr is really just a sanity check.
981 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
983 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
986 # Include query transaction state
987 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
989 $startTime = microtime( true );
990 $this->profiler
->profileIn( $queryProf );
991 $ret = $this->doQuery( $commentedSql );
992 $this->profiler
->profileOut( $queryProf );
993 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
995 unset( $queryProfSection ); // profile out (if set)
997 if ( $ret !== false ) {
998 $this->lastPing
= $startTime;
999 if ( $isWrite && $this->mTrxLevel
) {
1000 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1001 $this->mTrxWriteCallers
[] = $fname;
1005 if ( $sql === self
::PING_QUERY
) {
1006 $this->mRTTEstimate
= $queryRuntime;
1009 $this->trxProfiler
->recordQueryCompletion(
1010 $queryProf, $startTime, $isWrite, $this->affectedRows()
1012 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
1018 * Update the estimated run-time of a query, not counting large row lock times
1020 * LoadBalancer can be set to rollback transactions that will create huge replication
1021 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1022 * queries, like inserting a row can take a long time due to row locking. This method
1023 * uses some simple heuristics to discount those cases.
1025 * @param string $sql A SQL write query
1026 * @param float $runtime Total runtime, including RTT
1028 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1029 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1030 $indicativeOfReplicaRuntime = true;
1031 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1032 $verb = $this->getQueryVerb( $sql );
1033 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1034 if ( $verb === 'INSERT' ) {
1035 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1036 } elseif ( $verb === 'REPLACE' ) {
1037 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1041 $this->mTrxWriteDuration +
= $runtime;
1042 $this->mTrxWriteQueryCount +
= 1;
1043 if ( $indicativeOfReplicaRuntime ) {
1044 $this->mTrxWriteAdjDuration +
= $runtime;
1045 $this->mTrxWriteAdjQueryCount +
= 1;
1049 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1050 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1051 # Dropped connections also mean that named locks are automatically released.
1052 # Only allow error suppression in autocommit mode or when the lost transaction
1053 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1054 if ( $this->mNamedLocksHeld
) {
1055 return false; // possible critical section violation
1056 } elseif ( $sql === 'COMMIT' ) {
1057 return !$priorWritesPending; // nothing written anyway? (T127428)
1058 } elseif ( $sql === 'ROLLBACK' ) {
1059 return true; // transaction lost...which is also what was requested :)
1060 } elseif ( $this->explicitTrxActive() ) {
1061 return false; // don't drop atomocity
1062 } elseif ( $priorWritesPending ) {
1063 return false; // prior writes lost from implicit transaction
1069 private function handleTransactionLoss() {
1070 $this->mTrxLevel
= 0;
1071 $this->mTrxIdleCallbacks
= []; // bug 65263
1072 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1074 // Handle callbacks in mTrxEndCallbacks
1075 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1076 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1078 } catch ( Exception
$e ) {
1079 // Already logged; move on...
1084 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1085 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1086 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1088 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1089 $this->queryLogger
->error(
1090 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1091 $this->getLogContext( [
1092 'method' => __METHOD__
,
1095 'sql1line' => $sql1line,
1099 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1100 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1105 * Intended to be compatible with the PEAR::DB wrapper functions.
1106 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1108 * ? = scalar value, quoted as necessary
1109 * ! = raw SQL bit (a function for instance)
1110 * & = filename; reads the file and inserts as a blob
1111 * (we don't use this though...)
1113 * @param string $sql
1114 * @param string $func
1118 protected function prepare( $sql, $func = __METHOD__
) {
1119 /* MySQL doesn't support prepared statements (yet), so just
1120 * pack up the query for reference. We'll manually replace
1123 return [ 'query' => $sql, 'func' => $func ];
1127 * Free a prepared query, generated by prepare().
1128 * @param string $prepared
1130 protected function freePrepared( $prepared ) {
1131 /* No-op by default */
1135 * Execute a prepared query with the various arguments
1136 * @param string $prepared The prepared sql
1137 * @param mixed $args Either an array here, or put scalars as varargs
1139 * @return ResultWrapper
1141 public function execute( $prepared, $args = null ) {
1142 if ( !is_array( $args ) ) {
1144 $args = func_get_args();
1145 array_shift( $args );
1148 $sql = $this->fillPrepared( $prepared['query'], $args );
1150 return $this->query( $sql, $prepared['func'] );
1154 * For faking prepared SQL statements on DBs that don't support it directly.
1156 * @param string $preparedQuery A 'preparable' SQL statement
1157 * @param array $args Array of Arguments to fill it with
1158 * @return string Executable SQL
1160 public function fillPrepared( $preparedQuery, $args ) {
1162 $this->preparedArgs
=& $args;
1164 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1165 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1169 * preg_callback func for fillPrepared()
1170 * The arguments should be in $this->preparedArgs and must not be touched
1171 * while we're doing this.
1173 * @param array $matches
1174 * @throws DBUnexpectedError
1177 protected function fillPreparedArg( $matches ) {
1178 switch ( $matches[1] ) {
1187 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1189 switch ( $matches[1] ) {
1191 return $this->addQuotes( $arg );
1195 # return $this->addQuotes( file_get_contents( $arg ) );
1196 throw new DBUnexpectedError(
1198 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1201 throw new DBUnexpectedError(
1203 'Received invalid match. This should never happen!'
1208 public function freeResult( $res ) {
1211 public function selectField(
1212 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1214 if ( $var === '*' ) { // sanity
1215 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1218 if ( !is_array( $options ) ) {
1219 $options = [ $options ];
1222 $options['LIMIT'] = 1;
1224 $res = $this->select( $table, $var, $cond, $fname, $options );
1225 if ( $res === false ||
!$this->numRows( $res ) ) {
1229 $row = $this->fetchRow( $res );
1231 if ( $row !== false ) {
1232 return reset( $row );
1238 public function selectFieldValues(
1239 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1241 if ( $var === '*' ) { // sanity
1242 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1243 } elseif ( !is_string( $var ) ) { // sanity
1244 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1247 if ( !is_array( $options ) ) {
1248 $options = [ $options ];
1251 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1252 if ( $res === false ) {
1257 foreach ( $res as $row ) {
1258 $values[] = $row->$var;
1265 * Returns an optional USE INDEX clause to go after the table, and a
1266 * string to go at the end of the query.
1268 * @param array $options Associative array of options to be turned into
1269 * an SQL query, valid keys are listed in the function.
1271 * @see DatabaseBase::select()
1273 public function makeSelectOptions( $options ) {
1274 $preLimitTail = $postLimitTail = '';
1279 foreach ( $options as $key => $option ) {
1280 if ( is_numeric( $key ) ) {
1281 $noKeyOptions[$option] = true;
1285 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1287 $preLimitTail .= $this->makeOrderBy( $options );
1289 // if (isset($options['LIMIT'])) {
1290 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1291 // isset($options['OFFSET']) ? $options['OFFSET']
1295 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1296 $postLimitTail .= ' FOR UPDATE';
1299 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1300 $postLimitTail .= ' LOCK IN SHARE MODE';
1303 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1304 $startOpts .= 'DISTINCT';
1307 # Various MySQL extensions
1308 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1309 $startOpts .= ' /*! STRAIGHT_JOIN */';
1312 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1313 $startOpts .= ' HIGH_PRIORITY';
1316 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1317 $startOpts .= ' SQL_BIG_RESULT';
1320 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1321 $startOpts .= ' SQL_BUFFER_RESULT';
1324 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1325 $startOpts .= ' SQL_SMALL_RESULT';
1328 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1329 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1332 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1333 $startOpts .= ' SQL_CACHE';
1336 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1337 $startOpts .= ' SQL_NO_CACHE';
1340 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1341 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1345 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1346 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1351 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1355 * Returns an optional GROUP BY with an optional HAVING
1357 * @param array $options Associative array of options
1359 * @see DatabaseBase::select()
1362 public function makeGroupByWithHaving( $options ) {
1364 if ( isset( $options['GROUP BY'] ) ) {
1365 $gb = is_array( $options['GROUP BY'] )
1366 ?
implode( ',', $options['GROUP BY'] )
1367 : $options['GROUP BY'];
1368 $sql .= ' GROUP BY ' . $gb;
1370 if ( isset( $options['HAVING'] ) ) {
1371 $having = is_array( $options['HAVING'] )
1372 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1373 : $options['HAVING'];
1374 $sql .= ' HAVING ' . $having;
1381 * Returns an optional ORDER BY
1383 * @param array $options Associative array of options
1385 * @see DatabaseBase::select()
1388 public function makeOrderBy( $options ) {
1389 if ( isset( $options['ORDER BY'] ) ) {
1390 $ob = is_array( $options['ORDER BY'] )
1391 ?
implode( ',', $options['ORDER BY'] )
1392 : $options['ORDER BY'];
1394 return ' ORDER BY ' . $ob;
1400 // See IDatabase::select for the docs for this function
1401 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1402 $options = [], $join_conds = [] ) {
1403 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1405 return $this->query( $sql, $fname );
1408 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1409 $options = [], $join_conds = []
1411 if ( is_array( $vars ) ) {
1412 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1415 $options = (array)$options;
1416 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1417 ?
$options['USE INDEX']
1419 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1420 ?
$options['IGNORE INDEX']
1423 if ( is_array( $table ) ) {
1425 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1426 } elseif ( $table != '' ) {
1427 if ( $table[0] == ' ' ) {
1428 $from = ' FROM ' . $table;
1431 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1437 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1438 $this->makeSelectOptions( $options );
1440 if ( !empty( $conds ) ) {
1441 if ( is_array( $conds ) ) {
1442 $conds = $this->makeList( $conds, LIST_AND
);
1444 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1446 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1449 if ( isset( $options['LIMIT'] ) ) {
1450 $sql = $this->limitResult( $sql, $options['LIMIT'],
1451 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1453 $sql = "$sql $postLimitTail";
1455 if ( isset( $options['EXPLAIN'] ) ) {
1456 $sql = 'EXPLAIN ' . $sql;
1462 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1463 $options = [], $join_conds = []
1465 $options = (array)$options;
1466 $options['LIMIT'] = 1;
1467 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1469 if ( $res === false ) {
1473 if ( !$this->numRows( $res ) ) {
1477 $obj = $this->fetchObject( $res );
1482 public function estimateRowCount(
1483 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1486 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1489 $row = $this->fetchRow( $res );
1490 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1496 public function selectRowCount(
1497 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1500 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1501 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1504 $row = $this->fetchRow( $res );
1505 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1512 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1513 * It's only slightly flawed. Don't use for anything important.
1515 * @param string $sql A SQL Query
1519 protected static function generalizeSQL( $sql ) {
1520 # This does the same as the regexp below would do, but in such a way
1521 # as to avoid crashing php on some large strings.
1522 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1524 $sql = str_replace( "\\\\", '', $sql );
1525 $sql = str_replace( "\\'", '', $sql );
1526 $sql = str_replace( "\\\"", '', $sql );
1527 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1528 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1530 # All newlines, tabs, etc replaced by single space
1531 $sql = preg_replace( '/\s+/', ' ', $sql );
1534 # except the ones surrounded by characters, e.g. l10n
1535 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1536 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1541 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1542 $info = $this->fieldInfo( $table, $field );
1547 public function indexExists( $table, $index, $fname = __METHOD__
) {
1548 if ( !$this->tableExists( $table ) ) {
1552 $info = $this->indexInfo( $table, $index, $fname );
1553 if ( is_null( $info ) ) {
1556 return $info !== false;
1560 public function tableExists( $table, $fname = __METHOD__
) {
1561 $table = $this->tableName( $table );
1562 $old = $this->ignoreErrors( true );
1563 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1564 $this->ignoreErrors( $old );
1569 public function indexUnique( $table, $index ) {
1570 $indexInfo = $this->indexInfo( $table, $index );
1572 if ( !$indexInfo ) {
1576 return !$indexInfo[0]->Non_unique
;
1580 * Helper for DatabaseBase::insert().
1582 * @param array $options
1585 protected function makeInsertOptions( $options ) {
1586 return implode( ' ', $options );
1589 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1590 # No rows to insert, easy just return now
1591 if ( !count( $a ) ) {
1595 $table = $this->tableName( $table );
1597 if ( !is_array( $options ) ) {
1598 $options = [ $options ];
1602 if ( isset( $options['fileHandle'] ) ) {
1603 $fh = $options['fileHandle'];
1605 $options = $this->makeInsertOptions( $options );
1607 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1609 $keys = array_keys( $a[0] );
1612 $keys = array_keys( $a );
1615 $sql = 'INSERT ' . $options .
1616 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1620 foreach ( $a as $row ) {
1626 $sql .= '(' . $this->makeList( $row ) . ')';
1629 $sql .= '(' . $this->makeList( $a ) . ')';
1632 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1634 } elseif ( $fh !== null ) {
1638 return (bool)$this->query( $sql, $fname );
1642 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1644 * @param array $options
1647 protected function makeUpdateOptionsArray( $options ) {
1648 if ( !is_array( $options ) ) {
1649 $options = [ $options ];
1654 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1655 $opts[] = $this->lowPriorityOption();
1658 if ( in_array( 'IGNORE', $options ) ) {
1666 * Make UPDATE options for the DatabaseBase::update function
1668 * @param array $options The options passed to DatabaseBase::update
1671 protected function makeUpdateOptions( $options ) {
1672 $opts = $this->makeUpdateOptionsArray( $options );
1674 return implode( ' ', $opts );
1677 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1678 $table = $this->tableName( $table );
1679 $opts = $this->makeUpdateOptions( $options );
1680 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1682 if ( $conds !== [] && $conds !== '*' ) {
1683 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1686 return $this->query( $sql, $fname );
1689 public function makeList( $a, $mode = LIST_COMMA
) {
1690 if ( !is_array( $a ) ) {
1691 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1697 foreach ( $a as $field => $value ) {
1699 if ( $mode == LIST_AND
) {
1701 } elseif ( $mode == LIST_OR
) {
1710 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1711 $list .= "($value)";
1712 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1714 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1715 // Remove null from array to be handled separately if found
1716 $includeNull = false;
1717 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1718 $includeNull = true;
1719 unset( $value[$nullKey] );
1721 if ( count( $value ) == 0 && !$includeNull ) {
1722 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1723 } elseif ( count( $value ) == 0 ) {
1724 // only check if $field is null
1725 $list .= "$field IS NULL";
1727 // IN clause contains at least one valid element
1728 if ( $includeNull ) {
1729 // Group subconditions to ensure correct precedence
1732 if ( count( $value ) == 1 ) {
1733 // Special-case single values, as IN isn't terribly efficient
1734 // Don't necessarily assume the single key is 0; we don't
1735 // enforce linear numeric ordering on other arrays here.
1736 $value = array_values( $value )[0];
1737 $list .= $field . " = " . $this->addQuotes( $value );
1739 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1741 // if null present in array, append IS NULL
1742 if ( $includeNull ) {
1743 $list .= " OR $field IS NULL)";
1746 } elseif ( $value === null ) {
1747 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1748 $list .= "$field IS ";
1749 } elseif ( $mode == LIST_SET
) {
1750 $list .= "$field = ";
1754 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1755 $list .= "$field = ";
1757 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1764 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1767 foreach ( $data as $base => $sub ) {
1768 if ( count( $sub ) ) {
1769 $conds[] = $this->makeList(
1770 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1776 return $this->makeList( $conds, LIST_OR
);
1778 // Nothing to search for...
1784 * Return aggregated value alias
1786 * @param array $valuedata
1787 * @param string $valuename
1791 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1795 public function bitNot( $field ) {
1799 public function bitAnd( $fieldLeft, $fieldRight ) {
1800 return "($fieldLeft & $fieldRight)";
1803 public function bitOr( $fieldLeft, $fieldRight ) {
1804 return "($fieldLeft | $fieldRight)";
1807 public function buildConcat( $stringList ) {
1808 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1811 public function buildGroupConcatField(
1812 $delim, $table, $field, $conds = '', $join_conds = []
1814 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1816 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1820 * @param string $field Field or column to cast
1824 public function buildStringCast( $field ) {
1828 public function selectDB( $db ) {
1829 # Stub. Shouldn't cause serious problems if it's not overridden, but
1830 # if your database engine supports a concept similar to MySQL's
1831 # databases you may as well.
1832 $this->mDBname
= $db;
1837 public function getDBname() {
1838 return $this->mDBname
;
1841 public function getServer() {
1842 return $this->mServer
;
1846 * Format a table name ready for use in constructing an SQL query
1848 * This does two important things: it quotes the table names to clean them up,
1849 * and it adds a table prefix if only given a table name with no quotes.
1851 * All functions of this object which require a table name call this function
1852 * themselves. Pass the canonical name to such functions. This is only needed
1853 * when calling query() directly.
1855 * @note This function does not sanitize user input. It is not safe to use
1856 * this function to escape user input.
1857 * @param string $name Database table name
1858 * @param string $format One of:
1859 * quoted - Automatically pass the table name through addIdentifierQuotes()
1860 * so that it can be used in a query.
1861 * raw - Do not add identifier quotes to the table name
1862 * @return string Full database name
1864 public function tableName( $name, $format = 'quoted' ) {
1865 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1866 # Skip the entire process when we have a string quoted on both ends.
1867 # Note that we check the end so that we will still quote any use of
1868 # use of `database`.table. But won't break things if someone wants
1869 # to query a database table with a dot in the name.
1870 if ( $this->isQuotedIdentifier( $name ) ) {
1874 # Lets test for any bits of text that should never show up in a table
1875 # name. Basically anything like JOIN or ON which are actually part of
1876 # SQL queries, but may end up inside of the table value to combine
1877 # sql. Such as how the API is doing.
1878 # Note that we use a whitespace test rather than a \b test to avoid
1879 # any remote case where a word like on may be inside of a table name
1880 # surrounded by symbols which may be considered word breaks.
1881 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1885 # Split database and table into proper variables.
1886 # We reverse the explode so that database.table and table both output
1887 # the correct table.
1888 $dbDetails = explode( '.', $name, 3 );
1889 if ( count( $dbDetails ) == 3 ) {
1890 list( $database, $schema, $table ) = $dbDetails;
1891 # We don't want any prefix added in this case
1893 } elseif ( count( $dbDetails ) == 2 ) {
1894 list( $database, $table ) = $dbDetails;
1895 # We don't want any prefix added in this case
1896 # In dbs that support it, $database may actually be the schema
1897 # but that doesn't affect any of the functionality here
1901 list( $table ) = $dbDetails;
1902 if ( $wgSharedDB !== null # We have a shared database
1903 && $this->mForeign
== false # We're not working on a foreign database
1904 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1905 && in_array( $table, $wgSharedTables ) # A shared table is selected
1907 $database = $wgSharedDB;
1908 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1909 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1912 $schema = $this->mSchema
; # Default schema
1913 $prefix = $this->mTablePrefix
; # Default prefix
1917 # Quote $table and apply the prefix if not quoted.
1918 # $tableName might be empty if this is called from Database::replaceVars()
1919 $tableName = "{$prefix}{$table}";
1920 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1921 $tableName = $this->addIdentifierQuotes( $tableName );
1924 # Quote $schema and merge it with the table name if needed
1925 if ( strlen( $schema ) ) {
1926 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1927 $schema = $this->addIdentifierQuotes( $schema );
1929 $tableName = $schema . '.' . $tableName;
1932 # Quote $database and merge it with the table name if needed
1933 if ( $database !== null ) {
1934 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1935 $database = $this->addIdentifierQuotes( $database );
1937 $tableName = $database . '.' . $tableName;
1944 * Fetch a number of table names into an array
1945 * This is handy when you need to construct SQL for joins
1948 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1949 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1950 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1954 public function tableNames() {
1955 $inArray = func_get_args();
1958 foreach ( $inArray as $name ) {
1959 $retVal[$name] = $this->tableName( $name );
1966 * Fetch a number of table names into an zero-indexed numerical array
1967 * This is handy when you need to construct SQL for joins
1970 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1971 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1972 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1976 public function tableNamesN() {
1977 $inArray = func_get_args();
1980 foreach ( $inArray as $name ) {
1981 $retVal[] = $this->tableName( $name );
1988 * Get an aliased table name
1989 * e.g. tableName AS newTableName
1991 * @param string $name Table name, see tableName()
1992 * @param string|bool $alias Alias (optional)
1993 * @return string SQL name for aliased table. Will not alias a table to its own name
1995 public function tableNameWithAlias( $name, $alias = false ) {
1996 if ( !$alias ||
$alias == $name ) {
1997 return $this->tableName( $name );
1999 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2004 * Gets an array of aliased table names
2006 * @param array $tables [ [alias] => table ]
2007 * @return string[] See tableNameWithAlias()
2009 public function tableNamesWithAlias( $tables ) {
2011 foreach ( $tables as $alias => $table ) {
2012 if ( is_numeric( $alias ) ) {
2015 $retval[] = $this->tableNameWithAlias( $table, $alias );
2022 * Get an aliased field name
2023 * e.g. fieldName AS newFieldName
2025 * @param string $name Field name
2026 * @param string|bool $alias Alias (optional)
2027 * @return string SQL name for aliased field. Will not alias a field to its own name
2029 public function fieldNameWithAlias( $name, $alias = false ) {
2030 if ( !$alias ||
(string)$alias === (string)$name ) {
2033 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2038 * Gets an array of aliased field names
2040 * @param array $fields [ [alias] => field ]
2041 * @return string[] See fieldNameWithAlias()
2043 public function fieldNamesWithAlias( $fields ) {
2045 foreach ( $fields as $alias => $field ) {
2046 if ( is_numeric( $alias ) ) {
2049 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2056 * Get the aliased table name clause for a FROM clause
2057 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2059 * @param array $tables ( [alias] => table )
2060 * @param array $use_index Same as for select()
2061 * @param array $ignore_index Same as for select()
2062 * @param array $join_conds Same as for select()
2065 protected function tableNamesWithIndexClauseOrJOIN(
2066 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2070 $use_index = (array)$use_index;
2071 $ignore_index = (array)$ignore_index;
2072 $join_conds = (array)$join_conds;
2074 foreach ( $tables as $alias => $table ) {
2075 if ( !is_string( $alias ) ) {
2076 // No alias? Set it equal to the table name
2079 // Is there a JOIN clause for this table?
2080 if ( isset( $join_conds[$alias] ) ) {
2081 list( $joinType, $conds ) = $join_conds[$alias];
2082 $tableClause = $joinType;
2083 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2084 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2085 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2087 $tableClause .= ' ' . $use;
2090 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2091 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2092 if ( $ignore != '' ) {
2093 $tableClause .= ' ' . $ignore;
2096 $on = $this->makeList( (array)$conds, LIST_AND
);
2098 $tableClause .= ' ON (' . $on . ')';
2101 $retJOIN[] = $tableClause;
2102 } elseif ( isset( $use_index[$alias] ) ) {
2103 // Is there an INDEX clause for this table?
2104 $tableClause = $this->tableNameWithAlias( $table, $alias );
2105 $tableClause .= ' ' . $this->useIndexClause(
2106 implode( ',', (array)$use_index[$alias] )
2109 $ret[] = $tableClause;
2110 } elseif ( isset( $ignore_index[$alias] ) ) {
2111 // Is there an INDEX clause for this table?
2112 $tableClause = $this->tableNameWithAlias( $table, $alias );
2113 $tableClause .= ' ' . $this->ignoreIndexClause(
2114 implode( ',', (array)$ignore_index[$alias] )
2117 $ret[] = $tableClause;
2119 $tableClause = $this->tableNameWithAlias( $table, $alias );
2121 $ret[] = $tableClause;
2125 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2126 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2127 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2129 // Compile our final table clause
2130 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2134 * Get the name of an index in a given table.
2136 * @param string $index
2139 protected function indexName( $index ) {
2140 // Backwards-compatibility hack
2142 'ar_usertext_timestamp' => 'usertext_timestamp',
2143 'un_user_id' => 'user_id',
2144 'un_user_ip' => 'user_ip',
2147 if ( isset( $renamed[$index] ) ) {
2148 return $renamed[$index];
2154 public function addQuotes( $s ) {
2155 if ( $s instanceof Blob
) {
2158 if ( $s === null ) {
2161 # This will also quote numeric values. This should be harmless,
2162 # and protects against weird problems that occur when they really
2163 # _are_ strings such as article titles and string->number->string
2164 # conversion is not 1:1.
2165 return "'" . $this->strencode( $s ) . "'";
2170 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2171 * MySQL uses `backticks` while basically everything else uses double quotes.
2172 * Since MySQL is the odd one out here the double quotes are our generic
2173 * and we implement backticks in DatabaseMysql.
2178 public function addIdentifierQuotes( $s ) {
2179 return '"' . str_replace( '"', '""', $s ) . '"';
2183 * Returns if the given identifier looks quoted or not according to
2184 * the database convention for quoting identifiers .
2186 * @note Do not use this to determine if untrusted input is safe.
2187 * A malicious user can trick this function.
2188 * @param string $name
2191 public function isQuotedIdentifier( $name ) {
2192 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2199 protected function escapeLikeInternal( $s ) {
2200 return addcslashes( $s, '\%_' );
2203 public function buildLike() {
2204 $params = func_get_args();
2206 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2207 $params = $params[0];
2212 foreach ( $params as $value ) {
2213 if ( $value instanceof LikeMatch
) {
2214 $s .= $value->toString();
2216 $s .= $this->escapeLikeInternal( $value );
2220 return " LIKE {$this->addQuotes( $s )} ";
2223 public function anyChar() {
2224 return new LikeMatch( '_' );
2227 public function anyString() {
2228 return new LikeMatch( '%' );
2231 public function nextSequenceValue( $seqName ) {
2236 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2237 * is only needed because a) MySQL must be as efficient as possible due to
2238 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2239 * which index to pick. Anyway, other databases might have different
2240 * indexes on a given table. So don't bother overriding this unless you're
2242 * @param string $index
2245 public function useIndexClause( $index ) {
2250 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2251 * is only needed because a) MySQL must be as efficient as possible due to
2252 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2253 * which index to pick. Anyway, other databases might have different
2254 * indexes on a given table. So don't bother overriding this unless you're
2256 * @param string $index
2259 public function ignoreIndexClause( $index ) {
2263 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2264 $quotedTable = $this->tableName( $table );
2266 if ( count( $rows ) == 0 ) {
2271 if ( !is_array( reset( $rows ) ) ) {
2275 // @FXIME: this is not atomic, but a trx would break affectedRows()
2276 foreach ( $rows as $row ) {
2277 # Delete rows which collide
2278 if ( $uniqueIndexes ) {
2279 $sql = "DELETE FROM $quotedTable WHERE ";
2281 foreach ( $uniqueIndexes as $index ) {
2288 if ( is_array( $index ) ) {
2290 foreach ( $index as $col ) {
2296 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2299 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2303 $this->query( $sql, $fname );
2306 # Now insert the row
2307 $this->insert( $table, $row, $fname );
2312 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2315 * @param string $table Table name
2316 * @param array|string $rows Row(s) to insert
2317 * @param string $fname Caller function name
2319 * @return ResultWrapper
2321 protected function nativeReplace( $table, $rows, $fname ) {
2322 $table = $this->tableName( $table );
2325 if ( !is_array( reset( $rows ) ) ) {
2329 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2332 foreach ( $rows as $row ) {
2339 $sql .= '(' . $this->makeList( $row ) . ')';
2342 return $this->query( $sql, $fname );
2345 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2348 if ( !count( $rows ) ) {
2349 return true; // nothing to do
2352 if ( !is_array( reset( $rows ) ) ) {
2356 if ( count( $uniqueIndexes ) ) {
2357 $clauses = []; // list WHERE clauses that each identify a single row
2358 foreach ( $rows as $row ) {
2359 foreach ( $uniqueIndexes as $index ) {
2360 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2361 $rowKey = []; // unique key to this row
2362 foreach ( $index as $column ) {
2363 $rowKey[$column] = $row[$column];
2365 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2368 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2373 $useTrx = !$this->mTrxLevel
;
2375 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2378 # Update any existing conflicting row(s)
2379 if ( $where !== false ) {
2380 $ok = $this->update( $table, $set, $where, $fname );
2384 # Now insert any non-conflicting row(s)
2385 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2386 } catch ( Exception
$e ) {
2388 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2393 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2399 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2403 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2406 $delTable = $this->tableName( $delTable );
2407 $joinTable = $this->tableName( $joinTable );
2408 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2409 if ( $conds != '*' ) {
2410 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2414 $this->query( $sql, $fname );
2418 * Returns the size of a text field, or -1 for "unlimited"
2420 * @param string $table
2421 * @param string $field
2424 public function textFieldSize( $table, $field ) {
2425 $table = $this->tableName( $table );
2426 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2427 $res = $this->query( $sql, __METHOD__
);
2428 $row = $this->fetchObject( $res );
2432 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2442 * A string to insert into queries to show that they're low-priority, like
2443 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2444 * string and nothing bad should happen.
2446 * @return string Returns the text of the low priority option if it is
2447 * supported, or a blank string otherwise
2449 public function lowPriorityOption() {
2453 public function delete( $table, $conds, $fname = __METHOD__
) {
2455 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2458 $table = $this->tableName( $table );
2459 $sql = "DELETE FROM $table";
2461 if ( $conds != '*' ) {
2462 if ( is_array( $conds ) ) {
2463 $conds = $this->makeList( $conds, LIST_AND
);
2465 $sql .= ' WHERE ' . $conds;
2468 return $this->query( $sql, $fname );
2471 public function insertSelect(
2472 $destTable, $srcTable, $varMap, $conds,
2473 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2475 if ( $this->cliMode
) {
2476 // For massive migrations with downtime, we don't want to select everything
2477 // into memory and OOM, so do all this native on the server side if possible.
2478 return $this->nativeInsertSelect(
2489 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2490 // on only the master (without needing row-based-replication). It also makes it easy to
2491 // know how big the INSERT is going to be.
2493 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2494 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2496 $selectOptions[] = 'FOR UPDATE';
2497 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2503 foreach ( $res as $row ) {
2504 $rows[] = (array)$row;
2507 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2510 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2511 $fname = __METHOD__
,
2512 $insertOptions = [], $selectOptions = []
2514 $destTable = $this->tableName( $destTable );
2516 if ( !is_array( $insertOptions ) ) {
2517 $insertOptions = [ $insertOptions ];
2520 $insertOptions = $this->makeInsertOptions( $insertOptions );
2522 if ( !is_array( $selectOptions ) ) {
2523 $selectOptions = [ $selectOptions ];
2526 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2529 if ( is_array( $srcTable ) ) {
2530 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2532 $srcTable = $this->tableName( $srcTable );
2535 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2536 " SELECT $startOpts " . implode( ',', $varMap ) .
2537 " FROM $srcTable $useIndex $ignoreIndex ";
2539 if ( $conds != '*' ) {
2540 if ( is_array( $conds ) ) {
2541 $conds = $this->makeList( $conds, LIST_AND
);
2543 $sql .= " WHERE $conds";
2546 $sql .= " $tailOpts";
2548 return $this->query( $sql, $fname );
2552 * Construct a LIMIT query with optional offset. This is used for query
2553 * pages. The SQL should be adjusted so that only the first $limit rows
2554 * are returned. If $offset is provided as well, then the first $offset
2555 * rows should be discarded, and the next $limit rows should be returned.
2556 * If the result of the query is not ordered, then the rows to be returned
2557 * are theoretically arbitrary.
2559 * $sql is expected to be a SELECT, if that makes a difference.
2561 * The version provided by default works in MySQL and SQLite. It will very
2562 * likely need to be overridden for most other DBMSes.
2564 * @param string $sql SQL query we will append the limit too
2565 * @param int $limit The SQL limit
2566 * @param int|bool $offset The SQL offset (default false)
2567 * @throws DBUnexpectedError
2570 public function limitResult( $sql, $limit, $offset = false ) {
2571 if ( !is_numeric( $limit ) ) {
2572 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2575 return "$sql LIMIT "
2576 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2580 public function unionSupportsOrderAndLimit() {
2581 return true; // True for almost every DB supported
2584 public function unionQueries( $sqls, $all ) {
2585 $glue = $all ?
') UNION ALL (' : ') UNION (';
2587 return '(' . implode( $glue, $sqls ) . ')';
2590 public function conditional( $cond, $trueVal, $falseVal ) {
2591 if ( is_array( $cond ) ) {
2592 $cond = $this->makeList( $cond, LIST_AND
);
2595 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2598 public function strreplace( $orig, $old, $new ) {
2599 return "REPLACE({$orig}, {$old}, {$new})";
2602 public function getServerUptime() {
2606 public function wasDeadlock() {
2610 public function wasLockTimeout() {
2614 public function wasErrorReissuable() {
2618 public function wasReadOnlyError() {
2623 * Determines if the given query error was a connection drop
2626 * @param integer|string $errno
2629 public function wasConnectionError( $errno ) {
2634 * Perform a deadlock-prone transaction.
2636 * This function invokes a callback function to perform a set of write
2637 * queries. If a deadlock occurs during the processing, the transaction
2638 * will be rolled back and the callback function will be called again.
2640 * Avoid using this method outside of Job or Maintenance classes.
2643 * $dbw->deadlockLoop( callback, ... );
2645 * Extra arguments are passed through to the specified callback function.
2646 * This method requires that no transactions are already active to avoid
2647 * causing premature commits or exceptions.
2649 * Returns whatever the callback function returned on its successful,
2650 * iteration, or false on error, for example if the retry limit was
2654 * @throws DBUnexpectedError
2657 public function deadlockLoop() {
2658 $args = func_get_args();
2659 $function = array_shift( $args );
2660 $tries = self
::DEADLOCK_TRIES
;
2662 $this->begin( __METHOD__
);
2665 /** @var Exception $e */
2669 $retVal = call_user_func_array( $function, $args );
2671 } catch ( DBQueryError
$e ) {
2672 if ( $this->wasDeadlock() ) {
2673 // Retry after a randomized delay
2674 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2676 // Throw the error back up
2680 } while ( --$tries > 0 );
2682 if ( $tries <= 0 ) {
2683 // Too many deadlocks; give up
2684 $this->rollback( __METHOD__
);
2687 $this->commit( __METHOD__
);
2693 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2694 # Real waits are implemented in the subclass.
2698 public function getSlavePos() {
2703 public function getMasterPos() {
2708 public function serverIsReadOnly() {
2712 final public function onTransactionResolution( callable
$callback ) {
2713 if ( !$this->mTrxLevel
) {
2714 throw new DBUnexpectedError( $this, "No transaction is active." );
2716 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2719 final public function onTransactionIdle( callable
$callback ) {
2720 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2721 if ( !$this->mTrxLevel
) {
2722 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2726 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2727 if ( $this->mTrxLevel
) {
2728 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2730 // If no transaction is active, then make one for this callback
2731 $this->startAtomic( __METHOD__
);
2733 call_user_func( $callback );
2734 $this->endAtomic( __METHOD__
);
2735 } catch ( Exception
$e ) {
2736 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2742 final public function setTransactionListener( $name, callable
$callback = null ) {
2744 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2746 unset( $this->mTrxRecurringCallbacks
[$name] );
2751 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2753 * This method should not be used outside of Database/LoadBalancer
2755 * @param bool $suppress
2758 final public function setTrxEndCallbackSuppression( $suppress ) {
2759 $this->mTrxEndCallbacksSuppressed
= $suppress;
2763 * Actually run and consume any "on transaction idle/resolution" callbacks.
2765 * This method should not be used outside of Database/LoadBalancer
2767 * @param integer $trigger IDatabase::TRIGGER_* constant
2771 public function runOnTransactionIdleCallbacks( $trigger ) {
2772 if ( $this->mTrxEndCallbacksSuppressed
) {
2776 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2777 /** @var Exception $e */
2778 $e = null; // first exception
2779 do { // callbacks may add callbacks :)
2780 $callbacks = array_merge(
2781 $this->mTrxIdleCallbacks
,
2782 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2784 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2785 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2786 foreach ( $callbacks as $callback ) {
2788 list( $phpCallback ) = $callback;
2789 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2790 call_user_func_array( $phpCallback, [ $trigger ] );
2792 $this->setFlag( DBO_TRX
); // restore automatic begin()
2794 $this->clearFlag( DBO_TRX
); // restore auto-commit
2796 } catch ( Exception
$ex ) {
2797 call_user_func( $this->errorLogger
, $ex );
2799 // Some callbacks may use startAtomic/endAtomic, so make sure
2800 // their transactions are ended so other callbacks don't fail
2801 if ( $this->trxLevel() ) {
2802 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2806 } while ( count( $this->mTrxIdleCallbacks
) );
2808 if ( $e instanceof Exception
) {
2809 throw $e; // re-throw any first exception
2814 * Actually run and consume any "on transaction pre-commit" callbacks.
2816 * This method should not be used outside of Database/LoadBalancer
2821 public function runOnTransactionPreCommitCallbacks() {
2822 $e = null; // first exception
2823 do { // callbacks may add callbacks :)
2824 $callbacks = $this->mTrxPreCommitCallbacks
;
2825 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2826 foreach ( $callbacks as $callback ) {
2828 list( $phpCallback ) = $callback;
2829 call_user_func( $phpCallback );
2830 } catch ( Exception
$ex ) {
2831 call_user_func( $this->errorLogger
, $ex );
2835 } while ( count( $this->mTrxPreCommitCallbacks
) );
2837 if ( $e instanceof Exception
) {
2838 throw $e; // re-throw any first exception
2843 * Actually run any "transaction listener" callbacks.
2845 * This method should not be used outside of Database/LoadBalancer
2847 * @param integer $trigger IDatabase::TRIGGER_* constant
2851 public function runTransactionListenerCallbacks( $trigger ) {
2852 if ( $this->mTrxEndCallbacksSuppressed
) {
2856 /** @var Exception $e */
2857 $e = null; // first exception
2859 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2861 list( $phpCallback ) = $callback;
2862 $phpCallback( $trigger, $this );
2863 } catch ( Exception
$ex ) {
2864 call_user_func( $this->errorLogger
, $ex );
2869 if ( $e instanceof Exception
) {
2870 throw $e; // re-throw any first exception
2874 final public function startAtomic( $fname = __METHOD__
) {
2875 if ( !$this->mTrxLevel
) {
2876 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2877 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2878 // in all changes being in one transaction to keep requests transactional.
2879 if ( !$this->getFlag( DBO_TRX
) ) {
2880 $this->mTrxAutomaticAtomic
= true;
2884 $this->mTrxAtomicLevels
[] = $fname;
2887 final public function endAtomic( $fname = __METHOD__
) {
2888 if ( !$this->mTrxLevel
) {
2889 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2891 if ( !$this->mTrxAtomicLevels ||
2892 array_pop( $this->mTrxAtomicLevels
) !== $fname
2894 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2897 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2898 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2902 final public function doAtomicSection( $fname, callable
$callback ) {
2903 $this->startAtomic( $fname );
2905 $res = call_user_func_array( $callback, [ $this, $fname ] );
2906 } catch ( Exception
$e ) {
2907 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2910 $this->endAtomic( $fname );
2915 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2916 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2917 if ( $this->mTrxLevel
) {
2918 if ( $this->mTrxAtomicLevels
) {
2919 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2920 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2921 throw new DBUnexpectedError( $this, $msg );
2922 } elseif ( !$this->mTrxAutomatic
) {
2923 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2924 throw new DBUnexpectedError( $this, $msg );
2926 // @TODO: make this an exception at some point
2927 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2928 $this->queryLogger
->error( $msg );
2929 return; // join the main transaction set
2931 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2932 // @TODO: make this an exception at some point
2933 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2934 $this->queryLogger
->error( $msg );
2935 return; // let any writes be in the main transaction
2938 // Avoid fatals if close() was called
2939 $this->assertOpen();
2941 $this->doBegin( $fname );
2942 $this->mTrxTimestamp
= microtime( true );
2943 $this->mTrxFname
= $fname;
2944 $this->mTrxDoneWrites
= false;
2945 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2946 $this->mTrxAutomaticAtomic
= false;
2947 $this->mTrxAtomicLevels
= [];
2948 $this->mTrxShortId
= wfRandomString( 12 );
2949 $this->mTrxWriteDuration
= 0.0;
2950 $this->mTrxWriteQueryCount
= 0;
2951 $this->mTrxWriteAdjDuration
= 0.0;
2952 $this->mTrxWriteAdjQueryCount
= 0;
2953 $this->mTrxWriteCallers
= [];
2954 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2955 // Get an estimate of the replica DB lag before then, treating estimate staleness
2956 // as lag itself just to be safe
2957 $status = $this->getApproximateLagStatus();
2958 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2962 * Issues the BEGIN command to the database server.
2964 * @see DatabaseBase::begin()
2965 * @param string $fname
2967 protected function doBegin( $fname ) {
2968 $this->query( 'BEGIN', $fname );
2969 $this->mTrxLevel
= 1;
2972 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2973 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2974 // There are still atomic sections open. This cannot be ignored
2975 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2976 throw new DBUnexpectedError(
2978 "$fname: Got COMMIT while atomic sections $levels are still open."
2982 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2983 if ( !$this->mTrxLevel
) {
2984 return; // nothing to do
2985 } elseif ( !$this->mTrxAutomatic
) {
2986 throw new DBUnexpectedError(
2988 "$fname: Flushing an explicit transaction, getting out of sync."
2992 if ( !$this->mTrxLevel
) {
2993 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2994 return; // nothing to do
2995 } elseif ( $this->mTrxAutomatic
) {
2996 // @TODO: make this an exception at some point
2997 $msg = "$fname: Explicit commit of implicit transaction.";
2998 $this->queryLogger
->error( $msg );
2999 return; // wait for the main transaction set commit round
3003 // Avoid fatals if close() was called
3004 $this->assertOpen();
3006 $this->runOnTransactionPreCommitCallbacks();
3007 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3008 $this->doCommit( $fname );
3009 if ( $this->mTrxDoneWrites
) {
3010 $this->mDoneWrites
= microtime( true );
3011 $this->trxProfiler
->transactionWritingOut(
3012 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3015 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3016 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3020 * Issues the COMMIT command to the database server.
3022 * @see DatabaseBase::commit()
3023 * @param string $fname
3025 protected function doCommit( $fname ) {
3026 if ( $this->mTrxLevel
) {
3027 $this->query( 'COMMIT', $fname );
3028 $this->mTrxLevel
= 0;
3032 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3033 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3034 if ( !$this->mTrxLevel
) {
3035 return; // nothing to do
3038 if ( !$this->mTrxLevel
) {
3039 $this->queryLogger
->error(
3040 "$fname: No transaction to rollback, something got out of sync." );
3041 return; // nothing to do
3042 } elseif ( $this->getFlag( DBO_TRX
) ) {
3043 throw new DBUnexpectedError(
3045 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3050 // Avoid fatals if close() was called
3051 $this->assertOpen();
3053 $this->doRollback( $fname );
3054 $this->mTrxAtomicLevels
= [];
3055 if ( $this->mTrxDoneWrites
) {
3056 $this->trxProfiler
->transactionWritingOut(
3057 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3060 $this->mTrxIdleCallbacks
= []; // clear
3061 $this->mTrxPreCommitCallbacks
= []; // clear
3062 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3063 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3067 * Issues the ROLLBACK command to the database server.
3069 * @see DatabaseBase::rollback()
3070 * @param string $fname
3072 protected function doRollback( $fname ) {
3073 if ( $this->mTrxLevel
) {
3074 # Disconnects cause rollback anyway, so ignore those errors
3075 $ignoreErrors = true;
3076 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3077 $this->mTrxLevel
= 0;
3081 public function flushSnapshot( $fname = __METHOD__
) {
3082 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3083 // This only flushes transactions to clear snapshots, not to write data
3084 throw new DBUnexpectedError(
3086 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3090 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3093 public function explicitTrxActive() {
3094 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3098 * Creates a new table with structure copied from existing table
3099 * Note that unlike most database abstraction functions, this function does not
3100 * automatically append database prefix, because it works at a lower
3101 * abstraction level.
3102 * The table names passed to this function shall not be quoted (this
3103 * function calls addIdentifierQuotes when needed).
3105 * @param string $oldName Name of table whose structure should be copied
3106 * @param string $newName Name of table to be created
3107 * @param bool $temporary Whether the new table should be temporary
3108 * @param string $fname Calling function name
3109 * @throws RuntimeException
3110 * @return bool True if operation was successful
3112 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3115 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3118 function listTables( $prefix = null, $fname = __METHOD__
) {
3119 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3123 * Reset the views process cache set by listViews()
3126 final public function clearViewsCache() {
3127 $this->allViews
= null;
3131 * Lists all the VIEWs in the database
3133 * For caching purposes the list of all views should be stored in
3134 * $this->allViews. The process cache can be cleared with clearViewsCache()
3136 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3137 * @param string $fname Name of calling function
3138 * @throws RuntimeException
3142 public function listViews( $prefix = null, $fname = __METHOD__
) {
3143 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3147 * Differentiates between a TABLE and a VIEW
3149 * @param string $name Name of the database-structure to test.
3150 * @throws RuntimeException
3154 public function isView( $name ) {
3155 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3158 public function timestamp( $ts = 0 ) {
3159 return wfTimestamp( TS_MW
, $ts );
3162 public function timestampOrNull( $ts = null ) {
3163 if ( is_null( $ts ) ) {
3166 return $this->timestamp( $ts );
3171 * Take the result from a query, and wrap it in a ResultWrapper if
3172 * necessary. Boolean values are passed through as is, to indicate success
3173 * of write queries or failure.
3175 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3176 * resource, and it was necessary to call this function to convert it to
3177 * a wrapper. Nowadays, raw database objects are never exposed to external
3178 * callers, so this is unnecessary in external code.
3180 * @param bool|ResultWrapper|resource|object $result
3181 * @return bool|ResultWrapper
3183 protected function resultObject( $result ) {
3186 } elseif ( $result instanceof ResultWrapper
) {
3188 } elseif ( $result === true ) {
3189 // Successful write query
3192 return new ResultWrapper( $this, $result );
3196 public function ping( &$rtt = null ) {
3197 // Avoid hitting the server if it was hit recently
3198 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3199 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3200 $rtt = $this->mRTTEstimate
;
3201 return true; // don't care about $rtt
3205 // This will reconnect if possible or return false if not
3206 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3207 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3208 $this->restoreFlags( self
::RESTORE_PRIOR
);
3211 $rtt = $this->mRTTEstimate
;
3220 protected function reconnect() {
3221 $this->closeConnection();
3222 $this->mOpened
= false;
3223 $this->mConn
= false;
3225 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3226 $this->lastPing
= microtime( true );
3228 } catch ( DBConnectionError
$e ) {
3235 public function getSessionLagStatus() {
3236 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3240 * Get the replica DB lag when the current transaction started
3242 * This is useful when transactions might use snapshot isolation
3243 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3244 * is this lag plus transaction duration. If they don't, it is still
3245 * safe to be pessimistic. This returns null if there is no transaction.
3247 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3250 public function getTransactionLagStatus() {
3251 return $this->mTrxLevel
3252 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3257 * Get a replica DB lag estimate for this server
3259 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3262 public function getApproximateLagStatus() {
3264 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3265 'since' => microtime( true )
3270 * Merge the result of getSessionLagStatus() for several DBs
3271 * using the most pessimistic values to estimate the lag of
3272 * any data derived from them in combination
3274 * This is information is useful for caching modules
3276 * @see WANObjectCache::set()
3277 * @see WANObjectCache::getWithSetCallback()
3279 * @param IDatabase $db1
3280 * @param IDatabase ...
3281 * @return array Map of values:
3282 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3283 * - since: oldest UNIX timestamp of any of the DB lag estimates
3284 * - pending: whether any of the DBs have uncommitted changes
3287 public static function getCacheSetOptions( IDatabase
$db1 ) {
3288 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3289 foreach ( func_get_args() as $db ) {
3290 /** @var IDatabase $db */
3291 $status = $db->getSessionLagStatus();
3292 if ( $status['lag'] === false ) {
3293 $res['lag'] = false;
3294 } elseif ( $res['lag'] !== false ) {
3295 $res['lag'] = max( $res['lag'], $status['lag'] );
3297 $res['since'] = min( $res['since'], $status['since'] );
3298 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3304 public function getLag() {
3308 function maxListLen() {
3312 public function encodeBlob( $b ) {
3316 public function decodeBlob( $b ) {
3317 if ( $b instanceof Blob
) {
3323 public function setSessionOptions( array $options ) {
3327 * Read and execute SQL commands from a file.
3329 * Returns true on success, error string or exception on failure (depending
3330 * on object's error ignore settings).
3332 * @param string $filename File name to open
3333 * @param bool|callable $lineCallback Optional function called before reading each line
3334 * @param bool|callable $resultCallback Optional function called for each MySQL result
3335 * @param bool|string $fname Calling function name or false if name should be
3336 * generated dynamically using $filename
3337 * @param bool|callable $inputCallback Optional function called for each
3338 * complete line sent
3339 * @return bool|string
3342 public function sourceFile(
3343 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3345 MediaWiki\
suppressWarnings();
3346 $fp = fopen( $filename, 'r' );
3347 MediaWiki\restoreWarnings
();
3349 if ( false === $fp ) {
3350 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3354 $fname = __METHOD__
. "( $filename )";
3358 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3359 } catch ( Exception
$e ) {
3370 * Get the full path of a patch file. Originally based on archive()
3371 * from updaters.inc. Keep in mind this always returns a patch, as
3372 * it fails back to MySQL if no DB-specific patch can be found
3374 * @param string $patch The name of the patch, like patch-something.sql
3375 * @return string Full path to patch file
3377 public function patchPath( $patch ) {
3380 $dbType = $this->getType();
3381 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3382 return "$IP/maintenance/$dbType/archives/$patch";
3384 return "$IP/maintenance/archives/$patch";
3388 public function setSchemaVars( $vars ) {
3389 $this->mSchemaVars
= $vars;
3393 * Read and execute commands from an open file handle.
3395 * Returns true on success, error string or exception on failure (depending
3396 * on object's error ignore settings).
3398 * @param resource $fp File handle
3399 * @param bool|callable $lineCallback Optional function called before reading each query
3400 * @param bool|callable $resultCallback Optional function called for each MySQL result
3401 * @param string $fname Calling function name
3402 * @param bool|callable $inputCallback Optional function called for each complete query sent
3403 * @return bool|string
3405 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3406 $fname = __METHOD__
, $inputCallback = false
3410 while ( !feof( $fp ) ) {
3411 if ( $lineCallback ) {
3412 call_user_func( $lineCallback );
3415 $line = trim( fgets( $fp ) );
3417 if ( $line == '' ) {
3421 if ( '-' == $line[0] && '-' == $line[1] ) {
3429 $done = $this->streamStatementEnd( $cmd, $line );
3433 if ( $done ||
feof( $fp ) ) {
3434 $cmd = $this->replaceVars( $cmd );
3436 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3437 $res = $this->query( $cmd, $fname );
3439 if ( $resultCallback ) {
3440 call_user_func( $resultCallback, $res, $this );
3443 if ( false === $res ) {
3444 $err = $this->lastError();
3446 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3457 * Called by sourceStream() to check if we've reached a statement end
3459 * @param string $sql SQL assembled so far
3460 * @param string $newLine New line about to be added to $sql
3461 * @return bool Whether $newLine contains end of the statement
3463 public function streamStatementEnd( &$sql, &$newLine ) {
3464 if ( $this->delimiter
) {
3466 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3467 if ( $newLine != $prev ) {
3476 * Database independent variable replacement. Replaces a set of variables
3477 * in an SQL statement with their contents as given by $this->getSchemaVars().
3479 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3481 * - '{$var}' should be used for text and is passed through the database's
3483 * - `{$var}` should be used for identifiers (e.g. table and database names).
3484 * It is passed through the database's addIdentifierQuotes method which
3485 * can be overridden if the database uses something other than backticks.
3486 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3487 * database's tableName method.
3488 * - / *i* / passes the name that follows through the database's indexName method.
3489 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3490 * its use should be avoided. In 1.24 and older, string encoding was applied.
3492 * @param string $ins SQL statement to replace variables in
3493 * @return string The new SQL statement with variables replaced
3495 protected function replaceVars( $ins ) {
3496 $vars = $this->getSchemaVars();
3497 return preg_replace_callback(
3499 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3500 \'\{\$ (\w+) }\' | # 3. addQuotes
3501 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3502 /\*\$ (\w+) \*/ # 5. leave unencoded
3504 function ( $m ) use ( $vars ) {
3505 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3506 // check for both nonexistent keys *and* the empty string.
3507 if ( isset( $m[1] ) && $m[1] !== '' ) {
3508 if ( $m[1] === 'i' ) {
3509 return $this->indexName( $m[2] );
3511 return $this->tableName( $m[2] );
3513 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3514 return $this->addQuotes( $vars[$m[3]] );
3515 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3516 return $this->addIdentifierQuotes( $vars[$m[4]] );
3517 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3518 return $vars[$m[5]];
3528 * Get schema variables. If none have been set via setSchemaVars(), then
3529 * use some defaults from the current object.
3533 protected function getSchemaVars() {
3534 if ( $this->mSchemaVars
) {
3535 return $this->mSchemaVars
;
3537 return $this->getDefaultSchemaVars();
3542 * Get schema variables to use if none have been set via setSchemaVars().
3544 * Override this in derived classes to provide variables for tables.sql
3545 * and SQL patch files.
3549 protected function getDefaultSchemaVars() {
3553 public function lockIsFree( $lockName, $method ) {
3557 public function lock( $lockName, $method, $timeout = 5 ) {
3558 $this->mNamedLocksHeld
[$lockName] = 1;
3563 public function unlock( $lockName, $method ) {
3564 unset( $this->mNamedLocksHeld
[$lockName] );
3569 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3570 if ( $this->writesOrCallbacksPending() ) {
3571 // This only flushes transactions to clear snapshots, not to write data
3572 throw new DBUnexpectedError(
3574 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3578 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3582 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3583 if ( $this->trxLevel() ) {
3584 // There is a good chance an exception was thrown, causing any early return
3585 // from the caller. Let any error handler get a chance to issue rollback().
3586 // If there isn't one, let the error bubble up and trigger server-side rollback.
3587 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3588 $this->unlock( $lockKey, $fname );
3591 $this->unlock( $lockKey, $fname );
3595 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3600 public function namedLocksEnqueue() {
3605 * Lock specific tables
3607 * @param array $read Array of tables to lock for read access
3608 * @param array $write Array of tables to lock for write access
3609 * @param string $method Name of caller
3610 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3613 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3618 * Unlock specific tables
3620 * @param string $method The caller
3623 public function unlockTables( $method ) {
3629 * @param string $tableName
3630 * @param string $fName
3631 * @return bool|ResultWrapper
3634 public function dropTable( $tableName, $fName = __METHOD__
) {
3635 if ( !$this->tableExists( $tableName, $fName ) ) {
3638 $sql = "DROP TABLE " . $this->tableName( $tableName );
3639 if ( $this->cascadingDeletes() ) {
3643 return $this->query( $sql, $fName );
3647 * Get search engine class. All subclasses of this need to implement this
3648 * if they wish to use searching.
3652 public function getSearchEngine() {
3653 return 'SearchEngineDummy';
3656 public function getInfinity() {
3660 public function encodeExpiry( $expiry ) {
3661 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3662 ?
$this->getInfinity()
3663 : $this->timestamp( $expiry );
3666 public function decodeExpiry( $expiry, $format = TS_MW
) {
3667 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3669 : wfTimestamp( $format, $expiry );
3672 public function setBigSelects( $value = true ) {
3676 public function isReadOnly() {
3677 return ( $this->getReadOnlyReason() !== false );
3681 * @return string|bool Reason this DB is read-only or false if it is not
3683 protected function getReadOnlyReason() {
3684 $reason = $this->getLBInfo( 'readOnlyReason' );
3686 return is_string( $reason ) ?
$reason : false;
3693 public function __toString() {
3694 return (string)$this->mConn
;
3698 * Run a few simple sanity checks
3700 public function __destruct() {
3701 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3702 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3704 $danglingCallbacks = array_merge(
3705 $this->mTrxIdleCallbacks
,
3706 $this->mTrxPreCommitCallbacks
,
3707 $this->mTrxEndCallbacks
3709 if ( $danglingCallbacks ) {
3711 foreach ( $danglingCallbacks as $callbackInfo ) {
3712 $callers[] = $callbackInfo[1];
3714 $callers = implode( ', ', $callers );
3715 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3723 abstract class Database
extends DatabaseBase
{
3724 // B/C until nothing type hints for DatabaseBase
3725 // @TODO: finish renaming DatabaseBase => Database