Move DatabaseDomain to Rdbms namespace
[mediawiki.git] / includes / libs / rdbms / database / Database.php
blob72e39b7c2f94c7cff20e1da63fa6ab9fe8be1515
1 <?php
2 /**
3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
23 * @file
24 * @ingroup Database
26 use Psr\Log\LoggerAwareInterface;
27 use Psr\Log\LoggerInterface;
28 use Wikimedia\ScopedCallback;
29 use Wikimedia\Rdbms\TransactionProfiler;
30 use Wikimedia\Rdbms\LikeMatch;
31 use Wikimedia\Rdbms\DatabaseDomain;
33 /**
34 * Relational database abstraction object
36 * @ingroup Database
37 * @since 1.28
39 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
40 /** Number of times to re-try an operation in case of deadlock */
41 const DEADLOCK_TRIES = 4;
42 /** Minimum time to wait before retry, in microseconds */
43 const DEADLOCK_DELAY_MIN = 500000;
44 /** Maximum time to wait before retry */
45 const DEADLOCK_DELAY_MAX = 1500000;
47 /** How long before it is worth doing a dummy query to test the connection */
48 const PING_TTL = 1.0;
49 const PING_QUERY = 'SELECT 1 AS ping';
51 const TINY_WRITE_SEC = .010;
52 const SLOW_WRITE_SEC = .500;
53 const SMALL_WRITE_ROWS = 100;
55 /** @var string SQL query */
56 protected $mLastQuery = '';
57 /** @var float|bool UNIX timestamp of last write query */
58 protected $mLastWriteTime = false;
59 /** @var string|bool */
60 protected $mPHPError = false;
61 /** @var string */
62 protected $mServer;
63 /** @var string */
64 protected $mUser;
65 /** @var string */
66 protected $mPassword;
67 /** @var string */
68 protected $mDBname;
69 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
70 protected $tableAliases = [];
71 /** @var bool Whether this PHP instance is for a CLI script */
72 protected $cliMode;
73 /** @var string Agent name for query profiling */
74 protected $agent;
76 /** @var BagOStuff APC cache */
77 protected $srvCache;
78 /** @var LoggerInterface */
79 protected $connLogger;
80 /** @var LoggerInterface */
81 protected $queryLogger;
82 /** @var callback Error logging callback */
83 protected $errorLogger;
85 /** @var resource|null Database connection */
86 protected $mConn = null;
87 /** @var bool */
88 protected $mOpened = false;
90 /** @var array[] List of (callable, method name) */
91 protected $mTrxIdleCallbacks = [];
92 /** @var array[] List of (callable, method name) */
93 protected $mTrxPreCommitCallbacks = [];
94 /** @var array[] List of (callable, method name) */
95 protected $mTrxEndCallbacks = [];
96 /** @var callable[] Map of (name => callable) */
97 protected $mTrxRecurringCallbacks = [];
98 /** @var bool Whether to suppress triggering of transaction end callbacks */
99 protected $mTrxEndCallbacksSuppressed = false;
101 /** @var string */
102 protected $mTablePrefix = '';
103 /** @var string */
104 protected $mSchema = '';
105 /** @var integer */
106 protected $mFlags;
107 /** @var array */
108 protected $mLBInfo = [];
109 /** @var bool|null */
110 protected $mDefaultBigSelects = null;
111 /** @var array|bool */
112 protected $mSchemaVars = false;
113 /** @var array */
114 protected $mSessionVars = [];
115 /** @var array|null */
116 protected $preparedArgs;
117 /** @var string|bool|null Stashed value of html_errors INI setting */
118 protected $htmlErrors;
119 /** @var string */
120 protected $delimiter = ';';
121 /** @var DatabaseDomain */
122 protected $currentDomain;
125 * Either 1 if a transaction is active or 0 otherwise.
126 * The other Trx fields may not be meaningfull if this is 0.
128 * @var int
130 protected $mTrxLevel = 0;
132 * Either a short hexidecimal string if a transaction is active or ""
134 * @var string
135 * @see Database::mTrxLevel
137 protected $mTrxShortId = '';
139 * The UNIX time that the transaction started. Callers can assume that if
140 * snapshot isolation is used, then the data is *at least* up to date to that
141 * point (possibly more up-to-date since the first SELECT defines the snapshot).
143 * @var float|null
144 * @see Database::mTrxLevel
146 private $mTrxTimestamp = null;
147 /** @var float Lag estimate at the time of BEGIN */
148 private $mTrxReplicaLag = null;
150 * Remembers the function name given for starting the most recent transaction via begin().
151 * Used to provide additional context for error reporting.
153 * @var string
154 * @see Database::mTrxLevel
156 private $mTrxFname = null;
158 * Record if possible write queries were done in the last transaction started
160 * @var bool
161 * @see Database::mTrxLevel
163 private $mTrxDoneWrites = false;
165 * Record if the current transaction was started implicitly due to DBO_TRX being set.
167 * @var bool
168 * @see Database::mTrxLevel
170 private $mTrxAutomatic = false;
172 * Array of levels of atomicity within transactions
174 * @var array
176 private $mTrxAtomicLevels = [];
178 * Record if the current transaction was started implicitly by Database::startAtomic
180 * @var bool
182 private $mTrxAutomaticAtomic = false;
184 * Track the write query callers of the current transaction
186 * @var string[]
188 private $mTrxWriteCallers = [];
190 * @var float Seconds spent in write queries for the current transaction
192 private $mTrxWriteDuration = 0.0;
194 * @var integer Number of write queries for the current transaction
196 private $mTrxWriteQueryCount = 0;
198 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
200 private $mTrxWriteAdjDuration = 0.0;
202 * @var integer Number of write queries counted in mTrxWriteAdjDuration
204 private $mTrxWriteAdjQueryCount = 0;
206 * @var float RTT time estimate
208 private $mRTTEstimate = 0.0;
210 /** @var array Map of (name => 1) for locks obtained via lock() */
211 private $mNamedLocksHeld = [];
212 /** @var array Map of (table name => 1) for TEMPORARY tables */
213 protected $mSessionTempTables = [];
215 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
216 private $lazyMasterHandle;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
224 /** @var object|string Class name or object With profileIn/profileOut methods */
225 protected $profiler;
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
230 * Constructor and database handle and attempt to connect to the DB server
232 * IDatabase classes should not be constructed directly in external
233 * code. Database::factory() should be used instead.
235 * @param array $params Parameters passed from Database::factory()
237 function __construct( array $params ) {
238 $server = $params['host'];
239 $user = $params['user'];
240 $password = $params['password'];
241 $dbName = $params['dbname'];
243 $this->mSchema = $params['schema'];
244 $this->mTablePrefix = $params['tablePrefix'];
246 $this->cliMode = $params['cliMode'];
247 // Agent name is added to SQL queries in a comment, so make sure it can't break out
248 $this->agent = str_replace( '/', '-', $params['agent'] );
250 $this->mFlags = $params['flags'];
251 if ( $this->mFlags & self::DBO_DEFAULT ) {
252 if ( $this->cliMode ) {
253 $this->mFlags &= ~self::DBO_TRX;
254 } else {
255 $this->mFlags |= self::DBO_TRX;
259 $this->mSessionVars = $params['variables'];
261 $this->srvCache = isset( $params['srvCache'] )
262 ? $params['srvCache']
263 : new HashBagOStuff();
265 $this->profiler = $params['profiler'];
266 $this->trxProfiler = $params['trxProfiler'];
267 $this->connLogger = $params['connLogger'];
268 $this->queryLogger = $params['queryLogger'];
269 $this->errorLogger = $params['errorLogger'];
271 // Set initial dummy domain until open() sets the final DB/prefix
272 $this->currentDomain = DatabaseDomain::newUnspecified();
274 if ( $user ) {
275 $this->open( $server, $user, $password, $dbName );
276 } elseif ( $this->requiresDatabaseUser() ) {
277 throw new InvalidArgumentException( "No database user provided." );
280 // Set the domain object after open() sets the relevant fields
281 if ( $this->mDBname != '' ) {
282 // Domains with server scope but a table prefix are not used by IDatabase classes
283 $this->currentDomain = new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix );
288 * Construct a Database subclass instance given a database type and parameters
290 * This also connects to the database immediately upon object construction
292 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
293 * @param array $p Parameter map with keys:
294 * - host : The hostname of the DB server
295 * - user : The name of the database user the client operates under
296 * - password : The password for the database user
297 * - dbname : The name of the database to use where queries do not specify one.
298 * The database must exist or an error might be thrown. Setting this to the empty string
299 * will avoid any such errors and make the handle have no implicit database scope. This is
300 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
301 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
302 * in which user names and such are defined, e.g. users are database-specific in Postgres.
303 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
304 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
305 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
306 * recognized in queries. This can be used in place of schemas for handle site farms.
307 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
308 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
309 * flag in place UNLESS this this database simply acts as a key/value store.
310 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
311 * 'mysql' driver and the newer 'mysqli' driver.
312 * - variables: Optional map of session variables to set after connecting. This can be
313 * used to adjust lock timeouts or encoding modes and the like.
314 * - connLogger: Optional PSR-3 logger interface instance.
315 * - queryLogger: Optional PSR-3 logger interface instance.
316 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
317 * These will be called in query(), using a simplified version of the SQL that also
318 * includes the agent as a SQL comment.
319 * - trxProfiler: Optional TransactionProfiler instance.
320 * - errorLogger: Optional callback that takes an Exception and logs it.
321 * - cliMode: Whether to consider the execution context that of a CLI script.
322 * - agent: Optional name used to identify the end-user in query profiling/logging.
323 * - srvCache: Optional BagOStuff instance to an APC-style cache.
324 * @return Database|null If the database driver or extension cannot be found
325 * @throws InvalidArgumentException If the database driver or extension cannot be found
326 * @since 1.18
328 final public static function factory( $dbType, $p = [] ) {
329 static $canonicalDBTypes = [
330 'mysql' => [ 'mysqli', 'mysql' ],
331 'postgres' => [],
332 'sqlite' => [],
333 'oracle' => [],
334 'mssql' => [],
337 $driver = false;
338 $dbType = strtolower( $dbType );
339 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
340 $possibleDrivers = $canonicalDBTypes[$dbType];
341 if ( !empty( $p['driver'] ) ) {
342 if ( in_array( $p['driver'], $possibleDrivers ) ) {
343 $driver = $p['driver'];
344 } else {
345 throw new InvalidArgumentException( __METHOD__ .
346 " type '$dbType' does not support driver '{$p['driver']}'" );
348 } else {
349 foreach ( $possibleDrivers as $posDriver ) {
350 if ( extension_loaded( $posDriver ) ) {
351 $driver = $posDriver;
352 break;
356 } else {
357 $driver = $dbType;
359 if ( $driver === false || $driver === '' ) {
360 throw new InvalidArgumentException( __METHOD__ .
361 " no viable database extension found for type '$dbType'" );
364 $class = 'Database' . ucfirst( $driver );
365 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
366 // Resolve some defaults for b/c
367 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
368 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
369 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
370 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
371 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
372 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
373 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
374 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
375 $p['cliMode'] = isset( $p['cliMode'] ) ? $p['cliMode'] : ( PHP_SAPI === 'cli' );
376 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
377 if ( !isset( $p['connLogger'] ) ) {
378 $p['connLogger'] = new \Psr\Log\NullLogger();
380 if ( !isset( $p['queryLogger'] ) ) {
381 $p['queryLogger'] = new \Psr\Log\NullLogger();
383 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
384 if ( !isset( $p['trxProfiler'] ) ) {
385 $p['trxProfiler'] = new TransactionProfiler();
387 if ( !isset( $p['errorLogger'] ) ) {
388 $p['errorLogger'] = function ( Exception $e ) {
389 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
393 $conn = new $class( $p );
394 } else {
395 $conn = null;
398 return $conn;
401 public function setLogger( LoggerInterface $logger ) {
402 $this->queryLogger = $logger;
405 public function getServerInfo() {
406 return $this->getServerVersion();
409 public function bufferResults( $buffer = null ) {
410 $res = !$this->getFlag( self::DBO_NOBUFFER );
411 if ( $buffer !== null ) {
412 $buffer
413 ? $this->clearFlag( self::DBO_NOBUFFER )
414 : $this->setFlag( self::DBO_NOBUFFER );
417 return $res;
421 * Turns on (false) or off (true) the automatic generation and sending
422 * of a "we're sorry, but there has been a database error" page on
423 * database errors. Default is on (false). When turned off, the
424 * code should use lastErrno() and lastError() to handle the
425 * situation as appropriate.
427 * Do not use this function outside of the Database classes.
429 * @param null|bool $ignoreErrors
430 * @return bool The previous value of the flag.
432 protected function ignoreErrors( $ignoreErrors = null ) {
433 $res = $this->getFlag( self::DBO_IGNORE );
434 if ( $ignoreErrors !== null ) {
435 $ignoreErrors
436 ? $this->setFlag( self::DBO_IGNORE )
437 : $this->clearFlag( self::DBO_IGNORE );
440 return $res;
443 public function trxLevel() {
444 return $this->mTrxLevel;
447 public function trxTimestamp() {
448 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
451 public function tablePrefix( $prefix = null ) {
452 $old = $this->mTablePrefix;
453 if ( $prefix !== null ) {
454 $this->mTablePrefix = $prefix;
455 $this->currentDomain = ( $this->mDBname != '' )
456 ? new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix )
457 : DatabaseDomain::newUnspecified();
460 return $old;
463 public function dbSchema( $schema = null ) {
464 $old = $this->mSchema;
465 if ( $schema !== null ) {
466 $this->mSchema = $schema;
469 return $old;
472 public function getLBInfo( $name = null ) {
473 if ( is_null( $name ) ) {
474 return $this->mLBInfo;
475 } else {
476 if ( array_key_exists( $name, $this->mLBInfo ) ) {
477 return $this->mLBInfo[$name];
478 } else {
479 return null;
484 public function setLBInfo( $name, $value = null ) {
485 if ( is_null( $value ) ) {
486 $this->mLBInfo = $name;
487 } else {
488 $this->mLBInfo[$name] = $value;
492 public function setLazyMasterHandle( IDatabase $conn ) {
493 $this->lazyMasterHandle = $conn;
497 * @return IDatabase|null
498 * @see setLazyMasterHandle()
499 * @since 1.27
501 protected function getLazyMasterHandle() {
502 return $this->lazyMasterHandle;
505 public function implicitGroupby() {
506 return true;
509 public function implicitOrderby() {
510 return true;
513 public function lastQuery() {
514 return $this->mLastQuery;
517 public function doneWrites() {
518 return (bool)$this->mLastWriteTime;
521 public function lastDoneWrites() {
522 return $this->mLastWriteTime ?: false;
525 public function writesPending() {
526 return $this->mTrxLevel && $this->mTrxDoneWrites;
529 public function writesOrCallbacksPending() {
530 return $this->mTrxLevel && (
531 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
535 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
536 if ( !$this->mTrxLevel ) {
537 return false;
538 } elseif ( !$this->mTrxDoneWrites ) {
539 return 0.0;
542 switch ( $type ) {
543 case self::ESTIMATE_DB_APPLY:
544 $this->ping( $rtt );
545 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
546 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
547 // For omitted queries, make them count as something at least
548 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
549 $applyTime += self::TINY_WRITE_SEC * $omitted;
551 return $applyTime;
552 default: // everything
553 return $this->mTrxWriteDuration;
557 public function pendingWriteCallers() {
558 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
561 protected function pendingWriteAndCallbackCallers() {
562 if ( !$this->mTrxLevel ) {
563 return [];
566 $fnames = $this->mTrxWriteCallers;
567 foreach ( [
568 $this->mTrxIdleCallbacks,
569 $this->mTrxPreCommitCallbacks,
570 $this->mTrxEndCallbacks
571 ] as $callbacks ) {
572 foreach ( $callbacks as $callback ) {
573 $fnames[] = $callback[1];
577 return $fnames;
580 public function isOpen() {
581 return $this->mOpened;
584 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
585 if ( $remember === self::REMEMBER_PRIOR ) {
586 array_push( $this->priorFlags, $this->mFlags );
588 $this->mFlags |= $flag;
591 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
592 if ( $remember === self::REMEMBER_PRIOR ) {
593 array_push( $this->priorFlags, $this->mFlags );
595 $this->mFlags &= ~$flag;
598 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
599 if ( !$this->priorFlags ) {
600 return;
603 if ( $state === self::RESTORE_INITIAL ) {
604 $this->mFlags = reset( $this->priorFlags );
605 $this->priorFlags = [];
606 } else {
607 $this->mFlags = array_pop( $this->priorFlags );
611 public function getFlag( $flag ) {
612 return !!( $this->mFlags & $flag );
616 * @param string $name Class field name
617 * @return mixed
618 * @deprecated Since 1.28
620 public function getProperty( $name ) {
621 return $this->$name;
624 public function getDomainID() {
625 return $this->currentDomain->getId();
628 final public function getWikiID() {
629 return $this->getDomainID();
633 * Get information about an index into an object
634 * @param string $table Table name
635 * @param string $index Index name
636 * @param string $fname Calling function name
637 * @return mixed Database-specific index description class or false if the index does not exist
639 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
642 * Wrapper for addslashes()
644 * @param string $s String to be slashed.
645 * @return string Slashed string.
647 abstract function strencode( $s );
649 protected function installErrorHandler() {
650 $this->mPHPError = false;
651 $this->htmlErrors = ini_set( 'html_errors', '0' );
652 set_error_handler( [ $this, 'connectionErrorLogger' ] );
656 * @return bool|string
658 protected function restoreErrorHandler() {
659 restore_error_handler();
660 if ( $this->htmlErrors !== false ) {
661 ini_set( 'html_errors', $this->htmlErrors );
664 return $this->getLastPHPError();
668 * @return string|bool Last PHP error for this DB (typically connection errors)
670 protected function getLastPHPError() {
671 if ( $this->mPHPError ) {
672 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
673 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
675 return $error;
678 return false;
682 * This method should not be used outside of Database classes
684 * @param int $errno
685 * @param string $errstr
687 public function connectionErrorLogger( $errno, $errstr ) {
688 $this->mPHPError = $errstr;
692 * Create a log context to pass to PSR-3 logger functions.
694 * @param array $extras Additional data to add to context
695 * @return array
697 protected function getLogContext( array $extras = [] ) {
698 return array_merge(
700 'db_server' => $this->mServer,
701 'db_name' => $this->mDBname,
702 'db_user' => $this->mUser,
704 $extras
708 public function close() {
709 if ( $this->mConn ) {
710 if ( $this->trxLevel() ) {
711 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
714 $closed = $this->closeConnection();
715 $this->mConn = false;
716 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
717 throw new RuntimeException( "Transaction callbacks still pending." );
718 } else {
719 $closed = true;
721 $this->mOpened = false;
723 return $closed;
727 * Make sure isOpen() returns true as a sanity check
729 * @throws DBUnexpectedError
731 protected function assertOpen() {
732 if ( !$this->isOpen() ) {
733 throw new DBUnexpectedError( $this, "DB connection was already closed." );
738 * Closes underlying database connection
739 * @since 1.20
740 * @return bool Whether connection was closed successfully
742 abstract protected function closeConnection();
744 public function reportConnectionError( $error = 'Unknown error' ) {
745 $myError = $this->lastError();
746 if ( $myError ) {
747 $error = $myError;
750 # New method
751 throw new DBConnectionError( $this, $error );
755 * The DBMS-dependent part of query()
757 * @param string $sql SQL query.
758 * @return ResultWrapper|bool Result object to feed to fetchObject,
759 * fetchRow, ...; or false on failure
761 abstract protected function doQuery( $sql );
764 * Determine whether a query writes to the DB.
765 * Should return true if unsure.
767 * @param string $sql
768 * @return bool
770 protected function isWriteQuery( $sql ) {
771 return !preg_match(
772 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
776 * @param $sql
777 * @return string|null
779 protected function getQueryVerb( $sql ) {
780 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
784 * Determine whether a SQL statement is sensitive to isolation level.
785 * A SQL statement is considered transactable if its result could vary
786 * depending on the transaction isolation level. Operational commands
787 * such as 'SET' and 'SHOW' are not considered to be transactable.
789 * @param string $sql
790 * @return bool
792 protected function isTransactableQuery( $sql ) {
793 return !in_array(
794 $this->getQueryVerb( $sql ),
795 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
796 true
801 * @param string $sql A SQL query
802 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
804 protected function registerTempTableOperation( $sql ) {
805 if ( preg_match(
806 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
807 $sql,
808 $matches
809 ) ) {
810 $this->mSessionTempTables[$matches[1]] = 1;
812 return true;
813 } elseif ( preg_match(
814 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
815 $sql,
816 $matches
817 ) ) {
818 unset( $this->mSessionTempTables[$matches[1]] );
820 return true;
821 } elseif ( preg_match(
822 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
823 $sql,
824 $matches
825 ) ) {
826 return isset( $this->mSessionTempTables[$matches[1]] );
829 return false;
832 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
833 $priorWritesPending = $this->writesOrCallbacksPending();
834 $this->mLastQuery = $sql;
836 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
837 if ( $isWrite ) {
838 $reason = $this->getReadOnlyReason();
839 if ( $reason !== false ) {
840 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
842 # Set a flag indicating that writes have been done
843 $this->mLastWriteTime = microtime( true );
846 // Add trace comment to the begin of the sql string, right after the operator.
847 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
848 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
850 # Start implicit transactions that wrap the request if DBO_TRX is enabled
851 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
852 && $this->isTransactableQuery( $sql )
854 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
855 $this->mTrxAutomatic = true;
858 # Keep track of whether the transaction has write queries pending
859 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
860 $this->mTrxDoneWrites = true;
861 $this->trxProfiler->transactionWritingIn(
862 $this->mServer, $this->mDBname, $this->mTrxShortId );
865 if ( $this->getFlag( self::DBO_DEBUG ) ) {
866 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
869 # Avoid fatals if close() was called
870 $this->assertOpen();
872 # Send the query to the server
873 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
875 # Try reconnecting if the connection was lost
876 if ( false === $ret && $this->wasErrorReissuable() ) {
877 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
878 # Stash the last error values before anything might clear them
879 $lastError = $this->lastError();
880 $lastErrno = $this->lastErrno();
881 # Update state tracking to reflect transaction loss due to disconnection
882 $this->handleSessionLoss();
883 if ( $this->reconnect() ) {
884 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
885 $this->connLogger->warning( $msg );
886 $this->queryLogger->warning(
887 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
889 if ( !$recoverable ) {
890 # Callers may catch the exception and continue to use the DB
891 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
892 } else {
893 # Should be safe to silently retry the query
894 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
896 } else {
897 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
898 $this->connLogger->error( $msg );
902 if ( false === $ret ) {
903 # Deadlocks cause the entire transaction to abort, not just the statement.
904 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
905 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
906 if ( $this->wasDeadlock() ) {
907 if ( $this->explicitTrxActive() || $priorWritesPending ) {
908 $tempIgnore = false; // not recoverable
910 # Update state tracking to reflect transaction loss
911 $this->handleSessionLoss();
914 $this->reportQueryError(
915 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
918 $res = $this->resultObject( $ret );
920 return $res;
923 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
924 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
925 # generalizeSQL() will probably cut down the query to reasonable
926 # logging size most of the time. The substr is really just a sanity check.
927 if ( $isMaster ) {
928 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
929 } else {
930 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
933 # Include query transaction state
934 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
936 $startTime = microtime( true );
937 if ( $this->profiler ) {
938 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
940 $ret = $this->doQuery( $commentedSql );
941 if ( $this->profiler ) {
942 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
944 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
946 unset( $queryProfSection ); // profile out (if set)
948 if ( $ret !== false ) {
949 $this->lastPing = $startTime;
950 if ( $isWrite && $this->mTrxLevel ) {
951 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
952 $this->mTrxWriteCallers[] = $fname;
956 if ( $sql === self::PING_QUERY ) {
957 $this->mRTTEstimate = $queryRuntime;
960 $this->trxProfiler->recordQueryCompletion(
961 $queryProf, $startTime, $isWrite, $this->affectedRows()
963 $this->queryLogger->debug( $sql, [
964 'method' => $fname,
965 'master' => $isMaster,
966 'runtime' => $queryRuntime,
967 ] );
969 return $ret;
973 * Update the estimated run-time of a query, not counting large row lock times
975 * LoadBalancer can be set to rollback transactions that will create huge replication
976 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
977 * queries, like inserting a row can take a long time due to row locking. This method
978 * uses some simple heuristics to discount those cases.
980 * @param string $sql A SQL write query
981 * @param float $runtime Total runtime, including RTT
983 private function updateTrxWriteQueryTime( $sql, $runtime ) {
984 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
985 $indicativeOfReplicaRuntime = true;
986 if ( $runtime > self::SLOW_WRITE_SEC ) {
987 $verb = $this->getQueryVerb( $sql );
988 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
989 if ( $verb === 'INSERT' ) {
990 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
991 } elseif ( $verb === 'REPLACE' ) {
992 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
996 $this->mTrxWriteDuration += $runtime;
997 $this->mTrxWriteQueryCount += 1;
998 if ( $indicativeOfReplicaRuntime ) {
999 $this->mTrxWriteAdjDuration += $runtime;
1000 $this->mTrxWriteAdjQueryCount += 1;
1004 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1005 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1006 # Dropped connections also mean that named locks are automatically released.
1007 # Only allow error suppression in autocommit mode or when the lost transaction
1008 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1009 if ( $this->mNamedLocksHeld ) {
1010 return false; // possible critical section violation
1011 } elseif ( $sql === 'COMMIT' ) {
1012 return !$priorWritesPending; // nothing written anyway? (T127428)
1013 } elseif ( $sql === 'ROLLBACK' ) {
1014 return true; // transaction lost...which is also what was requested :)
1015 } elseif ( $this->explicitTrxActive() ) {
1016 return false; // don't drop atomocity
1017 } elseif ( $priorWritesPending ) {
1018 return false; // prior writes lost from implicit transaction
1021 return true;
1024 private function handleSessionLoss() {
1025 $this->mTrxLevel = 0;
1026 $this->mTrxIdleCallbacks = []; // bug 65263
1027 $this->mTrxPreCommitCallbacks = []; // bug 65263
1028 $this->mSessionTempTables = [];
1029 $this->mNamedLocksHeld = [];
1030 try {
1031 // Handle callbacks in mTrxEndCallbacks
1032 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1033 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1034 return null;
1035 } catch ( Exception $e ) {
1036 // Already logged; move on...
1037 return $e;
1041 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1042 if ( $this->ignoreErrors() || $tempIgnore ) {
1043 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1044 } else {
1045 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1046 $this->queryLogger->error(
1047 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1048 $this->getLogContext( [
1049 'method' => __METHOD__,
1050 'errno' => $errno,
1051 'error' => $error,
1052 'sql1line' => $sql1line,
1053 'fname' => $fname,
1056 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1057 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1061 public function freeResult( $res ) {
1064 public function selectField(
1065 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1067 if ( $var === '*' ) { // sanity
1068 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1071 if ( !is_array( $options ) ) {
1072 $options = [ $options ];
1075 $options['LIMIT'] = 1;
1077 $res = $this->select( $table, $var, $cond, $fname, $options );
1078 if ( $res === false || !$this->numRows( $res ) ) {
1079 return false;
1082 $row = $this->fetchRow( $res );
1084 if ( $row !== false ) {
1085 return reset( $row );
1086 } else {
1087 return false;
1091 public function selectFieldValues(
1092 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1094 if ( $var === '*' ) { // sanity
1095 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1096 } elseif ( !is_string( $var ) ) { // sanity
1097 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1100 if ( !is_array( $options ) ) {
1101 $options = [ $options ];
1104 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1105 if ( $res === false ) {
1106 return false;
1109 $values = [];
1110 foreach ( $res as $row ) {
1111 $values[] = $row->$var;
1114 return $values;
1118 * Returns an optional USE INDEX clause to go after the table, and a
1119 * string to go at the end of the query.
1121 * @param array $options Associative array of options to be turned into
1122 * an SQL query, valid keys are listed in the function.
1123 * @return array
1124 * @see Database::select()
1126 protected function makeSelectOptions( $options ) {
1127 $preLimitTail = $postLimitTail = '';
1128 $startOpts = '';
1130 $noKeyOptions = [];
1132 foreach ( $options as $key => $option ) {
1133 if ( is_numeric( $key ) ) {
1134 $noKeyOptions[$option] = true;
1138 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1140 $preLimitTail .= $this->makeOrderBy( $options );
1142 // if (isset($options['LIMIT'])) {
1143 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1144 // isset($options['OFFSET']) ? $options['OFFSET']
1145 // : false);
1146 // }
1148 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1149 $postLimitTail .= ' FOR UPDATE';
1152 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1153 $postLimitTail .= ' LOCK IN SHARE MODE';
1156 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1157 $startOpts .= 'DISTINCT';
1160 # Various MySQL extensions
1161 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1162 $startOpts .= ' /*! STRAIGHT_JOIN */';
1165 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1166 $startOpts .= ' HIGH_PRIORITY';
1169 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1170 $startOpts .= ' SQL_BIG_RESULT';
1173 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1174 $startOpts .= ' SQL_BUFFER_RESULT';
1177 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1178 $startOpts .= ' SQL_SMALL_RESULT';
1181 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1182 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1185 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1186 $startOpts .= ' SQL_CACHE';
1189 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1190 $startOpts .= ' SQL_NO_CACHE';
1193 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1194 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1195 } else {
1196 $useIndex = '';
1198 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1199 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1200 } else {
1201 $ignoreIndex = '';
1204 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1208 * Returns an optional GROUP BY with an optional HAVING
1210 * @param array $options Associative array of options
1211 * @return string
1212 * @see Database::select()
1213 * @since 1.21
1215 protected function makeGroupByWithHaving( $options ) {
1216 $sql = '';
1217 if ( isset( $options['GROUP BY'] ) ) {
1218 $gb = is_array( $options['GROUP BY'] )
1219 ? implode( ',', $options['GROUP BY'] )
1220 : $options['GROUP BY'];
1221 $sql .= ' GROUP BY ' . $gb;
1223 if ( isset( $options['HAVING'] ) ) {
1224 $having = is_array( $options['HAVING'] )
1225 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1226 : $options['HAVING'];
1227 $sql .= ' HAVING ' . $having;
1230 return $sql;
1234 * Returns an optional ORDER BY
1236 * @param array $options Associative array of options
1237 * @return string
1238 * @see Database::select()
1239 * @since 1.21
1241 protected function makeOrderBy( $options ) {
1242 if ( isset( $options['ORDER BY'] ) ) {
1243 $ob = is_array( $options['ORDER BY'] )
1244 ? implode( ',', $options['ORDER BY'] )
1245 : $options['ORDER BY'];
1247 return ' ORDER BY ' . $ob;
1250 return '';
1253 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1254 $options = [], $join_conds = [] ) {
1255 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1257 return $this->query( $sql, $fname );
1260 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1261 $options = [], $join_conds = []
1263 if ( is_array( $vars ) ) {
1264 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1267 $options = (array)$options;
1268 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1269 ? $options['USE INDEX']
1270 : [];
1271 $ignoreIndexes = (
1272 isset( $options['IGNORE INDEX'] ) &&
1273 is_array( $options['IGNORE INDEX'] )
1275 ? $options['IGNORE INDEX']
1276 : [];
1278 if ( is_array( $table ) ) {
1279 $from = ' FROM ' .
1280 $this->tableNamesWithIndexClauseOrJOIN(
1281 $table, $useIndexes, $ignoreIndexes, $join_conds );
1282 } elseif ( $table != '' ) {
1283 if ( $table[0] == ' ' ) {
1284 $from = ' FROM ' . $table;
1285 } else {
1286 $from = ' FROM ' .
1287 $this->tableNamesWithIndexClauseOrJOIN(
1288 [ $table ], $useIndexes, $ignoreIndexes, [] );
1290 } else {
1291 $from = '';
1294 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1295 $this->makeSelectOptions( $options );
1297 if ( !empty( $conds ) ) {
1298 if ( is_array( $conds ) ) {
1299 $conds = $this->makeList( $conds, self::LIST_AND );
1301 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1302 "WHERE $conds $preLimitTail";
1303 } else {
1304 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1307 if ( isset( $options['LIMIT'] ) ) {
1308 $sql = $this->limitResult( $sql, $options['LIMIT'],
1309 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1311 $sql = "$sql $postLimitTail";
1313 if ( isset( $options['EXPLAIN'] ) ) {
1314 $sql = 'EXPLAIN ' . $sql;
1317 return $sql;
1320 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1321 $options = [], $join_conds = []
1323 $options = (array)$options;
1324 $options['LIMIT'] = 1;
1325 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1327 if ( $res === false ) {
1328 return false;
1331 if ( !$this->numRows( $res ) ) {
1332 return false;
1335 $obj = $this->fetchObject( $res );
1337 return $obj;
1340 public function estimateRowCount(
1341 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1343 $rows = 0;
1344 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1346 if ( $res ) {
1347 $row = $this->fetchRow( $res );
1348 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1351 return $rows;
1354 public function selectRowCount(
1355 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1357 $rows = 0;
1358 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1359 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1361 if ( $res ) {
1362 $row = $this->fetchRow( $res );
1363 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1366 return $rows;
1370 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1371 * It's only slightly flawed. Don't use for anything important.
1373 * @param string $sql A SQL Query
1375 * @return string
1377 protected static function generalizeSQL( $sql ) {
1378 # This does the same as the regexp below would do, but in such a way
1379 # as to avoid crashing php on some large strings.
1380 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1382 $sql = str_replace( "\\\\", '', $sql );
1383 $sql = str_replace( "\\'", '', $sql );
1384 $sql = str_replace( "\\\"", '', $sql );
1385 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1386 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1388 # All newlines, tabs, etc replaced by single space
1389 $sql = preg_replace( '/\s+/', ' ', $sql );
1391 # All numbers => N,
1392 # except the ones surrounded by characters, e.g. l10n
1393 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1394 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1396 return $sql;
1399 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1400 $info = $this->fieldInfo( $table, $field );
1402 return (bool)$info;
1405 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1406 if ( !$this->tableExists( $table ) ) {
1407 return null;
1410 $info = $this->indexInfo( $table, $index, $fname );
1411 if ( is_null( $info ) ) {
1412 return null;
1413 } else {
1414 return $info !== false;
1418 public function tableExists( $table, $fname = __METHOD__ ) {
1419 $tableRaw = $this->tableName( $table, 'raw' );
1420 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1421 return true; // already known to exist
1424 $table = $this->tableName( $table );
1425 $ignoreErrors = true;
1426 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1428 return (bool)$res;
1431 public function indexUnique( $table, $index ) {
1432 $indexInfo = $this->indexInfo( $table, $index );
1434 if ( !$indexInfo ) {
1435 return null;
1438 return !$indexInfo[0]->Non_unique;
1442 * Helper for Database::insert().
1444 * @param array $options
1445 * @return string
1447 protected function makeInsertOptions( $options ) {
1448 return implode( ' ', $options );
1451 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1452 # No rows to insert, easy just return now
1453 if ( !count( $a ) ) {
1454 return true;
1457 $table = $this->tableName( $table );
1459 if ( !is_array( $options ) ) {
1460 $options = [ $options ];
1463 $fh = null;
1464 if ( isset( $options['fileHandle'] ) ) {
1465 $fh = $options['fileHandle'];
1467 $options = $this->makeInsertOptions( $options );
1469 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1470 $multi = true;
1471 $keys = array_keys( $a[0] );
1472 } else {
1473 $multi = false;
1474 $keys = array_keys( $a );
1477 $sql = 'INSERT ' . $options .
1478 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1480 if ( $multi ) {
1481 $first = true;
1482 foreach ( $a as $row ) {
1483 if ( $first ) {
1484 $first = false;
1485 } else {
1486 $sql .= ',';
1488 $sql .= '(' . $this->makeList( $row ) . ')';
1490 } else {
1491 $sql .= '(' . $this->makeList( $a ) . ')';
1494 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1495 return false;
1496 } elseif ( $fh !== null ) {
1497 return true;
1500 return (bool)$this->query( $sql, $fname );
1504 * Make UPDATE options array for Database::makeUpdateOptions
1506 * @param array $options
1507 * @return array
1509 protected function makeUpdateOptionsArray( $options ) {
1510 if ( !is_array( $options ) ) {
1511 $options = [ $options ];
1514 $opts = [];
1516 if ( in_array( 'IGNORE', $options ) ) {
1517 $opts[] = 'IGNORE';
1520 return $opts;
1524 * Make UPDATE options for the Database::update function
1526 * @param array $options The options passed to Database::update
1527 * @return string
1529 protected function makeUpdateOptions( $options ) {
1530 $opts = $this->makeUpdateOptionsArray( $options );
1532 return implode( ' ', $opts );
1535 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1536 $table = $this->tableName( $table );
1537 $opts = $this->makeUpdateOptions( $options );
1538 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1540 if ( $conds !== [] && $conds !== '*' ) {
1541 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1544 return $this->query( $sql, $fname );
1547 public function makeList( $a, $mode = self::LIST_COMMA ) {
1548 if ( !is_array( $a ) ) {
1549 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1552 $first = true;
1553 $list = '';
1555 foreach ( $a as $field => $value ) {
1556 if ( !$first ) {
1557 if ( $mode == self::LIST_AND ) {
1558 $list .= ' AND ';
1559 } elseif ( $mode == self::LIST_OR ) {
1560 $list .= ' OR ';
1561 } else {
1562 $list .= ',';
1564 } else {
1565 $first = false;
1568 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1569 $list .= "($value)";
1570 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1571 $list .= "$value";
1572 } elseif (
1573 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1575 // Remove null from array to be handled separately if found
1576 $includeNull = false;
1577 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1578 $includeNull = true;
1579 unset( $value[$nullKey] );
1581 if ( count( $value ) == 0 && !$includeNull ) {
1582 throw new InvalidArgumentException(
1583 __METHOD__ . ": empty input for field $field" );
1584 } elseif ( count( $value ) == 0 ) {
1585 // only check if $field is null
1586 $list .= "$field IS NULL";
1587 } else {
1588 // IN clause contains at least one valid element
1589 if ( $includeNull ) {
1590 // Group subconditions to ensure correct precedence
1591 $list .= '(';
1593 if ( count( $value ) == 1 ) {
1594 // Special-case single values, as IN isn't terribly efficient
1595 // Don't necessarily assume the single key is 0; we don't
1596 // enforce linear numeric ordering on other arrays here.
1597 $value = array_values( $value )[0];
1598 $list .= $field . " = " . $this->addQuotes( $value );
1599 } else {
1600 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1602 // if null present in array, append IS NULL
1603 if ( $includeNull ) {
1604 $list .= " OR $field IS NULL)";
1607 } elseif ( $value === null ) {
1608 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1609 $list .= "$field IS ";
1610 } elseif ( $mode == self::LIST_SET ) {
1611 $list .= "$field = ";
1613 $list .= 'NULL';
1614 } else {
1615 if (
1616 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1618 $list .= "$field = ";
1620 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1624 return $list;
1627 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1628 $conds = [];
1630 foreach ( $data as $base => $sub ) {
1631 if ( count( $sub ) ) {
1632 $conds[] = $this->makeList(
1633 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1634 self::LIST_AND );
1638 if ( $conds ) {
1639 return $this->makeList( $conds, self::LIST_OR );
1640 } else {
1641 // Nothing to search for...
1642 return false;
1646 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1647 return $valuename;
1650 public function bitNot( $field ) {
1651 return "(~$field)";
1654 public function bitAnd( $fieldLeft, $fieldRight ) {
1655 return "($fieldLeft & $fieldRight)";
1658 public function bitOr( $fieldLeft, $fieldRight ) {
1659 return "($fieldLeft | $fieldRight)";
1662 public function buildConcat( $stringList ) {
1663 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1666 public function buildGroupConcatField(
1667 $delim, $table, $field, $conds = '', $join_conds = []
1669 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1671 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1674 public function buildStringCast( $field ) {
1675 return $field;
1678 public function selectDB( $db ) {
1679 # Stub. Shouldn't cause serious problems if it's not overridden, but
1680 # if your database engine supports a concept similar to MySQL's
1681 # databases you may as well.
1682 $this->mDBname = $db;
1684 return true;
1687 public function getDBname() {
1688 return $this->mDBname;
1691 public function getServer() {
1692 return $this->mServer;
1695 public function tableName( $name, $format = 'quoted' ) {
1696 # Skip the entire process when we have a string quoted on both ends.
1697 # Note that we check the end so that we will still quote any use of
1698 # use of `database`.table. But won't break things if someone wants
1699 # to query a database table with a dot in the name.
1700 if ( $this->isQuotedIdentifier( $name ) ) {
1701 return $name;
1704 # Lets test for any bits of text that should never show up in a table
1705 # name. Basically anything like JOIN or ON which are actually part of
1706 # SQL queries, but may end up inside of the table value to combine
1707 # sql. Such as how the API is doing.
1708 # Note that we use a whitespace test rather than a \b test to avoid
1709 # any remote case where a word like on may be inside of a table name
1710 # surrounded by symbols which may be considered word breaks.
1711 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1712 return $name;
1715 # Split database and table into proper variables.
1716 # We reverse the explode so that database.table and table both output
1717 # the correct table.
1718 $dbDetails = explode( '.', $name, 3 );
1719 if ( count( $dbDetails ) == 3 ) {
1720 list( $database, $schema, $table ) = $dbDetails;
1721 # We don't want any prefix added in this case
1722 $prefix = '';
1723 } elseif ( count( $dbDetails ) == 2 ) {
1724 list( $database, $table ) = $dbDetails;
1725 # We don't want any prefix added in this case
1726 $prefix = '';
1727 # In dbs that support it, $database may actually be the schema
1728 # but that doesn't affect any of the functionality here
1729 $schema = '';
1730 } else {
1731 list( $table ) = $dbDetails;
1732 if ( isset( $this->tableAliases[$table] ) ) {
1733 $database = $this->tableAliases[$table]['dbname'];
1734 $schema = is_string( $this->tableAliases[$table]['schema'] )
1735 ? $this->tableAliases[$table]['schema']
1736 : $this->mSchema;
1737 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1738 ? $this->tableAliases[$table]['prefix']
1739 : $this->mTablePrefix;
1740 } else {
1741 $database = '';
1742 $schema = $this->mSchema; # Default schema
1743 $prefix = $this->mTablePrefix; # Default prefix
1747 # Quote $table and apply the prefix if not quoted.
1748 # $tableName might be empty if this is called from Database::replaceVars()
1749 $tableName = "{$prefix}{$table}";
1750 if ( $format === 'quoted'
1751 && !$this->isQuotedIdentifier( $tableName )
1752 && $tableName !== ''
1754 $tableName = $this->addIdentifierQuotes( $tableName );
1757 # Quote $schema and $database and merge them with the table name if needed
1758 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1759 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1761 return $tableName;
1765 * @param string|null $namespace Database or schema
1766 * @param string $relation Name of table, view, sequence, etc...
1767 * @param string $format One of (raw, quoted)
1768 * @return string Relation name with quoted and merged $namespace as needed
1770 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1771 if ( strlen( $namespace ) ) {
1772 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1773 $namespace = $this->addIdentifierQuotes( $namespace );
1775 $relation = $namespace . '.' . $relation;
1778 return $relation;
1781 public function tableNames() {
1782 $inArray = func_get_args();
1783 $retVal = [];
1785 foreach ( $inArray as $name ) {
1786 $retVal[$name] = $this->tableName( $name );
1789 return $retVal;
1792 public function tableNamesN() {
1793 $inArray = func_get_args();
1794 $retVal = [];
1796 foreach ( $inArray as $name ) {
1797 $retVal[] = $this->tableName( $name );
1800 return $retVal;
1804 * Get an aliased table name
1805 * e.g. tableName AS newTableName
1807 * @param string $name Table name, see tableName()
1808 * @param string|bool $alias Alias (optional)
1809 * @return string SQL name for aliased table. Will not alias a table to its own name
1811 protected function tableNameWithAlias( $name, $alias = false ) {
1812 if ( !$alias || $alias == $name ) {
1813 return $this->tableName( $name );
1814 } else {
1815 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1820 * Gets an array of aliased table names
1822 * @param array $tables [ [alias] => table ]
1823 * @return string[] See tableNameWithAlias()
1825 protected function tableNamesWithAlias( $tables ) {
1826 $retval = [];
1827 foreach ( $tables as $alias => $table ) {
1828 if ( is_numeric( $alias ) ) {
1829 $alias = $table;
1831 $retval[] = $this->tableNameWithAlias( $table, $alias );
1834 return $retval;
1838 * Get an aliased field name
1839 * e.g. fieldName AS newFieldName
1841 * @param string $name Field name
1842 * @param string|bool $alias Alias (optional)
1843 * @return string SQL name for aliased field. Will not alias a field to its own name
1845 protected function fieldNameWithAlias( $name, $alias = false ) {
1846 if ( !$alias || (string)$alias === (string)$name ) {
1847 return $name;
1848 } else {
1849 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1854 * Gets an array of aliased field names
1856 * @param array $fields [ [alias] => field ]
1857 * @return string[] See fieldNameWithAlias()
1859 protected function fieldNamesWithAlias( $fields ) {
1860 $retval = [];
1861 foreach ( $fields as $alias => $field ) {
1862 if ( is_numeric( $alias ) ) {
1863 $alias = $field;
1865 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1868 return $retval;
1872 * Get the aliased table name clause for a FROM clause
1873 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1875 * @param array $tables ( [alias] => table )
1876 * @param array $use_index Same as for select()
1877 * @param array $ignore_index Same as for select()
1878 * @param array $join_conds Same as for select()
1879 * @return string
1881 protected function tableNamesWithIndexClauseOrJOIN(
1882 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1884 $ret = [];
1885 $retJOIN = [];
1886 $use_index = (array)$use_index;
1887 $ignore_index = (array)$ignore_index;
1888 $join_conds = (array)$join_conds;
1890 foreach ( $tables as $alias => $table ) {
1891 if ( !is_string( $alias ) ) {
1892 // No alias? Set it equal to the table name
1893 $alias = $table;
1895 // Is there a JOIN clause for this table?
1896 if ( isset( $join_conds[$alias] ) ) {
1897 list( $joinType, $conds ) = $join_conds[$alias];
1898 $tableClause = $joinType;
1899 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1900 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1901 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1902 if ( $use != '' ) {
1903 $tableClause .= ' ' . $use;
1906 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1907 $ignore = $this->ignoreIndexClause(
1908 implode( ',', (array)$ignore_index[$alias] ) );
1909 if ( $ignore != '' ) {
1910 $tableClause .= ' ' . $ignore;
1913 $on = $this->makeList( (array)$conds, self::LIST_AND );
1914 if ( $on != '' ) {
1915 $tableClause .= ' ON (' . $on . ')';
1918 $retJOIN[] = $tableClause;
1919 } elseif ( isset( $use_index[$alias] ) ) {
1920 // Is there an INDEX clause for this table?
1921 $tableClause = $this->tableNameWithAlias( $table, $alias );
1922 $tableClause .= ' ' . $this->useIndexClause(
1923 implode( ',', (array)$use_index[$alias] )
1926 $ret[] = $tableClause;
1927 } elseif ( isset( $ignore_index[$alias] ) ) {
1928 // Is there an INDEX clause for this table?
1929 $tableClause = $this->tableNameWithAlias( $table, $alias );
1930 $tableClause .= ' ' . $this->ignoreIndexClause(
1931 implode( ',', (array)$ignore_index[$alias] )
1934 $ret[] = $tableClause;
1935 } else {
1936 $tableClause = $this->tableNameWithAlias( $table, $alias );
1938 $ret[] = $tableClause;
1942 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1943 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1944 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1946 // Compile our final table clause
1947 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1951 * Get the name of an index in a given table.
1953 * @param string $index
1954 * @return string
1956 protected function indexName( $index ) {
1957 return $index;
1960 public function addQuotes( $s ) {
1961 if ( $s instanceof Blob ) {
1962 $s = $s->fetch();
1964 if ( $s === null ) {
1965 return 'NULL';
1966 } elseif ( is_bool( $s ) ) {
1967 return (int)$s;
1968 } else {
1969 # This will also quote numeric values. This should be harmless,
1970 # and protects against weird problems that occur when they really
1971 # _are_ strings such as article titles and string->number->string
1972 # conversion is not 1:1.
1973 return "'" . $this->strencode( $s ) . "'";
1978 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1979 * MySQL uses `backticks` while basically everything else uses double quotes.
1980 * Since MySQL is the odd one out here the double quotes are our generic
1981 * and we implement backticks in DatabaseMysql.
1983 * @param string $s
1984 * @return string
1986 public function addIdentifierQuotes( $s ) {
1987 return '"' . str_replace( '"', '""', $s ) . '"';
1991 * Returns if the given identifier looks quoted or not according to
1992 * the database convention for quoting identifiers .
1994 * @note Do not use this to determine if untrusted input is safe.
1995 * A malicious user can trick this function.
1996 * @param string $name
1997 * @return bool
1999 public function isQuotedIdentifier( $name ) {
2000 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2004 * @param string $s
2005 * @return string
2007 protected function escapeLikeInternal( $s ) {
2008 return addcslashes( $s, '\%_' );
2011 public function buildLike() {
2012 $params = func_get_args();
2014 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2015 $params = $params[0];
2018 $s = '';
2020 foreach ( $params as $value ) {
2021 if ( $value instanceof LikeMatch ) {
2022 $s .= $value->toString();
2023 } else {
2024 $s .= $this->escapeLikeInternal( $value );
2028 return " LIKE {$this->addQuotes( $s )} ";
2031 public function anyChar() {
2032 return new LikeMatch( '_' );
2035 public function anyString() {
2036 return new LikeMatch( '%' );
2039 public function nextSequenceValue( $seqName ) {
2040 return null;
2044 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2045 * is only needed because a) MySQL must be as efficient as possible due to
2046 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2047 * which index to pick. Anyway, other databases might have different
2048 * indexes on a given table. So don't bother overriding this unless you're
2049 * MySQL.
2050 * @param string $index
2051 * @return string
2053 public function useIndexClause( $index ) {
2054 return '';
2058 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2059 * is only needed because a) MySQL must be as efficient as possible due to
2060 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2061 * which index to pick. Anyway, other databases might have different
2062 * indexes on a given table. So don't bother overriding this unless you're
2063 * MySQL.
2064 * @param string $index
2065 * @return string
2067 public function ignoreIndexClause( $index ) {
2068 return '';
2071 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2072 $quotedTable = $this->tableName( $table );
2074 if ( count( $rows ) == 0 ) {
2075 return;
2078 # Single row case
2079 if ( !is_array( reset( $rows ) ) ) {
2080 $rows = [ $rows ];
2083 // @FXIME: this is not atomic, but a trx would break affectedRows()
2084 foreach ( $rows as $row ) {
2085 # Delete rows which collide
2086 if ( $uniqueIndexes ) {
2087 $sql = "DELETE FROM $quotedTable WHERE ";
2088 $first = true;
2089 foreach ( $uniqueIndexes as $index ) {
2090 if ( $first ) {
2091 $first = false;
2092 $sql .= '( ';
2093 } else {
2094 $sql .= ' ) OR ( ';
2096 if ( is_array( $index ) ) {
2097 $first2 = true;
2098 foreach ( $index as $col ) {
2099 if ( $first2 ) {
2100 $first2 = false;
2101 } else {
2102 $sql .= ' AND ';
2104 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2106 } else {
2107 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2110 $sql .= ' )';
2111 $this->query( $sql, $fname );
2114 # Now insert the row
2115 $this->insert( $table, $row, $fname );
2120 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2121 * statement.
2123 * @param string $table Table name
2124 * @param array|string $rows Row(s) to insert
2125 * @param string $fname Caller function name
2127 * @return ResultWrapper
2129 protected function nativeReplace( $table, $rows, $fname ) {
2130 $table = $this->tableName( $table );
2132 # Single row case
2133 if ( !is_array( reset( $rows ) ) ) {
2134 $rows = [ $rows ];
2137 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2138 $first = true;
2140 foreach ( $rows as $row ) {
2141 if ( $first ) {
2142 $first = false;
2143 } else {
2144 $sql .= ',';
2147 $sql .= '(' . $this->makeList( $row ) . ')';
2150 return $this->query( $sql, $fname );
2153 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2154 $fname = __METHOD__
2156 if ( !count( $rows ) ) {
2157 return true; // nothing to do
2160 if ( !is_array( reset( $rows ) ) ) {
2161 $rows = [ $rows ];
2164 if ( count( $uniqueIndexes ) ) {
2165 $clauses = []; // list WHERE clauses that each identify a single row
2166 foreach ( $rows as $row ) {
2167 foreach ( $uniqueIndexes as $index ) {
2168 $index = is_array( $index ) ? $index : [ $index ]; // columns
2169 $rowKey = []; // unique key to this row
2170 foreach ( $index as $column ) {
2171 $rowKey[$column] = $row[$column];
2173 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2176 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2177 } else {
2178 $where = false;
2181 $useTrx = !$this->mTrxLevel;
2182 if ( $useTrx ) {
2183 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2185 try {
2186 # Update any existing conflicting row(s)
2187 if ( $where !== false ) {
2188 $ok = $this->update( $table, $set, $where, $fname );
2189 } else {
2190 $ok = true;
2192 # Now insert any non-conflicting row(s)
2193 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2194 } catch ( Exception $e ) {
2195 if ( $useTrx ) {
2196 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2198 throw $e;
2200 if ( $useTrx ) {
2201 $this->commit( $fname, self::FLUSHING_INTERNAL );
2204 return $ok;
2207 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2208 $fname = __METHOD__
2210 if ( !$conds ) {
2211 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2214 $delTable = $this->tableName( $delTable );
2215 $joinTable = $this->tableName( $joinTable );
2216 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2217 if ( $conds != '*' ) {
2218 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2220 $sql .= ')';
2222 $this->query( $sql, $fname );
2225 public function textFieldSize( $table, $field ) {
2226 $table = $this->tableName( $table );
2227 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2228 $res = $this->query( $sql, __METHOD__ );
2229 $row = $this->fetchObject( $res );
2231 $m = [];
2233 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2234 $size = $m[1];
2235 } else {
2236 $size = -1;
2239 return $size;
2242 public function delete( $table, $conds, $fname = __METHOD__ ) {
2243 if ( !$conds ) {
2244 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2247 $table = $this->tableName( $table );
2248 $sql = "DELETE FROM $table";
2250 if ( $conds != '*' ) {
2251 if ( is_array( $conds ) ) {
2252 $conds = $this->makeList( $conds, self::LIST_AND );
2254 $sql .= ' WHERE ' . $conds;
2257 return $this->query( $sql, $fname );
2260 public function insertSelect(
2261 $destTable, $srcTable, $varMap, $conds,
2262 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2264 if ( $this->cliMode ) {
2265 // For massive migrations with downtime, we don't want to select everything
2266 // into memory and OOM, so do all this native on the server side if possible.
2267 return $this->nativeInsertSelect(
2268 $destTable,
2269 $srcTable,
2270 $varMap,
2271 $conds,
2272 $fname,
2273 $insertOptions,
2274 $selectOptions
2278 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2279 // on only the master (without needing row-based-replication). It also makes it easy to
2280 // know how big the INSERT is going to be.
2281 $fields = [];
2282 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2283 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2285 $selectOptions[] = 'FOR UPDATE';
2286 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2287 if ( !$res ) {
2288 return false;
2291 $rows = [];
2292 foreach ( $res as $row ) {
2293 $rows[] = (array)$row;
2296 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2299 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2300 $fname = __METHOD__,
2301 $insertOptions = [], $selectOptions = []
2303 $destTable = $this->tableName( $destTable );
2305 if ( !is_array( $insertOptions ) ) {
2306 $insertOptions = [ $insertOptions ];
2309 $insertOptions = $this->makeInsertOptions( $insertOptions );
2311 if ( !is_array( $selectOptions ) ) {
2312 $selectOptions = [ $selectOptions ];
2315 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2316 $selectOptions );
2318 if ( is_array( $srcTable ) ) {
2319 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2320 } else {
2321 $srcTable = $this->tableName( $srcTable );
2324 $sql = "INSERT $insertOptions" .
2325 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2326 " SELECT $startOpts " . implode( ',', $varMap ) .
2327 " FROM $srcTable $useIndex $ignoreIndex ";
2329 if ( $conds != '*' ) {
2330 if ( is_array( $conds ) ) {
2331 $conds = $this->makeList( $conds, self::LIST_AND );
2333 $sql .= " WHERE $conds";
2336 $sql .= " $tailOpts";
2338 return $this->query( $sql, $fname );
2342 * Construct a LIMIT query with optional offset. This is used for query
2343 * pages. The SQL should be adjusted so that only the first $limit rows
2344 * are returned. If $offset is provided as well, then the first $offset
2345 * rows should be discarded, and the next $limit rows should be returned.
2346 * If the result of the query is not ordered, then the rows to be returned
2347 * are theoretically arbitrary.
2349 * $sql is expected to be a SELECT, if that makes a difference.
2351 * The version provided by default works in MySQL and SQLite. It will very
2352 * likely need to be overridden for most other DBMSes.
2354 * @param string $sql SQL query we will append the limit too
2355 * @param int $limit The SQL limit
2356 * @param int|bool $offset The SQL offset (default false)
2357 * @throws DBUnexpectedError
2358 * @return string
2360 public function limitResult( $sql, $limit, $offset = false ) {
2361 if ( !is_numeric( $limit ) ) {
2362 throw new DBUnexpectedError( $this,
2363 "Invalid non-numeric limit passed to limitResult()\n" );
2366 return "$sql LIMIT "
2367 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2368 . "{$limit} ";
2371 public function unionSupportsOrderAndLimit() {
2372 return true; // True for almost every DB supported
2375 public function unionQueries( $sqls, $all ) {
2376 $glue = $all ? ') UNION ALL (' : ') UNION (';
2378 return '(' . implode( $glue, $sqls ) . ')';
2381 public function conditional( $cond, $trueVal, $falseVal ) {
2382 if ( is_array( $cond ) ) {
2383 $cond = $this->makeList( $cond, self::LIST_AND );
2386 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2389 public function strreplace( $orig, $old, $new ) {
2390 return "REPLACE({$orig}, {$old}, {$new})";
2393 public function getServerUptime() {
2394 return 0;
2397 public function wasDeadlock() {
2398 return false;
2401 public function wasLockTimeout() {
2402 return false;
2405 public function wasErrorReissuable() {
2406 return false;
2409 public function wasReadOnlyError() {
2410 return false;
2414 * Do not use this method outside of Database/DBError classes
2416 * @param integer|string $errno
2417 * @return bool Whether the given query error was a connection drop
2419 public function wasConnectionError( $errno ) {
2420 return false;
2423 public function deadlockLoop() {
2424 $args = func_get_args();
2425 $function = array_shift( $args );
2426 $tries = self::DEADLOCK_TRIES;
2428 $this->begin( __METHOD__ );
2430 $retVal = null;
2431 /** @var Exception $e */
2432 $e = null;
2433 do {
2434 try {
2435 $retVal = call_user_func_array( $function, $args );
2436 break;
2437 } catch ( DBQueryError $e ) {
2438 if ( $this->wasDeadlock() ) {
2439 // Retry after a randomized delay
2440 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2441 } else {
2442 // Throw the error back up
2443 throw $e;
2446 } while ( --$tries > 0 );
2448 if ( $tries <= 0 ) {
2449 // Too many deadlocks; give up
2450 $this->rollback( __METHOD__ );
2451 throw $e;
2452 } else {
2453 $this->commit( __METHOD__ );
2455 return $retVal;
2459 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2460 # Real waits are implemented in the subclass.
2461 return 0;
2464 public function getReplicaPos() {
2465 # Stub
2466 return false;
2469 public function getMasterPos() {
2470 # Stub
2471 return false;
2474 public function serverIsReadOnly() {
2475 return false;
2478 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2479 if ( !$this->mTrxLevel ) {
2480 throw new DBUnexpectedError( $this, "No transaction is active." );
2482 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2485 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2486 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2487 if ( !$this->mTrxLevel ) {
2488 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2492 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2493 if ( $this->mTrxLevel ) {
2494 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2495 } else {
2496 // If no transaction is active, then make one for this callback
2497 $this->startAtomic( __METHOD__ );
2498 try {
2499 call_user_func( $callback );
2500 $this->endAtomic( __METHOD__ );
2501 } catch ( Exception $e ) {
2502 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2503 throw $e;
2508 final public function setTransactionListener( $name, callable $callback = null ) {
2509 if ( $callback ) {
2510 $this->mTrxRecurringCallbacks[$name] = $callback;
2511 } else {
2512 unset( $this->mTrxRecurringCallbacks[$name] );
2517 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2519 * This method should not be used outside of Database/LoadBalancer
2521 * @param bool $suppress
2522 * @since 1.28
2524 final public function setTrxEndCallbackSuppression( $suppress ) {
2525 $this->mTrxEndCallbacksSuppressed = $suppress;
2529 * Actually run and consume any "on transaction idle/resolution" callbacks.
2531 * This method should not be used outside of Database/LoadBalancer
2533 * @param integer $trigger IDatabase::TRIGGER_* constant
2534 * @since 1.20
2535 * @throws Exception
2537 public function runOnTransactionIdleCallbacks( $trigger ) {
2538 if ( $this->mTrxEndCallbacksSuppressed ) {
2539 return;
2542 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2543 /** @var Exception $e */
2544 $e = null; // first exception
2545 do { // callbacks may add callbacks :)
2546 $callbacks = array_merge(
2547 $this->mTrxIdleCallbacks,
2548 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2550 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2551 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2552 foreach ( $callbacks as $callback ) {
2553 try {
2554 list( $phpCallback ) = $callback;
2555 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2556 call_user_func_array( $phpCallback, [ $trigger ] );
2557 if ( $autoTrx ) {
2558 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2559 } else {
2560 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2562 } catch ( Exception $ex ) {
2563 call_user_func( $this->errorLogger, $ex );
2564 $e = $e ?: $ex;
2565 // Some callbacks may use startAtomic/endAtomic, so make sure
2566 // their transactions are ended so other callbacks don't fail
2567 if ( $this->trxLevel() ) {
2568 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2572 } while ( count( $this->mTrxIdleCallbacks ) );
2574 if ( $e instanceof Exception ) {
2575 throw $e; // re-throw any first exception
2580 * Actually run and consume any "on transaction pre-commit" callbacks.
2582 * This method should not be used outside of Database/LoadBalancer
2584 * @since 1.22
2585 * @throws Exception
2587 public function runOnTransactionPreCommitCallbacks() {
2588 $e = null; // first exception
2589 do { // callbacks may add callbacks :)
2590 $callbacks = $this->mTrxPreCommitCallbacks;
2591 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2592 foreach ( $callbacks as $callback ) {
2593 try {
2594 list( $phpCallback ) = $callback;
2595 call_user_func( $phpCallback );
2596 } catch ( Exception $ex ) {
2597 call_user_func( $this->errorLogger, $ex );
2598 $e = $e ?: $ex;
2601 } while ( count( $this->mTrxPreCommitCallbacks ) );
2603 if ( $e instanceof Exception ) {
2604 throw $e; // re-throw any first exception
2609 * Actually run any "transaction listener" callbacks.
2611 * This method should not be used outside of Database/LoadBalancer
2613 * @param integer $trigger IDatabase::TRIGGER_* constant
2614 * @throws Exception
2615 * @since 1.20
2617 public function runTransactionListenerCallbacks( $trigger ) {
2618 if ( $this->mTrxEndCallbacksSuppressed ) {
2619 return;
2622 /** @var Exception $e */
2623 $e = null; // first exception
2625 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2626 try {
2627 $phpCallback( $trigger, $this );
2628 } catch ( Exception $ex ) {
2629 call_user_func( $this->errorLogger, $ex );
2630 $e = $e ?: $ex;
2634 if ( $e instanceof Exception ) {
2635 throw $e; // re-throw any first exception
2639 final public function startAtomic( $fname = __METHOD__ ) {
2640 if ( !$this->mTrxLevel ) {
2641 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2642 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2643 // in all changes being in one transaction to keep requests transactional.
2644 if ( !$this->getFlag( self::DBO_TRX ) ) {
2645 $this->mTrxAutomaticAtomic = true;
2649 $this->mTrxAtomicLevels[] = $fname;
2652 final public function endAtomic( $fname = __METHOD__ ) {
2653 if ( !$this->mTrxLevel ) {
2654 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2656 if ( !$this->mTrxAtomicLevels ||
2657 array_pop( $this->mTrxAtomicLevels ) !== $fname
2659 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2662 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2663 $this->commit( $fname, self::FLUSHING_INTERNAL );
2667 final public function doAtomicSection( $fname, callable $callback ) {
2668 $this->startAtomic( $fname );
2669 try {
2670 $res = call_user_func_array( $callback, [ $this, $fname ] );
2671 } catch ( Exception $e ) {
2672 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2673 throw $e;
2675 $this->endAtomic( $fname );
2677 return $res;
2680 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2681 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2682 if ( $this->mTrxLevel ) {
2683 if ( $this->mTrxAtomicLevels ) {
2684 $levels = implode( ', ', $this->mTrxAtomicLevels );
2685 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2686 throw new DBUnexpectedError( $this, $msg );
2687 } elseif ( !$this->mTrxAutomatic ) {
2688 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2689 throw new DBUnexpectedError( $this, $msg );
2690 } else {
2691 // @TODO: make this an exception at some point
2692 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2693 $this->queryLogger->error( $msg );
2694 return; // join the main transaction set
2696 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2697 // @TODO: make this an exception at some point
2698 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2699 $this->queryLogger->error( $msg );
2700 return; // let any writes be in the main transaction
2703 // Avoid fatals if close() was called
2704 $this->assertOpen();
2706 $this->doBegin( $fname );
2707 $this->mTrxTimestamp = microtime( true );
2708 $this->mTrxFname = $fname;
2709 $this->mTrxDoneWrites = false;
2710 $this->mTrxAutomaticAtomic = false;
2711 $this->mTrxAtomicLevels = [];
2712 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2713 $this->mTrxWriteDuration = 0.0;
2714 $this->mTrxWriteQueryCount = 0;
2715 $this->mTrxWriteAdjDuration = 0.0;
2716 $this->mTrxWriteAdjQueryCount = 0;
2717 $this->mTrxWriteCallers = [];
2718 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2719 // Get an estimate of the replica DB lag before then, treating estimate staleness
2720 // as lag itself just to be safe
2721 $status = $this->getApproximateLagStatus();
2722 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2723 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2724 // caller will think its OK to muck around with the transaction just because startAtomic()
2725 // has not yet completed (e.g. setting mTrxAtomicLevels).
2726 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2730 * Issues the BEGIN command to the database server.
2732 * @see Database::begin()
2733 * @param string $fname
2735 protected function doBegin( $fname ) {
2736 $this->query( 'BEGIN', $fname );
2737 $this->mTrxLevel = 1;
2740 final public function commit( $fname = __METHOD__, $flush = '' ) {
2741 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2742 // There are still atomic sections open. This cannot be ignored
2743 $levels = implode( ', ', $this->mTrxAtomicLevels );
2744 throw new DBUnexpectedError(
2745 $this,
2746 "$fname: Got COMMIT while atomic sections $levels are still open."
2750 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2751 if ( !$this->mTrxLevel ) {
2752 return; // nothing to do
2753 } elseif ( !$this->mTrxAutomatic ) {
2754 throw new DBUnexpectedError(
2755 $this,
2756 "$fname: Flushing an explicit transaction, getting out of sync."
2759 } else {
2760 if ( !$this->mTrxLevel ) {
2761 $this->queryLogger->error(
2762 "$fname: No transaction to commit, something got out of sync." );
2763 return; // nothing to do
2764 } elseif ( $this->mTrxAutomatic ) {
2765 // @TODO: make this an exception at some point
2766 $msg = "$fname: Explicit commit of implicit transaction.";
2767 $this->queryLogger->error( $msg );
2768 return; // wait for the main transaction set commit round
2772 // Avoid fatals if close() was called
2773 $this->assertOpen();
2775 $this->runOnTransactionPreCommitCallbacks();
2776 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2777 $this->doCommit( $fname );
2778 if ( $this->mTrxDoneWrites ) {
2779 $this->mLastWriteTime = microtime( true );
2780 $this->trxProfiler->transactionWritingOut(
2781 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2784 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2785 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2789 * Issues the COMMIT command to the database server.
2791 * @see Database::commit()
2792 * @param string $fname
2794 protected function doCommit( $fname ) {
2795 if ( $this->mTrxLevel ) {
2796 $this->query( 'COMMIT', $fname );
2797 $this->mTrxLevel = 0;
2801 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2802 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2803 if ( !$this->mTrxLevel ) {
2804 return; // nothing to do
2806 } else {
2807 if ( !$this->mTrxLevel ) {
2808 $this->queryLogger->error(
2809 "$fname: No transaction to rollback, something got out of sync." );
2810 return; // nothing to do
2811 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
2812 throw new DBUnexpectedError(
2813 $this,
2814 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2819 // Avoid fatals if close() was called
2820 $this->assertOpen();
2822 $this->doRollback( $fname );
2823 $this->mTrxAtomicLevels = [];
2824 if ( $this->mTrxDoneWrites ) {
2825 $this->trxProfiler->transactionWritingOut(
2826 $this->mServer, $this->mDBname, $this->mTrxShortId );
2829 $this->mTrxIdleCallbacks = []; // clear
2830 $this->mTrxPreCommitCallbacks = []; // clear
2831 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2832 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2836 * Issues the ROLLBACK command to the database server.
2838 * @see Database::rollback()
2839 * @param string $fname
2841 protected function doRollback( $fname ) {
2842 if ( $this->mTrxLevel ) {
2843 # Disconnects cause rollback anyway, so ignore those errors
2844 $ignoreErrors = true;
2845 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2846 $this->mTrxLevel = 0;
2850 public function flushSnapshot( $fname = __METHOD__ ) {
2851 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
2852 // This only flushes transactions to clear snapshots, not to write data
2853 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2854 throw new DBUnexpectedError(
2855 $this,
2856 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2860 $this->commit( $fname, self::FLUSHING_INTERNAL );
2863 public function explicitTrxActive() {
2864 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
2867 public function duplicateTableStructure(
2868 $oldName, $newName, $temporary = false, $fname = __METHOD__
2870 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2873 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2874 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2877 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2878 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2881 public function timestamp( $ts = 0 ) {
2882 $t = new ConvertibleTimestamp( $ts );
2883 // Let errors bubble up to avoid putting garbage in the DB
2884 return $t->getTimestamp( TS_MW );
2887 public function timestampOrNull( $ts = null ) {
2888 if ( is_null( $ts ) ) {
2889 return null;
2890 } else {
2891 return $this->timestamp( $ts );
2896 * Take the result from a query, and wrap it in a ResultWrapper if
2897 * necessary. Boolean values are passed through as is, to indicate success
2898 * of write queries or failure.
2900 * Once upon a time, Database::query() returned a bare MySQL result
2901 * resource, and it was necessary to call this function to convert it to
2902 * a wrapper. Nowadays, raw database objects are never exposed to external
2903 * callers, so this is unnecessary in external code.
2905 * @param bool|ResultWrapper|resource|object $result
2906 * @return bool|ResultWrapper
2908 protected function resultObject( $result ) {
2909 if ( !$result ) {
2910 return false;
2911 } elseif ( $result instanceof ResultWrapper ) {
2912 return $result;
2913 } elseif ( $result === true ) {
2914 // Successful write query
2915 return $result;
2916 } else {
2917 return new ResultWrapper( $this, $result );
2921 public function ping( &$rtt = null ) {
2922 // Avoid hitting the server if it was hit recently
2923 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2924 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2925 $rtt = $this->mRTTEstimate;
2926 return true; // don't care about $rtt
2930 // This will reconnect if possible or return false if not
2931 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
2932 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
2933 $this->restoreFlags( self::RESTORE_PRIOR );
2935 if ( $ok ) {
2936 $rtt = $this->mRTTEstimate;
2939 return $ok;
2943 * @return bool
2945 protected function reconnect() {
2946 $this->closeConnection();
2947 $this->mOpened = false;
2948 $this->mConn = false;
2949 try {
2950 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2951 $this->lastPing = microtime( true );
2952 $ok = true;
2953 } catch ( DBConnectionError $e ) {
2954 $ok = false;
2957 return $ok;
2960 public function getSessionLagStatus() {
2961 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2965 * Get the replica DB lag when the current transaction started
2967 * This is useful when transactions might use snapshot isolation
2968 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2969 * is this lag plus transaction duration. If they don't, it is still
2970 * safe to be pessimistic. This returns null if there is no transaction.
2972 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2973 * @since 1.27
2975 protected function getTransactionLagStatus() {
2976 return $this->mTrxLevel
2977 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
2978 : null;
2982 * Get a replica DB lag estimate for this server
2984 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2985 * @since 1.27
2987 protected function getApproximateLagStatus() {
2988 return [
2989 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
2990 'since' => microtime( true )
2995 * Merge the result of getSessionLagStatus() for several DBs
2996 * using the most pessimistic values to estimate the lag of
2997 * any data derived from them in combination
2999 * This is information is useful for caching modules
3001 * @see WANObjectCache::set()
3002 * @see WANObjectCache::getWithSetCallback()
3004 * @param IDatabase $db1
3005 * @param IDatabase ...
3006 * @return array Map of values:
3007 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3008 * - since: oldest UNIX timestamp of any of the DB lag estimates
3009 * - pending: whether any of the DBs have uncommitted changes
3010 * @since 1.27
3012 public static function getCacheSetOptions( IDatabase $db1 ) {
3013 $res = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3014 foreach ( func_get_args() as $db ) {
3015 /** @var IDatabase $db */
3016 $status = $db->getSessionLagStatus();
3017 if ( $status['lag'] === false ) {
3018 $res['lag'] = false;
3019 } elseif ( $res['lag'] !== false ) {
3020 $res['lag'] = max( $res['lag'], $status['lag'] );
3022 $res['since'] = min( $res['since'], $status['since'] );
3023 $res['pending'] = $res['pending'] ?: $db->writesPending();
3026 return $res;
3029 public function getLag() {
3030 return 0;
3033 public function maxListLen() {
3034 return 0;
3037 public function encodeBlob( $b ) {
3038 return $b;
3041 public function decodeBlob( $b ) {
3042 if ( $b instanceof Blob ) {
3043 $b = $b->fetch();
3045 return $b;
3048 public function setSessionOptions( array $options ) {
3051 public function sourceFile(
3052 $filename,
3053 callable $lineCallback = null,
3054 callable $resultCallback = null,
3055 $fname = false,
3056 callable $inputCallback = null
3058 MediaWiki\suppressWarnings();
3059 $fp = fopen( $filename, 'r' );
3060 MediaWiki\restoreWarnings();
3062 if ( false === $fp ) {
3063 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3066 if ( !$fname ) {
3067 $fname = __METHOD__ . "( $filename )";
3070 try {
3071 $error = $this->sourceStream(
3072 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3073 } catch ( Exception $e ) {
3074 fclose( $fp );
3075 throw $e;
3078 fclose( $fp );
3080 return $error;
3083 public function setSchemaVars( $vars ) {
3084 $this->mSchemaVars = $vars;
3087 public function sourceStream(
3088 $fp,
3089 callable $lineCallback = null,
3090 callable $resultCallback = null,
3091 $fname = __METHOD__,
3092 callable $inputCallback = null
3094 $cmd = '';
3096 while ( !feof( $fp ) ) {
3097 if ( $lineCallback ) {
3098 call_user_func( $lineCallback );
3101 $line = trim( fgets( $fp ) );
3103 if ( $line == '' ) {
3104 continue;
3107 if ( '-' == $line[0] && '-' == $line[1] ) {
3108 continue;
3111 if ( $cmd != '' ) {
3112 $cmd .= ' ';
3115 $done = $this->streamStatementEnd( $cmd, $line );
3117 $cmd .= "$line\n";
3119 if ( $done || feof( $fp ) ) {
3120 $cmd = $this->replaceVars( $cmd );
3122 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3123 $res = $this->query( $cmd, $fname );
3125 if ( $resultCallback ) {
3126 call_user_func( $resultCallback, $res, $this );
3129 if ( false === $res ) {
3130 $err = $this->lastError();
3132 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3135 $cmd = '';
3139 return true;
3143 * Called by sourceStream() to check if we've reached a statement end
3145 * @param string &$sql SQL assembled so far
3146 * @param string &$newLine New line about to be added to $sql
3147 * @return bool Whether $newLine contains end of the statement
3149 public function streamStatementEnd( &$sql, &$newLine ) {
3150 if ( $this->delimiter ) {
3151 $prev = $newLine;
3152 $newLine = preg_replace(
3153 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3154 if ( $newLine != $prev ) {
3155 return true;
3159 return false;
3163 * Database independent variable replacement. Replaces a set of variables
3164 * in an SQL statement with their contents as given by $this->getSchemaVars().
3166 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3168 * - '{$var}' should be used for text and is passed through the database's
3169 * addQuotes method.
3170 * - `{$var}` should be used for identifiers (e.g. table and database names).
3171 * It is passed through the database's addIdentifierQuotes method which
3172 * can be overridden if the database uses something other than backticks.
3173 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3174 * database's tableName method.
3175 * - / *i* / passes the name that follows through the database's indexName method.
3176 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3177 * its use should be avoided. In 1.24 and older, string encoding was applied.
3179 * @param string $ins SQL statement to replace variables in
3180 * @return string The new SQL statement with variables replaced
3182 protected function replaceVars( $ins ) {
3183 $vars = $this->getSchemaVars();
3184 return preg_replace_callback(
3186 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3187 \'\{\$ (\w+) }\' | # 3. addQuotes
3188 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3189 /\*\$ (\w+) \*/ # 5. leave unencoded
3190 !x',
3191 function ( $m ) use ( $vars ) {
3192 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3193 // check for both nonexistent keys *and* the empty string.
3194 if ( isset( $m[1] ) && $m[1] !== '' ) {
3195 if ( $m[1] === 'i' ) {
3196 return $this->indexName( $m[2] );
3197 } else {
3198 return $this->tableName( $m[2] );
3200 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3201 return $this->addQuotes( $vars[$m[3]] );
3202 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3203 return $this->addIdentifierQuotes( $vars[$m[4]] );
3204 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3205 return $vars[$m[5]];
3206 } else {
3207 return $m[0];
3210 $ins
3215 * Get schema variables. If none have been set via setSchemaVars(), then
3216 * use some defaults from the current object.
3218 * @return array
3220 protected function getSchemaVars() {
3221 if ( $this->mSchemaVars ) {
3222 return $this->mSchemaVars;
3223 } else {
3224 return $this->getDefaultSchemaVars();
3229 * Get schema variables to use if none have been set via setSchemaVars().
3231 * Override this in derived classes to provide variables for tables.sql
3232 * and SQL patch files.
3234 * @return array
3236 protected function getDefaultSchemaVars() {
3237 return [];
3240 public function lockIsFree( $lockName, $method ) {
3241 return true;
3244 public function lock( $lockName, $method, $timeout = 5 ) {
3245 $this->mNamedLocksHeld[$lockName] = 1;
3247 return true;
3250 public function unlock( $lockName, $method ) {
3251 unset( $this->mNamedLocksHeld[$lockName] );
3253 return true;
3256 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3257 if ( $this->writesOrCallbacksPending() ) {
3258 // This only flushes transactions to clear snapshots, not to write data
3259 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3260 throw new DBUnexpectedError(
3261 $this,
3262 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3266 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3267 return null;
3270 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3271 if ( $this->trxLevel() ) {
3272 // There is a good chance an exception was thrown, causing any early return
3273 // from the caller. Let any error handler get a chance to issue rollback().
3274 // If there isn't one, let the error bubble up and trigger server-side rollback.
3275 $this->onTransactionResolution(
3276 function () use ( $lockKey, $fname ) {
3277 $this->unlock( $lockKey, $fname );
3279 $fname
3281 } else {
3282 $this->unlock( $lockKey, $fname );
3284 } );
3286 $this->commit( $fname, self::FLUSHING_INTERNAL );
3288 return $unlocker;
3291 public function namedLocksEnqueue() {
3292 return false;
3296 * Lock specific tables
3298 * @param array $read Array of tables to lock for read access
3299 * @param array $write Array of tables to lock for write access
3300 * @param string $method Name of caller
3301 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3302 * @return bool
3304 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3305 return true;
3309 * Unlock specific tables
3311 * @param string $method The caller
3312 * @return bool
3314 public function unlockTables( $method ) {
3315 return true;
3319 * Delete a table
3320 * @param string $tableName
3321 * @param string $fName
3322 * @return bool|ResultWrapper
3323 * @since 1.18
3325 public function dropTable( $tableName, $fName = __METHOD__ ) {
3326 if ( !$this->tableExists( $tableName, $fName ) ) {
3327 return false;
3329 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3331 return $this->query( $sql, $fName );
3334 public function getInfinity() {
3335 return 'infinity';
3338 public function encodeExpiry( $expiry ) {
3339 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3340 ? $this->getInfinity()
3341 : $this->timestamp( $expiry );
3344 public function decodeExpiry( $expiry, $format = TS_MW ) {
3345 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3346 return 'infinity';
3349 return ConvertibleTimestamp::convert( $format, $expiry );
3352 public function setBigSelects( $value = true ) {
3353 // no-op
3356 public function isReadOnly() {
3357 return ( $this->getReadOnlyReason() !== false );
3361 * @return string|bool Reason this DB is read-only or false if it is not
3363 protected function getReadOnlyReason() {
3364 $reason = $this->getLBInfo( 'readOnlyReason' );
3366 return is_string( $reason ) ? $reason : false;
3369 public function setTableAliases( array $aliases ) {
3370 $this->tableAliases = $aliases;
3374 * @return bool Whether a DB user is required to access the DB
3375 * @since 1.28
3377 protected function requiresDatabaseUser() {
3378 return true;
3382 * Get the underlying binding handle, mConn
3384 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3385 * This catches broken callers than catch and ignore disconnection exceptions.
3386 * Unlike checking isOpen(), this is safe to call inside of open().
3388 * @return resource|object
3389 * @throws DBUnexpectedError
3390 * @since 1.26
3392 protected function getBindingHandle() {
3393 if ( !$this->mConn ) {
3394 throw new DBUnexpectedError(
3395 $this,
3396 'DB connection was already closed or the connection dropped.'
3400 return $this->mConn;
3404 * @since 1.19
3405 * @return string
3407 public function __toString() {
3408 return (string)$this->mConn;
3412 * Make sure that copies do not share the same client binding handle
3413 * @throws DBConnectionError
3415 public function __clone() {
3416 $this->connLogger->warning(
3417 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3418 ( new RuntimeException() )->getTraceAsString()
3421 if ( $this->isOpen() ) {
3422 // Open a new connection resource without messing with the old one
3423 $this->mOpened = false;
3424 $this->mConn = false;
3425 $this->mTrxEndCallbacks = []; // don't copy
3426 $this->handleSessionLoss(); // no trx or locks anymore
3427 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3428 $this->lastPing = microtime( true );
3433 * Called by serialize. Throw an exception when DB connection is serialized.
3434 * This causes problems on some database engines because the connection is
3435 * not restored on unserialize.
3437 public function __sleep() {
3438 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3439 'the connection is not restored on wakeup.' );
3443 * Run a few simple sanity checks and close dangling connections
3445 public function __destruct() {
3446 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3447 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3450 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3451 if ( $danglingWriters ) {
3452 $fnames = implode( ', ', $danglingWriters );
3453 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3456 if ( $this->mConn ) {
3457 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3458 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3459 \MediaWiki\suppressWarnings();
3460 $this->closeConnection();
3461 \MediaWiki\restoreWarnings();
3462 $this->mConn = false;
3463 $this->mOpened = false;
3468 class_alias( 'Database', 'DatabaseBase' );