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 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Wikimedia\ScopedCallback
;
31 use Wikimedia\Timestamp\ConvertibleTimestamp
;
35 use InvalidArgumentException
;
40 * Relational database abstraction object
45 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
46 /** Number of times to re-try an operation in case of deadlock */
47 const DEADLOCK_TRIES
= 4;
48 /** Minimum time to wait before retry, in microseconds */
49 const DEADLOCK_DELAY_MIN
= 500000;
50 /** Maximum time to wait before retry */
51 const DEADLOCK_DELAY_MAX
= 1500000;
53 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_QUERY
= 'SELECT 1 AS ping';
57 const TINY_WRITE_SEC
= 0.010;
58 const SLOW_WRITE_SEC
= 0.500;
59 const SMALL_WRITE_ROWS
= 100;
61 /** @var string SQL query */
62 protected $mLastQuery = '';
63 /** @var float|bool UNIX timestamp of last write query */
64 protected $mLastWriteTime = false;
65 /** @var string|bool */
66 protected $mPHPError = false;
75 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
76 protected $tableAliases = [];
77 /** @var bool Whether this PHP instance is for a CLI script */
79 /** @var string Agent name for query profiling */
82 /** @var BagOStuff APC cache */
84 /** @var LoggerInterface */
85 protected $connLogger;
86 /** @var LoggerInterface */
87 protected $queryLogger;
88 /** @var callback Error logging callback */
89 protected $errorLogger;
91 /** @var resource|null Database connection */
92 protected $mConn = null;
94 protected $mOpened = false;
96 /** @var array[] List of (callable, method name) */
97 protected $mTrxIdleCallbacks = [];
98 /** @var array[] List of (callable, method name) */
99 protected $mTrxPreCommitCallbacks = [];
100 /** @var array[] List of (callable, method name) */
101 protected $mTrxEndCallbacks = [];
102 /** @var callable[] Map of (name => callable) */
103 protected $mTrxRecurringCallbacks = [];
104 /** @var bool Whether to suppress triggering of transaction end callbacks */
105 protected $mTrxEndCallbacksSuppressed = false;
108 protected $mTablePrefix = '';
110 protected $mSchema = '';
114 protected $mLBInfo = [];
115 /** @var bool|null */
116 protected $mDefaultBigSelects = null;
117 /** @var array|bool */
118 protected $mSchemaVars = false;
120 protected $mSessionVars = [];
121 /** @var array|null */
122 protected $preparedArgs;
123 /** @var string|bool|null Stashed value of html_errors INI setting */
124 protected $htmlErrors;
126 protected $delimiter = ';';
127 /** @var DatabaseDomain */
128 protected $currentDomain;
131 * Either 1 if a transaction is active or 0 otherwise.
132 * The other Trx fields may not be meaningfull if this is 0.
136 protected $mTrxLevel = 0;
138 * Either a short hexidecimal string if a transaction is active or ""
141 * @see Database::mTrxLevel
143 protected $mTrxShortId = '';
145 * The UNIX time that the transaction started. Callers can assume that if
146 * snapshot isolation is used, then the data is *at least* up to date to that
147 * point (possibly more up-to-date since the first SELECT defines the snapshot).
150 * @see Database::mTrxLevel
152 private $mTrxTimestamp = null;
153 /** @var float Lag estimate at the time of BEGIN */
154 private $mTrxReplicaLag = null;
156 * Remembers the function name given for starting the most recent transaction via begin().
157 * Used to provide additional context for error reporting.
160 * @see Database::mTrxLevel
162 private $mTrxFname = null;
164 * Record if possible write queries were done in the last transaction started
167 * @see Database::mTrxLevel
169 private $mTrxDoneWrites = false;
171 * Record if the current transaction was started implicitly due to DBO_TRX being set.
174 * @see Database::mTrxLevel
176 private $mTrxAutomatic = false;
178 * Array of levels of atomicity within transactions
182 private $mTrxAtomicLevels = [];
184 * Record if the current transaction was started implicitly by Database::startAtomic
188 private $mTrxAutomaticAtomic = false;
190 * Track the write query callers of the current transaction
194 private $mTrxWriteCallers = [];
196 * @var float Seconds spent in write queries for the current transaction
198 private $mTrxWriteDuration = 0.0;
200 * @var int Number of write queries for the current transaction
202 private $mTrxWriteQueryCount = 0;
204 * @var int Number of rows affected by write queries for the current transaction
206 private $mTrxWriteAffectedRows = 0;
208 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
210 private $mTrxWriteAdjDuration = 0.0;
212 * @var int Number of write queries counted in mTrxWriteAdjDuration
214 private $mTrxWriteAdjQueryCount = 0;
216 * @var float RTT time estimate
218 private $mRTTEstimate = 0.0;
220 /** @var array Map of (name => 1) for locks obtained via lock() */
221 private $mNamedLocksHeld = [];
222 /** @var array Map of (table name => 1) for TEMPORARY tables */
223 protected $mSessionTempTables = [];
225 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
226 private $lazyMasterHandle;
228 /** @var float UNIX timestamp */
229 protected $lastPing = 0.0;
231 /** @var int[] Prior mFlags values */
232 private $priorFlags = [];
234 /** @var object|string Class name or object With profileIn/profileOut methods */
236 /** @var TransactionProfiler */
237 protected $trxProfiler;
240 * Constructor and database handle and attempt to connect to the DB server
242 * IDatabase classes should not be constructed directly in external
243 * code. Database::factory() should be used instead.
245 * @param array $params Parameters passed from Database::factory()
247 function __construct( array $params ) {
248 $server = $params['host'];
249 $user = $params['user'];
250 $password = $params['password'];
251 $dbName = $params['dbname'];
253 $this->mSchema
= $params['schema'];
254 $this->mTablePrefix
= $params['tablePrefix'];
256 $this->cliMode
= $params['cliMode'];
257 // Agent name is added to SQL queries in a comment, so make sure it can't break out
258 $this->agent
= str_replace( '/', '-', $params['agent'] );
260 $this->mFlags
= $params['flags'];
261 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~self
::DBO_TRX
;
265 $this->mFlags |
= self
::DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= $params['profiler'];
276 $this->trxProfiler
= $params['trxProfiler'];
277 $this->connLogger
= $params['connLogger'];
278 $this->queryLogger
= $params['queryLogger'];
279 $this->errorLogger
= $params['errorLogger'];
281 // Set initial dummy domain until open() sets the final DB/prefix
282 $this->currentDomain
= DatabaseDomain
::newUnspecified();
285 $this->open( $server, $user, $password, $dbName );
286 } elseif ( $this->requiresDatabaseUser() ) {
287 throw new InvalidArgumentException( "No database user provided." );
290 // Set the domain object after open() sets the relevant fields
291 if ( $this->mDBname
!= '' ) {
292 // Domains with server scope but a table prefix are not used by IDatabase classes
293 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
298 * Construct a Database subclass instance given a database type and parameters
300 * This also connects to the database immediately upon object construction
302 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
303 * @param array $p Parameter map with keys:
304 * - host : The hostname of the DB server
305 * - user : The name of the database user the client operates under
306 * - password : The password for the database user
307 * - dbname : The name of the database to use where queries do not specify one.
308 * The database must exist or an error might be thrown. Setting this to the empty string
309 * will avoid any such errors and make the handle have no implicit database scope. This is
310 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
311 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
312 * in which user names and such are defined, e.g. users are database-specific in Postgres.
313 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
314 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
315 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
316 * recognized in queries. This can be used in place of schemas for handle site farms.
317 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
318 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
319 * flag in place UNLESS this this database simply acts as a key/value store.
320 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
321 * 'mysql' driver and the newer 'mysqli' driver.
322 * - variables: Optional map of session variables to set after connecting. This can be
323 * used to adjust lock timeouts or encoding modes and the like.
324 * - connLogger: Optional PSR-3 logger interface instance.
325 * - queryLogger: Optional PSR-3 logger interface instance.
326 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
327 * These will be called in query(), using a simplified version of the SQL that also
328 * includes the agent as a SQL comment.
329 * - trxProfiler: Optional TransactionProfiler instance.
330 * - errorLogger: Optional callback that takes an Exception and logs it.
331 * - cliMode: Whether to consider the execution context that of a CLI script.
332 * - agent: Optional name used to identify the end-user in query profiling/logging.
333 * - srvCache: Optional BagOStuff instance to an APC-style cache.
334 * @return Database|null If the database driver or extension cannot be found
335 * @throws InvalidArgumentException If the database driver or extension cannot be found
338 final public static function factory( $dbType, $p = [] ) {
339 static $canonicalDBTypes = [
340 'mysql' => [ 'mysqli', 'mysql' ],
346 static $classAliases = [
347 'DatabaseMssql' => DatabaseMssql
::class,
348 'DatabaseMysql' => DatabaseMysql
::class,
349 'DatabaseMysqli' => DatabaseMysqli
::class,
350 'DatabaseSqlite' => DatabaseSqlite
::class,
351 'DatabasePostgres' => DatabasePostgres
::class
355 $dbType = strtolower( $dbType );
356 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
357 $possibleDrivers = $canonicalDBTypes[$dbType];
358 if ( !empty( $p['driver'] ) ) {
359 if ( in_array( $p['driver'], $possibleDrivers ) ) {
360 $driver = $p['driver'];
362 throw new InvalidArgumentException( __METHOD__
.
363 " type '$dbType' does not support driver '{$p['driver']}'" );
366 foreach ( $possibleDrivers as $posDriver ) {
367 if ( extension_loaded( $posDriver ) ) {
368 $driver = $posDriver;
377 if ( $driver === false ||
$driver === '' ) {
378 throw new InvalidArgumentException( __METHOD__
.
379 " no viable database extension found for type '$dbType'" );
382 $class = 'Database' . ucfirst( $driver );
383 if ( isset( $classAliases[$class] ) ) {
384 $class = $classAliases[$class];
387 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
388 // Resolve some defaults for b/c
389 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
390 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
391 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
392 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
393 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
394 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
395 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
396 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
397 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
398 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
399 if ( !isset( $p['connLogger'] ) ) {
400 $p['connLogger'] = new \Psr\Log\
NullLogger();
402 if ( !isset( $p['queryLogger'] ) ) {
403 $p['queryLogger'] = new \Psr\Log\
NullLogger();
405 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
406 if ( !isset( $p['trxProfiler'] ) ) {
407 $p['trxProfiler'] = new TransactionProfiler();
409 if ( !isset( $p['errorLogger'] ) ) {
410 $p['errorLogger'] = function ( Exception
$e ) {
411 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
415 $conn = new $class( $p );
424 * Set the PSR-3 logger interface to use for query logging. (The logger
425 * interfaces for connection logging and error logging can be set with the
428 * @param LoggerInterface $logger
430 public function setLogger( LoggerInterface
$logger ) {
431 $this->queryLogger
= $logger;
434 public function getServerInfo() {
435 return $this->getServerVersion();
438 public function bufferResults( $buffer = null ) {
439 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
440 if ( $buffer !== null ) {
442 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
443 : $this->setFlag( self
::DBO_NOBUFFER
);
450 * Turns on (false) or off (true) the automatic generation and sending
451 * of a "we're sorry, but there has been a database error" page on
452 * database errors. Default is on (false). When turned off, the
453 * code should use lastErrno() and lastError() to handle the
454 * situation as appropriate.
456 * Do not use this function outside of the Database classes.
458 * @param null|bool $ignoreErrors
459 * @return bool The previous value of the flag.
461 protected function ignoreErrors( $ignoreErrors = null ) {
462 $res = $this->getFlag( self
::DBO_IGNORE
);
463 if ( $ignoreErrors !== null ) {
465 ?
$this->setFlag( self
::DBO_IGNORE
)
466 : $this->clearFlag( self
::DBO_IGNORE
);
472 public function trxLevel() {
473 return $this->mTrxLevel
;
476 public function trxTimestamp() {
477 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
480 public function tablePrefix( $prefix = null ) {
481 $old = $this->mTablePrefix
;
482 if ( $prefix !== null ) {
483 $this->mTablePrefix
= $prefix;
484 $this->currentDomain
= ( $this->mDBname
!= '' )
485 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
486 : DatabaseDomain
::newUnspecified();
492 public function dbSchema( $schema = null ) {
493 $old = $this->mSchema
;
494 if ( $schema !== null ) {
495 $this->mSchema
= $schema;
501 public function getLBInfo( $name = null ) {
502 if ( is_null( $name ) ) {
503 return $this->mLBInfo
;
505 if ( array_key_exists( $name, $this->mLBInfo
) ) {
506 return $this->mLBInfo
[$name];
513 public function setLBInfo( $name, $value = null ) {
514 if ( is_null( $value ) ) {
515 $this->mLBInfo
= $name;
517 $this->mLBInfo
[$name] = $value;
521 public function setLazyMasterHandle( IDatabase
$conn ) {
522 $this->lazyMasterHandle
= $conn;
526 * @return IDatabase|null
527 * @see setLazyMasterHandle()
530 protected function getLazyMasterHandle() {
531 return $this->lazyMasterHandle
;
534 public function implicitGroupby() {
538 public function implicitOrderby() {
542 public function lastQuery() {
543 return $this->mLastQuery
;
546 public function doneWrites() {
547 return (bool)$this->mLastWriteTime
;
550 public function lastDoneWrites() {
551 return $this->mLastWriteTime ?
: false;
554 public function writesPending() {
555 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
558 public function writesOrCallbacksPending() {
559 return $this->mTrxLevel
&& (
560 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
564 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
565 if ( !$this->mTrxLevel
) {
567 } elseif ( !$this->mTrxDoneWrites
) {
572 case self
::ESTIMATE_DB_APPLY
:
574 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
575 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
576 // For omitted queries, make them count as something at least
577 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
578 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
581 default: // everything
582 return $this->mTrxWriteDuration
;
586 public function pendingWriteCallers() {
587 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
590 public function pendingWriteRowsAffected() {
591 return $this->mTrxWriteAffectedRows
;
595 * Get the list of method names that have pending write queries or callbacks
596 * for this transaction
600 protected function pendingWriteAndCallbackCallers() {
601 if ( !$this->mTrxLevel
) {
605 $fnames = $this->mTrxWriteCallers
;
607 $this->mTrxIdleCallbacks
,
608 $this->mTrxPreCommitCallbacks
,
609 $this->mTrxEndCallbacks
611 foreach ( $callbacks as $callback ) {
612 $fnames[] = $callback[1];
619 public function isOpen() {
620 return $this->mOpened
;
623 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
624 if ( $remember === self
::REMEMBER_PRIOR
) {
625 array_push( $this->priorFlags
, $this->mFlags
);
627 $this->mFlags |
= $flag;
630 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
631 if ( $remember === self
::REMEMBER_PRIOR
) {
632 array_push( $this->priorFlags
, $this->mFlags
);
634 $this->mFlags
&= ~
$flag;
637 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
638 if ( !$this->priorFlags
) {
642 if ( $state === self
::RESTORE_INITIAL
) {
643 $this->mFlags
= reset( $this->priorFlags
);
644 $this->priorFlags
= [];
646 $this->mFlags
= array_pop( $this->priorFlags
);
650 public function getFlag( $flag ) {
651 return !!( $this->mFlags
& $flag );
655 * @param string $name Class field name
657 * @deprecated Since 1.28
659 public function getProperty( $name ) {
663 public function getDomainID() {
664 return $this->currentDomain
->getId();
667 final public function getWikiID() {
668 return $this->getDomainID();
672 * Get information about an index into an object
673 * @param string $table Table name
674 * @param string $index Index name
675 * @param string $fname Calling function name
676 * @return mixed Database-specific index description class or false if the index does not exist
678 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
681 * Wrapper for addslashes()
683 * @param string $s String to be slashed.
684 * @return string Slashed string.
686 abstract function strencode( $s );
689 * Set a custom error handler for logging errors during database connection
691 protected function installErrorHandler() {
692 $this->mPHPError
= false;
693 $this->htmlErrors
= ini_set( 'html_errors', '0' );
694 set_error_handler( [ $this, 'connectionErrorLogger' ] );
698 * Restore the previous error handler and return the last PHP error for this DB
700 * @return bool|string
702 protected function restoreErrorHandler() {
703 restore_error_handler();
704 if ( $this->htmlErrors
!== false ) {
705 ini_set( 'html_errors', $this->htmlErrors
);
708 return $this->getLastPHPError();
712 * @return string|bool Last PHP error for this DB (typically connection errors)
714 protected function getLastPHPError() {
715 if ( $this->mPHPError
) {
716 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
717 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
726 * Error handler for logging errors during database connection
727 * This method should not be used outside of Database classes
730 * @param string $errstr
732 public function connectionErrorLogger( $errno, $errstr ) {
733 $this->mPHPError
= $errstr;
737 * Create a log context to pass to PSR-3 logger functions.
739 * @param array $extras Additional data to add to context
742 protected function getLogContext( array $extras = [] ) {
745 'db_server' => $this->mServer
,
746 'db_name' => $this->mDBname
,
747 'db_user' => $this->mUser
,
753 public function close() {
754 if ( $this->mConn
) {
755 if ( $this->trxLevel() ) {
756 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
759 $closed = $this->closeConnection();
760 $this->mConn
= false;
762 $this->mTrxIdleCallbacks ||
763 $this->mTrxPreCommitCallbacks ||
764 $this->mTrxEndCallbacks
766 throw new RuntimeException( "Transaction callbacks still pending." );
770 $this->mOpened
= false;
776 * Make sure isOpen() returns true as a sanity check
778 * @throws DBUnexpectedError
780 protected function assertOpen() {
781 if ( !$this->isOpen() ) {
782 throw new DBUnexpectedError( $this, "DB connection was already closed." );
787 * Closes underlying database connection
789 * @return bool Whether connection was closed successfully
791 abstract protected function closeConnection();
793 public function reportConnectionError( $error = 'Unknown error' ) {
794 $myError = $this->lastError();
800 throw new DBConnectionError( $this, $error );
804 * The DBMS-dependent part of query()
806 * @param string $sql SQL query.
807 * @return ResultWrapper|bool Result object to feed to fetchObject,
808 * fetchRow, ...; or false on failure
810 abstract protected function doQuery( $sql );
813 * Determine whether a query writes to the DB.
814 * Should return true if unsure.
819 protected function isWriteQuery( $sql ) {
821 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
826 * @return string|null
828 protected function getQueryVerb( $sql ) {
829 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
833 * Determine whether a SQL statement is sensitive to isolation level.
834 * A SQL statement is considered transactable if its result could vary
835 * depending on the transaction isolation level. Operational commands
836 * such as 'SET' and 'SHOW' are not considered to be transactable.
841 protected function isTransactableQuery( $sql ) {
843 $this->getQueryVerb( $sql ),
844 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
850 * @param string $sql A SQL query
851 * @return bool Whether $sql is SQL for TEMPORARY table operation
853 protected function registerTempTableOperation( $sql ) {
855 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
859 $this->mSessionTempTables
[$matches[1]] = 1;
862 } elseif ( preg_match(
863 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
867 $isTemp = isset( $this->mSessionTempTables
[$matches[1]] );
868 unset( $this->mSessionTempTables
[$matches[1]] );
871 } elseif ( preg_match(
872 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
876 return isset( $this->mSessionTempTables
[$matches[1]] );
877 } elseif ( preg_match(
878 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
882 return isset( $this->mSessionTempTables
[$matches[1]] );
888 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
889 $priorWritesPending = $this->writesOrCallbacksPending();
890 $this->mLastQuery
= $sql;
892 $isWrite = $this->isWriteQuery( $sql );
894 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
896 $isNonTempWrite = false;
900 # In theory, non-persistent writes are allowed in read-only mode, but due to things
901 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
902 $reason = $this->getReadOnlyReason();
903 if ( $reason !== false ) {
904 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
906 # Set a flag indicating that writes have been done
907 $this->mLastWriteTime
= microtime( true );
910 # Add trace comment to the begin of the sql string, right after the operator.
911 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
912 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
914 # Start implicit transactions that wrap the request if DBO_TRX is enabled
915 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
916 && $this->isTransactableQuery( $sql )
918 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
919 $this->mTrxAutomatic
= true;
922 # Keep track of whether the transaction has write queries pending
923 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
924 $this->mTrxDoneWrites
= true;
925 $this->trxProfiler
->transactionWritingIn(
926 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
929 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
930 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
933 # Avoid fatals if close() was called
936 # Send the query to the server
937 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
939 # Try reconnecting if the connection was lost
940 if ( false === $ret && $this->wasErrorReissuable() ) {
941 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
942 # Stash the last error values before anything might clear them
943 $lastError = $this->lastError();
944 $lastErrno = $this->lastErrno();
945 # Update state tracking to reflect transaction loss due to disconnection
946 $this->handleSessionLoss();
947 if ( $this->reconnect() ) {
948 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
949 $this->connLogger
->warning( $msg );
950 $this->queryLogger
->warning(
951 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
953 if ( !$recoverable ) {
954 # Callers may catch the exception and continue to use the DB
955 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
957 # Should be safe to silently retry the query
958 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
961 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
962 $this->connLogger
->error( $msg );
966 if ( false === $ret ) {
967 # Deadlocks cause the entire transaction to abort, not just the statement.
968 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
969 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
970 if ( $this->wasDeadlock() ) {
971 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
972 $tempIgnore = false; // not recoverable
974 # Update state tracking to reflect transaction loss
975 $this->handleSessionLoss();
978 $this->reportQueryError(
979 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
982 $res = $this->resultObject( $ret );
988 * Helper method for query() that handles profiling and logging and sends
989 * the query to doQuery()
991 * @param string $sql Original SQL query
992 * @param string $commentedSql SQL query with debugging/trace comment
993 * @param bool $isWrite Whether the query is a (non-temporary) write operation
994 * @param string $fname Name of the calling function
995 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
996 * object for a successful read query, or false on failure
998 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
999 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1000 # generalizeSQL() will probably cut down the query to reasonable
1001 # logging size most of the time. The substr is really just a sanity check.
1003 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1005 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1008 # Include query transaction state
1009 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1011 $startTime = microtime( true );
1012 if ( $this->profiler
) {
1013 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1015 $ret = $this->doQuery( $commentedSql );
1016 if ( $this->profiler
) {
1017 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1019 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1021 unset( $queryProfSection ); // profile out (if set)
1023 if ( $ret !== false ) {
1024 $this->lastPing
= $startTime;
1025 if ( $isWrite && $this->mTrxLevel
) {
1026 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1027 $this->mTrxWriteCallers
[] = $fname;
1031 if ( $sql === self
::PING_QUERY
) {
1032 $this->mRTTEstimate
= $queryRuntime;
1035 $this->trxProfiler
->recordQueryCompletion(
1036 $queryProf, $startTime, $isWrite, $this->affectedRows()
1038 $this->queryLogger
->debug( $sql, [
1040 'master' => $isMaster,
1041 'runtime' => $queryRuntime,
1048 * Update the estimated run-time of a query, not counting large row lock times
1050 * LoadBalancer can be set to rollback transactions that will create huge replication
1051 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1052 * queries, like inserting a row can take a long time due to row locking. This method
1053 * uses some simple heuristics to discount those cases.
1055 * @param string $sql A SQL write query
1056 * @param float $runtime Total runtime, including RTT
1057 * @param int $affected Affected row count
1059 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1060 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1061 $indicativeOfReplicaRuntime = true;
1062 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1063 $verb = $this->getQueryVerb( $sql );
1064 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1065 if ( $verb === 'INSERT' ) {
1066 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1067 } elseif ( $verb === 'REPLACE' ) {
1068 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1072 $this->mTrxWriteDuration +
= $runtime;
1073 $this->mTrxWriteQueryCount +
= 1;
1074 $this->mTrxWriteAffectedRows +
= $affected;
1075 if ( $indicativeOfReplicaRuntime ) {
1076 $this->mTrxWriteAdjDuration +
= $runtime;
1077 $this->mTrxWriteAdjQueryCount +
= 1;
1082 * Determine whether or not it is safe to retry queries after a database
1083 * connection is lost
1085 * @param string $sql SQL query
1086 * @param bool $priorWritesPending Whether there is a transaction open with
1087 * possible write queries or transaction pre-commit/idle callbacks
1088 * waiting on it to finish.
1089 * @return bool True if it is safe to retry the query, false otherwise
1091 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1092 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1093 # Dropped connections also mean that named locks are automatically released.
1094 # Only allow error suppression in autocommit mode or when the lost transaction
1095 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1096 if ( $this->mNamedLocksHeld
) {
1097 return false; // possible critical section violation
1098 } elseif ( $sql === 'COMMIT' ) {
1099 return !$priorWritesPending; // nothing written anyway? (T127428)
1100 } elseif ( $sql === 'ROLLBACK' ) {
1101 return true; // transaction lost...which is also what was requested :)
1102 } elseif ( $this->explicitTrxActive() ) {
1103 return false; // don't drop atomocity
1104 } elseif ( $priorWritesPending ) {
1105 return false; // prior writes lost from implicit transaction
1112 * Clean things up after transaction loss due to disconnection
1114 * @return null|Exception
1116 private function handleSessionLoss() {
1117 $this->mTrxLevel
= 0;
1118 $this->mTrxIdleCallbacks
= []; // T67263
1119 $this->mTrxPreCommitCallbacks
= []; // T67263
1120 $this->mSessionTempTables
= [];
1121 $this->mNamedLocksHeld
= [];
1123 // Handle callbacks in mTrxEndCallbacks
1124 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1125 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1127 } catch ( Exception
$e ) {
1128 // Already logged; move on...
1134 * Checks whether the cause of the error is detected to be a timeout.
1136 * It returns false by default, and not all engines support detecting this yet.
1137 * If this returns false, it will be treated as a generic query error.
1139 * @param string $error Error text
1140 * @param int $errno Error number
1143 protected function wasQueryTimeout( $error, $errno ) {
1147 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1148 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1149 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1151 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1152 $this->queryLogger
->error(
1153 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1154 $this->getLogContext( [
1155 'method' => __METHOD__
,
1158 'sql1line' => $sql1line,
1162 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1163 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1164 if ( $wasQueryTimeout ) {
1165 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1167 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1172 public function freeResult( $res ) {
1175 public function selectField(
1176 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1178 if ( $var === '*' ) { // sanity
1179 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1182 if ( !is_array( $options ) ) {
1183 $options = [ $options ];
1186 $options['LIMIT'] = 1;
1188 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1189 if ( $res === false ||
!$this->numRows( $res ) ) {
1193 $row = $this->fetchRow( $res );
1195 if ( $row !== false ) {
1196 return reset( $row );
1202 public function selectFieldValues(
1203 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1205 if ( $var === '*' ) { // sanity
1206 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1207 } elseif ( !is_string( $var ) ) { // sanity
1208 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1211 if ( !is_array( $options ) ) {
1212 $options = [ $options ];
1215 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1216 if ( $res === false ) {
1221 foreach ( $res as $row ) {
1222 $values[] = $row->$var;
1229 * Returns an optional USE INDEX clause to go after the table, and a
1230 * string to go at the end of the query.
1232 * @param array $options Associative array of options to be turned into
1233 * an SQL query, valid keys are listed in the function.
1235 * @see Database::select()
1237 protected function makeSelectOptions( $options ) {
1238 $preLimitTail = $postLimitTail = '';
1243 foreach ( $options as $key => $option ) {
1244 if ( is_numeric( $key ) ) {
1245 $noKeyOptions[$option] = true;
1249 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1251 $preLimitTail .= $this->makeOrderBy( $options );
1253 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1254 $postLimitTail .= ' FOR UPDATE';
1257 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1258 $postLimitTail .= ' LOCK IN SHARE MODE';
1261 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1262 $startOpts .= 'DISTINCT';
1265 # Various MySQL extensions
1266 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1267 $startOpts .= ' /*! STRAIGHT_JOIN */';
1270 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1271 $startOpts .= ' HIGH_PRIORITY';
1274 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1275 $startOpts .= ' SQL_BIG_RESULT';
1278 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1279 $startOpts .= ' SQL_BUFFER_RESULT';
1282 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1283 $startOpts .= ' SQL_SMALL_RESULT';
1286 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1287 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1290 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1291 $startOpts .= ' SQL_CACHE';
1294 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1295 $startOpts .= ' SQL_NO_CACHE';
1298 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1299 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1303 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1304 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1309 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1313 * Returns an optional GROUP BY with an optional HAVING
1315 * @param array $options Associative array of options
1317 * @see Database::select()
1320 protected function makeGroupByWithHaving( $options ) {
1322 if ( isset( $options['GROUP BY'] ) ) {
1323 $gb = is_array( $options['GROUP BY'] )
1324 ?
implode( ',', $options['GROUP BY'] )
1325 : $options['GROUP BY'];
1326 $sql .= ' GROUP BY ' . $gb;
1328 if ( isset( $options['HAVING'] ) ) {
1329 $having = is_array( $options['HAVING'] )
1330 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1331 : $options['HAVING'];
1332 $sql .= ' HAVING ' . $having;
1339 * Returns an optional ORDER BY
1341 * @param array $options Associative array of options
1343 * @see Database::select()
1346 protected function makeOrderBy( $options ) {
1347 if ( isset( $options['ORDER BY'] ) ) {
1348 $ob = is_array( $options['ORDER BY'] )
1349 ?
implode( ',', $options['ORDER BY'] )
1350 : $options['ORDER BY'];
1352 return ' ORDER BY ' . $ob;
1358 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1359 $options = [], $join_conds = [] ) {
1360 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1362 return $this->query( $sql, $fname );
1365 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1366 $options = [], $join_conds = []
1368 if ( is_array( $vars ) ) {
1369 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1372 $options = (array)$options;
1373 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1374 ?
$options['USE INDEX']
1377 isset( $options['IGNORE INDEX'] ) &&
1378 is_array( $options['IGNORE INDEX'] )
1380 ?
$options['IGNORE INDEX']
1383 if ( is_array( $table ) ) {
1385 $this->tableNamesWithIndexClauseOrJOIN(
1386 $table, $useIndexes, $ignoreIndexes, $join_conds );
1387 } elseif ( $table != '' ) {
1388 if ( $table[0] == ' ' ) {
1389 $from = ' FROM ' . $table;
1392 $this->tableNamesWithIndexClauseOrJOIN(
1393 [ $table ], $useIndexes, $ignoreIndexes, [] );
1399 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1400 $this->makeSelectOptions( $options );
1402 if ( !empty( $conds ) ) {
1403 if ( is_array( $conds ) ) {
1404 $conds = $this->makeList( $conds, self
::LIST_AND
);
1406 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1407 "WHERE $conds $preLimitTail";
1409 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1412 if ( isset( $options['LIMIT'] ) ) {
1413 $sql = $this->limitResult( $sql, $options['LIMIT'],
1414 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1416 $sql = "$sql $postLimitTail";
1418 if ( isset( $options['EXPLAIN'] ) ) {
1419 $sql = 'EXPLAIN ' . $sql;
1425 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1426 $options = [], $join_conds = []
1428 $options = (array)$options;
1429 $options['LIMIT'] = 1;
1430 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1432 if ( $res === false ) {
1436 if ( !$this->numRows( $res ) ) {
1440 $obj = $this->fetchObject( $res );
1445 public function estimateRowCount(
1446 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1449 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1452 $row = $this->fetchRow( $res );
1453 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1459 public function selectRowCount(
1460 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1463 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1464 // The identifier quotes is primarily for MSSQL.
1465 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1466 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1467 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1470 $row = $this->fetchRow( $res );
1471 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1478 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1479 * It's only slightly flawed. Don't use for anything important.
1481 * @param string $sql A SQL Query
1485 protected static function generalizeSQL( $sql ) {
1486 # This does the same as the regexp below would do, but in such a way
1487 # as to avoid crashing php on some large strings.
1488 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1490 $sql = str_replace( "\\\\", '', $sql );
1491 $sql = str_replace( "\\'", '', $sql );
1492 $sql = str_replace( "\\\"", '', $sql );
1493 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1494 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1496 # All newlines, tabs, etc replaced by single space
1497 $sql = preg_replace( '/\s+/', ' ', $sql );
1500 # except the ones surrounded by characters, e.g. l10n
1501 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1502 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1507 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1508 $info = $this->fieldInfo( $table, $field );
1513 public function indexExists( $table, $index, $fname = __METHOD__
) {
1514 if ( !$this->tableExists( $table ) ) {
1518 $info = $this->indexInfo( $table, $index, $fname );
1519 if ( is_null( $info ) ) {
1522 return $info !== false;
1526 public function tableExists( $table, $fname = __METHOD__
) {
1527 $tableRaw = $this->tableName( $table, 'raw' );
1528 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1529 return true; // already known to exist
1532 $table = $this->tableName( $table );
1533 $ignoreErrors = true;
1534 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1539 public function indexUnique( $table, $index ) {
1540 $indexInfo = $this->indexInfo( $table, $index );
1542 if ( !$indexInfo ) {
1546 return !$indexInfo[0]->Non_unique
;
1550 * Helper for Database::insert().
1552 * @param array $options
1555 protected function makeInsertOptions( $options ) {
1556 return implode( ' ', $options );
1559 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1560 # No rows to insert, easy just return now
1561 if ( !count( $a ) ) {
1565 $table = $this->tableName( $table );
1567 if ( !is_array( $options ) ) {
1568 $options = [ $options ];
1572 if ( isset( $options['fileHandle'] ) ) {
1573 $fh = $options['fileHandle'];
1575 $options = $this->makeInsertOptions( $options );
1577 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1579 $keys = array_keys( $a[0] );
1582 $keys = array_keys( $a );
1585 $sql = 'INSERT ' . $options .
1586 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1590 foreach ( $a as $row ) {
1596 $sql .= '(' . $this->makeList( $row ) . ')';
1599 $sql .= '(' . $this->makeList( $a ) . ')';
1602 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1604 } elseif ( $fh !== null ) {
1608 return (bool)$this->query( $sql, $fname );
1612 * Make UPDATE options array for Database::makeUpdateOptions
1614 * @param array $options
1617 protected function makeUpdateOptionsArray( $options ) {
1618 if ( !is_array( $options ) ) {
1619 $options = [ $options ];
1624 if ( in_array( 'IGNORE', $options ) ) {
1632 * Make UPDATE options for the Database::update function
1634 * @param array $options The options passed to Database::update
1637 protected function makeUpdateOptions( $options ) {
1638 $opts = $this->makeUpdateOptionsArray( $options );
1640 return implode( ' ', $opts );
1643 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1644 $table = $this->tableName( $table );
1645 $opts = $this->makeUpdateOptions( $options );
1646 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1648 if ( $conds !== [] && $conds !== '*' ) {
1649 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1652 return (bool)$this->query( $sql, $fname );
1655 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1656 if ( !is_array( $a ) ) {
1657 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1663 foreach ( $a as $field => $value ) {
1665 if ( $mode == self
::LIST_AND
) {
1667 } elseif ( $mode == self
::LIST_OR
) {
1676 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1677 $list .= "($value)";
1678 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1681 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1683 // Remove null from array to be handled separately if found
1684 $includeNull = false;
1685 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1686 $includeNull = true;
1687 unset( $value[$nullKey] );
1689 if ( count( $value ) == 0 && !$includeNull ) {
1690 throw new InvalidArgumentException(
1691 __METHOD__
. ": empty input for field $field" );
1692 } elseif ( count( $value ) == 0 ) {
1693 // only check if $field is null
1694 $list .= "$field IS NULL";
1696 // IN clause contains at least one valid element
1697 if ( $includeNull ) {
1698 // Group subconditions to ensure correct precedence
1701 if ( count( $value ) == 1 ) {
1702 // Special-case single values, as IN isn't terribly efficient
1703 // Don't necessarily assume the single key is 0; we don't
1704 // enforce linear numeric ordering on other arrays here.
1705 $value = array_values( $value )[0];
1706 $list .= $field . " = " . $this->addQuotes( $value );
1708 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1710 // if null present in array, append IS NULL
1711 if ( $includeNull ) {
1712 $list .= " OR $field IS NULL)";
1715 } elseif ( $value === null ) {
1716 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1717 $list .= "$field IS ";
1718 } elseif ( $mode == self
::LIST_SET
) {
1719 $list .= "$field = ";
1724 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1726 $list .= "$field = ";
1728 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1735 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1738 foreach ( $data as $base => $sub ) {
1739 if ( count( $sub ) ) {
1740 $conds[] = $this->makeList(
1741 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1747 return $this->makeList( $conds, self
::LIST_OR
);
1749 // Nothing to search for...
1754 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1758 public function bitNot( $field ) {
1762 public function bitAnd( $fieldLeft, $fieldRight ) {
1763 return "($fieldLeft & $fieldRight)";
1766 public function bitOr( $fieldLeft, $fieldRight ) {
1767 return "($fieldLeft | $fieldRight)";
1770 public function buildConcat( $stringList ) {
1771 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1774 public function buildGroupConcatField(
1775 $delim, $table, $field, $conds = '', $join_conds = []
1777 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1779 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1782 public function buildStringCast( $field ) {
1786 public function databasesAreIndependent() {
1790 public function selectDB( $db ) {
1791 # Stub. Shouldn't cause serious problems if it's not overridden, but
1792 # if your database engine supports a concept similar to MySQL's
1793 # databases you may as well.
1794 $this->mDBname
= $db;
1799 public function getDBname() {
1800 return $this->mDBname
;
1803 public function getServer() {
1804 return $this->mServer
;
1807 public function tableName( $name, $format = 'quoted' ) {
1808 # Skip the entire process when we have a string quoted on both ends.
1809 # Note that we check the end so that we will still quote any use of
1810 # use of `database`.table. But won't break things if someone wants
1811 # to query a database table with a dot in the name.
1812 if ( $this->isQuotedIdentifier( $name ) ) {
1816 # Lets test for any bits of text that should never show up in a table
1817 # name. Basically anything like JOIN or ON which are actually part of
1818 # SQL queries, but may end up inside of the table value to combine
1819 # sql. Such as how the API is doing.
1820 # Note that we use a whitespace test rather than a \b test to avoid
1821 # any remote case where a word like on may be inside of a table name
1822 # surrounded by symbols which may be considered word breaks.
1823 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1827 # Split database and table into proper variables.
1828 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1830 # Quote $table and apply the prefix if not quoted.
1831 # $tableName might be empty if this is called from Database::replaceVars()
1832 $tableName = "{$prefix}{$table}";
1833 if ( $format === 'quoted'
1834 && !$this->isQuotedIdentifier( $tableName )
1835 && $tableName !== ''
1837 $tableName = $this->addIdentifierQuotes( $tableName );
1840 # Quote $schema and $database and merge them with the table name if needed
1841 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1842 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1848 * Get the table components needed for a query given the currently selected database
1850 * @param string $name Table name in the form of db.schema.table, db.table, or table
1851 * @return array (DB name or "" for default, schema name, table prefix, table name)
1853 protected function qualifiedTableComponents( $name ) {
1854 # We reverse the explode so that database.table and table both output the correct table.
1855 $dbDetails = explode( '.', $name, 3 );
1856 if ( count( $dbDetails ) == 3 ) {
1857 list( $database, $schema, $table ) = $dbDetails;
1858 # We don't want any prefix added in this case
1860 } elseif ( count( $dbDetails ) == 2 ) {
1861 list( $database, $table ) = $dbDetails;
1862 # We don't want any prefix added in this case
1864 # In dbs that support it, $database may actually be the schema
1865 # but that doesn't affect any of the functionality here
1868 list( $table ) = $dbDetails;
1869 if ( isset( $this->tableAliases
[$table] ) ) {
1870 $database = $this->tableAliases
[$table]['dbname'];
1871 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1872 ?
$this->tableAliases
[$table]['schema']
1874 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1875 ?
$this->tableAliases
[$table]['prefix']
1876 : $this->mTablePrefix
;
1879 $schema = $this->mSchema
; # Default schema
1880 $prefix = $this->mTablePrefix
; # Default prefix
1884 return [ $database, $schema, $prefix, $table ];
1888 * @param string|null $namespace Database or schema
1889 * @param string $relation Name of table, view, sequence, etc...
1890 * @param string $format One of (raw, quoted)
1891 * @return string Relation name with quoted and merged $namespace as needed
1893 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1894 if ( strlen( $namespace ) ) {
1895 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1896 $namespace = $this->addIdentifierQuotes( $namespace );
1898 $relation = $namespace . '.' . $relation;
1904 public function tableNames() {
1905 $inArray = func_get_args();
1908 foreach ( $inArray as $name ) {
1909 $retVal[$name] = $this->tableName( $name );
1915 public function tableNamesN() {
1916 $inArray = func_get_args();
1919 foreach ( $inArray as $name ) {
1920 $retVal[] = $this->tableName( $name );
1927 * Get an aliased table name
1928 * e.g. tableName AS newTableName
1930 * @param string $name Table name, see tableName()
1931 * @param string|bool $alias Alias (optional)
1932 * @return string SQL name for aliased table. Will not alias a table to its own name
1934 protected function tableNameWithAlias( $name, $alias = false ) {
1935 if ( !$alias ||
$alias == $name ) {
1936 return $this->tableName( $name );
1938 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1943 * Gets an array of aliased table names
1945 * @param array $tables [ [alias] => table ]
1946 * @return string[] See tableNameWithAlias()
1948 protected function tableNamesWithAlias( $tables ) {
1950 foreach ( $tables as $alias => $table ) {
1951 if ( is_numeric( $alias ) ) {
1954 $retval[] = $this->tableNameWithAlias( $table, $alias );
1961 * Get an aliased field name
1962 * e.g. fieldName AS newFieldName
1964 * @param string $name Field name
1965 * @param string|bool $alias Alias (optional)
1966 * @return string SQL name for aliased field. Will not alias a field to its own name
1968 protected function fieldNameWithAlias( $name, $alias = false ) {
1969 if ( !$alias ||
(string)$alias === (string)$name ) {
1972 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1977 * Gets an array of aliased field names
1979 * @param array $fields [ [alias] => field ]
1980 * @return string[] See fieldNameWithAlias()
1982 protected function fieldNamesWithAlias( $fields ) {
1984 foreach ( $fields as $alias => $field ) {
1985 if ( is_numeric( $alias ) ) {
1988 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1995 * Get the aliased table name clause for a FROM clause
1996 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1998 * @param array $tables ( [alias] => table )
1999 * @param array $use_index Same as for select()
2000 * @param array $ignore_index Same as for select()
2001 * @param array $join_conds Same as for select()
2004 protected function tableNamesWithIndexClauseOrJOIN(
2005 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2009 $use_index = (array)$use_index;
2010 $ignore_index = (array)$ignore_index;
2011 $join_conds = (array)$join_conds;
2013 foreach ( $tables as $alias => $table ) {
2014 if ( !is_string( $alias ) ) {
2015 // No alias? Set it equal to the table name
2019 if ( is_array( $table ) ) {
2020 // A parenthesized group
2022 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2025 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2028 // Is there a JOIN clause for this table?
2029 if ( isset( $join_conds[$alias] ) ) {
2030 list( $joinType, $conds ) = $join_conds[$alias];
2031 $tableClause = $joinType;
2032 $tableClause .= ' ' . $joinedTable;
2033 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2034 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2036 $tableClause .= ' ' . $use;
2039 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2040 $ignore = $this->ignoreIndexClause(
2041 implode( ',', (array)$ignore_index[$alias] ) );
2042 if ( $ignore != '' ) {
2043 $tableClause .= ' ' . $ignore;
2046 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2048 $tableClause .= ' ON (' . $on . ')';
2051 $retJOIN[] = $tableClause;
2052 } elseif ( isset( $use_index[$alias] ) ) {
2053 // Is there an INDEX clause for this table?
2054 $tableClause = $joinedTable;
2055 $tableClause .= ' ' . $this->useIndexClause(
2056 implode( ',', (array)$use_index[$alias] )
2059 $ret[] = $tableClause;
2060 } elseif ( isset( $ignore_index[$alias] ) ) {
2061 // Is there an INDEX clause for this table?
2062 $tableClause = $joinedTable;
2063 $tableClause .= ' ' . $this->ignoreIndexClause(
2064 implode( ',', (array)$ignore_index[$alias] )
2067 $ret[] = $tableClause;
2069 $tableClause = $joinedTable;
2071 $ret[] = $tableClause;
2075 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2076 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2077 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2079 // Compile our final table clause
2080 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2084 * Allows for index remapping in queries where this is not consistent across DBMS
2086 * @param string $index
2089 protected function indexName( $index ) {
2093 public function addQuotes( $s ) {
2094 if ( $s instanceof Blob
) {
2097 if ( $s === null ) {
2099 } elseif ( is_bool( $s ) ) {
2102 # This will also quote numeric values. This should be harmless,
2103 # and protects against weird problems that occur when they really
2104 # _are_ strings such as article titles and string->number->string
2105 # conversion is not 1:1.
2106 return "'" . $this->strencode( $s ) . "'";
2111 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2112 * MySQL uses `backticks` while basically everything else uses double quotes.
2113 * Since MySQL is the odd one out here the double quotes are our generic
2114 * and we implement backticks in DatabaseMysqlBase.
2119 public function addIdentifierQuotes( $s ) {
2120 return '"' . str_replace( '"', '""', $s ) . '"';
2124 * Returns if the given identifier looks quoted or not according to
2125 * the database convention for quoting identifiers .
2127 * @note Do not use this to determine if untrusted input is safe.
2128 * A malicious user can trick this function.
2129 * @param string $name
2132 public function isQuotedIdentifier( $name ) {
2133 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2138 * @param string $escapeChar
2141 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2142 return str_replace( [ $escapeChar, '%', '_' ],
2143 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2147 public function buildLike() {
2148 $params = func_get_args();
2150 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2151 $params = $params[0];
2156 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2157 // may escape backslashes, creating problems of double escaping. The `
2158 // character has good cross-DBMS compatibility, avoiding special operators
2159 // in MS SQL like ^ and %
2162 foreach ( $params as $value ) {
2163 if ( $value instanceof LikeMatch
) {
2164 $s .= $value->toString();
2166 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2170 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2173 public function anyChar() {
2174 return new LikeMatch( '_' );
2177 public function anyString() {
2178 return new LikeMatch( '%' );
2181 public function nextSequenceValue( $seqName ) {
2186 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2187 * is only needed because a) MySQL must be as efficient as possible due to
2188 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2189 * which index to pick. Anyway, other databases might have different
2190 * indexes on a given table. So don't bother overriding this unless you're
2192 * @param string $index
2195 public function useIndexClause( $index ) {
2200 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2201 * is only needed because a) MySQL must be as efficient as possible due to
2202 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2203 * which index to pick. Anyway, other databases might have different
2204 * indexes on a given table. So don't bother overriding this unless you're
2206 * @param string $index
2209 public function ignoreIndexClause( $index ) {
2213 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2214 $quotedTable = $this->tableName( $table );
2216 if ( count( $rows ) == 0 ) {
2221 if ( !is_array( reset( $rows ) ) ) {
2225 // @FXIME: this is not atomic, but a trx would break affectedRows()
2226 foreach ( $rows as $row ) {
2227 # Delete rows which collide
2228 if ( $uniqueIndexes ) {
2229 $sql = "DELETE FROM $quotedTable WHERE ";
2231 foreach ( $uniqueIndexes as $index ) {
2238 if ( is_array( $index ) ) {
2240 foreach ( $index as $col ) {
2246 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2249 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2253 $this->query( $sql, $fname );
2256 # Now insert the row
2257 $this->insert( $table, $row, $fname );
2262 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2265 * @param string $table Table name
2266 * @param array|string $rows Row(s) to insert
2267 * @param string $fname Caller function name
2269 * @return ResultWrapper
2271 protected function nativeReplace( $table, $rows, $fname ) {
2272 $table = $this->tableName( $table );
2275 if ( !is_array( reset( $rows ) ) ) {
2279 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2282 foreach ( $rows as $row ) {
2289 $sql .= '(' . $this->makeList( $row ) . ')';
2292 return $this->query( $sql, $fname );
2295 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2298 if ( !count( $rows ) ) {
2299 return true; // nothing to do
2302 if ( !is_array( reset( $rows ) ) ) {
2306 if ( count( $uniqueIndexes ) ) {
2307 $clauses = []; // list WHERE clauses that each identify a single row
2308 foreach ( $rows as $row ) {
2309 foreach ( $uniqueIndexes as $index ) {
2310 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2311 $rowKey = []; // unique key to this row
2312 foreach ( $index as $column ) {
2313 $rowKey[$column] = $row[$column];
2315 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2318 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2323 $useTrx = !$this->mTrxLevel
;
2325 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2328 # Update any existing conflicting row(s)
2329 if ( $where !== false ) {
2330 $ok = $this->update( $table, $set, $where, $fname );
2334 # Now insert any non-conflicting row(s)
2335 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2336 } catch ( Exception
$e ) {
2338 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2343 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2349 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2353 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2356 $delTable = $this->tableName( $delTable );
2357 $joinTable = $this->tableName( $joinTable );
2358 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2359 if ( $conds != '*' ) {
2360 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2364 $this->query( $sql, $fname );
2367 public function textFieldSize( $table, $field ) {
2368 $table = $this->tableName( $table );
2369 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2370 $res = $this->query( $sql, __METHOD__
);
2371 $row = $this->fetchObject( $res );
2375 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2384 public function delete( $table, $conds, $fname = __METHOD__
) {
2386 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2389 $table = $this->tableName( $table );
2390 $sql = "DELETE FROM $table";
2392 if ( $conds != '*' ) {
2393 if ( is_array( $conds ) ) {
2394 $conds = $this->makeList( $conds, self
::LIST_AND
);
2396 $sql .= ' WHERE ' . $conds;
2399 return $this->query( $sql, $fname );
2402 public function insertSelect(
2403 $destTable, $srcTable, $varMap, $conds,
2404 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2406 if ( $this->cliMode
) {
2407 // For massive migrations with downtime, we don't want to select everything
2408 // into memory and OOM, so do all this native on the server side if possible.
2409 return $this->nativeInsertSelect(
2421 return $this->nonNativeInsertSelect(
2434 * Implementation of insertSelect() based on select() and insert()
2436 * @see IDatabase::insertSelect()
2438 * @param string $destTable
2439 * @param string|array $srcTable
2440 * @param array $varMap
2441 * @param array $conds
2442 * @param string $fname
2443 * @param array $insertOptions
2444 * @param array $selectOptions
2445 * @param array $selectJoinConds
2448 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2449 $fname = __METHOD__
,
2450 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2452 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2453 // on only the master (without needing row-based-replication). It also makes it easy to
2454 // know how big the INSERT is going to be.
2456 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2457 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2459 $selectOptions[] = 'FOR UPDATE';
2460 $res = $this->select(
2461 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2468 foreach ( $res as $row ) {
2469 $rows[] = (array)$row;
2472 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2476 * Native server-side implementation of insertSelect() for situations where
2477 * we don't want to select everything into memory
2479 * @see IDatabase::insertSelect()
2480 * @param string $destTable
2481 * @param string|array $srcTable
2482 * @param array $varMap
2483 * @param array $conds
2484 * @param string $fname
2485 * @param array $insertOptions
2486 * @param array $selectOptions
2487 * @param array $selectJoinConds
2490 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2491 $fname = __METHOD__
,
2492 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2494 $destTable = $this->tableName( $destTable );
2496 if ( !is_array( $insertOptions ) ) {
2497 $insertOptions = [ $insertOptions ];
2500 $insertOptions = $this->makeInsertOptions( $insertOptions );
2502 $selectSql = $this->selectSQLText(
2504 array_values( $varMap ),
2511 $sql = "INSERT $insertOptions" .
2512 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2515 return $this->query( $sql, $fname );
2519 * Construct a LIMIT query with optional offset. This is used for query
2520 * pages. The SQL should be adjusted so that only the first $limit rows
2521 * are returned. If $offset is provided as well, then the first $offset
2522 * rows should be discarded, and the next $limit rows should be returned.
2523 * If the result of the query is not ordered, then the rows to be returned
2524 * are theoretically arbitrary.
2526 * $sql is expected to be a SELECT, if that makes a difference.
2528 * The version provided by default works in MySQL and SQLite. It will very
2529 * likely need to be overridden for most other DBMSes.
2531 * @param string $sql SQL query we will append the limit too
2532 * @param int $limit The SQL limit
2533 * @param int|bool $offset The SQL offset (default false)
2534 * @throws DBUnexpectedError
2537 public function limitResult( $sql, $limit, $offset = false ) {
2538 if ( !is_numeric( $limit ) ) {
2539 throw new DBUnexpectedError( $this,
2540 "Invalid non-numeric limit passed to limitResult()\n" );
2543 return "$sql LIMIT "
2544 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2548 public function unionSupportsOrderAndLimit() {
2549 return true; // True for almost every DB supported
2552 public function unionQueries( $sqls, $all ) {
2553 $glue = $all ?
') UNION ALL (' : ') UNION (';
2555 return '(' . implode( $glue, $sqls ) . ')';
2558 public function unionConditionPermutations(
2559 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2560 $options = [], $join_conds = []
2562 // First, build the Cartesian product of $permute_conds
2564 foreach ( $permute_conds as $field => $values ) {
2566 // Skip empty $values
2569 $values = array_unique( $values ); // For sanity
2571 foreach ( $conds as $cond ) {
2572 foreach ( $values as $value ) {
2573 $cond[$field] = $value;
2574 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2580 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2582 // If there's just one condition and no subordering, hand off to
2583 // selectSQLText directly.
2584 if ( count( $conds ) === 1 &&
2585 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2587 return $this->selectSQLText(
2588 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2592 // Otherwise, we need to pull out the order and limit to apply after
2593 // the union. Then build the SQL queries for each set of conditions in
2594 // $conds. Then union them together (using UNION ALL, because the
2595 // product *should* already be distinct).
2596 $orderBy = $this->makeOrderBy( $options );
2597 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2598 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2599 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2600 if ( !$this->unionSupportsOrderAndLimit() ) {
2601 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2603 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2604 $options['ORDER BY'] = $options['INNER ORDER BY'];
2606 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2607 // We need to increase the limit by the offset rather than
2608 // using the offset directly, otherwise it'll skip incorrectly
2609 // in the subqueries.
2610 $options['LIMIT'] = $limit +
$offset;
2611 unset( $options['OFFSET'] );
2616 foreach ( $conds as $cond ) {
2617 $sqls[] = $this->selectSQLText(
2618 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2621 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2622 if ( $limit !== null ) {
2623 $sql = $this->limitResult( $sql, $limit, $offset );
2629 public function conditional( $cond, $trueVal, $falseVal ) {
2630 if ( is_array( $cond ) ) {
2631 $cond = $this->makeList( $cond, self
::LIST_AND
);
2634 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2637 public function strreplace( $orig, $old, $new ) {
2638 return "REPLACE({$orig}, {$old}, {$new})";
2641 public function getServerUptime() {
2645 public function wasDeadlock() {
2649 public function wasLockTimeout() {
2653 public function wasErrorReissuable() {
2657 public function wasReadOnlyError() {
2662 * Do not use this method outside of Database/DBError classes
2664 * @param int|string $errno
2665 * @return bool Whether the given query error was a connection drop
2667 public function wasConnectionError( $errno ) {
2671 public function deadlockLoop() {
2672 $args = func_get_args();
2673 $function = array_shift( $args );
2674 $tries = self
::DEADLOCK_TRIES
;
2676 $this->begin( __METHOD__
);
2679 /** @var Exception $e */
2683 $retVal = call_user_func_array( $function, $args );
2685 } catch ( DBQueryError
$e ) {
2686 if ( $this->wasDeadlock() ) {
2687 // Retry after a randomized delay
2688 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2690 // Throw the error back up
2694 } while ( --$tries > 0 );
2696 if ( $tries <= 0 ) {
2697 // Too many deadlocks; give up
2698 $this->rollback( __METHOD__
);
2701 $this->commit( __METHOD__
);
2707 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2708 # Real waits are implemented in the subclass.
2712 public function getReplicaPos() {
2717 public function getMasterPos() {
2722 public function serverIsReadOnly() {
2726 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2727 if ( !$this->mTrxLevel
) {
2728 throw new DBUnexpectedError( $this, "No transaction is active." );
2730 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2733 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2734 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2735 if ( !$this->mTrxLevel
) {
2736 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2740 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2741 if ( $this->mTrxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2742 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2743 // an implicit commit of all peer databases. This is true even if a transaction has
2744 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2745 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2747 // No transaction is active nor will start implicitly, so make one for this callback
2748 $this->startAtomic( __METHOD__
);
2750 call_user_func( $callback );
2751 $this->endAtomic( __METHOD__
);
2752 } catch ( Exception
$e ) {
2753 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2759 final public function setTransactionListener( $name, callable
$callback = null ) {
2761 $this->mTrxRecurringCallbacks
[$name] = $callback;
2763 unset( $this->mTrxRecurringCallbacks
[$name] );
2768 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2770 * This method should not be used outside of Database/LoadBalancer
2772 * @param bool $suppress
2775 final public function setTrxEndCallbackSuppression( $suppress ) {
2776 $this->mTrxEndCallbacksSuppressed
= $suppress;
2780 * Actually run and consume any "on transaction idle/resolution" callbacks.
2782 * This method should not be used outside of Database/LoadBalancer
2784 * @param int $trigger IDatabase::TRIGGER_* constant
2788 public function runOnTransactionIdleCallbacks( $trigger ) {
2789 if ( $this->mTrxEndCallbacksSuppressed
) {
2793 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2794 /** @var Exception $e */
2795 $e = null; // first exception
2796 do { // callbacks may add callbacks :)
2797 $callbacks = array_merge(
2798 $this->mTrxIdleCallbacks
,
2799 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2801 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2802 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2803 foreach ( $callbacks as $callback ) {
2805 list( $phpCallback ) = $callback;
2806 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2807 call_user_func_array( $phpCallback, [ $trigger ] );
2809 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2811 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2813 } catch ( Exception
$ex ) {
2814 call_user_func( $this->errorLogger
, $ex );
2816 // Some callbacks may use startAtomic/endAtomic, so make sure
2817 // their transactions are ended so other callbacks don't fail
2818 if ( $this->trxLevel() ) {
2819 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2823 } while ( count( $this->mTrxIdleCallbacks
) );
2825 if ( $e instanceof Exception
) {
2826 throw $e; // re-throw any first exception
2831 * Actually run and consume any "on transaction pre-commit" callbacks.
2833 * This method should not be used outside of Database/LoadBalancer
2838 public function runOnTransactionPreCommitCallbacks() {
2839 $e = null; // first exception
2840 do { // callbacks may add callbacks :)
2841 $callbacks = $this->mTrxPreCommitCallbacks
;
2842 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2843 foreach ( $callbacks as $callback ) {
2845 list( $phpCallback ) = $callback;
2846 call_user_func( $phpCallback );
2847 } catch ( Exception
$ex ) {
2848 call_user_func( $this->errorLogger
, $ex );
2852 } while ( count( $this->mTrxPreCommitCallbacks
) );
2854 if ( $e instanceof Exception
) {
2855 throw $e; // re-throw any first exception
2860 * Actually run any "transaction listener" callbacks.
2862 * This method should not be used outside of Database/LoadBalancer
2864 * @param int $trigger IDatabase::TRIGGER_* constant
2868 public function runTransactionListenerCallbacks( $trigger ) {
2869 if ( $this->mTrxEndCallbacksSuppressed
) {
2873 /** @var Exception $e */
2874 $e = null; // first exception
2876 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2878 $phpCallback( $trigger, $this );
2879 } catch ( Exception
$ex ) {
2880 call_user_func( $this->errorLogger
, $ex );
2885 if ( $e instanceof Exception
) {
2886 throw $e; // re-throw any first exception
2890 final public function startAtomic( $fname = __METHOD__
) {
2891 if ( !$this->mTrxLevel
) {
2892 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2893 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2894 // in all changes being in one transaction to keep requests transactional.
2895 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2896 $this->mTrxAutomaticAtomic
= true;
2900 $this->mTrxAtomicLevels
[] = $fname;
2903 final public function endAtomic( $fname = __METHOD__
) {
2904 if ( !$this->mTrxLevel
) {
2905 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2907 if ( !$this->mTrxAtomicLevels ||
2908 array_pop( $this->mTrxAtomicLevels
) !== $fname
2910 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2913 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2914 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2918 final public function doAtomicSection( $fname, callable
$callback ) {
2919 $this->startAtomic( $fname );
2921 $res = call_user_func_array( $callback, [ $this, $fname ] );
2922 } catch ( Exception
$e ) {
2923 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2926 $this->endAtomic( $fname );
2931 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2932 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2933 if ( $this->mTrxLevel
) {
2934 if ( $this->mTrxAtomicLevels
) {
2935 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2936 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2937 throw new DBUnexpectedError( $this, $msg );
2938 } elseif ( !$this->mTrxAutomatic
) {
2939 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2940 throw new DBUnexpectedError( $this, $msg );
2942 // @TODO: make this an exception at some point
2943 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2944 $this->queryLogger
->error( $msg );
2945 return; // join the main transaction set
2947 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2948 // @TODO: make this an exception at some point
2949 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2950 $this->queryLogger
->error( $msg );
2951 return; // let any writes be in the main transaction
2954 // Avoid fatals if close() was called
2955 $this->assertOpen();
2957 $this->doBegin( $fname );
2958 $this->mTrxTimestamp
= microtime( true );
2959 $this->mTrxFname
= $fname;
2960 $this->mTrxDoneWrites
= false;
2961 $this->mTrxAutomaticAtomic
= false;
2962 $this->mTrxAtomicLevels
= [];
2963 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2964 $this->mTrxWriteDuration
= 0.0;
2965 $this->mTrxWriteQueryCount
= 0;
2966 $this->mTrxWriteAffectedRows
= 0;
2967 $this->mTrxWriteAdjDuration
= 0.0;
2968 $this->mTrxWriteAdjQueryCount
= 0;
2969 $this->mTrxWriteCallers
= [];
2970 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2971 // Get an estimate of the replica DB lag before then, treating estimate staleness
2972 // as lag itself just to be safe
2973 $status = $this->getApproximateLagStatus();
2974 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2975 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2976 // caller will think its OK to muck around with the transaction just because startAtomic()
2977 // has not yet completed (e.g. setting mTrxAtomicLevels).
2978 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2982 * Issues the BEGIN command to the database server.
2984 * @see Database::begin()
2985 * @param string $fname
2987 protected function doBegin( $fname ) {
2988 $this->query( 'BEGIN', $fname );
2989 $this->mTrxLevel
= 1;
2992 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2993 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2994 // There are still atomic sections open. This cannot be ignored
2995 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2996 throw new DBUnexpectedError(
2998 "$fname: Got COMMIT while atomic sections $levels are still open."
3002 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3003 if ( !$this->mTrxLevel
) {
3004 return; // nothing to do
3005 } elseif ( !$this->mTrxAutomatic
) {
3006 throw new DBUnexpectedError(
3008 "$fname: Flushing an explicit transaction, getting out of sync."
3012 if ( !$this->mTrxLevel
) {
3013 $this->queryLogger
->error(
3014 "$fname: No transaction to commit, something got out of sync." );
3015 return; // nothing to do
3016 } elseif ( $this->mTrxAutomatic
) {
3017 // @TODO: make this an exception at some point
3018 $msg = "$fname: Explicit commit of implicit transaction.";
3019 $this->queryLogger
->error( $msg );
3020 return; // wait for the main transaction set commit round
3024 // Avoid fatals if close() was called
3025 $this->assertOpen();
3027 $this->runOnTransactionPreCommitCallbacks();
3028 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3029 $this->doCommit( $fname );
3030 if ( $this->mTrxDoneWrites
) {
3031 $this->mLastWriteTime
= microtime( true );
3032 $this->trxProfiler
->transactionWritingOut(
3037 $this->mTrxWriteAffectedRows
3041 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3042 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3046 * Issues the COMMIT command to the database server.
3048 * @see Database::commit()
3049 * @param string $fname
3051 protected function doCommit( $fname ) {
3052 if ( $this->mTrxLevel
) {
3053 $this->query( 'COMMIT', $fname );
3054 $this->mTrxLevel
= 0;
3058 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3059 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3060 if ( !$this->mTrxLevel
) {
3061 return; // nothing to do
3064 if ( !$this->mTrxLevel
) {
3065 $this->queryLogger
->error(
3066 "$fname: No transaction to rollback, something got out of sync." );
3067 return; // nothing to do
3068 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3069 throw new DBUnexpectedError(
3071 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3076 // Avoid fatals if close() was called
3077 $this->assertOpen();
3079 $this->doRollback( $fname );
3080 $this->mTrxAtomicLevels
= [];
3081 if ( $this->mTrxDoneWrites
) {
3082 $this->trxProfiler
->transactionWritingOut(
3089 $this->mTrxIdleCallbacks
= []; // clear
3090 $this->mTrxPreCommitCallbacks
= []; // clear
3092 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3093 } catch ( Exception
$e ) {
3094 // already logged; finish and let LoadBalancer move on during mass-rollback
3097 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3098 } catch ( Exception
$e ) {
3099 // already logged; let LoadBalancer move on during mass-rollback
3104 * Issues the ROLLBACK command to the database server.
3106 * @see Database::rollback()
3107 * @param string $fname
3109 protected function doRollback( $fname ) {
3110 if ( $this->mTrxLevel
) {
3111 # Disconnects cause rollback anyway, so ignore those errors
3112 $ignoreErrors = true;
3113 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3114 $this->mTrxLevel
= 0;
3118 public function flushSnapshot( $fname = __METHOD__
) {
3119 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3120 // This only flushes transactions to clear snapshots, not to write data
3121 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3122 throw new DBUnexpectedError(
3124 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3128 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3131 public function explicitTrxActive() {
3132 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3135 public function duplicateTableStructure(
3136 $oldName, $newName, $temporary = false, $fname = __METHOD__
3138 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3141 public function listTables( $prefix = null, $fname = __METHOD__
) {
3142 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3145 public function listViews( $prefix = null, $fname = __METHOD__
) {
3146 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3149 public function timestamp( $ts = 0 ) {
3150 $t = new ConvertibleTimestamp( $ts );
3151 // Let errors bubble up to avoid putting garbage in the DB
3152 return $t->getTimestamp( TS_MW
);
3155 public function timestampOrNull( $ts = null ) {
3156 if ( is_null( $ts ) ) {
3159 return $this->timestamp( $ts );
3164 * Take the result from a query, and wrap it in a ResultWrapper if
3165 * necessary. Boolean values are passed through as is, to indicate success
3166 * of write queries or failure.
3168 * Once upon a time, Database::query() returned a bare MySQL result
3169 * resource, and it was necessary to call this function to convert it to
3170 * a wrapper. Nowadays, raw database objects are never exposed to external
3171 * callers, so this is unnecessary in external code.
3173 * @param bool|ResultWrapper|resource|object $result
3174 * @return bool|ResultWrapper
3176 protected function resultObject( $result ) {
3179 } elseif ( $result instanceof ResultWrapper
) {
3181 } elseif ( $result === true ) {
3182 // Successful write query
3185 return new ResultWrapper( $this, $result );
3189 public function ping( &$rtt = null ) {
3190 // Avoid hitting the server if it was hit recently
3191 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3192 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3193 $rtt = $this->mRTTEstimate
;
3194 return true; // don't care about $rtt
3198 // This will reconnect if possible or return false if not
3199 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3200 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3201 $this->restoreFlags( self
::RESTORE_PRIOR
);
3204 $rtt = $this->mRTTEstimate
;
3211 * Close existing database connection and open a new connection
3213 * @return bool True if new connection is opened successfully, false if error
3215 protected function reconnect() {
3216 $this->closeConnection();
3217 $this->mOpened
= false;
3218 $this->mConn
= false;
3220 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3221 $this->lastPing
= microtime( true );
3223 } catch ( DBConnectionError
$e ) {
3230 public function getSessionLagStatus() {
3231 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3235 * Get the replica DB lag when the current transaction started
3237 * This is useful when transactions might use snapshot isolation
3238 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3239 * is this lag plus transaction duration. If they don't, it is still
3240 * safe to be pessimistic. This returns null if there is no transaction.
3242 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3245 protected function getTransactionLagStatus() {
3246 return $this->mTrxLevel
3247 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3252 * Get a replica DB lag estimate for this server
3254 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3257 protected function getApproximateLagStatus() {
3259 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3260 'since' => microtime( true )
3265 * Merge the result of getSessionLagStatus() for several DBs
3266 * using the most pessimistic values to estimate the lag of
3267 * any data derived from them in combination
3269 * This is information is useful for caching modules
3271 * @see WANObjectCache::set()
3272 * @see WANObjectCache::getWithSetCallback()
3274 * @param IDatabase $db1
3275 * @param IDatabase $dbs,...
3276 * @return array Map of values:
3277 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3278 * - since: oldest UNIX timestamp of any of the DB lag estimates
3279 * - pending: whether any of the DBs have uncommitted changes
3282 public static function getCacheSetOptions( IDatabase
$db1 ) {
3283 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3284 foreach ( func_get_args() as $db ) {
3285 /** @var IDatabase $db */
3286 $status = $db->getSessionLagStatus();
3287 if ( $status['lag'] === false ) {
3288 $res['lag'] = false;
3289 } elseif ( $res['lag'] !== false ) {
3290 $res['lag'] = max( $res['lag'], $status['lag'] );
3292 $res['since'] = min( $res['since'], $status['since'] );
3293 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3299 public function getLag() {
3303 public function maxListLen() {
3307 public function encodeBlob( $b ) {
3311 public function decodeBlob( $b ) {
3312 if ( $b instanceof Blob
) {
3318 public function setSessionOptions( array $options ) {
3321 public function sourceFile(
3323 callable
$lineCallback = null,
3324 callable
$resultCallback = null,
3326 callable
$inputCallback = null
3328 MediaWiki\
suppressWarnings();
3329 $fp = fopen( $filename, 'r' );
3330 MediaWiki\restoreWarnings
();
3332 if ( false === $fp ) {
3333 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3337 $fname = __METHOD__
. "( $filename )";
3341 $error = $this->sourceStream(
3342 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3343 } catch ( Exception
$e ) {
3353 public function setSchemaVars( $vars ) {
3354 $this->mSchemaVars
= $vars;
3357 public function sourceStream(
3359 callable
$lineCallback = null,
3360 callable
$resultCallback = null,
3361 $fname = __METHOD__
,
3362 callable
$inputCallback = null
3366 while ( !feof( $fp ) ) {
3367 if ( $lineCallback ) {
3368 call_user_func( $lineCallback );
3371 $line = trim( fgets( $fp ) );
3373 if ( $line == '' ) {
3377 if ( '-' == $line[0] && '-' == $line[1] ) {
3385 $done = $this->streamStatementEnd( $cmd, $line );
3389 if ( $done ||
feof( $fp ) ) {
3390 $cmd = $this->replaceVars( $cmd );
3392 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3393 $res = $this->query( $cmd, $fname );
3395 if ( $resultCallback ) {
3396 call_user_func( $resultCallback, $res, $this );
3399 if ( false === $res ) {
3400 $err = $this->lastError();
3402 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3413 * Called by sourceStream() to check if we've reached a statement end
3415 * @param string &$sql SQL assembled so far
3416 * @param string &$newLine New line about to be added to $sql
3417 * @return bool Whether $newLine contains end of the statement
3419 public function streamStatementEnd( &$sql, &$newLine ) {
3420 if ( $this->delimiter
) {
3422 $newLine = preg_replace(
3423 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3424 if ( $newLine != $prev ) {
3433 * Database independent variable replacement. Replaces a set of variables
3434 * in an SQL statement with their contents as given by $this->getSchemaVars().
3436 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3438 * - '{$var}' should be used for text and is passed through the database's
3440 * - `{$var}` should be used for identifiers (e.g. table and database names).
3441 * It is passed through the database's addIdentifierQuotes method which
3442 * can be overridden if the database uses something other than backticks.
3443 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3444 * database's tableName method.
3445 * - / *i* / passes the name that follows through the database's indexName method.
3446 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3447 * its use should be avoided. In 1.24 and older, string encoding was applied.
3449 * @param string $ins SQL statement to replace variables in
3450 * @return string The new SQL statement with variables replaced
3452 protected function replaceVars( $ins ) {
3453 $vars = $this->getSchemaVars();
3454 return preg_replace_callback(
3456 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3457 \'\{\$ (\w+) }\' | # 3. addQuotes
3458 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3459 /\*\$ (\w+) \*/ # 5. leave unencoded
3461 function ( $m ) use ( $vars ) {
3462 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3463 // check for both nonexistent keys *and* the empty string.
3464 if ( isset( $m[1] ) && $m[1] !== '' ) {
3465 if ( $m[1] === 'i' ) {
3466 return $this->indexName( $m[2] );
3468 return $this->tableName( $m[2] );
3470 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3471 return $this->addQuotes( $vars[$m[3]] );
3472 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3473 return $this->addIdentifierQuotes( $vars[$m[4]] );
3474 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3475 return $vars[$m[5]];
3485 * Get schema variables. If none have been set via setSchemaVars(), then
3486 * use some defaults from the current object.
3490 protected function getSchemaVars() {
3491 if ( $this->mSchemaVars
) {
3492 return $this->mSchemaVars
;
3494 return $this->getDefaultSchemaVars();
3499 * Get schema variables to use if none have been set via setSchemaVars().
3501 * Override this in derived classes to provide variables for tables.sql
3502 * and SQL patch files.
3506 protected function getDefaultSchemaVars() {
3510 public function lockIsFree( $lockName, $method ) {
3514 public function lock( $lockName, $method, $timeout = 5 ) {
3515 $this->mNamedLocksHeld
[$lockName] = 1;
3520 public function unlock( $lockName, $method ) {
3521 unset( $this->mNamedLocksHeld
[$lockName] );
3526 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3527 if ( $this->writesOrCallbacksPending() ) {
3528 // This only flushes transactions to clear snapshots, not to write data
3529 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3530 throw new DBUnexpectedError(
3532 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3536 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3540 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3541 if ( $this->trxLevel() ) {
3542 // There is a good chance an exception was thrown, causing any early return
3543 // from the caller. Let any error handler get a chance to issue rollback().
3544 // If there isn't one, let the error bubble up and trigger server-side rollback.
3545 $this->onTransactionResolution(
3546 function () use ( $lockKey, $fname ) {
3547 $this->unlock( $lockKey, $fname );
3552 $this->unlock( $lockKey, $fname );
3556 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3561 public function namedLocksEnqueue() {
3565 public function tableLocksHaveTransactionScope() {
3569 final public function lockTables( array $read, array $write, $method ) {
3570 if ( $this->writesOrCallbacksPending() ) {
3571 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3574 if ( $this->tableLocksHaveTransactionScope() ) {
3575 $this->startAtomic( $method );
3578 return $this->doLockTables( $read, $write, $method );
3582 * Helper function for lockTables() that handles the actual table locking
3584 * @param array $read Array of tables to lock for read access
3585 * @param array $write Array of tables to lock for write access
3586 * @param string $method Name of caller
3589 protected function doLockTables( array $read, array $write, $method ) {
3593 final public function unlockTables( $method ) {
3594 if ( $this->tableLocksHaveTransactionScope() ) {
3595 $this->endAtomic( $method );
3597 return true; // locks released on COMMIT/ROLLBACK
3600 return $this->doUnlockTables( $method );
3604 * Helper function for unlockTables() that handles the actual table unlocking
3606 * @param string $method Name of caller
3609 protected function doUnlockTables( $method ) {
3615 * @param string $tableName
3616 * @param string $fName
3617 * @return bool|ResultWrapper
3620 public function dropTable( $tableName, $fName = __METHOD__
) {
3621 if ( !$this->tableExists( $tableName, $fName ) ) {
3624 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3626 return $this->query( $sql, $fName );
3629 public function getInfinity() {
3633 public function encodeExpiry( $expiry ) {
3634 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3635 ?
$this->getInfinity()
3636 : $this->timestamp( $expiry );
3639 public function decodeExpiry( $expiry, $format = TS_MW
) {
3640 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3644 return ConvertibleTimestamp
::convert( $format, $expiry );
3647 public function setBigSelects( $value = true ) {
3651 public function isReadOnly() {
3652 return ( $this->getReadOnlyReason() !== false );
3656 * @return string|bool Reason this DB is read-only or false if it is not
3658 protected function getReadOnlyReason() {
3659 $reason = $this->getLBInfo( 'readOnlyReason' );
3661 return is_string( $reason ) ?
$reason : false;
3664 public function setTableAliases( array $aliases ) {
3665 $this->tableAliases
= $aliases;
3669 * @return bool Whether a DB user is required to access the DB
3672 protected function requiresDatabaseUser() {
3677 * Get the underlying binding handle, mConn
3679 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3680 * This catches broken callers than catch and ignore disconnection exceptions.
3681 * Unlike checking isOpen(), this is safe to call inside of open().
3683 * @return resource|object
3684 * @throws DBUnexpectedError
3687 protected function getBindingHandle() {
3688 if ( !$this->mConn
) {
3689 throw new DBUnexpectedError(
3691 'DB connection was already closed or the connection dropped.'
3695 return $this->mConn
;
3702 public function __toString() {
3703 return (string)$this->mConn
;
3707 * Make sure that copies do not share the same client binding handle
3708 * @throws DBConnectionError
3710 public function __clone() {
3711 $this->connLogger
->warning(
3712 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3713 ( new RuntimeException() )->getTraceAsString()
3716 if ( $this->isOpen() ) {
3717 // Open a new connection resource without messing with the old one
3718 $this->mOpened
= false;
3719 $this->mConn
= false;
3720 $this->mTrxEndCallbacks
= []; // don't copy
3721 $this->handleSessionLoss(); // no trx or locks anymore
3722 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3723 $this->lastPing
= microtime( true );
3728 * Called by serialize. Throw an exception when DB connection is serialized.
3729 * This causes problems on some database engines because the connection is
3730 * not restored on unserialize.
3732 public function __sleep() {
3733 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3734 'the connection is not restored on wakeup.' );
3738 * Run a few simple sanity checks and close dangling connections
3740 public function __destruct() {
3741 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3742 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3745 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3746 if ( $danglingWriters ) {
3747 $fnames = implode( ', ', $danglingWriters );
3748 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3751 if ( $this->mConn
) {
3752 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3753 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3754 \MediaWiki\
suppressWarnings();
3755 $this->closeConnection();
3756 \MediaWiki\restoreWarnings
();
3757 $this->mConn
= false;
3758 $this->mOpened
= false;
3763 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3764 class_alias( Database
::class, 'Database' ); // b/c global alias