Move ChronologyProtector/TransactionProfiler to Rdbms namespace
[mediawiki.git] / includes / libs / rdbms / database / Database.php
blob68d500ba6c503441f8cc1f6e410eb234df42892a
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;
31 /**
32 * Relational database abstraction object
34 * @ingroup Database
35 * @since 1.28
37 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
38 /** Number of times to re-try an operation in case of deadlock */
39 const DEADLOCK_TRIES = 4;
40 /** Minimum time to wait before retry, in microseconds */
41 const DEADLOCK_DELAY_MIN = 500000;
42 /** Maximum time to wait before retry */
43 const DEADLOCK_DELAY_MAX = 1500000;
45 /** How long before it is worth doing a dummy query to test the connection */
46 const PING_TTL = 1.0;
47 const PING_QUERY = 'SELECT 1 AS ping';
49 const TINY_WRITE_SEC = .010;
50 const SLOW_WRITE_SEC = .500;
51 const SMALL_WRITE_ROWS = 100;
53 /** @var string SQL query */
54 protected $mLastQuery = '';
55 /** @var float|bool UNIX timestamp of last write query */
56 protected $mLastWriteTime = false;
57 /** @var string|bool */
58 protected $mPHPError = false;
59 /** @var string */
60 protected $mServer;
61 /** @var string */
62 protected $mUser;
63 /** @var string */
64 protected $mPassword;
65 /** @var string */
66 protected $mDBname;
67 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
68 protected $tableAliases = [];
69 /** @var bool Whether this PHP instance is for a CLI script */
70 protected $cliMode;
71 /** @var string Agent name for query profiling */
72 protected $agent;
74 /** @var BagOStuff APC cache */
75 protected $srvCache;
76 /** @var LoggerInterface */
77 protected $connLogger;
78 /** @var LoggerInterface */
79 protected $queryLogger;
80 /** @var callback Error logging callback */
81 protected $errorLogger;
83 /** @var resource|null Database connection */
84 protected $mConn = null;
85 /** @var bool */
86 protected $mOpened = false;
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxIdleCallbacks = [];
90 /** @var array[] List of (callable, method name) */
91 protected $mTrxPreCommitCallbacks = [];
92 /** @var array[] List of (callable, method name) */
93 protected $mTrxEndCallbacks = [];
94 /** @var callable[] Map of (name => callable) */
95 protected $mTrxRecurringCallbacks = [];
96 /** @var bool Whether to suppress triggering of transaction end callbacks */
97 protected $mTrxEndCallbacksSuppressed = false;
99 /** @var string */
100 protected $mTablePrefix = '';
101 /** @var string */
102 protected $mSchema = '';
103 /** @var integer */
104 protected $mFlags;
105 /** @var array */
106 protected $mLBInfo = [];
107 /** @var bool|null */
108 protected $mDefaultBigSelects = null;
109 /** @var array|bool */
110 protected $mSchemaVars = false;
111 /** @var array */
112 protected $mSessionVars = [];
113 /** @var array|null */
114 protected $preparedArgs;
115 /** @var string|bool|null Stashed value of html_errors INI setting */
116 protected $htmlErrors;
117 /** @var string */
118 protected $delimiter = ';';
119 /** @var DatabaseDomain */
120 protected $currentDomain;
123 * Either 1 if a transaction is active or 0 otherwise.
124 * The other Trx fields may not be meaningfull if this is 0.
126 * @var int
128 protected $mTrxLevel = 0;
130 * Either a short hexidecimal string if a transaction is active or ""
132 * @var string
133 * @see Database::mTrxLevel
135 protected $mTrxShortId = '';
137 * The UNIX time that the transaction started. Callers can assume that if
138 * snapshot isolation is used, then the data is *at least* up to date to that
139 * point (possibly more up-to-date since the first SELECT defines the snapshot).
141 * @var float|null
142 * @see Database::mTrxLevel
144 private $mTrxTimestamp = null;
145 /** @var float Lag estimate at the time of BEGIN */
146 private $mTrxReplicaLag = null;
148 * Remembers the function name given for starting the most recent transaction via begin().
149 * Used to provide additional context for error reporting.
151 * @var string
152 * @see Database::mTrxLevel
154 private $mTrxFname = null;
156 * Record if possible write queries were done in the last transaction started
158 * @var bool
159 * @see Database::mTrxLevel
161 private $mTrxDoneWrites = false;
163 * Record if the current transaction was started implicitly due to DBO_TRX being set.
165 * @var bool
166 * @see Database::mTrxLevel
168 private $mTrxAutomatic = false;
170 * Array of levels of atomicity within transactions
172 * @var array
174 private $mTrxAtomicLevels = [];
176 * Record if the current transaction was started implicitly by Database::startAtomic
178 * @var bool
180 private $mTrxAutomaticAtomic = false;
182 * Track the write query callers of the current transaction
184 * @var string[]
186 private $mTrxWriteCallers = [];
188 * @var float Seconds spent in write queries for the current transaction
190 private $mTrxWriteDuration = 0.0;
192 * @var integer Number of write queries for the current transaction
194 private $mTrxWriteQueryCount = 0;
196 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
198 private $mTrxWriteAdjDuration = 0.0;
200 * @var integer Number of write queries counted in mTrxWriteAdjDuration
202 private $mTrxWriteAdjQueryCount = 0;
204 * @var float RTT time estimate
206 private $mRTTEstimate = 0.0;
208 /** @var array Map of (name => 1) for locks obtained via lock() */
209 private $mNamedLocksHeld = [];
210 /** @var array Map of (table name => 1) for TEMPORARY tables */
211 protected $mSessionTempTables = [];
213 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
214 private $lazyMasterHandle;
216 /** @var float UNIX timestamp */
217 protected $lastPing = 0.0;
219 /** @var int[] Prior mFlags values */
220 private $priorFlags = [];
222 /** @var object|string Class name or object With profileIn/profileOut methods */
223 protected $profiler;
224 /** @var TransactionProfiler */
225 protected $trxProfiler;
228 * Constructor and database handle and attempt to connect to the DB server
230 * IDatabase classes should not be constructed directly in external
231 * code. Database::factory() should be used instead.
233 * @param array $params Parameters passed from Database::factory()
235 function __construct( array $params ) {
236 $server = $params['host'];
237 $user = $params['user'];
238 $password = $params['password'];
239 $dbName = $params['dbname'];
241 $this->mSchema = $params['schema'];
242 $this->mTablePrefix = $params['tablePrefix'];
244 $this->cliMode = $params['cliMode'];
245 // Agent name is added to SQL queries in a comment, so make sure it can't break out
246 $this->agent = str_replace( '/', '-', $params['agent'] );
248 $this->mFlags = $params['flags'];
249 if ( $this->mFlags & self::DBO_DEFAULT ) {
250 if ( $this->cliMode ) {
251 $this->mFlags &= ~self::DBO_TRX;
252 } else {
253 $this->mFlags |= self::DBO_TRX;
257 $this->mSessionVars = $params['variables'];
259 $this->srvCache = isset( $params['srvCache'] )
260 ? $params['srvCache']
261 : new HashBagOStuff();
263 $this->profiler = $params['profiler'];
264 $this->trxProfiler = $params['trxProfiler'];
265 $this->connLogger = $params['connLogger'];
266 $this->queryLogger = $params['queryLogger'];
267 $this->errorLogger = $params['errorLogger'];
269 // Set initial dummy domain until open() sets the final DB/prefix
270 $this->currentDomain = DatabaseDomain::newUnspecified();
272 if ( $user ) {
273 $this->open( $server, $user, $password, $dbName );
274 } elseif ( $this->requiresDatabaseUser() ) {
275 throw new InvalidArgumentException( "No database user provided." );
278 // Set the domain object after open() sets the relevant fields
279 if ( $this->mDBname != '' ) {
280 // Domains with server scope but a table prefix are not used by IDatabase classes
281 $this->currentDomain = new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix );
286 * Construct a Database subclass instance given a database type and parameters
288 * This also connects to the database immediately upon object construction
290 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
291 * @param array $p Parameter map with keys:
292 * - host : The hostname of the DB server
293 * - user : The name of the database user the client operates under
294 * - password : The password for the database user
295 * - dbname : The name of the database to use where queries do not specify one.
296 * The database must exist or an error might be thrown. Setting this to the empty string
297 * will avoid any such errors and make the handle have no implicit database scope. This is
298 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
299 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
300 * in which user names and such are defined, e.g. users are database-specific in Postgres.
301 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
302 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
303 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
304 * recognized in queries. This can be used in place of schemas for handle site farms.
305 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
306 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
307 * flag in place UNLESS this this database simply acts as a key/value store.
308 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
309 * 'mysql' driver and the newer 'mysqli' driver.
310 * - variables: Optional map of session variables to set after connecting. This can be
311 * used to adjust lock timeouts or encoding modes and the like.
312 * - connLogger: Optional PSR-3 logger interface instance.
313 * - queryLogger: Optional PSR-3 logger interface instance.
314 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
315 * These will be called in query(), using a simplified version of the SQL that also
316 * includes the agent as a SQL comment.
317 * - trxProfiler: Optional TransactionProfiler instance.
318 * - errorLogger: Optional callback that takes an Exception and logs it.
319 * - cliMode: Whether to consider the execution context that of a CLI script.
320 * - agent: Optional name used to identify the end-user in query profiling/logging.
321 * - srvCache: Optional BagOStuff instance to an APC-style cache.
322 * @return Database|null If the database driver or extension cannot be found
323 * @throws InvalidArgumentException If the database driver or extension cannot be found
324 * @since 1.18
326 final public static function factory( $dbType, $p = [] ) {
327 static $canonicalDBTypes = [
328 'mysql' => [ 'mysqli', 'mysql' ],
329 'postgres' => [],
330 'sqlite' => [],
331 'oracle' => [],
332 'mssql' => [],
335 $driver = false;
336 $dbType = strtolower( $dbType );
337 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
338 $possibleDrivers = $canonicalDBTypes[$dbType];
339 if ( !empty( $p['driver'] ) ) {
340 if ( in_array( $p['driver'], $possibleDrivers ) ) {
341 $driver = $p['driver'];
342 } else {
343 throw new InvalidArgumentException( __METHOD__ .
344 " type '$dbType' does not support driver '{$p['driver']}'" );
346 } else {
347 foreach ( $possibleDrivers as $posDriver ) {
348 if ( extension_loaded( $posDriver ) ) {
349 $driver = $posDriver;
350 break;
354 } else {
355 $driver = $dbType;
357 if ( $driver === false || $driver === '' ) {
358 throw new InvalidArgumentException( __METHOD__ .
359 " no viable database extension found for type '$dbType'" );
362 $class = 'Database' . ucfirst( $driver );
363 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
364 // Resolve some defaults for b/c
365 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
366 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
367 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
368 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
369 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
370 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
371 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
372 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
373 $p['cliMode'] = isset( $p['cliMode'] ) ? $p['cliMode'] : ( PHP_SAPI === 'cli' );
374 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
375 if ( !isset( $p['connLogger'] ) ) {
376 $p['connLogger'] = new \Psr\Log\NullLogger();
378 if ( !isset( $p['queryLogger'] ) ) {
379 $p['queryLogger'] = new \Psr\Log\NullLogger();
381 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
382 if ( !isset( $p['trxProfiler'] ) ) {
383 $p['trxProfiler'] = new TransactionProfiler();
385 if ( !isset( $p['errorLogger'] ) ) {
386 $p['errorLogger'] = function ( Exception $e ) {
387 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
391 $conn = new $class( $p );
392 } else {
393 $conn = null;
396 return $conn;
399 public function setLogger( LoggerInterface $logger ) {
400 $this->queryLogger = $logger;
403 public function getServerInfo() {
404 return $this->getServerVersion();
407 public function bufferResults( $buffer = null ) {
408 $res = !$this->getFlag( self::DBO_NOBUFFER );
409 if ( $buffer !== null ) {
410 $buffer
411 ? $this->clearFlag( self::DBO_NOBUFFER )
412 : $this->setFlag( self::DBO_NOBUFFER );
415 return $res;
419 * Turns on (false) or off (true) the automatic generation and sending
420 * of a "we're sorry, but there has been a database error" page on
421 * database errors. Default is on (false). When turned off, the
422 * code should use lastErrno() and lastError() to handle the
423 * situation as appropriate.
425 * Do not use this function outside of the Database classes.
427 * @param null|bool $ignoreErrors
428 * @return bool The previous value of the flag.
430 protected function ignoreErrors( $ignoreErrors = null ) {
431 $res = $this->getFlag( self::DBO_IGNORE );
432 if ( $ignoreErrors !== null ) {
433 $ignoreErrors
434 ? $this->setFlag( self::DBO_IGNORE )
435 : $this->clearFlag( self::DBO_IGNORE );
438 return $res;
441 public function trxLevel() {
442 return $this->mTrxLevel;
445 public function trxTimestamp() {
446 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
449 public function tablePrefix( $prefix = null ) {
450 $old = $this->mTablePrefix;
451 if ( $prefix !== null ) {
452 $this->mTablePrefix = $prefix;
453 $this->currentDomain = ( $this->mDBname != '' )
454 ? new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix )
455 : DatabaseDomain::newUnspecified();
458 return $old;
461 public function dbSchema( $schema = null ) {
462 $old = $this->mSchema;
463 if ( $schema !== null ) {
464 $this->mSchema = $schema;
467 return $old;
470 public function getLBInfo( $name = null ) {
471 if ( is_null( $name ) ) {
472 return $this->mLBInfo;
473 } else {
474 if ( array_key_exists( $name, $this->mLBInfo ) ) {
475 return $this->mLBInfo[$name];
476 } else {
477 return null;
482 public function setLBInfo( $name, $value = null ) {
483 if ( is_null( $value ) ) {
484 $this->mLBInfo = $name;
485 } else {
486 $this->mLBInfo[$name] = $value;
490 public function setLazyMasterHandle( IDatabase $conn ) {
491 $this->lazyMasterHandle = $conn;
495 * @return IDatabase|null
496 * @see setLazyMasterHandle()
497 * @since 1.27
499 protected function getLazyMasterHandle() {
500 return $this->lazyMasterHandle;
503 public function implicitGroupby() {
504 return true;
507 public function implicitOrderby() {
508 return true;
511 public function lastQuery() {
512 return $this->mLastQuery;
515 public function doneWrites() {
516 return (bool)$this->mLastWriteTime;
519 public function lastDoneWrites() {
520 return $this->mLastWriteTime ?: false;
523 public function writesPending() {
524 return $this->mTrxLevel && $this->mTrxDoneWrites;
527 public function writesOrCallbacksPending() {
528 return $this->mTrxLevel && (
529 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
533 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
534 if ( !$this->mTrxLevel ) {
535 return false;
536 } elseif ( !$this->mTrxDoneWrites ) {
537 return 0.0;
540 switch ( $type ) {
541 case self::ESTIMATE_DB_APPLY:
542 $this->ping( $rtt );
543 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
544 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
545 // For omitted queries, make them count as something at least
546 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
547 $applyTime += self::TINY_WRITE_SEC * $omitted;
549 return $applyTime;
550 default: // everything
551 return $this->mTrxWriteDuration;
555 public function pendingWriteCallers() {
556 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
559 protected function pendingWriteAndCallbackCallers() {
560 if ( !$this->mTrxLevel ) {
561 return [];
564 $fnames = $this->mTrxWriteCallers;
565 foreach ( [
566 $this->mTrxIdleCallbacks,
567 $this->mTrxPreCommitCallbacks,
568 $this->mTrxEndCallbacks
569 ] as $callbacks ) {
570 foreach ( $callbacks as $callback ) {
571 $fnames[] = $callback[1];
575 return $fnames;
578 public function isOpen() {
579 return $this->mOpened;
582 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
583 if ( $remember === self::REMEMBER_PRIOR ) {
584 array_push( $this->priorFlags, $this->mFlags );
586 $this->mFlags |= $flag;
589 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
590 if ( $remember === self::REMEMBER_PRIOR ) {
591 array_push( $this->priorFlags, $this->mFlags );
593 $this->mFlags &= ~$flag;
596 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
597 if ( !$this->priorFlags ) {
598 return;
601 if ( $state === self::RESTORE_INITIAL ) {
602 $this->mFlags = reset( $this->priorFlags );
603 $this->priorFlags = [];
604 } else {
605 $this->mFlags = array_pop( $this->priorFlags );
609 public function getFlag( $flag ) {
610 return !!( $this->mFlags & $flag );
614 * @param string $name Class field name
615 * @return mixed
616 * @deprecated Since 1.28
618 public function getProperty( $name ) {
619 return $this->$name;
622 public function getDomainID() {
623 return $this->currentDomain->getId();
626 final public function getWikiID() {
627 return $this->getDomainID();
631 * Get information about an index into an object
632 * @param string $table Table name
633 * @param string $index Index name
634 * @param string $fname Calling function name
635 * @return mixed Database-specific index description class or false if the index does not exist
637 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
640 * Wrapper for addslashes()
642 * @param string $s String to be slashed.
643 * @return string Slashed string.
645 abstract function strencode( $s );
647 protected function installErrorHandler() {
648 $this->mPHPError = false;
649 $this->htmlErrors = ini_set( 'html_errors', '0' );
650 set_error_handler( [ $this, 'connectionErrorLogger' ] );
654 * @return bool|string
656 protected function restoreErrorHandler() {
657 restore_error_handler();
658 if ( $this->htmlErrors !== false ) {
659 ini_set( 'html_errors', $this->htmlErrors );
662 return $this->getLastPHPError();
666 * @return string|bool Last PHP error for this DB (typically connection errors)
668 protected function getLastPHPError() {
669 if ( $this->mPHPError ) {
670 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
671 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
673 return $error;
676 return false;
680 * This method should not be used outside of Database classes
682 * @param int $errno
683 * @param string $errstr
685 public function connectionErrorLogger( $errno, $errstr ) {
686 $this->mPHPError = $errstr;
690 * Create a log context to pass to PSR-3 logger functions.
692 * @param array $extras Additional data to add to context
693 * @return array
695 protected function getLogContext( array $extras = [] ) {
696 return array_merge(
698 'db_server' => $this->mServer,
699 'db_name' => $this->mDBname,
700 'db_user' => $this->mUser,
702 $extras
706 public function close() {
707 if ( $this->mConn ) {
708 if ( $this->trxLevel() ) {
709 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
712 $closed = $this->closeConnection();
713 $this->mConn = false;
714 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
715 throw new RuntimeException( "Transaction callbacks still pending." );
716 } else {
717 $closed = true;
719 $this->mOpened = false;
721 return $closed;
725 * Make sure isOpen() returns true as a sanity check
727 * @throws DBUnexpectedError
729 protected function assertOpen() {
730 if ( !$this->isOpen() ) {
731 throw new DBUnexpectedError( $this, "DB connection was already closed." );
736 * Closes underlying database connection
737 * @since 1.20
738 * @return bool Whether connection was closed successfully
740 abstract protected function closeConnection();
742 public function reportConnectionError( $error = 'Unknown error' ) {
743 $myError = $this->lastError();
744 if ( $myError ) {
745 $error = $myError;
748 # New method
749 throw new DBConnectionError( $this, $error );
753 * The DBMS-dependent part of query()
755 * @param string $sql SQL query.
756 * @return ResultWrapper|bool Result object to feed to fetchObject,
757 * fetchRow, ...; or false on failure
759 abstract protected function doQuery( $sql );
762 * Determine whether a query writes to the DB.
763 * Should return true if unsure.
765 * @param string $sql
766 * @return bool
768 protected function isWriteQuery( $sql ) {
769 return !preg_match(
770 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
774 * @param $sql
775 * @return string|null
777 protected function getQueryVerb( $sql ) {
778 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
782 * Determine whether a SQL statement is sensitive to isolation level.
783 * A SQL statement is considered transactable if its result could vary
784 * depending on the transaction isolation level. Operational commands
785 * such as 'SET' and 'SHOW' are not considered to be transactable.
787 * @param string $sql
788 * @return bool
790 protected function isTransactableQuery( $sql ) {
791 return !in_array(
792 $this->getQueryVerb( $sql ),
793 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
794 true
799 * @param string $sql A SQL query
800 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
802 protected function registerTempTableOperation( $sql ) {
803 if ( preg_match(
804 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
805 $sql,
806 $matches
807 ) ) {
808 $this->mSessionTempTables[$matches[1]] = 1;
810 return true;
811 } elseif ( preg_match(
812 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
813 $sql,
814 $matches
815 ) ) {
816 unset( $this->mSessionTempTables[$matches[1]] );
818 return true;
819 } elseif ( preg_match(
820 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
821 $sql,
822 $matches
823 ) ) {
824 return isset( $this->mSessionTempTables[$matches[1]] );
827 return false;
830 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
831 $priorWritesPending = $this->writesOrCallbacksPending();
832 $this->mLastQuery = $sql;
834 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
835 if ( $isWrite ) {
836 $reason = $this->getReadOnlyReason();
837 if ( $reason !== false ) {
838 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
840 # Set a flag indicating that writes have been done
841 $this->mLastWriteTime = microtime( true );
844 // Add trace comment to the begin of the sql string, right after the operator.
845 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
846 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
848 # Start implicit transactions that wrap the request if DBO_TRX is enabled
849 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
850 && $this->isTransactableQuery( $sql )
852 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
853 $this->mTrxAutomatic = true;
856 # Keep track of whether the transaction has write queries pending
857 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
858 $this->mTrxDoneWrites = true;
859 $this->trxProfiler->transactionWritingIn(
860 $this->mServer, $this->mDBname, $this->mTrxShortId );
863 if ( $this->getFlag( self::DBO_DEBUG ) ) {
864 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
867 # Avoid fatals if close() was called
868 $this->assertOpen();
870 # Send the query to the server
871 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
873 # Try reconnecting if the connection was lost
874 if ( false === $ret && $this->wasErrorReissuable() ) {
875 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
876 # Stash the last error values before anything might clear them
877 $lastError = $this->lastError();
878 $lastErrno = $this->lastErrno();
879 # Update state tracking to reflect transaction loss due to disconnection
880 $this->handleSessionLoss();
881 if ( $this->reconnect() ) {
882 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
883 $this->connLogger->warning( $msg );
884 $this->queryLogger->warning(
885 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
887 if ( !$recoverable ) {
888 # Callers may catch the exception and continue to use the DB
889 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
890 } else {
891 # Should be safe to silently retry the query
892 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
894 } else {
895 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
896 $this->connLogger->error( $msg );
900 if ( false === $ret ) {
901 # Deadlocks cause the entire transaction to abort, not just the statement.
902 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
903 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
904 if ( $this->wasDeadlock() ) {
905 if ( $this->explicitTrxActive() || $priorWritesPending ) {
906 $tempIgnore = false; // not recoverable
908 # Update state tracking to reflect transaction loss
909 $this->handleSessionLoss();
912 $this->reportQueryError(
913 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
916 $res = $this->resultObject( $ret );
918 return $res;
921 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
922 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
923 # generalizeSQL() will probably cut down the query to reasonable
924 # logging size most of the time. The substr is really just a sanity check.
925 if ( $isMaster ) {
926 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
927 } else {
928 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
931 # Include query transaction state
932 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
934 $startTime = microtime( true );
935 if ( $this->profiler ) {
936 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
938 $ret = $this->doQuery( $commentedSql );
939 if ( $this->profiler ) {
940 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
942 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
944 unset( $queryProfSection ); // profile out (if set)
946 if ( $ret !== false ) {
947 $this->lastPing = $startTime;
948 if ( $isWrite && $this->mTrxLevel ) {
949 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
950 $this->mTrxWriteCallers[] = $fname;
954 if ( $sql === self::PING_QUERY ) {
955 $this->mRTTEstimate = $queryRuntime;
958 $this->trxProfiler->recordQueryCompletion(
959 $queryProf, $startTime, $isWrite, $this->affectedRows()
961 $this->queryLogger->debug( $sql, [
962 'method' => $fname,
963 'master' => $isMaster,
964 'runtime' => $queryRuntime,
965 ] );
967 return $ret;
971 * Update the estimated run-time of a query, not counting large row lock times
973 * LoadBalancer can be set to rollback transactions that will create huge replication
974 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
975 * queries, like inserting a row can take a long time due to row locking. This method
976 * uses some simple heuristics to discount those cases.
978 * @param string $sql A SQL write query
979 * @param float $runtime Total runtime, including RTT
981 private function updateTrxWriteQueryTime( $sql, $runtime ) {
982 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
983 $indicativeOfReplicaRuntime = true;
984 if ( $runtime > self::SLOW_WRITE_SEC ) {
985 $verb = $this->getQueryVerb( $sql );
986 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
987 if ( $verb === 'INSERT' ) {
988 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
989 } elseif ( $verb === 'REPLACE' ) {
990 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
994 $this->mTrxWriteDuration += $runtime;
995 $this->mTrxWriteQueryCount += 1;
996 if ( $indicativeOfReplicaRuntime ) {
997 $this->mTrxWriteAdjDuration += $runtime;
998 $this->mTrxWriteAdjQueryCount += 1;
1002 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1003 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1004 # Dropped connections also mean that named locks are automatically released.
1005 # Only allow error suppression in autocommit mode or when the lost transaction
1006 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1007 if ( $this->mNamedLocksHeld ) {
1008 return false; // possible critical section violation
1009 } elseif ( $sql === 'COMMIT' ) {
1010 return !$priorWritesPending; // nothing written anyway? (T127428)
1011 } elseif ( $sql === 'ROLLBACK' ) {
1012 return true; // transaction lost...which is also what was requested :)
1013 } elseif ( $this->explicitTrxActive() ) {
1014 return false; // don't drop atomocity
1015 } elseif ( $priorWritesPending ) {
1016 return false; // prior writes lost from implicit transaction
1019 return true;
1022 private function handleSessionLoss() {
1023 $this->mTrxLevel = 0;
1024 $this->mTrxIdleCallbacks = []; // bug 65263
1025 $this->mTrxPreCommitCallbacks = []; // bug 65263
1026 $this->mSessionTempTables = [];
1027 $this->mNamedLocksHeld = [];
1028 try {
1029 // Handle callbacks in mTrxEndCallbacks
1030 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1031 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1032 return null;
1033 } catch ( Exception $e ) {
1034 // Already logged; move on...
1035 return $e;
1039 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1040 if ( $this->ignoreErrors() || $tempIgnore ) {
1041 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1042 } else {
1043 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1044 $this->queryLogger->error(
1045 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1046 $this->getLogContext( [
1047 'method' => __METHOD__,
1048 'errno' => $errno,
1049 'error' => $error,
1050 'sql1line' => $sql1line,
1051 'fname' => $fname,
1054 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1055 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1059 public function freeResult( $res ) {
1062 public function selectField(
1063 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1065 if ( $var === '*' ) { // sanity
1066 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1069 if ( !is_array( $options ) ) {
1070 $options = [ $options ];
1073 $options['LIMIT'] = 1;
1075 $res = $this->select( $table, $var, $cond, $fname, $options );
1076 if ( $res === false || !$this->numRows( $res ) ) {
1077 return false;
1080 $row = $this->fetchRow( $res );
1082 if ( $row !== false ) {
1083 return reset( $row );
1084 } else {
1085 return false;
1089 public function selectFieldValues(
1090 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1092 if ( $var === '*' ) { // sanity
1093 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1094 } elseif ( !is_string( $var ) ) { // sanity
1095 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1098 if ( !is_array( $options ) ) {
1099 $options = [ $options ];
1102 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1103 if ( $res === false ) {
1104 return false;
1107 $values = [];
1108 foreach ( $res as $row ) {
1109 $values[] = $row->$var;
1112 return $values;
1116 * Returns an optional USE INDEX clause to go after the table, and a
1117 * string to go at the end of the query.
1119 * @param array $options Associative array of options to be turned into
1120 * an SQL query, valid keys are listed in the function.
1121 * @return array
1122 * @see Database::select()
1124 protected function makeSelectOptions( $options ) {
1125 $preLimitTail = $postLimitTail = '';
1126 $startOpts = '';
1128 $noKeyOptions = [];
1130 foreach ( $options as $key => $option ) {
1131 if ( is_numeric( $key ) ) {
1132 $noKeyOptions[$option] = true;
1136 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1138 $preLimitTail .= $this->makeOrderBy( $options );
1140 // if (isset($options['LIMIT'])) {
1141 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1142 // isset($options['OFFSET']) ? $options['OFFSET']
1143 // : false);
1144 // }
1146 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1147 $postLimitTail .= ' FOR UPDATE';
1150 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1151 $postLimitTail .= ' LOCK IN SHARE MODE';
1154 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1155 $startOpts .= 'DISTINCT';
1158 # Various MySQL extensions
1159 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1160 $startOpts .= ' /*! STRAIGHT_JOIN */';
1163 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1164 $startOpts .= ' HIGH_PRIORITY';
1167 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1168 $startOpts .= ' SQL_BIG_RESULT';
1171 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1172 $startOpts .= ' SQL_BUFFER_RESULT';
1175 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1176 $startOpts .= ' SQL_SMALL_RESULT';
1179 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1180 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1183 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1184 $startOpts .= ' SQL_CACHE';
1187 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1188 $startOpts .= ' SQL_NO_CACHE';
1191 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1192 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1193 } else {
1194 $useIndex = '';
1196 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1197 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1198 } else {
1199 $ignoreIndex = '';
1202 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1206 * Returns an optional GROUP BY with an optional HAVING
1208 * @param array $options Associative array of options
1209 * @return string
1210 * @see Database::select()
1211 * @since 1.21
1213 protected function makeGroupByWithHaving( $options ) {
1214 $sql = '';
1215 if ( isset( $options['GROUP BY'] ) ) {
1216 $gb = is_array( $options['GROUP BY'] )
1217 ? implode( ',', $options['GROUP BY'] )
1218 : $options['GROUP BY'];
1219 $sql .= ' GROUP BY ' . $gb;
1221 if ( isset( $options['HAVING'] ) ) {
1222 $having = is_array( $options['HAVING'] )
1223 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1224 : $options['HAVING'];
1225 $sql .= ' HAVING ' . $having;
1228 return $sql;
1232 * Returns an optional ORDER BY
1234 * @param array $options Associative array of options
1235 * @return string
1236 * @see Database::select()
1237 * @since 1.21
1239 protected function makeOrderBy( $options ) {
1240 if ( isset( $options['ORDER BY'] ) ) {
1241 $ob = is_array( $options['ORDER BY'] )
1242 ? implode( ',', $options['ORDER BY'] )
1243 : $options['ORDER BY'];
1245 return ' ORDER BY ' . $ob;
1248 return '';
1251 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1252 $options = [], $join_conds = [] ) {
1253 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1255 return $this->query( $sql, $fname );
1258 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1259 $options = [], $join_conds = []
1261 if ( is_array( $vars ) ) {
1262 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1265 $options = (array)$options;
1266 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1267 ? $options['USE INDEX']
1268 : [];
1269 $ignoreIndexes = (
1270 isset( $options['IGNORE INDEX'] ) &&
1271 is_array( $options['IGNORE INDEX'] )
1273 ? $options['IGNORE INDEX']
1274 : [];
1276 if ( is_array( $table ) ) {
1277 $from = ' FROM ' .
1278 $this->tableNamesWithIndexClauseOrJOIN(
1279 $table, $useIndexes, $ignoreIndexes, $join_conds );
1280 } elseif ( $table != '' ) {
1281 if ( $table[0] == ' ' ) {
1282 $from = ' FROM ' . $table;
1283 } else {
1284 $from = ' FROM ' .
1285 $this->tableNamesWithIndexClauseOrJOIN(
1286 [ $table ], $useIndexes, $ignoreIndexes, [] );
1288 } else {
1289 $from = '';
1292 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1293 $this->makeSelectOptions( $options );
1295 if ( !empty( $conds ) ) {
1296 if ( is_array( $conds ) ) {
1297 $conds = $this->makeList( $conds, self::LIST_AND );
1299 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1300 "WHERE $conds $preLimitTail";
1301 } else {
1302 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1305 if ( isset( $options['LIMIT'] ) ) {
1306 $sql = $this->limitResult( $sql, $options['LIMIT'],
1307 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1309 $sql = "$sql $postLimitTail";
1311 if ( isset( $options['EXPLAIN'] ) ) {
1312 $sql = 'EXPLAIN ' . $sql;
1315 return $sql;
1318 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1319 $options = [], $join_conds = []
1321 $options = (array)$options;
1322 $options['LIMIT'] = 1;
1323 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1325 if ( $res === false ) {
1326 return false;
1329 if ( !$this->numRows( $res ) ) {
1330 return false;
1333 $obj = $this->fetchObject( $res );
1335 return $obj;
1338 public function estimateRowCount(
1339 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1341 $rows = 0;
1342 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1344 if ( $res ) {
1345 $row = $this->fetchRow( $res );
1346 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1349 return $rows;
1352 public function selectRowCount(
1353 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1355 $rows = 0;
1356 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1357 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1359 if ( $res ) {
1360 $row = $this->fetchRow( $res );
1361 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1364 return $rows;
1368 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1369 * It's only slightly flawed. Don't use for anything important.
1371 * @param string $sql A SQL Query
1373 * @return string
1375 protected static function generalizeSQL( $sql ) {
1376 # This does the same as the regexp below would do, but in such a way
1377 # as to avoid crashing php on some large strings.
1378 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1380 $sql = str_replace( "\\\\", '', $sql );
1381 $sql = str_replace( "\\'", '', $sql );
1382 $sql = str_replace( "\\\"", '', $sql );
1383 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1384 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1386 # All newlines, tabs, etc replaced by single space
1387 $sql = preg_replace( '/\s+/', ' ', $sql );
1389 # All numbers => N,
1390 # except the ones surrounded by characters, e.g. l10n
1391 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1392 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1394 return $sql;
1397 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1398 $info = $this->fieldInfo( $table, $field );
1400 return (bool)$info;
1403 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1404 if ( !$this->tableExists( $table ) ) {
1405 return null;
1408 $info = $this->indexInfo( $table, $index, $fname );
1409 if ( is_null( $info ) ) {
1410 return null;
1411 } else {
1412 return $info !== false;
1416 public function tableExists( $table, $fname = __METHOD__ ) {
1417 $tableRaw = $this->tableName( $table, 'raw' );
1418 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1419 return true; // already known to exist
1422 $table = $this->tableName( $table );
1423 $ignoreErrors = true;
1424 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1426 return (bool)$res;
1429 public function indexUnique( $table, $index ) {
1430 $indexInfo = $this->indexInfo( $table, $index );
1432 if ( !$indexInfo ) {
1433 return null;
1436 return !$indexInfo[0]->Non_unique;
1440 * Helper for Database::insert().
1442 * @param array $options
1443 * @return string
1445 protected function makeInsertOptions( $options ) {
1446 return implode( ' ', $options );
1449 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1450 # No rows to insert, easy just return now
1451 if ( !count( $a ) ) {
1452 return true;
1455 $table = $this->tableName( $table );
1457 if ( !is_array( $options ) ) {
1458 $options = [ $options ];
1461 $fh = null;
1462 if ( isset( $options['fileHandle'] ) ) {
1463 $fh = $options['fileHandle'];
1465 $options = $this->makeInsertOptions( $options );
1467 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1468 $multi = true;
1469 $keys = array_keys( $a[0] );
1470 } else {
1471 $multi = false;
1472 $keys = array_keys( $a );
1475 $sql = 'INSERT ' . $options .
1476 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1478 if ( $multi ) {
1479 $first = true;
1480 foreach ( $a as $row ) {
1481 if ( $first ) {
1482 $first = false;
1483 } else {
1484 $sql .= ',';
1486 $sql .= '(' . $this->makeList( $row ) . ')';
1488 } else {
1489 $sql .= '(' . $this->makeList( $a ) . ')';
1492 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1493 return false;
1494 } elseif ( $fh !== null ) {
1495 return true;
1498 return (bool)$this->query( $sql, $fname );
1502 * Make UPDATE options array for Database::makeUpdateOptions
1504 * @param array $options
1505 * @return array
1507 protected function makeUpdateOptionsArray( $options ) {
1508 if ( !is_array( $options ) ) {
1509 $options = [ $options ];
1512 $opts = [];
1514 if ( in_array( 'IGNORE', $options ) ) {
1515 $opts[] = 'IGNORE';
1518 return $opts;
1522 * Make UPDATE options for the Database::update function
1524 * @param array $options The options passed to Database::update
1525 * @return string
1527 protected function makeUpdateOptions( $options ) {
1528 $opts = $this->makeUpdateOptionsArray( $options );
1530 return implode( ' ', $opts );
1533 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1534 $table = $this->tableName( $table );
1535 $opts = $this->makeUpdateOptions( $options );
1536 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1538 if ( $conds !== [] && $conds !== '*' ) {
1539 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1542 return $this->query( $sql, $fname );
1545 public function makeList( $a, $mode = self::LIST_COMMA ) {
1546 if ( !is_array( $a ) ) {
1547 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1550 $first = true;
1551 $list = '';
1553 foreach ( $a as $field => $value ) {
1554 if ( !$first ) {
1555 if ( $mode == self::LIST_AND ) {
1556 $list .= ' AND ';
1557 } elseif ( $mode == self::LIST_OR ) {
1558 $list .= ' OR ';
1559 } else {
1560 $list .= ',';
1562 } else {
1563 $first = false;
1566 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1567 $list .= "($value)";
1568 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1569 $list .= "$value";
1570 } elseif (
1571 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1573 // Remove null from array to be handled separately if found
1574 $includeNull = false;
1575 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1576 $includeNull = true;
1577 unset( $value[$nullKey] );
1579 if ( count( $value ) == 0 && !$includeNull ) {
1580 throw new InvalidArgumentException(
1581 __METHOD__ . ": empty input for field $field" );
1582 } elseif ( count( $value ) == 0 ) {
1583 // only check if $field is null
1584 $list .= "$field IS NULL";
1585 } else {
1586 // IN clause contains at least one valid element
1587 if ( $includeNull ) {
1588 // Group subconditions to ensure correct precedence
1589 $list .= '(';
1591 if ( count( $value ) == 1 ) {
1592 // Special-case single values, as IN isn't terribly efficient
1593 // Don't necessarily assume the single key is 0; we don't
1594 // enforce linear numeric ordering on other arrays here.
1595 $value = array_values( $value )[0];
1596 $list .= $field . " = " . $this->addQuotes( $value );
1597 } else {
1598 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1600 // if null present in array, append IS NULL
1601 if ( $includeNull ) {
1602 $list .= " OR $field IS NULL)";
1605 } elseif ( $value === null ) {
1606 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1607 $list .= "$field IS ";
1608 } elseif ( $mode == self::LIST_SET ) {
1609 $list .= "$field = ";
1611 $list .= 'NULL';
1612 } else {
1613 if (
1614 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1616 $list .= "$field = ";
1618 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1622 return $list;
1625 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1626 $conds = [];
1628 foreach ( $data as $base => $sub ) {
1629 if ( count( $sub ) ) {
1630 $conds[] = $this->makeList(
1631 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1632 self::LIST_AND );
1636 if ( $conds ) {
1637 return $this->makeList( $conds, self::LIST_OR );
1638 } else {
1639 // Nothing to search for...
1640 return false;
1644 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1645 return $valuename;
1648 public function bitNot( $field ) {
1649 return "(~$field)";
1652 public function bitAnd( $fieldLeft, $fieldRight ) {
1653 return "($fieldLeft & $fieldRight)";
1656 public function bitOr( $fieldLeft, $fieldRight ) {
1657 return "($fieldLeft | $fieldRight)";
1660 public function buildConcat( $stringList ) {
1661 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1664 public function buildGroupConcatField(
1665 $delim, $table, $field, $conds = '', $join_conds = []
1667 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1669 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1672 public function buildStringCast( $field ) {
1673 return $field;
1676 public function selectDB( $db ) {
1677 # Stub. Shouldn't cause serious problems if it's not overridden, but
1678 # if your database engine supports a concept similar to MySQL's
1679 # databases you may as well.
1680 $this->mDBname = $db;
1682 return true;
1685 public function getDBname() {
1686 return $this->mDBname;
1689 public function getServer() {
1690 return $this->mServer;
1693 public function tableName( $name, $format = 'quoted' ) {
1694 # Skip the entire process when we have a string quoted on both ends.
1695 # Note that we check the end so that we will still quote any use of
1696 # use of `database`.table. But won't break things if someone wants
1697 # to query a database table with a dot in the name.
1698 if ( $this->isQuotedIdentifier( $name ) ) {
1699 return $name;
1702 # Lets test for any bits of text that should never show up in a table
1703 # name. Basically anything like JOIN or ON which are actually part of
1704 # SQL queries, but may end up inside of the table value to combine
1705 # sql. Such as how the API is doing.
1706 # Note that we use a whitespace test rather than a \b test to avoid
1707 # any remote case where a word like on may be inside of a table name
1708 # surrounded by symbols which may be considered word breaks.
1709 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1710 return $name;
1713 # Split database and table into proper variables.
1714 # We reverse the explode so that database.table and table both output
1715 # the correct table.
1716 $dbDetails = explode( '.', $name, 3 );
1717 if ( count( $dbDetails ) == 3 ) {
1718 list( $database, $schema, $table ) = $dbDetails;
1719 # We don't want any prefix added in this case
1720 $prefix = '';
1721 } elseif ( count( $dbDetails ) == 2 ) {
1722 list( $database, $table ) = $dbDetails;
1723 # We don't want any prefix added in this case
1724 $prefix = '';
1725 # In dbs that support it, $database may actually be the schema
1726 # but that doesn't affect any of the functionality here
1727 $schema = '';
1728 } else {
1729 list( $table ) = $dbDetails;
1730 if ( isset( $this->tableAliases[$table] ) ) {
1731 $database = $this->tableAliases[$table]['dbname'];
1732 $schema = is_string( $this->tableAliases[$table]['schema'] )
1733 ? $this->tableAliases[$table]['schema']
1734 : $this->mSchema;
1735 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1736 ? $this->tableAliases[$table]['prefix']
1737 : $this->mTablePrefix;
1738 } else {
1739 $database = '';
1740 $schema = $this->mSchema; # Default schema
1741 $prefix = $this->mTablePrefix; # Default prefix
1745 # Quote $table and apply the prefix if not quoted.
1746 # $tableName might be empty if this is called from Database::replaceVars()
1747 $tableName = "{$prefix}{$table}";
1748 if ( $format === 'quoted'
1749 && !$this->isQuotedIdentifier( $tableName )
1750 && $tableName !== ''
1752 $tableName = $this->addIdentifierQuotes( $tableName );
1755 # Quote $schema and $database and merge them with the table name if needed
1756 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1757 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1759 return $tableName;
1763 * @param string|null $namespace Database or schema
1764 * @param string $relation Name of table, view, sequence, etc...
1765 * @param string $format One of (raw, quoted)
1766 * @return string Relation name with quoted and merged $namespace as needed
1768 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1769 if ( strlen( $namespace ) ) {
1770 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1771 $namespace = $this->addIdentifierQuotes( $namespace );
1773 $relation = $namespace . '.' . $relation;
1776 return $relation;
1779 public function tableNames() {
1780 $inArray = func_get_args();
1781 $retVal = [];
1783 foreach ( $inArray as $name ) {
1784 $retVal[$name] = $this->tableName( $name );
1787 return $retVal;
1790 public function tableNamesN() {
1791 $inArray = func_get_args();
1792 $retVal = [];
1794 foreach ( $inArray as $name ) {
1795 $retVal[] = $this->tableName( $name );
1798 return $retVal;
1802 * Get an aliased table name
1803 * e.g. tableName AS newTableName
1805 * @param string $name Table name, see tableName()
1806 * @param string|bool $alias Alias (optional)
1807 * @return string SQL name for aliased table. Will not alias a table to its own name
1809 protected function tableNameWithAlias( $name, $alias = false ) {
1810 if ( !$alias || $alias == $name ) {
1811 return $this->tableName( $name );
1812 } else {
1813 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1818 * Gets an array of aliased table names
1820 * @param array $tables [ [alias] => table ]
1821 * @return string[] See tableNameWithAlias()
1823 protected function tableNamesWithAlias( $tables ) {
1824 $retval = [];
1825 foreach ( $tables as $alias => $table ) {
1826 if ( is_numeric( $alias ) ) {
1827 $alias = $table;
1829 $retval[] = $this->tableNameWithAlias( $table, $alias );
1832 return $retval;
1836 * Get an aliased field name
1837 * e.g. fieldName AS newFieldName
1839 * @param string $name Field name
1840 * @param string|bool $alias Alias (optional)
1841 * @return string SQL name for aliased field. Will not alias a field to its own name
1843 protected function fieldNameWithAlias( $name, $alias = false ) {
1844 if ( !$alias || (string)$alias === (string)$name ) {
1845 return $name;
1846 } else {
1847 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1852 * Gets an array of aliased field names
1854 * @param array $fields [ [alias] => field ]
1855 * @return string[] See fieldNameWithAlias()
1857 protected function fieldNamesWithAlias( $fields ) {
1858 $retval = [];
1859 foreach ( $fields as $alias => $field ) {
1860 if ( is_numeric( $alias ) ) {
1861 $alias = $field;
1863 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1866 return $retval;
1870 * Get the aliased table name clause for a FROM clause
1871 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1873 * @param array $tables ( [alias] => table )
1874 * @param array $use_index Same as for select()
1875 * @param array $ignore_index Same as for select()
1876 * @param array $join_conds Same as for select()
1877 * @return string
1879 protected function tableNamesWithIndexClauseOrJOIN(
1880 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1882 $ret = [];
1883 $retJOIN = [];
1884 $use_index = (array)$use_index;
1885 $ignore_index = (array)$ignore_index;
1886 $join_conds = (array)$join_conds;
1888 foreach ( $tables as $alias => $table ) {
1889 if ( !is_string( $alias ) ) {
1890 // No alias? Set it equal to the table name
1891 $alias = $table;
1893 // Is there a JOIN clause for this table?
1894 if ( isset( $join_conds[$alias] ) ) {
1895 list( $joinType, $conds ) = $join_conds[$alias];
1896 $tableClause = $joinType;
1897 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1898 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1899 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1900 if ( $use != '' ) {
1901 $tableClause .= ' ' . $use;
1904 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1905 $ignore = $this->ignoreIndexClause(
1906 implode( ',', (array)$ignore_index[$alias] ) );
1907 if ( $ignore != '' ) {
1908 $tableClause .= ' ' . $ignore;
1911 $on = $this->makeList( (array)$conds, self::LIST_AND );
1912 if ( $on != '' ) {
1913 $tableClause .= ' ON (' . $on . ')';
1916 $retJOIN[] = $tableClause;
1917 } elseif ( isset( $use_index[$alias] ) ) {
1918 // Is there an INDEX clause for this table?
1919 $tableClause = $this->tableNameWithAlias( $table, $alias );
1920 $tableClause .= ' ' . $this->useIndexClause(
1921 implode( ',', (array)$use_index[$alias] )
1924 $ret[] = $tableClause;
1925 } elseif ( isset( $ignore_index[$alias] ) ) {
1926 // Is there an INDEX clause for this table?
1927 $tableClause = $this->tableNameWithAlias( $table, $alias );
1928 $tableClause .= ' ' . $this->ignoreIndexClause(
1929 implode( ',', (array)$ignore_index[$alias] )
1932 $ret[] = $tableClause;
1933 } else {
1934 $tableClause = $this->tableNameWithAlias( $table, $alias );
1936 $ret[] = $tableClause;
1940 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1941 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1942 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1944 // Compile our final table clause
1945 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1949 * Get the name of an index in a given table.
1951 * @param string $index
1952 * @return string
1954 protected function indexName( $index ) {
1955 return $index;
1958 public function addQuotes( $s ) {
1959 if ( $s instanceof Blob ) {
1960 $s = $s->fetch();
1962 if ( $s === null ) {
1963 return 'NULL';
1964 } elseif ( is_bool( $s ) ) {
1965 return (int)$s;
1966 } else {
1967 # This will also quote numeric values. This should be harmless,
1968 # and protects against weird problems that occur when they really
1969 # _are_ strings such as article titles and string->number->string
1970 # conversion is not 1:1.
1971 return "'" . $this->strencode( $s ) . "'";
1976 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1977 * MySQL uses `backticks` while basically everything else uses double quotes.
1978 * Since MySQL is the odd one out here the double quotes are our generic
1979 * and we implement backticks in DatabaseMysql.
1981 * @param string $s
1982 * @return string
1984 public function addIdentifierQuotes( $s ) {
1985 return '"' . str_replace( '"', '""', $s ) . '"';
1989 * Returns if the given identifier looks quoted or not according to
1990 * the database convention for quoting identifiers .
1992 * @note Do not use this to determine if untrusted input is safe.
1993 * A malicious user can trick this function.
1994 * @param string $name
1995 * @return bool
1997 public function isQuotedIdentifier( $name ) {
1998 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2002 * @param string $s
2003 * @return string
2005 protected function escapeLikeInternal( $s ) {
2006 return addcslashes( $s, '\%_' );
2009 public function buildLike() {
2010 $params = func_get_args();
2012 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2013 $params = $params[0];
2016 $s = '';
2018 foreach ( $params as $value ) {
2019 if ( $value instanceof LikeMatch ) {
2020 $s .= $value->toString();
2021 } else {
2022 $s .= $this->escapeLikeInternal( $value );
2026 return " LIKE {$this->addQuotes( $s )} ";
2029 public function anyChar() {
2030 return new LikeMatch( '_' );
2033 public function anyString() {
2034 return new LikeMatch( '%' );
2037 public function nextSequenceValue( $seqName ) {
2038 return null;
2042 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2043 * is only needed because a) MySQL must be as efficient as possible due to
2044 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2045 * which index to pick. Anyway, other databases might have different
2046 * indexes on a given table. So don't bother overriding this unless you're
2047 * MySQL.
2048 * @param string $index
2049 * @return string
2051 public function useIndexClause( $index ) {
2052 return '';
2056 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2057 * is only needed because a) MySQL must be as efficient as possible due to
2058 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2059 * which index to pick. Anyway, other databases might have different
2060 * indexes on a given table. So don't bother overriding this unless you're
2061 * MySQL.
2062 * @param string $index
2063 * @return string
2065 public function ignoreIndexClause( $index ) {
2066 return '';
2069 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2070 $quotedTable = $this->tableName( $table );
2072 if ( count( $rows ) == 0 ) {
2073 return;
2076 # Single row case
2077 if ( !is_array( reset( $rows ) ) ) {
2078 $rows = [ $rows ];
2081 // @FXIME: this is not atomic, but a trx would break affectedRows()
2082 foreach ( $rows as $row ) {
2083 # Delete rows which collide
2084 if ( $uniqueIndexes ) {
2085 $sql = "DELETE FROM $quotedTable WHERE ";
2086 $first = true;
2087 foreach ( $uniqueIndexes as $index ) {
2088 if ( $first ) {
2089 $first = false;
2090 $sql .= '( ';
2091 } else {
2092 $sql .= ' ) OR ( ';
2094 if ( is_array( $index ) ) {
2095 $first2 = true;
2096 foreach ( $index as $col ) {
2097 if ( $first2 ) {
2098 $first2 = false;
2099 } else {
2100 $sql .= ' AND ';
2102 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2104 } else {
2105 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2108 $sql .= ' )';
2109 $this->query( $sql, $fname );
2112 # Now insert the row
2113 $this->insert( $table, $row, $fname );
2118 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2119 * statement.
2121 * @param string $table Table name
2122 * @param array|string $rows Row(s) to insert
2123 * @param string $fname Caller function name
2125 * @return ResultWrapper
2127 protected function nativeReplace( $table, $rows, $fname ) {
2128 $table = $this->tableName( $table );
2130 # Single row case
2131 if ( !is_array( reset( $rows ) ) ) {
2132 $rows = [ $rows ];
2135 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2136 $first = true;
2138 foreach ( $rows as $row ) {
2139 if ( $first ) {
2140 $first = false;
2141 } else {
2142 $sql .= ',';
2145 $sql .= '(' . $this->makeList( $row ) . ')';
2148 return $this->query( $sql, $fname );
2151 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2152 $fname = __METHOD__
2154 if ( !count( $rows ) ) {
2155 return true; // nothing to do
2158 if ( !is_array( reset( $rows ) ) ) {
2159 $rows = [ $rows ];
2162 if ( count( $uniqueIndexes ) ) {
2163 $clauses = []; // list WHERE clauses that each identify a single row
2164 foreach ( $rows as $row ) {
2165 foreach ( $uniqueIndexes as $index ) {
2166 $index = is_array( $index ) ? $index : [ $index ]; // columns
2167 $rowKey = []; // unique key to this row
2168 foreach ( $index as $column ) {
2169 $rowKey[$column] = $row[$column];
2171 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2174 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2175 } else {
2176 $where = false;
2179 $useTrx = !$this->mTrxLevel;
2180 if ( $useTrx ) {
2181 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2183 try {
2184 # Update any existing conflicting row(s)
2185 if ( $where !== false ) {
2186 $ok = $this->update( $table, $set, $where, $fname );
2187 } else {
2188 $ok = true;
2190 # Now insert any non-conflicting row(s)
2191 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2192 } catch ( Exception $e ) {
2193 if ( $useTrx ) {
2194 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2196 throw $e;
2198 if ( $useTrx ) {
2199 $this->commit( $fname, self::FLUSHING_INTERNAL );
2202 return $ok;
2205 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2206 $fname = __METHOD__
2208 if ( !$conds ) {
2209 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2212 $delTable = $this->tableName( $delTable );
2213 $joinTable = $this->tableName( $joinTable );
2214 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2215 if ( $conds != '*' ) {
2216 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2218 $sql .= ')';
2220 $this->query( $sql, $fname );
2223 public function textFieldSize( $table, $field ) {
2224 $table = $this->tableName( $table );
2225 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2226 $res = $this->query( $sql, __METHOD__ );
2227 $row = $this->fetchObject( $res );
2229 $m = [];
2231 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2232 $size = $m[1];
2233 } else {
2234 $size = -1;
2237 return $size;
2240 public function delete( $table, $conds, $fname = __METHOD__ ) {
2241 if ( !$conds ) {
2242 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2245 $table = $this->tableName( $table );
2246 $sql = "DELETE FROM $table";
2248 if ( $conds != '*' ) {
2249 if ( is_array( $conds ) ) {
2250 $conds = $this->makeList( $conds, self::LIST_AND );
2252 $sql .= ' WHERE ' . $conds;
2255 return $this->query( $sql, $fname );
2258 public function insertSelect(
2259 $destTable, $srcTable, $varMap, $conds,
2260 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2262 if ( $this->cliMode ) {
2263 // For massive migrations with downtime, we don't want to select everything
2264 // into memory and OOM, so do all this native on the server side if possible.
2265 return $this->nativeInsertSelect(
2266 $destTable,
2267 $srcTable,
2268 $varMap,
2269 $conds,
2270 $fname,
2271 $insertOptions,
2272 $selectOptions
2276 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2277 // on only the master (without needing row-based-replication). It also makes it easy to
2278 // know how big the INSERT is going to be.
2279 $fields = [];
2280 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2281 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2283 $selectOptions[] = 'FOR UPDATE';
2284 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2285 if ( !$res ) {
2286 return false;
2289 $rows = [];
2290 foreach ( $res as $row ) {
2291 $rows[] = (array)$row;
2294 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2297 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2298 $fname = __METHOD__,
2299 $insertOptions = [], $selectOptions = []
2301 $destTable = $this->tableName( $destTable );
2303 if ( !is_array( $insertOptions ) ) {
2304 $insertOptions = [ $insertOptions ];
2307 $insertOptions = $this->makeInsertOptions( $insertOptions );
2309 if ( !is_array( $selectOptions ) ) {
2310 $selectOptions = [ $selectOptions ];
2313 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2314 $selectOptions );
2316 if ( is_array( $srcTable ) ) {
2317 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2318 } else {
2319 $srcTable = $this->tableName( $srcTable );
2322 $sql = "INSERT $insertOptions" .
2323 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2324 " SELECT $startOpts " . implode( ',', $varMap ) .
2325 " FROM $srcTable $useIndex $ignoreIndex ";
2327 if ( $conds != '*' ) {
2328 if ( is_array( $conds ) ) {
2329 $conds = $this->makeList( $conds, self::LIST_AND );
2331 $sql .= " WHERE $conds";
2334 $sql .= " $tailOpts";
2336 return $this->query( $sql, $fname );
2340 * Construct a LIMIT query with optional offset. This is used for query
2341 * pages. The SQL should be adjusted so that only the first $limit rows
2342 * are returned. If $offset is provided as well, then the first $offset
2343 * rows should be discarded, and the next $limit rows should be returned.
2344 * If the result of the query is not ordered, then the rows to be returned
2345 * are theoretically arbitrary.
2347 * $sql is expected to be a SELECT, if that makes a difference.
2349 * The version provided by default works in MySQL and SQLite. It will very
2350 * likely need to be overridden for most other DBMSes.
2352 * @param string $sql SQL query we will append the limit too
2353 * @param int $limit The SQL limit
2354 * @param int|bool $offset The SQL offset (default false)
2355 * @throws DBUnexpectedError
2356 * @return string
2358 public function limitResult( $sql, $limit, $offset = false ) {
2359 if ( !is_numeric( $limit ) ) {
2360 throw new DBUnexpectedError( $this,
2361 "Invalid non-numeric limit passed to limitResult()\n" );
2364 return "$sql LIMIT "
2365 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2366 . "{$limit} ";
2369 public function unionSupportsOrderAndLimit() {
2370 return true; // True for almost every DB supported
2373 public function unionQueries( $sqls, $all ) {
2374 $glue = $all ? ') UNION ALL (' : ') UNION (';
2376 return '(' . implode( $glue, $sqls ) . ')';
2379 public function conditional( $cond, $trueVal, $falseVal ) {
2380 if ( is_array( $cond ) ) {
2381 $cond = $this->makeList( $cond, self::LIST_AND );
2384 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2387 public function strreplace( $orig, $old, $new ) {
2388 return "REPLACE({$orig}, {$old}, {$new})";
2391 public function getServerUptime() {
2392 return 0;
2395 public function wasDeadlock() {
2396 return false;
2399 public function wasLockTimeout() {
2400 return false;
2403 public function wasErrorReissuable() {
2404 return false;
2407 public function wasReadOnlyError() {
2408 return false;
2412 * Do not use this method outside of Database/DBError classes
2414 * @param integer|string $errno
2415 * @return bool Whether the given query error was a connection drop
2417 public function wasConnectionError( $errno ) {
2418 return false;
2421 public function deadlockLoop() {
2422 $args = func_get_args();
2423 $function = array_shift( $args );
2424 $tries = self::DEADLOCK_TRIES;
2426 $this->begin( __METHOD__ );
2428 $retVal = null;
2429 /** @var Exception $e */
2430 $e = null;
2431 do {
2432 try {
2433 $retVal = call_user_func_array( $function, $args );
2434 break;
2435 } catch ( DBQueryError $e ) {
2436 if ( $this->wasDeadlock() ) {
2437 // Retry after a randomized delay
2438 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2439 } else {
2440 // Throw the error back up
2441 throw $e;
2444 } while ( --$tries > 0 );
2446 if ( $tries <= 0 ) {
2447 // Too many deadlocks; give up
2448 $this->rollback( __METHOD__ );
2449 throw $e;
2450 } else {
2451 $this->commit( __METHOD__ );
2453 return $retVal;
2457 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2458 # Real waits are implemented in the subclass.
2459 return 0;
2462 public function getReplicaPos() {
2463 # Stub
2464 return false;
2467 public function getMasterPos() {
2468 # Stub
2469 return false;
2472 public function serverIsReadOnly() {
2473 return false;
2476 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2477 if ( !$this->mTrxLevel ) {
2478 throw new DBUnexpectedError( $this, "No transaction is active." );
2480 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2483 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2484 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2485 if ( !$this->mTrxLevel ) {
2486 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2490 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2491 if ( $this->mTrxLevel ) {
2492 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2493 } else {
2494 // If no transaction is active, then make one for this callback
2495 $this->startAtomic( __METHOD__ );
2496 try {
2497 call_user_func( $callback );
2498 $this->endAtomic( __METHOD__ );
2499 } catch ( Exception $e ) {
2500 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2501 throw $e;
2506 final public function setTransactionListener( $name, callable $callback = null ) {
2507 if ( $callback ) {
2508 $this->mTrxRecurringCallbacks[$name] = $callback;
2509 } else {
2510 unset( $this->mTrxRecurringCallbacks[$name] );
2515 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2517 * This method should not be used outside of Database/LoadBalancer
2519 * @param bool $suppress
2520 * @since 1.28
2522 final public function setTrxEndCallbackSuppression( $suppress ) {
2523 $this->mTrxEndCallbacksSuppressed = $suppress;
2527 * Actually run and consume any "on transaction idle/resolution" callbacks.
2529 * This method should not be used outside of Database/LoadBalancer
2531 * @param integer $trigger IDatabase::TRIGGER_* constant
2532 * @since 1.20
2533 * @throws Exception
2535 public function runOnTransactionIdleCallbacks( $trigger ) {
2536 if ( $this->mTrxEndCallbacksSuppressed ) {
2537 return;
2540 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2541 /** @var Exception $e */
2542 $e = null; // first exception
2543 do { // callbacks may add callbacks :)
2544 $callbacks = array_merge(
2545 $this->mTrxIdleCallbacks,
2546 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2548 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2549 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2550 foreach ( $callbacks as $callback ) {
2551 try {
2552 list( $phpCallback ) = $callback;
2553 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2554 call_user_func_array( $phpCallback, [ $trigger ] );
2555 if ( $autoTrx ) {
2556 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2557 } else {
2558 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2560 } catch ( Exception $ex ) {
2561 call_user_func( $this->errorLogger, $ex );
2562 $e = $e ?: $ex;
2563 // Some callbacks may use startAtomic/endAtomic, so make sure
2564 // their transactions are ended so other callbacks don't fail
2565 if ( $this->trxLevel() ) {
2566 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2570 } while ( count( $this->mTrxIdleCallbacks ) );
2572 if ( $e instanceof Exception ) {
2573 throw $e; // re-throw any first exception
2578 * Actually run and consume any "on transaction pre-commit" callbacks.
2580 * This method should not be used outside of Database/LoadBalancer
2582 * @since 1.22
2583 * @throws Exception
2585 public function runOnTransactionPreCommitCallbacks() {
2586 $e = null; // first exception
2587 do { // callbacks may add callbacks :)
2588 $callbacks = $this->mTrxPreCommitCallbacks;
2589 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2590 foreach ( $callbacks as $callback ) {
2591 try {
2592 list( $phpCallback ) = $callback;
2593 call_user_func( $phpCallback );
2594 } catch ( Exception $ex ) {
2595 call_user_func( $this->errorLogger, $ex );
2596 $e = $e ?: $ex;
2599 } while ( count( $this->mTrxPreCommitCallbacks ) );
2601 if ( $e instanceof Exception ) {
2602 throw $e; // re-throw any first exception
2607 * Actually run any "transaction listener" callbacks.
2609 * This method should not be used outside of Database/LoadBalancer
2611 * @param integer $trigger IDatabase::TRIGGER_* constant
2612 * @throws Exception
2613 * @since 1.20
2615 public function runTransactionListenerCallbacks( $trigger ) {
2616 if ( $this->mTrxEndCallbacksSuppressed ) {
2617 return;
2620 /** @var Exception $e */
2621 $e = null; // first exception
2623 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2624 try {
2625 $phpCallback( $trigger, $this );
2626 } catch ( Exception $ex ) {
2627 call_user_func( $this->errorLogger, $ex );
2628 $e = $e ?: $ex;
2632 if ( $e instanceof Exception ) {
2633 throw $e; // re-throw any first exception
2637 final public function startAtomic( $fname = __METHOD__ ) {
2638 if ( !$this->mTrxLevel ) {
2639 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2640 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2641 // in all changes being in one transaction to keep requests transactional.
2642 if ( !$this->getFlag( self::DBO_TRX ) ) {
2643 $this->mTrxAutomaticAtomic = true;
2647 $this->mTrxAtomicLevels[] = $fname;
2650 final public function endAtomic( $fname = __METHOD__ ) {
2651 if ( !$this->mTrxLevel ) {
2652 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2654 if ( !$this->mTrxAtomicLevels ||
2655 array_pop( $this->mTrxAtomicLevels ) !== $fname
2657 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2660 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2661 $this->commit( $fname, self::FLUSHING_INTERNAL );
2665 final public function doAtomicSection( $fname, callable $callback ) {
2666 $this->startAtomic( $fname );
2667 try {
2668 $res = call_user_func_array( $callback, [ $this, $fname ] );
2669 } catch ( Exception $e ) {
2670 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2671 throw $e;
2673 $this->endAtomic( $fname );
2675 return $res;
2678 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2679 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2680 if ( $this->mTrxLevel ) {
2681 if ( $this->mTrxAtomicLevels ) {
2682 $levels = implode( ', ', $this->mTrxAtomicLevels );
2683 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2684 throw new DBUnexpectedError( $this, $msg );
2685 } elseif ( !$this->mTrxAutomatic ) {
2686 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2687 throw new DBUnexpectedError( $this, $msg );
2688 } else {
2689 // @TODO: make this an exception at some point
2690 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2691 $this->queryLogger->error( $msg );
2692 return; // join the main transaction set
2694 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2695 // @TODO: make this an exception at some point
2696 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2697 $this->queryLogger->error( $msg );
2698 return; // let any writes be in the main transaction
2701 // Avoid fatals if close() was called
2702 $this->assertOpen();
2704 $this->doBegin( $fname );
2705 $this->mTrxTimestamp = microtime( true );
2706 $this->mTrxFname = $fname;
2707 $this->mTrxDoneWrites = false;
2708 $this->mTrxAutomaticAtomic = false;
2709 $this->mTrxAtomicLevels = [];
2710 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2711 $this->mTrxWriteDuration = 0.0;
2712 $this->mTrxWriteQueryCount = 0;
2713 $this->mTrxWriteAdjDuration = 0.0;
2714 $this->mTrxWriteAdjQueryCount = 0;
2715 $this->mTrxWriteCallers = [];
2716 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2717 // Get an estimate of the replica DB lag before then, treating estimate staleness
2718 // as lag itself just to be safe
2719 $status = $this->getApproximateLagStatus();
2720 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2721 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2722 // caller will think its OK to muck around with the transaction just because startAtomic()
2723 // has not yet completed (e.g. setting mTrxAtomicLevels).
2724 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2728 * Issues the BEGIN command to the database server.
2730 * @see Database::begin()
2731 * @param string $fname
2733 protected function doBegin( $fname ) {
2734 $this->query( 'BEGIN', $fname );
2735 $this->mTrxLevel = 1;
2738 final public function commit( $fname = __METHOD__, $flush = '' ) {
2739 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2740 // There are still atomic sections open. This cannot be ignored
2741 $levels = implode( ', ', $this->mTrxAtomicLevels );
2742 throw new DBUnexpectedError(
2743 $this,
2744 "$fname: Got COMMIT while atomic sections $levels are still open."
2748 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2749 if ( !$this->mTrxLevel ) {
2750 return; // nothing to do
2751 } elseif ( !$this->mTrxAutomatic ) {
2752 throw new DBUnexpectedError(
2753 $this,
2754 "$fname: Flushing an explicit transaction, getting out of sync."
2757 } else {
2758 if ( !$this->mTrxLevel ) {
2759 $this->queryLogger->error(
2760 "$fname: No transaction to commit, something got out of sync." );
2761 return; // nothing to do
2762 } elseif ( $this->mTrxAutomatic ) {
2763 // @TODO: make this an exception at some point
2764 $msg = "$fname: Explicit commit of implicit transaction.";
2765 $this->queryLogger->error( $msg );
2766 return; // wait for the main transaction set commit round
2770 // Avoid fatals if close() was called
2771 $this->assertOpen();
2773 $this->runOnTransactionPreCommitCallbacks();
2774 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2775 $this->doCommit( $fname );
2776 if ( $this->mTrxDoneWrites ) {
2777 $this->mLastWriteTime = microtime( true );
2778 $this->trxProfiler->transactionWritingOut(
2779 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2782 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2783 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2787 * Issues the COMMIT command to the database server.
2789 * @see Database::commit()
2790 * @param string $fname
2792 protected function doCommit( $fname ) {
2793 if ( $this->mTrxLevel ) {
2794 $this->query( 'COMMIT', $fname );
2795 $this->mTrxLevel = 0;
2799 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2800 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2801 if ( !$this->mTrxLevel ) {
2802 return; // nothing to do
2804 } else {
2805 if ( !$this->mTrxLevel ) {
2806 $this->queryLogger->error(
2807 "$fname: No transaction to rollback, something got out of sync." );
2808 return; // nothing to do
2809 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
2810 throw new DBUnexpectedError(
2811 $this,
2812 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2817 // Avoid fatals if close() was called
2818 $this->assertOpen();
2820 $this->doRollback( $fname );
2821 $this->mTrxAtomicLevels = [];
2822 if ( $this->mTrxDoneWrites ) {
2823 $this->trxProfiler->transactionWritingOut(
2824 $this->mServer, $this->mDBname, $this->mTrxShortId );
2827 $this->mTrxIdleCallbacks = []; // clear
2828 $this->mTrxPreCommitCallbacks = []; // clear
2829 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2830 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2834 * Issues the ROLLBACK command to the database server.
2836 * @see Database::rollback()
2837 * @param string $fname
2839 protected function doRollback( $fname ) {
2840 if ( $this->mTrxLevel ) {
2841 # Disconnects cause rollback anyway, so ignore those errors
2842 $ignoreErrors = true;
2843 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2844 $this->mTrxLevel = 0;
2848 public function flushSnapshot( $fname = __METHOD__ ) {
2849 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
2850 // This only flushes transactions to clear snapshots, not to write data
2851 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2852 throw new DBUnexpectedError(
2853 $this,
2854 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2858 $this->commit( $fname, self::FLUSHING_INTERNAL );
2861 public function explicitTrxActive() {
2862 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
2865 public function duplicateTableStructure(
2866 $oldName, $newName, $temporary = false, $fname = __METHOD__
2868 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2871 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2872 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2875 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2876 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2879 public function timestamp( $ts = 0 ) {
2880 $t = new ConvertibleTimestamp( $ts );
2881 // Let errors bubble up to avoid putting garbage in the DB
2882 return $t->getTimestamp( TS_MW );
2885 public function timestampOrNull( $ts = null ) {
2886 if ( is_null( $ts ) ) {
2887 return null;
2888 } else {
2889 return $this->timestamp( $ts );
2894 * Take the result from a query, and wrap it in a ResultWrapper if
2895 * necessary. Boolean values are passed through as is, to indicate success
2896 * of write queries or failure.
2898 * Once upon a time, Database::query() returned a bare MySQL result
2899 * resource, and it was necessary to call this function to convert it to
2900 * a wrapper. Nowadays, raw database objects are never exposed to external
2901 * callers, so this is unnecessary in external code.
2903 * @param bool|ResultWrapper|resource|object $result
2904 * @return bool|ResultWrapper
2906 protected function resultObject( $result ) {
2907 if ( !$result ) {
2908 return false;
2909 } elseif ( $result instanceof ResultWrapper ) {
2910 return $result;
2911 } elseif ( $result === true ) {
2912 // Successful write query
2913 return $result;
2914 } else {
2915 return new ResultWrapper( $this, $result );
2919 public function ping( &$rtt = null ) {
2920 // Avoid hitting the server if it was hit recently
2921 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2922 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2923 $rtt = $this->mRTTEstimate;
2924 return true; // don't care about $rtt
2928 // This will reconnect if possible or return false if not
2929 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
2930 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
2931 $this->restoreFlags( self::RESTORE_PRIOR );
2933 if ( $ok ) {
2934 $rtt = $this->mRTTEstimate;
2937 return $ok;
2941 * @return bool
2943 protected function reconnect() {
2944 $this->closeConnection();
2945 $this->mOpened = false;
2946 $this->mConn = false;
2947 try {
2948 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2949 $this->lastPing = microtime( true );
2950 $ok = true;
2951 } catch ( DBConnectionError $e ) {
2952 $ok = false;
2955 return $ok;
2958 public function getSessionLagStatus() {
2959 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2963 * Get the replica DB lag when the current transaction started
2965 * This is useful when transactions might use snapshot isolation
2966 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2967 * is this lag plus transaction duration. If they don't, it is still
2968 * safe to be pessimistic. This returns null if there is no transaction.
2970 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2971 * @since 1.27
2973 protected function getTransactionLagStatus() {
2974 return $this->mTrxLevel
2975 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
2976 : null;
2980 * Get a replica DB lag estimate for this server
2982 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2983 * @since 1.27
2985 protected function getApproximateLagStatus() {
2986 return [
2987 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
2988 'since' => microtime( true )
2993 * Merge the result of getSessionLagStatus() for several DBs
2994 * using the most pessimistic values to estimate the lag of
2995 * any data derived from them in combination
2997 * This is information is useful for caching modules
2999 * @see WANObjectCache::set()
3000 * @see WANObjectCache::getWithSetCallback()
3002 * @param IDatabase $db1
3003 * @param IDatabase ...
3004 * @return array Map of values:
3005 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3006 * - since: oldest UNIX timestamp of any of the DB lag estimates
3007 * - pending: whether any of the DBs have uncommitted changes
3008 * @since 1.27
3010 public static function getCacheSetOptions( IDatabase $db1 ) {
3011 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3012 foreach ( func_get_args() as $db ) {
3013 /** @var IDatabase $db */
3014 $status = $db->getSessionLagStatus();
3015 if ( $status['lag'] === false ) {
3016 $res['lag'] = false;
3017 } elseif ( $res['lag'] !== false ) {
3018 $res['lag'] = max( $res['lag'], $status['lag'] );
3020 $res['since'] = min( $res['since'], $status['since'] );
3021 $res['pending'] = $res['pending'] ?: $db->writesPending();
3024 return $res;
3027 public function getLag() {
3028 return 0;
3031 public function maxListLen() {
3032 return 0;
3035 public function encodeBlob( $b ) {
3036 return $b;
3039 public function decodeBlob( $b ) {
3040 if ( $b instanceof Blob ) {
3041 $b = $b->fetch();
3043 return $b;
3046 public function setSessionOptions( array $options ) {
3049 public function sourceFile(
3050 $filename,
3051 callable $lineCallback = null,
3052 callable $resultCallback = null,
3053 $fname = false,
3054 callable $inputCallback = null
3056 MediaWiki\suppressWarnings();
3057 $fp = fopen( $filename, 'r' );
3058 MediaWiki\restoreWarnings();
3060 if ( false === $fp ) {
3061 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3064 if ( !$fname ) {
3065 $fname = __METHOD__ . "( $filename )";
3068 try {
3069 $error = $this->sourceStream(
3070 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3071 } catch ( Exception $e ) {
3072 fclose( $fp );
3073 throw $e;
3076 fclose( $fp );
3078 return $error;
3081 public function setSchemaVars( $vars ) {
3082 $this->mSchemaVars = $vars;
3085 public function sourceStream(
3086 $fp,
3087 callable $lineCallback = null,
3088 callable $resultCallback = null,
3089 $fname = __METHOD__,
3090 callable $inputCallback = null
3092 $cmd = '';
3094 while ( !feof( $fp ) ) {
3095 if ( $lineCallback ) {
3096 call_user_func( $lineCallback );
3099 $line = trim( fgets( $fp ) );
3101 if ( $line == '' ) {
3102 continue;
3105 if ( '-' == $line[0] && '-' == $line[1] ) {
3106 continue;
3109 if ( $cmd != '' ) {
3110 $cmd .= ' ';
3113 $done = $this->streamStatementEnd( $cmd, $line );
3115 $cmd .= "$line\n";
3117 if ( $done || feof( $fp ) ) {
3118 $cmd = $this->replaceVars( $cmd );
3120 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3121 $res = $this->query( $cmd, $fname );
3123 if ( $resultCallback ) {
3124 call_user_func( $resultCallback, $res, $this );
3127 if ( false === $res ) {
3128 $err = $this->lastError();
3130 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3133 $cmd = '';
3137 return true;
3141 * Called by sourceStream() to check if we've reached a statement end
3143 * @param string &$sql SQL assembled so far
3144 * @param string &$newLine New line about to be added to $sql
3145 * @return bool Whether $newLine contains end of the statement
3147 public function streamStatementEnd( &$sql, &$newLine ) {
3148 if ( $this->delimiter ) {
3149 $prev = $newLine;
3150 $newLine = preg_replace(
3151 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3152 if ( $newLine != $prev ) {
3153 return true;
3157 return false;
3161 * Database independent variable replacement. Replaces a set of variables
3162 * in an SQL statement with their contents as given by $this->getSchemaVars().
3164 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3166 * - '{$var}' should be used for text and is passed through the database's
3167 * addQuotes method.
3168 * - `{$var}` should be used for identifiers (e.g. table and database names).
3169 * It is passed through the database's addIdentifierQuotes method which
3170 * can be overridden if the database uses something other than backticks.
3171 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3172 * database's tableName method.
3173 * - / *i* / passes the name that follows through the database's indexName method.
3174 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3175 * its use should be avoided. In 1.24 and older, string encoding was applied.
3177 * @param string $ins SQL statement to replace variables in
3178 * @return string The new SQL statement with variables replaced
3180 protected function replaceVars( $ins ) {
3181 $vars = $this->getSchemaVars();
3182 return preg_replace_callback(
3184 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3185 \'\{\$ (\w+) }\' | # 3. addQuotes
3186 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3187 /\*\$ (\w+) \*/ # 5. leave unencoded
3188 !x',
3189 function ( $m ) use ( $vars ) {
3190 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3191 // check for both nonexistent keys *and* the empty string.
3192 if ( isset( $m[1] ) && $m[1] !== '' ) {
3193 if ( $m[1] === 'i' ) {
3194 return $this->indexName( $m[2] );
3195 } else {
3196 return $this->tableName( $m[2] );
3198 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3199 return $this->addQuotes( $vars[$m[3]] );
3200 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3201 return $this->addIdentifierQuotes( $vars[$m[4]] );
3202 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3203 return $vars[$m[5]];
3204 } else {
3205 return $m[0];
3208 $ins
3213 * Get schema variables. If none have been set via setSchemaVars(), then
3214 * use some defaults from the current object.
3216 * @return array
3218 protected function getSchemaVars() {
3219 if ( $this->mSchemaVars ) {
3220 return $this->mSchemaVars;
3221 } else {
3222 return $this->getDefaultSchemaVars();
3227 * Get schema variables to use if none have been set via setSchemaVars().
3229 * Override this in derived classes to provide variables for tables.sql
3230 * and SQL patch files.
3232 * @return array
3234 protected function getDefaultSchemaVars() {
3235 return [];
3238 public function lockIsFree( $lockName, $method ) {
3239 return true;
3242 public function lock( $lockName, $method, $timeout = 5 ) {
3243 $this->mNamedLocksHeld[$lockName] = 1;
3245 return true;
3248 public function unlock( $lockName, $method ) {
3249 unset( $this->mNamedLocksHeld[$lockName] );
3251 return true;
3254 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3255 if ( $this->writesOrCallbacksPending() ) {
3256 // This only flushes transactions to clear snapshots, not to write data
3257 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3258 throw new DBUnexpectedError(
3259 $this,
3260 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3264 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3265 return null;
3268 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3269 if ( $this->trxLevel() ) {
3270 // There is a good chance an exception was thrown, causing any early return
3271 // from the caller. Let any error handler get a chance to issue rollback().
3272 // If there isn't one, let the error bubble up and trigger server-side rollback.
3273 $this->onTransactionResolution(
3274 function () use ( $lockKey, $fname ) {
3275 $this->unlock( $lockKey, $fname );
3277 $fname
3279 } else {
3280 $this->unlock( $lockKey, $fname );
3282 } );
3284 $this->commit( $fname, self::FLUSHING_INTERNAL );
3286 return $unlocker;
3289 public function namedLocksEnqueue() {
3290 return false;
3294 * Lock specific tables
3296 * @param array $read Array of tables to lock for read access
3297 * @param array $write Array of tables to lock for write access
3298 * @param string $method Name of caller
3299 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3300 * @return bool
3302 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3303 return true;
3307 * Unlock specific tables
3309 * @param string $method The caller
3310 * @return bool
3312 public function unlockTables( $method ) {
3313 return true;
3317 * Delete a table
3318 * @param string $tableName
3319 * @param string $fName
3320 * @return bool|ResultWrapper
3321 * @since 1.18
3323 public function dropTable( $tableName, $fName = __METHOD__ ) {
3324 if ( !$this->tableExists( $tableName, $fName ) ) {
3325 return false;
3327 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3329 return $this->query( $sql, $fName );
3332 public function getInfinity() {
3333 return 'infinity';
3336 public function encodeExpiry( $expiry ) {
3337 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3338 ? $this->getInfinity()
3339 : $this->timestamp( $expiry );
3342 public function decodeExpiry( $expiry, $format = TS_MW ) {
3343 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3344 return 'infinity';
3347 return ConvertibleTimestamp::convert( $format, $expiry );
3350 public function setBigSelects( $value = true ) {
3351 // no-op
3354 public function isReadOnly() {
3355 return ( $this->getReadOnlyReason() !== false );
3359 * @return string|bool Reason this DB is read-only or false if it is not
3361 protected function getReadOnlyReason() {
3362 $reason = $this->getLBInfo( 'readOnlyReason' );
3364 return is_string( $reason ) ? $reason : false;
3367 public function setTableAliases( array $aliases ) {
3368 $this->tableAliases = $aliases;
3372 * @return bool Whether a DB user is required to access the DB
3373 * @since 1.28
3375 protected function requiresDatabaseUser() {
3376 return true;
3380 * Get the underlying binding handle, mConn
3382 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3383 * This catches broken callers than catch and ignore disconnection exceptions.
3384 * Unlike checking isOpen(), this is safe to call inside of open().
3386 * @return resource|object
3387 * @throws DBUnexpectedError
3388 * @since 1.26
3390 protected function getBindingHandle() {
3391 if ( !$this->mConn ) {
3392 throw new DBUnexpectedError(
3393 $this,
3394 'DB connection was already closed or the connection dropped.'
3398 return $this->mConn;
3402 * @since 1.19
3403 * @return string
3405 public function __toString() {
3406 return (string)$this->mConn;
3410 * Make sure that copies do not share the same client binding handle
3411 * @throws DBConnectionError
3413 public function __clone() {
3414 $this->connLogger->warning(
3415 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3416 ( new RuntimeException() )->getTraceAsString()
3419 if ( $this->isOpen() ) {
3420 // Open a new connection resource without messing with the old one
3421 $this->mOpened = false;
3422 $this->mConn = false;
3423 $this->mTrxEndCallbacks = []; // don't copy
3424 $this->handleSessionLoss(); // no trx or locks anymore
3425 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3426 $this->lastPing = microtime( true );
3431 * Called by serialize. Throw an exception when DB connection is serialized.
3432 * This causes problems on some database engines because the connection is
3433 * not restored on unserialize.
3435 public function __sleep() {
3436 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3437 'the connection is not restored on wakeup.' );
3441 * Run a few simple sanity checks and close dangling connections
3443 public function __destruct() {
3444 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3445 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3448 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3449 if ( $danglingWriters ) {
3450 $fnames = implode( ', ', $danglingWriters );
3451 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3454 if ( $this->mConn ) {
3455 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3456 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3457 \MediaWiki\suppressWarnings();
3458 $this->closeConnection();
3459 \MediaWiki\restoreWarnings();
3460 $this->mConn = false;
3461 $this->mOpened = false;
3466 class_alias( 'Database', 'DatabaseBase' );