Move DBConnRef/MaintainableDBConnRef to Rdbms namespace
[mediawiki.git] / includes / libs / rdbms / database / Database.php
blobbeb38bc0d70c2d3c94b1e3f00dd8942d700f705d
1 <?php
2 /**
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
23 * @file
24 * @ingroup Database
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Wikimedia\ScopedCallback;
29 use Wikimedia\Rdbms\TransactionProfiler;
30 use Wikimedia\Rdbms\LikeMatch;
31 use Wikimedia\Rdbms\DatabaseDomain;
32 use Wikimedia\Rdbms\ResultWrapper;
33 use Wikimedia\Rdbms\DBMasterPos;
34 use Wikimedia\Rdbms\Blob;
35 use Wikimedia\Timestamp\ConvertibleTimestamp;
36 use Wikimedia\Rdbms\IDatabase;
37 use Wikimedia\Rdbms\IMaintainableDatabase;
39 /**
40 * Relational database abstraction object
42 * @ingroup Database
43 * @since 1.28
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 */
54 const PING_TTL = 1.0;
55 const PING_QUERY = 'SELECT 1 AS ping';
57 const TINY_WRITE_SEC = .010;
58 const SLOW_WRITE_SEC = .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;
67 /** @var string */
68 protected $mServer;
69 /** @var string */
70 protected $mUser;
71 /** @var string */
72 protected $mPassword;
73 /** @var string */
74 protected $mDBname;
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 */
78 protected $cliMode;
79 /** @var string Agent name for query profiling */
80 protected $agent;
82 /** @var BagOStuff APC cache */
83 protected $srvCache;
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;
93 /** @var bool */
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;
107 /** @var string */
108 protected $mTablePrefix = '';
109 /** @var string */
110 protected $mSchema = '';
111 /** @var integer */
112 protected $mFlags;
113 /** @var array */
114 protected $mLBInfo = [];
115 /** @var bool|null */
116 protected $mDefaultBigSelects = null;
117 /** @var array|bool */
118 protected $mSchemaVars = false;
119 /** @var array */
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;
125 /** @var string */
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.
134 * @var int
136 protected $mTrxLevel = 0;
138 * Either a short hexidecimal string if a transaction is active or ""
140 * @var string
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).
149 * @var float|null
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.
159 * @var string
160 * @see Database::mTrxLevel
162 private $mTrxFname = null;
164 * Record if possible write queries were done in the last transaction started
166 * @var bool
167 * @see Database::mTrxLevel
169 private $mTrxDoneWrites = false;
171 * Record if the current transaction was started implicitly due to DBO_TRX being set.
173 * @var bool
174 * @see Database::mTrxLevel
176 private $mTrxAutomatic = false;
178 * Array of levels of atomicity within transactions
180 * @var array
182 private $mTrxAtomicLevels = [];
184 * Record if the current transaction was started implicitly by Database::startAtomic
186 * @var bool
188 private $mTrxAutomaticAtomic = false;
190 * Track the write query callers of the current transaction
192 * @var string[]
194 private $mTrxWriteCallers = [];
196 * @var float Seconds spent in write queries for the current transaction
198 private $mTrxWriteDuration = 0.0;
200 * @var integer Number of write queries for the current transaction
202 private $mTrxWriteQueryCount = 0;
204 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
206 private $mTrxWriteAdjDuration = 0.0;
208 * @var integer Number of write queries counted in mTrxWriteAdjDuration
210 private $mTrxWriteAdjQueryCount = 0;
212 * @var float RTT time estimate
214 private $mRTTEstimate = 0.0;
216 /** @var array Map of (name => 1) for locks obtained via lock() */
217 private $mNamedLocksHeld = [];
218 /** @var array Map of (table name => 1) for TEMPORARY tables */
219 protected $mSessionTempTables = [];
221 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
222 private $lazyMasterHandle;
224 /** @var float UNIX timestamp */
225 protected $lastPing = 0.0;
227 /** @var int[] Prior mFlags values */
228 private $priorFlags = [];
230 /** @var object|string Class name or object With profileIn/profileOut methods */
231 protected $profiler;
232 /** @var TransactionProfiler */
233 protected $trxProfiler;
236 * Constructor and database handle and attempt to connect to the DB server
238 * IDatabase classes should not be constructed directly in external
239 * code. Database::factory() should be used instead.
241 * @param array $params Parameters passed from Database::factory()
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
249 $this->mSchema = $params['schema'];
250 $this->mTablePrefix = $params['tablePrefix'];
252 $this->cliMode = $params['cliMode'];
253 // Agent name is added to SQL queries in a comment, so make sure it can't break out
254 $this->agent = str_replace( '/', '-', $params['agent'] );
256 $this->mFlags = $params['flags'];
257 if ( $this->mFlags & self::DBO_DEFAULT ) {
258 if ( $this->cliMode ) {
259 $this->mFlags &= ~self::DBO_TRX;
260 } else {
261 $this->mFlags |= self::DBO_TRX;
265 $this->mSessionVars = $params['variables'];
267 $this->srvCache = isset( $params['srvCache'] )
268 ? $params['srvCache']
269 : new HashBagOStuff();
271 $this->profiler = $params['profiler'];
272 $this->trxProfiler = $params['trxProfiler'];
273 $this->connLogger = $params['connLogger'];
274 $this->queryLogger = $params['queryLogger'];
275 $this->errorLogger = $params['errorLogger'];
277 // Set initial dummy domain until open() sets the final DB/prefix
278 $this->currentDomain = DatabaseDomain::newUnspecified();
280 if ( $user ) {
281 $this->open( $server, $user, $password, $dbName );
282 } elseif ( $this->requiresDatabaseUser() ) {
283 throw new InvalidArgumentException( "No database user provided." );
286 // Set the domain object after open() sets the relevant fields
287 if ( $this->mDBname != '' ) {
288 // Domains with server scope but a table prefix are not used by IDatabase classes
289 $this->currentDomain = new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix );
294 * Construct a Database subclass instance given a database type and parameters
296 * This also connects to the database immediately upon object construction
298 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
299 * @param array $p Parameter map with keys:
300 * - host : The hostname of the DB server
301 * - user : The name of the database user the client operates under
302 * - password : The password for the database user
303 * - dbname : The name of the database to use where queries do not specify one.
304 * The database must exist or an error might be thrown. Setting this to the empty string
305 * will avoid any such errors and make the handle have no implicit database scope. This is
306 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
307 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
308 * in which user names and such are defined, e.g. users are database-specific in Postgres.
309 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
310 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
311 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
312 * recognized in queries. This can be used in place of schemas for handle site farms.
313 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
314 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
315 * flag in place UNLESS this this database simply acts as a key/value store.
316 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
317 * 'mysql' driver and the newer 'mysqli' driver.
318 * - variables: Optional map of session variables to set after connecting. This can be
319 * used to adjust lock timeouts or encoding modes and the like.
320 * - connLogger: Optional PSR-3 logger interface instance.
321 * - queryLogger: Optional PSR-3 logger interface instance.
322 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
323 * These will be called in query(), using a simplified version of the SQL that also
324 * includes the agent as a SQL comment.
325 * - trxProfiler: Optional TransactionProfiler instance.
326 * - errorLogger: Optional callback that takes an Exception and logs it.
327 * - cliMode: Whether to consider the execution context that of a CLI script.
328 * - agent: Optional name used to identify the end-user in query profiling/logging.
329 * - srvCache: Optional BagOStuff instance to an APC-style cache.
330 * @return Database|null If the database driver or extension cannot be found
331 * @throws InvalidArgumentException If the database driver or extension cannot be found
332 * @since 1.18
334 final public static function factory( $dbType, $p = [] ) {
335 static $canonicalDBTypes = [
336 'mysql' => [ 'mysqli', 'mysql' ],
337 'postgres' => [],
338 'sqlite' => [],
339 'oracle' => [],
340 'mssql' => [],
343 $driver = false;
344 $dbType = strtolower( $dbType );
345 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
346 $possibleDrivers = $canonicalDBTypes[$dbType];
347 if ( !empty( $p['driver'] ) ) {
348 if ( in_array( $p['driver'], $possibleDrivers ) ) {
349 $driver = $p['driver'];
350 } else {
351 throw new InvalidArgumentException( __METHOD__ .
352 " type '$dbType' does not support driver '{$p['driver']}'" );
354 } else {
355 foreach ( $possibleDrivers as $posDriver ) {
356 if ( extension_loaded( $posDriver ) ) {
357 $driver = $posDriver;
358 break;
362 } else {
363 $driver = $dbType;
365 if ( $driver === false || $driver === '' ) {
366 throw new InvalidArgumentException( __METHOD__ .
367 " no viable database extension found for type '$dbType'" );
370 $class = 'Database' . ucfirst( $driver );
371 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase::class ) ) {
372 // Resolve some defaults for b/c
373 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
374 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
375 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
376 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
377 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
378 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
379 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
380 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
381 $p['cliMode'] = isset( $p['cliMode'] ) ? $p['cliMode'] : ( PHP_SAPI === 'cli' );
382 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
383 if ( !isset( $p['connLogger'] ) ) {
384 $p['connLogger'] = new \Psr\Log\NullLogger();
386 if ( !isset( $p['queryLogger'] ) ) {
387 $p['queryLogger'] = new \Psr\Log\NullLogger();
389 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
390 if ( !isset( $p['trxProfiler'] ) ) {
391 $p['trxProfiler'] = new TransactionProfiler();
393 if ( !isset( $p['errorLogger'] ) ) {
394 $p['errorLogger'] = function ( Exception $e ) {
395 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
399 $conn = new $class( $p );
400 } else {
401 $conn = null;
404 return $conn;
407 public function setLogger( LoggerInterface $logger ) {
408 $this->queryLogger = $logger;
411 public function getServerInfo() {
412 return $this->getServerVersion();
415 public function bufferResults( $buffer = null ) {
416 $res = !$this->getFlag( self::DBO_NOBUFFER );
417 if ( $buffer !== null ) {
418 $buffer
419 ? $this->clearFlag( self::DBO_NOBUFFER )
420 : $this->setFlag( self::DBO_NOBUFFER );
423 return $res;
427 * Turns on (false) or off (true) the automatic generation and sending
428 * of a "we're sorry, but there has been a database error" page on
429 * database errors. Default is on (false). When turned off, the
430 * code should use lastErrno() and lastError() to handle the
431 * situation as appropriate.
433 * Do not use this function outside of the Database classes.
435 * @param null|bool $ignoreErrors
436 * @return bool The previous value of the flag.
438 protected function ignoreErrors( $ignoreErrors = null ) {
439 $res = $this->getFlag( self::DBO_IGNORE );
440 if ( $ignoreErrors !== null ) {
441 $ignoreErrors
442 ? $this->setFlag( self::DBO_IGNORE )
443 : $this->clearFlag( self::DBO_IGNORE );
446 return $res;
449 public function trxLevel() {
450 return $this->mTrxLevel;
453 public function trxTimestamp() {
454 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
457 public function tablePrefix( $prefix = null ) {
458 $old = $this->mTablePrefix;
459 if ( $prefix !== null ) {
460 $this->mTablePrefix = $prefix;
461 $this->currentDomain = ( $this->mDBname != '' )
462 ? new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix )
463 : DatabaseDomain::newUnspecified();
466 return $old;
469 public function dbSchema( $schema = null ) {
470 $old = $this->mSchema;
471 if ( $schema !== null ) {
472 $this->mSchema = $schema;
475 return $old;
478 public function getLBInfo( $name = null ) {
479 if ( is_null( $name ) ) {
480 return $this->mLBInfo;
481 } else {
482 if ( array_key_exists( $name, $this->mLBInfo ) ) {
483 return $this->mLBInfo[$name];
484 } else {
485 return null;
490 public function setLBInfo( $name, $value = null ) {
491 if ( is_null( $value ) ) {
492 $this->mLBInfo = $name;
493 } else {
494 $this->mLBInfo[$name] = $value;
498 public function setLazyMasterHandle( IDatabase $conn ) {
499 $this->lazyMasterHandle = $conn;
503 * @return IDatabase|null
504 * @see setLazyMasterHandle()
505 * @since 1.27
507 protected function getLazyMasterHandle() {
508 return $this->lazyMasterHandle;
511 public function implicitGroupby() {
512 return true;
515 public function implicitOrderby() {
516 return true;
519 public function lastQuery() {
520 return $this->mLastQuery;
523 public function doneWrites() {
524 return (bool)$this->mLastWriteTime;
527 public function lastDoneWrites() {
528 return $this->mLastWriteTime ?: false;
531 public function writesPending() {
532 return $this->mTrxLevel && $this->mTrxDoneWrites;
535 public function writesOrCallbacksPending() {
536 return $this->mTrxLevel && (
537 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
541 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
542 if ( !$this->mTrxLevel ) {
543 return false;
544 } elseif ( !$this->mTrxDoneWrites ) {
545 return 0.0;
548 switch ( $type ) {
549 case self::ESTIMATE_DB_APPLY:
550 $this->ping( $rtt );
551 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
552 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
553 // For omitted queries, make them count as something at least
554 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
555 $applyTime += self::TINY_WRITE_SEC * $omitted;
557 return $applyTime;
558 default: // everything
559 return $this->mTrxWriteDuration;
563 public function pendingWriteCallers() {
564 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
567 protected function pendingWriteAndCallbackCallers() {
568 if ( !$this->mTrxLevel ) {
569 return [];
572 $fnames = $this->mTrxWriteCallers;
573 foreach ( [
574 $this->mTrxIdleCallbacks,
575 $this->mTrxPreCommitCallbacks,
576 $this->mTrxEndCallbacks
577 ] as $callbacks ) {
578 foreach ( $callbacks as $callback ) {
579 $fnames[] = $callback[1];
583 return $fnames;
586 public function isOpen() {
587 return $this->mOpened;
590 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
591 if ( $remember === self::REMEMBER_PRIOR ) {
592 array_push( $this->priorFlags, $this->mFlags );
594 $this->mFlags |= $flag;
597 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
598 if ( $remember === self::REMEMBER_PRIOR ) {
599 array_push( $this->priorFlags, $this->mFlags );
601 $this->mFlags &= ~$flag;
604 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
605 if ( !$this->priorFlags ) {
606 return;
609 if ( $state === self::RESTORE_INITIAL ) {
610 $this->mFlags = reset( $this->priorFlags );
611 $this->priorFlags = [];
612 } else {
613 $this->mFlags = array_pop( $this->priorFlags );
617 public function getFlag( $flag ) {
618 return !!( $this->mFlags & $flag );
622 * @param string $name Class field name
623 * @return mixed
624 * @deprecated Since 1.28
626 public function getProperty( $name ) {
627 return $this->$name;
630 public function getDomainID() {
631 return $this->currentDomain->getId();
634 final public function getWikiID() {
635 return $this->getDomainID();
639 * Get information about an index into an object
640 * @param string $table Table name
641 * @param string $index Index name
642 * @param string $fname Calling function name
643 * @return mixed Database-specific index description class or false if the index does not exist
645 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
648 * Wrapper for addslashes()
650 * @param string $s String to be slashed.
651 * @return string Slashed string.
653 abstract function strencode( $s );
655 protected function installErrorHandler() {
656 $this->mPHPError = false;
657 $this->htmlErrors = ini_set( 'html_errors', '0' );
658 set_error_handler( [ $this, 'connectionErrorLogger' ] );
662 * @return bool|string
664 protected function restoreErrorHandler() {
665 restore_error_handler();
666 if ( $this->htmlErrors !== false ) {
667 ini_set( 'html_errors', $this->htmlErrors );
670 return $this->getLastPHPError();
674 * @return string|bool Last PHP error for this DB (typically connection errors)
676 protected function getLastPHPError() {
677 if ( $this->mPHPError ) {
678 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
679 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
681 return $error;
684 return false;
688 * This method should not be used outside of Database classes
690 * @param int $errno
691 * @param string $errstr
693 public function connectionErrorLogger( $errno, $errstr ) {
694 $this->mPHPError = $errstr;
698 * Create a log context to pass to PSR-3 logger functions.
700 * @param array $extras Additional data to add to context
701 * @return array
703 protected function getLogContext( array $extras = [] ) {
704 return array_merge(
706 'db_server' => $this->mServer,
707 'db_name' => $this->mDBname,
708 'db_user' => $this->mUser,
710 $extras
714 public function close() {
715 if ( $this->mConn ) {
716 if ( $this->trxLevel() ) {
717 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
720 $closed = $this->closeConnection();
721 $this->mConn = false;
722 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
723 throw new RuntimeException( "Transaction callbacks still pending." );
724 } else {
725 $closed = true;
727 $this->mOpened = false;
729 return $closed;
733 * Make sure isOpen() returns true as a sanity check
735 * @throws DBUnexpectedError
737 protected function assertOpen() {
738 if ( !$this->isOpen() ) {
739 throw new DBUnexpectedError( $this, "DB connection was already closed." );
744 * Closes underlying database connection
745 * @since 1.20
746 * @return bool Whether connection was closed successfully
748 abstract protected function closeConnection();
750 public function reportConnectionError( $error = 'Unknown error' ) {
751 $myError = $this->lastError();
752 if ( $myError ) {
753 $error = $myError;
756 # New method
757 throw new DBConnectionError( $this, $error );
761 * The DBMS-dependent part of query()
763 * @param string $sql SQL query.
764 * @return ResultWrapper|bool Result object to feed to fetchObject,
765 * fetchRow, ...; or false on failure
767 abstract protected function doQuery( $sql );
770 * Determine whether a query writes to the DB.
771 * Should return true if unsure.
773 * @param string $sql
774 * @return bool
776 protected function isWriteQuery( $sql ) {
777 return !preg_match(
778 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
782 * @param $sql
783 * @return string|null
785 protected function getQueryVerb( $sql ) {
786 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
790 * Determine whether a SQL statement is sensitive to isolation level.
791 * A SQL statement is considered transactable if its result could vary
792 * depending on the transaction isolation level. Operational commands
793 * such as 'SET' and 'SHOW' are not considered to be transactable.
795 * @param string $sql
796 * @return bool
798 protected function isTransactableQuery( $sql ) {
799 return !in_array(
800 $this->getQueryVerb( $sql ),
801 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
802 true
807 * @param string $sql A SQL query
808 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
810 protected function registerTempTableOperation( $sql ) {
811 if ( preg_match(
812 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
813 $sql,
814 $matches
815 ) ) {
816 $this->mSessionTempTables[$matches[1]] = 1;
818 return true;
819 } elseif ( preg_match(
820 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
821 $sql,
822 $matches
823 ) ) {
824 unset( $this->mSessionTempTables[$matches[1]] );
826 return true;
827 } elseif ( preg_match(
828 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
829 $sql,
830 $matches
831 ) ) {
832 return isset( $this->mSessionTempTables[$matches[1]] );
835 return false;
838 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
839 $priorWritesPending = $this->writesOrCallbacksPending();
840 $this->mLastQuery = $sql;
842 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
843 if ( $isWrite ) {
844 $reason = $this->getReadOnlyReason();
845 if ( $reason !== false ) {
846 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
848 # Set a flag indicating that writes have been done
849 $this->mLastWriteTime = microtime( true );
852 // Add trace comment to the begin of the sql string, right after the operator.
853 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
854 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
856 # Start implicit transactions that wrap the request if DBO_TRX is enabled
857 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
858 && $this->isTransactableQuery( $sql )
860 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
861 $this->mTrxAutomatic = true;
864 # Keep track of whether the transaction has write queries pending
865 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
866 $this->mTrxDoneWrites = true;
867 $this->trxProfiler->transactionWritingIn(
868 $this->mServer, $this->mDBname, $this->mTrxShortId );
871 if ( $this->getFlag( self::DBO_DEBUG ) ) {
872 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
875 # Avoid fatals if close() was called
876 $this->assertOpen();
878 # Send the query to the server
879 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
881 # Try reconnecting if the connection was lost
882 if ( false === $ret && $this->wasErrorReissuable() ) {
883 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
884 # Stash the last error values before anything might clear them
885 $lastError = $this->lastError();
886 $lastErrno = $this->lastErrno();
887 # Update state tracking to reflect transaction loss due to disconnection
888 $this->handleSessionLoss();
889 if ( $this->reconnect() ) {
890 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
891 $this->connLogger->warning( $msg );
892 $this->queryLogger->warning(
893 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
895 if ( !$recoverable ) {
896 # Callers may catch the exception and continue to use the DB
897 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
898 } else {
899 # Should be safe to silently retry the query
900 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
902 } else {
903 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
904 $this->connLogger->error( $msg );
908 if ( false === $ret ) {
909 # Deadlocks cause the entire transaction to abort, not just the statement.
910 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
911 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
912 if ( $this->wasDeadlock() ) {
913 if ( $this->explicitTrxActive() || $priorWritesPending ) {
914 $tempIgnore = false; // not recoverable
916 # Update state tracking to reflect transaction loss
917 $this->handleSessionLoss();
920 $this->reportQueryError(
921 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
924 $res = $this->resultObject( $ret );
926 return $res;
929 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
930 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
931 # generalizeSQL() will probably cut down the query to reasonable
932 # logging size most of the time. The substr is really just a sanity check.
933 if ( $isMaster ) {
934 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
935 } else {
936 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
939 # Include query transaction state
940 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
942 $startTime = microtime( true );
943 if ( $this->profiler ) {
944 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
946 $ret = $this->doQuery( $commentedSql );
947 if ( $this->profiler ) {
948 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
950 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
952 unset( $queryProfSection ); // profile out (if set)
954 if ( $ret !== false ) {
955 $this->lastPing = $startTime;
956 if ( $isWrite && $this->mTrxLevel ) {
957 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
958 $this->mTrxWriteCallers[] = $fname;
962 if ( $sql === self::PING_QUERY ) {
963 $this->mRTTEstimate = $queryRuntime;
966 $this->trxProfiler->recordQueryCompletion(
967 $queryProf, $startTime, $isWrite, $this->affectedRows()
969 $this->queryLogger->debug( $sql, [
970 'method' => $fname,
971 'master' => $isMaster,
972 'runtime' => $queryRuntime,
973 ] );
975 return $ret;
979 * Update the estimated run-time of a query, not counting large row lock times
981 * LoadBalancer can be set to rollback transactions that will create huge replication
982 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
983 * queries, like inserting a row can take a long time due to row locking. This method
984 * uses some simple heuristics to discount those cases.
986 * @param string $sql A SQL write query
987 * @param float $runtime Total runtime, including RTT
989 private function updateTrxWriteQueryTime( $sql, $runtime ) {
990 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
991 $indicativeOfReplicaRuntime = true;
992 if ( $runtime > self::SLOW_WRITE_SEC ) {
993 $verb = $this->getQueryVerb( $sql );
994 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
995 if ( $verb === 'INSERT' ) {
996 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
997 } elseif ( $verb === 'REPLACE' ) {
998 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1002 $this->mTrxWriteDuration += $runtime;
1003 $this->mTrxWriteQueryCount += 1;
1004 if ( $indicativeOfReplicaRuntime ) {
1005 $this->mTrxWriteAdjDuration += $runtime;
1006 $this->mTrxWriteAdjQueryCount += 1;
1010 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1011 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1012 # Dropped connections also mean that named locks are automatically released.
1013 # Only allow error suppression in autocommit mode or when the lost transaction
1014 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1015 if ( $this->mNamedLocksHeld ) {
1016 return false; // possible critical section violation
1017 } elseif ( $sql === 'COMMIT' ) {
1018 return !$priorWritesPending; // nothing written anyway? (T127428)
1019 } elseif ( $sql === 'ROLLBACK' ) {
1020 return true; // transaction lost...which is also what was requested :)
1021 } elseif ( $this->explicitTrxActive() ) {
1022 return false; // don't drop atomocity
1023 } elseif ( $priorWritesPending ) {
1024 return false; // prior writes lost from implicit transaction
1027 return true;
1030 private function handleSessionLoss() {
1031 $this->mTrxLevel = 0;
1032 $this->mTrxIdleCallbacks = []; // T67263
1033 $this->mTrxPreCommitCallbacks = []; // T67263
1034 $this->mSessionTempTables = [];
1035 $this->mNamedLocksHeld = [];
1036 try {
1037 // Handle callbacks in mTrxEndCallbacks
1038 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1039 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1040 return null;
1041 } catch ( Exception $e ) {
1042 // Already logged; move on...
1043 return $e;
1047 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1048 if ( $this->ignoreErrors() || $tempIgnore ) {
1049 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1050 } else {
1051 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1052 $this->queryLogger->error(
1053 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1054 $this->getLogContext( [
1055 'method' => __METHOD__,
1056 'errno' => $errno,
1057 'error' => $error,
1058 'sql1line' => $sql1line,
1059 'fname' => $fname,
1062 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1063 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1067 public function freeResult( $res ) {
1070 public function selectField(
1071 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1073 if ( $var === '*' ) { // sanity
1074 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1077 if ( !is_array( $options ) ) {
1078 $options = [ $options ];
1081 $options['LIMIT'] = 1;
1083 $res = $this->select( $table, $var, $cond, $fname, $options );
1084 if ( $res === false || !$this->numRows( $res ) ) {
1085 return false;
1088 $row = $this->fetchRow( $res );
1090 if ( $row !== false ) {
1091 return reset( $row );
1092 } else {
1093 return false;
1097 public function selectFieldValues(
1098 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1100 if ( $var === '*' ) { // sanity
1101 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1102 } elseif ( !is_string( $var ) ) { // sanity
1103 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1106 if ( !is_array( $options ) ) {
1107 $options = [ $options ];
1110 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1111 if ( $res === false ) {
1112 return false;
1115 $values = [];
1116 foreach ( $res as $row ) {
1117 $values[] = $row->$var;
1120 return $values;
1124 * Returns an optional USE INDEX clause to go after the table, and a
1125 * string to go at the end of the query.
1127 * @param array $options Associative array of options to be turned into
1128 * an SQL query, valid keys are listed in the function.
1129 * @return array
1130 * @see Database::select()
1132 protected function makeSelectOptions( $options ) {
1133 $preLimitTail = $postLimitTail = '';
1134 $startOpts = '';
1136 $noKeyOptions = [];
1138 foreach ( $options as $key => $option ) {
1139 if ( is_numeric( $key ) ) {
1140 $noKeyOptions[$option] = true;
1144 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1146 $preLimitTail .= $this->makeOrderBy( $options );
1148 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1149 $postLimitTail .= ' FOR UPDATE';
1152 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1153 $postLimitTail .= ' LOCK IN SHARE MODE';
1156 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1157 $startOpts .= 'DISTINCT';
1160 # Various MySQL extensions
1161 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1162 $startOpts .= ' /*! STRAIGHT_JOIN */';
1165 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1166 $startOpts .= ' HIGH_PRIORITY';
1169 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1170 $startOpts .= ' SQL_BIG_RESULT';
1173 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1174 $startOpts .= ' SQL_BUFFER_RESULT';
1177 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1178 $startOpts .= ' SQL_SMALL_RESULT';
1181 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1182 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1185 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1186 $startOpts .= ' SQL_CACHE';
1189 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1190 $startOpts .= ' SQL_NO_CACHE';
1193 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1194 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1195 } else {
1196 $useIndex = '';
1198 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1199 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1200 } else {
1201 $ignoreIndex = '';
1204 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1208 * Returns an optional GROUP BY with an optional HAVING
1210 * @param array $options Associative array of options
1211 * @return string
1212 * @see Database::select()
1213 * @since 1.21
1215 protected function makeGroupByWithHaving( $options ) {
1216 $sql = '';
1217 if ( isset( $options['GROUP BY'] ) ) {
1218 $gb = is_array( $options['GROUP BY'] )
1219 ? implode( ',', $options['GROUP BY'] )
1220 : $options['GROUP BY'];
1221 $sql .= ' GROUP BY ' . $gb;
1223 if ( isset( $options['HAVING'] ) ) {
1224 $having = is_array( $options['HAVING'] )
1225 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1226 : $options['HAVING'];
1227 $sql .= ' HAVING ' . $having;
1230 return $sql;
1234 * Returns an optional ORDER BY
1236 * @param array $options Associative array of options
1237 * @return string
1238 * @see Database::select()
1239 * @since 1.21
1241 protected function makeOrderBy( $options ) {
1242 if ( isset( $options['ORDER BY'] ) ) {
1243 $ob = is_array( $options['ORDER BY'] )
1244 ? implode( ',', $options['ORDER BY'] )
1245 : $options['ORDER BY'];
1247 return ' ORDER BY ' . $ob;
1250 return '';
1253 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1254 $options = [], $join_conds = [] ) {
1255 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1257 return $this->query( $sql, $fname );
1260 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1261 $options = [], $join_conds = []
1263 if ( is_array( $vars ) ) {
1264 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1267 $options = (array)$options;
1268 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1269 ? $options['USE INDEX']
1270 : [];
1271 $ignoreIndexes = (
1272 isset( $options['IGNORE INDEX'] ) &&
1273 is_array( $options['IGNORE INDEX'] )
1275 ? $options['IGNORE INDEX']
1276 : [];
1278 if ( is_array( $table ) ) {
1279 $from = ' FROM ' .
1280 $this->tableNamesWithIndexClauseOrJOIN(
1281 $table, $useIndexes, $ignoreIndexes, $join_conds );
1282 } elseif ( $table != '' ) {
1283 if ( $table[0] == ' ' ) {
1284 $from = ' FROM ' . $table;
1285 } else {
1286 $from = ' FROM ' .
1287 $this->tableNamesWithIndexClauseOrJOIN(
1288 [ $table ], $useIndexes, $ignoreIndexes, [] );
1290 } else {
1291 $from = '';
1294 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1295 $this->makeSelectOptions( $options );
1297 if ( !empty( $conds ) ) {
1298 if ( is_array( $conds ) ) {
1299 $conds = $this->makeList( $conds, self::LIST_AND );
1301 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1302 "WHERE $conds $preLimitTail";
1303 } else {
1304 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1307 if ( isset( $options['LIMIT'] ) ) {
1308 $sql = $this->limitResult( $sql, $options['LIMIT'],
1309 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1311 $sql = "$sql $postLimitTail";
1313 if ( isset( $options['EXPLAIN'] ) ) {
1314 $sql = 'EXPLAIN ' . $sql;
1317 return $sql;
1320 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1321 $options = [], $join_conds = []
1323 $options = (array)$options;
1324 $options['LIMIT'] = 1;
1325 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1327 if ( $res === false ) {
1328 return false;
1331 if ( !$this->numRows( $res ) ) {
1332 return false;
1335 $obj = $this->fetchObject( $res );
1337 return $obj;
1340 public function estimateRowCount(
1341 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1343 $rows = 0;
1344 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1346 if ( $res ) {
1347 $row = $this->fetchRow( $res );
1348 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1351 return $rows;
1354 public function selectRowCount(
1355 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1357 $rows = 0;
1358 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1359 // The identifier quotes is primarily for MSSQL.
1360 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1361 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1362 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1364 if ( $res ) {
1365 $row = $this->fetchRow( $res );
1366 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1369 return $rows;
1373 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1374 * It's only slightly flawed. Don't use for anything important.
1376 * @param string $sql A SQL Query
1378 * @return string
1380 protected static function generalizeSQL( $sql ) {
1381 # This does the same as the regexp below would do, but in such a way
1382 # as to avoid crashing php on some large strings.
1383 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1385 $sql = str_replace( "\\\\", '', $sql );
1386 $sql = str_replace( "\\'", '', $sql );
1387 $sql = str_replace( "\\\"", '', $sql );
1388 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1389 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1391 # All newlines, tabs, etc replaced by single space
1392 $sql = preg_replace( '/\s+/', ' ', $sql );
1394 # All numbers => N,
1395 # except the ones surrounded by characters, e.g. l10n
1396 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1397 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1399 return $sql;
1402 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1403 $info = $this->fieldInfo( $table, $field );
1405 return (bool)$info;
1408 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1409 if ( !$this->tableExists( $table ) ) {
1410 return null;
1413 $info = $this->indexInfo( $table, $index, $fname );
1414 if ( is_null( $info ) ) {
1415 return null;
1416 } else {
1417 return $info !== false;
1421 public function tableExists( $table, $fname = __METHOD__ ) {
1422 $tableRaw = $this->tableName( $table, 'raw' );
1423 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1424 return true; // already known to exist
1427 $table = $this->tableName( $table );
1428 $ignoreErrors = true;
1429 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1431 return (bool)$res;
1434 public function indexUnique( $table, $index ) {
1435 $indexInfo = $this->indexInfo( $table, $index );
1437 if ( !$indexInfo ) {
1438 return null;
1441 return !$indexInfo[0]->Non_unique;
1445 * Helper for Database::insert().
1447 * @param array $options
1448 * @return string
1450 protected function makeInsertOptions( $options ) {
1451 return implode( ' ', $options );
1454 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1455 # No rows to insert, easy just return now
1456 if ( !count( $a ) ) {
1457 return true;
1460 $table = $this->tableName( $table );
1462 if ( !is_array( $options ) ) {
1463 $options = [ $options ];
1466 $fh = null;
1467 if ( isset( $options['fileHandle'] ) ) {
1468 $fh = $options['fileHandle'];
1470 $options = $this->makeInsertOptions( $options );
1472 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1473 $multi = true;
1474 $keys = array_keys( $a[0] );
1475 } else {
1476 $multi = false;
1477 $keys = array_keys( $a );
1480 $sql = 'INSERT ' . $options .
1481 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1483 if ( $multi ) {
1484 $first = true;
1485 foreach ( $a as $row ) {
1486 if ( $first ) {
1487 $first = false;
1488 } else {
1489 $sql .= ',';
1491 $sql .= '(' . $this->makeList( $row ) . ')';
1493 } else {
1494 $sql .= '(' . $this->makeList( $a ) . ')';
1497 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1498 return false;
1499 } elseif ( $fh !== null ) {
1500 return true;
1503 return (bool)$this->query( $sql, $fname );
1507 * Make UPDATE options array for Database::makeUpdateOptions
1509 * @param array $options
1510 * @return array
1512 protected function makeUpdateOptionsArray( $options ) {
1513 if ( !is_array( $options ) ) {
1514 $options = [ $options ];
1517 $opts = [];
1519 if ( in_array( 'IGNORE', $options ) ) {
1520 $opts[] = 'IGNORE';
1523 return $opts;
1527 * Make UPDATE options for the Database::update function
1529 * @param array $options The options passed to Database::update
1530 * @return string
1532 protected function makeUpdateOptions( $options ) {
1533 $opts = $this->makeUpdateOptionsArray( $options );
1535 return implode( ' ', $opts );
1538 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1539 $table = $this->tableName( $table );
1540 $opts = $this->makeUpdateOptions( $options );
1541 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1543 if ( $conds !== [] && $conds !== '*' ) {
1544 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1547 return (bool)$this->query( $sql, $fname );
1550 public function makeList( $a, $mode = self::LIST_COMMA ) {
1551 if ( !is_array( $a ) ) {
1552 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1555 $first = true;
1556 $list = '';
1558 foreach ( $a as $field => $value ) {
1559 if ( !$first ) {
1560 if ( $mode == self::LIST_AND ) {
1561 $list .= ' AND ';
1562 } elseif ( $mode == self::LIST_OR ) {
1563 $list .= ' OR ';
1564 } else {
1565 $list .= ',';
1567 } else {
1568 $first = false;
1571 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1572 $list .= "($value)";
1573 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1574 $list .= "$value";
1575 } elseif (
1576 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1578 // Remove null from array to be handled separately if found
1579 $includeNull = false;
1580 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1581 $includeNull = true;
1582 unset( $value[$nullKey] );
1584 if ( count( $value ) == 0 && !$includeNull ) {
1585 throw new InvalidArgumentException(
1586 __METHOD__ . ": empty input for field $field" );
1587 } elseif ( count( $value ) == 0 ) {
1588 // only check if $field is null
1589 $list .= "$field IS NULL";
1590 } else {
1591 // IN clause contains at least one valid element
1592 if ( $includeNull ) {
1593 // Group subconditions to ensure correct precedence
1594 $list .= '(';
1596 if ( count( $value ) == 1 ) {
1597 // Special-case single values, as IN isn't terribly efficient
1598 // Don't necessarily assume the single key is 0; we don't
1599 // enforce linear numeric ordering on other arrays here.
1600 $value = array_values( $value )[0];
1601 $list .= $field . " = " . $this->addQuotes( $value );
1602 } else {
1603 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1605 // if null present in array, append IS NULL
1606 if ( $includeNull ) {
1607 $list .= " OR $field IS NULL)";
1610 } elseif ( $value === null ) {
1611 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1612 $list .= "$field IS ";
1613 } elseif ( $mode == self::LIST_SET ) {
1614 $list .= "$field = ";
1616 $list .= 'NULL';
1617 } else {
1618 if (
1619 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1621 $list .= "$field = ";
1623 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1627 return $list;
1630 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1631 $conds = [];
1633 foreach ( $data as $base => $sub ) {
1634 if ( count( $sub ) ) {
1635 $conds[] = $this->makeList(
1636 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1637 self::LIST_AND );
1641 if ( $conds ) {
1642 return $this->makeList( $conds, self::LIST_OR );
1643 } else {
1644 // Nothing to search for...
1645 return false;
1649 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1650 return $valuename;
1653 public function bitNot( $field ) {
1654 return "(~$field)";
1657 public function bitAnd( $fieldLeft, $fieldRight ) {
1658 return "($fieldLeft & $fieldRight)";
1661 public function bitOr( $fieldLeft, $fieldRight ) {
1662 return "($fieldLeft | $fieldRight)";
1665 public function buildConcat( $stringList ) {
1666 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1669 public function buildGroupConcatField(
1670 $delim, $table, $field, $conds = '', $join_conds = []
1672 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1674 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1677 public function buildStringCast( $field ) {
1678 return $field;
1681 public function selectDB( $db ) {
1682 # Stub. Shouldn't cause serious problems if it's not overridden, but
1683 # if your database engine supports a concept similar to MySQL's
1684 # databases you may as well.
1685 $this->mDBname = $db;
1687 return true;
1690 public function getDBname() {
1691 return $this->mDBname;
1694 public function getServer() {
1695 return $this->mServer;
1698 public function tableName( $name, $format = 'quoted' ) {
1699 # Skip the entire process when we have a string quoted on both ends.
1700 # Note that we check the end so that we will still quote any use of
1701 # use of `database`.table. But won't break things if someone wants
1702 # to query a database table with a dot in the name.
1703 if ( $this->isQuotedIdentifier( $name ) ) {
1704 return $name;
1707 # Lets test for any bits of text that should never show up in a table
1708 # name. Basically anything like JOIN or ON which are actually part of
1709 # SQL queries, but may end up inside of the table value to combine
1710 # sql. Such as how the API is doing.
1711 # Note that we use a whitespace test rather than a \b test to avoid
1712 # any remote case where a word like on may be inside of a table name
1713 # surrounded by symbols which may be considered word breaks.
1714 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1715 return $name;
1718 # Split database and table into proper variables.
1719 # We reverse the explode so that database.table and table both output
1720 # the correct table.
1721 $dbDetails = explode( '.', $name, 3 );
1722 if ( count( $dbDetails ) == 3 ) {
1723 list( $database, $schema, $table ) = $dbDetails;
1724 # We don't want any prefix added in this case
1725 $prefix = '';
1726 } elseif ( count( $dbDetails ) == 2 ) {
1727 list( $database, $table ) = $dbDetails;
1728 # We don't want any prefix added in this case
1729 $prefix = '';
1730 # In dbs that support it, $database may actually be the schema
1731 # but that doesn't affect any of the functionality here
1732 $schema = '';
1733 } else {
1734 list( $table ) = $dbDetails;
1735 if ( isset( $this->tableAliases[$table] ) ) {
1736 $database = $this->tableAliases[$table]['dbname'];
1737 $schema = is_string( $this->tableAliases[$table]['schema'] )
1738 ? $this->tableAliases[$table]['schema']
1739 : $this->mSchema;
1740 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1741 ? $this->tableAliases[$table]['prefix']
1742 : $this->mTablePrefix;
1743 } else {
1744 $database = '';
1745 $schema = $this->mSchema; # Default schema
1746 $prefix = $this->mTablePrefix; # Default prefix
1750 # Quote $table and apply the prefix if not quoted.
1751 # $tableName might be empty if this is called from Database::replaceVars()
1752 $tableName = "{$prefix}{$table}";
1753 if ( $format === 'quoted'
1754 && !$this->isQuotedIdentifier( $tableName )
1755 && $tableName !== ''
1757 $tableName = $this->addIdentifierQuotes( $tableName );
1760 # Quote $schema and $database and merge them with the table name if needed
1761 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1762 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1764 return $tableName;
1768 * @param string|null $namespace Database or schema
1769 * @param string $relation Name of table, view, sequence, etc...
1770 * @param string $format One of (raw, quoted)
1771 * @return string Relation name with quoted and merged $namespace as needed
1773 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1774 if ( strlen( $namespace ) ) {
1775 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1776 $namespace = $this->addIdentifierQuotes( $namespace );
1778 $relation = $namespace . '.' . $relation;
1781 return $relation;
1784 public function tableNames() {
1785 $inArray = func_get_args();
1786 $retVal = [];
1788 foreach ( $inArray as $name ) {
1789 $retVal[$name] = $this->tableName( $name );
1792 return $retVal;
1795 public function tableNamesN() {
1796 $inArray = func_get_args();
1797 $retVal = [];
1799 foreach ( $inArray as $name ) {
1800 $retVal[] = $this->tableName( $name );
1803 return $retVal;
1807 * Get an aliased table name
1808 * e.g. tableName AS newTableName
1810 * @param string $name Table name, see tableName()
1811 * @param string|bool $alias Alias (optional)
1812 * @return string SQL name for aliased table. Will not alias a table to its own name
1814 protected function tableNameWithAlias( $name, $alias = false ) {
1815 if ( !$alias || $alias == $name ) {
1816 return $this->tableName( $name );
1817 } else {
1818 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1823 * Gets an array of aliased table names
1825 * @param array $tables [ [alias] => table ]
1826 * @return string[] See tableNameWithAlias()
1828 protected function tableNamesWithAlias( $tables ) {
1829 $retval = [];
1830 foreach ( $tables as $alias => $table ) {
1831 if ( is_numeric( $alias ) ) {
1832 $alias = $table;
1834 $retval[] = $this->tableNameWithAlias( $table, $alias );
1837 return $retval;
1841 * Get an aliased field name
1842 * e.g. fieldName AS newFieldName
1844 * @param string $name Field name
1845 * @param string|bool $alias Alias (optional)
1846 * @return string SQL name for aliased field. Will not alias a field to its own name
1848 protected function fieldNameWithAlias( $name, $alias = false ) {
1849 if ( !$alias || (string)$alias === (string)$name ) {
1850 return $name;
1851 } else {
1852 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1857 * Gets an array of aliased field names
1859 * @param array $fields [ [alias] => field ]
1860 * @return string[] See fieldNameWithAlias()
1862 protected function fieldNamesWithAlias( $fields ) {
1863 $retval = [];
1864 foreach ( $fields as $alias => $field ) {
1865 if ( is_numeric( $alias ) ) {
1866 $alias = $field;
1868 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1871 return $retval;
1875 * Get the aliased table name clause for a FROM clause
1876 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1878 * @param array $tables ( [alias] => table )
1879 * @param array $use_index Same as for select()
1880 * @param array $ignore_index Same as for select()
1881 * @param array $join_conds Same as for select()
1882 * @return string
1884 protected function tableNamesWithIndexClauseOrJOIN(
1885 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1887 $ret = [];
1888 $retJOIN = [];
1889 $use_index = (array)$use_index;
1890 $ignore_index = (array)$ignore_index;
1891 $join_conds = (array)$join_conds;
1893 foreach ( $tables as $alias => $table ) {
1894 if ( !is_string( $alias ) ) {
1895 // No alias? Set it equal to the table name
1896 $alias = $table;
1898 // Is there a JOIN clause for this table?
1899 if ( isset( $join_conds[$alias] ) ) {
1900 list( $joinType, $conds ) = $join_conds[$alias];
1901 $tableClause = $joinType;
1902 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1903 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1904 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1905 if ( $use != '' ) {
1906 $tableClause .= ' ' . $use;
1909 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1910 $ignore = $this->ignoreIndexClause(
1911 implode( ',', (array)$ignore_index[$alias] ) );
1912 if ( $ignore != '' ) {
1913 $tableClause .= ' ' . $ignore;
1916 $on = $this->makeList( (array)$conds, self::LIST_AND );
1917 if ( $on != '' ) {
1918 $tableClause .= ' ON (' . $on . ')';
1921 $retJOIN[] = $tableClause;
1922 } elseif ( isset( $use_index[$alias] ) ) {
1923 // Is there an INDEX clause for this table?
1924 $tableClause = $this->tableNameWithAlias( $table, $alias );
1925 $tableClause .= ' ' . $this->useIndexClause(
1926 implode( ',', (array)$use_index[$alias] )
1929 $ret[] = $tableClause;
1930 } elseif ( isset( $ignore_index[$alias] ) ) {
1931 // Is there an INDEX clause for this table?
1932 $tableClause = $this->tableNameWithAlias( $table, $alias );
1933 $tableClause .= ' ' . $this->ignoreIndexClause(
1934 implode( ',', (array)$ignore_index[$alias] )
1937 $ret[] = $tableClause;
1938 } else {
1939 $tableClause = $this->tableNameWithAlias( $table, $alias );
1941 $ret[] = $tableClause;
1945 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1946 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1947 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1949 // Compile our final table clause
1950 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1954 * Get the name of an index in a given table.
1956 * @param string $index
1957 * @return string
1959 protected function indexName( $index ) {
1960 return $index;
1963 public function addQuotes( $s ) {
1964 if ( $s instanceof Blob ) {
1965 $s = $s->fetch();
1967 if ( $s === null ) {
1968 return 'NULL';
1969 } elseif ( is_bool( $s ) ) {
1970 return (int)$s;
1971 } else {
1972 # This will also quote numeric values. This should be harmless,
1973 # and protects against weird problems that occur when they really
1974 # _are_ strings such as article titles and string->number->string
1975 # conversion is not 1:1.
1976 return "'" . $this->strencode( $s ) . "'";
1981 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1982 * MySQL uses `backticks` while basically everything else uses double quotes.
1983 * Since MySQL is the odd one out here the double quotes are our generic
1984 * and we implement backticks in DatabaseMysql.
1986 * @param string $s
1987 * @return string
1989 public function addIdentifierQuotes( $s ) {
1990 return '"' . str_replace( '"', '""', $s ) . '"';
1994 * Returns if the given identifier looks quoted or not according to
1995 * the database convention for quoting identifiers .
1997 * @note Do not use this to determine if untrusted input is safe.
1998 * A malicious user can trick this function.
1999 * @param string $name
2000 * @return bool
2002 public function isQuotedIdentifier( $name ) {
2003 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2007 * @param string $s
2008 * @return string
2010 protected function escapeLikeInternal( $s ) {
2011 return addcslashes( $s, '\%_' );
2014 public function buildLike() {
2015 $params = func_get_args();
2017 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2018 $params = $params[0];
2021 $s = '';
2023 foreach ( $params as $value ) {
2024 if ( $value instanceof LikeMatch ) {
2025 $s .= $value->toString();
2026 } else {
2027 $s .= $this->escapeLikeInternal( $value );
2031 return " LIKE {$this->addQuotes( $s )} ";
2034 public function anyChar() {
2035 return new LikeMatch( '_' );
2038 public function anyString() {
2039 return new LikeMatch( '%' );
2042 public function nextSequenceValue( $seqName ) {
2043 return null;
2047 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2048 * is only needed because a) MySQL must be as efficient as possible due to
2049 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2050 * which index to pick. Anyway, other databases might have different
2051 * indexes on a given table. So don't bother overriding this unless you're
2052 * MySQL.
2053 * @param string $index
2054 * @return string
2056 public function useIndexClause( $index ) {
2057 return '';
2061 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2062 * is only needed because a) MySQL must be as efficient as possible due to
2063 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2064 * which index to pick. Anyway, other databases might have different
2065 * indexes on a given table. So don't bother overriding this unless you're
2066 * MySQL.
2067 * @param string $index
2068 * @return string
2070 public function ignoreIndexClause( $index ) {
2071 return '';
2074 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2075 $quotedTable = $this->tableName( $table );
2077 if ( count( $rows ) == 0 ) {
2078 return;
2081 # Single row case
2082 if ( !is_array( reset( $rows ) ) ) {
2083 $rows = [ $rows ];
2086 // @FXIME: this is not atomic, but a trx would break affectedRows()
2087 foreach ( $rows as $row ) {
2088 # Delete rows which collide
2089 if ( $uniqueIndexes ) {
2090 $sql = "DELETE FROM $quotedTable WHERE ";
2091 $first = true;
2092 foreach ( $uniqueIndexes as $index ) {
2093 if ( $first ) {
2094 $first = false;
2095 $sql .= '( ';
2096 } else {
2097 $sql .= ' ) OR ( ';
2099 if ( is_array( $index ) ) {
2100 $first2 = true;
2101 foreach ( $index as $col ) {
2102 if ( $first2 ) {
2103 $first2 = false;
2104 } else {
2105 $sql .= ' AND ';
2107 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2109 } else {
2110 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2113 $sql .= ' )';
2114 $this->query( $sql, $fname );
2117 # Now insert the row
2118 $this->insert( $table, $row, $fname );
2123 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2124 * statement.
2126 * @param string $table Table name
2127 * @param array|string $rows Row(s) to insert
2128 * @param string $fname Caller function name
2130 * @return ResultWrapper
2132 protected function nativeReplace( $table, $rows, $fname ) {
2133 $table = $this->tableName( $table );
2135 # Single row case
2136 if ( !is_array( reset( $rows ) ) ) {
2137 $rows = [ $rows ];
2140 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2141 $first = true;
2143 foreach ( $rows as $row ) {
2144 if ( $first ) {
2145 $first = false;
2146 } else {
2147 $sql .= ',';
2150 $sql .= '(' . $this->makeList( $row ) . ')';
2153 return $this->query( $sql, $fname );
2156 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2157 $fname = __METHOD__
2159 if ( !count( $rows ) ) {
2160 return true; // nothing to do
2163 if ( !is_array( reset( $rows ) ) ) {
2164 $rows = [ $rows ];
2167 if ( count( $uniqueIndexes ) ) {
2168 $clauses = []; // list WHERE clauses that each identify a single row
2169 foreach ( $rows as $row ) {
2170 foreach ( $uniqueIndexes as $index ) {
2171 $index = is_array( $index ) ? $index : [ $index ]; // columns
2172 $rowKey = []; // unique key to this row
2173 foreach ( $index as $column ) {
2174 $rowKey[$column] = $row[$column];
2176 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2179 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2180 } else {
2181 $where = false;
2184 $useTrx = !$this->mTrxLevel;
2185 if ( $useTrx ) {
2186 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2188 try {
2189 # Update any existing conflicting row(s)
2190 if ( $where !== false ) {
2191 $ok = $this->update( $table, $set, $where, $fname );
2192 } else {
2193 $ok = true;
2195 # Now insert any non-conflicting row(s)
2196 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2197 } catch ( Exception $e ) {
2198 if ( $useTrx ) {
2199 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2201 throw $e;
2203 if ( $useTrx ) {
2204 $this->commit( $fname, self::FLUSHING_INTERNAL );
2207 return $ok;
2210 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2211 $fname = __METHOD__
2213 if ( !$conds ) {
2214 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2217 $delTable = $this->tableName( $delTable );
2218 $joinTable = $this->tableName( $joinTable );
2219 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2220 if ( $conds != '*' ) {
2221 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2223 $sql .= ')';
2225 $this->query( $sql, $fname );
2228 public function textFieldSize( $table, $field ) {
2229 $table = $this->tableName( $table );
2230 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2231 $res = $this->query( $sql, __METHOD__ );
2232 $row = $this->fetchObject( $res );
2234 $m = [];
2236 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2237 $size = $m[1];
2238 } else {
2239 $size = -1;
2242 return $size;
2245 public function delete( $table, $conds, $fname = __METHOD__ ) {
2246 if ( !$conds ) {
2247 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2250 $table = $this->tableName( $table );
2251 $sql = "DELETE FROM $table";
2253 if ( $conds != '*' ) {
2254 if ( is_array( $conds ) ) {
2255 $conds = $this->makeList( $conds, self::LIST_AND );
2257 $sql .= ' WHERE ' . $conds;
2260 return $this->query( $sql, $fname );
2263 public function insertSelect(
2264 $destTable, $srcTable, $varMap, $conds,
2265 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2267 if ( $this->cliMode ) {
2268 // For massive migrations with downtime, we don't want to select everything
2269 // into memory and OOM, so do all this native on the server side if possible.
2270 return $this->nativeInsertSelect(
2271 $destTable,
2272 $srcTable,
2273 $varMap,
2274 $conds,
2275 $fname,
2276 $insertOptions,
2277 $selectOptions
2281 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2282 // on only the master (without needing row-based-replication). It also makes it easy to
2283 // know how big the INSERT is going to be.
2284 $fields = [];
2285 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2286 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2288 $selectOptions[] = 'FOR UPDATE';
2289 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2290 if ( !$res ) {
2291 return false;
2294 $rows = [];
2295 foreach ( $res as $row ) {
2296 $rows[] = (array)$row;
2299 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2302 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2303 $fname = __METHOD__,
2304 $insertOptions = [], $selectOptions = []
2306 $destTable = $this->tableName( $destTable );
2308 if ( !is_array( $insertOptions ) ) {
2309 $insertOptions = [ $insertOptions ];
2312 $insertOptions = $this->makeInsertOptions( $insertOptions );
2314 if ( !is_array( $selectOptions ) ) {
2315 $selectOptions = [ $selectOptions ];
2318 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2319 $selectOptions );
2321 if ( is_array( $srcTable ) ) {
2322 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2323 } else {
2324 $srcTable = $this->tableName( $srcTable );
2327 $sql = "INSERT $insertOptions" .
2328 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2329 " SELECT $startOpts " . implode( ',', $varMap ) .
2330 " FROM $srcTable $useIndex $ignoreIndex ";
2332 if ( $conds != '*' ) {
2333 if ( is_array( $conds ) ) {
2334 $conds = $this->makeList( $conds, self::LIST_AND );
2336 $sql .= " WHERE $conds";
2339 $sql .= " $tailOpts";
2341 return $this->query( $sql, $fname );
2345 * Construct a LIMIT query with optional offset. This is used for query
2346 * pages. The SQL should be adjusted so that only the first $limit rows
2347 * are returned. If $offset is provided as well, then the first $offset
2348 * rows should be discarded, and the next $limit rows should be returned.
2349 * If the result of the query is not ordered, then the rows to be returned
2350 * are theoretically arbitrary.
2352 * $sql is expected to be a SELECT, if that makes a difference.
2354 * The version provided by default works in MySQL and SQLite. It will very
2355 * likely need to be overridden for most other DBMSes.
2357 * @param string $sql SQL query we will append the limit too
2358 * @param int $limit The SQL limit
2359 * @param int|bool $offset The SQL offset (default false)
2360 * @throws DBUnexpectedError
2361 * @return string
2363 public function limitResult( $sql, $limit, $offset = false ) {
2364 if ( !is_numeric( $limit ) ) {
2365 throw new DBUnexpectedError( $this,
2366 "Invalid non-numeric limit passed to limitResult()\n" );
2369 return "$sql LIMIT "
2370 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2371 . "{$limit} ";
2374 public function unionSupportsOrderAndLimit() {
2375 return true; // True for almost every DB supported
2378 public function unionQueries( $sqls, $all ) {
2379 $glue = $all ? ') UNION ALL (' : ') UNION (';
2381 return '(' . implode( $glue, $sqls ) . ')';
2384 public function conditional( $cond, $trueVal, $falseVal ) {
2385 if ( is_array( $cond ) ) {
2386 $cond = $this->makeList( $cond, self::LIST_AND );
2389 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2392 public function strreplace( $orig, $old, $new ) {
2393 return "REPLACE({$orig}, {$old}, {$new})";
2396 public function getServerUptime() {
2397 return 0;
2400 public function wasDeadlock() {
2401 return false;
2404 public function wasLockTimeout() {
2405 return false;
2408 public function wasErrorReissuable() {
2409 return false;
2412 public function wasReadOnlyError() {
2413 return false;
2417 * Do not use this method outside of Database/DBError classes
2419 * @param integer|string $errno
2420 * @return bool Whether the given query error was a connection drop
2422 public function wasConnectionError( $errno ) {
2423 return false;
2426 public function deadlockLoop() {
2427 $args = func_get_args();
2428 $function = array_shift( $args );
2429 $tries = self::DEADLOCK_TRIES;
2431 $this->begin( __METHOD__ );
2433 $retVal = null;
2434 /** @var Exception $e */
2435 $e = null;
2436 do {
2437 try {
2438 $retVal = call_user_func_array( $function, $args );
2439 break;
2440 } catch ( DBQueryError $e ) {
2441 if ( $this->wasDeadlock() ) {
2442 // Retry after a randomized delay
2443 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2444 } else {
2445 // Throw the error back up
2446 throw $e;
2449 } while ( --$tries > 0 );
2451 if ( $tries <= 0 ) {
2452 // Too many deadlocks; give up
2453 $this->rollback( __METHOD__ );
2454 throw $e;
2455 } else {
2456 $this->commit( __METHOD__ );
2458 return $retVal;
2462 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2463 # Real waits are implemented in the subclass.
2464 return 0;
2467 public function getReplicaPos() {
2468 # Stub
2469 return false;
2472 public function getMasterPos() {
2473 # Stub
2474 return false;
2477 public function serverIsReadOnly() {
2478 return false;
2481 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2482 if ( !$this->mTrxLevel ) {
2483 throw new DBUnexpectedError( $this, "No transaction is active." );
2485 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2488 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2489 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2490 if ( !$this->mTrxLevel ) {
2491 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2495 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2496 if ( $this->mTrxLevel ) {
2497 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2498 } else {
2499 // If no transaction is active, then make one for this callback
2500 $this->startAtomic( __METHOD__ );
2501 try {
2502 call_user_func( $callback );
2503 $this->endAtomic( __METHOD__ );
2504 } catch ( Exception $e ) {
2505 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2506 throw $e;
2511 final public function setTransactionListener( $name, callable $callback = null ) {
2512 if ( $callback ) {
2513 $this->mTrxRecurringCallbacks[$name] = $callback;
2514 } else {
2515 unset( $this->mTrxRecurringCallbacks[$name] );
2520 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2522 * This method should not be used outside of Database/LoadBalancer
2524 * @param bool $suppress
2525 * @since 1.28
2527 final public function setTrxEndCallbackSuppression( $suppress ) {
2528 $this->mTrxEndCallbacksSuppressed = $suppress;
2532 * Actually run and consume any "on transaction idle/resolution" callbacks.
2534 * This method should not be used outside of Database/LoadBalancer
2536 * @param integer $trigger IDatabase::TRIGGER_* constant
2537 * @since 1.20
2538 * @throws Exception
2540 public function runOnTransactionIdleCallbacks( $trigger ) {
2541 if ( $this->mTrxEndCallbacksSuppressed ) {
2542 return;
2545 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2546 /** @var Exception $e */
2547 $e = null; // first exception
2548 do { // callbacks may add callbacks :)
2549 $callbacks = array_merge(
2550 $this->mTrxIdleCallbacks,
2551 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2553 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2554 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2555 foreach ( $callbacks as $callback ) {
2556 try {
2557 list( $phpCallback ) = $callback;
2558 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2559 call_user_func_array( $phpCallback, [ $trigger ] );
2560 if ( $autoTrx ) {
2561 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2562 } else {
2563 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2565 } catch ( Exception $ex ) {
2566 call_user_func( $this->errorLogger, $ex );
2567 $e = $e ?: $ex;
2568 // Some callbacks may use startAtomic/endAtomic, so make sure
2569 // their transactions are ended so other callbacks don't fail
2570 if ( $this->trxLevel() ) {
2571 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2575 } while ( count( $this->mTrxIdleCallbacks ) );
2577 if ( $e instanceof Exception ) {
2578 throw $e; // re-throw any first exception
2583 * Actually run and consume any "on transaction pre-commit" callbacks.
2585 * This method should not be used outside of Database/LoadBalancer
2587 * @since 1.22
2588 * @throws Exception
2590 public function runOnTransactionPreCommitCallbacks() {
2591 $e = null; // first exception
2592 do { // callbacks may add callbacks :)
2593 $callbacks = $this->mTrxPreCommitCallbacks;
2594 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2595 foreach ( $callbacks as $callback ) {
2596 try {
2597 list( $phpCallback ) = $callback;
2598 call_user_func( $phpCallback );
2599 } catch ( Exception $ex ) {
2600 call_user_func( $this->errorLogger, $ex );
2601 $e = $e ?: $ex;
2604 } while ( count( $this->mTrxPreCommitCallbacks ) );
2606 if ( $e instanceof Exception ) {
2607 throw $e; // re-throw any first exception
2612 * Actually run any "transaction listener" callbacks.
2614 * This method should not be used outside of Database/LoadBalancer
2616 * @param integer $trigger IDatabase::TRIGGER_* constant
2617 * @throws Exception
2618 * @since 1.20
2620 public function runTransactionListenerCallbacks( $trigger ) {
2621 if ( $this->mTrxEndCallbacksSuppressed ) {
2622 return;
2625 /** @var Exception $e */
2626 $e = null; // first exception
2628 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2629 try {
2630 $phpCallback( $trigger, $this );
2631 } catch ( Exception $ex ) {
2632 call_user_func( $this->errorLogger, $ex );
2633 $e = $e ?: $ex;
2637 if ( $e instanceof Exception ) {
2638 throw $e; // re-throw any first exception
2642 final public function startAtomic( $fname = __METHOD__ ) {
2643 if ( !$this->mTrxLevel ) {
2644 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2645 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2646 // in all changes being in one transaction to keep requests transactional.
2647 if ( !$this->getFlag( self::DBO_TRX ) ) {
2648 $this->mTrxAutomaticAtomic = true;
2652 $this->mTrxAtomicLevels[] = $fname;
2655 final public function endAtomic( $fname = __METHOD__ ) {
2656 if ( !$this->mTrxLevel ) {
2657 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2659 if ( !$this->mTrxAtomicLevels ||
2660 array_pop( $this->mTrxAtomicLevels ) !== $fname
2662 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2665 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2666 $this->commit( $fname, self::FLUSHING_INTERNAL );
2670 final public function doAtomicSection( $fname, callable $callback ) {
2671 $this->startAtomic( $fname );
2672 try {
2673 $res = call_user_func_array( $callback, [ $this, $fname ] );
2674 } catch ( Exception $e ) {
2675 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2676 throw $e;
2678 $this->endAtomic( $fname );
2680 return $res;
2683 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2684 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2685 if ( $this->mTrxLevel ) {
2686 if ( $this->mTrxAtomicLevels ) {
2687 $levels = implode( ', ', $this->mTrxAtomicLevels );
2688 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2689 throw new DBUnexpectedError( $this, $msg );
2690 } elseif ( !$this->mTrxAutomatic ) {
2691 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2692 throw new DBUnexpectedError( $this, $msg );
2693 } else {
2694 // @TODO: make this an exception at some point
2695 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2696 $this->queryLogger->error( $msg );
2697 return; // join the main transaction set
2699 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2700 // @TODO: make this an exception at some point
2701 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2702 $this->queryLogger->error( $msg );
2703 return; // let any writes be in the main transaction
2706 // Avoid fatals if close() was called
2707 $this->assertOpen();
2709 $this->doBegin( $fname );
2710 $this->mTrxTimestamp = microtime( true );
2711 $this->mTrxFname = $fname;
2712 $this->mTrxDoneWrites = false;
2713 $this->mTrxAutomaticAtomic = false;
2714 $this->mTrxAtomicLevels = [];
2715 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2716 $this->mTrxWriteDuration = 0.0;
2717 $this->mTrxWriteQueryCount = 0;
2718 $this->mTrxWriteAdjDuration = 0.0;
2719 $this->mTrxWriteAdjQueryCount = 0;
2720 $this->mTrxWriteCallers = [];
2721 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2722 // Get an estimate of the replica DB lag before then, treating estimate staleness
2723 // as lag itself just to be safe
2724 $status = $this->getApproximateLagStatus();
2725 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2726 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2727 // caller will think its OK to muck around with the transaction just because startAtomic()
2728 // has not yet completed (e.g. setting mTrxAtomicLevels).
2729 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2733 * Issues the BEGIN command to the database server.
2735 * @see Database::begin()
2736 * @param string $fname
2738 protected function doBegin( $fname ) {
2739 $this->query( 'BEGIN', $fname );
2740 $this->mTrxLevel = 1;
2743 final public function commit( $fname = __METHOD__, $flush = '' ) {
2744 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2745 // There are still atomic sections open. This cannot be ignored
2746 $levels = implode( ', ', $this->mTrxAtomicLevels );
2747 throw new DBUnexpectedError(
2748 $this,
2749 "$fname: Got COMMIT while atomic sections $levels are still open."
2753 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2754 if ( !$this->mTrxLevel ) {
2755 return; // nothing to do
2756 } elseif ( !$this->mTrxAutomatic ) {
2757 throw new DBUnexpectedError(
2758 $this,
2759 "$fname: Flushing an explicit transaction, getting out of sync."
2762 } else {
2763 if ( !$this->mTrxLevel ) {
2764 $this->queryLogger->error(
2765 "$fname: No transaction to commit, something got out of sync." );
2766 return; // nothing to do
2767 } elseif ( $this->mTrxAutomatic ) {
2768 // @TODO: make this an exception at some point
2769 $msg = "$fname: Explicit commit of implicit transaction.";
2770 $this->queryLogger->error( $msg );
2771 return; // wait for the main transaction set commit round
2775 // Avoid fatals if close() was called
2776 $this->assertOpen();
2778 $this->runOnTransactionPreCommitCallbacks();
2779 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2780 $this->doCommit( $fname );
2781 if ( $this->mTrxDoneWrites ) {
2782 $this->mLastWriteTime = microtime( true );
2783 $this->trxProfiler->transactionWritingOut(
2784 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2787 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2788 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2792 * Issues the COMMIT command to the database server.
2794 * @see Database::commit()
2795 * @param string $fname
2797 protected function doCommit( $fname ) {
2798 if ( $this->mTrxLevel ) {
2799 $this->query( 'COMMIT', $fname );
2800 $this->mTrxLevel = 0;
2804 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2805 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2806 if ( !$this->mTrxLevel ) {
2807 return; // nothing to do
2809 } else {
2810 if ( !$this->mTrxLevel ) {
2811 $this->queryLogger->error(
2812 "$fname: No transaction to rollback, something got out of sync." );
2813 return; // nothing to do
2814 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
2815 throw new DBUnexpectedError(
2816 $this,
2817 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2822 // Avoid fatals if close() was called
2823 $this->assertOpen();
2825 $this->doRollback( $fname );
2826 $this->mTrxAtomicLevels = [];
2827 if ( $this->mTrxDoneWrites ) {
2828 $this->trxProfiler->transactionWritingOut(
2829 $this->mServer, $this->mDBname, $this->mTrxShortId );
2832 $this->mTrxIdleCallbacks = []; // clear
2833 $this->mTrxPreCommitCallbacks = []; // clear
2834 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2835 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2839 * Issues the ROLLBACK command to the database server.
2841 * @see Database::rollback()
2842 * @param string $fname
2844 protected function doRollback( $fname ) {
2845 if ( $this->mTrxLevel ) {
2846 # Disconnects cause rollback anyway, so ignore those errors
2847 $ignoreErrors = true;
2848 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2849 $this->mTrxLevel = 0;
2853 public function flushSnapshot( $fname = __METHOD__ ) {
2854 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
2855 // This only flushes transactions to clear snapshots, not to write data
2856 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2857 throw new DBUnexpectedError(
2858 $this,
2859 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2863 $this->commit( $fname, self::FLUSHING_INTERNAL );
2866 public function explicitTrxActive() {
2867 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
2870 public function duplicateTableStructure(
2871 $oldName, $newName, $temporary = false, $fname = __METHOD__
2873 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2876 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2877 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2880 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2881 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2884 public function timestamp( $ts = 0 ) {
2885 $t = new ConvertibleTimestamp( $ts );
2886 // Let errors bubble up to avoid putting garbage in the DB
2887 return $t->getTimestamp( TS_MW );
2890 public function timestampOrNull( $ts = null ) {
2891 if ( is_null( $ts ) ) {
2892 return null;
2893 } else {
2894 return $this->timestamp( $ts );
2899 * Take the result from a query, and wrap it in a ResultWrapper if
2900 * necessary. Boolean values are passed through as is, to indicate success
2901 * of write queries or failure.
2903 * Once upon a time, Database::query() returned a bare MySQL result
2904 * resource, and it was necessary to call this function to convert it to
2905 * a wrapper. Nowadays, raw database objects are never exposed to external
2906 * callers, so this is unnecessary in external code.
2908 * @param bool|ResultWrapper|resource|object $result
2909 * @return bool|ResultWrapper
2911 protected function resultObject( $result ) {
2912 if ( !$result ) {
2913 return false;
2914 } elseif ( $result instanceof ResultWrapper ) {
2915 return $result;
2916 } elseif ( $result === true ) {
2917 // Successful write query
2918 return $result;
2919 } else {
2920 return new ResultWrapper( $this, $result );
2924 public function ping( &$rtt = null ) {
2925 // Avoid hitting the server if it was hit recently
2926 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2927 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2928 $rtt = $this->mRTTEstimate;
2929 return true; // don't care about $rtt
2933 // This will reconnect if possible or return false if not
2934 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
2935 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
2936 $this->restoreFlags( self::RESTORE_PRIOR );
2938 if ( $ok ) {
2939 $rtt = $this->mRTTEstimate;
2942 return $ok;
2946 * @return bool
2948 protected function reconnect() {
2949 $this->closeConnection();
2950 $this->mOpened = false;
2951 $this->mConn = false;
2952 try {
2953 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2954 $this->lastPing = microtime( true );
2955 $ok = true;
2956 } catch ( DBConnectionError $e ) {
2957 $ok = false;
2960 return $ok;
2963 public function getSessionLagStatus() {
2964 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2968 * Get the replica DB lag when the current transaction started
2970 * This is useful when transactions might use snapshot isolation
2971 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2972 * is this lag plus transaction duration. If they don't, it is still
2973 * safe to be pessimistic. This returns null if there is no transaction.
2975 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2976 * @since 1.27
2978 protected function getTransactionLagStatus() {
2979 return $this->mTrxLevel
2980 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
2981 : null;
2985 * Get a replica DB lag estimate for this server
2987 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2988 * @since 1.27
2990 protected function getApproximateLagStatus() {
2991 return [
2992 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
2993 'since' => microtime( true )
2998 * Merge the result of getSessionLagStatus() for several DBs
2999 * using the most pessimistic values to estimate the lag of
3000 * any data derived from them in combination
3002 * This is information is useful for caching modules
3004 * @see WANObjectCache::set()
3005 * @see WANObjectCache::getWithSetCallback()
3007 * @param IDatabase $db1
3008 * @param IDatabase ...
3009 * @return array Map of values:
3010 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3011 * - since: oldest UNIX timestamp of any of the DB lag estimates
3012 * - pending: whether any of the DBs have uncommitted changes
3013 * @since 1.27
3015 public static function getCacheSetOptions( IDatabase $db1 ) {
3016 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3017 foreach ( func_get_args() as $db ) {
3018 /** @var IDatabase $db */
3019 $status = $db->getSessionLagStatus();
3020 if ( $status['lag'] === false ) {
3021 $res['lag'] = false;
3022 } elseif ( $res['lag'] !== false ) {
3023 $res['lag'] = max( $res['lag'], $status['lag'] );
3025 $res['since'] = min( $res['since'], $status['since'] );
3026 $res['pending'] = $res['pending'] ?: $db->writesPending();
3029 return $res;
3032 public function getLag() {
3033 return 0;
3036 public function maxListLen() {
3037 return 0;
3040 public function encodeBlob( $b ) {
3041 return $b;
3044 public function decodeBlob( $b ) {
3045 if ( $b instanceof Blob ) {
3046 $b = $b->fetch();
3048 return $b;
3051 public function setSessionOptions( array $options ) {
3054 public function sourceFile(
3055 $filename,
3056 callable $lineCallback = null,
3057 callable $resultCallback = null,
3058 $fname = false,
3059 callable $inputCallback = null
3061 MediaWiki\suppressWarnings();
3062 $fp = fopen( $filename, 'r' );
3063 MediaWiki\restoreWarnings();
3065 if ( false === $fp ) {
3066 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3069 if ( !$fname ) {
3070 $fname = __METHOD__ . "( $filename )";
3073 try {
3074 $error = $this->sourceStream(
3075 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3076 } catch ( Exception $e ) {
3077 fclose( $fp );
3078 throw $e;
3081 fclose( $fp );
3083 return $error;
3086 public function setSchemaVars( $vars ) {
3087 $this->mSchemaVars = $vars;
3090 public function sourceStream(
3091 $fp,
3092 callable $lineCallback = null,
3093 callable $resultCallback = null,
3094 $fname = __METHOD__,
3095 callable $inputCallback = null
3097 $cmd = '';
3099 while ( !feof( $fp ) ) {
3100 if ( $lineCallback ) {
3101 call_user_func( $lineCallback );
3104 $line = trim( fgets( $fp ) );
3106 if ( $line == '' ) {
3107 continue;
3110 if ( '-' == $line[0] && '-' == $line[1] ) {
3111 continue;
3114 if ( $cmd != '' ) {
3115 $cmd .= ' ';
3118 $done = $this->streamStatementEnd( $cmd, $line );
3120 $cmd .= "$line\n";
3122 if ( $done || feof( $fp ) ) {
3123 $cmd = $this->replaceVars( $cmd );
3125 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3126 $res = $this->query( $cmd, $fname );
3128 if ( $resultCallback ) {
3129 call_user_func( $resultCallback, $res, $this );
3132 if ( false === $res ) {
3133 $err = $this->lastError();
3135 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3138 $cmd = '';
3142 return true;
3146 * Called by sourceStream() to check if we've reached a statement end
3148 * @param string &$sql SQL assembled so far
3149 * @param string &$newLine New line about to be added to $sql
3150 * @return bool Whether $newLine contains end of the statement
3152 public function streamStatementEnd( &$sql, &$newLine ) {
3153 if ( $this->delimiter ) {
3154 $prev = $newLine;
3155 $newLine = preg_replace(
3156 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3157 if ( $newLine != $prev ) {
3158 return true;
3162 return false;
3166 * Database independent variable replacement. Replaces a set of variables
3167 * in an SQL statement with their contents as given by $this->getSchemaVars().
3169 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3171 * - '{$var}' should be used for text and is passed through the database's
3172 * addQuotes method.
3173 * - `{$var}` should be used for identifiers (e.g. table and database names).
3174 * It is passed through the database's addIdentifierQuotes method which
3175 * can be overridden if the database uses something other than backticks.
3176 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3177 * database's tableName method.
3178 * - / *i* / passes the name that follows through the database's indexName method.
3179 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3180 * its use should be avoided. In 1.24 and older, string encoding was applied.
3182 * @param string $ins SQL statement to replace variables in
3183 * @return string The new SQL statement with variables replaced
3185 protected function replaceVars( $ins ) {
3186 $vars = $this->getSchemaVars();
3187 return preg_replace_callback(
3189 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3190 \'\{\$ (\w+) }\' | # 3. addQuotes
3191 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3192 /\*\$ (\w+) \*/ # 5. leave unencoded
3193 !x',
3194 function ( $m ) use ( $vars ) {
3195 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3196 // check for both nonexistent keys *and* the empty string.
3197 if ( isset( $m[1] ) && $m[1] !== '' ) {
3198 if ( $m[1] === 'i' ) {
3199 return $this->indexName( $m[2] );
3200 } else {
3201 return $this->tableName( $m[2] );
3203 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3204 return $this->addQuotes( $vars[$m[3]] );
3205 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3206 return $this->addIdentifierQuotes( $vars[$m[4]] );
3207 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3208 return $vars[$m[5]];
3209 } else {
3210 return $m[0];
3213 $ins
3218 * Get schema variables. If none have been set via setSchemaVars(), then
3219 * use some defaults from the current object.
3221 * @return array
3223 protected function getSchemaVars() {
3224 if ( $this->mSchemaVars ) {
3225 return $this->mSchemaVars;
3226 } else {
3227 return $this->getDefaultSchemaVars();
3232 * Get schema variables to use if none have been set via setSchemaVars().
3234 * Override this in derived classes to provide variables for tables.sql
3235 * and SQL patch files.
3237 * @return array
3239 protected function getDefaultSchemaVars() {
3240 return [];
3243 public function lockIsFree( $lockName, $method ) {
3244 return true;
3247 public function lock( $lockName, $method, $timeout = 5 ) {
3248 $this->mNamedLocksHeld[$lockName] = 1;
3250 return true;
3253 public function unlock( $lockName, $method ) {
3254 unset( $this->mNamedLocksHeld[$lockName] );
3256 return true;
3259 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3260 if ( $this->writesOrCallbacksPending() ) {
3261 // This only flushes transactions to clear snapshots, not to write data
3262 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3263 throw new DBUnexpectedError(
3264 $this,
3265 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3269 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3270 return null;
3273 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3274 if ( $this->trxLevel() ) {
3275 // There is a good chance an exception was thrown, causing any early return
3276 // from the caller. Let any error handler get a chance to issue rollback().
3277 // If there isn't one, let the error bubble up and trigger server-side rollback.
3278 $this->onTransactionResolution(
3279 function () use ( $lockKey, $fname ) {
3280 $this->unlock( $lockKey, $fname );
3282 $fname
3284 } else {
3285 $this->unlock( $lockKey, $fname );
3287 } );
3289 $this->commit( $fname, self::FLUSHING_INTERNAL );
3291 return $unlocker;
3294 public function namedLocksEnqueue() {
3295 return false;
3299 * Lock specific tables
3301 * @param array $read Array of tables to lock for read access
3302 * @param array $write Array of tables to lock for write access
3303 * @param string $method Name of caller
3304 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3305 * @return bool
3307 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3308 return true;
3312 * Unlock specific tables
3314 * @param string $method The caller
3315 * @return bool
3317 public function unlockTables( $method ) {
3318 return true;
3322 * Delete a table
3323 * @param string $tableName
3324 * @param string $fName
3325 * @return bool|ResultWrapper
3326 * @since 1.18
3328 public function dropTable( $tableName, $fName = __METHOD__ ) {
3329 if ( !$this->tableExists( $tableName, $fName ) ) {
3330 return false;
3332 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3334 return $this->query( $sql, $fName );
3337 public function getInfinity() {
3338 return 'infinity';
3341 public function encodeExpiry( $expiry ) {
3342 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3343 ? $this->getInfinity()
3344 : $this->timestamp( $expiry );
3347 public function decodeExpiry( $expiry, $format = TS_MW ) {
3348 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3349 return 'infinity';
3352 return ConvertibleTimestamp::convert( $format, $expiry );
3355 public function setBigSelects( $value = true ) {
3356 // no-op
3359 public function isReadOnly() {
3360 return ( $this->getReadOnlyReason() !== false );
3364 * @return string|bool Reason this DB is read-only or false if it is not
3366 protected function getReadOnlyReason() {
3367 $reason = $this->getLBInfo( 'readOnlyReason' );
3369 return is_string( $reason ) ? $reason : false;
3372 public function setTableAliases( array $aliases ) {
3373 $this->tableAliases = $aliases;
3377 * @return bool Whether a DB user is required to access the DB
3378 * @since 1.28
3380 protected function requiresDatabaseUser() {
3381 return true;
3385 * Get the underlying binding handle, mConn
3387 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3388 * This catches broken callers than catch and ignore disconnection exceptions.
3389 * Unlike checking isOpen(), this is safe to call inside of open().
3391 * @return resource|object
3392 * @throws DBUnexpectedError
3393 * @since 1.26
3395 protected function getBindingHandle() {
3396 if ( !$this->mConn ) {
3397 throw new DBUnexpectedError(
3398 $this,
3399 'DB connection was already closed or the connection dropped.'
3403 return $this->mConn;
3407 * @since 1.19
3408 * @return string
3410 public function __toString() {
3411 return (string)$this->mConn;
3415 * Make sure that copies do not share the same client binding handle
3416 * @throws DBConnectionError
3418 public function __clone() {
3419 $this->connLogger->warning(
3420 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3421 ( new RuntimeException() )->getTraceAsString()
3424 if ( $this->isOpen() ) {
3425 // Open a new connection resource without messing with the old one
3426 $this->mOpened = false;
3427 $this->mConn = false;
3428 $this->mTrxEndCallbacks = []; // don't copy
3429 $this->handleSessionLoss(); // no trx or locks anymore
3430 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3431 $this->lastPing = microtime( true );
3436 * Called by serialize. Throw an exception when DB connection is serialized.
3437 * This causes problems on some database engines because the connection is
3438 * not restored on unserialize.
3440 public function __sleep() {
3441 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3442 'the connection is not restored on wakeup.' );
3446 * Run a few simple sanity checks and close dangling connections
3448 public function __destruct() {
3449 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3450 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3453 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3454 if ( $danglingWriters ) {
3455 $fnames = implode( ', ', $danglingWriters );
3456 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3459 if ( $this->mConn ) {
3460 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3461 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3462 \MediaWiki\suppressWarnings();
3463 $this->closeConnection();
3464 \MediaWiki\restoreWarnings();
3465 $this->mConn = false;
3466 $this->mOpened = false;
3471 class_alias( Database::class, 'DatabaseBase' );