3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
43 * Relational database abstraction object
48 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
49 /** Number of times to re-try an operation in case of deadlock */
50 const DEADLOCK_TRIES
= 4;
51 /** Minimum time to wait before retry, in microseconds */
52 const DEADLOCK_DELAY_MIN
= 500000;
53 /** Maximum time to wait before retry */
54 const DEADLOCK_DELAY_MAX
= 1500000;
56 /** How long before it is worth doing a dummy query to test the connection */
58 const PING_QUERY
= 'SELECT 1 AS ping';
60 const TINY_WRITE_SEC
= 0.010;
61 const SLOW_WRITE_SEC
= 0.500;
62 const SMALL_WRITE_ROWS
= 100;
64 /** @var string Whether lock granularity is on the level of the entire database */
65 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
67 /** @var int New Database instance will not be connected yet when returned */
68 const NEW_UNCONNECTED
= 0;
69 /** @var int New Database instance will already be connected when returned */
70 const NEW_CONNECTED
= 1;
72 /** @var string SQL query */
73 protected $lastQuery = '';
74 /** @var float|bool UNIX timestamp of last write query */
75 protected $lastWriteTime = false;
76 /** @var string|bool */
77 protected $phpError = false;
78 /** @var string Server that this instance is currently connected to */
80 /** @var string User that this instance is currently connected under the name of */
82 /** @var string Password used to establish the current connection */
84 /** @var string Database that this instance is currently connected to */
86 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
87 protected $tableAliases = [];
88 /** @var string[] Map of (index alias => index) */
89 protected $indexAliases = [];
90 /** @var bool Whether this PHP instance is for a CLI script */
92 /** @var string Agent name for query profiling */
94 /** @var array Parameters used by initConnection() to establish a connection */
95 protected $connectionParams = [];
96 /** @var BagOStuff APC cache */
98 /** @var LoggerInterface */
99 protected $connLogger;
100 /** @var LoggerInterface */
101 protected $queryLogger;
102 /** @var callback Error logging callback */
103 protected $errorLogger;
105 /** @var resource|null Database connection */
106 protected $conn = null;
108 protected $opened = false;
110 /** @var array[] List of (callable, method name) */
111 protected $trxIdleCallbacks = [];
112 /** @var array[] List of (callable, method name) */
113 protected $trxPreCommitCallbacks = [];
114 /** @var array[] List of (callable, method name) */
115 protected $trxEndCallbacks = [];
116 /** @var callable[] Map of (name => callable) */
117 protected $trxRecurringCallbacks = [];
118 /** @var bool Whether to suppress triggering of transaction end callbacks */
119 protected $trxEndCallbacksSuppressed = false;
122 protected $tablePrefix = '';
124 protected $schema = '';
128 protected $lbInfo = [];
129 /** @var array|bool */
130 protected $schemaVars = false;
132 protected $sessionVars = [];
133 /** @var array|null */
134 protected $preparedArgs;
135 /** @var string|bool|null Stashed value of html_errors INI setting */
136 protected $htmlErrors;
138 protected $delimiter = ';';
139 /** @var DatabaseDomain */
140 protected $currentDomain;
141 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
142 protected $affectedRowCount;
145 * @var int Transaction status
147 protected $trxStatus = self
::STATUS_TRX_NONE
;
149 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
151 protected $trxStatusCause;
153 * Either 1 if a transaction is active or 0 otherwise.
154 * The other Trx fields may not be meaningfull if this is 0.
158 protected $trxLevel = 0;
160 * Either a short hexidecimal string if a transaction is active or ""
163 * @see Database::trxLevel
165 protected $trxShortId = '';
167 * The UNIX time that the transaction started. Callers can assume that if
168 * snapshot isolation is used, then the data is *at least* up to date to that
169 * point (possibly more up-to-date since the first SELECT defines the snapshot).
172 * @see Database::trxLevel
174 private $trxTimestamp = null;
175 /** @var float Lag estimate at the time of BEGIN */
176 private $trxReplicaLag = null;
178 * Remembers the function name given for starting the most recent transaction via begin().
179 * Used to provide additional context for error reporting.
182 * @see Database::trxLevel
184 private $trxFname = null;
186 * Record if possible write queries were done in the last transaction started
189 * @see Database::trxLevel
191 private $trxDoneWrites = false;
193 * Record if the current transaction was started implicitly due to DBO_TRX being set.
196 * @see Database::trxLevel
198 private $trxAutomatic = false;
200 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
204 private $trxAtomicCounter = 0;
206 * Array of levels of atomicity within transactions
210 private $trxAtomicLevels = [];
212 * Record if the current transaction was started implicitly by Database::startAtomic
216 private $trxAutomaticAtomic = false;
218 * Track the write query callers of the current transaction
222 private $trxWriteCallers = [];
224 * @var float Seconds spent in write queries for the current transaction
226 private $trxWriteDuration = 0.0;
228 * @var int Number of write queries for the current transaction
230 private $trxWriteQueryCount = 0;
232 * @var int Number of rows affected by write queries for the current transaction
234 private $trxWriteAffectedRows = 0;
236 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
238 private $trxWriteAdjDuration = 0.0;
240 * @var int Number of write queries counted in trxWriteAdjDuration
242 private $trxWriteAdjQueryCount = 0;
244 * @var float RTT time estimate
246 private $rttEstimate = 0.0;
248 /** @var array Map of (name => 1) for locks obtained via lock() */
249 private $namedLocksHeld = [];
250 /** @var array Map of (table name => 1) for TEMPORARY tables */
251 protected $sessionTempTables = [];
253 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
254 private $lazyMasterHandle;
256 /** @var float UNIX timestamp */
257 protected $lastPing = 0.0;
259 /** @var int[] Prior flags member variable values */
260 private $priorFlags = [];
262 /** @var object|string Class name or object With profileIn/profileOut methods */
264 /** @var TransactionProfiler */
265 protected $trxProfiler;
268 protected $nonNativeInsertSelectBatchSize = 10000;
270 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
271 const STATUS_TRX_ERROR
= 1;
272 /** @var int Transaction is active and in a normal state */
273 const STATUS_TRX_OK
= 2;
274 /** @var int No transaction is active */
275 const STATUS_TRX_NONE
= 3;
278 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
279 * @param array $params Parameters passed from Database::factory()
281 protected function __construct( array $params ) {
282 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
283 $this->connectionParams
[$name] = $params[$name];
286 $this->schema
= $params['schema'];
287 $this->tablePrefix
= $params['tablePrefix'];
289 $this->cliMode
= $params['cliMode'];
290 // Agent name is added to SQL queries in a comment, so make sure it can't break out
291 $this->agent
= str_replace( '/', '-', $params['agent'] );
293 $this->flags
= $params['flags'];
294 if ( $this->flags
& self
::DBO_DEFAULT
) {
295 if ( $this->cliMode
) {
296 $this->flags
&= ~self
::DBO_TRX
;
298 $this->flags |
= self
::DBO_TRX
;
301 // Disregard deprecated DBO_IGNORE flag (T189999)
302 $this->flags
&= ~self
::DBO_IGNORE
;
304 $this->sessionVars
= $params['variables'];
306 $this->srvCache
= isset( $params['srvCache'] )
307 ?
$params['srvCache']
308 : new HashBagOStuff();
310 $this->profiler
= $params['profiler'];
311 $this->trxProfiler
= $params['trxProfiler'];
312 $this->connLogger
= $params['connLogger'];
313 $this->queryLogger
= $params['queryLogger'];
314 $this->errorLogger
= $params['errorLogger'];
316 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
317 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
320 // Set initial dummy domain until open() sets the final DB/prefix
321 $this->currentDomain
= DatabaseDomain
::newUnspecified();
325 * Initialize the connection to the database over the wire (or to local files)
327 * @throws LogicException
328 * @throws InvalidArgumentException
329 * @throws DBConnectionError
332 final public function initConnection() {
333 if ( $this->isOpen() ) {
334 throw new LogicException( __METHOD__
. ': already connected.' );
336 // Establish the connection
337 $this->doInitConnection();
338 // Set the domain object after open() sets the relevant fields
339 if ( $this->dbName
!= '' ) {
340 // Domains with server scope but a table prefix are not used by IDatabase classes
341 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
346 * Actually connect to the database over the wire (or to local files)
348 * @throws InvalidArgumentException
349 * @throws DBConnectionError
352 protected function doInitConnection() {
353 if ( strlen( $this->connectionParams
['user'] ) ) {
355 $this->connectionParams
['host'],
356 $this->connectionParams
['user'],
357 $this->connectionParams
['password'],
358 $this->connectionParams
['dbname']
361 throw new InvalidArgumentException( "No database user provided." );
366 * Construct a Database subclass instance given a database type and parameters
368 * This also connects to the database immediately upon object construction
370 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
371 * @param array $p Parameter map with keys:
372 * - host : The hostname of the DB server
373 * - user : The name of the database user the client operates under
374 * - password : The password for the database user
375 * - dbname : The name of the database to use where queries do not specify one.
376 * The database must exist or an error might be thrown. Setting this to the empty string
377 * will avoid any such errors and make the handle have no implicit database scope. This is
378 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
379 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
380 * in which user names and such are defined, e.g. users are database-specific in Postgres.
381 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
382 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
383 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
384 * recognized in queries. This can be used in place of schemas for handle site farms.
385 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
386 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
387 * flag in place UNLESS this this database simply acts as a key/value store.
388 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
389 * 'mysqli' driver; the old one 'mysql' has been removed.
390 * - variables: Optional map of session variables to set after connecting. This can be
391 * used to adjust lock timeouts or encoding modes and the like.
392 * - connLogger: Optional PSR-3 logger interface instance.
393 * - queryLogger: Optional PSR-3 logger interface instance.
394 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
395 * These will be called in query(), using a simplified version of the SQL that also
396 * includes the agent as a SQL comment.
397 * - trxProfiler: Optional TransactionProfiler instance.
398 * - errorLogger: Optional callback that takes an Exception and logs it.
399 * - cliMode: Whether to consider the execution context that of a CLI script.
400 * - agent: Optional name used to identify the end-user in query profiling/logging.
401 * - srvCache: Optional BagOStuff instance to an APC-style cache.
402 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
403 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
404 * @return Database|null If the database driver or extension cannot be found
405 * @throws InvalidArgumentException If the database driver or extension cannot be found
408 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
409 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
411 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
412 // Resolve some defaults for b/c
413 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
414 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
415 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
416 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
417 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
418 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
419 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
420 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
421 $p['cliMode'] = isset( $p['cliMode'] )
423 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
424 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
425 if ( !isset( $p['connLogger'] ) ) {
426 $p['connLogger'] = new NullLogger();
428 if ( !isset( $p['queryLogger'] ) ) {
429 $p['queryLogger'] = new NullLogger();
431 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
432 if ( !isset( $p['trxProfiler'] ) ) {
433 $p['trxProfiler'] = new TransactionProfiler();
435 if ( !isset( $p['errorLogger'] ) ) {
436 $p['errorLogger'] = function ( Exception
$e ) {
437 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
441 /** @var Database $conn */
442 $conn = new $class( $p );
443 if ( $connect == self
::NEW_CONNECTED
) {
444 $conn->initConnection();
454 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
455 * @param string|null $driver Optional name of a specific DB client driver
456 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
457 * @throws InvalidArgumentException
460 final public static function attributesFromType( $dbType, $driver = null ) {
461 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
463 $class = self
::getClass( $dbType, $driver );
465 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
469 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
470 * @param string|null $driver Optional name of a specific DB client driver
471 * @return string Database subclass name to use
472 * @throws InvalidArgumentException
474 private static function getClass( $dbType, $driver = null ) {
475 // For database types with built-in support, the below maps type to IDatabase
476 // implementations. For types with multipe driver implementations (PHP extensions),
477 // an array can be used, keyed by extension name. In case of an array, the
478 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
479 // we auto-detect the first available driver. For types without built-in support,
480 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
481 static $builtinTypes = [
482 'mssql' => DatabaseMssql
::class,
483 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
484 'sqlite' => DatabaseSqlite
::class,
485 'postgres' => DatabasePostgres
::class,
488 $dbType = strtolower( $dbType );
491 if ( isset( $builtinTypes[$dbType] ) ) {
492 $possibleDrivers = $builtinTypes[$dbType];
493 if ( is_string( $possibleDrivers ) ) {
494 $class = $possibleDrivers;
496 if ( (string)$driver !== '' ) {
497 if ( !isset( $possibleDrivers[$driver] ) ) {
498 throw new InvalidArgumentException( __METHOD__
.
499 " type '$dbType' does not support driver '{$driver}'" );
501 $class = $possibleDrivers[$driver];
504 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
505 if ( extension_loaded( $posDriver ) ) {
506 $class = $possibleClass;
513 $class = 'Database' . ucfirst( $dbType );
516 if ( $class === false ) {
517 throw new InvalidArgumentException( __METHOD__
.
518 " no viable database extension found for type '$dbType'" );
525 * @return array Map of (Database::ATTRIBUTE_* constant => value
528 protected static function getAttributes() {
533 * Set the PSR-3 logger interface to use for query logging. (The logger
534 * interfaces for connection logging and error logging can be set with the
537 * @param LoggerInterface $logger
539 public function setLogger( LoggerInterface
$logger ) {
540 $this->queryLogger
= $logger;
543 public function getServerInfo() {
544 return $this->getServerVersion();
547 public function bufferResults( $buffer = null ) {
548 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
549 if ( $buffer !== null ) {
551 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
552 : $this->setFlag( self
::DBO_NOBUFFER
);
558 public function trxLevel() {
559 return $this->trxLevel
;
562 public function trxTimestamp() {
563 return $this->trxLevel ?
$this->trxTimestamp
: null;
567 * @return int One of the STATUS_TRX_* class constants
570 public function trxStatus() {
571 return $this->trxStatus
;
574 public function tablePrefix( $prefix = null ) {
575 $old = $this->tablePrefix
;
576 if ( $prefix !== null ) {
577 $this->tablePrefix
= $prefix;
578 $this->currentDomain
= ( $this->dbName
!= '' )
579 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
580 : DatabaseDomain
::newUnspecified();
586 public function dbSchema( $schema = null ) {
587 $old = $this->schema
;
588 if ( $schema !== null ) {
589 $this->schema
= $schema;
595 public function getLBInfo( $name = null ) {
596 if ( is_null( $name ) ) {
597 return $this->lbInfo
;
599 if ( array_key_exists( $name, $this->lbInfo
) ) {
600 return $this->lbInfo
[$name];
607 public function setLBInfo( $name, $value = null ) {
608 if ( is_null( $value ) ) {
609 $this->lbInfo
= $name;
611 $this->lbInfo
[$name] = $value;
615 public function setLazyMasterHandle( IDatabase
$conn ) {
616 $this->lazyMasterHandle
= $conn;
620 * @return IDatabase|null
621 * @see setLazyMasterHandle()
624 protected function getLazyMasterHandle() {
625 return $this->lazyMasterHandle
;
628 public function implicitGroupby() {
632 public function implicitOrderby() {
636 public function lastQuery() {
637 return $this->lastQuery
;
640 public function doneWrites() {
641 return (bool)$this->lastWriteTime
;
644 public function lastDoneWrites() {
645 return $this->lastWriteTime ?
: false;
648 public function writesPending() {
649 return $this->trxLevel
&& $this->trxDoneWrites
;
652 public function writesOrCallbacksPending() {
653 return $this->trxLevel
&& (
654 $this->trxDoneWrites ||
655 $this->trxIdleCallbacks ||
656 $this->trxPreCommitCallbacks ||
657 $this->trxEndCallbacks
662 * @return string|null
664 final protected function getTransactionRoundId() {
665 // If transaction round participation is enabled, see if one is active
666 if ( $this->getFlag( self
::DBO_TRX
) ) {
667 $id = $this->getLBInfo( 'trxRoundId' );
669 return is_string( $id ) ?
$id : null;
675 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
676 if ( !$this->trxLevel
) {
678 } elseif ( !$this->trxDoneWrites
) {
683 case self
::ESTIMATE_DB_APPLY
:
685 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
686 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
687 // For omitted queries, make them count as something at least
688 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
689 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
692 default: // everything
693 return $this->trxWriteDuration
;
697 public function pendingWriteCallers() {
698 return $this->trxLevel ?
$this->trxWriteCallers
: [];
701 public function pendingWriteRowsAffected() {
702 return $this->trxWriteAffectedRows
;
706 * Get the list of method names that have pending write queries or callbacks
707 * for this transaction
711 protected function pendingWriteAndCallbackCallers() {
712 if ( !$this->trxLevel
) {
716 $fnames = $this->trxWriteCallers
;
718 $this->trxIdleCallbacks
,
719 $this->trxPreCommitCallbacks
,
720 $this->trxEndCallbacks
722 foreach ( $callbacks as $callback ) {
723 $fnames[] = $callback[1];
733 private function flatAtomicSectionList() {
734 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
735 return $accum === null ?
$v[0] : "$accum, " . $v[0];
739 public function isOpen() {
740 return $this->opened
;
743 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
744 if ( ( $flag & self
::DBO_IGNORE
) ) {
745 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
748 if ( $remember === self
::REMEMBER_PRIOR
) {
749 array_push( $this->priorFlags
, $this->flags
);
751 $this->flags |
= $flag;
754 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
755 if ( ( $flag & self
::DBO_IGNORE
) ) {
756 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
759 if ( $remember === self
::REMEMBER_PRIOR
) {
760 array_push( $this->priorFlags
, $this->flags
);
762 $this->flags
&= ~
$flag;
765 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
766 if ( !$this->priorFlags
) {
770 if ( $state === self
::RESTORE_INITIAL
) {
771 $this->flags
= reset( $this->priorFlags
);
772 $this->priorFlags
= [];
774 $this->flags
= array_pop( $this->priorFlags
);
778 public function getFlag( $flag ) {
779 return !!( $this->flags
& $flag );
783 * @param string $name Class field name
785 * @deprecated Since 1.28
787 public function getProperty( $name ) {
791 public function getDomainID() {
792 return $this->currentDomain
->getId();
795 final public function getWikiID() {
796 return $this->getDomainID();
800 * Get information about an index into an object
801 * @param string $table Table name
802 * @param string $index Index name
803 * @param string $fname Calling function name
804 * @return mixed Database-specific index description class or false if the index does not exist
806 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
809 * Wrapper for addslashes()
811 * @param string $s String to be slashed.
812 * @return string Slashed string.
814 abstract function strencode( $s );
817 * Set a custom error handler for logging errors during database connection
819 protected function installErrorHandler() {
820 $this->phpError
= false;
821 $this->htmlErrors
= ini_set( 'html_errors', '0' );
822 set_error_handler( [ $this, 'connectionErrorLogger' ] );
826 * Restore the previous error handler and return the last PHP error for this DB
828 * @return bool|string
830 protected function restoreErrorHandler() {
831 restore_error_handler();
832 if ( $this->htmlErrors
!== false ) {
833 ini_set( 'html_errors', $this->htmlErrors
);
836 return $this->getLastPHPError();
840 * @return string|bool Last PHP error for this DB (typically connection errors)
842 protected function getLastPHPError() {
843 if ( $this->phpError
) {
844 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
845 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
854 * Error handler for logging errors during database connection
855 * This method should not be used outside of Database classes
858 * @param string $errstr
860 public function connectionErrorLogger( $errno, $errstr ) {
861 $this->phpError
= $errstr;
865 * Create a log context to pass to PSR-3 logger functions.
867 * @param array $extras Additional data to add to context
870 protected function getLogContext( array $extras = [] ) {
873 'db_server' => $this->server
,
874 'db_name' => $this->dbName
,
875 'db_user' => $this->user
,
881 final public function close() {
882 $exception = null; // error to throw after disconnecting
885 // Resolve any dangling transaction first
886 if ( $this->trxLevel
) {
887 // Meaningful transactions should ideally have been resolved by now
888 if ( $this->writesOrCallbacksPending() ) {
889 $this->queryLogger
->warning(
890 __METHOD__
. ": writes or callbacks still pending.",
891 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
893 // Cannot let incomplete atomic sections be committed
894 if ( $this->trxAtomicLevels
) {
895 $levels = $this->flatAtomicSectionList();
896 $exception = new DBUnexpectedError(
898 __METHOD__
. ": atomic sections $levels are still open."
900 // Check if it is possible to properly commit and trigger callbacks
901 } elseif ( $this->trxEndCallbacksSuppressed
) {
902 $exception = new DBUnexpectedError(
904 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
908 // Commit or rollback the changes and run any callbacks as needed
909 if ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& !$exception ) {
910 $this->commit( __METHOD__
, self
::TRANSACTION_INTERNAL
);
912 $this->rollback( __METHOD__
, self
::TRANSACTION_INTERNAL
);
915 // Close the actual connection in the binding handle
916 $closed = $this->closeConnection();
919 $closed = true; // already closed; nothing to do
922 $this->opened
= false;
924 // Throw any unexpected errors after having disconnected
925 if ( $exception instanceof Exception
) {
929 // Sanity check that no callbacks are dangling
931 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
933 throw new RuntimeException(
934 "Transaction callbacks are still pending:\n" .
935 implode( ', ', $this->pendingWriteAndCallbackCallers() )
943 * Make sure isOpen() returns true as a sanity check
945 * @throws DBUnexpectedError
947 protected function assertOpen() {
948 if ( !$this->isOpen() ) {
949 throw new DBUnexpectedError( $this, "DB connection was already closed." );
954 * Closes underlying database connection
956 * @return bool Whether connection was closed successfully
958 abstract protected function closeConnection();
961 * @param string $error Fallback error message, used if none is given by DB
962 * @throws DBConnectionError
964 public function reportConnectionError( $error = 'Unknown error' ) {
965 $myError = $this->lastError();
971 throw new DBConnectionError( $this, $error );
975 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
977 * This might return things, such as mysqli_result, that do not formally implement
978 * IResultWrapper, but nonetheless implement all of its methods correctly
980 * @param string $sql SQL query.
981 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
983 abstract protected function doQuery( $sql );
986 * Determine whether a query writes to the DB.
987 * Should return true if unsure.
992 protected function isWriteQuery( $sql ) {
994 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
999 * @return string|null
1001 protected function getQueryVerb( $sql ) {
1002 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1006 * Determine whether a SQL statement is sensitive to isolation level.
1007 * A SQL statement is considered transactable if its result could vary
1008 * depending on the transaction isolation level. Operational commands
1009 * such as 'SET' and 'SHOW' are not considered to be transactable.
1011 * @param string $sql
1014 protected function isTransactableQuery( $sql ) {
1016 $this->getQueryVerb( $sql ),
1017 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1023 * @param string $sql A SQL query
1024 * @return bool Whether $sql is SQL for TEMPORARY table operation
1026 protected function registerTempTableOperation( $sql ) {
1028 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1032 $this->sessionTempTables
[$matches[1]] = 1;
1035 } elseif ( preg_match(
1036 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1040 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1041 unset( $this->sessionTempTables
[$matches[1]] );
1044 } elseif ( preg_match(
1045 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1049 return isset( $this->sessionTempTables
[$matches[1]] );
1050 } elseif ( preg_match(
1051 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1055 return isset( $this->sessionTempTables
[$matches[1]] );
1061 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1062 $this->assertTransactionStatus( $sql, $fname );
1064 # Avoid fatals if close() was called
1065 $this->assertOpen();
1067 $priorWritesPending = $this->writesOrCallbacksPending();
1068 $this->lastQuery
= $sql;
1070 $isWrite = $this->isWriteQuery( $sql );
1072 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1074 $isNonTempWrite = false;
1078 if ( $this->getLBInfo( 'replica' ) === true ) {
1081 'Write operations are not allowed on replica database connections.'
1084 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1085 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1086 $reason = $this->getReadOnlyReason();
1087 if ( $reason !== false ) {
1088 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1090 # Set a flag indicating that writes have been done
1091 $this->lastWriteTime
= microtime( true );
1094 # Add trace comment to the begin of the sql string, right after the operator.
1095 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1096 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1098 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1099 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1100 && $this->isTransactableQuery( $sql )
1102 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1103 $this->trxAutomatic
= true;
1106 # Keep track of whether the transaction has write queries pending
1107 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1108 $this->trxDoneWrites
= true;
1109 $this->trxProfiler
->transactionWritingIn(
1110 $this->server
, $this->dbName
, $this->trxShortId
);
1113 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1114 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1117 # Send the query to the server and fetch any corresponding errors
1118 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1119 $lastError = $this->lastError();
1120 $lastErrno = $this->lastErrno();
1122 # Try reconnecting if the connection was lost
1123 if ( $ret === false && $this->wasConnectionLoss() ) {
1124 # Check if any meaningful session state was lost
1125 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1126 # Update session state tracking and try to restore the connection
1127 $reconnected = $this->replaceLostConnection( __METHOD__
);
1128 # Silently resend the query to the server if it is safe and possible
1129 if ( $reconnected && $recoverable ) {
1130 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1131 $lastError = $this->lastError();
1132 $lastErrno = $this->lastErrno();
1134 if ( $ret === false && $this->wasConnectionLoss() ) {
1135 # Query probably causes disconnects; reconnect and do not re-run it
1136 $this->replaceLostConnection( __METHOD__
);
1141 if ( $ret === false ) {
1142 if ( $this->trxLevel
&& !$this->wasKnownStatementRollbackError() ) {
1143 # Either the query was aborted or all queries after BEGIN where aborted.
1144 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1145 # In the first case, the only options going forward are (a) ROLLBACK, or
1146 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1147 # option is ROLLBACK, since the snapshots would have been released.
1148 if ( is_object( $tempIgnore ) ) {
1149 // Ugly hack to know that savepoints are in use for postgres
1150 // FIXME: remove this and make DatabasePostgres use ATOMIC_CANCELABLE
1152 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1153 $this->trxStatusCause
=
1154 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1155 $tempIgnore = false; // cannot recover
1158 # Nothing prior was there to lose from the transaction
1159 $this->trxStatus
= self
::STATUS_TRX_OK
;
1163 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1166 return $this->resultObject( $ret );
1170 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1172 * @param string $sql Original SQL query
1173 * @param string $commentedSql SQL query with debugging/trace comment
1174 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1175 * @param string $fname Name of the calling function
1176 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1177 * object for a successful read query, or false on failure
1179 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1180 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1181 # generalizeSQL() will probably cut down the query to reasonable
1182 # logging size most of the time. The substr is really just a sanity check.
1184 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1186 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1189 # Include query transaction state
1190 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1192 $startTime = microtime( true );
1193 if ( $this->profiler
) {
1194 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1196 $this->affectedRowCount
= null;
1197 $ret = $this->doQuery( $commentedSql );
1198 $this->affectedRowCount
= $this->affectedRows();
1199 if ( $this->profiler
) {
1200 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1202 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1204 unset( $queryProfSection ); // profile out (if set)
1206 if ( $ret !== false ) {
1207 $this->lastPing
= $startTime;
1208 if ( $isWrite && $this->trxLevel
) {
1209 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1210 $this->trxWriteCallers
[] = $fname;
1214 if ( $sql === self
::PING_QUERY
) {
1215 $this->rttEstimate
= $queryRuntime;
1218 $this->trxProfiler
->recordQueryCompletion(
1219 $queryProf, $startTime, $isWrite, $this->affectedRows()
1221 $this->queryLogger
->debug( $sql, [
1223 'master' => $isMaster,
1224 'runtime' => $queryRuntime,
1231 * Update the estimated run-time of a query, not counting large row lock times
1233 * LoadBalancer can be set to rollback transactions that will create huge replication
1234 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1235 * queries, like inserting a row can take a long time due to row locking. This method
1236 * uses some simple heuristics to discount those cases.
1238 * @param string $sql A SQL write query
1239 * @param float $runtime Total runtime, including RTT
1240 * @param int $affected Affected row count
1242 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1243 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1244 $indicativeOfReplicaRuntime = true;
1245 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1246 $verb = $this->getQueryVerb( $sql );
1247 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1248 if ( $verb === 'INSERT' ) {
1249 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1250 } elseif ( $verb === 'REPLACE' ) {
1251 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1255 $this->trxWriteDuration +
= $runtime;
1256 $this->trxWriteQueryCount +
= 1;
1257 $this->trxWriteAffectedRows +
= $affected;
1258 if ( $indicativeOfReplicaRuntime ) {
1259 $this->trxWriteAdjDuration +
= $runtime;
1260 $this->trxWriteAdjQueryCount +
= 1;
1265 * @param string $sql
1266 * @param string $fname
1267 * @throws DBTransactionStateError
1269 private function assertTransactionStatus( $sql, $fname ) {
1271 $this->trxStatus
< self
::STATUS_TRX_OK
&&
1272 $this->getQueryVerb( $sql ) !== 'ROLLBACK' // transaction/savepoint
1274 throw new DBTransactionStateError(
1276 "Cannot execute query from $fname while transaction status is ERROR. ",
1278 $this->trxStatusCause
1284 * Determine whether or not it is safe to retry queries after a database
1285 * connection is lost
1287 * @param string $sql SQL query
1288 * @param bool $priorWritesPending Whether there is a transaction open with
1289 * possible write queries or transaction pre-commit/idle callbacks
1290 * waiting on it to finish.
1291 * @return bool True if it is safe to retry the query, false otherwise
1293 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1294 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1295 # Dropped connections also mean that named locks are automatically released.
1296 # Only allow error suppression in autocommit mode or when the lost transaction
1297 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1298 if ( $this->namedLocksHeld
) {
1299 return false; // possible critical section violation
1300 } elseif ( $this->sessionTempTables
) {
1301 return false; // tables might be queried latter
1302 } elseif ( $sql === 'COMMIT' ) {
1303 return !$priorWritesPending; // nothing written anyway? (T127428)
1304 } elseif ( $sql === 'ROLLBACK' ) {
1305 return true; // transaction lost...which is also what was requested :)
1306 } elseif ( $this->explicitTrxActive() ) {
1307 return false; // don't drop atomocity and explicit snapshots
1308 } elseif ( $priorWritesPending ) {
1309 return false; // prior writes lost from implicit transaction
1316 * Clean things up after session (and thus transaction) loss
1318 private function handleSessionLoss() {
1319 // Clean up tracking of session-level things...
1320 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1321 // https://www.postgresql.org/docs/9.1/static/sql-createtable.html (ignoring ON COMMIT)
1322 $this->sessionTempTables
= [];
1323 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1324 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1325 $this->namedLocksHeld
= [];
1326 // Session loss implies transaction loss
1327 $this->handleTransactionLoss();
1331 * Clean things up after transaction loss
1333 private function handleTransactionLoss() {
1334 $this->trxLevel
= 0;
1335 $this->trxAtomicCounter
= 0;
1336 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1337 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1339 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1340 // If callback suppression is set then the array will remain unhandled.
1341 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1342 } catch ( Exception
$ex ) {
1343 // Already logged; move on...
1346 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1347 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1348 } catch ( Exception
$ex ) {
1349 // Already logged; move on...
1354 * Checks whether the cause of the error is detected to be a timeout.
1356 * It returns false by default, and not all engines support detecting this yet.
1357 * If this returns false, it will be treated as a generic query error.
1359 * @param string $error Error text
1360 * @param int $errno Error number
1363 protected function wasQueryTimeout( $error, $errno ) {
1368 * Report a query error. Log the error, and if neither the object ignore
1369 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1371 * @param string $error
1373 * @param string $sql
1374 * @param string $fname
1375 * @param bool $tempIgnore
1376 * @throws DBQueryError
1378 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1379 if ( $tempIgnore ) {
1380 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1382 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1389 * @param string $error
1390 * @param string|int $errno
1391 * @param string $sql
1392 * @param string $fname
1395 private function makeQueryException( $error, $errno, $sql, $fname ) {
1396 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1397 $this->queryLogger
->error(
1398 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1399 $this->getLogContext( [
1400 'method' => __METHOD__
,
1403 'sql1line' => $sql1line,
1407 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1408 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1409 if ( $wasQueryTimeout ) {
1410 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1412 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1418 public function freeResult( $res ) {
1421 public function selectField(
1422 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1424 if ( $var === '*' ) { // sanity
1425 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1428 if ( !is_array( $options ) ) {
1429 $options = [ $options ];
1432 $options['LIMIT'] = 1;
1434 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1435 if ( $res === false ||
!$this->numRows( $res ) ) {
1439 $row = $this->fetchRow( $res );
1441 if ( $row !== false ) {
1442 return reset( $row );
1448 public function selectFieldValues(
1449 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1451 if ( $var === '*' ) { // sanity
1452 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1453 } elseif ( !is_string( $var ) ) { // sanity
1454 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1457 if ( !is_array( $options ) ) {
1458 $options = [ $options ];
1461 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1462 if ( $res === false ) {
1467 foreach ( $res as $row ) {
1468 $values[] = $row->$var;
1475 * Returns an optional USE INDEX clause to go after the table, and a
1476 * string to go at the end of the query.
1478 * @param array $options Associative array of options to be turned into
1479 * an SQL query, valid keys are listed in the function.
1481 * @see Database::select()
1483 protected function makeSelectOptions( $options ) {
1484 $preLimitTail = $postLimitTail = '';
1489 foreach ( $options as $key => $option ) {
1490 if ( is_numeric( $key ) ) {
1491 $noKeyOptions[$option] = true;
1495 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1497 $preLimitTail .= $this->makeOrderBy( $options );
1499 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1500 $postLimitTail .= ' FOR UPDATE';
1503 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1504 $postLimitTail .= ' LOCK IN SHARE MODE';
1507 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1508 $startOpts .= 'DISTINCT';
1511 # Various MySQL extensions
1512 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1513 $startOpts .= ' /*! STRAIGHT_JOIN */';
1516 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1517 $startOpts .= ' HIGH_PRIORITY';
1520 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1521 $startOpts .= ' SQL_BIG_RESULT';
1524 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1525 $startOpts .= ' SQL_BUFFER_RESULT';
1528 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1529 $startOpts .= ' SQL_SMALL_RESULT';
1532 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1533 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1536 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1537 $startOpts .= ' SQL_CACHE';
1540 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1541 $startOpts .= ' SQL_NO_CACHE';
1544 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1545 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1549 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1550 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1555 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1559 * Returns an optional GROUP BY with an optional HAVING
1561 * @param array $options Associative array of options
1563 * @see Database::select()
1566 protected function makeGroupByWithHaving( $options ) {
1568 if ( isset( $options['GROUP BY'] ) ) {
1569 $gb = is_array( $options['GROUP BY'] )
1570 ?
implode( ',', $options['GROUP BY'] )
1571 : $options['GROUP BY'];
1572 $sql .= ' GROUP BY ' . $gb;
1574 if ( isset( $options['HAVING'] ) ) {
1575 $having = is_array( $options['HAVING'] )
1576 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1577 : $options['HAVING'];
1578 $sql .= ' HAVING ' . $having;
1585 * Returns an optional ORDER BY
1587 * @param array $options Associative array of options
1589 * @see Database::select()
1592 protected function makeOrderBy( $options ) {
1593 if ( isset( $options['ORDER BY'] ) ) {
1594 $ob = is_array( $options['ORDER BY'] )
1595 ?
implode( ',', $options['ORDER BY'] )
1596 : $options['ORDER BY'];
1598 return ' ORDER BY ' . $ob;
1604 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1605 $options = [], $join_conds = [] ) {
1606 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1608 return $this->query( $sql, $fname );
1611 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1612 $options = [], $join_conds = []
1614 if ( is_array( $vars ) ) {
1615 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1618 $options = (array)$options;
1619 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1620 ?
$options['USE INDEX']
1623 isset( $options['IGNORE INDEX'] ) &&
1624 is_array( $options['IGNORE INDEX'] )
1626 ?
$options['IGNORE INDEX']
1629 if ( is_array( $table ) ) {
1631 $this->tableNamesWithIndexClauseOrJOIN(
1632 $table, $useIndexes, $ignoreIndexes, $join_conds );
1633 } elseif ( $table != '' ) {
1635 $this->tableNamesWithIndexClauseOrJOIN(
1636 [ $table ], $useIndexes, $ignoreIndexes, [] );
1641 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1642 $this->makeSelectOptions( $options );
1644 if ( is_array( $conds ) ) {
1645 $conds = $this->makeList( $conds, self
::LIST_AND
);
1648 if ( $conds === null ||
$conds === false ) {
1649 $this->queryLogger
->warning(
1653 . ' with incorrect parameters: $conds must be a string or an array'
1658 if ( $conds === '' ) {
1659 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1660 } elseif ( is_string( $conds ) ) {
1661 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1662 "WHERE $conds $preLimitTail";
1664 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1667 if ( isset( $options['LIMIT'] ) ) {
1668 $sql = $this->limitResult( $sql, $options['LIMIT'],
1669 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1671 $sql = "$sql $postLimitTail";
1673 if ( isset( $options['EXPLAIN'] ) ) {
1674 $sql = 'EXPLAIN ' . $sql;
1680 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1681 $options = [], $join_conds = []
1683 $options = (array)$options;
1684 $options['LIMIT'] = 1;
1685 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1687 if ( $res === false ) {
1691 if ( !$this->numRows( $res ) ) {
1695 $obj = $this->fetchObject( $res );
1700 public function estimateRowCount(
1701 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1703 $conds = $this->normalizeConditions( $conds, $fname );
1704 $column = $this->extractSingleFieldFromList( $var );
1705 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1706 $conds[] = "$column IS NOT NULL";
1709 $res = $this->select(
1710 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1712 $row = $res ?
$this->fetchRow( $res ) : [];
1714 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1717 public function selectRowCount(
1718 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1720 $conds = $this->normalizeConditions( $conds, $fname );
1721 $column = $this->extractSingleFieldFromList( $var );
1722 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1723 $conds[] = "$column IS NOT NULL";
1726 $res = $this->select(
1728 'tmp_count' => $this->buildSelectSubquery(
1737 [ 'rowcount' => 'COUNT(*)' ],
1741 $row = $res ?
$this->fetchRow( $res ) : [];
1743 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1747 * @param array|string $conds
1748 * @param string $fname
1751 final protected function normalizeConditions( $conds, $fname ) {
1752 if ( $conds === null ||
$conds === false ) {
1753 $this->queryLogger
->warning(
1757 . ' with incorrect parameters: $conds must be a string or an array'
1762 if ( !is_array( $conds ) ) {
1763 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1770 * @param array|string $var Field parameter in the style of select()
1771 * @return string|null Column name or null; ignores aliases
1772 * @throws DBUnexpectedError Errors out if multiple columns are given
1774 final protected function extractSingleFieldFromList( $var ) {
1775 if ( is_array( $var ) ) {
1778 } elseif ( count( $var ) == 1 ) {
1779 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1781 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1791 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1792 * It's only slightly flawed. Don't use for anything important.
1794 * @param string $sql A SQL Query
1798 protected static function generalizeSQL( $sql ) {
1799 # This does the same as the regexp below would do, but in such a way
1800 # as to avoid crashing php on some large strings.
1801 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1803 $sql = str_replace( "\\\\", '', $sql );
1804 $sql = str_replace( "\\'", '', $sql );
1805 $sql = str_replace( "\\\"", '', $sql );
1806 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1807 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1809 # All newlines, tabs, etc replaced by single space
1810 $sql = preg_replace( '/\s+/', ' ', $sql );
1813 # except the ones surrounded by characters, e.g. l10n
1814 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1815 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1820 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1821 $info = $this->fieldInfo( $table, $field );
1826 public function indexExists( $table, $index, $fname = __METHOD__
) {
1827 if ( !$this->tableExists( $table ) ) {
1831 $info = $this->indexInfo( $table, $index, $fname );
1832 if ( is_null( $info ) ) {
1835 return $info !== false;
1839 public function tableExists( $table, $fname = __METHOD__
) {
1840 $tableRaw = $this->tableName( $table, 'raw' );
1841 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1842 return true; // already known to exist
1845 $table = $this->tableName( $table );
1846 $ignoreErrors = true;
1847 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1852 public function indexUnique( $table, $index ) {
1853 $indexInfo = $this->indexInfo( $table, $index );
1855 if ( !$indexInfo ) {
1859 return !$indexInfo[0]->Non_unique
;
1863 * Helper for Database::insert().
1865 * @param array $options
1868 protected function makeInsertOptions( $options ) {
1869 return implode( ' ', $options );
1872 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1873 # No rows to insert, easy just return now
1874 if ( !count( $a ) ) {
1878 $table = $this->tableName( $table );
1880 if ( !is_array( $options ) ) {
1881 $options = [ $options ];
1885 if ( isset( $options['fileHandle'] ) ) {
1886 $fh = $options['fileHandle'];
1888 $options = $this->makeInsertOptions( $options );
1890 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1892 $keys = array_keys( $a[0] );
1895 $keys = array_keys( $a );
1898 $sql = 'INSERT ' . $options .
1899 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1903 foreach ( $a as $row ) {
1909 $sql .= '(' . $this->makeList( $row ) . ')';
1912 $sql .= '(' . $this->makeList( $a ) . ')';
1915 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1917 } elseif ( $fh !== null ) {
1921 return (bool)$this->query( $sql, $fname );
1925 * Make UPDATE options array for Database::makeUpdateOptions
1927 * @param array $options
1930 protected function makeUpdateOptionsArray( $options ) {
1931 if ( !is_array( $options ) ) {
1932 $options = [ $options ];
1937 if ( in_array( 'IGNORE', $options ) ) {
1945 * Make UPDATE options for the Database::update function
1947 * @param array $options The options passed to Database::update
1950 protected function makeUpdateOptions( $options ) {
1951 $opts = $this->makeUpdateOptionsArray( $options );
1953 return implode( ' ', $opts );
1956 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1957 $table = $this->tableName( $table );
1958 $opts = $this->makeUpdateOptions( $options );
1959 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1961 if ( $conds !== [] && $conds !== '*' ) {
1962 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1965 return (bool)$this->query( $sql, $fname );
1968 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1969 if ( !is_array( $a ) ) {
1970 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1976 foreach ( $a as $field => $value ) {
1978 if ( $mode == self
::LIST_AND
) {
1980 } elseif ( $mode == self
::LIST_OR
) {
1989 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1990 $list .= "($value)";
1991 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1994 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1996 // Remove null from array to be handled separately if found
1997 $includeNull = false;
1998 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1999 $includeNull = true;
2000 unset( $value[$nullKey] );
2002 if ( count( $value ) == 0 && !$includeNull ) {
2003 throw new InvalidArgumentException(
2004 __METHOD__
. ": empty input for field $field" );
2005 } elseif ( count( $value ) == 0 ) {
2006 // only check if $field is null
2007 $list .= "$field IS NULL";
2009 // IN clause contains at least one valid element
2010 if ( $includeNull ) {
2011 // Group subconditions to ensure correct precedence
2014 if ( count( $value ) == 1 ) {
2015 // Special-case single values, as IN isn't terribly efficient
2016 // Don't necessarily assume the single key is 0; we don't
2017 // enforce linear numeric ordering on other arrays here.
2018 $value = array_values( $value )[0];
2019 $list .= $field . " = " . $this->addQuotes( $value );
2021 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2023 // if null present in array, append IS NULL
2024 if ( $includeNull ) {
2025 $list .= " OR $field IS NULL)";
2028 } elseif ( $value === null ) {
2029 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2030 $list .= "$field IS ";
2031 } elseif ( $mode == self
::LIST_SET
) {
2032 $list .= "$field = ";
2037 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2039 $list .= "$field = ";
2041 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2048 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2051 foreach ( $data as $base => $sub ) {
2052 if ( count( $sub ) ) {
2053 $conds[] = $this->makeList(
2054 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2060 return $this->makeList( $conds, self
::LIST_OR
);
2062 // Nothing to search for...
2067 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2071 public function bitNot( $field ) {
2075 public function bitAnd( $fieldLeft, $fieldRight ) {
2076 return "($fieldLeft & $fieldRight)";
2079 public function bitOr( $fieldLeft, $fieldRight ) {
2080 return "($fieldLeft | $fieldRight)";
2083 public function buildConcat( $stringList ) {
2084 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2087 public function buildGroupConcatField(
2088 $delim, $table, $field, $conds = '', $join_conds = []
2090 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2092 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2095 public function buildSubstring( $input, $startPosition, $length = null ) {
2096 $this->assertBuildSubstringParams( $startPosition, $length );
2097 $functionBody = "$input FROM $startPosition";
2098 if ( $length !== null ) {
2099 $functionBody .= " FOR $length";
2101 return 'SUBSTRING(' . $functionBody . ')';
2105 * Check type and bounds for parameters to self::buildSubstring()
2107 * All supported databases have substring functions that behave the same for
2108 * positive $startPosition and non-negative $length, but behaviors differ when
2109 * given 0 or negative $startPosition or negative $length. The simplest
2110 * solution to that is to just forbid those values.
2112 * @param int $startPosition
2113 * @param int|null $length
2116 protected function assertBuildSubstringParams( $startPosition, $length ) {
2117 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2118 throw new InvalidArgumentException(
2119 '$startPosition must be a positive integer'
2122 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2123 throw new InvalidArgumentException(
2124 '$length must be null or an integer greater than or equal to 0'
2129 public function buildStringCast( $field ) {
2133 public function buildIntegerCast( $field ) {
2134 return 'CAST( ' . $field . ' AS INTEGER )';
2137 public function buildSelectSubquery(
2138 $table, $vars, $conds = '', $fname = __METHOD__
,
2139 $options = [], $join_conds = []
2141 return new Subquery(
2142 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2146 public function databasesAreIndependent() {
2150 public function selectDB( $db ) {
2151 # Stub. Shouldn't cause serious problems if it's not overridden, but
2152 # if your database engine supports a concept similar to MySQL's
2153 # databases you may as well.
2154 $this->dbName
= $db;
2159 public function getDBname() {
2160 return $this->dbName
;
2163 public function getServer() {
2164 return $this->server
;
2167 public function tableName( $name, $format = 'quoted' ) {
2168 if ( $name instanceof Subquery
) {
2169 throw new DBUnexpectedError(
2171 __METHOD__
. ': got Subquery instance when expecting a string.'
2175 # Skip the entire process when we have a string quoted on both ends.
2176 # Note that we check the end so that we will still quote any use of
2177 # use of `database`.table. But won't break things if someone wants
2178 # to query a database table with a dot in the name.
2179 if ( $this->isQuotedIdentifier( $name ) ) {
2183 # Lets test for any bits of text that should never show up in a table
2184 # name. Basically anything like JOIN or ON which are actually part of
2185 # SQL queries, but may end up inside of the table value to combine
2186 # sql. Such as how the API is doing.
2187 # Note that we use a whitespace test rather than a \b test to avoid
2188 # any remote case where a word like on may be inside of a table name
2189 # surrounded by symbols which may be considered word breaks.
2190 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2191 $this->queryLogger
->warning(
2192 __METHOD__
. ": use of subqueries is not supported this way.",
2193 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2199 # Split database and table into proper variables.
2200 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2202 # Quote $table and apply the prefix if not quoted.
2203 # $tableName might be empty if this is called from Database::replaceVars()
2204 $tableName = "{$prefix}{$table}";
2205 if ( $format === 'quoted'
2206 && !$this->isQuotedIdentifier( $tableName )
2207 && $tableName !== ''
2209 $tableName = $this->addIdentifierQuotes( $tableName );
2212 # Quote $schema and $database and merge them with the table name if needed
2213 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2214 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2220 * Get the table components needed for a query given the currently selected database
2222 * @param string $name Table name in the form of db.schema.table, db.table, or table
2223 * @return array (DB name or "" for default, schema name, table prefix, table name)
2225 protected function qualifiedTableComponents( $name ) {
2226 # We reverse the explode so that database.table and table both output the correct table.
2227 $dbDetails = explode( '.', $name, 3 );
2228 if ( count( $dbDetails ) == 3 ) {
2229 list( $database, $schema, $table ) = $dbDetails;
2230 # We don't want any prefix added in this case
2232 } elseif ( count( $dbDetails ) == 2 ) {
2233 list( $database, $table ) = $dbDetails;
2234 # We don't want any prefix added in this case
2236 # In dbs that support it, $database may actually be the schema
2237 # but that doesn't affect any of the functionality here
2240 list( $table ) = $dbDetails;
2241 if ( isset( $this->tableAliases
[$table] ) ) {
2242 $database = $this->tableAliases
[$table]['dbname'];
2243 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2244 ?
$this->tableAliases
[$table]['schema']
2246 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2247 ?
$this->tableAliases
[$table]['prefix']
2248 : $this->tablePrefix
;
2251 $schema = $this->schema
; # Default schema
2252 $prefix = $this->tablePrefix
; # Default prefix
2256 return [ $database, $schema, $prefix, $table ];
2260 * @param string|null $namespace Database or schema
2261 * @param string $relation Name of table, view, sequence, etc...
2262 * @param string $format One of (raw, quoted)
2263 * @return string Relation name with quoted and merged $namespace as needed
2265 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2266 if ( strlen( $namespace ) ) {
2267 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2268 $namespace = $this->addIdentifierQuotes( $namespace );
2270 $relation = $namespace . '.' . $relation;
2276 public function tableNames() {
2277 $inArray = func_get_args();
2280 foreach ( $inArray as $name ) {
2281 $retVal[$name] = $this->tableName( $name );
2287 public function tableNamesN() {
2288 $inArray = func_get_args();
2291 foreach ( $inArray as $name ) {
2292 $retVal[] = $this->tableName( $name );
2299 * Get an aliased table name
2301 * This returns strings like "tableName AS newTableName" for aliased tables
2302 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2304 * @see Database::tableName()
2305 * @param string|Subquery $table Table name or object with a 'sql' field
2306 * @param string|bool $alias Table alias (optional)
2307 * @return string SQL name for aliased table. Will not alias a table to its own name
2309 protected function tableNameWithAlias( $table, $alias = false ) {
2310 if ( is_string( $table ) ) {
2311 $quotedTable = $this->tableName( $table );
2312 } elseif ( $table instanceof Subquery
) {
2313 $quotedTable = (string)$table;
2315 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2318 if ( !strlen( $alias ) ||
$alias === $table ) {
2319 if ( $table instanceof Subquery
) {
2320 throw new InvalidArgumentException( "Subquery table missing alias." );
2323 return $quotedTable;
2325 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2330 * Gets an array of aliased table names
2332 * @param array $tables [ [alias] => table ]
2333 * @return string[] See tableNameWithAlias()
2335 protected function tableNamesWithAlias( $tables ) {
2337 foreach ( $tables as $alias => $table ) {
2338 if ( is_numeric( $alias ) ) {
2341 $retval[] = $this->tableNameWithAlias( $table, $alias );
2348 * Get an aliased field name
2349 * e.g. fieldName AS newFieldName
2351 * @param string $name Field name
2352 * @param string|bool $alias Alias (optional)
2353 * @return string SQL name for aliased field. Will not alias a field to its own name
2355 protected function fieldNameWithAlias( $name, $alias = false ) {
2356 if ( !$alias ||
(string)$alias === (string)$name ) {
2359 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2364 * Gets an array of aliased field names
2366 * @param array $fields [ [alias] => field ]
2367 * @return string[] See fieldNameWithAlias()
2369 protected function fieldNamesWithAlias( $fields ) {
2371 foreach ( $fields as $alias => $field ) {
2372 if ( is_numeric( $alias ) ) {
2375 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2382 * Get the aliased table name clause for a FROM clause
2383 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2385 * @param array $tables ( [alias] => table )
2386 * @param array $use_index Same as for select()
2387 * @param array $ignore_index Same as for select()
2388 * @param array $join_conds Same as for select()
2391 protected function tableNamesWithIndexClauseOrJOIN(
2392 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2396 $use_index = (array)$use_index;
2397 $ignore_index = (array)$ignore_index;
2398 $join_conds = (array)$join_conds;
2400 foreach ( $tables as $alias => $table ) {
2401 if ( !is_string( $alias ) ) {
2402 // No alias? Set it equal to the table name
2406 if ( is_array( $table ) ) {
2407 // A parenthesized group
2408 if ( count( $table ) > 1 ) {
2409 $joinedTable = '(' .
2410 $this->tableNamesWithIndexClauseOrJOIN(
2411 $table, $use_index, $ignore_index, $join_conds ) . ')';
2414 $innerTable = reset( $table );
2415 $innerAlias = key( $table );
2416 $joinedTable = $this->tableNameWithAlias(
2418 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2422 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2425 // Is there a JOIN clause for this table?
2426 if ( isset( $join_conds[$alias] ) ) {
2427 list( $joinType, $conds ) = $join_conds[$alias];
2428 $tableClause = $joinType;
2429 $tableClause .= ' ' . $joinedTable;
2430 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2431 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2433 $tableClause .= ' ' . $use;
2436 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2437 $ignore = $this->ignoreIndexClause(
2438 implode( ',', (array)$ignore_index[$alias] ) );
2439 if ( $ignore != '' ) {
2440 $tableClause .= ' ' . $ignore;
2443 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2445 $tableClause .= ' ON (' . $on . ')';
2448 $retJOIN[] = $tableClause;
2449 } elseif ( isset( $use_index[$alias] ) ) {
2450 // Is there an INDEX clause for this table?
2451 $tableClause = $joinedTable;
2452 $tableClause .= ' ' . $this->useIndexClause(
2453 implode( ',', (array)$use_index[$alias] )
2456 $ret[] = $tableClause;
2457 } elseif ( isset( $ignore_index[$alias] ) ) {
2458 // Is there an INDEX clause for this table?
2459 $tableClause = $joinedTable;
2460 $tableClause .= ' ' . $this->ignoreIndexClause(
2461 implode( ',', (array)$ignore_index[$alias] )
2464 $ret[] = $tableClause;
2466 $tableClause = $joinedTable;
2468 $ret[] = $tableClause;
2472 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2473 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2474 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2476 // Compile our final table clause
2477 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2481 * Allows for index remapping in queries where this is not consistent across DBMS
2483 * @param string $index
2486 protected function indexName( $index ) {
2487 return isset( $this->indexAliases
[$index] )
2488 ?
$this->indexAliases
[$index]
2492 public function addQuotes( $s ) {
2493 if ( $s instanceof Blob
) {
2496 if ( $s === null ) {
2498 } elseif ( is_bool( $s ) ) {
2501 # This will also quote numeric values. This should be harmless,
2502 # and protects against weird problems that occur when they really
2503 # _are_ strings such as article titles and string->number->string
2504 # conversion is not 1:1.
2505 return "'" . $this->strencode( $s ) . "'";
2510 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2511 * MySQL uses `backticks` while basically everything else uses double quotes.
2512 * Since MySQL is the odd one out here the double quotes are our generic
2513 * and we implement backticks in DatabaseMysqlBase.
2518 public function addIdentifierQuotes( $s ) {
2519 return '"' . str_replace( '"', '""', $s ) . '"';
2523 * Returns if the given identifier looks quoted or not according to
2524 * the database convention for quoting identifiers .
2526 * @note Do not use this to determine if untrusted input is safe.
2527 * A malicious user can trick this function.
2528 * @param string $name
2531 public function isQuotedIdentifier( $name ) {
2532 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2537 * @param string $escapeChar
2540 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2541 return str_replace( [ $escapeChar, '%', '_' ],
2542 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2546 public function buildLike() {
2547 $params = func_get_args();
2549 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2550 $params = $params[0];
2555 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2556 // may escape backslashes, creating problems of double escaping. The `
2557 // character has good cross-DBMS compatibility, avoiding special operators
2558 // in MS SQL like ^ and %
2561 foreach ( $params as $value ) {
2562 if ( $value instanceof LikeMatch
) {
2563 $s .= $value->toString();
2565 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2570 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2573 public function anyChar() {
2574 return new LikeMatch( '_' );
2577 public function anyString() {
2578 return new LikeMatch( '%' );
2581 public function nextSequenceValue( $seqName ) {
2586 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2587 * is only needed because a) MySQL must be as efficient as possible due to
2588 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2589 * which index to pick. Anyway, other databases might have different
2590 * indexes on a given table. So don't bother overriding this unless you're
2592 * @param string $index
2595 public function useIndexClause( $index ) {
2600 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2601 * is only needed because a) MySQL must be as efficient as possible due to
2602 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2603 * which index to pick. Anyway, other databases might have different
2604 * indexes on a given table. So don't bother overriding this unless you're
2606 * @param string $index
2609 public function ignoreIndexClause( $index ) {
2613 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2614 if ( count( $rows ) == 0 ) {
2619 if ( !is_array( reset( $rows ) ) ) {
2624 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2625 $affectedRowCount = 0;
2626 foreach ( $rows as $row ) {
2627 // Delete rows which collide with this one
2628 $indexWhereClauses = [];
2629 foreach ( $uniqueIndexes as $index ) {
2630 $indexColumns = (array)$index;
2631 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2632 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2633 throw new DBUnexpectedError(
2635 'New record does not provide all values for unique key (' .
2636 implode( ', ', $indexColumns ) . ')'
2638 } elseif ( in_array( null, $indexRowValues, true ) ) {
2639 throw new DBUnexpectedError(
2641 'New record has a null value for unique key (' .
2642 implode( ', ', $indexColumns ) . ')'
2645 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2648 if ( $indexWhereClauses ) {
2649 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2650 $affectedRowCount +
= $this->affectedRows();
2653 // Now insert the row
2654 $this->insert( $table, $row, $fname );
2655 $affectedRowCount +
= $this->affectedRows();
2657 $this->endAtomic( $fname );
2658 $this->affectedRowCount
= $affectedRowCount;
2659 } catch ( Exception
$e ) {
2660 $this->cancelAtomic( $fname );
2666 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2669 * @param string $table Table name
2670 * @param array|string $rows Row(s) to insert
2671 * @param string $fname Caller function name
2673 * @return ResultWrapper
2675 protected function nativeReplace( $table, $rows, $fname ) {
2676 $table = $this->tableName( $table );
2679 if ( !is_array( reset( $rows ) ) ) {
2683 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2686 foreach ( $rows as $row ) {
2693 $sql .= '(' . $this->makeList( $row ) . ')';
2696 return $this->query( $sql, $fname );
2699 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2702 if ( !count( $rows ) ) {
2703 return true; // nothing to do
2706 if ( !is_array( reset( $rows ) ) ) {
2710 if ( count( $uniqueIndexes ) ) {
2711 $clauses = []; // list WHERE clauses that each identify a single row
2712 foreach ( $rows as $row ) {
2713 foreach ( $uniqueIndexes as $index ) {
2714 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2715 $rowKey = []; // unique key to this row
2716 foreach ( $index as $column ) {
2717 $rowKey[$column] = $row[$column];
2719 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2722 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2727 $affectedRowCount = 0;
2729 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2730 # Update any existing conflicting row(s)
2731 if ( $where !== false ) {
2732 $ok = $this->update( $table, $set, $where, $fname );
2733 $affectedRowCount +
= $this->affectedRows();
2737 # Now insert any non-conflicting row(s)
2738 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2739 $affectedRowCount +
= $this->affectedRows();
2740 $this->endAtomic( $fname );
2741 $this->affectedRowCount
= $affectedRowCount;
2742 } catch ( Exception
$e ) {
2743 $this->cancelAtomic( $fname );
2750 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2754 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2757 $delTable = $this->tableName( $delTable );
2758 $joinTable = $this->tableName( $joinTable );
2759 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2760 if ( $conds != '*' ) {
2761 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2765 $this->query( $sql, $fname );
2768 public function textFieldSize( $table, $field ) {
2769 $table = $this->tableName( $table );
2770 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2771 $res = $this->query( $sql, __METHOD__
);
2772 $row = $this->fetchObject( $res );
2776 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2785 public function delete( $table, $conds, $fname = __METHOD__
) {
2787 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2790 $table = $this->tableName( $table );
2791 $sql = "DELETE FROM $table";
2793 if ( $conds != '*' ) {
2794 if ( is_array( $conds ) ) {
2795 $conds = $this->makeList( $conds, self
::LIST_AND
);
2797 $sql .= ' WHERE ' . $conds;
2800 return $this->query( $sql, $fname );
2803 final public function insertSelect(
2804 $destTable, $srcTable, $varMap, $conds,
2805 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2807 static $hints = [ 'NO_AUTO_COLUMNS' ];
2809 $insertOptions = (array)$insertOptions;
2810 $selectOptions = (array)$selectOptions;
2812 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2813 // For massive migrations with downtime, we don't want to select everything
2814 // into memory and OOM, so do all this native on the server side if possible.
2815 return $this->nativeInsertSelect(
2821 array_diff( $insertOptions, $hints ),
2827 return $this->nonNativeInsertSelect(
2833 array_diff( $insertOptions, $hints ),
2840 * @param array $insertOptions INSERT options
2841 * @param array $selectOptions SELECT options
2842 * @return bool Whether an INSERT SELECT with these options will be replication safe
2845 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2850 * Implementation of insertSelect() based on select() and insert()
2852 * @see IDatabase::insertSelect()
2854 * @param string $destTable
2855 * @param string|array $srcTable
2856 * @param array $varMap
2857 * @param array $conds
2858 * @param string $fname
2859 * @param array $insertOptions
2860 * @param array $selectOptions
2861 * @param array $selectJoinConds
2864 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2865 $fname = __METHOD__
,
2866 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2868 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2869 // on only the master (without needing row-based-replication). It also makes it easy to
2870 // know how big the INSERT is going to be.
2872 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2873 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2875 $selectOptions[] = 'FOR UPDATE';
2876 $res = $this->select(
2877 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2884 $affectedRowCount = 0;
2885 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2888 foreach ( $res as $row ) {
2889 $rows[] = (array)$row;
2891 // Avoid inserts that are too huge
2892 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2893 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2897 $affectedRowCount +
= $this->affectedRows();
2901 if ( $rows && $ok ) {
2902 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2904 $affectedRowCount +
= $this->affectedRows();
2908 $this->endAtomic( $fname );
2909 $this->affectedRowCount
= $affectedRowCount;
2911 $this->cancelAtomic( $fname );
2914 } catch ( Exception
$e ) {
2915 $this->cancelAtomic( $fname );
2921 * Native server-side implementation of insertSelect() for situations where
2922 * we don't want to select everything into memory
2924 * @see IDatabase::insertSelect()
2925 * @param string $destTable
2926 * @param string|array $srcTable
2927 * @param array $varMap
2928 * @param array $conds
2929 * @param string $fname
2930 * @param array $insertOptions
2931 * @param array $selectOptions
2932 * @param array $selectJoinConds
2935 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2936 $fname = __METHOD__
,
2937 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2939 $destTable = $this->tableName( $destTable );
2941 if ( !is_array( $insertOptions ) ) {
2942 $insertOptions = [ $insertOptions ];
2945 $insertOptions = $this->makeInsertOptions( $insertOptions );
2947 $selectSql = $this->selectSQLText(
2949 array_values( $varMap ),
2956 $sql = "INSERT $insertOptions" .
2957 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2960 return $this->query( $sql, $fname );
2964 * Construct a LIMIT query with optional offset. This is used for query
2965 * pages. The SQL should be adjusted so that only the first $limit rows
2966 * are returned. If $offset is provided as well, then the first $offset
2967 * rows should be discarded, and the next $limit rows should be returned.
2968 * If the result of the query is not ordered, then the rows to be returned
2969 * are theoretically arbitrary.
2971 * $sql is expected to be a SELECT, if that makes a difference.
2973 * The version provided by default works in MySQL and SQLite. It will very
2974 * likely need to be overridden for most other DBMSes.
2976 * @param string $sql SQL query we will append the limit too
2977 * @param int $limit The SQL limit
2978 * @param int|bool $offset The SQL offset (default false)
2979 * @throws DBUnexpectedError
2982 public function limitResult( $sql, $limit, $offset = false ) {
2983 if ( !is_numeric( $limit ) ) {
2984 throw new DBUnexpectedError( $this,
2985 "Invalid non-numeric limit passed to limitResult()\n" );
2988 return "$sql LIMIT "
2989 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2993 public function unionSupportsOrderAndLimit() {
2994 return true; // True for almost every DB supported
2997 public function unionQueries( $sqls, $all ) {
2998 $glue = $all ?
') UNION ALL (' : ') UNION (';
3000 return '(' . implode( $glue, $sqls ) . ')';
3003 public function unionConditionPermutations(
3004 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3005 $options = [], $join_conds = []
3007 // First, build the Cartesian product of $permute_conds
3009 foreach ( $permute_conds as $field => $values ) {
3011 // Skip empty $values
3014 $values = array_unique( $values ); // For sanity
3016 foreach ( $conds as $cond ) {
3017 foreach ( $values as $value ) {
3018 $cond[$field] = $value;
3019 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3025 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3027 // If there's just one condition and no subordering, hand off to
3028 // selectSQLText directly.
3029 if ( count( $conds ) === 1 &&
3030 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3032 return $this->selectSQLText(
3033 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3037 // Otherwise, we need to pull out the order and limit to apply after
3038 // the union. Then build the SQL queries for each set of conditions in
3039 // $conds. Then union them together (using UNION ALL, because the
3040 // product *should* already be distinct).
3041 $orderBy = $this->makeOrderBy( $options );
3042 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
3043 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
3044 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3045 if ( !$this->unionSupportsOrderAndLimit() ) {
3046 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3048 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3049 $options['ORDER BY'] = $options['INNER ORDER BY'];
3051 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3052 // We need to increase the limit by the offset rather than
3053 // using the offset directly, otherwise it'll skip incorrectly
3054 // in the subqueries.
3055 $options['LIMIT'] = $limit +
$offset;
3056 unset( $options['OFFSET'] );
3061 foreach ( $conds as $cond ) {
3062 $sqls[] = $this->selectSQLText(
3063 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3066 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3067 if ( $limit !== null ) {
3068 $sql = $this->limitResult( $sql, $limit, $offset );
3074 public function conditional( $cond, $trueVal, $falseVal ) {
3075 if ( is_array( $cond ) ) {
3076 $cond = $this->makeList( $cond, self
::LIST_AND
);
3079 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3082 public function strreplace( $orig, $old, $new ) {
3083 return "REPLACE({$orig}, {$old}, {$new})";
3086 public function getServerUptime() {
3090 public function wasDeadlock() {
3094 public function wasLockTimeout() {
3098 public function wasConnectionLoss() {
3099 return $this->wasConnectionError( $this->lastErrno() );
3102 public function wasReadOnlyError() {
3106 public function wasErrorReissuable() {
3108 $this->wasDeadlock() ||
3109 $this->wasLockTimeout() ||
3110 $this->wasConnectionLoss()
3115 * Do not use this method outside of Database/DBError classes
3117 * @param int|string $errno
3118 * @return bool Whether the given query error was a connection drop
3120 public function wasConnectionError( $errno ) {
3125 * @return bool Whether it is safe to assume the given error only caused statement rollback
3126 * @note This is for backwards compatibility for callers catching DBError exceptions in
3127 * order to ignore problems like duplicate key errors or foriegn key violations
3130 protected function wasKnownStatementRollbackError() {
3131 return false; // don't know; it could have caused a transaction rollback
3134 public function deadlockLoop() {
3135 $args = func_get_args();
3136 $function = array_shift( $args );
3137 $tries = self
::DEADLOCK_TRIES
;
3139 $this->begin( __METHOD__
);
3142 /** @var Exception $e */
3146 $retVal = call_user_func_array( $function, $args );
3148 } catch ( DBQueryError
$e ) {
3149 if ( $this->wasDeadlock() ) {
3150 // Retry after a randomized delay
3151 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3153 // Throw the error back up
3157 } while ( --$tries > 0 );
3159 if ( $tries <= 0 ) {
3160 // Too many deadlocks; give up
3161 $this->rollback( __METHOD__
);
3164 $this->commit( __METHOD__
);
3170 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3171 # Real waits are implemented in the subclass.
3175 public function getReplicaPos() {
3180 public function getMasterPos() {
3185 public function serverIsReadOnly() {
3189 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3190 if ( !$this->trxLevel
) {
3191 throw new DBUnexpectedError( $this, "No transaction is active." );
3193 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3196 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3197 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3198 // Start an implicit transaction similar to how query() does
3199 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3200 $this->trxAutomatic
= true;
3203 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3204 if ( !$this->trxLevel
) {
3205 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3209 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3210 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3211 // Start an implicit transaction similar to how query() does
3212 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3213 $this->trxAutomatic
= true;
3216 if ( $this->trxLevel
) {
3217 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3219 // No transaction is active nor will start implicitly, so make one for this callback
3220 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3222 call_user_func( $callback );
3223 $this->endAtomic( __METHOD__
);
3224 } catch ( Exception
$e ) {
3225 $this->cancelAtomic( __METHOD__
);
3231 final public function setTransactionListener( $name, callable
$callback = null ) {
3233 $this->trxRecurringCallbacks
[$name] = $callback;
3235 unset( $this->trxRecurringCallbacks
[$name] );
3240 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3242 * This method should not be used outside of Database/LoadBalancer
3244 * @param bool $suppress
3247 final public function setTrxEndCallbackSuppression( $suppress ) {
3248 $this->trxEndCallbacksSuppressed
= $suppress;
3252 * Actually run and consume any "on transaction idle/resolution" callbacks.
3254 * This method should not be used outside of Database/LoadBalancer
3256 * @param int $trigger IDatabase::TRIGGER_* constant
3260 public function runOnTransactionIdleCallbacks( $trigger ) {
3261 if ( $this->trxEndCallbacksSuppressed
) {
3265 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3266 /** @var Exception $e */
3267 $e = null; // first exception
3268 do { // callbacks may add callbacks :)
3269 $callbacks = array_merge(
3270 $this->trxIdleCallbacks
,
3271 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3273 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3274 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3275 foreach ( $callbacks as $callback ) {
3277 list( $phpCallback ) = $callback;
3278 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3279 call_user_func_array( $phpCallback, [ $trigger ] );
3281 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3283 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3285 } catch ( Exception
$ex ) {
3286 call_user_func( $this->errorLogger
, $ex );
3288 // Some callbacks may use startAtomic/endAtomic, so make sure
3289 // their transactions are ended so other callbacks don't fail
3290 if ( $this->trxLevel() ) {
3291 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3295 } while ( count( $this->trxIdleCallbacks
) );
3297 if ( $e instanceof Exception
) {
3298 throw $e; // re-throw any first exception
3303 * Actually run and consume any "on transaction pre-commit" callbacks.
3305 * This method should not be used outside of Database/LoadBalancer
3310 public function runOnTransactionPreCommitCallbacks() {
3311 $e = null; // first exception
3312 do { // callbacks may add callbacks :)
3313 $callbacks = $this->trxPreCommitCallbacks
;
3314 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3315 foreach ( $callbacks as $callback ) {
3317 list( $phpCallback ) = $callback;
3318 call_user_func( $phpCallback );
3319 } catch ( Exception
$ex ) {
3320 call_user_func( $this->errorLogger
, $ex );
3324 } while ( count( $this->trxPreCommitCallbacks
) );
3326 if ( $e instanceof Exception
) {
3327 throw $e; // re-throw any first exception
3332 * Actually run any "transaction listener" callbacks.
3334 * This method should not be used outside of Database/LoadBalancer
3336 * @param int $trigger IDatabase::TRIGGER_* constant
3340 public function runTransactionListenerCallbacks( $trigger ) {
3341 if ( $this->trxEndCallbacksSuppressed
) {
3345 /** @var Exception $e */
3346 $e = null; // first exception
3348 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3350 $phpCallback( $trigger, $this );
3351 } catch ( Exception
$ex ) {
3352 call_user_func( $this->errorLogger
, $ex );
3357 if ( $e instanceof Exception
) {
3358 throw $e; // re-throw any first exception
3363 * Create a savepoint
3365 * This is used internally to implement atomic sections. It should not be
3369 * @param string $identifier Identifier for the savepoint
3370 * @param string $fname Calling function name
3372 protected function doSavepoint( $identifier, $fname ) {
3373 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3377 * Release a savepoint
3379 * This is used internally to implement atomic sections. It should not be
3383 * @param string $identifier Identifier for the savepoint
3384 * @param string $fname Calling function name
3386 protected function doReleaseSavepoint( $identifier, $fname ) {
3387 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3391 * Rollback to a savepoint
3393 * This is used internally to implement atomic sections. It should not be
3397 * @param string $identifier Identifier for the savepoint
3398 * @param string $fname Calling function name
3400 protected function doRollbackToSavepoint( $identifier, $fname ) {
3401 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3404 final public function startAtomic(
3405 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3407 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3408 if ( !$this->trxLevel
) {
3409 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3410 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3411 // in all changes being in one transaction to keep requests transactional.
3412 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3413 $this->trxAutomaticAtomic
= true;
3415 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3416 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3417 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3418 $this->queryLogger
->warning(
3419 'There have been an excessively large number of atomic sections in a transaction'
3420 . " started by $this->trxFname, reusing IDs (at $fname)",
3421 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3423 $this->trxAtomicCounter
= 0;
3424 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3426 $this->doSavepoint( $savepointId, $fname );
3429 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3432 final public function endAtomic( $fname = __METHOD__
) {
3433 if ( !$this->trxLevel
) {
3434 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3437 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3438 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3439 if ( $savedFname !== $fname ) {
3440 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3443 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3444 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3445 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3446 $this->doReleaseSavepoint( $savepointId, $fname );
3450 final public function cancelAtomic( $fname = __METHOD__
) {
3451 if ( !$this->trxLevel
) {
3452 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3455 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3456 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3457 if ( $savedFname !== $fname ) {
3458 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3460 if ( !$savepointId ) {
3461 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3464 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3465 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3466 } elseif ( $savepointId !== 'n/a' ) {
3467 $this->doRollbackToSavepoint( $savepointId, $fname );
3468 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3471 $this->affectedRowCount
= 0; // for the sake of consistency
3474 final public function doAtomicSection( $fname, callable
$callback ) {
3475 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3477 $res = call_user_func_array( $callback, [ $this, $fname ] );
3478 } catch ( Exception
$e ) {
3479 $this->cancelAtomic( $fname );
3482 $this->endAtomic( $fname );
3487 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3488 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3489 if ( $this->trxLevel
) {
3490 if ( $this->trxAtomicLevels
) {
3491 $levels = $this->flatAtomicSectionList();
3492 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3493 throw new DBUnexpectedError( $this, $msg );
3494 } elseif ( !$this->trxAutomatic
) {
3495 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3496 throw new DBUnexpectedError( $this, $msg );
3498 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3499 throw new DBUnexpectedError( $this, $msg );
3501 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3502 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3503 throw new DBUnexpectedError( $this, $msg );
3506 // Avoid fatals if close() was called
3507 $this->assertOpen();
3509 $this->doBegin( $fname );
3510 $this->trxStatus
= self
::STATUS_TRX_OK
;
3511 $this->trxAtomicCounter
= 0;
3512 $this->trxTimestamp
= microtime( true );
3513 $this->trxFname
= $fname;
3514 $this->trxDoneWrites
= false;
3515 $this->trxAutomaticAtomic
= false;
3516 $this->trxAtomicLevels
= [];
3517 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3518 $this->trxWriteDuration
= 0.0;
3519 $this->trxWriteQueryCount
= 0;
3520 $this->trxWriteAffectedRows
= 0;
3521 $this->trxWriteAdjDuration
= 0.0;
3522 $this->trxWriteAdjQueryCount
= 0;
3523 $this->trxWriteCallers
= [];
3524 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3525 // Get an estimate of the replication lag before any such queries.
3526 $this->trxReplicaLag
= null; // clear cached value first
3527 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3528 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3529 // caller will think its OK to muck around with the transaction just because startAtomic()
3530 // has not yet completed (e.g. setting trxAtomicLevels).
3531 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3535 * Issues the BEGIN command to the database server.
3537 * @see Database::begin()
3538 * @param string $fname
3540 protected function doBegin( $fname ) {
3541 $this->query( 'BEGIN', $fname );
3542 $this->trxLevel
= 1;
3545 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3546 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3547 // There are still atomic sections open. This cannot be ignored
3548 $levels = $this->flatAtomicSectionList();
3549 throw new DBUnexpectedError(
3551 "$fname: Got COMMIT while atomic sections $levels are still open."
3555 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3556 if ( !$this->trxLevel
) {
3557 return; // nothing to do
3558 } elseif ( !$this->trxAutomatic
) {
3559 throw new DBUnexpectedError(
3561 "$fname: Flushing an explicit transaction, getting out of sync."
3565 if ( !$this->trxLevel
) {
3566 $this->queryLogger
->error(
3567 "$fname: No transaction to commit, something got out of sync." );
3568 return; // nothing to do
3569 } elseif ( $this->trxAutomatic
) {
3570 throw new DBUnexpectedError(
3572 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3577 // Avoid fatals if close() was called
3578 $this->assertOpen();
3580 $this->runOnTransactionPreCommitCallbacks();
3581 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3582 $this->doCommit( $fname );
3583 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3584 if ( $this->trxDoneWrites
) {
3585 $this->lastWriteTime
= microtime( true );
3586 $this->trxProfiler
->transactionWritingOut(
3591 $this->trxWriteAffectedRows
3595 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3596 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3600 * Issues the COMMIT command to the database server.
3602 * @see Database::commit()
3603 * @param string $fname
3605 protected function doCommit( $fname ) {
3606 if ( $this->trxLevel
) {
3607 $this->query( 'COMMIT', $fname );
3608 $this->trxLevel
= 0;
3612 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3613 $trxActive = $this->trxLevel
;
3615 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3616 if ( $this->getFlag( self
::DBO_TRX
) ) {
3617 throw new DBUnexpectedError(
3619 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3625 // Avoid fatals if close() was called
3626 $this->assertOpen();
3628 $this->doRollback( $fname );
3629 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3630 $this->trxAtomicLevels
= [];
3631 if ( $this->trxDoneWrites
) {
3632 $this->trxProfiler
->transactionWritingOut(
3640 // Clear any commit-dependant callbacks. They might even be present
3641 // only due to transaction rounds, with no SQL transaction being active
3642 $this->trxIdleCallbacks
= [];
3643 $this->trxPreCommitCallbacks
= [];
3647 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3648 } catch ( Exception
$e ) {
3649 // already logged; finish and let LoadBalancer move on during mass-rollback
3652 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3653 } catch ( Exception
$e ) {
3654 // already logged; let LoadBalancer move on during mass-rollback
3657 $this->affectedRowCount
= 0; // for the sake of consistency
3662 * Issues the ROLLBACK command to the database server.
3664 * @see Database::rollback()
3665 * @param string $fname
3667 protected function doRollback( $fname ) {
3668 if ( $this->trxLevel
) {
3669 # Disconnects cause rollback anyway, so ignore those errors
3670 $ignoreErrors = true;
3671 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3672 $this->trxLevel
= 0;
3676 public function flushSnapshot( $fname = __METHOD__
) {
3677 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3678 // This only flushes transactions to clear snapshots, not to write data
3679 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3680 throw new DBUnexpectedError(
3682 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3686 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3689 public function explicitTrxActive() {
3690 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3693 public function duplicateTableStructure(
3694 $oldName, $newName, $temporary = false, $fname = __METHOD__
3696 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3699 public function listTables( $prefix = null, $fname = __METHOD__
) {
3700 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3703 public function listViews( $prefix = null, $fname = __METHOD__
) {
3704 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3707 public function timestamp( $ts = 0 ) {
3708 $t = new ConvertibleTimestamp( $ts );
3709 // Let errors bubble up to avoid putting garbage in the DB
3710 return $t->getTimestamp( TS_MW
);
3713 public function timestampOrNull( $ts = null ) {
3714 if ( is_null( $ts ) ) {
3717 return $this->timestamp( $ts );
3721 public function affectedRows() {
3722 return ( $this->affectedRowCount
=== null )
3723 ?
$this->fetchAffectedRowCount() // default to driver value
3724 : $this->affectedRowCount
;
3728 * @return int Number of retrieved rows according to the driver
3730 abstract protected function fetchAffectedRowCount();
3733 * Take the result from a query, and wrap it in a ResultWrapper if
3734 * necessary. Boolean values are passed through as is, to indicate success
3735 * of write queries or failure.
3737 * Once upon a time, Database::query() returned a bare MySQL result
3738 * resource, and it was necessary to call this function to convert it to
3739 * a wrapper. Nowadays, raw database objects are never exposed to external
3740 * callers, so this is unnecessary in external code.
3742 * @param bool|ResultWrapper|resource|object $result
3743 * @return bool|ResultWrapper
3745 protected function resultObject( $result ) {
3748 } elseif ( $result instanceof ResultWrapper
) {
3750 } elseif ( $result === true ) {
3751 // Successful write query
3754 return new ResultWrapper( $this, $result );
3758 public function ping( &$rtt = null ) {
3759 // Avoid hitting the server if it was hit recently
3760 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3761 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3762 $rtt = $this->rttEstimate
;
3763 return true; // don't care about $rtt
3767 // This will reconnect if possible or return false if not
3768 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3769 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3770 $this->restoreFlags( self
::RESTORE_PRIOR
);
3773 $rtt = $this->rttEstimate
;
3780 * Close any existing (dead) database connection and open a new connection
3782 * @param string $fname
3783 * @return bool True if new connection is opened successfully, false if error
3785 protected function replaceLostConnection( $fname ) {
3786 $this->closeConnection();
3787 $this->opened
= false;
3788 $this->conn
= false;
3790 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3791 $this->lastPing
= microtime( true );
3794 $this->connLogger
->warning(
3795 $fname . ': lost connection to {dbserver}; reconnected',
3797 'dbserver' => $this->getServer(),
3798 'trace' => ( new RuntimeException() )->getTraceAsString()
3801 } catch ( DBConnectionError
$e ) {
3804 $this->connLogger
->error(
3805 $fname . ': lost connection to {dbserver} permanently',
3806 [ 'dbserver' => $this->getServer() ]
3810 $this->handleSessionLoss();
3815 public function getSessionLagStatus() {
3816 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3820 * Get the replica DB lag when the current transaction started
3822 * This is useful when transactions might use snapshot isolation
3823 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3824 * is this lag plus transaction duration. If they don't, it is still
3825 * safe to be pessimistic. This returns null if there is no transaction.
3827 * This returns null if the lag status for this transaction was not yet recorded.
3829 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3832 final protected function getRecordedTransactionLagStatus() {
3833 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
3834 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3839 * Get a replica DB lag estimate for this server
3841 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3844 protected function getApproximateLagStatus() {
3846 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3847 'since' => microtime( true )
3852 * Merge the result of getSessionLagStatus() for several DBs
3853 * using the most pessimistic values to estimate the lag of
3854 * any data derived from them in combination
3856 * This is information is useful for caching modules
3858 * @see WANObjectCache::set()
3859 * @see WANObjectCache::getWithSetCallback()
3861 * @param IDatabase $db1
3862 * @param IDatabase $db2 [optional]
3863 * @return array Map of values:
3864 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3865 * - since: oldest UNIX timestamp of any of the DB lag estimates
3866 * - pending: whether any of the DBs have uncommitted changes
3870 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3871 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3872 foreach ( func_get_args() as $db ) {
3873 /** @var IDatabase $db */
3874 $status = $db->getSessionLagStatus();
3875 if ( $status['lag'] === false ) {
3876 $res['lag'] = false;
3877 } elseif ( $res['lag'] !== false ) {
3878 $res['lag'] = max( $res['lag'], $status['lag'] );
3880 $res['since'] = min( $res['since'], $status['since'] );
3881 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3887 public function getLag() {
3891 public function maxListLen() {
3895 public function encodeBlob( $b ) {
3899 public function decodeBlob( $b ) {
3900 if ( $b instanceof Blob
) {
3906 public function setSessionOptions( array $options ) {
3909 public function sourceFile(
3911 callable
$lineCallback = null,
3912 callable
$resultCallback = null,
3914 callable
$inputCallback = null
3916 Wikimedia\
suppressWarnings();
3917 $fp = fopen( $filename, 'r' );
3918 Wikimedia\restoreWarnings
();
3920 if ( false === $fp ) {
3921 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3925 $fname = __METHOD__
. "( $filename )";
3929 $error = $this->sourceStream(
3930 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3931 } catch ( Exception
$e ) {
3941 public function setSchemaVars( $vars ) {
3942 $this->schemaVars
= $vars;
3945 public function sourceStream(
3947 callable
$lineCallback = null,
3948 callable
$resultCallback = null,
3949 $fname = __METHOD__
,
3950 callable
$inputCallback = null
3952 $delimiterReset = new ScopedCallback(
3953 function ( $delimiter ) {
3954 $this->delimiter
= $delimiter;
3956 [ $this->delimiter
]
3960 while ( !feof( $fp ) ) {
3961 if ( $lineCallback ) {
3962 call_user_func( $lineCallback );
3965 $line = trim( fgets( $fp ) );
3967 if ( $line == '' ) {
3971 if ( '-' == $line[0] && '-' == $line[1] ) {
3979 $done = $this->streamStatementEnd( $cmd, $line );
3983 if ( $done ||
feof( $fp ) ) {
3984 $cmd = $this->replaceVars( $cmd );
3986 if ( $inputCallback ) {
3987 $callbackResult = call_user_func( $inputCallback, $cmd );
3989 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3990 $cmd = $callbackResult;
3995 $res = $this->query( $cmd, $fname );
3997 if ( $resultCallback ) {
3998 call_user_func( $resultCallback, $res, $this );
4001 if ( false === $res ) {
4002 $err = $this->lastError();
4004 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4011 ScopedCallback
::consume( $delimiterReset );
4016 * Called by sourceStream() to check if we've reached a statement end
4018 * @param string &$sql SQL assembled so far
4019 * @param string &$newLine New line about to be added to $sql
4020 * @return bool Whether $newLine contains end of the statement
4022 public function streamStatementEnd( &$sql, &$newLine ) {
4023 if ( $this->delimiter
) {
4025 $newLine = preg_replace(
4026 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4027 if ( $newLine != $prev ) {
4036 * Database independent variable replacement. Replaces a set of variables
4037 * in an SQL statement with their contents as given by $this->getSchemaVars().
4039 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4041 * - '{$var}' should be used for text and is passed through the database's
4043 * - `{$var}` should be used for identifiers (e.g. table and database names).
4044 * It is passed through the database's addIdentifierQuotes method which
4045 * can be overridden if the database uses something other than backticks.
4046 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4047 * database's tableName method.
4048 * - / *i* / passes the name that follows through the database's indexName method.
4049 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4050 * its use should be avoided. In 1.24 and older, string encoding was applied.
4052 * @param string $ins SQL statement to replace variables in
4053 * @return string The new SQL statement with variables replaced
4055 protected function replaceVars( $ins ) {
4056 $vars = $this->getSchemaVars();
4057 return preg_replace_callback(
4059 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4060 \'\{\$ (\w+) }\' | # 3. addQuotes
4061 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4062 /\*\$ (\w+) \*/ # 5. leave unencoded
4064 function ( $m ) use ( $vars ) {
4065 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4066 // check for both nonexistent keys *and* the empty string.
4067 if ( isset( $m[1] ) && $m[1] !== '' ) {
4068 if ( $m[1] === 'i' ) {
4069 return $this->indexName( $m[2] );
4071 return $this->tableName( $m[2] );
4073 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4074 return $this->addQuotes( $vars[$m[3]] );
4075 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4076 return $this->addIdentifierQuotes( $vars[$m[4]] );
4077 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4078 return $vars[$m[5]];
4088 * Get schema variables. If none have been set via setSchemaVars(), then
4089 * use some defaults from the current object.
4093 protected function getSchemaVars() {
4094 if ( $this->schemaVars
) {
4095 return $this->schemaVars
;
4097 return $this->getDefaultSchemaVars();
4102 * Get schema variables to use if none have been set via setSchemaVars().
4104 * Override this in derived classes to provide variables for tables.sql
4105 * and SQL patch files.
4109 protected function getDefaultSchemaVars() {
4113 public function lockIsFree( $lockName, $method ) {
4114 // RDBMs methods for checking named locks may or may not count this thread itself.
4115 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4116 // the behavior choosen by the interface for this method.
4117 return !isset( $this->namedLocksHeld
[$lockName] );
4120 public function lock( $lockName, $method, $timeout = 5 ) {
4121 $this->namedLocksHeld
[$lockName] = 1;
4126 public function unlock( $lockName, $method ) {
4127 unset( $this->namedLocksHeld
[$lockName] );
4132 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4133 if ( $this->writesOrCallbacksPending() ) {
4134 // This only flushes transactions to clear snapshots, not to write data
4135 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4136 throw new DBUnexpectedError(
4138 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4142 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4146 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4147 if ( $this->trxLevel() ) {
4148 // There is a good chance an exception was thrown, causing any early return
4149 // from the caller. Let any error handler get a chance to issue rollback().
4150 // If there isn't one, let the error bubble up and trigger server-side rollback.
4151 $this->onTransactionResolution(
4152 function () use ( $lockKey, $fname ) {
4153 $this->unlock( $lockKey, $fname );
4158 $this->unlock( $lockKey, $fname );
4162 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4167 public function namedLocksEnqueue() {
4171 public function tableLocksHaveTransactionScope() {
4175 final public function lockTables( array $read, array $write, $method ) {
4176 if ( $this->writesOrCallbacksPending() ) {
4177 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4180 if ( $this->tableLocksHaveTransactionScope() ) {
4181 $this->startAtomic( $method );
4184 return $this->doLockTables( $read, $write, $method );
4188 * Helper function for lockTables() that handles the actual table locking
4190 * @param array $read Array of tables to lock for read access
4191 * @param array $write Array of tables to lock for write access
4192 * @param string $method Name of caller
4195 protected function doLockTables( array $read, array $write, $method ) {
4199 final public function unlockTables( $method ) {
4200 if ( $this->tableLocksHaveTransactionScope() ) {
4201 $this->endAtomic( $method );
4203 return true; // locks released on COMMIT/ROLLBACK
4206 return $this->doUnlockTables( $method );
4210 * Helper function for unlockTables() that handles the actual table unlocking
4212 * @param string $method Name of caller
4215 protected function doUnlockTables( $method ) {
4221 * @param string $tableName
4222 * @param string $fName
4223 * @return bool|ResultWrapper
4226 public function dropTable( $tableName, $fName = __METHOD__
) {
4227 if ( !$this->tableExists( $tableName, $fName ) ) {
4230 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4232 return $this->query( $sql, $fName );
4235 public function getInfinity() {
4239 public function encodeExpiry( $expiry ) {
4240 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4241 ?
$this->getInfinity()
4242 : $this->timestamp( $expiry );
4245 public function decodeExpiry( $expiry, $format = TS_MW
) {
4246 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4250 return ConvertibleTimestamp
::convert( $format, $expiry );
4253 public function setBigSelects( $value = true ) {
4257 public function isReadOnly() {
4258 return ( $this->getReadOnlyReason() !== false );
4262 * @return string|bool Reason this DB is read-only or false if it is not
4264 protected function getReadOnlyReason() {
4265 $reason = $this->getLBInfo( 'readOnlyReason' );
4267 return is_string( $reason ) ?
$reason : false;
4270 public function setTableAliases( array $aliases ) {
4271 $this->tableAliases
= $aliases;
4274 public function setIndexAliases( array $aliases ) {
4275 $this->indexAliases
= $aliases;
4279 * Get the underlying binding connection handle
4281 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4282 * This catches broken callers than catch and ignore disconnection exceptions.
4283 * Unlike checking isOpen(), this is safe to call inside of open().
4286 * @throws DBUnexpectedError
4289 protected function getBindingHandle() {
4290 if ( !$this->conn
) {
4291 throw new DBUnexpectedError(
4293 'DB connection was already closed or the connection dropped.'
4304 public function __toString() {
4305 return (string)$this->conn
;
4309 * Make sure that copies do not share the same client binding handle
4310 * @throws DBConnectionError
4312 public function __clone() {
4313 $this->connLogger
->warning(
4314 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4315 ( new RuntimeException() )->getTraceAsString()
4318 if ( $this->isOpen() ) {
4319 // Open a new connection resource without messing with the old one
4320 $this->opened
= false;
4321 $this->conn
= false;
4322 $this->trxEndCallbacks
= []; // don't copy
4323 $this->handleSessionLoss(); // no trx or locks anymore
4324 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4325 $this->lastPing
= microtime( true );
4330 * Called by serialize. Throw an exception when DB connection is serialized.
4331 * This causes problems on some database engines because the connection is
4332 * not restored on unserialize.
4334 public function __sleep() {
4335 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4336 'the connection is not restored on wakeup.' );
4340 * Run a few simple sanity checks and close dangling connections
4342 public function __destruct() {
4343 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4344 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4347 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4348 if ( $danglingWriters ) {
4349 $fnames = implode( ', ', $danglingWriters );
4350 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4353 if ( $this->conn
) {
4354 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4355 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4356 Wikimedia\
suppressWarnings();
4357 $this->closeConnection();
4358 Wikimedia\restoreWarnings
();
4359 $this->conn
= false;
4360 $this->opened
= false;
4365 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4366 class_alias( Database
::class, 'Database' ); // b/c global alias