4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
35 /** Minimum time to wait before retry, in microseconds */
36 const DEADLOCK_DELAY_MIN
= 500000;
37 /** Maximum time to wait before retry */
38 const DEADLOCK_DELAY_MAX
= 1500000;
40 /** How long before it is worth doing a dummy query to test the connection */
43 /** @var string SQL query */
44 protected $mLastQuery = '';
46 protected $mDoneWrites = false;
47 /** @var string|bool */
48 protected $mPHPError = false;
58 /** @var BagOStuff APC cache */
61 /** @var resource Database connection */
62 protected $mConn = null;
64 protected $mOpened = false;
66 /** @var array[] List of (callable, method name) */
67 protected $mTrxIdleCallbacks = [];
68 /** @var array[] List of (callable, method name) */
69 protected $mTrxPreCommitCallbacks = [];
70 /** @var array[] List of (callable, method name) */
71 protected $mTrxEndCallbacks = [];
72 /** @var bool Whether to suppress triggering of post-commit callbacks */
73 protected $suppressPostCommitCallbacks = false;
76 protected $mTablePrefix;
84 protected $mLBInfo = [];
86 protected $mDefaultBigSelects = null;
87 /** @var array|bool */
88 protected $mSchemaVars = false;
90 protected $mSessionVars = [];
91 /** @var array|null */
92 protected $preparedArgs;
93 /** @var string|bool|null Stashed value of html_errors INI setting */
94 protected $htmlErrors;
96 protected $delimiter = ';';
99 * Either 1 if a transaction is active or 0 otherwise.
100 * The other Trx fields may not be meaningfull if this is 0.
104 protected $mTrxLevel = 0;
107 * Either a short hexidecimal string if a transaction is active or ""
110 * @see DatabaseBase::mTrxLevel
112 protected $mTrxShortId = '';
115 * The UNIX time that the transaction started. Callers can assume that if
116 * snapshot isolation is used, then the data is *at least* up to date to that
117 * point (possibly more up-to-date since the first SELECT defines the snapshot).
120 * @see DatabaseBase::mTrxLevel
122 private $mTrxTimestamp = null;
124 /** @var float Lag estimate at the time of BEGIN */
125 private $mTrxSlaveLag = null;
128 * Remembers the function name given for starting the most recent transaction via begin().
129 * Used to provide additional context for error reporting.
132 * @see DatabaseBase::mTrxLevel
134 private $mTrxFname = null;
137 * Record if possible write queries were done in the last transaction started
140 * @see DatabaseBase::mTrxLevel
142 private $mTrxDoneWrites = false;
145 * Record if the current transaction was started implicitly due to DBO_TRX being set.
148 * @see DatabaseBase::mTrxLevel
150 private $mTrxAutomatic = false;
153 * Array of levels of atomicity within transactions
157 private $mTrxAtomicLevels = [];
160 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
164 private $mTrxAutomaticAtomic = false;
167 * Track the write query callers of the current transaction
171 private $mTrxWriteCallers = [];
174 * Track the seconds spent in write queries for the current transaction
178 private $mTrxWriteDuration = 0.0;
180 /** @var array Map of (name => 1) for locks obtained via lock() */
181 private $mNamedLocksHeld = [];
183 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
184 private $lazyMasterHandle;
188 * @var resource File handle for upgrade
190 protected $fileHandle = null;
194 * @var string[] Process cache of VIEWs names in the database
196 protected $allViews = null;
198 /** @var float UNIX timestamp */
199 protected $lastPing = 0.0;
201 /** @var int[] Prior mFlags values */
202 private $priorFlags = [];
204 /** @var TransactionProfiler */
205 protected $trxProfiler;
207 public function getServerInfo() {
208 return $this->getServerVersion();
212 * @return string Command delimiter used by this database engine
214 public function getDelimiter() {
215 return $this->delimiter
;
219 * Boolean, controls output of large amounts of debug information.
220 * @param bool|null $debug
221 * - true to enable debugging
222 * - false to disable debugging
223 * - omitted or null to do nothing
225 * @return bool|null Previous value of the flag
227 public function debug( $debug = null ) {
228 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
231 public function bufferResults( $buffer = null ) {
232 if ( is_null( $buffer ) ) {
233 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
235 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
240 * Turns on (false) or off (true) the automatic generation and sending
241 * of a "we're sorry, but there has been a database error" page on
242 * database errors. Default is on (false). When turned off, the
243 * code should use lastErrno() and lastError() to handle the
244 * situation as appropriate.
246 * Do not use this function outside of the Database classes.
248 * @param null|bool $ignoreErrors
249 * @return bool The previous value of the flag.
251 protected function ignoreErrors( $ignoreErrors = null ) {
252 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
255 public function trxLevel() {
256 return $this->mTrxLevel
;
259 public function trxTimestamp() {
260 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
263 public function tablePrefix( $prefix = null ) {
264 return wfSetVar( $this->mTablePrefix
, $prefix );
267 public function dbSchema( $schema = null ) {
268 return wfSetVar( $this->mSchema
, $schema );
272 * Set the filehandle to copy write statements to.
274 * @param resource $fh File handle
276 public function setFileHandle( $fh ) {
277 $this->fileHandle
= $fh;
280 public function getLBInfo( $name = null ) {
281 if ( is_null( $name ) ) {
282 return $this->mLBInfo
;
284 if ( array_key_exists( $name, $this->mLBInfo
) ) {
285 return $this->mLBInfo
[$name];
292 public function setLBInfo( $name, $value = null ) {
293 if ( is_null( $value ) ) {
294 $this->mLBInfo
= $name;
296 $this->mLBInfo
[$name] = $value;
301 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
303 * @param IDatabase $conn
306 public function setLazyMasterHandle( IDatabase
$conn ) {
307 $this->lazyMasterHandle
= $conn;
311 * @return IDatabase|null
312 * @see setLazyMasterHandle()
315 public function getLazyMasterHandle() {
316 return $this->lazyMasterHandle
;
320 * @return TransactionProfiler
322 protected function getTransactionProfiler() {
323 if ( !$this->trxProfiler
) {
324 $this->trxProfiler
= new TransactionProfiler();
327 return $this->trxProfiler
;
331 * @param TransactionProfiler $profiler
334 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
335 $this->trxProfiler
= $profiler;
339 * Returns true if this database supports (and uses) cascading deletes
343 public function cascadingDeletes() {
348 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
352 public function cleanupTriggers() {
357 * Returns true if this database is strict about what can be put into an IP field.
358 * Specifically, it uses a NULL value instead of an empty string.
362 public function strictIPs() {
367 * Returns true if this database uses timestamps rather than integers
371 public function realTimestamps() {
375 public function implicitGroupby() {
379 public function implicitOrderby() {
384 * Returns true if this database can do a native search on IP columns
385 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
389 public function searchableIPs() {
394 * Returns true if this database can use functional indexes
398 public function functionalIndexes() {
402 public function lastQuery() {
403 return $this->mLastQuery
;
406 public function doneWrites() {
407 return (bool)$this->mDoneWrites
;
410 public function lastDoneWrites() {
411 return $this->mDoneWrites ?
: false;
414 public function writesPending() {
415 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
418 public function writesOrCallbacksPending() {
419 return $this->mTrxLevel
&& (
420 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
424 public function pendingWriteQueryDuration() {
425 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
428 public function pendingWriteCallers() {
429 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
432 public function isOpen() {
433 return $this->mOpened
;
436 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
437 if ( $remember === self
::REMEMBER_PRIOR
) {
438 array_push( $this->priorFlags
, $this->mFlags
);
440 $this->mFlags |
= $flag;
443 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
444 if ( $remember === self
::REMEMBER_PRIOR
) {
445 array_push( $this->priorFlags
, $this->mFlags
);
447 $this->mFlags
&= ~
$flag;
450 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
451 if ( !$this->priorFlags
) {
455 if ( $state === self
::RESTORE_INITIAL
) {
456 $this->mFlags
= reset( $this->priorFlags
);
457 $this->priorFlags
= [];
459 $this->mFlags
= array_pop( $this->priorFlags
);
463 public function getFlag( $flag ) {
464 return !!( $this->mFlags
& $flag );
467 public function getProperty( $name ) {
471 public function getWikiID() {
472 if ( $this->mTablePrefix
) {
473 return "{$this->mDBname}-{$this->mTablePrefix}";
475 return $this->mDBname
;
480 * Return a path to the DBMS-specific SQL file if it exists,
481 * otherwise default SQL file
483 * @param string $filename
486 private function getSqlFilePath( $filename ) {
488 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
489 if ( file_exists( $dbmsSpecificFilePath ) ) {
490 return $dbmsSpecificFilePath;
492 return "$IP/maintenance/$filename";
497 * Return a path to the DBMS-specific schema file,
498 * otherwise default to tables.sql
502 public function getSchemaPath() {
503 return $this->getSqlFilePath( 'tables.sql' );
507 * Return a path to the DBMS-specific update key file,
508 * otherwise default to update-keys.sql
512 public function getUpdateKeysPath() {
513 return $this->getSqlFilePath( 'update-keys.sql' );
517 * Get information about an index into an object
518 * @param string $table Table name
519 * @param string $index Index name
520 * @param string $fname Calling function name
521 * @return mixed Database-specific index description class or false if the index does not exist
523 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
526 * Wrapper for addslashes()
528 * @param string $s String to be slashed.
529 * @return string Slashed string.
531 abstract function strencode( $s );
536 * FIXME: It is possible to construct a Database object with no associated
537 * connection object, by specifying no parameters to __construct(). This
538 * feature is deprecated and should be removed.
540 * DatabaseBase subclasses should not be constructed directly in external
541 * code. DatabaseBase::factory() should be used instead.
543 * @param array $params Parameters passed from DatabaseBase::factory()
545 function __construct( array $params ) {
546 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
548 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
550 $server = $params['host'];
551 $user = $params['user'];
552 $password = $params['password'];
553 $dbName = $params['dbname'];
554 $flags = $params['flags'];
555 $tablePrefix = $params['tablePrefix'];
556 $schema = $params['schema'];
557 $foreign = $params['foreign'];
559 $this->mFlags
= $flags;
560 if ( $this->mFlags
& DBO_DEFAULT
) {
561 if ( $wgCommandLineMode ) {
562 $this->mFlags
&= ~DBO_TRX
;
564 $this->mFlags |
= DBO_TRX
;
568 $this->mSessionVars
= $params['variables'];
570 /** Get the default table prefix*/
571 if ( $tablePrefix === 'get from global' ) {
572 $this->mTablePrefix
= $wgDBprefix;
574 $this->mTablePrefix
= $tablePrefix;
577 /** Get the database schema*/
578 if ( $schema === 'get from global' ) {
579 $this->mSchema
= $wgDBmwschema;
581 $this->mSchema
= $schema;
584 $this->mForeign
= $foreign;
586 if ( isset( $params['trxProfiler'] ) ) {
587 $this->trxProfiler
= $params['trxProfiler']; // override
591 $this->open( $server, $user, $password, $dbName );
596 * Called by serialize. Throw an exception when DB connection is serialized.
597 * This causes problems on some database engines because the connection is
598 * not restored on unserialize.
600 public function __sleep() {
601 throw new MWException( 'Database serialization may cause problems, since ' .
602 'the connection is not restored on wakeup.' );
606 * Given a DB type, construct the name of the appropriate child class of
607 * DatabaseBase. This is designed to replace all of the manual stuff like:
608 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
609 * as well as validate against the canonical list of DB types we have
611 * This factory function is mostly useful for when you need to connect to a
612 * database other than the MediaWiki default (such as for external auth,
613 * an extension, et cetera). Do not use this to connect to the MediaWiki
614 * database. Example uses in core:
615 * @see LoadBalancer::reallyOpenConnection()
616 * @see ForeignDBRepo::getMasterDB()
617 * @see WebInstallerDBConnect::execute()
621 * @param string $dbType A possible DB type
622 * @param array $p An array of options to pass to the constructor.
623 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
624 * @throws MWException If the database driver or extension cannot be found
625 * @return DatabaseBase|null DatabaseBase subclass or null
627 final public static function factory( $dbType, $p = [] ) {
628 $canonicalDBTypes = [
629 'mysql' => [ 'mysqli', 'mysql' ],
637 $dbType = strtolower( $dbType );
638 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
639 $possibleDrivers = $canonicalDBTypes[$dbType];
640 if ( !empty( $p['driver'] ) ) {
641 if ( in_array( $p['driver'], $possibleDrivers ) ) {
642 $driver = $p['driver'];
644 throw new MWException( __METHOD__
.
645 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
648 foreach ( $possibleDrivers as $posDriver ) {
649 if ( extension_loaded( $posDriver ) ) {
650 $driver = $posDriver;
658 if ( $driver === false ) {
659 throw new MWException( __METHOD__
.
660 " no viable database extension found for type '$dbType'" );
663 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
664 // and everything else doesn't use a schema (e.g. null)
665 // Although postgres and oracle support schemas, we don't use them (yet)
666 // to maintain backwards compatibility
668 'mssql' => 'get from global',
671 $class = 'Database' . ucfirst( $driver );
672 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
673 // Resolve some defaults for b/c
674 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
675 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
676 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
677 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
678 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
679 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
680 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
681 if ( !isset( $p['schema'] ) ) {
682 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
684 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
686 return new $class( $p );
692 protected function installErrorHandler() {
693 $this->mPHPError
= false;
694 $this->htmlErrors
= ini_set( 'html_errors', '0' );
695 set_error_handler( [ $this, 'connectionErrorHandler' ] );
699 * @return bool|string
701 protected function restoreErrorHandler() {
702 restore_error_handler();
703 if ( $this->htmlErrors
!== false ) {
704 ini_set( 'html_errors', $this->htmlErrors
);
706 if ( $this->mPHPError
) {
707 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
708 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
718 * @param string $errstr
720 public function connectionErrorHandler( $errno, $errstr ) {
721 $this->mPHPError
= $errstr;
725 * Create a log context to pass to wfLogDBError or other logging functions.
727 * @param array $extras Additional data to add to context
730 protected function getLogContext( array $extras = [] ) {
733 'db_server' => $this->mServer
,
734 'db_name' => $this->mDBname
,
735 'db_user' => $this->mUser
,
741 public function close() {
742 if ( $this->mConn
) {
743 if ( $this->trxLevel() ) {
744 if ( !$this->mTrxAutomatic
) {
745 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
746 " performing implicit commit before closing connection!" );
749 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
752 $closed = $this->closeConnection();
753 $this->mConn
= false;
754 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
755 throw new MWException( "Transaction callbacks still pending." );
759 $this->mOpened
= false;
765 * Make sure isOpen() returns true as a sanity check
767 * @throws DBUnexpectedError
769 protected function assertOpen() {
770 if ( !$this->isOpen() ) {
771 throw new DBUnexpectedError( $this, "DB connection was already closed." );
776 * Closes underlying database connection
778 * @return bool Whether connection was closed successfully
780 abstract protected function closeConnection();
782 function reportConnectionError( $error = 'Unknown error' ) {
783 $myError = $this->lastError();
789 throw new DBConnectionError( $this, $error );
793 * The DBMS-dependent part of query()
795 * @param string $sql SQL query.
796 * @return ResultWrapper|bool Result object to feed to fetchObject,
797 * fetchRow, ...; or false on failure
799 abstract protected function doQuery( $sql );
802 * Determine whether a query writes to the DB.
803 * Should return true if unsure.
808 protected function isWriteQuery( $sql ) {
809 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
813 * Determine whether a SQL statement is sensitive to isolation level.
814 * A SQL statement is considered transactable if its result could vary
815 * depending on the transaction isolation level. Operational commands
816 * such as 'SET' and 'SHOW' are not considered to be transactable.
821 protected function isTransactableQuery( $sql ) {
822 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
823 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ] );
826 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
829 $priorWritesPending = $this->writesOrCallbacksPending();
830 $this->mLastQuery
= $sql;
832 $isWrite = $this->isWriteQuery( $sql );
834 $reason = $this->getReadOnlyReason();
835 if ( $reason !== false ) {
836 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
838 # Set a flag indicating that writes have been done
839 $this->mDoneWrites
= microtime( true );
842 # Add a comment for easy SHOW PROCESSLIST interpretation
843 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
844 $userName = $wgUser->getName();
845 if ( mb_strlen( $userName ) > 15 ) {
846 $userName = mb_substr( $userName, 0, 15 ) . '...';
848 $userName = str_replace( '/', '', $userName );
853 // Add trace comment to the begin of the sql string, right after the operator.
854 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
855 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
857 # Start implicit transactions that wrap the request if DBO_TRX is enabled
858 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
859 && $this->isTransactableQuery( $sql )
861 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
862 $this->mTrxAutomatic
= true;
865 # Keep track of whether the transaction has write queries pending
866 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
867 $this->mTrxDoneWrites
= true;
868 $this->getTransactionProfiler()->transactionWritingIn(
869 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
872 if ( $this->debug() ) {
873 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
876 # Avoid fatals if close() was called
879 # Send the query to the server
880 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
882 # Try reconnecting if the connection was lost
883 if ( false === $ret && $this->wasErrorReissuable() ) {
884 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
885 # Stash the last error values before anything might clear them
886 $lastError = $this->lastError();
887 $lastErrno = $this->lastErrno();
888 # Update state tracking to reflect transaction loss due to disconnection
889 $this->handleTransactionLoss();
890 wfDebug( "Connection lost, reconnecting...\n" );
891 if ( $this->reconnect() ) {
892 wfDebug( "Reconnected\n" );
893 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
894 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
896 if ( !$recoverable ) {
897 # Callers may catch the exception and continue to use the DB
898 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
900 # Should be safe to silently retry the query
901 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
904 wfDebug( "Failed\n" );
908 if ( false === $ret ) {
909 # Deadlocks cause the entire transaction to abort, not just the statement.
910 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
911 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
912 if ( $this->wasDeadlock() ) {
913 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
914 $tempIgnore = false; // not recoverable
916 # Update state tracking to reflect transaction loss
917 $this->handleTransactionLoss();
920 $this->reportQueryError(
921 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
924 $res = $this->resultObject( $ret );
929 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
930 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
931 # generalizeSQL() will probably cut down the query to reasonable
932 # logging size most of the time. The substr is really just a sanity check.
934 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
936 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
939 # Include query transaction state
940 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
942 $profiler = Profiler
::instance();
943 if ( !( $profiler instanceof ProfilerStub
) ) {
944 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
947 $startTime = microtime( true );
948 $ret = $this->doQuery( $commentedSql );
949 $queryRuntime = microtime( true ) - $startTime;
951 unset( $queryProfSection ); // profile out (if set)
953 if ( $ret !== false ) {
954 $this->lastPing
= $startTime;
955 if ( $isWrite && $this->mTrxLevel
) {
956 $this->mTrxWriteDuration +
= $queryRuntime;
957 $this->mTrxWriteCallers
[] = $fname;
961 $this->getTransactionProfiler()->recordQueryCompletion(
962 $queryProf, $startTime, $isWrite, $this->affectedRows()
964 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
969 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
970 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
971 # Dropped connections also mean that named locks are automatically released.
972 # Only allow error suppression in autocommit mode or when the lost transaction
973 # didn't matter anyway (aside from DBO_TRX snapshot loss).
974 if ( $this->mNamedLocksHeld
) {
975 return false; // possible critical section violation
976 } elseif ( $sql === 'COMMIT' ) {
977 return !$priorWritesPending; // nothing written anyway? (T127428)
978 } elseif ( $sql === 'ROLLBACK' ) {
979 return true; // transaction lost...which is also what was requested :)
980 } elseif ( $this->explicitTrxActive() ) {
981 return false; // don't drop atomocity
982 } elseif ( $priorWritesPending ) {
983 return false; // prior writes lost from implicit transaction
989 private function handleTransactionLoss() {
990 $this->mTrxLevel
= 0;
991 $this->mTrxIdleCallbacks
= []; // bug 65263
992 $this->mTrxPreCommitCallbacks
= []; // bug 65263
994 // Handle callbacks in mTrxEndCallbacks
995 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
997 } catch ( Exception
$e ) {
998 // Already logged; move on...
1003 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1004 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1005 wfDebug( "SQL ERROR (ignored): $error\n" );
1007 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1009 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1010 $this->getLogContext( [
1011 'method' => __METHOD__
,
1014 'sql1line' => $sql1line,
1018 wfDebug( "SQL ERROR: " . $error . "\n" );
1019 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1024 * Intended to be compatible with the PEAR::DB wrapper functions.
1025 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1027 * ? = scalar value, quoted as necessary
1028 * ! = raw SQL bit (a function for instance)
1029 * & = filename; reads the file and inserts as a blob
1030 * (we don't use this though...)
1032 * @param string $sql
1033 * @param string $func
1037 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1038 /* MySQL doesn't support prepared statements (yet), so just
1039 * pack up the query for reference. We'll manually replace
1042 return [ 'query' => $sql, 'func' => $func ];
1046 * Free a prepared query, generated by prepare().
1047 * @param string $prepared
1049 protected function freePrepared( $prepared ) {
1050 /* No-op by default */
1054 * Execute a prepared query with the various arguments
1055 * @param string $prepared The prepared sql
1056 * @param mixed $args Either an array here, or put scalars as varargs
1058 * @return ResultWrapper
1060 public function execute( $prepared, $args = null ) {
1061 if ( !is_array( $args ) ) {
1063 $args = func_get_args();
1064 array_shift( $args );
1067 $sql = $this->fillPrepared( $prepared['query'], $args );
1069 return $this->query( $sql, $prepared['func'] );
1073 * For faking prepared SQL statements on DBs that don't support it directly.
1075 * @param string $preparedQuery A 'preparable' SQL statement
1076 * @param array $args Array of Arguments to fill it with
1077 * @return string Executable SQL
1079 public function fillPrepared( $preparedQuery, $args ) {
1081 $this->preparedArgs
=& $args;
1083 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1084 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1088 * preg_callback func for fillPrepared()
1089 * The arguments should be in $this->preparedArgs and must not be touched
1090 * while we're doing this.
1092 * @param array $matches
1093 * @throws DBUnexpectedError
1096 protected function fillPreparedArg( $matches ) {
1097 switch ( $matches[1] ) {
1106 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1108 switch ( $matches[1] ) {
1110 return $this->addQuotes( $arg );
1114 # return $this->addQuotes( file_get_contents( $arg ) );
1115 throw new DBUnexpectedError(
1117 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1120 throw new DBUnexpectedError(
1122 'Received invalid match. This should never happen!'
1127 public function freeResult( $res ) {
1130 public function selectField(
1131 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1133 if ( $var === '*' ) { // sanity
1134 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1137 if ( !is_array( $options ) ) {
1138 $options = [ $options ];
1141 $options['LIMIT'] = 1;
1143 $res = $this->select( $table, $var, $cond, $fname, $options );
1144 if ( $res === false ||
!$this->numRows( $res ) ) {
1148 $row = $this->fetchRow( $res );
1150 if ( $row !== false ) {
1151 return reset( $row );
1157 public function selectFieldValues(
1158 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1160 if ( $var === '*' ) { // sanity
1161 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1162 } elseif ( !is_string( $var ) ) { // sanity
1163 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1166 if ( !is_array( $options ) ) {
1167 $options = [ $options ];
1170 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1171 if ( $res === false ) {
1176 foreach ( $res as $row ) {
1177 $values[] = $row->$var;
1184 * Returns an optional USE INDEX clause to go after the table, and a
1185 * string to go at the end of the query.
1187 * @param array $options Associative array of options to be turned into
1188 * an SQL query, valid keys are listed in the function.
1190 * @see DatabaseBase::select()
1192 public function makeSelectOptions( $options ) {
1193 $preLimitTail = $postLimitTail = '';
1198 foreach ( $options as $key => $option ) {
1199 if ( is_numeric( $key ) ) {
1200 $noKeyOptions[$option] = true;
1204 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1206 $preLimitTail .= $this->makeOrderBy( $options );
1208 // if (isset($options['LIMIT'])) {
1209 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1210 // isset($options['OFFSET']) ? $options['OFFSET']
1214 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1215 $postLimitTail .= ' FOR UPDATE';
1218 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1219 $postLimitTail .= ' LOCK IN SHARE MODE';
1222 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1223 $startOpts .= 'DISTINCT';
1226 # Various MySQL extensions
1227 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1228 $startOpts .= ' /*! STRAIGHT_JOIN */';
1231 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1232 $startOpts .= ' HIGH_PRIORITY';
1235 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1236 $startOpts .= ' SQL_BIG_RESULT';
1239 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1240 $startOpts .= ' SQL_BUFFER_RESULT';
1243 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1244 $startOpts .= ' SQL_SMALL_RESULT';
1247 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1248 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1251 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1252 $startOpts .= ' SQL_CACHE';
1255 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1256 $startOpts .= ' SQL_NO_CACHE';
1259 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1260 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1265 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1269 * Returns an optional GROUP BY with an optional HAVING
1271 * @param array $options Associative array of options
1273 * @see DatabaseBase::select()
1276 public function makeGroupByWithHaving( $options ) {
1278 if ( isset( $options['GROUP BY'] ) ) {
1279 $gb = is_array( $options['GROUP BY'] )
1280 ?
implode( ',', $options['GROUP BY'] )
1281 : $options['GROUP BY'];
1282 $sql .= ' GROUP BY ' . $gb;
1284 if ( isset( $options['HAVING'] ) ) {
1285 $having = is_array( $options['HAVING'] )
1286 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1287 : $options['HAVING'];
1288 $sql .= ' HAVING ' . $having;
1295 * Returns an optional ORDER BY
1297 * @param array $options Associative array of options
1299 * @see DatabaseBase::select()
1302 public function makeOrderBy( $options ) {
1303 if ( isset( $options['ORDER BY'] ) ) {
1304 $ob = is_array( $options['ORDER BY'] )
1305 ?
implode( ',', $options['ORDER BY'] )
1306 : $options['ORDER BY'];
1308 return ' ORDER BY ' . $ob;
1314 // See IDatabase::select for the docs for this function
1315 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1316 $options = [], $join_conds = [] ) {
1317 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1319 return $this->query( $sql, $fname );
1322 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1323 $options = [], $join_conds = []
1325 if ( is_array( $vars ) ) {
1326 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1329 $options = (array)$options;
1330 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1331 ?
$options['USE INDEX']
1334 if ( is_array( $table ) ) {
1336 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1337 } elseif ( $table != '' ) {
1338 if ( $table[0] == ' ' ) {
1339 $from = ' FROM ' . $table;
1342 $this->tableNamesWithUseIndexOrJOIN( [ $table ], $useIndexes, [] );
1348 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1349 $this->makeSelectOptions( $options );
1351 if ( !empty( $conds ) ) {
1352 if ( is_array( $conds ) ) {
1353 $conds = $this->makeList( $conds, LIST_AND
);
1355 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1357 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1360 if ( isset( $options['LIMIT'] ) ) {
1361 $sql = $this->limitResult( $sql, $options['LIMIT'],
1362 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1364 $sql = "$sql $postLimitTail";
1366 if ( isset( $options['EXPLAIN'] ) ) {
1367 $sql = 'EXPLAIN ' . $sql;
1373 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1374 $options = [], $join_conds = []
1376 $options = (array)$options;
1377 $options['LIMIT'] = 1;
1378 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1380 if ( $res === false ) {
1384 if ( !$this->numRows( $res ) ) {
1388 $obj = $this->fetchObject( $res );
1393 public function estimateRowCount(
1394 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1397 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1400 $row = $this->fetchRow( $res );
1401 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1407 public function selectRowCount(
1408 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1411 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1412 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1415 $row = $this->fetchRow( $res );
1416 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1423 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1424 * It's only slightly flawed. Don't use for anything important.
1426 * @param string $sql A SQL Query
1430 protected static function generalizeSQL( $sql ) {
1431 # This does the same as the regexp below would do, but in such a way
1432 # as to avoid crashing php on some large strings.
1433 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1435 $sql = str_replace( "\\\\", '', $sql );
1436 $sql = str_replace( "\\'", '', $sql );
1437 $sql = str_replace( "\\\"", '', $sql );
1438 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1439 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1441 # All newlines, tabs, etc replaced by single space
1442 $sql = preg_replace( '/\s+/', ' ', $sql );
1445 # except the ones surrounded by characters, e.g. l10n
1446 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1447 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1452 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1453 $info = $this->fieldInfo( $table, $field );
1458 public function indexExists( $table, $index, $fname = __METHOD__
) {
1459 if ( !$this->tableExists( $table ) ) {
1463 $info = $this->indexInfo( $table, $index, $fname );
1464 if ( is_null( $info ) ) {
1467 return $info !== false;
1471 public function tableExists( $table, $fname = __METHOD__
) {
1472 $table = $this->tableName( $table );
1473 $old = $this->ignoreErrors( true );
1474 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1475 $this->ignoreErrors( $old );
1480 public function indexUnique( $table, $index ) {
1481 $indexInfo = $this->indexInfo( $table, $index );
1483 if ( !$indexInfo ) {
1487 return !$indexInfo[0]->Non_unique
;
1491 * Helper for DatabaseBase::insert().
1493 * @param array $options
1496 protected function makeInsertOptions( $options ) {
1497 return implode( ' ', $options );
1500 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1501 # No rows to insert, easy just return now
1502 if ( !count( $a ) ) {
1506 $table = $this->tableName( $table );
1508 if ( !is_array( $options ) ) {
1509 $options = [ $options ];
1513 if ( isset( $options['fileHandle'] ) ) {
1514 $fh = $options['fileHandle'];
1516 $options = $this->makeInsertOptions( $options );
1518 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1520 $keys = array_keys( $a[0] );
1523 $keys = array_keys( $a );
1526 $sql = 'INSERT ' . $options .
1527 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1531 foreach ( $a as $row ) {
1537 $sql .= '(' . $this->makeList( $row ) . ')';
1540 $sql .= '(' . $this->makeList( $a ) . ')';
1543 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1545 } elseif ( $fh !== null ) {
1549 return (bool)$this->query( $sql, $fname );
1553 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1555 * @param array $options
1558 protected function makeUpdateOptionsArray( $options ) {
1559 if ( !is_array( $options ) ) {
1560 $options = [ $options ];
1565 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1566 $opts[] = $this->lowPriorityOption();
1569 if ( in_array( 'IGNORE', $options ) ) {
1577 * Make UPDATE options for the DatabaseBase::update function
1579 * @param array $options The options passed to DatabaseBase::update
1582 protected function makeUpdateOptions( $options ) {
1583 $opts = $this->makeUpdateOptionsArray( $options );
1585 return implode( ' ', $opts );
1588 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1589 $table = $this->tableName( $table );
1590 $opts = $this->makeUpdateOptions( $options );
1591 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1593 if ( $conds !== [] && $conds !== '*' ) {
1594 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1597 return $this->query( $sql, $fname );
1600 public function makeList( $a, $mode = LIST_COMMA
) {
1601 if ( !is_array( $a ) ) {
1602 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1608 foreach ( $a as $field => $value ) {
1610 if ( $mode == LIST_AND
) {
1612 } elseif ( $mode == LIST_OR
) {
1621 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1622 $list .= "($value)";
1623 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1625 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1626 // Remove null from array to be handled separately if found
1627 $includeNull = false;
1628 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1629 $includeNull = true;
1630 unset( $value[$nullKey] );
1632 if ( count( $value ) == 0 && !$includeNull ) {
1633 throw new MWException( __METHOD__
. ": empty input for field $field" );
1634 } elseif ( count( $value ) == 0 ) {
1635 // only check if $field is null
1636 $list .= "$field IS NULL";
1638 // IN clause contains at least one valid element
1639 if ( $includeNull ) {
1640 // Group subconditions to ensure correct precedence
1643 if ( count( $value ) == 1 ) {
1644 // Special-case single values, as IN isn't terribly efficient
1645 // Don't necessarily assume the single key is 0; we don't
1646 // enforce linear numeric ordering on other arrays here.
1647 $value = array_values( $value )[0];
1648 $list .= $field . " = " . $this->addQuotes( $value );
1650 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1652 // if null present in array, append IS NULL
1653 if ( $includeNull ) {
1654 $list .= " OR $field IS NULL)";
1657 } elseif ( $value === null ) {
1658 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1659 $list .= "$field IS ";
1660 } elseif ( $mode == LIST_SET
) {
1661 $list .= "$field = ";
1665 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1666 $list .= "$field = ";
1668 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1675 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1678 foreach ( $data as $base => $sub ) {
1679 if ( count( $sub ) ) {
1680 $conds[] = $this->makeList(
1681 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1687 return $this->makeList( $conds, LIST_OR
);
1689 // Nothing to search for...
1695 * Return aggregated value alias
1697 * @param array $valuedata
1698 * @param string $valuename
1702 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1706 public function bitNot( $field ) {
1710 public function bitAnd( $fieldLeft, $fieldRight ) {
1711 return "($fieldLeft & $fieldRight)";
1714 public function bitOr( $fieldLeft, $fieldRight ) {
1715 return "($fieldLeft | $fieldRight)";
1718 public function buildConcat( $stringList ) {
1719 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1722 public function buildGroupConcatField(
1723 $delim, $table, $field, $conds = '', $join_conds = []
1725 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1727 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1730 public function selectDB( $db ) {
1731 # Stub. Shouldn't cause serious problems if it's not overridden, but
1732 # if your database engine supports a concept similar to MySQL's
1733 # databases you may as well.
1734 $this->mDBname
= $db;
1739 public function getDBname() {
1740 return $this->mDBname
;
1743 public function getServer() {
1744 return $this->mServer
;
1748 * Format a table name ready for use in constructing an SQL query
1750 * This does two important things: it quotes the table names to clean them up,
1751 * and it adds a table prefix if only given a table name with no quotes.
1753 * All functions of this object which require a table name call this function
1754 * themselves. Pass the canonical name to such functions. This is only needed
1755 * when calling query() directly.
1757 * @note This function does not sanitize user input. It is not safe to use
1758 * this function to escape user input.
1759 * @param string $name Database table name
1760 * @param string $format One of:
1761 * quoted - Automatically pass the table name through addIdentifierQuotes()
1762 * so that it can be used in a query.
1763 * raw - Do not add identifier quotes to the table name
1764 * @return string Full database name
1766 public function tableName( $name, $format = 'quoted' ) {
1767 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1768 # Skip the entire process when we have a string quoted on both ends.
1769 # Note that we check the end so that we will still quote any use of
1770 # use of `database`.table. But won't break things if someone wants
1771 # to query a database table with a dot in the name.
1772 if ( $this->isQuotedIdentifier( $name ) ) {
1776 # Lets test for any bits of text that should never show up in a table
1777 # name. Basically anything like JOIN or ON which are actually part of
1778 # SQL queries, but may end up inside of the table value to combine
1779 # sql. Such as how the API is doing.
1780 # Note that we use a whitespace test rather than a \b test to avoid
1781 # any remote case where a word like on may be inside of a table name
1782 # surrounded by symbols which may be considered word breaks.
1783 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1787 # Split database and table into proper variables.
1788 # We reverse the explode so that database.table and table both output
1789 # the correct table.
1790 $dbDetails = explode( '.', $name, 3 );
1791 if ( count( $dbDetails ) == 3 ) {
1792 list( $database, $schema, $table ) = $dbDetails;
1793 # We don't want any prefix added in this case
1795 } elseif ( count( $dbDetails ) == 2 ) {
1796 list( $database, $table ) = $dbDetails;
1797 # We don't want any prefix added in this case
1798 # In dbs that support it, $database may actually be the schema
1799 # but that doesn't affect any of the functionality here
1803 list( $table ) = $dbDetails;
1804 if ( $wgSharedDB !== null # We have a shared database
1805 && $this->mForeign
== false # We're not working on a foreign database
1806 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1807 && in_array( $table, $wgSharedTables ) # A shared table is selected
1809 $database = $wgSharedDB;
1810 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1811 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1814 $schema = $this->mSchema
; # Default schema
1815 $prefix = $this->mTablePrefix
; # Default prefix
1819 # Quote $table and apply the prefix if not quoted.
1820 # $tableName might be empty if this is called from Database::replaceVars()
1821 $tableName = "{$prefix}{$table}";
1822 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1823 $tableName = $this->addIdentifierQuotes( $tableName );
1826 # Quote $schema and merge it with the table name if needed
1827 if ( strlen( $schema ) ) {
1828 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1829 $schema = $this->addIdentifierQuotes( $schema );
1831 $tableName = $schema . '.' . $tableName;
1834 # Quote $database and merge it with the table name if needed
1835 if ( $database !== null ) {
1836 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1837 $database = $this->addIdentifierQuotes( $database );
1839 $tableName = $database . '.' . $tableName;
1846 * Fetch a number of table names into an array
1847 * This is handy when you need to construct SQL for joins
1850 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1851 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1852 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1856 public function tableNames() {
1857 $inArray = func_get_args();
1860 foreach ( $inArray as $name ) {
1861 $retVal[$name] = $this->tableName( $name );
1868 * Fetch a number of table names into an zero-indexed numerical array
1869 * This is handy when you need to construct SQL for joins
1872 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1873 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1874 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1878 public function tableNamesN() {
1879 $inArray = func_get_args();
1882 foreach ( $inArray as $name ) {
1883 $retVal[] = $this->tableName( $name );
1890 * Get an aliased table name
1891 * e.g. tableName AS newTableName
1893 * @param string $name Table name, see tableName()
1894 * @param string|bool $alias Alias (optional)
1895 * @return string SQL name for aliased table. Will not alias a table to its own name
1897 public function tableNameWithAlias( $name, $alias = false ) {
1898 if ( !$alias ||
$alias == $name ) {
1899 return $this->tableName( $name );
1901 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1906 * Gets an array of aliased table names
1908 * @param array $tables [ [alias] => table ]
1909 * @return string[] See tableNameWithAlias()
1911 public function tableNamesWithAlias( $tables ) {
1913 foreach ( $tables as $alias => $table ) {
1914 if ( is_numeric( $alias ) ) {
1917 $retval[] = $this->tableNameWithAlias( $table, $alias );
1924 * Get an aliased field name
1925 * e.g. fieldName AS newFieldName
1927 * @param string $name Field name
1928 * @param string|bool $alias Alias (optional)
1929 * @return string SQL name for aliased field. Will not alias a field to its own name
1931 public function fieldNameWithAlias( $name, $alias = false ) {
1932 if ( !$alias ||
(string)$alias === (string)$name ) {
1935 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1940 * Gets an array of aliased field names
1942 * @param array $fields [ [alias] => field ]
1943 * @return string[] See fieldNameWithAlias()
1945 public function fieldNamesWithAlias( $fields ) {
1947 foreach ( $fields as $alias => $field ) {
1948 if ( is_numeric( $alias ) ) {
1951 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1958 * Get the aliased table name clause for a FROM clause
1959 * which might have a JOIN and/or USE INDEX clause
1961 * @param array $tables ( [alias] => table )
1962 * @param array $use_index Same as for select()
1963 * @param array $join_conds Same as for select()
1966 protected function tableNamesWithUseIndexOrJOIN(
1967 $tables, $use_index = [], $join_conds = []
1971 $use_index = (array)$use_index;
1972 $join_conds = (array)$join_conds;
1974 foreach ( $tables as $alias => $table ) {
1975 if ( !is_string( $alias ) ) {
1976 // No alias? Set it equal to the table name
1979 // Is there a JOIN clause for this table?
1980 if ( isset( $join_conds[$alias] ) ) {
1981 list( $joinType, $conds ) = $join_conds[$alias];
1982 $tableClause = $joinType;
1983 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1984 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1985 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1987 $tableClause .= ' ' . $use;
1990 $on = $this->makeList( (array)$conds, LIST_AND
);
1992 $tableClause .= ' ON (' . $on . ')';
1995 $retJOIN[] = $tableClause;
1996 } elseif ( isset( $use_index[$alias] ) ) {
1997 // Is there an INDEX clause for this table?
1998 $tableClause = $this->tableNameWithAlias( $table, $alias );
1999 $tableClause .= ' ' . $this->useIndexClause(
2000 implode( ',', (array)$use_index[$alias] )
2003 $ret[] = $tableClause;
2005 $tableClause = $this->tableNameWithAlias( $table, $alias );
2007 $ret[] = $tableClause;
2011 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2012 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2013 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2015 // Compile our final table clause
2016 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2020 * Get the name of an index in a given table.
2022 * @param string $index
2025 protected function indexName( $index ) {
2026 // Backwards-compatibility hack
2028 'ar_usertext_timestamp' => 'usertext_timestamp',
2029 'un_user_id' => 'user_id',
2030 'un_user_ip' => 'user_ip',
2033 if ( isset( $renamed[$index] ) ) {
2034 return $renamed[$index];
2040 public function addQuotes( $s ) {
2041 if ( $s instanceof Blob
) {
2044 if ( $s === null ) {
2047 # This will also quote numeric values. This should be harmless,
2048 # and protects against weird problems that occur when they really
2049 # _are_ strings such as article titles and string->number->string
2050 # conversion is not 1:1.
2051 return "'" . $this->strencode( $s ) . "'";
2056 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2057 * MySQL uses `backticks` while basically everything else uses double quotes.
2058 * Since MySQL is the odd one out here the double quotes are our generic
2059 * and we implement backticks in DatabaseMysql.
2064 public function addIdentifierQuotes( $s ) {
2065 return '"' . str_replace( '"', '""', $s ) . '"';
2069 * Returns if the given identifier looks quoted or not according to
2070 * the database convention for quoting identifiers .
2072 * @note Do not use this to determine if untrusted input is safe.
2073 * A malicious user can trick this function.
2074 * @param string $name
2077 public function isQuotedIdentifier( $name ) {
2078 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2085 protected function escapeLikeInternal( $s ) {
2086 return addcslashes( $s, '\%_' );
2089 public function buildLike() {
2090 $params = func_get_args();
2092 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2093 $params = $params[0];
2098 foreach ( $params as $value ) {
2099 if ( $value instanceof LikeMatch
) {
2100 $s .= $value->toString();
2102 $s .= $this->escapeLikeInternal( $value );
2106 return " LIKE {$this->addQuotes( $s )} ";
2109 public function anyChar() {
2110 return new LikeMatch( '_' );
2113 public function anyString() {
2114 return new LikeMatch( '%' );
2117 public function nextSequenceValue( $seqName ) {
2122 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2123 * is only needed because a) MySQL must be as efficient as possible due to
2124 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2125 * which index to pick. Anyway, other databases might have different
2126 * indexes on a given table. So don't bother overriding this unless you're
2128 * @param string $index
2131 public function useIndexClause( $index ) {
2135 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2136 $quotedTable = $this->tableName( $table );
2138 if ( count( $rows ) == 0 ) {
2143 if ( !is_array( reset( $rows ) ) ) {
2147 // @FXIME: this is not atomic, but a trx would break affectedRows()
2148 foreach ( $rows as $row ) {
2149 # Delete rows which collide
2150 if ( $uniqueIndexes ) {
2151 $sql = "DELETE FROM $quotedTable WHERE ";
2153 foreach ( $uniqueIndexes as $index ) {
2160 if ( is_array( $index ) ) {
2162 foreach ( $index as $col ) {
2168 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2171 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2175 $this->query( $sql, $fname );
2178 # Now insert the row
2179 $this->insert( $table, $row, $fname );
2184 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2187 * @param string $table Table name
2188 * @param array|string $rows Row(s) to insert
2189 * @param string $fname Caller function name
2191 * @return ResultWrapper
2193 protected function nativeReplace( $table, $rows, $fname ) {
2194 $table = $this->tableName( $table );
2197 if ( !is_array( reset( $rows ) ) ) {
2201 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2204 foreach ( $rows as $row ) {
2211 $sql .= '(' . $this->makeList( $row ) . ')';
2214 return $this->query( $sql, $fname );
2217 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2220 if ( !count( $rows ) ) {
2221 return true; // nothing to do
2224 if ( !is_array( reset( $rows ) ) ) {
2228 if ( count( $uniqueIndexes ) ) {
2229 $clauses = []; // list WHERE clauses that each identify a single row
2230 foreach ( $rows as $row ) {
2231 foreach ( $uniqueIndexes as $index ) {
2232 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2233 $rowKey = []; // unique key to this row
2234 foreach ( $index as $column ) {
2235 $rowKey[$column] = $row[$column];
2237 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2240 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2245 $useTrx = !$this->mTrxLevel
;
2247 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2250 # Update any existing conflicting row(s)
2251 if ( $where !== false ) {
2252 $ok = $this->update( $table, $set, $where, $fname );
2256 # Now insert any non-conflicting row(s)
2257 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2258 } catch ( Exception
$e ) {
2260 $this->rollback( $fname );
2265 $this->commit( $fname, self
::TRANSACTION_INTERNAL
);
2271 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2275 throw new DBUnexpectedError( $this,
2276 'DatabaseBase::deleteJoin() called with empty $conds' );
2279 $delTable = $this->tableName( $delTable );
2280 $joinTable = $this->tableName( $joinTable );
2281 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2282 if ( $conds != '*' ) {
2283 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2287 $this->query( $sql, $fname );
2291 * Returns the size of a text field, or -1 for "unlimited"
2293 * @param string $table
2294 * @param string $field
2297 public function textFieldSize( $table, $field ) {
2298 $table = $this->tableName( $table );
2299 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2300 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2301 $row = $this->fetchObject( $res );
2305 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2315 * A string to insert into queries to show that they're low-priority, like
2316 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2317 * string and nothing bad should happen.
2319 * @return string Returns the text of the low priority option if it is
2320 * supported, or a blank string otherwise
2322 public function lowPriorityOption() {
2326 public function delete( $table, $conds, $fname = __METHOD__
) {
2328 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2331 $table = $this->tableName( $table );
2332 $sql = "DELETE FROM $table";
2334 if ( $conds != '*' ) {
2335 if ( is_array( $conds ) ) {
2336 $conds = $this->makeList( $conds, LIST_AND
);
2338 $sql .= ' WHERE ' . $conds;
2341 return $this->query( $sql, $fname );
2344 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2345 $fname = __METHOD__
,
2346 $insertOptions = [], $selectOptions = []
2348 $destTable = $this->tableName( $destTable );
2350 if ( !is_array( $insertOptions ) ) {
2351 $insertOptions = [ $insertOptions ];
2354 $insertOptions = $this->makeInsertOptions( $insertOptions );
2356 if ( !is_array( $selectOptions ) ) {
2357 $selectOptions = [ $selectOptions ];
2360 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2362 if ( is_array( $srcTable ) ) {
2363 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2365 $srcTable = $this->tableName( $srcTable );
2368 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2369 " SELECT $startOpts " . implode( ',', $varMap ) .
2370 " FROM $srcTable $useIndex ";
2372 if ( $conds != '*' ) {
2373 if ( is_array( $conds ) ) {
2374 $conds = $this->makeList( $conds, LIST_AND
);
2376 $sql .= " WHERE $conds";
2379 $sql .= " $tailOpts";
2381 return $this->query( $sql, $fname );
2385 * Construct a LIMIT query with optional offset. This is used for query
2386 * pages. The SQL should be adjusted so that only the first $limit rows
2387 * are returned. If $offset is provided as well, then the first $offset
2388 * rows should be discarded, and the next $limit rows should be returned.
2389 * If the result of the query is not ordered, then the rows to be returned
2390 * are theoretically arbitrary.
2392 * $sql is expected to be a SELECT, if that makes a difference.
2394 * The version provided by default works in MySQL and SQLite. It will very
2395 * likely need to be overridden for most other DBMSes.
2397 * @param string $sql SQL query we will append the limit too
2398 * @param int $limit The SQL limit
2399 * @param int|bool $offset The SQL offset (default false)
2400 * @throws DBUnexpectedError
2403 public function limitResult( $sql, $limit, $offset = false ) {
2404 if ( !is_numeric( $limit ) ) {
2405 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2408 return "$sql LIMIT "
2409 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2413 public function unionSupportsOrderAndLimit() {
2414 return true; // True for almost every DB supported
2417 public function unionQueries( $sqls, $all ) {
2418 $glue = $all ?
') UNION ALL (' : ') UNION (';
2420 return '(' . implode( $glue, $sqls ) . ')';
2423 public function conditional( $cond, $trueVal, $falseVal ) {
2424 if ( is_array( $cond ) ) {
2425 $cond = $this->makeList( $cond, LIST_AND
);
2428 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2431 public function strreplace( $orig, $old, $new ) {
2432 return "REPLACE({$orig}, {$old}, {$new})";
2435 public function getServerUptime() {
2439 public function wasDeadlock() {
2443 public function wasLockTimeout() {
2447 public function wasErrorReissuable() {
2451 public function wasReadOnlyError() {
2456 * Determines if the given query error was a connection drop
2459 * @param integer|string $errno
2462 public function wasConnectionError( $errno ) {
2467 * Perform a deadlock-prone transaction.
2469 * This function invokes a callback function to perform a set of write
2470 * queries. If a deadlock occurs during the processing, the transaction
2471 * will be rolled back and the callback function will be called again.
2473 * Avoid using this method outside of Job or Maintenance classes.
2476 * $dbw->deadlockLoop( callback, ... );
2478 * Extra arguments are passed through to the specified callback function.
2479 * This method requires that no transactions are already active to avoid
2480 * causing premature commits or exceptions.
2482 * Returns whatever the callback function returned on its successful,
2483 * iteration, or false on error, for example if the retry limit was
2487 * @throws DBUnexpectedError
2490 public function deadlockLoop() {
2491 $args = func_get_args();
2492 $function = array_shift( $args );
2493 $tries = self
::DEADLOCK_TRIES
;
2495 $this->begin( __METHOD__
);
2498 /** @var Exception $e */
2502 $retVal = call_user_func_array( $function, $args );
2504 } catch ( DBQueryError
$e ) {
2505 if ( $this->wasDeadlock() ) {
2506 // Retry after a randomized delay
2507 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2509 // Throw the error back up
2513 } while ( --$tries > 0 );
2515 if ( $tries <= 0 ) {
2516 // Too many deadlocks; give up
2517 $this->rollback( __METHOD__
);
2520 $this->commit( __METHOD__
);
2526 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2527 # Real waits are implemented in the subclass.
2531 public function getSlavePos() {
2536 public function getMasterPos() {
2541 public function serverIsReadOnly() {
2545 final public function onTransactionResolution( callable
$callback ) {
2546 if ( !$this->mTrxLevel
) {
2547 throw new DBUnexpectedError( $this, "No transaction is active." );
2549 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2552 final public function onTransactionIdle( callable
$callback ) {
2553 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2554 if ( !$this->mTrxLevel
) {
2555 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2559 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2560 if ( $this->mTrxLevel
) {
2561 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2563 // If no transaction is active, then make one for this callback
2564 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
2566 call_user_func( $callback );
2567 $this->commit( __METHOD__
);
2568 } catch ( Exception
$e ) {
2569 $this->rollback( __METHOD__
);
2576 * Whether to disable running of post-commit callbacks
2578 * This method should not be used outside of Database/LoadBalancer
2580 * @param bool $suppress
2583 final public function setPostCommitCallbackSupression( $suppress ) {
2584 $this->suppressPostCommitCallbacks
= $suppress;
2588 * Actually run and consume any "on transaction idle/resolution" callbacks.
2590 * This method should not be used outside of Database/LoadBalancer
2592 * @param integer $trigger IDatabase::TRIGGER_* constant
2596 public function runOnTransactionIdleCallbacks( $trigger ) {
2597 if ( $this->suppressPostCommitCallbacks
) {
2601 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2602 /** @var Exception $e */
2603 $e = null; // first exception
2604 do { // callbacks may add callbacks :)
2605 $callbacks = array_merge(
2606 $this->mTrxIdleCallbacks
,
2607 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2609 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2610 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2611 foreach ( $callbacks as $callback ) {
2613 list( $phpCallback ) = $callback;
2614 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2615 call_user_func_array( $phpCallback, [ $trigger ] );
2617 $this->setFlag( DBO_TRX
); // restore automatic begin()
2619 $this->clearFlag( DBO_TRX
); // restore auto-commit
2621 } catch ( Exception
$ex ) {
2622 MWExceptionHandler
::logException( $ex );
2624 // Some callbacks may use startAtomic/endAtomic, so make sure
2625 // their transactions are ended so other callbacks don't fail
2626 if ( $this->trxLevel() ) {
2627 $this->rollback( __METHOD__
);
2631 } while ( count( $this->mTrxIdleCallbacks
) );
2633 if ( $e instanceof Exception
) {
2634 throw $e; // re-throw any first exception
2639 * Actually run and consume any "on transaction pre-commit" callbacks.
2641 * This method should not be used outside of Database/LoadBalancer
2646 public function runOnTransactionPreCommitCallbacks() {
2647 $e = null; // first exception
2648 do { // callbacks may add callbacks :)
2649 $callbacks = $this->mTrxPreCommitCallbacks
;
2650 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2651 foreach ( $callbacks as $callback ) {
2653 list( $phpCallback ) = $callback;
2654 call_user_func( $phpCallback );
2655 } catch ( Exception
$ex ) {
2656 MWExceptionHandler
::logException( $ex );
2660 } while ( count( $this->mTrxPreCommitCallbacks
) );
2662 if ( $e instanceof Exception
) {
2663 throw $e; // re-throw any first exception
2667 final public function startAtomic( $fname = __METHOD__
) {
2668 if ( !$this->mTrxLevel
) {
2669 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2670 $this->mTrxAutomatic
= true;
2671 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2672 // in all changes being in one transaction to keep requests transactional.
2673 if ( !$this->getFlag( DBO_TRX
) ) {
2674 $this->mTrxAutomaticAtomic
= true;
2678 $this->mTrxAtomicLevels
[] = $fname;
2681 final public function endAtomic( $fname = __METHOD__
) {
2682 if ( !$this->mTrxLevel
) {
2683 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2685 if ( !$this->mTrxAtomicLevels ||
2686 array_pop( $this->mTrxAtomicLevels
) !== $fname
2688 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2691 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2692 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2696 final public function doAtomicSection( $fname, callable
$callback ) {
2697 $this->startAtomic( $fname );
2699 $res = call_user_func_array( $callback, [ $this, $fname ] );
2700 } catch ( Exception
$e ) {
2701 $this->rollback( $fname );
2704 $this->endAtomic( $fname );
2709 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2710 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2711 if ( $this->mTrxLevel
) {
2712 if ( $this->mTrxAtomicLevels
) {
2713 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2714 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2715 throw new DBUnexpectedError( $this, $msg );
2716 } elseif ( !$this->mTrxAutomatic
) {
2717 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2718 throw new DBUnexpectedError( $this, $msg );
2720 // @TODO: make this an exception at some point
2721 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2722 wfLogDBError( $msg );
2723 return; // join the main transaction set
2725 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2726 // @TODO: make this an exception at some point
2727 wfLogDBError( "$fname: Implicit transaction expected (DBO_TRX set)." );
2728 return; // let any writes be in the main transaction
2731 // Avoid fatals if close() was called
2732 $this->assertOpen();
2734 $this->doBegin( $fname );
2735 $this->mTrxTimestamp
= microtime( true );
2736 $this->mTrxFname
= $fname;
2737 $this->mTrxDoneWrites
= false;
2738 $this->mTrxAutomatic
= false;
2739 $this->mTrxAutomaticAtomic
= false;
2740 $this->mTrxAtomicLevels
= [];
2741 $this->mTrxShortId
= wfRandomString( 12 );
2742 $this->mTrxWriteDuration
= 0.0;
2743 $this->mTrxWriteCallers
= [];
2744 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2745 // Get an estimate of the slave lag before then, treating estimate staleness
2746 // as lag itself just to be safe
2747 $status = $this->getApproximateLagStatus();
2748 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2752 * Issues the BEGIN command to the database server.
2754 * @see DatabaseBase::begin()
2755 * @param string $fname
2757 protected function doBegin( $fname ) {
2758 $this->query( 'BEGIN', $fname );
2759 $this->mTrxLevel
= 1;
2762 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2763 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2764 // There are still atomic sections open. This cannot be ignored
2765 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2766 throw new DBUnexpectedError(
2768 "$fname: Got COMMIT while atomic sections $levels are still open."
2772 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2773 if ( !$this->mTrxLevel
) {
2774 return; // nothing to do
2775 } elseif ( !$this->mTrxAutomatic
) {
2776 throw new DBUnexpectedError(
2778 "$fname: Flushing an explicit transaction, getting out of sync."
2782 if ( !$this->mTrxLevel
) {
2783 wfWarn( "$fname: No transaction to commit, something got out of sync." );
2784 return; // nothing to do
2785 } elseif ( $this->mTrxAutomatic
) {
2786 // @TODO: make this an exception at some point
2787 wfLogDBError( "$fname: Explicit commit of implicit transaction." );
2788 return; // wait for the main transaction set commit round
2792 // Avoid fatals if close() was called
2793 $this->assertOpen();
2795 $this->runOnTransactionPreCommitCallbacks();
2796 $writeTime = $this->pendingWriteQueryDuration();
2797 $this->doCommit( $fname );
2798 if ( $this->mTrxDoneWrites
) {
2799 $this->mDoneWrites
= microtime( true );
2800 $this->getTransactionProfiler()->transactionWritingOut(
2801 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2804 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2808 * Issues the COMMIT command to the database server.
2810 * @see DatabaseBase::commit()
2811 * @param string $fname
2813 protected function doCommit( $fname ) {
2814 if ( $this->mTrxLevel
) {
2815 $this->query( 'COMMIT', $fname );
2816 $this->mTrxLevel
= 0;
2820 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2821 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2822 if ( !$this->mTrxLevel
) {
2823 return; // nothing to do
2826 if ( !$this->mTrxLevel
) {
2827 wfWarn( "$fname: No transaction to rollback, something got out of sync." );
2828 return; // nothing to do
2829 } elseif ( $this->getFlag( DBO_TRX
) ) {
2830 throw new DBUnexpectedError(
2832 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2837 // Avoid fatals if close() was called
2838 $this->assertOpen();
2840 $this->doRollback( $fname );
2841 $this->mTrxAtomicLevels
= [];
2842 if ( $this->mTrxDoneWrites
) {
2843 $this->getTransactionProfiler()->transactionWritingOut(
2844 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2847 $this->mTrxIdleCallbacks
= []; // clear
2848 $this->mTrxPreCommitCallbacks
= []; // clear
2849 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2853 * Issues the ROLLBACK command to the database server.
2855 * @see DatabaseBase::rollback()
2856 * @param string $fname
2858 protected function doRollback( $fname ) {
2859 if ( $this->mTrxLevel
) {
2860 # Disconnects cause rollback anyway, so ignore those errors
2861 $ignoreErrors = true;
2862 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2863 $this->mTrxLevel
= 0;
2867 public function explicitTrxActive() {
2868 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2872 * Creates a new table with structure copied from existing table
2873 * Note that unlike most database abstraction functions, this function does not
2874 * automatically append database prefix, because it works at a lower
2875 * abstraction level.
2876 * The table names passed to this function shall not be quoted (this
2877 * function calls addIdentifierQuotes when needed).
2879 * @param string $oldName Name of table whose structure should be copied
2880 * @param string $newName Name of table to be created
2881 * @param bool $temporary Whether the new table should be temporary
2882 * @param string $fname Calling function name
2883 * @throws MWException
2884 * @return bool True if operation was successful
2886 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2889 throw new MWException(
2890 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2893 function listTables( $prefix = null, $fname = __METHOD__
) {
2894 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2898 * Reset the views process cache set by listViews()
2901 final public function clearViewsCache() {
2902 $this->allViews
= null;
2906 * Lists all the VIEWs in the database
2908 * For caching purposes the list of all views should be stored in
2909 * $this->allViews. The process cache can be cleared with clearViewsCache()
2911 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2912 * @param string $fname Name of calling function
2913 * @throws MWException
2917 public function listViews( $prefix = null, $fname = __METHOD__
) {
2918 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2922 * Differentiates between a TABLE and a VIEW
2924 * @param string $name Name of the database-structure to test.
2925 * @throws MWException
2929 public function isView( $name ) {
2930 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2933 public function timestamp( $ts = 0 ) {
2934 return wfTimestamp( TS_MW
, $ts );
2937 public function timestampOrNull( $ts = null ) {
2938 if ( is_null( $ts ) ) {
2941 return $this->timestamp( $ts );
2946 * Take the result from a query, and wrap it in a ResultWrapper if
2947 * necessary. Boolean values are passed through as is, to indicate success
2948 * of write queries or failure.
2950 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2951 * resource, and it was necessary to call this function to convert it to
2952 * a wrapper. Nowadays, raw database objects are never exposed to external
2953 * callers, so this is unnecessary in external code.
2955 * @param bool|ResultWrapper|resource|object $result
2956 * @return bool|ResultWrapper
2958 protected function resultObject( $result ) {
2961 } elseif ( $result instanceof ResultWrapper
) {
2963 } elseif ( $result === true ) {
2964 // Successful write query
2967 return new ResultWrapper( $this, $result );
2971 public function ping() {
2972 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2976 $ignoreErrors = true;
2977 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2978 // This will reconnect if possible or return false if not
2979 $ok = (bool)$this->query( "SELECT 1 AS ping", __METHOD__
, $ignoreErrors );
2980 $this->restoreFlags( self
::RESTORE_PRIOR
);
2988 protected function reconnect() {
2989 $this->closeConnection();
2990 $this->mOpened
= false;
2991 $this->mConn
= false;
2993 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2994 $this->lastPing
= microtime( true );
2996 } catch ( DBConnectionError
$e ) {
3003 public function getSessionLagStatus() {
3004 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3008 * Get the slave lag when the current transaction started
3010 * This is useful when transactions might use snapshot isolation
3011 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3012 * is this lag plus transaction duration. If they don't, it is still
3013 * safe to be pessimistic. This returns null if there is no transaction.
3015 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3018 public function getTransactionLagStatus() {
3019 return $this->mTrxLevel
3020 ?
[ 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() ]
3025 * Get a slave lag estimate for this server
3027 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3030 public function getApproximateLagStatus() {
3032 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3033 'since' => microtime( true )
3038 * Merge the result of getSessionLagStatus() for several DBs
3039 * using the most pessimistic values to estimate the lag of
3040 * any data derived from them in combination
3042 * This is information is useful for caching modules
3044 * @see WANObjectCache::set()
3045 * @see WANObjectCache::getWithSetCallback()
3047 * @param IDatabase $db1
3048 * @param IDatabase ...
3049 * @return array Map of values:
3050 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3051 * - since: oldest UNIX timestamp of any of the DB lag estimates
3052 * - pending: whether any of the DBs have uncommitted changes
3055 public static function getCacheSetOptions( IDatabase
$db1 ) {
3056 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3057 foreach ( func_get_args() as $db ) {
3058 /** @var IDatabase $db */
3059 $status = $db->getSessionLagStatus();
3060 if ( $status['lag'] === false ) {
3061 $res['lag'] = false;
3062 } elseif ( $res['lag'] !== false ) {
3063 $res['lag'] = max( $res['lag'], $status['lag'] );
3065 $res['since'] = min( $res['since'], $status['since'] );
3066 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3072 public function getLag() {
3076 function maxListLen() {
3080 public function encodeBlob( $b ) {
3084 public function decodeBlob( $b ) {
3085 if ( $b instanceof Blob
) {
3091 public function setSessionOptions( array $options ) {
3095 * Read and execute SQL commands from a file.
3097 * Returns true on success, error string or exception on failure (depending
3098 * on object's error ignore settings).
3100 * @param string $filename File name to open
3101 * @param bool|callable $lineCallback Optional function called before reading each line
3102 * @param bool|callable $resultCallback Optional function called for each MySQL result
3103 * @param bool|string $fname Calling function name or false if name should be
3104 * generated dynamically using $filename
3105 * @param bool|callable $inputCallback Optional function called for each
3106 * complete line sent
3107 * @throws Exception|MWException
3108 * @return bool|string
3110 public function sourceFile(
3111 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3113 MediaWiki\
suppressWarnings();
3114 $fp = fopen( $filename, 'r' );
3115 MediaWiki\restoreWarnings
();
3117 if ( false === $fp ) {
3118 throw new MWException( "Could not open \"{$filename}\".\n" );
3122 $fname = __METHOD__
. "( $filename )";
3126 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3127 } catch ( Exception
$e ) {
3138 * Get the full path of a patch file. Originally based on archive()
3139 * from updaters.inc. Keep in mind this always returns a patch, as
3140 * it fails back to MySQL if no DB-specific patch can be found
3142 * @param string $patch The name of the patch, like patch-something.sql
3143 * @return string Full path to patch file
3145 public function patchPath( $patch ) {
3148 $dbType = $this->getType();
3149 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3150 return "$IP/maintenance/$dbType/archives/$patch";
3152 return "$IP/maintenance/archives/$patch";
3156 public function setSchemaVars( $vars ) {
3157 $this->mSchemaVars
= $vars;
3161 * Read and execute commands from an open file handle.
3163 * Returns true on success, error string or exception on failure (depending
3164 * on object's error ignore settings).
3166 * @param resource $fp File handle
3167 * @param bool|callable $lineCallback Optional function called before reading each query
3168 * @param bool|callable $resultCallback Optional function called for each MySQL result
3169 * @param string $fname Calling function name
3170 * @param bool|callable $inputCallback Optional function called for each complete query sent
3171 * @return bool|string
3173 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3174 $fname = __METHOD__
, $inputCallback = false
3178 while ( !feof( $fp ) ) {
3179 if ( $lineCallback ) {
3180 call_user_func( $lineCallback );
3183 $line = trim( fgets( $fp ) );
3185 if ( $line == '' ) {
3189 if ( '-' == $line[0] && '-' == $line[1] ) {
3197 $done = $this->streamStatementEnd( $cmd, $line );
3201 if ( $done ||
feof( $fp ) ) {
3202 $cmd = $this->replaceVars( $cmd );
3204 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3205 $res = $this->query( $cmd, $fname );
3207 if ( $resultCallback ) {
3208 call_user_func( $resultCallback, $res, $this );
3211 if ( false === $res ) {
3212 $err = $this->lastError();
3214 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3225 * Called by sourceStream() to check if we've reached a statement end
3227 * @param string $sql SQL assembled so far
3228 * @param string $newLine New line about to be added to $sql
3229 * @return bool Whether $newLine contains end of the statement
3231 public function streamStatementEnd( &$sql, &$newLine ) {
3232 if ( $this->delimiter
) {
3234 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3235 if ( $newLine != $prev ) {
3244 * Database independent variable replacement. Replaces a set of variables
3245 * in an SQL statement with their contents as given by $this->getSchemaVars().
3247 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3249 * - '{$var}' should be used for text and is passed through the database's
3251 * - `{$var}` should be used for identifiers (e.g. table and database names).
3252 * It is passed through the database's addIdentifierQuotes method which
3253 * can be overridden if the database uses something other than backticks.
3254 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3255 * database's tableName method.
3256 * - / *i* / passes the name that follows through the database's indexName method.
3257 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3258 * its use should be avoided. In 1.24 and older, string encoding was applied.
3260 * @param string $ins SQL statement to replace variables in
3261 * @return string The new SQL statement with variables replaced
3263 protected function replaceVars( $ins ) {
3264 $vars = $this->getSchemaVars();
3265 return preg_replace_callback(
3267 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3268 \'\{\$ (\w+) }\' | # 3. addQuotes
3269 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3270 /\*\$ (\w+) \*/ # 5. leave unencoded
3272 function ( $m ) use ( $vars ) {
3273 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3274 // check for both nonexistent keys *and* the empty string.
3275 if ( isset( $m[1] ) && $m[1] !== '' ) {
3276 if ( $m[1] === 'i' ) {
3277 return $this->indexName( $m[2] );
3279 return $this->tableName( $m[2] );
3281 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3282 return $this->addQuotes( $vars[$m[3]] );
3283 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3284 return $this->addIdentifierQuotes( $vars[$m[4]] );
3285 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3286 return $vars[$m[5]];
3296 * Get schema variables. If none have been set via setSchemaVars(), then
3297 * use some defaults from the current object.
3301 protected function getSchemaVars() {
3302 if ( $this->mSchemaVars
) {
3303 return $this->mSchemaVars
;
3305 return $this->getDefaultSchemaVars();
3310 * Get schema variables to use if none have been set via setSchemaVars().
3312 * Override this in derived classes to provide variables for tables.sql
3313 * and SQL patch files.
3317 protected function getDefaultSchemaVars() {
3321 public function lockIsFree( $lockName, $method ) {
3325 public function lock( $lockName, $method, $timeout = 5 ) {
3326 $this->mNamedLocksHeld
[$lockName] = 1;
3331 public function unlock( $lockName, $method ) {
3332 unset( $this->mNamedLocksHeld
[$lockName] );
3337 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3338 if ( $this->writesOrCallbacksPending() ) {
3339 // This only flushes transactions to clear snapshots, not to write data
3340 throw new DBUnexpectedError(
3342 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3346 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3350 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3351 if ( $this->trxLevel() ) {
3352 // There is a good chance an exception was thrown, causing any early return
3353 // from the caller. Let any error handler get a chance to issue rollback().
3354 // If there isn't one, let the error bubble up and trigger server-side rollback.
3355 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3356 $this->unlock( $lockKey, $fname );
3359 $this->unlock( $lockKey, $fname );
3363 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3368 public function namedLocksEnqueue() {
3373 * Lock specific tables
3375 * @param array $read Array of tables to lock for read access
3376 * @param array $write Array of tables to lock for write access
3377 * @param string $method Name of caller
3378 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3381 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3386 * Unlock specific tables
3388 * @param string $method The caller
3391 public function unlockTables( $method ) {
3397 * @param string $tableName
3398 * @param string $fName
3399 * @return bool|ResultWrapper
3402 public function dropTable( $tableName, $fName = __METHOD__
) {
3403 if ( !$this->tableExists( $tableName, $fName ) ) {
3406 $sql = "DROP TABLE " . $this->tableName( $tableName );
3407 if ( $this->cascadingDeletes() ) {
3411 return $this->query( $sql, $fName );
3415 * Get search engine class. All subclasses of this need to implement this
3416 * if they wish to use searching.
3420 public function getSearchEngine() {
3421 return 'SearchEngineDummy';
3424 public function getInfinity() {
3428 public function encodeExpiry( $expiry ) {
3429 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3430 ?
$this->getInfinity()
3431 : $this->timestamp( $expiry );
3434 public function decodeExpiry( $expiry, $format = TS_MW
) {
3435 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3437 : wfTimestamp( $format, $expiry );
3440 public function setBigSelects( $value = true ) {
3444 public function isReadOnly() {
3445 return ( $this->getReadOnlyReason() !== false );
3449 * @return string|bool Reason this DB is read-only or false if it is not
3451 protected function getReadOnlyReason() {
3452 $reason = $this->getLBInfo( 'readOnlyReason' );
3454 return is_string( $reason ) ?
$reason : false;
3461 public function __toString() {
3462 return (string)$this->mConn
;
3466 * Run a few simple sanity checks
3468 public function __destruct() {
3469 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3470 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3472 $danglingCallbacks = array_merge(
3473 $this->mTrxIdleCallbacks
,
3474 $this->mTrxPreCommitCallbacks
,
3475 $this->mTrxEndCallbacks
3477 if ( $danglingCallbacks ) {
3479 foreach ( $danglingCallbacks as $callbackInfo ) {
3480 $callers[] = $callbackInfo[1];
3482 $callers = implode( ', ', $callers );
3483 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3491 abstract class Database
extends DatabaseBase
{
3492 // B/C until nothing type hints for DatabaseBase
3493 // @TODO: finish renaming DatabaseBase => Database