objectcache: detect default getWithSetCallback() set options
[mediawiki.git] / includes / libs / rdbms / database / Database.php
blob0bbbb82e2747f183c2feb037e73ca896f2ee9f77
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;
30 /**
31 * Relational database abstraction object
33 * @ingroup Database
34 * @since 1.28
36 abstract class Database implements IDatabase, IMaintainableDatabase, LoggerAwareInterface {
37 /** Number of times to re-try an operation in case of deadlock */
38 const DEADLOCK_TRIES = 4;
39 /** Minimum time to wait before retry, in microseconds */
40 const DEADLOCK_DELAY_MIN = 500000;
41 /** Maximum time to wait before retry */
42 const DEADLOCK_DELAY_MAX = 1500000;
44 /** How long before it is worth doing a dummy query to test the connection */
45 const PING_TTL = 1.0;
46 const PING_QUERY = 'SELECT 1 AS ping';
48 const TINY_WRITE_SEC = .010;
49 const SLOW_WRITE_SEC = .500;
50 const SMALL_WRITE_ROWS = 100;
52 /** @var string SQL query */
53 protected $mLastQuery = '';
54 /** @var float|bool UNIX timestamp of last write query */
55 protected $mLastWriteTime = false;
56 /** @var string|bool */
57 protected $mPHPError = false;
58 /** @var string */
59 protected $mServer;
60 /** @var string */
61 protected $mUser;
62 /** @var string */
63 protected $mPassword;
64 /** @var string */
65 protected $mDBname;
66 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
67 protected $tableAliases = [];
68 /** @var bool Whether this PHP instance is for a CLI script */
69 protected $cliMode;
70 /** @var string Agent name for query profiling */
71 protected $agent;
72 /** @var array[] Map of (section ID => info map) for usage section IDs */
73 protected $usageSectionInfo = [];
75 /** @var BagOStuff APC cache */
76 protected $srvCache;
77 /** @var LoggerInterface */
78 protected $connLogger;
79 /** @var LoggerInterface */
80 protected $queryLogger;
81 /** @var callback Error logging callback */
82 protected $errorLogger;
84 /** @var resource|null Database connection */
85 protected $mConn = null;
86 /** @var bool */
87 protected $mOpened = false;
89 /** @var array[] List of (callable, method name) */
90 protected $mTrxIdleCallbacks = [];
91 /** @var array[] List of (callable, method name) */
92 protected $mTrxPreCommitCallbacks = [];
93 /** @var array[] List of (callable, method name) */
94 protected $mTrxEndCallbacks = [];
95 /** @var callable[] Map of (name => callable) */
96 protected $mTrxRecurringCallbacks = [];
97 /** @var bool Whether to suppress triggering of transaction end callbacks */
98 protected $mTrxEndCallbacksSuppressed = false;
100 /** @var string */
101 protected $mTablePrefix = '';
102 /** @var string */
103 protected $mSchema = '';
104 /** @var integer */
105 protected $mFlags;
106 /** @var array */
107 protected $mLBInfo = [];
108 /** @var bool|null */
109 protected $mDefaultBigSelects = null;
110 /** @var array|bool */
111 protected $mSchemaVars = false;
112 /** @var array */
113 protected $mSessionVars = [];
114 /** @var array|null */
115 protected $preparedArgs;
116 /** @var string|bool|null Stashed value of html_errors INI setting */
117 protected $htmlErrors;
118 /** @var string */
119 protected $delimiter = ';';
120 /** @var DatabaseDomain */
121 protected $currentDomain;
124 * Either 1 if a transaction is active or 0 otherwise.
125 * The other Trx fields may not be meaningfull if this is 0.
127 * @var int
129 protected $mTrxLevel = 0;
131 * Either a short hexidecimal string if a transaction is active or ""
133 * @var string
134 * @see Database::mTrxLevel
136 protected $mTrxShortId = '';
138 * The UNIX time that the transaction started. Callers can assume that if
139 * snapshot isolation is used, then the data is *at least* up to date to that
140 * point (possibly more up-to-date since the first SELECT defines the snapshot).
142 * @var float|null
143 * @see Database::mTrxLevel
145 private $mTrxTimestamp = null;
146 /** @var float Lag estimate at the time of BEGIN */
147 private $mTrxReplicaLag = null;
149 * Remembers the function name given for starting the most recent transaction via begin().
150 * Used to provide additional context for error reporting.
152 * @var string
153 * @see Database::mTrxLevel
155 private $mTrxFname = null;
157 * Record if possible write queries were done in the last transaction started
159 * @var bool
160 * @see Database::mTrxLevel
162 private $mTrxDoneWrites = false;
164 * Record if the current transaction was started implicitly due to DBO_TRX being set.
166 * @var bool
167 * @see Database::mTrxLevel
169 private $mTrxAutomatic = false;
171 * Array of levels of atomicity within transactions
173 * @var array
175 private $mTrxAtomicLevels = [];
177 * Record if the current transaction was started implicitly by Database::startAtomic
179 * @var bool
181 private $mTrxAutomaticAtomic = false;
183 * Track the write query callers of the current transaction
185 * @var string[]
187 private $mTrxWriteCallers = [];
189 * @var float Seconds spent in write queries for the current transaction
191 private $mTrxWriteDuration = 0.0;
193 * @var integer Number of write queries for the current transaction
195 private $mTrxWriteQueryCount = 0;
197 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
199 private $mTrxWriteAdjDuration = 0.0;
201 * @var integer Number of write queries counted in mTrxWriteAdjDuration
203 private $mTrxWriteAdjQueryCount = 0;
205 * @var float RTT time estimate
207 private $mRTTEstimate = 0.0;
209 /** @var array Map of (name => 1) for locks obtained via lock() */
210 private $mNamedLocksHeld = [];
211 /** @var array Map of (table name => 1) for TEMPORARY tables */
212 protected $mSessionTempTables = [];
214 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
215 private $lazyMasterHandle;
217 /** @var float UNIX timestamp */
218 protected $lastPing = 0.0;
220 /** @var int[] Prior mFlags values */
221 private $priorFlags = [];
223 /** @var object|string Class name or object With profileIn/profileOut methods */
224 protected $profiler;
225 /** @var TransactionProfiler */
226 protected $trxProfiler;
229 * Constructor and database handle and attempt to connect to the DB server
231 * IDatabase classes should not be constructed directly in external
232 * code. Database::factory() should be used instead.
234 * @param array $params Parameters passed from Database::factory()
236 function __construct( array $params ) {
237 $server = $params['host'];
238 $user = $params['user'];
239 $password = $params['password'];
240 $dbName = $params['dbname'];
242 $this->mSchema = $params['schema'];
243 $this->mTablePrefix = $params['tablePrefix'];
245 $this->cliMode = $params['cliMode'];
246 // Agent name is added to SQL queries in a comment, so make sure it can't break out
247 $this->agent = str_replace( '/', '-', $params['agent'] );
249 $this->mFlags = $params['flags'];
250 if ( $this->mFlags & self::DBO_DEFAULT ) {
251 if ( $this->cliMode ) {
252 $this->mFlags &= ~self::DBO_TRX;
253 } else {
254 $this->mFlags |= self::DBO_TRX;
258 $this->mSessionVars = $params['variables'];
260 $this->srvCache = isset( $params['srvCache'] )
261 ? $params['srvCache']
262 : new HashBagOStuff();
264 $this->profiler = $params['profiler'];
265 $this->trxProfiler = $params['trxProfiler'];
266 $this->connLogger = $params['connLogger'];
267 $this->queryLogger = $params['queryLogger'];
268 $this->errorLogger = $params['errorLogger'];
270 // Set initial dummy domain until open() sets the final DB/prefix
271 $this->currentDomain = DatabaseDomain::newUnspecified();
273 if ( $user ) {
274 $this->open( $server, $user, $password, $dbName );
275 } elseif ( $this->requiresDatabaseUser() ) {
276 throw new InvalidArgumentException( "No database user provided." );
279 // Set the domain object after open() sets the relevant fields
280 if ( $this->mDBname != '' ) {
281 // Domains with server scope but a table prefix are not used by IDatabase classes
282 $this->currentDomain = new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix );
287 * Construct a Database subclass instance given a database type and parameters
289 * This also connects to the database immediately upon object construction
291 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
292 * @param array $p Parameter map with keys:
293 * - host : The hostname of the DB server
294 * - user : The name of the database user the client operates under
295 * - password : The password for the database user
296 * - dbname : The name of the database to use where queries do not specify one.
297 * The database must exist or an error might be thrown. Setting this to the empty string
298 * will avoid any such errors and make the handle have no implicit database scope. This is
299 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
300 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
301 * in which user names and such are defined, e.g. users are database-specific in Postgres.
302 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
303 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
304 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
305 * recognized in queries. This can be used in place of schemas for handle site farms.
306 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
307 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
308 * flag in place UNLESS this this database simply acts as a key/value store.
309 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
310 * 'mysql' driver and the newer 'mysqli' driver.
311 * - variables: Optional map of session variables to set after connecting. This can be
312 * used to adjust lock timeouts or encoding modes and the like.
313 * - connLogger: Optional PSR-3 logger interface instance.
314 * - queryLogger: Optional PSR-3 logger interface instance.
315 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
316 * These will be called in query(), using a simplified version of the SQL that also
317 * includes the agent as a SQL comment.
318 * - trxProfiler: Optional TransactionProfiler instance.
319 * - errorLogger: Optional callback that takes an Exception and logs it.
320 * - cliMode: Whether to consider the execution context that of a CLI script.
321 * - agent: Optional name used to identify the end-user in query profiling/logging.
322 * - srvCache: Optional BagOStuff instance to an APC-style cache.
323 * @return Database|null If the database driver or extension cannot be found
324 * @throws InvalidArgumentException If the database driver or extension cannot be found
325 * @since 1.18
327 final public static function factory( $dbType, $p = [] ) {
328 static $canonicalDBTypes = [
329 'mysql' => [ 'mysqli', 'mysql' ],
330 'postgres' => [],
331 'sqlite' => [],
332 'oracle' => [],
333 'mssql' => [],
336 $driver = false;
337 $dbType = strtolower( $dbType );
338 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
339 $possibleDrivers = $canonicalDBTypes[$dbType];
340 if ( !empty( $p['driver'] ) ) {
341 if ( in_array( $p['driver'], $possibleDrivers ) ) {
342 $driver = $p['driver'];
343 } else {
344 throw new InvalidArgumentException( __METHOD__ .
345 " type '$dbType' does not support driver '{$p['driver']}'" );
347 } else {
348 foreach ( $possibleDrivers as $posDriver ) {
349 if ( extension_loaded( $posDriver ) ) {
350 $driver = $posDriver;
351 break;
355 } else {
356 $driver = $dbType;
358 if ( $driver === false || $driver === '' ) {
359 throw new InvalidArgumentException( __METHOD__ .
360 " no viable database extension found for type '$dbType'" );
363 $class = 'Database' . ucfirst( $driver );
364 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
365 // Resolve some defaults for b/c
366 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
367 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
368 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
369 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
370 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
371 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : [];
372 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : '';
373 $p['schema'] = isset( $p['schema'] ) ? $p['schema'] : '';
374 $p['cliMode'] = isset( $p['cliMode'] ) ? $p['cliMode'] : ( PHP_SAPI === 'cli' );
375 $p['agent'] = isset( $p['agent'] ) ? $p['agent'] : '';
376 if ( !isset( $p['connLogger'] ) ) {
377 $p['connLogger'] = new \Psr\Log\NullLogger();
379 if ( !isset( $p['queryLogger'] ) ) {
380 $p['queryLogger'] = new \Psr\Log\NullLogger();
382 $p['profiler'] = isset( $p['profiler'] ) ? $p['profiler'] : null;
383 if ( !isset( $p['trxProfiler'] ) ) {
384 $p['trxProfiler'] = new TransactionProfiler();
386 if ( !isset( $p['errorLogger'] ) ) {
387 $p['errorLogger'] = function ( Exception $e ) {
388 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING );
392 $conn = new $class( $p );
393 } else {
394 $conn = null;
397 return $conn;
400 public function setLogger( LoggerInterface $logger ) {
401 $this->queryLogger = $logger;
404 public function getServerInfo() {
405 return $this->getServerVersion();
408 public function bufferResults( $buffer = null ) {
409 $res = !$this->getFlag( self::DBO_NOBUFFER );
410 if ( $buffer !== null ) {
411 $buffer
412 ? $this->clearFlag( self::DBO_NOBUFFER )
413 : $this->setFlag( self::DBO_NOBUFFER );
416 return $res;
420 * Turns on (false) or off (true) the automatic generation and sending
421 * of a "we're sorry, but there has been a database error" page on
422 * database errors. Default is on (false). When turned off, the
423 * code should use lastErrno() and lastError() to handle the
424 * situation as appropriate.
426 * Do not use this function outside of the Database classes.
428 * @param null|bool $ignoreErrors
429 * @return bool The previous value of the flag.
431 protected function ignoreErrors( $ignoreErrors = null ) {
432 $res = $this->getFlag( self::DBO_IGNORE );
433 if ( $ignoreErrors !== null ) {
434 $ignoreErrors
435 ? $this->setFlag( self::DBO_IGNORE )
436 : $this->clearFlag( self::DBO_IGNORE );
439 return $res;
442 public function trxLevel() {
443 return $this->mTrxLevel;
446 public function trxTimestamp() {
447 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
450 public function tablePrefix( $prefix = null ) {
451 $old = $this->mTablePrefix;
452 if ( $prefix !== null ) {
453 $this->mTablePrefix = $prefix;
454 $this->currentDomain = ( $this->mDBname != '' )
455 ? new DatabaseDomain( $this->mDBname, null, $this->mTablePrefix )
456 : DatabaseDomain::newUnspecified();
459 return $old;
462 public function dbSchema( $schema = null ) {
463 $old = $this->mSchema;
464 if ( $schema !== null ) {
465 $this->mSchema = $schema;
468 return $old;
471 public function getLBInfo( $name = null ) {
472 if ( is_null( $name ) ) {
473 return $this->mLBInfo;
474 } else {
475 if ( array_key_exists( $name, $this->mLBInfo ) ) {
476 return $this->mLBInfo[$name];
477 } else {
478 return null;
483 public function setLBInfo( $name, $value = null ) {
484 if ( is_null( $value ) ) {
485 $this->mLBInfo = $name;
486 } else {
487 $this->mLBInfo[$name] = $value;
491 public function setLazyMasterHandle( IDatabase $conn ) {
492 $this->lazyMasterHandle = $conn;
496 * @return IDatabase|null
497 * @see setLazyMasterHandle()
498 * @since 1.27
500 protected function getLazyMasterHandle() {
501 return $this->lazyMasterHandle;
504 public function implicitGroupby() {
505 return true;
508 public function implicitOrderby() {
509 return true;
512 public function lastQuery() {
513 return $this->mLastQuery;
516 public function doneWrites() {
517 return (bool)$this->mLastWriteTime;
520 public function lastDoneWrites() {
521 return $this->mLastWriteTime ?: false;
524 public function writesPending() {
525 return $this->mTrxLevel && $this->mTrxDoneWrites;
528 public function writesOrCallbacksPending() {
529 return $this->mTrxLevel && (
530 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
534 public function pendingWriteQueryDuration( $type = self::ESTIMATE_TOTAL ) {
535 if ( !$this->mTrxLevel ) {
536 return false;
537 } elseif ( !$this->mTrxDoneWrites ) {
538 return 0.0;
541 switch ( $type ) {
542 case self::ESTIMATE_DB_APPLY:
543 $this->ping( $rtt );
544 $rttAdjTotal = $this->mTrxWriteAdjQueryCount * $rtt;
545 $applyTime = max( $this->mTrxWriteAdjDuration - $rttAdjTotal, 0 );
546 // For omitted queries, make them count as something at least
547 $omitted = $this->mTrxWriteQueryCount - $this->mTrxWriteAdjQueryCount;
548 $applyTime += self::TINY_WRITE_SEC * $omitted;
550 return $applyTime;
551 default: // everything
552 return $this->mTrxWriteDuration;
556 public function pendingWriteCallers() {
557 return $this->mTrxLevel ? $this->mTrxWriteCallers : [];
560 protected function pendingWriteAndCallbackCallers() {
561 if ( !$this->mTrxLevel ) {
562 return [];
565 $fnames = $this->mTrxWriteCallers;
566 foreach ( [
567 $this->mTrxIdleCallbacks,
568 $this->mTrxPreCommitCallbacks,
569 $this->mTrxEndCallbacks
570 ] as $callbacks ) {
571 foreach ( $callbacks as $callback ) {
572 $fnames[] = $callback[1];
576 return $fnames;
579 public function isOpen() {
580 return $this->mOpened;
583 public function setFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
584 if ( $remember === self::REMEMBER_PRIOR ) {
585 array_push( $this->priorFlags, $this->mFlags );
587 $this->mFlags |= $flag;
590 public function clearFlag( $flag, $remember = self::REMEMBER_NOTHING ) {
591 if ( $remember === self::REMEMBER_PRIOR ) {
592 array_push( $this->priorFlags, $this->mFlags );
594 $this->mFlags &= ~$flag;
597 public function restoreFlags( $state = self::RESTORE_PRIOR ) {
598 if ( !$this->priorFlags ) {
599 return;
602 if ( $state === self::RESTORE_INITIAL ) {
603 $this->mFlags = reset( $this->priorFlags );
604 $this->priorFlags = [];
605 } else {
606 $this->mFlags = array_pop( $this->priorFlags );
610 public function getFlag( $flag ) {
611 return !!( $this->mFlags & $flag );
615 * @param string $name Class field name
616 * @return mixed
617 * @deprecated Since 1.28
619 public function getProperty( $name ) {
620 return $this->$name;
623 public function getDomainID() {
624 return $this->currentDomain->getId();
627 final public function getWikiID() {
628 return $this->getDomainID();
632 * Get information about an index into an object
633 * @param string $table Table name
634 * @param string $index Index name
635 * @param string $fname Calling function name
636 * @return mixed Database-specific index description class or false if the index does not exist
638 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
641 * Wrapper for addslashes()
643 * @param string $s String to be slashed.
644 * @return string Slashed string.
646 abstract function strencode( $s );
648 protected function installErrorHandler() {
649 $this->mPHPError = false;
650 $this->htmlErrors = ini_set( 'html_errors', '0' );
651 set_error_handler( [ $this, 'connectionErrorLogger' ] );
655 * @return bool|string
657 protected function restoreErrorHandler() {
658 restore_error_handler();
659 if ( $this->htmlErrors !== false ) {
660 ini_set( 'html_errors', $this->htmlErrors );
663 return $this->getLastPHPError();
667 * @return string|bool Last PHP error for this DB (typically connection errors)
669 protected function getLastPHPError() {
670 if ( $this->mPHPError ) {
671 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
672 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
674 return $error;
677 return false;
681 * This method should not be used outside of Database classes
683 * @param int $errno
684 * @param string $errstr
686 public function connectionErrorLogger( $errno, $errstr ) {
687 $this->mPHPError = $errstr;
691 * Create a log context to pass to PSR-3 logger functions.
693 * @param array $extras Additional data to add to context
694 * @return array
696 protected function getLogContext( array $extras = [] ) {
697 return array_merge(
699 'db_server' => $this->mServer,
700 'db_name' => $this->mDBname,
701 'db_user' => $this->mUser,
703 $extras
707 public function close() {
708 if ( $this->mConn ) {
709 if ( $this->trxLevel() ) {
710 $this->commit( __METHOD__, self::FLUSHING_INTERNAL );
713 $closed = $this->closeConnection();
714 $this->mConn = false;
715 } elseif ( $this->mTrxIdleCallbacks || $this->mTrxEndCallbacks ) { // sanity
716 throw new RuntimeException( "Transaction callbacks still pending." );
717 } else {
718 $closed = true;
720 $this->mOpened = false;
722 return $closed;
726 * Make sure isOpen() returns true as a sanity check
728 * @throws DBUnexpectedError
730 protected function assertOpen() {
731 if ( !$this->isOpen() ) {
732 throw new DBUnexpectedError( $this, "DB connection was already closed." );
737 * Closes underlying database connection
738 * @since 1.20
739 * @return bool Whether connection was closed successfully
741 abstract protected function closeConnection();
743 public function reportConnectionError( $error = 'Unknown error' ) {
744 $myError = $this->lastError();
745 if ( $myError ) {
746 $error = $myError;
749 # New method
750 throw new DBConnectionError( $this, $error );
754 * The DBMS-dependent part of query()
756 * @param string $sql SQL query.
757 * @return ResultWrapper|bool Result object to feed to fetchObject,
758 * fetchRow, ...; or false on failure
760 abstract protected function doQuery( $sql );
763 * Determine whether a query writes to the DB.
764 * Should return true if unsure.
766 * @param string $sql
767 * @return bool
769 protected function isWriteQuery( $sql ) {
770 return !preg_match(
771 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
775 * @param $sql
776 * @return string|null
778 protected function getQueryVerb( $sql ) {
779 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ? strtoupper( $m[1] ) : null;
783 * Determine whether a SQL statement is sensitive to isolation level.
784 * A SQL statement is considered transactable if its result could vary
785 * depending on the transaction isolation level. Operational commands
786 * such as 'SET' and 'SHOW' are not considered to be transactable.
788 * @param string $sql
789 * @return bool
791 protected function isTransactableQuery( $sql ) {
792 return !in_array(
793 $this->getQueryVerb( $sql ),
794 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
795 true
800 * @param string $sql A SQL query
801 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
803 protected function registerTempTableOperation( $sql ) {
804 if ( preg_match(
805 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
806 $sql,
807 $matches
808 ) ) {
809 $this->mSessionTempTables[$matches[1]] = 1;
811 return true;
812 } elseif ( preg_match(
813 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
814 $sql,
815 $matches
816 ) ) {
817 unset( $this->mSessionTempTables[$matches[1]] );
819 return true;
820 } elseif ( preg_match(
821 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
822 $sql,
823 $matches
824 ) ) {
825 return isset( $this->mSessionTempTables[$matches[1]] );
828 return false;
831 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
832 $priorWritesPending = $this->writesOrCallbacksPending();
833 $this->mLastQuery = $sql;
835 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
836 if ( $isWrite ) {
837 $reason = $this->getReadOnlyReason();
838 if ( $reason !== false ) {
839 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
841 # Set a flag indicating that writes have been done
842 $this->mLastWriteTime = microtime( true );
845 // Add trace comment to the begin of the sql string, right after the operator.
846 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
847 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
849 # Start implicit transactions that wrap the request if DBO_TRX is enabled
850 if ( !$this->mTrxLevel && $this->getFlag( self::DBO_TRX )
851 && $this->isTransactableQuery( $sql )
853 $this->begin( __METHOD__ . " ($fname)", self::TRANSACTION_INTERNAL );
854 $this->mTrxAutomatic = true;
857 # Keep track of whether the transaction has write queries pending
858 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWrite ) {
859 $this->mTrxDoneWrites = true;
860 $this->trxProfiler->transactionWritingIn(
861 $this->mServer, $this->mDBname, $this->mTrxShortId );
864 if ( $this->getFlag( self::DBO_DEBUG ) ) {
865 $this->queryLogger->debug( "{$this->mDBname} {$commentedSql}" );
868 # Avoid fatals if close() was called
869 $this->assertOpen();
871 # Send the query to the server
872 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
874 # Try reconnecting if the connection was lost
875 if ( false === $ret && $this->wasErrorReissuable() ) {
876 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
877 # Stash the last error values before anything might clear them
878 $lastError = $this->lastError();
879 $lastErrno = $this->lastErrno();
880 # Update state tracking to reflect transaction loss due to disconnection
881 $this->handleSessionLoss();
882 if ( $this->reconnect() ) {
883 $msg = __METHOD__ . ": lost connection to {$this->getServer()}; reconnected";
884 $this->connLogger->warning( $msg );
885 $this->queryLogger->warning(
886 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
888 if ( !$recoverable ) {
889 # Callers may catch the exception and continue to use the DB
890 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
891 } else {
892 # Should be safe to silently retry the query
893 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
895 } else {
896 $msg = __METHOD__ . ": lost connection to {$this->getServer()} permanently";
897 $this->connLogger->error( $msg );
901 if ( false === $ret ) {
902 # Deadlocks cause the entire transaction to abort, not just the statement.
903 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
904 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
905 if ( $this->wasDeadlock() ) {
906 if ( $this->explicitTrxActive() || $priorWritesPending ) {
907 $tempIgnore = false; // not recoverable
909 # Update state tracking to reflect transaction loss
910 $this->handleSessionLoss();
913 $this->reportQueryError(
914 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
917 $res = $this->resultObject( $ret );
919 return $res;
922 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
923 // Update usage information for all active usage tracking sections
924 foreach ( $this->usageSectionInfo as $id => &$info ) {
925 if ( $isWrite ) {
926 ++$info['writeQueries'];
927 } else {
928 ++$info['readQueries'];
930 if ( $info['cacheSetOptions'] === null ) {
931 $info['cacheSetOptions'] = self::getCacheSetOptions( $this );
934 unset( $info ); // destroy any reference
936 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
937 // generalizeSQL() will probably cut down the query to reasonable
938 // logging size most of the time. The substr is really just a sanity check.
939 if ( $isMaster ) {
940 $queryProf = 'query-m: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
941 } else {
942 $queryProf = 'query: ' . substr( self::generalizeSQL( $sql ), 0, 255 );
945 // Include query transaction state
946 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
948 $startTime = microtime( true );
949 if ( $this->profiler ) {
950 call_user_func( [ $this->profiler, 'profileIn' ], $queryProf );
952 $ret = $this->doQuery( $commentedSql );
953 if ( $this->profiler ) {
954 call_user_func( [ $this->profiler, 'profileOut' ], $queryProf );
956 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
958 unset( $queryProfSection ); // profile out (if set)
960 if ( $ret !== false ) {
961 $this->lastPing = $startTime;
962 if ( $isWrite && $this->mTrxLevel ) {
963 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
964 $this->mTrxWriteCallers[] = $fname;
968 if ( $sql === self::PING_QUERY ) {
969 $this->mRTTEstimate = $queryRuntime;
972 $this->trxProfiler->recordQueryCompletion(
973 $queryProf, $startTime, $isWrite, $this->affectedRows()
975 $this->queryLogger->debug( $sql, [
976 'method' => $fname,
977 'master' => $isMaster,
978 'runtime' => $queryRuntime,
979 ] );
981 return $ret;
985 * Update the estimated run-time of a query, not counting large row lock times
987 * LoadBalancer can be set to rollback transactions that will create huge replication
988 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
989 * queries, like inserting a row can take a long time due to row locking. This method
990 * uses some simple heuristics to discount those cases.
992 * @param string $sql A SQL write query
993 * @param float $runtime Total runtime, including RTT
995 private function updateTrxWriteQueryTime( $sql, $runtime ) {
996 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
997 $indicativeOfReplicaRuntime = true;
998 if ( $runtime > self::SLOW_WRITE_SEC ) {
999 $verb = $this->getQueryVerb( $sql );
1000 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1001 if ( $verb === 'INSERT' ) {
1002 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS;
1003 } elseif ( $verb === 'REPLACE' ) {
1004 $indicativeOfReplicaRuntime = $this->affectedRows() > self::SMALL_WRITE_ROWS / 2;
1008 $this->mTrxWriteDuration += $runtime;
1009 $this->mTrxWriteQueryCount += 1;
1010 if ( $indicativeOfReplicaRuntime ) {
1011 $this->mTrxWriteAdjDuration += $runtime;
1012 $this->mTrxWriteAdjQueryCount += 1;
1016 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1017 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1018 # Dropped connections also mean that named locks are automatically released.
1019 # Only allow error suppression in autocommit mode or when the lost transaction
1020 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1021 if ( $this->mNamedLocksHeld ) {
1022 return false; // possible critical section violation
1023 } elseif ( $sql === 'COMMIT' ) {
1024 return !$priorWritesPending; // nothing written anyway? (T127428)
1025 } elseif ( $sql === 'ROLLBACK' ) {
1026 return true; // transaction lost...which is also what was requested :)
1027 } elseif ( $this->explicitTrxActive() ) {
1028 return false; // don't drop atomocity
1029 } elseif ( $priorWritesPending ) {
1030 return false; // prior writes lost from implicit transaction
1033 return true;
1036 private function handleSessionLoss() {
1037 $this->mTrxLevel = 0;
1038 $this->mTrxIdleCallbacks = []; // bug 65263
1039 $this->mTrxPreCommitCallbacks = []; // bug 65263
1040 $this->mSessionTempTables = [];
1041 $this->mNamedLocksHeld = [];
1042 try {
1043 // Handle callbacks in mTrxEndCallbacks
1044 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
1045 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
1046 return null;
1047 } catch ( Exception $e ) {
1048 // Already logged; move on...
1049 return $e;
1053 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1054 if ( $this->ignoreErrors() || $tempIgnore ) {
1055 $this->queryLogger->debug( "SQL ERROR (ignored): $error\n" );
1056 } else {
1057 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1058 $this->queryLogger->error(
1059 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1060 $this->getLogContext( [
1061 'method' => __METHOD__,
1062 'errno' => $errno,
1063 'error' => $error,
1064 'sql1line' => $sql1line,
1065 'fname' => $fname,
1068 $this->queryLogger->debug( "SQL ERROR: " . $error . "\n" );
1069 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1073 public function freeResult( $res ) {
1076 public function selectField(
1077 $table, $var, $cond = '', $fname = __METHOD__, $options = []
1079 if ( $var === '*' ) { // sanity
1080 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1083 if ( !is_array( $options ) ) {
1084 $options = [ $options ];
1087 $options['LIMIT'] = 1;
1089 $res = $this->select( $table, $var, $cond, $fname, $options );
1090 if ( $res === false || !$this->numRows( $res ) ) {
1091 return false;
1094 $row = $this->fetchRow( $res );
1096 if ( $row !== false ) {
1097 return reset( $row );
1098 } else {
1099 return false;
1103 public function selectFieldValues(
1104 $table, $var, $cond = '', $fname = __METHOD__, $options = [], $join_conds = []
1106 if ( $var === '*' ) { // sanity
1107 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1108 } elseif ( !is_string( $var ) ) { // sanity
1109 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1112 if ( !is_array( $options ) ) {
1113 $options = [ $options ];
1116 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1117 if ( $res === false ) {
1118 return false;
1121 $values = [];
1122 foreach ( $res as $row ) {
1123 $values[] = $row->$var;
1126 return $values;
1130 * Returns an optional USE INDEX clause to go after the table, and a
1131 * string to go at the end of the query.
1133 * @param array $options Associative array of options to be turned into
1134 * an SQL query, valid keys are listed in the function.
1135 * @return array
1136 * @see Database::select()
1138 protected function makeSelectOptions( $options ) {
1139 $preLimitTail = $postLimitTail = '';
1140 $startOpts = '';
1142 $noKeyOptions = [];
1144 foreach ( $options as $key => $option ) {
1145 if ( is_numeric( $key ) ) {
1146 $noKeyOptions[$option] = true;
1150 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1152 $preLimitTail .= $this->makeOrderBy( $options );
1154 // if (isset($options['LIMIT'])) {
1155 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1156 // isset($options['OFFSET']) ? $options['OFFSET']
1157 // : false);
1158 // }
1160 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1161 $postLimitTail .= ' FOR UPDATE';
1164 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1165 $postLimitTail .= ' LOCK IN SHARE MODE';
1168 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1169 $startOpts .= 'DISTINCT';
1172 # Various MySQL extensions
1173 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1174 $startOpts .= ' /*! STRAIGHT_JOIN */';
1177 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1178 $startOpts .= ' HIGH_PRIORITY';
1181 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1182 $startOpts .= ' SQL_BIG_RESULT';
1185 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1186 $startOpts .= ' SQL_BUFFER_RESULT';
1189 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1190 $startOpts .= ' SQL_SMALL_RESULT';
1193 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1194 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1197 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1198 $startOpts .= ' SQL_CACHE';
1201 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1202 $startOpts .= ' SQL_NO_CACHE';
1205 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1206 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1207 } else {
1208 $useIndex = '';
1210 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1211 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1212 } else {
1213 $ignoreIndex = '';
1216 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1220 * Returns an optional GROUP BY with an optional HAVING
1222 * @param array $options Associative array of options
1223 * @return string
1224 * @see Database::select()
1225 * @since 1.21
1227 protected function makeGroupByWithHaving( $options ) {
1228 $sql = '';
1229 if ( isset( $options['GROUP BY'] ) ) {
1230 $gb = is_array( $options['GROUP BY'] )
1231 ? implode( ',', $options['GROUP BY'] )
1232 : $options['GROUP BY'];
1233 $sql .= ' GROUP BY ' . $gb;
1235 if ( isset( $options['HAVING'] ) ) {
1236 $having = is_array( $options['HAVING'] )
1237 ? $this->makeList( $options['HAVING'], self::LIST_AND )
1238 : $options['HAVING'];
1239 $sql .= ' HAVING ' . $having;
1242 return $sql;
1246 * Returns an optional ORDER BY
1248 * @param array $options Associative array of options
1249 * @return string
1250 * @see Database::select()
1251 * @since 1.21
1253 protected function makeOrderBy( $options ) {
1254 if ( isset( $options['ORDER BY'] ) ) {
1255 $ob = is_array( $options['ORDER BY'] )
1256 ? implode( ',', $options['ORDER BY'] )
1257 : $options['ORDER BY'];
1259 return ' ORDER BY ' . $ob;
1262 return '';
1265 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1266 $options = [], $join_conds = [] ) {
1267 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1269 return $this->query( $sql, $fname );
1272 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1273 $options = [], $join_conds = []
1275 if ( is_array( $vars ) ) {
1276 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1279 $options = (array)$options;
1280 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1281 ? $options['USE INDEX']
1282 : [];
1283 $ignoreIndexes = (
1284 isset( $options['IGNORE INDEX'] ) &&
1285 is_array( $options['IGNORE INDEX'] )
1287 ? $options['IGNORE INDEX']
1288 : [];
1290 if ( is_array( $table ) ) {
1291 $from = ' FROM ' .
1292 $this->tableNamesWithIndexClauseOrJOIN(
1293 $table, $useIndexes, $ignoreIndexes, $join_conds );
1294 } elseif ( $table != '' ) {
1295 if ( $table[0] == ' ' ) {
1296 $from = ' FROM ' . $table;
1297 } else {
1298 $from = ' FROM ' .
1299 $this->tableNamesWithIndexClauseOrJOIN(
1300 [ $table ], $useIndexes, $ignoreIndexes, [] );
1302 } else {
1303 $from = '';
1306 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1307 $this->makeSelectOptions( $options );
1309 if ( !empty( $conds ) ) {
1310 if ( is_array( $conds ) ) {
1311 $conds = $this->makeList( $conds, self::LIST_AND );
1313 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1314 "WHERE $conds $preLimitTail";
1315 } else {
1316 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1319 if ( isset( $options['LIMIT'] ) ) {
1320 $sql = $this->limitResult( $sql, $options['LIMIT'],
1321 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1323 $sql = "$sql $postLimitTail";
1325 if ( isset( $options['EXPLAIN'] ) ) {
1326 $sql = 'EXPLAIN ' . $sql;
1329 return $sql;
1332 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1333 $options = [], $join_conds = []
1335 $options = (array)$options;
1336 $options['LIMIT'] = 1;
1337 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1339 if ( $res === false ) {
1340 return false;
1343 if ( !$this->numRows( $res ) ) {
1344 return false;
1347 $obj = $this->fetchObject( $res );
1349 return $obj;
1352 public function estimateRowCount(
1353 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = []
1355 $rows = 0;
1356 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1358 if ( $res ) {
1359 $row = $this->fetchRow( $res );
1360 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1363 return $rows;
1366 public function selectRowCount(
1367 $tables, $vars = '*', $conds = '', $fname = __METHOD__, $options = [], $join_conds = []
1369 $rows = 0;
1370 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1371 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1373 if ( $res ) {
1374 $row = $this->fetchRow( $res );
1375 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1378 return $rows;
1382 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1383 * It's only slightly flawed. Don't use for anything important.
1385 * @param string $sql A SQL Query
1387 * @return string
1389 protected static function generalizeSQL( $sql ) {
1390 # This does the same as the regexp below would do, but in such a way
1391 # as to avoid crashing php on some large strings.
1392 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1394 $sql = str_replace( "\\\\", '', $sql );
1395 $sql = str_replace( "\\'", '', $sql );
1396 $sql = str_replace( "\\\"", '', $sql );
1397 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1398 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1400 # All newlines, tabs, etc replaced by single space
1401 $sql = preg_replace( '/\s+/', ' ', $sql );
1403 # All numbers => N,
1404 # except the ones surrounded by characters, e.g. l10n
1405 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1406 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1408 return $sql;
1411 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1412 $info = $this->fieldInfo( $table, $field );
1414 return (bool)$info;
1417 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1418 if ( !$this->tableExists( $table ) ) {
1419 return null;
1422 $info = $this->indexInfo( $table, $index, $fname );
1423 if ( is_null( $info ) ) {
1424 return null;
1425 } else {
1426 return $info !== false;
1430 public function tableExists( $table, $fname = __METHOD__ ) {
1431 $tableRaw = $this->tableName( $table, 'raw' );
1432 if ( isset( $this->mSessionTempTables[$tableRaw] ) ) {
1433 return true; // already known to exist
1436 $table = $this->tableName( $table );
1437 $old = $this->ignoreErrors( true );
1438 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1439 $this->ignoreErrors( $old );
1441 return (bool)$res;
1444 public function indexUnique( $table, $index ) {
1445 $indexInfo = $this->indexInfo( $table, $index );
1447 if ( !$indexInfo ) {
1448 return null;
1451 return !$indexInfo[0]->Non_unique;
1455 * Helper for Database::insert().
1457 * @param array $options
1458 * @return string
1460 protected function makeInsertOptions( $options ) {
1461 return implode( ' ', $options );
1464 public function insert( $table, $a, $fname = __METHOD__, $options = [] ) {
1465 # No rows to insert, easy just return now
1466 if ( !count( $a ) ) {
1467 return true;
1470 $table = $this->tableName( $table );
1472 if ( !is_array( $options ) ) {
1473 $options = [ $options ];
1476 $fh = null;
1477 if ( isset( $options['fileHandle'] ) ) {
1478 $fh = $options['fileHandle'];
1480 $options = $this->makeInsertOptions( $options );
1482 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1483 $multi = true;
1484 $keys = array_keys( $a[0] );
1485 } else {
1486 $multi = false;
1487 $keys = array_keys( $a );
1490 $sql = 'INSERT ' . $options .
1491 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1493 if ( $multi ) {
1494 $first = true;
1495 foreach ( $a as $row ) {
1496 if ( $first ) {
1497 $first = false;
1498 } else {
1499 $sql .= ',';
1501 $sql .= '(' . $this->makeList( $row ) . ')';
1503 } else {
1504 $sql .= '(' . $this->makeList( $a ) . ')';
1507 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1508 return false;
1509 } elseif ( $fh !== null ) {
1510 return true;
1513 return (bool)$this->query( $sql, $fname );
1517 * Make UPDATE options array for Database::makeUpdateOptions
1519 * @param array $options
1520 * @return array
1522 protected function makeUpdateOptionsArray( $options ) {
1523 if ( !is_array( $options ) ) {
1524 $options = [ $options ];
1527 $opts = [];
1529 if ( in_array( 'IGNORE', $options ) ) {
1530 $opts[] = 'IGNORE';
1533 return $opts;
1537 * Make UPDATE options for the Database::update function
1539 * @param array $options The options passed to Database::update
1540 * @return string
1542 protected function makeUpdateOptions( $options ) {
1543 $opts = $this->makeUpdateOptionsArray( $options );
1545 return implode( ' ', $opts );
1548 public function update( $table, $values, $conds, $fname = __METHOD__, $options = [] ) {
1549 $table = $this->tableName( $table );
1550 $opts = $this->makeUpdateOptions( $options );
1551 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self::LIST_SET );
1553 if ( $conds !== [] && $conds !== '*' ) {
1554 $sql .= " WHERE " . $this->makeList( $conds, self::LIST_AND );
1557 return $this->query( $sql, $fname );
1560 public function makeList( $a, $mode = self::LIST_COMMA ) {
1561 if ( !is_array( $a ) ) {
1562 throw new DBUnexpectedError( $this, __METHOD__ . ' called with incorrect parameters' );
1565 $first = true;
1566 $list = '';
1568 foreach ( $a as $field => $value ) {
1569 if ( !$first ) {
1570 if ( $mode == self::LIST_AND ) {
1571 $list .= ' AND ';
1572 } elseif ( $mode == self::LIST_OR ) {
1573 $list .= ' OR ';
1574 } else {
1575 $list .= ',';
1577 } else {
1578 $first = false;
1581 if ( ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_numeric( $field ) ) {
1582 $list .= "($value)";
1583 } elseif ( $mode == self::LIST_SET && is_numeric( $field ) ) {
1584 $list .= "$value";
1585 } elseif (
1586 ( $mode == self::LIST_AND || $mode == self::LIST_OR ) && is_array( $value )
1588 // Remove null from array to be handled separately if found
1589 $includeNull = false;
1590 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1591 $includeNull = true;
1592 unset( $value[$nullKey] );
1594 if ( count( $value ) == 0 && !$includeNull ) {
1595 throw new InvalidArgumentException(
1596 __METHOD__ . ": empty input for field $field" );
1597 } elseif ( count( $value ) == 0 ) {
1598 // only check if $field is null
1599 $list .= "$field IS NULL";
1600 } else {
1601 // IN clause contains at least one valid element
1602 if ( $includeNull ) {
1603 // Group subconditions to ensure correct precedence
1604 $list .= '(';
1606 if ( count( $value ) == 1 ) {
1607 // Special-case single values, as IN isn't terribly efficient
1608 // Don't necessarily assume the single key is 0; we don't
1609 // enforce linear numeric ordering on other arrays here.
1610 $value = array_values( $value )[0];
1611 $list .= $field . " = " . $this->addQuotes( $value );
1612 } else {
1613 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1615 // if null present in array, append IS NULL
1616 if ( $includeNull ) {
1617 $list .= " OR $field IS NULL)";
1620 } elseif ( $value === null ) {
1621 if ( $mode == self::LIST_AND || $mode == self::LIST_OR ) {
1622 $list .= "$field IS ";
1623 } elseif ( $mode == self::LIST_SET ) {
1624 $list .= "$field = ";
1626 $list .= 'NULL';
1627 } else {
1628 if (
1629 $mode == self::LIST_AND || $mode == self::LIST_OR || $mode == self::LIST_SET
1631 $list .= "$field = ";
1633 $list .= $mode == self::LIST_NAMES ? $value : $this->addQuotes( $value );
1637 return $list;
1640 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1641 $conds = [];
1643 foreach ( $data as $base => $sub ) {
1644 if ( count( $sub ) ) {
1645 $conds[] = $this->makeList(
1646 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1647 self::LIST_AND );
1651 if ( $conds ) {
1652 return $this->makeList( $conds, self::LIST_OR );
1653 } else {
1654 // Nothing to search for...
1655 return false;
1659 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1660 return $valuename;
1663 public function bitNot( $field ) {
1664 return "(~$field)";
1667 public function bitAnd( $fieldLeft, $fieldRight ) {
1668 return "($fieldLeft & $fieldRight)";
1671 public function bitOr( $fieldLeft, $fieldRight ) {
1672 return "($fieldLeft | $fieldRight)";
1675 public function buildConcat( $stringList ) {
1676 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1679 public function buildGroupConcatField(
1680 $delim, $table, $field, $conds = '', $join_conds = []
1682 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1684 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1687 public function buildStringCast( $field ) {
1688 return $field;
1691 public function selectDB( $db ) {
1692 # Stub. Shouldn't cause serious problems if it's not overridden, but
1693 # if your database engine supports a concept similar to MySQL's
1694 # databases you may as well.
1695 $this->mDBname = $db;
1697 return true;
1700 public function getDBname() {
1701 return $this->mDBname;
1704 public function getServer() {
1705 return $this->mServer;
1708 public function tableName( $name, $format = 'quoted' ) {
1709 # Skip the entire process when we have a string quoted on both ends.
1710 # Note that we check the end so that we will still quote any use of
1711 # use of `database`.table. But won't break things if someone wants
1712 # to query a database table with a dot in the name.
1713 if ( $this->isQuotedIdentifier( $name ) ) {
1714 return $name;
1717 # Lets test for any bits of text that should never show up in a table
1718 # name. Basically anything like JOIN or ON which are actually part of
1719 # SQL queries, but may end up inside of the table value to combine
1720 # sql. Such as how the API is doing.
1721 # Note that we use a whitespace test rather than a \b test to avoid
1722 # any remote case where a word like on may be inside of a table name
1723 # surrounded by symbols which may be considered word breaks.
1724 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1725 return $name;
1728 # Split database and table into proper variables.
1729 # We reverse the explode so that database.table and table both output
1730 # the correct table.
1731 $dbDetails = explode( '.', $name, 3 );
1732 if ( count( $dbDetails ) == 3 ) {
1733 list( $database, $schema, $table ) = $dbDetails;
1734 # We don't want any prefix added in this case
1735 $prefix = '';
1736 } elseif ( count( $dbDetails ) == 2 ) {
1737 list( $database, $table ) = $dbDetails;
1738 # We don't want any prefix added in this case
1739 $prefix = '';
1740 # In dbs that support it, $database may actually be the schema
1741 # but that doesn't affect any of the functionality here
1742 $schema = '';
1743 } else {
1744 list( $table ) = $dbDetails;
1745 if ( isset( $this->tableAliases[$table] ) ) {
1746 $database = $this->tableAliases[$table]['dbname'];
1747 $schema = is_string( $this->tableAliases[$table]['schema'] )
1748 ? $this->tableAliases[$table]['schema']
1749 : $this->mSchema;
1750 $prefix = is_string( $this->tableAliases[$table]['prefix'] )
1751 ? $this->tableAliases[$table]['prefix']
1752 : $this->mTablePrefix;
1753 } else {
1754 $database = '';
1755 $schema = $this->mSchema; # Default schema
1756 $prefix = $this->mTablePrefix; # Default prefix
1760 # Quote $table and apply the prefix if not quoted.
1761 # $tableName might be empty if this is called from Database::replaceVars()
1762 $tableName = "{$prefix}{$table}";
1763 if ( $format === 'quoted'
1764 && !$this->isQuotedIdentifier( $tableName )
1765 && $tableName !== ''
1767 $tableName = $this->addIdentifierQuotes( $tableName );
1770 # Quote $schema and $database and merge them with the table name if needed
1771 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1772 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1774 return $tableName;
1778 * @param string|null $namespace Database or schema
1779 * @param string $relation Name of table, view, sequence, etc...
1780 * @param string $format One of (raw, quoted)
1781 * @return string Relation name with quoted and merged $namespace as needed
1783 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1784 if ( strlen( $namespace ) ) {
1785 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1786 $namespace = $this->addIdentifierQuotes( $namespace );
1788 $relation = $namespace . '.' . $relation;
1791 return $relation;
1794 public function tableNames() {
1795 $inArray = func_get_args();
1796 $retVal = [];
1798 foreach ( $inArray as $name ) {
1799 $retVal[$name] = $this->tableName( $name );
1802 return $retVal;
1805 public function tableNamesN() {
1806 $inArray = func_get_args();
1807 $retVal = [];
1809 foreach ( $inArray as $name ) {
1810 $retVal[] = $this->tableName( $name );
1813 return $retVal;
1817 * Get an aliased table name
1818 * e.g. tableName AS newTableName
1820 * @param string $name Table name, see tableName()
1821 * @param string|bool $alias Alias (optional)
1822 * @return string SQL name for aliased table. Will not alias a table to its own name
1824 protected function tableNameWithAlias( $name, $alias = false ) {
1825 if ( !$alias || $alias == $name ) {
1826 return $this->tableName( $name );
1827 } else {
1828 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1833 * Gets an array of aliased table names
1835 * @param array $tables [ [alias] => table ]
1836 * @return string[] See tableNameWithAlias()
1838 protected function tableNamesWithAlias( $tables ) {
1839 $retval = [];
1840 foreach ( $tables as $alias => $table ) {
1841 if ( is_numeric( $alias ) ) {
1842 $alias = $table;
1844 $retval[] = $this->tableNameWithAlias( $table, $alias );
1847 return $retval;
1851 * Get an aliased field name
1852 * e.g. fieldName AS newFieldName
1854 * @param string $name Field name
1855 * @param string|bool $alias Alias (optional)
1856 * @return string SQL name for aliased field. Will not alias a field to its own name
1858 protected function fieldNameWithAlias( $name, $alias = false ) {
1859 if ( !$alias || (string)$alias === (string)$name ) {
1860 return $name;
1861 } else {
1862 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1867 * Gets an array of aliased field names
1869 * @param array $fields [ [alias] => field ]
1870 * @return string[] See fieldNameWithAlias()
1872 protected function fieldNamesWithAlias( $fields ) {
1873 $retval = [];
1874 foreach ( $fields as $alias => $field ) {
1875 if ( is_numeric( $alias ) ) {
1876 $alias = $field;
1878 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1881 return $retval;
1885 * Get the aliased table name clause for a FROM clause
1886 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1888 * @param array $tables ( [alias] => table )
1889 * @param array $use_index Same as for select()
1890 * @param array $ignore_index Same as for select()
1891 * @param array $join_conds Same as for select()
1892 * @return string
1894 protected function tableNamesWithIndexClauseOrJOIN(
1895 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1897 $ret = [];
1898 $retJOIN = [];
1899 $use_index = (array)$use_index;
1900 $ignore_index = (array)$ignore_index;
1901 $join_conds = (array)$join_conds;
1903 foreach ( $tables as $alias => $table ) {
1904 if ( !is_string( $alias ) ) {
1905 // No alias? Set it equal to the table name
1906 $alias = $table;
1908 // Is there a JOIN clause for this table?
1909 if ( isset( $join_conds[$alias] ) ) {
1910 list( $joinType, $conds ) = $join_conds[$alias];
1911 $tableClause = $joinType;
1912 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1913 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1914 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1915 if ( $use != '' ) {
1916 $tableClause .= ' ' . $use;
1919 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1920 $ignore = $this->ignoreIndexClause(
1921 implode( ',', (array)$ignore_index[$alias] ) );
1922 if ( $ignore != '' ) {
1923 $tableClause .= ' ' . $ignore;
1926 $on = $this->makeList( (array)$conds, self::LIST_AND );
1927 if ( $on != '' ) {
1928 $tableClause .= ' ON (' . $on . ')';
1931 $retJOIN[] = $tableClause;
1932 } elseif ( isset( $use_index[$alias] ) ) {
1933 // Is there an INDEX clause for this table?
1934 $tableClause = $this->tableNameWithAlias( $table, $alias );
1935 $tableClause .= ' ' . $this->useIndexClause(
1936 implode( ',', (array)$use_index[$alias] )
1939 $ret[] = $tableClause;
1940 } elseif ( isset( $ignore_index[$alias] ) ) {
1941 // Is there an INDEX clause for this table?
1942 $tableClause = $this->tableNameWithAlias( $table, $alias );
1943 $tableClause .= ' ' . $this->ignoreIndexClause(
1944 implode( ',', (array)$ignore_index[$alias] )
1947 $ret[] = $tableClause;
1948 } else {
1949 $tableClause = $this->tableNameWithAlias( $table, $alias );
1951 $ret[] = $tableClause;
1955 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1956 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
1957 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
1959 // Compile our final table clause
1960 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1964 * Get the name of an index in a given table.
1966 * @param string $index
1967 * @return string
1969 protected function indexName( $index ) {
1970 return $index;
1973 public function addQuotes( $s ) {
1974 if ( $s instanceof Blob ) {
1975 $s = $s->fetch();
1977 if ( $s === null ) {
1978 return 'NULL';
1979 } elseif ( is_bool( $s ) ) {
1980 return (int)$s;
1981 } else {
1982 # This will also quote numeric values. This should be harmless,
1983 # and protects against weird problems that occur when they really
1984 # _are_ strings such as article titles and string->number->string
1985 # conversion is not 1:1.
1986 return "'" . $this->strencode( $s ) . "'";
1991 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1992 * MySQL uses `backticks` while basically everything else uses double quotes.
1993 * Since MySQL is the odd one out here the double quotes are our generic
1994 * and we implement backticks in DatabaseMysql.
1996 * @param string $s
1997 * @return string
1999 public function addIdentifierQuotes( $s ) {
2000 return '"' . str_replace( '"', '""', $s ) . '"';
2004 * Returns if the given identifier looks quoted or not according to
2005 * the database convention for quoting identifiers .
2007 * @note Do not use this to determine if untrusted input is safe.
2008 * A malicious user can trick this function.
2009 * @param string $name
2010 * @return bool
2012 public function isQuotedIdentifier( $name ) {
2013 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2017 * @param string $s
2018 * @return string
2020 protected function escapeLikeInternal( $s ) {
2021 return addcslashes( $s, '\%_' );
2024 public function buildLike() {
2025 $params = func_get_args();
2027 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2028 $params = $params[0];
2031 $s = '';
2033 foreach ( $params as $value ) {
2034 if ( $value instanceof LikeMatch ) {
2035 $s .= $value->toString();
2036 } else {
2037 $s .= $this->escapeLikeInternal( $value );
2041 return " LIKE {$this->addQuotes( $s )} ";
2044 public function anyChar() {
2045 return new LikeMatch( '_' );
2048 public function anyString() {
2049 return new LikeMatch( '%' );
2052 public function nextSequenceValue( $seqName ) {
2053 return null;
2057 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2058 * is only needed because a) MySQL must be as efficient as possible due to
2059 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2060 * which index to pick. Anyway, other databases might have different
2061 * indexes on a given table. So don't bother overriding this unless you're
2062 * MySQL.
2063 * @param string $index
2064 * @return string
2066 public function useIndexClause( $index ) {
2067 return '';
2071 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2072 * is only needed because a) MySQL must be as efficient as possible due to
2073 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2074 * which index to pick. Anyway, other databases might have different
2075 * indexes on a given table. So don't bother overriding this unless you're
2076 * MySQL.
2077 * @param string $index
2078 * @return string
2080 public function ignoreIndexClause( $index ) {
2081 return '';
2084 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2085 $quotedTable = $this->tableName( $table );
2087 if ( count( $rows ) == 0 ) {
2088 return;
2091 # Single row case
2092 if ( !is_array( reset( $rows ) ) ) {
2093 $rows = [ $rows ];
2096 // @FXIME: this is not atomic, but a trx would break affectedRows()
2097 foreach ( $rows as $row ) {
2098 # Delete rows which collide
2099 if ( $uniqueIndexes ) {
2100 $sql = "DELETE FROM $quotedTable WHERE ";
2101 $first = true;
2102 foreach ( $uniqueIndexes as $index ) {
2103 if ( $first ) {
2104 $first = false;
2105 $sql .= '( ';
2106 } else {
2107 $sql .= ' ) OR ( ';
2109 if ( is_array( $index ) ) {
2110 $first2 = true;
2111 foreach ( $index as $col ) {
2112 if ( $first2 ) {
2113 $first2 = false;
2114 } else {
2115 $sql .= ' AND ';
2117 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2119 } else {
2120 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2123 $sql .= ' )';
2124 $this->query( $sql, $fname );
2127 # Now insert the row
2128 $this->insert( $table, $row, $fname );
2133 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2134 * statement.
2136 * @param string $table Table name
2137 * @param array|string $rows Row(s) to insert
2138 * @param string $fname Caller function name
2140 * @return ResultWrapper
2142 protected function nativeReplace( $table, $rows, $fname ) {
2143 $table = $this->tableName( $table );
2145 # Single row case
2146 if ( !is_array( reset( $rows ) ) ) {
2147 $rows = [ $rows ];
2150 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2151 $first = true;
2153 foreach ( $rows as $row ) {
2154 if ( $first ) {
2155 $first = false;
2156 } else {
2157 $sql .= ',';
2160 $sql .= '(' . $this->makeList( $row ) . ')';
2163 return $this->query( $sql, $fname );
2166 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2167 $fname = __METHOD__
2169 if ( !count( $rows ) ) {
2170 return true; // nothing to do
2173 if ( !is_array( reset( $rows ) ) ) {
2174 $rows = [ $rows ];
2177 if ( count( $uniqueIndexes ) ) {
2178 $clauses = []; // list WHERE clauses that each identify a single row
2179 foreach ( $rows as $row ) {
2180 foreach ( $uniqueIndexes as $index ) {
2181 $index = is_array( $index ) ? $index : [ $index ]; // columns
2182 $rowKey = []; // unique key to this row
2183 foreach ( $index as $column ) {
2184 $rowKey[$column] = $row[$column];
2186 $clauses[] = $this->makeList( $rowKey, self::LIST_AND );
2189 $where = [ $this->makeList( $clauses, self::LIST_OR ) ];
2190 } else {
2191 $where = false;
2194 $useTrx = !$this->mTrxLevel;
2195 if ( $useTrx ) {
2196 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2198 try {
2199 # Update any existing conflicting row(s)
2200 if ( $where !== false ) {
2201 $ok = $this->update( $table, $set, $where, $fname );
2202 } else {
2203 $ok = true;
2205 # Now insert any non-conflicting row(s)
2206 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2207 } catch ( Exception $e ) {
2208 if ( $useTrx ) {
2209 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2211 throw $e;
2213 if ( $useTrx ) {
2214 $this->commit( $fname, self::FLUSHING_INTERNAL );
2217 return $ok;
2220 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2221 $fname = __METHOD__
2223 if ( !$conds ) {
2224 throw new DBUnexpectedError( $this, __METHOD__ . ' called with empty $conds' );
2227 $delTable = $this->tableName( $delTable );
2228 $joinTable = $this->tableName( $joinTable );
2229 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2230 if ( $conds != '*' ) {
2231 $sql .= 'WHERE ' . $this->makeList( $conds, self::LIST_AND );
2233 $sql .= ')';
2235 $this->query( $sql, $fname );
2238 public function textFieldSize( $table, $field ) {
2239 $table = $this->tableName( $table );
2240 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2241 $res = $this->query( $sql, __METHOD__ );
2242 $row = $this->fetchObject( $res );
2244 $m = [];
2246 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2247 $size = $m[1];
2248 } else {
2249 $size = -1;
2252 return $size;
2255 public function delete( $table, $conds, $fname = __METHOD__ ) {
2256 if ( !$conds ) {
2257 throw new DBUnexpectedError( $this, __METHOD__ . ' called with no conditions' );
2260 $table = $this->tableName( $table );
2261 $sql = "DELETE FROM $table";
2263 if ( $conds != '*' ) {
2264 if ( is_array( $conds ) ) {
2265 $conds = $this->makeList( $conds, self::LIST_AND );
2267 $sql .= ' WHERE ' . $conds;
2270 return $this->query( $sql, $fname );
2273 public function insertSelect(
2274 $destTable, $srcTable, $varMap, $conds,
2275 $fname = __METHOD__, $insertOptions = [], $selectOptions = []
2277 if ( $this->cliMode ) {
2278 // For massive migrations with downtime, we don't want to select everything
2279 // into memory and OOM, so do all this native on the server side if possible.
2280 return $this->nativeInsertSelect(
2281 $destTable,
2282 $srcTable,
2283 $varMap,
2284 $conds,
2285 $fname,
2286 $insertOptions,
2287 $selectOptions
2291 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2292 // on only the master (without needing row-based-replication). It also makes it easy to
2293 // know how big the INSERT is going to be.
2294 $fields = [];
2295 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2296 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2298 $selectOptions[] = 'FOR UPDATE';
2299 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2300 if ( !$res ) {
2301 return false;
2304 $rows = [];
2305 foreach ( $res as $row ) {
2306 $rows[] = (array)$row;
2309 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2312 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2313 $fname = __METHOD__,
2314 $insertOptions = [], $selectOptions = []
2316 $destTable = $this->tableName( $destTable );
2318 if ( !is_array( $insertOptions ) ) {
2319 $insertOptions = [ $insertOptions ];
2322 $insertOptions = $this->makeInsertOptions( $insertOptions );
2324 if ( !is_array( $selectOptions ) ) {
2325 $selectOptions = [ $selectOptions ];
2328 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2329 $selectOptions );
2331 if ( is_array( $srcTable ) ) {
2332 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2333 } else {
2334 $srcTable = $this->tableName( $srcTable );
2337 $sql = "INSERT $insertOptions" .
2338 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2339 " SELECT $startOpts " . implode( ',', $varMap ) .
2340 " FROM $srcTable $useIndex $ignoreIndex ";
2342 if ( $conds != '*' ) {
2343 if ( is_array( $conds ) ) {
2344 $conds = $this->makeList( $conds, self::LIST_AND );
2346 $sql .= " WHERE $conds";
2349 $sql .= " $tailOpts";
2351 return $this->query( $sql, $fname );
2355 * Construct a LIMIT query with optional offset. This is used for query
2356 * pages. The SQL should be adjusted so that only the first $limit rows
2357 * are returned. If $offset is provided as well, then the first $offset
2358 * rows should be discarded, and the next $limit rows should be returned.
2359 * If the result of the query is not ordered, then the rows to be returned
2360 * are theoretically arbitrary.
2362 * $sql is expected to be a SELECT, if that makes a difference.
2364 * The version provided by default works in MySQL and SQLite. It will very
2365 * likely need to be overridden for most other DBMSes.
2367 * @param string $sql SQL query we will append the limit too
2368 * @param int $limit The SQL limit
2369 * @param int|bool $offset The SQL offset (default false)
2370 * @throws DBUnexpectedError
2371 * @return string
2373 public function limitResult( $sql, $limit, $offset = false ) {
2374 if ( !is_numeric( $limit ) ) {
2375 throw new DBUnexpectedError( $this,
2376 "Invalid non-numeric limit passed to limitResult()\n" );
2379 return "$sql LIMIT "
2380 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
2381 . "{$limit} ";
2384 public function unionSupportsOrderAndLimit() {
2385 return true; // True for almost every DB supported
2388 public function unionQueries( $sqls, $all ) {
2389 $glue = $all ? ') UNION ALL (' : ') UNION (';
2391 return '(' . implode( $glue, $sqls ) . ')';
2394 public function conditional( $cond, $trueVal, $falseVal ) {
2395 if ( is_array( $cond ) ) {
2396 $cond = $this->makeList( $cond, self::LIST_AND );
2399 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2402 public function strreplace( $orig, $old, $new ) {
2403 return "REPLACE({$orig}, {$old}, {$new})";
2406 public function getServerUptime() {
2407 return 0;
2410 public function wasDeadlock() {
2411 return false;
2414 public function wasLockTimeout() {
2415 return false;
2418 public function wasErrorReissuable() {
2419 return false;
2422 public function wasReadOnlyError() {
2423 return false;
2427 * Do not use this method outside of Database/DBError classes
2429 * @param integer|string $errno
2430 * @return bool Whether the given query error was a connection drop
2432 public function wasConnectionError( $errno ) {
2433 return false;
2436 public function deadlockLoop() {
2437 $args = func_get_args();
2438 $function = array_shift( $args );
2439 $tries = self::DEADLOCK_TRIES;
2441 $this->begin( __METHOD__ );
2443 $retVal = null;
2444 /** @var Exception $e */
2445 $e = null;
2446 do {
2447 try {
2448 $retVal = call_user_func_array( $function, $args );
2449 break;
2450 } catch ( DBQueryError $e ) {
2451 if ( $this->wasDeadlock() ) {
2452 // Retry after a randomized delay
2453 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
2454 } else {
2455 // Throw the error back up
2456 throw $e;
2459 } while ( --$tries > 0 );
2461 if ( $tries <= 0 ) {
2462 // Too many deadlocks; give up
2463 $this->rollback( __METHOD__ );
2464 throw $e;
2465 } else {
2466 $this->commit( __METHOD__ );
2468 return $retVal;
2472 public function masterPosWait( DBMasterPos $pos, $timeout ) {
2473 # Real waits are implemented in the subclass.
2474 return 0;
2477 public function getReplicaPos() {
2478 # Stub
2479 return false;
2482 public function getMasterPos() {
2483 # Stub
2484 return false;
2487 public function serverIsReadOnly() {
2488 return false;
2491 final public function onTransactionResolution( callable $callback, $fname = __METHOD__ ) {
2492 if ( !$this->mTrxLevel ) {
2493 throw new DBUnexpectedError( $this, "No transaction is active." );
2495 $this->mTrxEndCallbacks[] = [ $callback, $fname ];
2498 final public function onTransactionIdle( callable $callback, $fname = __METHOD__ ) {
2499 $this->mTrxIdleCallbacks[] = [ $callback, $fname ];
2500 if ( !$this->mTrxLevel ) {
2501 $this->runOnTransactionIdleCallbacks( self::TRIGGER_IDLE );
2505 final public function onTransactionPreCommitOrIdle( callable $callback, $fname = __METHOD__ ) {
2506 if ( $this->mTrxLevel ) {
2507 $this->mTrxPreCommitCallbacks[] = [ $callback, $fname ];
2508 } else {
2509 // If no transaction is active, then make one for this callback
2510 $this->startAtomic( __METHOD__ );
2511 try {
2512 call_user_func( $callback );
2513 $this->endAtomic( __METHOD__ );
2514 } catch ( Exception $e ) {
2515 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2516 throw $e;
2521 final public function setTransactionListener( $name, callable $callback = null ) {
2522 if ( $callback ) {
2523 $this->mTrxRecurringCallbacks[$name] = $callback;
2524 } else {
2525 unset( $this->mTrxRecurringCallbacks[$name] );
2530 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2532 * This method should not be used outside of Database/LoadBalancer
2534 * @param bool $suppress
2535 * @since 1.28
2537 final public function setTrxEndCallbackSuppression( $suppress ) {
2538 $this->mTrxEndCallbacksSuppressed = $suppress;
2542 * Actually run and consume any "on transaction idle/resolution" callbacks.
2544 * This method should not be used outside of Database/LoadBalancer
2546 * @param integer $trigger IDatabase::TRIGGER_* constant
2547 * @since 1.20
2548 * @throws Exception
2550 public function runOnTransactionIdleCallbacks( $trigger ) {
2551 if ( $this->mTrxEndCallbacksSuppressed ) {
2552 return;
2555 $autoTrx = $this->getFlag( self::DBO_TRX ); // automatic begin() enabled?
2556 /** @var Exception $e */
2557 $e = null; // first exception
2558 do { // callbacks may add callbacks :)
2559 $callbacks = array_merge(
2560 $this->mTrxIdleCallbacks,
2561 $this->mTrxEndCallbacks // include "transaction resolution" callbacks
2563 $this->mTrxIdleCallbacks = []; // consumed (and recursion guard)
2564 $this->mTrxEndCallbacks = []; // consumed (recursion guard)
2565 foreach ( $callbacks as $callback ) {
2566 try {
2567 list( $phpCallback ) = $callback;
2568 $this->clearFlag( self::DBO_TRX ); // make each query its own transaction
2569 call_user_func_array( $phpCallback, [ $trigger ] );
2570 if ( $autoTrx ) {
2571 $this->setFlag( self::DBO_TRX ); // restore automatic begin()
2572 } else {
2573 $this->clearFlag( self::DBO_TRX ); // restore auto-commit
2575 } catch ( Exception $ex ) {
2576 call_user_func( $this->errorLogger, $ex );
2577 $e = $e ?: $ex;
2578 // Some callbacks may use startAtomic/endAtomic, so make sure
2579 // their transactions are ended so other callbacks don't fail
2580 if ( $this->trxLevel() ) {
2581 $this->rollback( __METHOD__, self::FLUSHING_INTERNAL );
2585 } while ( count( $this->mTrxIdleCallbacks ) );
2587 if ( $e instanceof Exception ) {
2588 throw $e; // re-throw any first exception
2593 * Actually run and consume any "on transaction pre-commit" callbacks.
2595 * This method should not be used outside of Database/LoadBalancer
2597 * @since 1.22
2598 * @throws Exception
2600 public function runOnTransactionPreCommitCallbacks() {
2601 $e = null; // first exception
2602 do { // callbacks may add callbacks :)
2603 $callbacks = $this->mTrxPreCommitCallbacks;
2604 $this->mTrxPreCommitCallbacks = []; // consumed (and recursion guard)
2605 foreach ( $callbacks as $callback ) {
2606 try {
2607 list( $phpCallback ) = $callback;
2608 call_user_func( $phpCallback );
2609 } catch ( Exception $ex ) {
2610 call_user_func( $this->errorLogger, $ex );
2611 $e = $e ?: $ex;
2614 } while ( count( $this->mTrxPreCommitCallbacks ) );
2616 if ( $e instanceof Exception ) {
2617 throw $e; // re-throw any first exception
2622 * Actually run any "transaction listener" callbacks.
2624 * This method should not be used outside of Database/LoadBalancer
2626 * @param integer $trigger IDatabase::TRIGGER_* constant
2627 * @throws Exception
2628 * @since 1.20
2630 public function runTransactionListenerCallbacks( $trigger ) {
2631 if ( $this->mTrxEndCallbacksSuppressed ) {
2632 return;
2635 /** @var Exception $e */
2636 $e = null; // first exception
2638 foreach ( $this->mTrxRecurringCallbacks as $phpCallback ) {
2639 try {
2640 $phpCallback( $trigger, $this );
2641 } catch ( Exception $ex ) {
2642 call_user_func( $this->errorLogger, $ex );
2643 $e = $e ?: $ex;
2647 if ( $e instanceof Exception ) {
2648 throw $e; // re-throw any first exception
2652 final public function startAtomic( $fname = __METHOD__ ) {
2653 if ( !$this->mTrxLevel ) {
2654 $this->begin( $fname, self::TRANSACTION_INTERNAL );
2655 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2656 // in all changes being in one transaction to keep requests transactional.
2657 if ( !$this->getFlag( self::DBO_TRX ) ) {
2658 $this->mTrxAutomaticAtomic = true;
2662 $this->mTrxAtomicLevels[] = $fname;
2665 final public function endAtomic( $fname = __METHOD__ ) {
2666 if ( !$this->mTrxLevel ) {
2667 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2669 if ( !$this->mTrxAtomicLevels ||
2670 array_pop( $this->mTrxAtomicLevels ) !== $fname
2672 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2675 if ( !$this->mTrxAtomicLevels && $this->mTrxAutomaticAtomic ) {
2676 $this->commit( $fname, self::FLUSHING_INTERNAL );
2680 final public function doAtomicSection( $fname, callable $callback ) {
2681 $this->startAtomic( $fname );
2682 try {
2683 $res = call_user_func_array( $callback, [ $this, $fname ] );
2684 } catch ( Exception $e ) {
2685 $this->rollback( $fname, self::FLUSHING_INTERNAL );
2686 throw $e;
2688 $this->endAtomic( $fname );
2690 return $res;
2693 final public function begin( $fname = __METHOD__, $mode = self::TRANSACTION_EXPLICIT ) {
2694 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2695 if ( $this->mTrxLevel ) {
2696 if ( $this->mTrxAtomicLevels ) {
2697 $levels = implode( ', ', $this->mTrxAtomicLevels );
2698 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2699 throw new DBUnexpectedError( $this, $msg );
2700 } elseif ( !$this->mTrxAutomatic ) {
2701 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2702 throw new DBUnexpectedError( $this, $msg );
2703 } else {
2704 // @TODO: make this an exception at some point
2705 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2706 $this->queryLogger->error( $msg );
2707 return; // join the main transaction set
2709 } elseif ( $this->getFlag( self::DBO_TRX ) && $mode !== self::TRANSACTION_INTERNAL ) {
2710 // @TODO: make this an exception at some point
2711 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2712 $this->queryLogger->error( $msg );
2713 return; // let any writes be in the main transaction
2716 // Avoid fatals if close() was called
2717 $this->assertOpen();
2719 $this->doBegin( $fname );
2720 $this->mTrxTimestamp = microtime( true );
2721 $this->mTrxFname = $fname;
2722 $this->mTrxDoneWrites = false;
2723 $this->mTrxAutomaticAtomic = false;
2724 $this->mTrxAtomicLevels = [];
2725 $this->mTrxShortId = sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2726 $this->mTrxWriteDuration = 0.0;
2727 $this->mTrxWriteQueryCount = 0;
2728 $this->mTrxWriteAdjDuration = 0.0;
2729 $this->mTrxWriteAdjQueryCount = 0;
2730 $this->mTrxWriteCallers = [];
2731 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2732 // Get an estimate of the replica DB lag before then, treating estimate staleness
2733 // as lag itself just to be safe
2734 $status = $this->getApproximateLagStatus();
2735 $this->mTrxReplicaLag = $status['lag'] + ( microtime( true ) - $status['since'] );
2736 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2737 // caller will think its OK to muck around with the transaction just because startAtomic()
2738 // has not yet completed (e.g. setting mTrxAtomicLevels).
2739 $this->mTrxAutomatic = ( $mode === self::TRANSACTION_INTERNAL );
2743 * Issues the BEGIN command to the database server.
2745 * @see Database::begin()
2746 * @param string $fname
2748 protected function doBegin( $fname ) {
2749 $this->query( 'BEGIN', $fname );
2750 $this->mTrxLevel = 1;
2753 final public function commit( $fname = __METHOD__, $flush = '' ) {
2754 if ( $this->mTrxLevel && $this->mTrxAtomicLevels ) {
2755 // There are still atomic sections open. This cannot be ignored
2756 $levels = implode( ', ', $this->mTrxAtomicLevels );
2757 throw new DBUnexpectedError(
2758 $this,
2759 "$fname: Got COMMIT while atomic sections $levels are still open."
2763 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2764 if ( !$this->mTrxLevel ) {
2765 return; // nothing to do
2766 } elseif ( !$this->mTrxAutomatic ) {
2767 throw new DBUnexpectedError(
2768 $this,
2769 "$fname: Flushing an explicit transaction, getting out of sync."
2772 } else {
2773 if ( !$this->mTrxLevel ) {
2774 $this->queryLogger->error(
2775 "$fname: No transaction to commit, something got out of sync." );
2776 return; // nothing to do
2777 } elseif ( $this->mTrxAutomatic ) {
2778 // @TODO: make this an exception at some point
2779 $msg = "$fname: Explicit commit of implicit transaction.";
2780 $this->queryLogger->error( $msg );
2781 return; // wait for the main transaction set commit round
2785 // Avoid fatals if close() was called
2786 $this->assertOpen();
2788 $this->runOnTransactionPreCommitCallbacks();
2789 $writeTime = $this->pendingWriteQueryDuration( self::ESTIMATE_DB_APPLY );
2790 $this->doCommit( $fname );
2791 if ( $this->mTrxDoneWrites ) {
2792 $this->mLastWriteTime = microtime( true );
2793 $this->trxProfiler->transactionWritingOut(
2794 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
2797 $this->runOnTransactionIdleCallbacks( self::TRIGGER_COMMIT );
2798 $this->runTransactionListenerCallbacks( self::TRIGGER_COMMIT );
2802 * Issues the COMMIT command to the database server.
2804 * @see Database::commit()
2805 * @param string $fname
2807 protected function doCommit( $fname ) {
2808 if ( $this->mTrxLevel ) {
2809 $this->query( 'COMMIT', $fname );
2810 $this->mTrxLevel = 0;
2814 final public function rollback( $fname = __METHOD__, $flush = '' ) {
2815 if ( $flush === self::FLUSHING_INTERNAL || $flush === self::FLUSHING_ALL_PEERS ) {
2816 if ( !$this->mTrxLevel ) {
2817 return; // nothing to do
2819 } else {
2820 if ( !$this->mTrxLevel ) {
2821 $this->queryLogger->error(
2822 "$fname: No transaction to rollback, something got out of sync." );
2823 return; // nothing to do
2824 } elseif ( $this->getFlag( self::DBO_TRX ) ) {
2825 throw new DBUnexpectedError(
2826 $this,
2827 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2832 // Avoid fatals if close() was called
2833 $this->assertOpen();
2835 $this->doRollback( $fname );
2836 $this->mTrxAtomicLevels = [];
2837 if ( $this->mTrxDoneWrites ) {
2838 $this->trxProfiler->transactionWritingOut(
2839 $this->mServer, $this->mDBname, $this->mTrxShortId );
2842 $this->mTrxIdleCallbacks = []; // clear
2843 $this->mTrxPreCommitCallbacks = []; // clear
2844 $this->runOnTransactionIdleCallbacks( self::TRIGGER_ROLLBACK );
2845 $this->runTransactionListenerCallbacks( self::TRIGGER_ROLLBACK );
2849 * Issues the ROLLBACK command to the database server.
2851 * @see Database::rollback()
2852 * @param string $fname
2854 protected function doRollback( $fname ) {
2855 if ( $this->mTrxLevel ) {
2856 # Disconnects cause rollback anyway, so ignore those errors
2857 $ignoreErrors = true;
2858 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2859 $this->mTrxLevel = 0;
2863 public function flushSnapshot( $fname = __METHOD__ ) {
2864 if ( $this->writesOrCallbacksPending() || $this->explicitTrxActive() ) {
2865 // This only flushes transactions to clear snapshots, not to write data
2866 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2867 throw new DBUnexpectedError(
2868 $this,
2869 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2873 $this->commit( $fname, self::FLUSHING_INTERNAL );
2876 public function explicitTrxActive() {
2877 return $this->mTrxLevel && ( $this->mTrxAtomicLevels || !$this->mTrxAutomatic );
2881 * Creates a new table with structure copied from existing table
2882 * Note that unlike most database abstraction functions, this function does not
2883 * automatically append database prefix, because it works at a lower
2884 * abstraction level.
2885 * The table names passed to this function shall not be quoted (this
2886 * function calls addIdentifierQuotes when needed).
2888 * @param string $oldName Name of table whose structure should be copied
2889 * @param string $newName Name of table to be created
2890 * @param bool $temporary Whether the new table should be temporary
2891 * @param string $fname Calling function name
2892 * @throws RuntimeException
2893 * @return bool True if operation was successful
2895 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2896 $fname = __METHOD__
2898 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2901 public function listTables( $prefix = null, $fname = __METHOD__ ) {
2902 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2905 public function listViews( $prefix = null, $fname = __METHOD__ ) {
2906 throw new RuntimeException( __METHOD__ . ' is not implemented in descendant class' );
2909 public function timestamp( $ts = 0 ) {
2910 $t = new ConvertibleTimestamp( $ts );
2911 // Let errors bubble up to avoid putting garbage in the DB
2912 return $t->getTimestamp( TS_MW );
2915 public function timestampOrNull( $ts = null ) {
2916 if ( is_null( $ts ) ) {
2917 return null;
2918 } else {
2919 return $this->timestamp( $ts );
2924 * Take the result from a query, and wrap it in a ResultWrapper if
2925 * necessary. Boolean values are passed through as is, to indicate success
2926 * of write queries or failure.
2928 * Once upon a time, Database::query() returned a bare MySQL result
2929 * resource, and it was necessary to call this function to convert it to
2930 * a wrapper. Nowadays, raw database objects are never exposed to external
2931 * callers, so this is unnecessary in external code.
2933 * @param bool|ResultWrapper|resource|object $result
2934 * @return bool|ResultWrapper
2936 protected function resultObject( $result ) {
2937 if ( !$result ) {
2938 return false;
2939 } elseif ( $result instanceof ResultWrapper ) {
2940 return $result;
2941 } elseif ( $result === true ) {
2942 // Successful write query
2943 return $result;
2944 } else {
2945 return new ResultWrapper( $this, $result );
2949 public function ping( &$rtt = null ) {
2950 // Avoid hitting the server if it was hit recently
2951 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing ) < self::PING_TTL ) {
2952 if ( !func_num_args() || $this->mRTTEstimate > 0 ) {
2953 $rtt = $this->mRTTEstimate;
2954 return true; // don't care about $rtt
2958 // This will reconnect if possible or return false if not
2959 $this->clearFlag( self::DBO_TRX, self::REMEMBER_PRIOR );
2960 $ok = ( $this->query( self::PING_QUERY, __METHOD__, true ) !== false );
2961 $this->restoreFlags( self::RESTORE_PRIOR );
2963 if ( $ok ) {
2964 $rtt = $this->mRTTEstimate;
2967 return $ok;
2971 * @return bool
2973 protected function reconnect() {
2974 $this->closeConnection();
2975 $this->mOpened = false;
2976 $this->mConn = false;
2977 try {
2978 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
2979 $this->lastPing = microtime( true );
2980 $ok = true;
2981 } catch ( DBConnectionError $e ) {
2982 $ok = false;
2985 return $ok;
2988 public function getSessionLagStatus() {
2989 return $this->getTransactionLagStatus() ?: $this->getApproximateLagStatus();
2993 * Get the replica DB lag when the current transaction started
2995 * This is useful when transactions might use snapshot isolation
2996 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2997 * is this lag plus transaction duration. If they don't, it is still
2998 * safe to be pessimistic. This returns null if there is no transaction.
3000 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3001 * @since 1.27
3003 protected function getTransactionLagStatus() {
3004 return $this->mTrxLevel
3005 ? [ 'lag' => $this->mTrxReplicaLag, 'since' => $this->trxTimestamp() ]
3006 : null;
3010 * Get a replica DB lag estimate for this server
3012 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3013 * @since 1.27
3015 protected function getApproximateLagStatus() {
3016 return [
3017 'lag' => $this->getLBInfo( 'replica' ) ? $this->getLag() : 0,
3018 'since' => microtime( true )
3023 * Merge the result of getSessionLagStatus() for several DBs
3024 * using the most pessimistic values to estimate the lag of
3025 * any data derived from them in combination
3027 * This is information is useful for caching modules
3029 * @see WANObjectCache::set()
3030 * @see WANObjectCache::getWithSetCallback()
3032 * @param IDatabase $db1
3033 * @param IDatabase ...
3034 * @return array Map of values:
3035 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3036 * - since: oldest UNIX timestamp of any of the DB lag estimates
3037 * - pending: whether any of the DBs have uncommitted changes
3038 * @since 1.27
3040 public static function getCacheSetOptions( IDatabase $db1 ) {
3041 $opts = [ 'lag' => 0, 'since' => INF, 'pending' => false ];
3042 foreach ( func_get_args() as $db ) {
3043 /** @var IDatabase $db */
3044 $dbOpts = $db->getSessionLagStatus();
3045 $dbOpts['pending'] = $db->writesPending();
3046 $opts = self::mergeCacheSetOptions( $opts, $dbOpts );
3049 return $opts;
3053 * @param array $base Map in the format of getCacheSetOptions() results
3054 * @param array $other Map in the format of getCacheSetOptions() results
3055 * @return array Pessimistically merged result of $base/$other in the format of $base
3056 * @since 1.28
3058 public static function mergeCacheSetOptions( array $base, array $other ) {
3059 if ( $other['lag'] === false ) {
3060 $base['lag'] = false;
3061 } elseif ( $base['lag'] !== false ) {
3062 $base['lag'] = max( $base['lag'], $other['lag'] );
3064 $base['since'] = min( $base['since'], $other['since'] );
3065 $base['pending'] = $base['pending'] ?: $other['pending'];
3067 return $base;
3070 public function getLag() {
3071 return 0;
3074 public function maxListLen() {
3075 return 0;
3078 public function encodeBlob( $b ) {
3079 return $b;
3082 public function decodeBlob( $b ) {
3083 if ( $b instanceof Blob ) {
3084 $b = $b->fetch();
3086 return $b;
3089 public function setSessionOptions( array $options ) {
3092 public function sourceFile(
3093 $filename,
3094 callable $lineCallback = null,
3095 callable $resultCallback = null,
3096 $fname = false,
3097 callable $inputCallback = null
3099 MediaWiki\suppressWarnings();
3100 $fp = fopen( $filename, 'r' );
3101 MediaWiki\restoreWarnings();
3103 if ( false === $fp ) {
3104 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3107 if ( !$fname ) {
3108 $fname = __METHOD__ . "( $filename )";
3111 try {
3112 $error = $this->sourceStream(
3113 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3114 } catch ( Exception $e ) {
3115 fclose( $fp );
3116 throw $e;
3119 fclose( $fp );
3121 return $error;
3124 public function setSchemaVars( $vars ) {
3125 $this->mSchemaVars = $vars;
3128 public function sourceStream(
3129 $fp,
3130 callable $lineCallback = null,
3131 callable $resultCallback = null,
3132 $fname = __METHOD__,
3133 callable $inputCallback = null
3135 $cmd = '';
3137 while ( !feof( $fp ) ) {
3138 if ( $lineCallback ) {
3139 call_user_func( $lineCallback );
3142 $line = trim( fgets( $fp ) );
3144 if ( $line == '' ) {
3145 continue;
3148 if ( '-' == $line[0] && '-' == $line[1] ) {
3149 continue;
3152 if ( $cmd != '' ) {
3153 $cmd .= ' ';
3156 $done = $this->streamStatementEnd( $cmd, $line );
3158 $cmd .= "$line\n";
3160 if ( $done || feof( $fp ) ) {
3161 $cmd = $this->replaceVars( $cmd );
3163 if ( !$inputCallback || call_user_func( $inputCallback, $cmd ) ) {
3164 $res = $this->query( $cmd, $fname );
3166 if ( $resultCallback ) {
3167 call_user_func( $resultCallback, $res, $this );
3170 if ( false === $res ) {
3171 $err = $this->lastError();
3173 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3176 $cmd = '';
3180 return true;
3184 * Called by sourceStream() to check if we've reached a statement end
3186 * @param string &$sql SQL assembled so far
3187 * @param string &$newLine New line about to be added to $sql
3188 * @return bool Whether $newLine contains end of the statement
3190 public function streamStatementEnd( &$sql, &$newLine ) {
3191 if ( $this->delimiter ) {
3192 $prev = $newLine;
3193 $newLine = preg_replace(
3194 '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
3195 if ( $newLine != $prev ) {
3196 return true;
3200 return false;
3204 * Database independent variable replacement. Replaces a set of variables
3205 * in an SQL statement with their contents as given by $this->getSchemaVars().
3207 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3209 * - '{$var}' should be used for text and is passed through the database's
3210 * addQuotes method.
3211 * - `{$var}` should be used for identifiers (e.g. table and database names).
3212 * It is passed through the database's addIdentifierQuotes method which
3213 * can be overridden if the database uses something other than backticks.
3214 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3215 * database's tableName method.
3216 * - / *i* / passes the name that follows through the database's indexName method.
3217 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3218 * its use should be avoided. In 1.24 and older, string encoding was applied.
3220 * @param string $ins SQL statement to replace variables in
3221 * @return string The new SQL statement with variables replaced
3223 protected function replaceVars( $ins ) {
3224 $vars = $this->getSchemaVars();
3225 return preg_replace_callback(
3227 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3228 \'\{\$ (\w+) }\' | # 3. addQuotes
3229 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3230 /\*\$ (\w+) \*/ # 5. leave unencoded
3231 !x',
3232 function ( $m ) use ( $vars ) {
3233 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3234 // check for both nonexistent keys *and* the empty string.
3235 if ( isset( $m[1] ) && $m[1] !== '' ) {
3236 if ( $m[1] === 'i' ) {
3237 return $this->indexName( $m[2] );
3238 } else {
3239 return $this->tableName( $m[2] );
3241 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3242 return $this->addQuotes( $vars[$m[3]] );
3243 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3244 return $this->addIdentifierQuotes( $vars[$m[4]] );
3245 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3246 return $vars[$m[5]];
3247 } else {
3248 return $m[0];
3251 $ins
3256 * Get schema variables. If none have been set via setSchemaVars(), then
3257 * use some defaults from the current object.
3259 * @return array
3261 protected function getSchemaVars() {
3262 if ( $this->mSchemaVars ) {
3263 return $this->mSchemaVars;
3264 } else {
3265 return $this->getDefaultSchemaVars();
3270 * Get schema variables to use if none have been set via setSchemaVars().
3272 * Override this in derived classes to provide variables for tables.sql
3273 * and SQL patch files.
3275 * @return array
3277 protected function getDefaultSchemaVars() {
3278 return [];
3281 public function lockIsFree( $lockName, $method ) {
3282 return true;
3285 public function lock( $lockName, $method, $timeout = 5 ) {
3286 $this->mNamedLocksHeld[$lockName] = 1;
3288 return true;
3291 public function unlock( $lockName, $method ) {
3292 unset( $this->mNamedLocksHeld[$lockName] );
3294 return true;
3297 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3298 if ( $this->writesOrCallbacksPending() ) {
3299 // This only flushes transactions to clear snapshots, not to write data
3300 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3301 throw new DBUnexpectedError(
3302 $this,
3303 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3307 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3308 return null;
3311 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3312 if ( $this->trxLevel() ) {
3313 // There is a good chance an exception was thrown, causing any early return
3314 // from the caller. Let any error handler get a chance to issue rollback().
3315 // If there isn't one, let the error bubble up and trigger server-side rollback.
3316 $this->onTransactionResolution(
3317 function () use ( $lockKey, $fname ) {
3318 $this->unlock( $lockKey, $fname );
3320 $fname
3322 } else {
3323 $this->unlock( $lockKey, $fname );
3325 } );
3327 $this->commit( $fname, self::FLUSHING_INTERNAL );
3329 return $unlocker;
3332 public function namedLocksEnqueue() {
3333 return false;
3337 * Lock specific tables
3339 * @param array $read Array of tables to lock for read access
3340 * @param array $write Array of tables to lock for write access
3341 * @param string $method Name of caller
3342 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3343 * @return bool
3345 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3346 return true;
3350 * Unlock specific tables
3352 * @param string $method The caller
3353 * @return bool
3355 public function unlockTables( $method ) {
3356 return true;
3360 * Delete a table
3361 * @param string $tableName
3362 * @param string $fName
3363 * @return bool|ResultWrapper
3364 * @since 1.18
3366 public function dropTable( $tableName, $fName = __METHOD__ ) {
3367 if ( !$this->tableExists( $tableName, $fName ) ) {
3368 return false;
3370 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3372 return $this->query( $sql, $fName );
3375 public function getInfinity() {
3376 return 'infinity';
3379 public function encodeExpiry( $expiry ) {
3380 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
3381 ? $this->getInfinity()
3382 : $this->timestamp( $expiry );
3385 public function decodeExpiry( $expiry, $format = TS_MW ) {
3386 if ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() ) {
3387 return 'infinity';
3390 return ConvertibleTimestamp::convert( $format, $expiry );
3393 public function setBigSelects( $value = true ) {
3394 // no-op
3397 public function isReadOnly() {
3398 return ( $this->getReadOnlyReason() !== false );
3402 * @return string|bool Reason this DB is read-only or false if it is not
3404 protected function getReadOnlyReason() {
3405 $reason = $this->getLBInfo( 'readOnlyReason' );
3407 return is_string( $reason ) ? $reason : false;
3410 public function setTableAliases( array $aliases ) {
3411 $this->tableAliases = $aliases;
3414 public function declareUsageSectionStart( $id ) {
3415 $this->usageSectionInfo[$id] = [
3416 'readQueries' => 0,
3417 'writeQueries' => 0,
3418 'cacheSetOptions' => null
3422 public function declareUsageSectionEnd( $id ) {
3423 if ( !isset( $this->usageSectionInfo[$id] ) ) {
3424 throw new InvalidArgumentException( "No section with ID '$id'" );
3427 $info = $this->usageSectionInfo[$id];
3428 unset( $this->usageSectionInfo[$id] );
3430 return $info;
3434 * @return bool Whether a DB user is required to access the DB
3435 * @since 1.28
3437 protected function requiresDatabaseUser() {
3438 return true;
3442 * Get the underlying binding handle, mConn
3444 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3445 * This catches broken callers than catch and ignore disconnection exceptions.
3446 * Unlike checking isOpen(), this is safe to call inside of open().
3448 * @return resource|object
3449 * @throws DBUnexpectedError
3450 * @since 1.26
3452 protected function getBindingHandle() {
3453 if ( !$this->mConn ) {
3454 throw new DBUnexpectedError(
3455 $this,
3456 'DB connection was already closed or the connection dropped.'
3460 return $this->mConn;
3464 * @since 1.19
3465 * @return string
3467 public function __toString() {
3468 return (string)$this->mConn;
3472 * Make sure that copies do not share the same client binding handle
3473 * @throws DBConnectionError
3475 public function __clone() {
3476 $this->connLogger->warning(
3477 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3478 ( new RuntimeException() )->getTraceAsString()
3481 if ( $this->isOpen() ) {
3482 // Open a new connection resource without messing with the old one
3483 $this->mOpened = false;
3484 $this->mConn = false;
3485 $this->mTrxEndCallbacks = []; // don't copy
3486 $this->handleSessionLoss(); // no trx or locks anymore
3487 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
3488 $this->lastPing = microtime( true );
3493 * Called by serialize. Throw an exception when DB connection is serialized.
3494 * This causes problems on some database engines because the connection is
3495 * not restored on unserialize.
3497 public function __sleep() {
3498 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3499 'the connection is not restored on wakeup.' );
3503 * Run a few simple sanity checks and close dangling connections
3505 public function __destruct() {
3506 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
3507 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3510 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3511 if ( $danglingWriters ) {
3512 $fnames = implode( ', ', $danglingWriters );
3513 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3516 if ( $this->mConn ) {
3517 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3518 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3519 \MediaWiki\suppressWarnings();
3520 $this->closeConnection();
3521 \MediaWiki\restoreWarnings();
3522 $this->mConn = false;
3523 $this->mOpened = false;
3528 class_alias( 'Database', 'DatabaseBase' );