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 EmptyBagOStuff();
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 Previous value of the flag
416 * @deprecated since 1.28; use setFlag()
418 public function debug( $debug = null ) {
419 $res = $this->getFlag( DBO_DEBUG
);
420 if ( $debug !== null ) {
421 $debug ?
$this->setFlag( DBO_DEBUG
) : $this->clearFlag( DBO_DEBUG
);
427 public function bufferResults( $buffer = null ) {
428 $res = !$this->getFlag( DBO_NOBUFFER
);
429 if ( $buffer !== null ) {
430 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
437 * Turns on (false) or off (true) the automatic generation and sending
438 * of a "we're sorry, but there has been a database error" page on
439 * database errors. Default is on (false). When turned off, the
440 * code should use lastErrno() and lastError() to handle the
441 * situation as appropriate.
443 * Do not use this function outside of the Database classes.
445 * @param null|bool $ignoreErrors
446 * @return bool The previous value of the flag.
448 protected function ignoreErrors( $ignoreErrors = null ) {
449 $res = $this->getFlag( DBO_IGNORE
);
450 if ( $ignoreErrors !== null ) {
451 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
457 public function trxLevel() {
458 return $this->mTrxLevel
;
461 public function trxTimestamp() {
462 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
465 public function tablePrefix( $prefix = null ) {
466 $old = $this->mTablePrefix
;
467 $this->mTablePrefix
= $prefix;
472 public function dbSchema( $schema = null ) {
473 $old = $this->mSchema
;
474 $this->mSchema
= $schema;
480 * Set the filehandle to copy write statements to.
482 * @param resource $fh File handle
484 public function setFileHandle( $fh ) {
485 $this->fileHandle
= $fh;
488 public function getLBInfo( $name = null ) {
489 if ( is_null( $name ) ) {
490 return $this->mLBInfo
;
492 if ( array_key_exists( $name, $this->mLBInfo
) ) {
493 return $this->mLBInfo
[$name];
500 public function setLBInfo( $name, $value = null ) {
501 if ( is_null( $value ) ) {
502 $this->mLBInfo
= $name;
504 $this->mLBInfo
[$name] = $value;
508 public function setLazyMasterHandle( IDatabase
$conn ) {
509 $this->lazyMasterHandle
= $conn;
513 * @return IDatabase|null
514 * @see setLazyMasterHandle()
517 public function getLazyMasterHandle() {
518 return $this->lazyMasterHandle
;
522 * @param TransactionProfiler $profiler
525 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
526 $this->trxProfiler
= $profiler;
530 * Returns true if this database supports (and uses) cascading deletes
534 public function cascadingDeletes() {
539 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
543 public function cleanupTriggers() {
548 * Returns true if this database is strict about what can be put into an IP field.
549 * Specifically, it uses a NULL value instead of an empty string.
553 public function strictIPs() {
558 * Returns true if this database uses timestamps rather than integers
562 public function realTimestamps() {
566 public function implicitGroupby() {
570 public function implicitOrderby() {
575 * Returns true if this database can do a native search on IP columns
576 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
580 public function searchableIPs() {
585 * Returns true if this database can use functional indexes
589 public function functionalIndexes() {
593 public function lastQuery() {
594 return $this->mLastQuery
;
597 public function doneWrites() {
598 return (bool)$this->mDoneWrites
;
601 public function lastDoneWrites() {
602 return $this->mDoneWrites ?
: false;
605 public function writesPending() {
606 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
609 public function writesOrCallbacksPending() {
610 return $this->mTrxLevel
&& (
611 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
615 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
616 if ( !$this->mTrxLevel
) {
618 } elseif ( !$this->mTrxDoneWrites
) {
623 case self
::ESTIMATE_DB_APPLY
:
625 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
626 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
627 // For omitted queries, make them count as something at least
628 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
629 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
632 default: // everything
633 return $this->mTrxWriteDuration
;
637 public function pendingWriteCallers() {
638 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
641 public function isOpen() {
642 return $this->mOpened
;
645 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
646 if ( $remember === self
::REMEMBER_PRIOR
) {
647 array_push( $this->priorFlags
, $this->mFlags
);
649 $this->mFlags |
= $flag;
652 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
653 if ( $remember === self
::REMEMBER_PRIOR
) {
654 array_push( $this->priorFlags
, $this->mFlags
);
656 $this->mFlags
&= ~
$flag;
659 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
660 if ( !$this->priorFlags
) {
664 if ( $state === self
::RESTORE_INITIAL
) {
665 $this->mFlags
= reset( $this->priorFlags
);
666 $this->priorFlags
= [];
668 $this->mFlags
= array_pop( $this->priorFlags
);
672 public function getFlag( $flag ) {
673 return !!( $this->mFlags
& $flag );
676 public function getProperty( $name ) {
680 public function getWikiID() {
681 if ( $this->mTablePrefix
) {
682 return "{$this->mDBname}-{$this->mTablePrefix}";
684 return $this->mDBname
;
689 * Return a path to the DBMS-specific SQL file if it exists,
690 * otherwise default SQL file
692 * @param string $filename
695 private function getSqlFilePath( $filename ) {
697 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
698 if ( file_exists( $dbmsSpecificFilePath ) ) {
699 return $dbmsSpecificFilePath;
701 return "$IP/maintenance/$filename";
706 * Return a path to the DBMS-specific schema file,
707 * otherwise default to tables.sql
711 public function getSchemaPath() {
712 return $this->getSqlFilePath( 'tables.sql' );
716 * Return a path to the DBMS-specific update key file,
717 * otherwise default to update-keys.sql
721 public function getUpdateKeysPath() {
722 return $this->getSqlFilePath( 'update-keys.sql' );
726 * Get information about an index into an object
727 * @param string $table Table name
728 * @param string $index Index name
729 * @param string $fname Calling function name
730 * @return mixed Database-specific index description class or false if the index does not exist
732 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
735 * Wrapper for addslashes()
737 * @param string $s String to be slashed.
738 * @return string Slashed string.
740 abstract function strencode( $s );
743 * Called by serialize. Throw an exception when DB connection is serialized.
744 * This causes problems on some database engines because the connection is
745 * not restored on unserialize.
747 public function __sleep() {
748 throw new RuntimeException( 'Database serialization may cause problems, since ' .
749 'the connection is not restored on wakeup.' );
752 protected function installErrorHandler() {
753 $this->mPHPError
= false;
754 $this->htmlErrors
= ini_set( 'html_errors', '0' );
755 set_error_handler( [ $this, 'connectionerrorLogger' ] );
759 * @return bool|string
761 protected function restoreErrorHandler() {
762 restore_error_handler();
763 if ( $this->htmlErrors
!== false ) {
764 ini_set( 'html_errors', $this->htmlErrors
);
766 if ( $this->mPHPError
) {
767 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
768 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
778 * @param string $errstr
780 public function connectionerrorLogger( $errno, $errstr ) {
781 $this->mPHPError
= $errstr;
785 * Create a log context to pass to PSR logging functions.
787 * @param array $extras Additional data to add to context
790 protected function getLogContext( array $extras = [] ) {
793 'db_server' => $this->mServer
,
794 'db_name' => $this->mDBname
,
795 'db_user' => $this->mUser
,
801 public function close() {
802 if ( $this->mConn
) {
803 if ( $this->trxLevel() ) {
804 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
807 $closed = $this->closeConnection();
808 $this->mConn
= false;
809 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
810 throw new RuntimeException( "Transaction callbacks still pending." );
814 $this->mOpened
= false;
820 * Make sure isOpen() returns true as a sanity check
822 * @throws DBUnexpectedError
824 protected function assertOpen() {
825 if ( !$this->isOpen() ) {
826 throw new DBUnexpectedError( $this, "DB connection was already closed." );
831 * Closes underlying database connection
833 * @return bool Whether connection was closed successfully
835 abstract protected function closeConnection();
837 function reportConnectionError( $error = 'Unknown error' ) {
838 $myError = $this->lastError();
844 throw new DBConnectionError( $this, $error );
848 * The DBMS-dependent part of query()
850 * @param string $sql SQL query.
851 * @return ResultWrapper|bool Result object to feed to fetchObject,
852 * fetchRow, ...; or false on failure
854 abstract protected function doQuery( $sql );
857 * Determine whether a query writes to the DB.
858 * Should return true if unsure.
863 protected function isWriteQuery( $sql ) {
865 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
870 * @return string|null
872 protected function getQueryVerb( $sql ) {
873 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
877 * Determine whether a SQL statement is sensitive to isolation level.
878 * A SQL statement is considered transactable if its result could vary
879 * depending on the transaction isolation level. Operational commands
880 * such as 'SET' and 'SHOW' are not considered to be transactable.
885 protected function isTransactableQuery( $sql ) {
886 $verb = $this->getQueryVerb( $sql );
887 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
890 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
893 $priorWritesPending = $this->writesOrCallbacksPending();
894 $this->mLastQuery
= $sql;
896 $isWrite = $this->isWriteQuery( $sql );
898 $reason = $this->getReadOnlyReason();
899 if ( $reason !== false ) {
900 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
902 # Set a flag indicating that writes have been done
903 $this->mDoneWrites
= microtime( true );
906 # Add a comment for easy SHOW PROCESSLIST interpretation
907 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
908 $userName = $wgUser->getName();
909 if ( mb_strlen( $userName ) > 15 ) {
910 $userName = mb_substr( $userName, 0, 15 ) . '...';
912 $userName = str_replace( '/', '', $userName );
917 // Add trace comment to the begin of the sql string, right after the operator.
918 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
919 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
921 # Start implicit transactions that wrap the request if DBO_TRX is enabled
922 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
923 && $this->isTransactableQuery( $sql )
925 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
926 $this->mTrxAutomatic
= true;
929 # Keep track of whether the transaction has write queries pending
930 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
931 $this->mTrxDoneWrites
= true;
932 $this->trxProfiler
->transactionWritingIn(
933 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
936 if ( $this->debug() ) {
937 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
940 # Avoid fatals if close() was called
943 # Send the query to the server
944 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
946 # Try reconnecting if the connection was lost
947 if ( false === $ret && $this->wasErrorReissuable() ) {
948 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
949 # Stash the last error values before anything might clear them
950 $lastError = $this->lastError();
951 $lastErrno = $this->lastErrno();
952 # Update state tracking to reflect transaction loss due to disconnection
953 $this->handleTransactionLoss();
954 if ( $this->reconnect() ) {
955 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
956 $this->connLogger
->warning( $msg );
957 $this->queryLogger
->warning(
958 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
960 if ( !$recoverable ) {
961 # Callers may catch the exception and continue to use the DB
962 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
964 # Should be safe to silently retry the query
965 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
968 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
969 $this->connLogger
->error( $msg );
973 if ( false === $ret ) {
974 # Deadlocks cause the entire transaction to abort, not just the statement.
975 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
976 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
977 if ( $this->wasDeadlock() ) {
978 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
979 $tempIgnore = false; // not recoverable
981 # Update state tracking to reflect transaction loss
982 $this->handleTransactionLoss();
985 $this->reportQueryError(
986 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
989 $res = $this->resultObject( $ret );
994 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
995 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
996 # generalizeSQL() will probably cut down the query to reasonable
997 # logging size most of the time. The substr is really just a sanity check.
999 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1001 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1004 # Include query transaction state
1005 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1007 $startTime = microtime( true );
1008 $this->profiler
->profileIn( $queryProf );
1009 $ret = $this->doQuery( $commentedSql );
1010 $this->profiler
->profileOut( $queryProf );
1011 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1013 unset( $queryProfSection ); // profile out (if set)
1015 if ( $ret !== false ) {
1016 $this->lastPing
= $startTime;
1017 if ( $isWrite && $this->mTrxLevel
) {
1018 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1019 $this->mTrxWriteCallers
[] = $fname;
1023 if ( $sql === self
::PING_QUERY
) {
1024 $this->mRTTEstimate
= $queryRuntime;
1027 $this->trxProfiler
->recordQueryCompletion(
1028 $queryProf, $startTime, $isWrite, $this->affectedRows()
1030 MWDebug
::query( $sql, $fname, $isMaster, $queryRuntime );
1036 * Update the estimated run-time of a query, not counting large row lock times
1038 * LoadBalancer can be set to rollback transactions that will create huge replication
1039 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1040 * queries, like inserting a row can take a long time due to row locking. This method
1041 * uses some simple heuristics to discount those cases.
1043 * @param string $sql A SQL write query
1044 * @param float $runtime Total runtime, including RTT
1046 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1047 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1048 $indicativeOfReplicaRuntime = true;
1049 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1050 $verb = $this->getQueryVerb( $sql );
1051 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1052 if ( $verb === 'INSERT' ) {
1053 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1054 } elseif ( $verb === 'REPLACE' ) {
1055 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1059 $this->mTrxWriteDuration +
= $runtime;
1060 $this->mTrxWriteQueryCount +
= 1;
1061 if ( $indicativeOfReplicaRuntime ) {
1062 $this->mTrxWriteAdjDuration +
= $runtime;
1063 $this->mTrxWriteAdjQueryCount +
= 1;
1067 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1068 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1069 # Dropped connections also mean that named locks are automatically released.
1070 # Only allow error suppression in autocommit mode or when the lost transaction
1071 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1072 if ( $this->mNamedLocksHeld
) {
1073 return false; // possible critical section violation
1074 } elseif ( $sql === 'COMMIT' ) {
1075 return !$priorWritesPending; // nothing written anyway? (T127428)
1076 } elseif ( $sql === 'ROLLBACK' ) {
1077 return true; // transaction lost...which is also what was requested :)
1078 } elseif ( $this->explicitTrxActive() ) {
1079 return false; // don't drop atomocity
1080 } elseif ( $priorWritesPending ) {
1081 return false; // prior writes lost from implicit transaction
1087 private function handleTransactionLoss() {
1088 $this->mTrxLevel
= 0;
1089 $this->mTrxIdleCallbacks
= []; // bug 65263
1090 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1092 // Handle callbacks in mTrxEndCallbacks
1093 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1094 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1096 } catch ( Exception
$e ) {
1097 // Already logged; move on...
1102 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1103 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1104 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1106 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1107 $this->queryLogger
->error(
1108 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1109 $this->getLogContext( [
1110 'method' => __METHOD__
,
1113 'sql1line' => $sql1line,
1117 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1118 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1123 * Intended to be compatible with the PEAR::DB wrapper functions.
1124 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1126 * ? = scalar value, quoted as necessary
1127 * ! = raw SQL bit (a function for instance)
1128 * & = filename; reads the file and inserts as a blob
1129 * (we don't use this though...)
1131 * @param string $sql
1132 * @param string $func
1136 protected function prepare( $sql, $func = __METHOD__
) {
1137 /* MySQL doesn't support prepared statements (yet), so just
1138 * pack up the query for reference. We'll manually replace
1141 return [ 'query' => $sql, 'func' => $func ];
1145 * Free a prepared query, generated by prepare().
1146 * @param string $prepared
1148 protected function freePrepared( $prepared ) {
1149 /* No-op by default */
1153 * Execute a prepared query with the various arguments
1154 * @param string $prepared The prepared sql
1155 * @param mixed $args Either an array here, or put scalars as varargs
1157 * @return ResultWrapper
1159 public function execute( $prepared, $args = null ) {
1160 if ( !is_array( $args ) ) {
1162 $args = func_get_args();
1163 array_shift( $args );
1166 $sql = $this->fillPrepared( $prepared['query'], $args );
1168 return $this->query( $sql, $prepared['func'] );
1172 * For faking prepared SQL statements on DBs that don't support it directly.
1174 * @param string $preparedQuery A 'preparable' SQL statement
1175 * @param array $args Array of Arguments to fill it with
1176 * @return string Executable SQL
1178 public function fillPrepared( $preparedQuery, $args ) {
1180 $this->preparedArgs
=& $args;
1182 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1183 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1187 * preg_callback func for fillPrepared()
1188 * The arguments should be in $this->preparedArgs and must not be touched
1189 * while we're doing this.
1191 * @param array $matches
1192 * @throws DBUnexpectedError
1195 protected function fillPreparedArg( $matches ) {
1196 switch ( $matches[1] ) {
1205 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1207 switch ( $matches[1] ) {
1209 return $this->addQuotes( $arg );
1213 # return $this->addQuotes( file_get_contents( $arg ) );
1214 throw new DBUnexpectedError(
1216 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1219 throw new DBUnexpectedError(
1221 'Received invalid match. This should never happen!'
1226 public function freeResult( $res ) {
1229 public function selectField(
1230 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1232 if ( $var === '*' ) { // sanity
1233 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1236 if ( !is_array( $options ) ) {
1237 $options = [ $options ];
1240 $options['LIMIT'] = 1;
1242 $res = $this->select( $table, $var, $cond, $fname, $options );
1243 if ( $res === false ||
!$this->numRows( $res ) ) {
1247 $row = $this->fetchRow( $res );
1249 if ( $row !== false ) {
1250 return reset( $row );
1256 public function selectFieldValues(
1257 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1259 if ( $var === '*' ) { // sanity
1260 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1261 } elseif ( !is_string( $var ) ) { // sanity
1262 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1265 if ( !is_array( $options ) ) {
1266 $options = [ $options ];
1269 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1270 if ( $res === false ) {
1275 foreach ( $res as $row ) {
1276 $values[] = $row->$var;
1283 * Returns an optional USE INDEX clause to go after the table, and a
1284 * string to go at the end of the query.
1286 * @param array $options Associative array of options to be turned into
1287 * an SQL query, valid keys are listed in the function.
1289 * @see DatabaseBase::select()
1291 public function makeSelectOptions( $options ) {
1292 $preLimitTail = $postLimitTail = '';
1297 foreach ( $options as $key => $option ) {
1298 if ( is_numeric( $key ) ) {
1299 $noKeyOptions[$option] = true;
1303 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1305 $preLimitTail .= $this->makeOrderBy( $options );
1307 // if (isset($options['LIMIT'])) {
1308 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1309 // isset($options['OFFSET']) ? $options['OFFSET']
1313 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1314 $postLimitTail .= ' FOR UPDATE';
1317 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1318 $postLimitTail .= ' LOCK IN SHARE MODE';
1321 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1322 $startOpts .= 'DISTINCT';
1325 # Various MySQL extensions
1326 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1327 $startOpts .= ' /*! STRAIGHT_JOIN */';
1330 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1331 $startOpts .= ' HIGH_PRIORITY';
1334 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1335 $startOpts .= ' SQL_BIG_RESULT';
1338 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1339 $startOpts .= ' SQL_BUFFER_RESULT';
1342 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1343 $startOpts .= ' SQL_SMALL_RESULT';
1346 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1347 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1350 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1351 $startOpts .= ' SQL_CACHE';
1354 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1355 $startOpts .= ' SQL_NO_CACHE';
1358 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1359 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1363 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1364 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1369 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1373 * Returns an optional GROUP BY with an optional HAVING
1375 * @param array $options Associative array of options
1377 * @see DatabaseBase::select()
1380 public function makeGroupByWithHaving( $options ) {
1382 if ( isset( $options['GROUP BY'] ) ) {
1383 $gb = is_array( $options['GROUP BY'] )
1384 ?
implode( ',', $options['GROUP BY'] )
1385 : $options['GROUP BY'];
1386 $sql .= ' GROUP BY ' . $gb;
1388 if ( isset( $options['HAVING'] ) ) {
1389 $having = is_array( $options['HAVING'] )
1390 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1391 : $options['HAVING'];
1392 $sql .= ' HAVING ' . $having;
1399 * Returns an optional ORDER BY
1401 * @param array $options Associative array of options
1403 * @see DatabaseBase::select()
1406 public function makeOrderBy( $options ) {
1407 if ( isset( $options['ORDER BY'] ) ) {
1408 $ob = is_array( $options['ORDER BY'] )
1409 ?
implode( ',', $options['ORDER BY'] )
1410 : $options['ORDER BY'];
1412 return ' ORDER BY ' . $ob;
1418 // See IDatabase::select for the docs for this function
1419 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1420 $options = [], $join_conds = [] ) {
1421 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1423 return $this->query( $sql, $fname );
1426 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1427 $options = [], $join_conds = []
1429 if ( is_array( $vars ) ) {
1430 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1433 $options = (array)$options;
1434 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1435 ?
$options['USE INDEX']
1437 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1438 ?
$options['IGNORE INDEX']
1441 if ( is_array( $table ) ) {
1443 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1444 } elseif ( $table != '' ) {
1445 if ( $table[0] == ' ' ) {
1446 $from = ' FROM ' . $table;
1449 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1455 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1456 $this->makeSelectOptions( $options );
1458 if ( !empty( $conds ) ) {
1459 if ( is_array( $conds ) ) {
1460 $conds = $this->makeList( $conds, LIST_AND
);
1462 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1464 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1467 if ( isset( $options['LIMIT'] ) ) {
1468 $sql = $this->limitResult( $sql, $options['LIMIT'],
1469 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1471 $sql = "$sql $postLimitTail";
1473 if ( isset( $options['EXPLAIN'] ) ) {
1474 $sql = 'EXPLAIN ' . $sql;
1480 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1481 $options = [], $join_conds = []
1483 $options = (array)$options;
1484 $options['LIMIT'] = 1;
1485 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1487 if ( $res === false ) {
1491 if ( !$this->numRows( $res ) ) {
1495 $obj = $this->fetchObject( $res );
1500 public function estimateRowCount(
1501 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1504 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1507 $row = $this->fetchRow( $res );
1508 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1514 public function selectRowCount(
1515 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1518 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1519 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1522 $row = $this->fetchRow( $res );
1523 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1530 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1531 * It's only slightly flawed. Don't use for anything important.
1533 * @param string $sql A SQL Query
1537 protected static function generalizeSQL( $sql ) {
1538 # This does the same as the regexp below would do, but in such a way
1539 # as to avoid crashing php on some large strings.
1540 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1542 $sql = str_replace( "\\\\", '', $sql );
1543 $sql = str_replace( "\\'", '', $sql );
1544 $sql = str_replace( "\\\"", '', $sql );
1545 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1546 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1548 # All newlines, tabs, etc replaced by single space
1549 $sql = preg_replace( '/\s+/', ' ', $sql );
1552 # except the ones surrounded by characters, e.g. l10n
1553 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1554 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1559 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1560 $info = $this->fieldInfo( $table, $field );
1565 public function indexExists( $table, $index, $fname = __METHOD__
) {
1566 if ( !$this->tableExists( $table ) ) {
1570 $info = $this->indexInfo( $table, $index, $fname );
1571 if ( is_null( $info ) ) {
1574 return $info !== false;
1578 public function tableExists( $table, $fname = __METHOD__
) {
1579 $table = $this->tableName( $table );
1580 $old = $this->ignoreErrors( true );
1581 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1582 $this->ignoreErrors( $old );
1587 public function indexUnique( $table, $index ) {
1588 $indexInfo = $this->indexInfo( $table, $index );
1590 if ( !$indexInfo ) {
1594 return !$indexInfo[0]->Non_unique
;
1598 * Helper for DatabaseBase::insert().
1600 * @param array $options
1603 protected function makeInsertOptions( $options ) {
1604 return implode( ' ', $options );
1607 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1608 # No rows to insert, easy just return now
1609 if ( !count( $a ) ) {
1613 $table = $this->tableName( $table );
1615 if ( !is_array( $options ) ) {
1616 $options = [ $options ];
1620 if ( isset( $options['fileHandle'] ) ) {
1621 $fh = $options['fileHandle'];
1623 $options = $this->makeInsertOptions( $options );
1625 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1627 $keys = array_keys( $a[0] );
1630 $keys = array_keys( $a );
1633 $sql = 'INSERT ' . $options .
1634 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1638 foreach ( $a as $row ) {
1644 $sql .= '(' . $this->makeList( $row ) . ')';
1647 $sql .= '(' . $this->makeList( $a ) . ')';
1650 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1652 } elseif ( $fh !== null ) {
1656 return (bool)$this->query( $sql, $fname );
1660 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1662 * @param array $options
1665 protected function makeUpdateOptionsArray( $options ) {
1666 if ( !is_array( $options ) ) {
1667 $options = [ $options ];
1672 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1673 $opts[] = $this->lowPriorityOption();
1676 if ( in_array( 'IGNORE', $options ) ) {
1684 * Make UPDATE options for the DatabaseBase::update function
1686 * @param array $options The options passed to DatabaseBase::update
1689 protected function makeUpdateOptions( $options ) {
1690 $opts = $this->makeUpdateOptionsArray( $options );
1692 return implode( ' ', $opts );
1695 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1696 $table = $this->tableName( $table );
1697 $opts = $this->makeUpdateOptions( $options );
1698 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1700 if ( $conds !== [] && $conds !== '*' ) {
1701 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1704 return $this->query( $sql, $fname );
1707 public function makeList( $a, $mode = LIST_COMMA
) {
1708 if ( !is_array( $a ) ) {
1709 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1715 foreach ( $a as $field => $value ) {
1717 if ( $mode == LIST_AND
) {
1719 } elseif ( $mode == LIST_OR
) {
1728 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1729 $list .= "($value)";
1730 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1732 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1733 // Remove null from array to be handled separately if found
1734 $includeNull = false;
1735 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1736 $includeNull = true;
1737 unset( $value[$nullKey] );
1739 if ( count( $value ) == 0 && !$includeNull ) {
1740 throw new InvalidArgumentException( __METHOD__
. ": empty input for field $field" );
1741 } elseif ( count( $value ) == 0 ) {
1742 // only check if $field is null
1743 $list .= "$field IS NULL";
1745 // IN clause contains at least one valid element
1746 if ( $includeNull ) {
1747 // Group subconditions to ensure correct precedence
1750 if ( count( $value ) == 1 ) {
1751 // Special-case single values, as IN isn't terribly efficient
1752 // Don't necessarily assume the single key is 0; we don't
1753 // enforce linear numeric ordering on other arrays here.
1754 $value = array_values( $value )[0];
1755 $list .= $field . " = " . $this->addQuotes( $value );
1757 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1759 // if null present in array, append IS NULL
1760 if ( $includeNull ) {
1761 $list .= " OR $field IS NULL)";
1764 } elseif ( $value === null ) {
1765 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1766 $list .= "$field IS ";
1767 } elseif ( $mode == LIST_SET
) {
1768 $list .= "$field = ";
1772 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1773 $list .= "$field = ";
1775 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1782 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1785 foreach ( $data as $base => $sub ) {
1786 if ( count( $sub ) ) {
1787 $conds[] = $this->makeList(
1788 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1794 return $this->makeList( $conds, LIST_OR
);
1796 // Nothing to search for...
1802 * Return aggregated value alias
1804 * @param array $valuedata
1805 * @param string $valuename
1809 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1813 public function bitNot( $field ) {
1817 public function bitAnd( $fieldLeft, $fieldRight ) {
1818 return "($fieldLeft & $fieldRight)";
1821 public function bitOr( $fieldLeft, $fieldRight ) {
1822 return "($fieldLeft | $fieldRight)";
1825 public function buildConcat( $stringList ) {
1826 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1829 public function buildGroupConcatField(
1830 $delim, $table, $field, $conds = '', $join_conds = []
1832 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1834 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1838 * @param string $field Field or column to cast
1842 public function buildStringCast( $field ) {
1846 public function selectDB( $db ) {
1847 # Stub. Shouldn't cause serious problems if it's not overridden, but
1848 # if your database engine supports a concept similar to MySQL's
1849 # databases you may as well.
1850 $this->mDBname
= $db;
1855 public function getDBname() {
1856 return $this->mDBname
;
1859 public function getServer() {
1860 return $this->mServer
;
1864 * Format a table name ready for use in constructing an SQL query
1866 * This does two important things: it quotes the table names to clean them up,
1867 * and it adds a table prefix if only given a table name with no quotes.
1869 * All functions of this object which require a table name call this function
1870 * themselves. Pass the canonical name to such functions. This is only needed
1871 * when calling query() directly.
1873 * @note This function does not sanitize user input. It is not safe to use
1874 * this function to escape user input.
1875 * @param string $name Database table name
1876 * @param string $format One of:
1877 * quoted - Automatically pass the table name through addIdentifierQuotes()
1878 * so that it can be used in a query.
1879 * raw - Do not add identifier quotes to the table name
1880 * @return string Full database name
1882 public function tableName( $name, $format = 'quoted' ) {
1883 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1884 # Skip the entire process when we have a string quoted on both ends.
1885 # Note that we check the end so that we will still quote any use of
1886 # use of `database`.table. But won't break things if someone wants
1887 # to query a database table with a dot in the name.
1888 if ( $this->isQuotedIdentifier( $name ) ) {
1892 # Lets test for any bits of text that should never show up in a table
1893 # name. Basically anything like JOIN or ON which are actually part of
1894 # SQL queries, but may end up inside of the table value to combine
1895 # sql. Such as how the API is doing.
1896 # Note that we use a whitespace test rather than a \b test to avoid
1897 # any remote case where a word like on may be inside of a table name
1898 # surrounded by symbols which may be considered word breaks.
1899 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1903 # Split database and table into proper variables.
1904 # We reverse the explode so that database.table and table both output
1905 # the correct table.
1906 $dbDetails = explode( '.', $name, 3 );
1907 if ( count( $dbDetails ) == 3 ) {
1908 list( $database, $schema, $table ) = $dbDetails;
1909 # We don't want any prefix added in this case
1911 } elseif ( count( $dbDetails ) == 2 ) {
1912 list( $database, $table ) = $dbDetails;
1913 # We don't want any prefix added in this case
1914 # In dbs that support it, $database may actually be the schema
1915 # but that doesn't affect any of the functionality here
1919 list( $table ) = $dbDetails;
1920 if ( $wgSharedDB !== null # We have a shared database
1921 && $this->mForeign
== false # We're not working on a foreign database
1922 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1923 && in_array( $table, $wgSharedTables ) # A shared table is selected
1925 $database = $wgSharedDB;
1926 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1927 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1930 $schema = $this->mSchema
; # Default schema
1931 $prefix = $this->mTablePrefix
; # Default prefix
1935 # Quote $table and apply the prefix if not quoted.
1936 # $tableName might be empty if this is called from Database::replaceVars()
1937 $tableName = "{$prefix}{$table}";
1938 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1939 $tableName = $this->addIdentifierQuotes( $tableName );
1942 # Quote $schema and merge it with the table name if needed
1943 if ( strlen( $schema ) ) {
1944 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1945 $schema = $this->addIdentifierQuotes( $schema );
1947 $tableName = $schema . '.' . $tableName;
1950 # Quote $database and merge it with the table name if needed
1951 if ( $database !== null ) {
1952 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1953 $database = $this->addIdentifierQuotes( $database );
1955 $tableName = $database . '.' . $tableName;
1962 * Fetch a number of table names into an array
1963 * This is handy when you need to construct SQL for joins
1966 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1967 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1968 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1972 public function tableNames() {
1973 $inArray = func_get_args();
1976 foreach ( $inArray as $name ) {
1977 $retVal[$name] = $this->tableName( $name );
1984 * Fetch a number of table names into an zero-indexed numerical array
1985 * This is handy when you need to construct SQL for joins
1988 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1989 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1990 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1994 public function tableNamesN() {
1995 $inArray = func_get_args();
1998 foreach ( $inArray as $name ) {
1999 $retVal[] = $this->tableName( $name );
2006 * Get an aliased table name
2007 * e.g. tableName AS newTableName
2009 * @param string $name Table name, see tableName()
2010 * @param string|bool $alias Alias (optional)
2011 * @return string SQL name for aliased table. Will not alias a table to its own name
2013 public function tableNameWithAlias( $name, $alias = false ) {
2014 if ( !$alias ||
$alias == $name ) {
2015 return $this->tableName( $name );
2017 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2022 * Gets an array of aliased table names
2024 * @param array $tables [ [alias] => table ]
2025 * @return string[] See tableNameWithAlias()
2027 public function tableNamesWithAlias( $tables ) {
2029 foreach ( $tables as $alias => $table ) {
2030 if ( is_numeric( $alias ) ) {
2033 $retval[] = $this->tableNameWithAlias( $table, $alias );
2040 * Get an aliased field name
2041 * e.g. fieldName AS newFieldName
2043 * @param string $name Field name
2044 * @param string|bool $alias Alias (optional)
2045 * @return string SQL name for aliased field. Will not alias a field to its own name
2047 public function fieldNameWithAlias( $name, $alias = false ) {
2048 if ( !$alias ||
(string)$alias === (string)$name ) {
2051 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2056 * Gets an array of aliased field names
2058 * @param array $fields [ [alias] => field ]
2059 * @return string[] See fieldNameWithAlias()
2061 public function fieldNamesWithAlias( $fields ) {
2063 foreach ( $fields as $alias => $field ) {
2064 if ( is_numeric( $alias ) ) {
2067 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2074 * Get the aliased table name clause for a FROM clause
2075 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2077 * @param array $tables ( [alias] => table )
2078 * @param array $use_index Same as for select()
2079 * @param array $ignore_index Same as for select()
2080 * @param array $join_conds Same as for select()
2083 protected function tableNamesWithIndexClauseOrJOIN(
2084 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2088 $use_index = (array)$use_index;
2089 $ignore_index = (array)$ignore_index;
2090 $join_conds = (array)$join_conds;
2092 foreach ( $tables as $alias => $table ) {
2093 if ( !is_string( $alias ) ) {
2094 // No alias? Set it equal to the table name
2097 // Is there a JOIN clause for this table?
2098 if ( isset( $join_conds[$alias] ) ) {
2099 list( $joinType, $conds ) = $join_conds[$alias];
2100 $tableClause = $joinType;
2101 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2102 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2103 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2105 $tableClause .= ' ' . $use;
2108 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2109 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
2110 if ( $ignore != '' ) {
2111 $tableClause .= ' ' . $ignore;
2114 $on = $this->makeList( (array)$conds, LIST_AND
);
2116 $tableClause .= ' ON (' . $on . ')';
2119 $retJOIN[] = $tableClause;
2120 } elseif ( isset( $use_index[$alias] ) ) {
2121 // Is there an INDEX clause for this table?
2122 $tableClause = $this->tableNameWithAlias( $table, $alias );
2123 $tableClause .= ' ' . $this->useIndexClause(
2124 implode( ',', (array)$use_index[$alias] )
2127 $ret[] = $tableClause;
2128 } elseif ( isset( $ignore_index[$alias] ) ) {
2129 // Is there an INDEX clause for this table?
2130 $tableClause = $this->tableNameWithAlias( $table, $alias );
2131 $tableClause .= ' ' . $this->ignoreIndexClause(
2132 implode( ',', (array)$ignore_index[$alias] )
2135 $ret[] = $tableClause;
2137 $tableClause = $this->tableNameWithAlias( $table, $alias );
2139 $ret[] = $tableClause;
2143 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2144 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2145 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2147 // Compile our final table clause
2148 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2152 * Get the name of an index in a given table.
2154 * @param string $index
2157 protected function indexName( $index ) {
2158 // Backwards-compatibility hack
2160 'ar_usertext_timestamp' => 'usertext_timestamp',
2161 'un_user_id' => 'user_id',
2162 'un_user_ip' => 'user_ip',
2165 if ( isset( $renamed[$index] ) ) {
2166 return $renamed[$index];
2172 public function addQuotes( $s ) {
2173 if ( $s instanceof Blob
) {
2176 if ( $s === null ) {
2179 # This will also quote numeric values. This should be harmless,
2180 # and protects against weird problems that occur when they really
2181 # _are_ strings such as article titles and string->number->string
2182 # conversion is not 1:1.
2183 return "'" . $this->strencode( $s ) . "'";
2188 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2189 * MySQL uses `backticks` while basically everything else uses double quotes.
2190 * Since MySQL is the odd one out here the double quotes are our generic
2191 * and we implement backticks in DatabaseMysql.
2196 public function addIdentifierQuotes( $s ) {
2197 return '"' . str_replace( '"', '""', $s ) . '"';
2201 * Returns if the given identifier looks quoted or not according to
2202 * the database convention for quoting identifiers .
2204 * @note Do not use this to determine if untrusted input is safe.
2205 * A malicious user can trick this function.
2206 * @param string $name
2209 public function isQuotedIdentifier( $name ) {
2210 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2217 protected function escapeLikeInternal( $s ) {
2218 return addcslashes( $s, '\%_' );
2221 public function buildLike() {
2222 $params = func_get_args();
2224 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2225 $params = $params[0];
2230 foreach ( $params as $value ) {
2231 if ( $value instanceof LikeMatch
) {
2232 $s .= $value->toString();
2234 $s .= $this->escapeLikeInternal( $value );
2238 return " LIKE {$this->addQuotes( $s )} ";
2241 public function anyChar() {
2242 return new LikeMatch( '_' );
2245 public function anyString() {
2246 return new LikeMatch( '%' );
2249 public function nextSequenceValue( $seqName ) {
2254 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2255 * is only needed because a) MySQL must be as efficient as possible due to
2256 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2257 * which index to pick. Anyway, other databases might have different
2258 * indexes on a given table. So don't bother overriding this unless you're
2260 * @param string $index
2263 public function useIndexClause( $index ) {
2268 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2269 * is only needed because a) MySQL must be as efficient as possible due to
2270 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2271 * which index to pick. Anyway, other databases might have different
2272 * indexes on a given table. So don't bother overriding this unless you're
2274 * @param string $index
2277 public function ignoreIndexClause( $index ) {
2281 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2282 $quotedTable = $this->tableName( $table );
2284 if ( count( $rows ) == 0 ) {
2289 if ( !is_array( reset( $rows ) ) ) {
2293 // @FXIME: this is not atomic, but a trx would break affectedRows()
2294 foreach ( $rows as $row ) {
2295 # Delete rows which collide
2296 if ( $uniqueIndexes ) {
2297 $sql = "DELETE FROM $quotedTable WHERE ";
2299 foreach ( $uniqueIndexes as $index ) {
2306 if ( is_array( $index ) ) {
2308 foreach ( $index as $col ) {
2314 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2317 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2321 $this->query( $sql, $fname );
2324 # Now insert the row
2325 $this->insert( $table, $row, $fname );
2330 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2333 * @param string $table Table name
2334 * @param array|string $rows Row(s) to insert
2335 * @param string $fname Caller function name
2337 * @return ResultWrapper
2339 protected function nativeReplace( $table, $rows, $fname ) {
2340 $table = $this->tableName( $table );
2343 if ( !is_array( reset( $rows ) ) ) {
2347 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2350 foreach ( $rows as $row ) {
2357 $sql .= '(' . $this->makeList( $row ) . ')';
2360 return $this->query( $sql, $fname );
2363 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2366 if ( !count( $rows ) ) {
2367 return true; // nothing to do
2370 if ( !is_array( reset( $rows ) ) ) {
2374 if ( count( $uniqueIndexes ) ) {
2375 $clauses = []; // list WHERE clauses that each identify a single row
2376 foreach ( $rows as $row ) {
2377 foreach ( $uniqueIndexes as $index ) {
2378 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2379 $rowKey = []; // unique key to this row
2380 foreach ( $index as $column ) {
2381 $rowKey[$column] = $row[$column];
2383 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2386 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2391 $useTrx = !$this->mTrxLevel
;
2393 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2396 # Update any existing conflicting row(s)
2397 if ( $where !== false ) {
2398 $ok = $this->update( $table, $set, $where, $fname );
2402 # Now insert any non-conflicting row(s)
2403 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2404 } catch ( Exception
$e ) {
2406 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2411 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2417 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2421 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2424 $delTable = $this->tableName( $delTable );
2425 $joinTable = $this->tableName( $joinTable );
2426 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2427 if ( $conds != '*' ) {
2428 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2432 $this->query( $sql, $fname );
2436 * Returns the size of a text field, or -1 for "unlimited"
2438 * @param string $table
2439 * @param string $field
2442 public function textFieldSize( $table, $field ) {
2443 $table = $this->tableName( $table );
2444 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2445 $res = $this->query( $sql, __METHOD__
);
2446 $row = $this->fetchObject( $res );
2450 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2460 * A string to insert into queries to show that they're low-priority, like
2461 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2462 * string and nothing bad should happen.
2464 * @return string Returns the text of the low priority option if it is
2465 * supported, or a blank string otherwise
2467 public function lowPriorityOption() {
2471 public function delete( $table, $conds, $fname = __METHOD__
) {
2473 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2476 $table = $this->tableName( $table );
2477 $sql = "DELETE FROM $table";
2479 if ( $conds != '*' ) {
2480 if ( is_array( $conds ) ) {
2481 $conds = $this->makeList( $conds, LIST_AND
);
2483 $sql .= ' WHERE ' . $conds;
2486 return $this->query( $sql, $fname );
2489 public function insertSelect(
2490 $destTable, $srcTable, $varMap, $conds,
2491 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2493 if ( $this->cliMode
) {
2494 // For massive migrations with downtime, we don't want to select everything
2495 // into memory and OOM, so do all this native on the server side if possible.
2496 return $this->nativeInsertSelect(
2507 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2508 // on only the master (without needing row-based-replication). It also makes it easy to
2509 // know how big the INSERT is going to be.
2511 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2512 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2514 $selectOptions[] = 'FOR UPDATE';
2515 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2521 foreach ( $res as $row ) {
2522 $rows[] = (array)$row;
2525 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2528 public function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2529 $fname = __METHOD__
,
2530 $insertOptions = [], $selectOptions = []
2532 $destTable = $this->tableName( $destTable );
2534 if ( !is_array( $insertOptions ) ) {
2535 $insertOptions = [ $insertOptions ];
2538 $insertOptions = $this->makeInsertOptions( $insertOptions );
2540 if ( !is_array( $selectOptions ) ) {
2541 $selectOptions = [ $selectOptions ];
2544 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2547 if ( is_array( $srcTable ) ) {
2548 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2550 $srcTable = $this->tableName( $srcTable );
2553 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2554 " SELECT $startOpts " . implode( ',', $varMap ) .
2555 " FROM $srcTable $useIndex $ignoreIndex ";
2557 if ( $conds != '*' ) {
2558 if ( is_array( $conds ) ) {
2559 $conds = $this->makeList( $conds, LIST_AND
);
2561 $sql .= " WHERE $conds";
2564 $sql .= " $tailOpts";
2566 return $this->query( $sql, $fname );
2570 * Construct a LIMIT query with optional offset. This is used for query
2571 * pages. The SQL should be adjusted so that only the first $limit rows
2572 * are returned. If $offset is provided as well, then the first $offset
2573 * rows should be discarded, and the next $limit rows should be returned.
2574 * If the result of the query is not ordered, then the rows to be returned
2575 * are theoretically arbitrary.
2577 * $sql is expected to be a SELECT, if that makes a difference.
2579 * The version provided by default works in MySQL and SQLite. It will very
2580 * likely need to be overridden for most other DBMSes.
2582 * @param string $sql SQL query we will append the limit too
2583 * @param int $limit The SQL limit
2584 * @param int|bool $offset The SQL offset (default false)
2585 * @throws DBUnexpectedError
2588 public function limitResult( $sql, $limit, $offset = false ) {
2589 if ( !is_numeric( $limit ) ) {
2590 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2593 return "$sql LIMIT "
2594 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2598 public function unionSupportsOrderAndLimit() {
2599 return true; // True for almost every DB supported
2602 public function unionQueries( $sqls, $all ) {
2603 $glue = $all ?
') UNION ALL (' : ') UNION (';
2605 return '(' . implode( $glue, $sqls ) . ')';
2608 public function conditional( $cond, $trueVal, $falseVal ) {
2609 if ( is_array( $cond ) ) {
2610 $cond = $this->makeList( $cond, LIST_AND
);
2613 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2616 public function strreplace( $orig, $old, $new ) {
2617 return "REPLACE({$orig}, {$old}, {$new})";
2620 public function getServerUptime() {
2624 public function wasDeadlock() {
2628 public function wasLockTimeout() {
2632 public function wasErrorReissuable() {
2636 public function wasReadOnlyError() {
2641 * Determines if the given query error was a connection drop
2644 * @param integer|string $errno
2647 public function wasConnectionError( $errno ) {
2652 * Perform a deadlock-prone transaction.
2654 * This function invokes a callback function to perform a set of write
2655 * queries. If a deadlock occurs during the processing, the transaction
2656 * will be rolled back and the callback function will be called again.
2658 * Avoid using this method outside of Job or Maintenance classes.
2661 * $dbw->deadlockLoop( callback, ... );
2663 * Extra arguments are passed through to the specified callback function.
2664 * This method requires that no transactions are already active to avoid
2665 * causing premature commits or exceptions.
2667 * Returns whatever the callback function returned on its successful,
2668 * iteration, or false on error, for example if the retry limit was
2672 * @throws DBUnexpectedError
2675 public function deadlockLoop() {
2676 $args = func_get_args();
2677 $function = array_shift( $args );
2678 $tries = self
::DEADLOCK_TRIES
;
2680 $this->begin( __METHOD__
);
2683 /** @var Exception $e */
2687 $retVal = call_user_func_array( $function, $args );
2689 } catch ( DBQueryError
$e ) {
2690 if ( $this->wasDeadlock() ) {
2691 // Retry after a randomized delay
2692 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2694 // Throw the error back up
2698 } while ( --$tries > 0 );
2700 if ( $tries <= 0 ) {
2701 // Too many deadlocks; give up
2702 $this->rollback( __METHOD__
);
2705 $this->commit( __METHOD__
);
2711 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2712 # Real waits are implemented in the subclass.
2716 public function getSlavePos() {
2721 public function getMasterPos() {
2726 public function serverIsReadOnly() {
2730 final public function onTransactionResolution( callable
$callback ) {
2731 if ( !$this->mTrxLevel
) {
2732 throw new DBUnexpectedError( $this, "No transaction is active." );
2734 $this->mTrxEndCallbacks
[] = [ $callback, wfGetCaller() ];
2737 final public function onTransactionIdle( callable
$callback ) {
2738 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2739 if ( !$this->mTrxLevel
) {
2740 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2744 final public function onTransactionPreCommitOrIdle( callable
$callback ) {
2745 if ( $this->mTrxLevel
) {
2746 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2748 // If no transaction is active, then make one for this callback
2749 $this->startAtomic( __METHOD__
);
2751 call_user_func( $callback );
2752 $this->endAtomic( __METHOD__
);
2753 } catch ( Exception
$e ) {
2754 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2760 final public function setTransactionListener( $name, callable
$callback = null ) {
2762 $this->mTrxRecurringCallbacks
[$name] = [ $callback, wfGetCaller() ];
2764 unset( $this->mTrxRecurringCallbacks
[$name] );
2769 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2771 * This method should not be used outside of Database/LoadBalancer
2773 * @param bool $suppress
2776 final public function setTrxEndCallbackSuppression( $suppress ) {
2777 $this->mTrxEndCallbacksSuppressed
= $suppress;
2781 * Actually run and consume any "on transaction idle/resolution" callbacks.
2783 * This method should not be used outside of Database/LoadBalancer
2785 * @param integer $trigger IDatabase::TRIGGER_* constant
2789 public function runOnTransactionIdleCallbacks( $trigger ) {
2790 if ( $this->mTrxEndCallbacksSuppressed
) {
2794 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2795 /** @var Exception $e */
2796 $e = null; // first exception
2797 do { // callbacks may add callbacks :)
2798 $callbacks = array_merge(
2799 $this->mTrxIdleCallbacks
,
2800 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2802 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2803 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2804 foreach ( $callbacks as $callback ) {
2806 list( $phpCallback ) = $callback;
2807 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2808 call_user_func_array( $phpCallback, [ $trigger ] );
2810 $this->setFlag( DBO_TRX
); // restore automatic begin()
2812 $this->clearFlag( DBO_TRX
); // restore auto-commit
2814 } catch ( Exception
$ex ) {
2815 call_user_func( $this->errorLogger
, $ex );
2817 // Some callbacks may use startAtomic/endAtomic, so make sure
2818 // their transactions are ended so other callbacks don't fail
2819 if ( $this->trxLevel() ) {
2820 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2824 } while ( count( $this->mTrxIdleCallbacks
) );
2826 if ( $e instanceof Exception
) {
2827 throw $e; // re-throw any first exception
2832 * Actually run and consume any "on transaction pre-commit" callbacks.
2834 * This method should not be used outside of Database/LoadBalancer
2839 public function runOnTransactionPreCommitCallbacks() {
2840 $e = null; // first exception
2841 do { // callbacks may add callbacks :)
2842 $callbacks = $this->mTrxPreCommitCallbacks
;
2843 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2844 foreach ( $callbacks as $callback ) {
2846 list( $phpCallback ) = $callback;
2847 call_user_func( $phpCallback );
2848 } catch ( Exception
$ex ) {
2849 call_user_func( $this->errorLogger
, $ex );
2853 } while ( count( $this->mTrxPreCommitCallbacks
) );
2855 if ( $e instanceof Exception
) {
2856 throw $e; // re-throw any first exception
2861 * Actually run any "transaction listener" callbacks.
2863 * This method should not be used outside of Database/LoadBalancer
2865 * @param integer $trigger IDatabase::TRIGGER_* constant
2869 public function runTransactionListenerCallbacks( $trigger ) {
2870 if ( $this->mTrxEndCallbacksSuppressed
) {
2874 /** @var Exception $e */
2875 $e = null; // first exception
2877 foreach ( $this->mTrxRecurringCallbacks
as $callback ) {
2879 list( $phpCallback ) = $callback;
2880 $phpCallback( $trigger, $this );
2881 } catch ( Exception
$ex ) {
2882 call_user_func( $this->errorLogger
, $ex );
2887 if ( $e instanceof Exception
) {
2888 throw $e; // re-throw any first exception
2892 final public function startAtomic( $fname = __METHOD__
) {
2893 if ( !$this->mTrxLevel
) {
2894 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2895 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2896 // in all changes being in one transaction to keep requests transactional.
2897 if ( !$this->getFlag( DBO_TRX
) ) {
2898 $this->mTrxAutomaticAtomic
= true;
2902 $this->mTrxAtomicLevels
[] = $fname;
2905 final public function endAtomic( $fname = __METHOD__
) {
2906 if ( !$this->mTrxLevel
) {
2907 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2909 if ( !$this->mTrxAtomicLevels ||
2910 array_pop( $this->mTrxAtomicLevels
) !== $fname
2912 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2915 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2916 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2920 final public function doAtomicSection( $fname, callable
$callback ) {
2921 $this->startAtomic( $fname );
2923 $res = call_user_func_array( $callback, [ $this, $fname ] );
2924 } catch ( Exception
$e ) {
2925 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2928 $this->endAtomic( $fname );
2933 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2934 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2935 if ( $this->mTrxLevel
) {
2936 if ( $this->mTrxAtomicLevels
) {
2937 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2938 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2939 throw new DBUnexpectedError( $this, $msg );
2940 } elseif ( !$this->mTrxAutomatic
) {
2941 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2942 throw new DBUnexpectedError( $this, $msg );
2944 // @TODO: make this an exception at some point
2945 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2946 $this->queryLogger
->error( $msg );
2947 return; // join the main transaction set
2949 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2950 // @TODO: make this an exception at some point
2951 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2952 $this->queryLogger
->error( $msg );
2953 return; // let any writes be in the main transaction
2956 // Avoid fatals if close() was called
2957 $this->assertOpen();
2959 $this->doBegin( $fname );
2960 $this->mTrxTimestamp
= microtime( true );
2961 $this->mTrxFname
= $fname;
2962 $this->mTrxDoneWrites
= false;
2963 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2964 $this->mTrxAutomaticAtomic
= false;
2965 $this->mTrxAtomicLevels
= [];
2966 $this->mTrxShortId
= wfRandomString( 12 );
2967 $this->mTrxWriteDuration
= 0.0;
2968 $this->mTrxWriteQueryCount
= 0;
2969 $this->mTrxWriteAdjDuration
= 0.0;
2970 $this->mTrxWriteAdjQueryCount
= 0;
2971 $this->mTrxWriteCallers
= [];
2972 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2973 // Get an estimate of the replica DB lag before then, treating estimate staleness
2974 // as lag itself just to be safe
2975 $status = $this->getApproximateLagStatus();
2976 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2980 * Issues the BEGIN command to the database server.
2982 * @see DatabaseBase::begin()
2983 * @param string $fname
2985 protected function doBegin( $fname ) {
2986 $this->query( 'BEGIN', $fname );
2987 $this->mTrxLevel
= 1;
2990 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2991 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2992 // There are still atomic sections open. This cannot be ignored
2993 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2994 throw new DBUnexpectedError(
2996 "$fname: Got COMMIT while atomic sections $levels are still open."
3000 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3001 if ( !$this->mTrxLevel
) {
3002 return; // nothing to do
3003 } elseif ( !$this->mTrxAutomatic
) {
3004 throw new DBUnexpectedError(
3006 "$fname: Flushing an explicit transaction, getting out of sync."
3010 if ( !$this->mTrxLevel
) {
3011 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
3012 return; // nothing to do
3013 } elseif ( $this->mTrxAutomatic
) {
3014 // @TODO: make this an exception at some point
3015 $msg = "$fname: Explicit commit of implicit transaction.";
3016 $this->queryLogger
->error( $msg );
3017 return; // wait for the main transaction set commit round
3021 // Avoid fatals if close() was called
3022 $this->assertOpen();
3024 $this->runOnTransactionPreCommitCallbacks();
3025 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3026 $this->doCommit( $fname );
3027 if ( $this->mTrxDoneWrites
) {
3028 $this->mDoneWrites
= microtime( true );
3029 $this->trxProfiler
->transactionWritingOut(
3030 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3033 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3034 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3038 * Issues the COMMIT command to the database server.
3040 * @see DatabaseBase::commit()
3041 * @param string $fname
3043 protected function doCommit( $fname ) {
3044 if ( $this->mTrxLevel
) {
3045 $this->query( 'COMMIT', $fname );
3046 $this->mTrxLevel
= 0;
3050 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3051 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3052 if ( !$this->mTrxLevel
) {
3053 return; // nothing to do
3056 if ( !$this->mTrxLevel
) {
3057 $this->queryLogger
->error(
3058 "$fname: No transaction to rollback, something got out of sync." );
3059 return; // nothing to do
3060 } elseif ( $this->getFlag( DBO_TRX
) ) {
3061 throw new DBUnexpectedError(
3063 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3068 // Avoid fatals if close() was called
3069 $this->assertOpen();
3071 $this->doRollback( $fname );
3072 $this->mTrxAtomicLevels
= [];
3073 if ( $this->mTrxDoneWrites
) {
3074 $this->trxProfiler
->transactionWritingOut(
3075 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3078 $this->mTrxIdleCallbacks
= []; // clear
3079 $this->mTrxPreCommitCallbacks
= []; // clear
3080 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3081 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3085 * Issues the ROLLBACK command to the database server.
3087 * @see DatabaseBase::rollback()
3088 * @param string $fname
3090 protected function doRollback( $fname ) {
3091 if ( $this->mTrxLevel
) {
3092 # Disconnects cause rollback anyway, so ignore those errors
3093 $ignoreErrors = true;
3094 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3095 $this->mTrxLevel
= 0;
3099 public function flushSnapshot( $fname = __METHOD__
) {
3100 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3101 // This only flushes transactions to clear snapshots, not to write data
3102 throw new DBUnexpectedError(
3104 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3108 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3111 public function explicitTrxActive() {
3112 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3116 * Creates a new table with structure copied from existing table
3117 * Note that unlike most database abstraction functions, this function does not
3118 * automatically append database prefix, because it works at a lower
3119 * abstraction level.
3120 * The table names passed to this function shall not be quoted (this
3121 * function calls addIdentifierQuotes when needed).
3123 * @param string $oldName Name of table whose structure should be copied
3124 * @param string $newName Name of table to be created
3125 * @param bool $temporary Whether the new table should be temporary
3126 * @param string $fname Calling function name
3127 * @throws RuntimeException
3128 * @return bool True if operation was successful
3130 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3133 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3136 function listTables( $prefix = null, $fname = __METHOD__
) {
3137 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3141 * Reset the views process cache set by listViews()
3144 final public function clearViewsCache() {
3145 $this->allViews
= null;
3149 * Lists all the VIEWs in the database
3151 * For caching purposes the list of all views should be stored in
3152 * $this->allViews. The process cache can be cleared with clearViewsCache()
3154 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3155 * @param string $fname Name of calling function
3156 * @throws RuntimeException
3160 public function listViews( $prefix = null, $fname = __METHOD__
) {
3161 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3165 * Differentiates between a TABLE and a VIEW
3167 * @param string $name Name of the database-structure to test.
3168 * @throws RuntimeException
3172 public function isView( $name ) {
3173 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3176 public function timestamp( $ts = 0 ) {
3177 return wfTimestamp( TS_MW
, $ts );
3180 public function timestampOrNull( $ts = null ) {
3181 if ( is_null( $ts ) ) {
3184 return $this->timestamp( $ts );
3189 * Take the result from a query, and wrap it in a ResultWrapper if
3190 * necessary. Boolean values are passed through as is, to indicate success
3191 * of write queries or failure.
3193 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3194 * resource, and it was necessary to call this function to convert it to
3195 * a wrapper. Nowadays, raw database objects are never exposed to external
3196 * callers, so this is unnecessary in external code.
3198 * @param bool|ResultWrapper|resource|object $result
3199 * @return bool|ResultWrapper
3201 protected function resultObject( $result ) {
3204 } elseif ( $result instanceof ResultWrapper
) {
3206 } elseif ( $result === true ) {
3207 // Successful write query
3210 return new ResultWrapper( $this, $result );
3214 public function ping( &$rtt = null ) {
3215 // Avoid hitting the server if it was hit recently
3216 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3217 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3218 $rtt = $this->mRTTEstimate
;
3219 return true; // don't care about $rtt
3223 // This will reconnect if possible or return false if not
3224 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3225 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3226 $this->restoreFlags( self
::RESTORE_PRIOR
);
3229 $rtt = $this->mRTTEstimate
;
3238 protected function reconnect() {
3239 $this->closeConnection();
3240 $this->mOpened
= false;
3241 $this->mConn
= false;
3243 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3244 $this->lastPing
= microtime( true );
3246 } catch ( DBConnectionError
$e ) {
3253 public function getSessionLagStatus() {
3254 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3258 * Get the replica DB lag when the current transaction started
3260 * This is useful when transactions might use snapshot isolation
3261 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3262 * is this lag plus transaction duration. If they don't, it is still
3263 * safe to be pessimistic. This returns null if there is no transaction.
3265 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3268 public function getTransactionLagStatus() {
3269 return $this->mTrxLevel
3270 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3275 * Get a replica DB lag estimate for this server
3277 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3280 public function getApproximateLagStatus() {
3282 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3283 'since' => microtime( true )
3288 * Merge the result of getSessionLagStatus() for several DBs
3289 * using the most pessimistic values to estimate the lag of
3290 * any data derived from them in combination
3292 * This is information is useful for caching modules
3294 * @see WANObjectCache::set()
3295 * @see WANObjectCache::getWithSetCallback()
3297 * @param IDatabase $db1
3298 * @param IDatabase ...
3299 * @return array Map of values:
3300 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3301 * - since: oldest UNIX timestamp of any of the DB lag estimates
3302 * - pending: whether any of the DBs have uncommitted changes
3305 public static function getCacheSetOptions( IDatabase
$db1 ) {
3306 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3307 foreach ( func_get_args() as $db ) {
3308 /** @var IDatabase $db */
3309 $status = $db->getSessionLagStatus();
3310 if ( $status['lag'] === false ) {
3311 $res['lag'] = false;
3312 } elseif ( $res['lag'] !== false ) {
3313 $res['lag'] = max( $res['lag'], $status['lag'] );
3315 $res['since'] = min( $res['since'], $status['since'] );
3316 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3322 public function getLag() {
3326 function maxListLen() {
3330 public function encodeBlob( $b ) {
3334 public function decodeBlob( $b ) {
3335 if ( $b instanceof Blob
) {
3341 public function setSessionOptions( array $options ) {
3345 * Read and execute SQL commands from a file.
3347 * Returns true on success, error string or exception on failure (depending
3348 * on object's error ignore settings).
3350 * @param string $filename File name to open
3351 * @param bool|callable $lineCallback Optional function called before reading each line
3352 * @param bool|callable $resultCallback Optional function called for each MySQL result
3353 * @param bool|string $fname Calling function name or false if name should be
3354 * generated dynamically using $filename
3355 * @param bool|callable $inputCallback Optional function called for each
3356 * complete line sent
3357 * @return bool|string
3360 public function sourceFile(
3361 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3363 MediaWiki\
suppressWarnings();
3364 $fp = fopen( $filename, 'r' );
3365 MediaWiki\restoreWarnings
();
3367 if ( false === $fp ) {
3368 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3372 $fname = __METHOD__
. "( $filename )";
3376 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3377 } catch ( Exception
$e ) {
3388 * Get the full path of a patch file. Originally based on archive()
3389 * from updaters.inc. Keep in mind this always returns a patch, as
3390 * it fails back to MySQL if no DB-specific patch can be found
3392 * @param string $patch The name of the patch, like patch-something.sql
3393 * @return string Full path to patch file
3395 public function patchPath( $patch ) {
3398 $dbType = $this->getType();
3399 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3400 return "$IP/maintenance/$dbType/archives/$patch";
3402 return "$IP/maintenance/archives/$patch";
3406 public function setSchemaVars( $vars ) {
3407 $this->mSchemaVars
= $vars;
3411 * Read and execute commands from an open file handle.
3413 * Returns true on success, error string or exception on failure (depending
3414 * on object's error ignore settings).
3416 * @param resource $fp File handle
3417 * @param bool|callable $lineCallback Optional function called before reading each query
3418 * @param bool|callable $resultCallback Optional function called for each MySQL result
3419 * @param string $fname Calling function name
3420 * @param bool|callable $inputCallback Optional function called for each complete query sent
3421 * @return bool|string
3423 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3424 $fname = __METHOD__
, $inputCallback = false
3428 while ( !feof( $fp ) ) {
3429 if ( $lineCallback ) {
3430 call_user_func( $lineCallback );
3433 $line = trim( fgets( $fp ) );
3435 if ( $line == '' ) {
3439 if ( '-' == $line[0] && '-' == $line[1] ) {
3447 $done = $this->streamStatementEnd( $cmd, $line );
3451 if ( $done ||
feof( $fp ) ) {
3452 $cmd = $this->replaceVars( $cmd );
3454 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3455 $res = $this->query( $cmd, $fname );
3457 if ( $resultCallback ) {
3458 call_user_func( $resultCallback, $res, $this );
3461 if ( false === $res ) {
3462 $err = $this->lastError();
3464 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3475 * Called by sourceStream() to check if we've reached a statement end
3477 * @param string $sql SQL assembled so far
3478 * @param string $newLine New line about to be added to $sql
3479 * @return bool Whether $newLine contains end of the statement
3481 public function streamStatementEnd( &$sql, &$newLine ) {
3482 if ( $this->delimiter
) {
3484 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3485 if ( $newLine != $prev ) {
3494 * Database independent variable replacement. Replaces a set of variables
3495 * in an SQL statement with their contents as given by $this->getSchemaVars().
3497 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3499 * - '{$var}' should be used for text and is passed through the database's
3501 * - `{$var}` should be used for identifiers (e.g. table and database names).
3502 * It is passed through the database's addIdentifierQuotes method which
3503 * can be overridden if the database uses something other than backticks.
3504 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3505 * database's tableName method.
3506 * - / *i* / passes the name that follows through the database's indexName method.
3507 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3508 * its use should be avoided. In 1.24 and older, string encoding was applied.
3510 * @param string $ins SQL statement to replace variables in
3511 * @return string The new SQL statement with variables replaced
3513 protected function replaceVars( $ins ) {
3514 $vars = $this->getSchemaVars();
3515 return preg_replace_callback(
3517 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3518 \'\{\$ (\w+) }\' | # 3. addQuotes
3519 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3520 /\*\$ (\w+) \*/ # 5. leave unencoded
3522 function ( $m ) use ( $vars ) {
3523 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3524 // check for both nonexistent keys *and* the empty string.
3525 if ( isset( $m[1] ) && $m[1] !== '' ) {
3526 if ( $m[1] === 'i' ) {
3527 return $this->indexName( $m[2] );
3529 return $this->tableName( $m[2] );
3531 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3532 return $this->addQuotes( $vars[$m[3]] );
3533 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3534 return $this->addIdentifierQuotes( $vars[$m[4]] );
3535 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3536 return $vars[$m[5]];
3546 * Get schema variables. If none have been set via setSchemaVars(), then
3547 * use some defaults from the current object.
3551 protected function getSchemaVars() {
3552 if ( $this->mSchemaVars
) {
3553 return $this->mSchemaVars
;
3555 return $this->getDefaultSchemaVars();
3560 * Get schema variables to use if none have been set via setSchemaVars().
3562 * Override this in derived classes to provide variables for tables.sql
3563 * and SQL patch files.
3567 protected function getDefaultSchemaVars() {
3571 public function lockIsFree( $lockName, $method ) {
3575 public function lock( $lockName, $method, $timeout = 5 ) {
3576 $this->mNamedLocksHeld
[$lockName] = 1;
3581 public function unlock( $lockName, $method ) {
3582 unset( $this->mNamedLocksHeld
[$lockName] );
3587 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3588 if ( $this->writesOrCallbacksPending() ) {
3589 // This only flushes transactions to clear snapshots, not to write data
3590 throw new DBUnexpectedError(
3592 "$fname: Cannot COMMIT to clear snapshot because writes are pending."
3596 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3600 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3601 if ( $this->trxLevel() ) {
3602 // There is a good chance an exception was thrown, causing any early return
3603 // from the caller. Let any error handler get a chance to issue rollback().
3604 // If there isn't one, let the error bubble up and trigger server-side rollback.
3605 $this->onTransactionResolution( function () use ( $lockKey, $fname ) {
3606 $this->unlock( $lockKey, $fname );
3609 $this->unlock( $lockKey, $fname );
3613 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
3618 public function namedLocksEnqueue() {
3623 * Lock specific tables
3625 * @param array $read Array of tables to lock for read access
3626 * @param array $write Array of tables to lock for write access
3627 * @param string $method Name of caller
3628 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3631 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3636 * Unlock specific tables
3638 * @param string $method The caller
3641 public function unlockTables( $method ) {
3647 * @param string $tableName
3648 * @param string $fName
3649 * @return bool|ResultWrapper
3652 public function dropTable( $tableName, $fName = __METHOD__
) {
3653 if ( !$this->tableExists( $tableName, $fName ) ) {
3656 $sql = "DROP TABLE " . $this->tableName( $tableName );
3657 if ( $this->cascadingDeletes() ) {
3661 return $this->query( $sql, $fName );
3665 * Get search engine class. All subclasses of this need to implement this
3666 * if they wish to use searching.
3670 public function getSearchEngine() {
3671 return 'SearchEngineDummy';
3674 public function getInfinity() {
3678 public function encodeExpiry( $expiry ) {
3679 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3680 ?
$this->getInfinity()
3681 : $this->timestamp( $expiry );
3684 public function decodeExpiry( $expiry, $format = TS_MW
) {
3685 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3687 : wfTimestamp( $format, $expiry );
3690 public function setBigSelects( $value = true ) {
3694 public function isReadOnly() {
3695 return ( $this->getReadOnlyReason() !== false );
3699 * @return string|bool Reason this DB is read-only or false if it is not
3701 protected function getReadOnlyReason() {
3702 $reason = $this->getLBInfo( 'readOnlyReason' );
3704 return is_string( $reason ) ?
$reason : false;
3711 public function __toString() {
3712 return (string)$this->mConn
;
3716 * Run a few simple sanity checks
3718 public function __destruct() {
3719 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3720 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3722 $danglingCallbacks = array_merge(
3723 $this->mTrxIdleCallbacks
,
3724 $this->mTrxPreCommitCallbacks
,
3725 $this->mTrxEndCallbacks
3727 if ( $danglingCallbacks ) {
3729 foreach ( $danglingCallbacks as $callbackInfo ) {
3730 $callers[] = $callbackInfo[1];
3732 $callers = implode( ', ', $callers );
3733 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3741 abstract class Database
extends DatabaseBase
{
3742 // B/C until nothing type hints for DatabaseBase
3743 // @TODO: finish renaming DatabaseBase => Database