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;
104 /** @var callback Deprecation logging callback */
105 protected $deprecationLogger;
107 /** @var resource|null Database connection */
108 protected $conn = null;
110 protected $opened = false;
112 /** @var array[] List of (callable, method name, atomic section id) */
113 protected $trxIdleCallbacks = [];
114 /** @var array[] List of (callable, method name, atomic section id) */
115 protected $trxPreCommitCallbacks = [];
116 /** @var array[] List of (callable, method name, atomic section id) */
117 protected $trxEndCallbacks = [];
118 /** @var callable[] Map of (name => callable) */
119 protected $trxRecurringCallbacks = [];
120 /** @var bool Whether to suppress triggering of transaction end callbacks */
121 protected $trxEndCallbacksSuppressed = false;
124 protected $tablePrefix = '';
126 protected $schema = '';
130 protected $lbInfo = [];
131 /** @var array|bool */
132 protected $schemaVars = false;
134 protected $sessionVars = [];
135 /** @var array|null */
136 protected $preparedArgs;
137 /** @var string|bool|null Stashed value of html_errors INI setting */
138 protected $htmlErrors;
140 protected $delimiter = ';';
141 /** @var DatabaseDomain */
142 protected $currentDomain;
143 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
144 protected $affectedRowCount;
147 * @var int Transaction status
149 protected $trxStatus = self
::STATUS_TRX_NONE
;
151 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
153 protected $trxStatusCause;
155 * @var array|null If wasKnownStatementRollbackError() prevented trxStatus from being set,
156 * the relevant details are stored here.
158 protected $trxStatusIgnoredCause;
160 * Either 1 if a transaction is active or 0 otherwise.
161 * The other Trx fields may not be meaningfull if this is 0.
165 protected $trxLevel = 0;
167 * Either a short hexidecimal string if a transaction is active or ""
170 * @see Database::trxLevel
172 protected $trxShortId = '';
174 * The UNIX time that the transaction started. Callers can assume that if
175 * snapshot isolation is used, then the data is *at least* up to date to that
176 * point (possibly more up-to-date since the first SELECT defines the snapshot).
179 * @see Database::trxLevel
181 private $trxTimestamp = null;
182 /** @var float Lag estimate at the time of BEGIN */
183 private $trxReplicaLag = null;
185 * Remembers the function name given for starting the most recent transaction via begin().
186 * Used to provide additional context for error reporting.
189 * @see Database::trxLevel
191 private $trxFname = null;
193 * Record if possible write queries were done in the last transaction started
196 * @see Database::trxLevel
198 private $trxDoneWrites = false;
200 * Record if the current transaction was started implicitly due to DBO_TRX being set.
203 * @see Database::trxLevel
205 private $trxAutomatic = false;
207 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
211 private $trxAtomicCounter = 0;
213 * Array of levels of atomicity within transactions
215 * @var array List of (name, unique ID, savepoint ID)
217 private $trxAtomicLevels = [];
219 * Record if the current transaction was started implicitly by Database::startAtomic
223 private $trxAutomaticAtomic = false;
225 * Track the write query callers of the current transaction
229 private $trxWriteCallers = [];
231 * @var float Seconds spent in write queries for the current transaction
233 private $trxWriteDuration = 0.0;
235 * @var int Number of write queries for the current transaction
237 private $trxWriteQueryCount = 0;
239 * @var int Number of rows affected by write queries for the current transaction
241 private $trxWriteAffectedRows = 0;
243 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
245 private $trxWriteAdjDuration = 0.0;
247 * @var int Number of write queries counted in trxWriteAdjDuration
249 private $trxWriteAdjQueryCount = 0;
251 * @var float RTT time estimate
253 private $rttEstimate = 0.0;
255 /** @var array Map of (name => 1) for locks obtained via lock() */
256 private $namedLocksHeld = [];
257 /** @var array Map of (table name => 1) for TEMPORARY tables */
258 protected $sessionTempTables = [];
260 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
261 private $lazyMasterHandle;
263 /** @var float UNIX timestamp */
264 protected $lastPing = 0.0;
266 /** @var int[] Prior flags member variable values */
267 private $priorFlags = [];
269 /** @var object|string Class name or object With profileIn/profileOut methods */
271 /** @var TransactionProfiler */
272 protected $trxProfiler;
275 protected $nonNativeInsertSelectBatchSize = 10000;
277 /** @var string Idiom used when a cancelable atomic section started the transaction */
278 private static $NOT_APPLICABLE = 'n/a';
279 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
280 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
282 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
283 const STATUS_TRX_ERROR
= 1;
284 /** @var int Transaction is active and in a normal state */
285 const STATUS_TRX_OK
= 2;
286 /** @var int No transaction is active */
287 const STATUS_TRX_NONE
= 3;
290 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
291 * @param array $params Parameters passed from Database::factory()
293 protected function __construct( array $params ) {
294 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
295 $this->connectionParams
[$name] = $params[$name];
298 $this->schema
= $params['schema'];
299 $this->tablePrefix
= $params['tablePrefix'];
301 $this->cliMode
= $params['cliMode'];
302 // Agent name is added to SQL queries in a comment, so make sure it can't break out
303 $this->agent
= str_replace( '/', '-', $params['agent'] );
305 $this->flags
= $params['flags'];
306 if ( $this->flags
& self
::DBO_DEFAULT
) {
307 if ( $this->cliMode
) {
308 $this->flags
&= ~self
::DBO_TRX
;
310 $this->flags |
= self
::DBO_TRX
;
313 // Disregard deprecated DBO_IGNORE flag (T189999)
314 $this->flags
&= ~self
::DBO_IGNORE
;
316 $this->sessionVars
= $params['variables'];
318 $this->srvCache
= isset( $params['srvCache'] )
319 ?
$params['srvCache']
320 : new HashBagOStuff();
322 $this->profiler
= $params['profiler'];
323 $this->trxProfiler
= $params['trxProfiler'];
324 $this->connLogger
= $params['connLogger'];
325 $this->queryLogger
= $params['queryLogger'];
326 $this->errorLogger
= $params['errorLogger'];
327 $this->deprecationLogger
= $params['deprecationLogger'];
329 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
330 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
333 // Set initial dummy domain until open() sets the final DB/prefix
334 $this->currentDomain
= DatabaseDomain
::newUnspecified();
338 * Initialize the connection to the database over the wire (or to local files)
340 * @throws LogicException
341 * @throws InvalidArgumentException
342 * @throws DBConnectionError
345 final public function initConnection() {
346 if ( $this->isOpen() ) {
347 throw new LogicException( __METHOD__
. ': already connected.' );
349 // Establish the connection
350 $this->doInitConnection();
351 // Set the domain object after open() sets the relevant fields
352 if ( $this->dbName
!= '' ) {
353 // Domains with server scope but a table prefix are not used by IDatabase classes
354 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
359 * Actually connect to the database over the wire (or to local files)
361 * @throws InvalidArgumentException
362 * @throws DBConnectionError
365 protected function doInitConnection() {
366 if ( strlen( $this->connectionParams
['user'] ) ) {
368 $this->connectionParams
['host'],
369 $this->connectionParams
['user'],
370 $this->connectionParams
['password'],
371 $this->connectionParams
['dbname']
374 throw new InvalidArgumentException( "No database user provided." );
379 * Construct a Database subclass instance given a database type and parameters
381 * This also connects to the database immediately upon object construction
383 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
384 * @param array $p Parameter map with keys:
385 * - host : The hostname of the DB server
386 * - user : The name of the database user the client operates under
387 * - password : The password for the database user
388 * - dbname : The name of the database to use where queries do not specify one.
389 * The database must exist or an error might be thrown. Setting this to the empty string
390 * will avoid any such errors and make the handle have no implicit database scope. This is
391 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
392 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
393 * in which user names and such are defined, e.g. users are database-specific in Postgres.
394 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
395 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
396 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
397 * recognized in queries. This can be used in place of schemas for handle site farms.
398 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
399 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
400 * flag in place UNLESS this this database simply acts as a key/value store.
401 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
402 * 'mysqli' driver; the old one 'mysql' has been removed.
403 * - variables: Optional map of session variables to set after connecting. This can be
404 * used to adjust lock timeouts or encoding modes and the like.
405 * - connLogger: Optional PSR-3 logger interface instance.
406 * - queryLogger: Optional PSR-3 logger interface instance.
407 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
408 * These will be called in query(), using a simplified version of the SQL that also
409 * includes the agent as a SQL comment.
410 * - trxProfiler: Optional TransactionProfiler instance.
411 * - errorLogger: Optional callback that takes an Exception and logs it.
412 * - deprecationLogger: Optional callback that takes a string and logs it.
413 * - cliMode: Whether to consider the execution context that of a CLI script.
414 * - agent: Optional name used to identify the end-user in query profiling/logging.
415 * - srvCache: Optional BagOStuff instance to an APC-style cache.
416 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
417 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
418 * @return Database|null If the database driver or extension cannot be found
419 * @throws InvalidArgumentException If the database driver or extension cannot be found
422 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
423 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
425 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
426 // Resolve some defaults for b/c
427 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
428 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
429 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
430 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
431 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
432 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
433 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
434 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
435 $p['cliMode'] = isset( $p['cliMode'] )
437 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
438 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
439 if ( !isset( $p['connLogger'] ) ) {
440 $p['connLogger'] = new NullLogger();
442 if ( !isset( $p['queryLogger'] ) ) {
443 $p['queryLogger'] = new NullLogger();
445 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
446 if ( !isset( $p['trxProfiler'] ) ) {
447 $p['trxProfiler'] = new TransactionProfiler();
449 if ( !isset( $p['errorLogger'] ) ) {
450 $p['errorLogger'] = function ( Exception
$e ) {
451 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
454 if ( !isset( $p['deprecationLogger'] ) ) {
455 $p['deprecationLogger'] = function ( $msg ) {
456 trigger_error( $msg, E_USER_DEPRECATED
);
460 /** @var Database $conn */
461 $conn = new $class( $p );
462 if ( $connect == self
::NEW_CONNECTED
) {
463 $conn->initConnection();
473 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
474 * @param string|null $driver Optional name of a specific DB client driver
475 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
476 * @throws InvalidArgumentException
479 final public static function attributesFromType( $dbType, $driver = null ) {
480 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
482 $class = self
::getClass( $dbType, $driver );
484 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
488 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
489 * @param string|null $driver Optional name of a specific DB client driver
490 * @return string Database subclass name to use
491 * @throws InvalidArgumentException
493 private static function getClass( $dbType, $driver = null ) {
494 // For database types with built-in support, the below maps type to IDatabase
495 // implementations. For types with multipe driver implementations (PHP extensions),
496 // an array can be used, keyed by extension name. In case of an array, the
497 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
498 // we auto-detect the first available driver. For types without built-in support,
499 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
500 static $builtinTypes = [
501 'mssql' => DatabaseMssql
::class,
502 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
503 'sqlite' => DatabaseSqlite
::class,
504 'postgres' => DatabasePostgres
::class,
507 $dbType = strtolower( $dbType );
510 if ( isset( $builtinTypes[$dbType] ) ) {
511 $possibleDrivers = $builtinTypes[$dbType];
512 if ( is_string( $possibleDrivers ) ) {
513 $class = $possibleDrivers;
515 if ( (string)$driver !== '' ) {
516 if ( !isset( $possibleDrivers[$driver] ) ) {
517 throw new InvalidArgumentException( __METHOD__
.
518 " type '$dbType' does not support driver '{$driver}'" );
520 $class = $possibleDrivers[$driver];
523 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
524 if ( extension_loaded( $posDriver ) ) {
525 $class = $possibleClass;
532 $class = 'Database' . ucfirst( $dbType );
535 if ( $class === false ) {
536 throw new InvalidArgumentException( __METHOD__
.
537 " no viable database extension found for type '$dbType'" );
544 * @return array Map of (Database::ATTRIBUTE_* constant => value
547 protected static function getAttributes() {
552 * Set the PSR-3 logger interface to use for query logging. (The logger
553 * interfaces for connection logging and error logging can be set with the
556 * @param LoggerInterface $logger
558 public function setLogger( LoggerInterface
$logger ) {
559 $this->queryLogger
= $logger;
562 public function getServerInfo() {
563 return $this->getServerVersion();
566 public function bufferResults( $buffer = null ) {
567 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
568 if ( $buffer !== null ) {
570 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
571 : $this->setFlag( self
::DBO_NOBUFFER
);
577 public function trxLevel() {
578 return $this->trxLevel
;
581 public function trxTimestamp() {
582 return $this->trxLevel ?
$this->trxTimestamp
: null;
586 * @return int One of the STATUS_TRX_* class constants
589 public function trxStatus() {
590 return $this->trxStatus
;
593 public function tablePrefix( $prefix = null ) {
594 $old = $this->tablePrefix
;
595 if ( $prefix !== null ) {
596 $this->tablePrefix
= $prefix;
597 $this->currentDomain
= ( $this->dbName
!= '' )
598 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
599 : DatabaseDomain
::newUnspecified();
605 public function dbSchema( $schema = null ) {
606 $old = $this->schema
;
607 if ( $schema !== null ) {
608 $this->schema
= $schema;
614 public function getLBInfo( $name = null ) {
615 if ( is_null( $name ) ) {
616 return $this->lbInfo
;
618 if ( array_key_exists( $name, $this->lbInfo
) ) {
619 return $this->lbInfo
[$name];
626 public function setLBInfo( $name, $value = null ) {
627 if ( is_null( $value ) ) {
628 $this->lbInfo
= $name;
630 $this->lbInfo
[$name] = $value;
634 public function setLazyMasterHandle( IDatabase
$conn ) {
635 $this->lazyMasterHandle
= $conn;
639 * @return IDatabase|null
640 * @see setLazyMasterHandle()
643 protected function getLazyMasterHandle() {
644 return $this->lazyMasterHandle
;
647 public function implicitGroupby() {
651 public function implicitOrderby() {
655 public function lastQuery() {
656 return $this->lastQuery
;
659 public function doneWrites() {
660 return (bool)$this->lastWriteTime
;
663 public function lastDoneWrites() {
664 return $this->lastWriteTime ?
: false;
667 public function writesPending() {
668 return $this->trxLevel
&& $this->trxDoneWrites
;
671 public function writesOrCallbacksPending() {
672 return $this->trxLevel
&& (
673 $this->trxDoneWrites ||
674 $this->trxIdleCallbacks ||
675 $this->trxPreCommitCallbacks ||
676 $this->trxEndCallbacks
680 public function preCommitCallbacksPending() {
681 return $this->trxLevel
&& $this->trxPreCommitCallbacks
;
685 * @return string|null
687 final protected function getTransactionRoundId() {
688 // If transaction round participation is enabled, see if one is active
689 if ( $this->getFlag( self
::DBO_TRX
) ) {
690 $id = $this->getLBInfo( 'trxRoundId' );
692 return is_string( $id ) ?
$id : null;
698 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
699 if ( !$this->trxLevel
) {
701 } elseif ( !$this->trxDoneWrites
) {
706 case self
::ESTIMATE_DB_APPLY
:
708 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
709 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
710 // For omitted queries, make them count as something at least
711 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
712 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
715 default: // everything
716 return $this->trxWriteDuration
;
720 public function pendingWriteCallers() {
721 return $this->trxLevel ?
$this->trxWriteCallers
: [];
724 public function pendingWriteRowsAffected() {
725 return $this->trxWriteAffectedRows
;
729 * List the methods that have write queries or callbacks for the current transaction
731 * This method should not be used outside of Database/LoadBalancer
736 public function pendingWriteAndCallbackCallers() {
737 $fnames = $this->pendingWriteCallers();
739 $this->trxIdleCallbacks
,
740 $this->trxPreCommitCallbacks
,
741 $this->trxEndCallbacks
743 foreach ( $callbacks as $callback ) {
744 $fnames[] = $callback[1];
754 private function flatAtomicSectionList() {
755 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
756 return $accum === null ?
$v[0] : "$accum, " . $v[0];
760 public function isOpen() {
761 return $this->opened
;
764 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
765 if ( ( $flag & self
::DBO_IGNORE
) ) {
766 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
769 if ( $remember === self
::REMEMBER_PRIOR
) {
770 array_push( $this->priorFlags
, $this->flags
);
772 $this->flags |
= $flag;
775 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
776 if ( ( $flag & self
::DBO_IGNORE
) ) {
777 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
780 if ( $remember === self
::REMEMBER_PRIOR
) {
781 array_push( $this->priorFlags
, $this->flags
);
783 $this->flags
&= ~
$flag;
786 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
787 if ( !$this->priorFlags
) {
791 if ( $state === self
::RESTORE_INITIAL
) {
792 $this->flags
= reset( $this->priorFlags
);
793 $this->priorFlags
= [];
795 $this->flags
= array_pop( $this->priorFlags
);
799 public function getFlag( $flag ) {
800 return !!( $this->flags
& $flag );
804 * @param string $name Class field name
806 * @deprecated Since 1.28
808 public function getProperty( $name ) {
812 public function getDomainID() {
813 return $this->currentDomain
->getId();
816 final public function getWikiID() {
817 return $this->getDomainID();
821 * Get information about an index into an object
822 * @param string $table Table name
823 * @param string $index Index name
824 * @param string $fname Calling function name
825 * @return mixed Database-specific index description class or false if the index does not exist
827 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
830 * Wrapper for addslashes()
832 * @param string $s String to be slashed.
833 * @return string Slashed string.
835 abstract function strencode( $s );
838 * Set a custom error handler for logging errors during database connection
840 protected function installErrorHandler() {
841 $this->phpError
= false;
842 $this->htmlErrors
= ini_set( 'html_errors', '0' );
843 set_error_handler( [ $this, 'connectionErrorLogger' ] );
847 * Restore the previous error handler and return the last PHP error for this DB
849 * @return bool|string
851 protected function restoreErrorHandler() {
852 restore_error_handler();
853 if ( $this->htmlErrors
!== false ) {
854 ini_set( 'html_errors', $this->htmlErrors
);
857 return $this->getLastPHPError();
861 * @return string|bool Last PHP error for this DB (typically connection errors)
863 protected function getLastPHPError() {
864 if ( $this->phpError
) {
865 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
866 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
875 * Error handler for logging errors during database connection
876 * This method should not be used outside of Database classes
879 * @param string $errstr
881 public function connectionErrorLogger( $errno, $errstr ) {
882 $this->phpError
= $errstr;
886 * Create a log context to pass to PSR-3 logger functions.
888 * @param array $extras Additional data to add to context
891 protected function getLogContext( array $extras = [] ) {
894 'db_server' => $this->server
,
895 'db_name' => $this->dbName
,
896 'db_user' => $this->user
,
902 final public function close() {
903 $exception = null; // error to throw after disconnecting
906 // Resolve any dangling transaction first
907 if ( $this->trxLevel
) {
908 if ( $this->trxAtomicLevels
) {
909 // Cannot let incomplete atomic sections be committed
910 $levels = $this->flatAtomicSectionList();
911 $exception = new DBUnexpectedError(
913 __METHOD__
. ": atomic sections $levels are still open."
915 } elseif ( $this->trxAutomatic
) {
916 // Only the connection manager can commit non-empty DBO_TRX transactions
917 if ( $this->writesOrCallbacksPending() ) {
918 $exception = new DBUnexpectedError(
921 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
924 } elseif ( $this->trxLevel
) {
925 // Commit explicit transactions as if this was commit()
926 $this->queryLogger
->warning(
927 __METHOD__
. ": writes or callbacks still pending.",
928 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
932 if ( $this->trxEndCallbacksSuppressed
) {
933 $exception = $exception ?
: new DBUnexpectedError(
935 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
939 // Commit or rollback the changes and run any callbacks as needed
940 if ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& !$exception ) {
943 $this->trxAutomatic ? self
::FLUSHING_INTERNAL
: self
::FLUSHING_ONE
946 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
950 // Close the actual connection in the binding handle
951 $closed = $this->closeConnection();
954 $closed = true; // already closed; nothing to do
957 $this->opened
= false;
959 // Throw any unexpected errors after having disconnected
960 if ( $exception instanceof Exception
) {
964 // Sanity check that no callbacks are dangling
965 $fnames = $this->pendingWriteAndCallbackCallers();
967 throw new RuntimeException(
968 "Transaction callbacks are still pending:\n" . implode( ', ', $fnames )
976 * Make sure isOpen() returns true as a sanity check
978 * @throws DBUnexpectedError
980 protected function assertOpen() {
981 if ( !$this->isOpen() ) {
982 throw new DBUnexpectedError( $this, "DB connection was already closed." );
987 * Closes underlying database connection
989 * @return bool Whether connection was closed successfully
991 abstract protected function closeConnection();
994 * @deprecated since 1.32
995 * @param string $error Fallback message, if none is given by DB
996 * @throws DBConnectionError
998 public function reportConnectionError( $error = 'Unknown error' ) {
999 call_user_func( $this->deprecationLogger
, 'Use of ' . __METHOD__
. ' is deprecated.' );
1000 throw new DBConnectionError( $this, $this->lastError() ?
: $error );
1004 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
1006 * This might return things, such as mysqli_result, that do not formally implement
1007 * IResultWrapper, but nonetheless implement all of its methods correctly
1009 * @param string $sql SQL query.
1010 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
1012 abstract protected function doQuery( $sql );
1015 * Determine whether a query writes to the DB.
1016 * Should return true if unsure.
1018 * @param string $sql
1021 protected function isWriteQuery( $sql ) {
1023 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1027 * @param string $sql
1028 * @return string|null
1030 protected function getQueryVerb( $sql ) {
1031 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1035 * Determine whether a SQL statement is sensitive to isolation level.
1036 * A SQL statement is considered transactable if its result could vary
1037 * depending on the transaction isolation level. Operational commands
1038 * such as 'SET' and 'SHOW' are not considered to be transactable.
1040 * @param string $sql
1043 protected function isTransactableQuery( $sql ) {
1045 $this->getQueryVerb( $sql ),
1046 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1052 * @param string $sql A SQL query
1053 * @return bool Whether $sql is SQL for TEMPORARY table operation
1055 protected function registerTempTableOperation( $sql ) {
1057 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1061 $this->sessionTempTables
[$matches[1]] = 1;
1064 } elseif ( preg_match(
1065 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1069 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1070 unset( $this->sessionTempTables
[$matches[1]] );
1073 } elseif ( preg_match(
1074 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1078 return isset( $this->sessionTempTables
[$matches[1]] );
1079 } elseif ( preg_match(
1080 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1084 return isset( $this->sessionTempTables
[$matches[1]] );
1090 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1091 $this->assertTransactionStatus( $sql, $fname );
1093 # Avoid fatals if close() was called
1094 $this->assertOpen();
1096 $priorWritesPending = $this->writesOrCallbacksPending();
1097 $this->lastQuery
= $sql;
1099 $isWrite = $this->isWriteQuery( $sql );
1101 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1103 $isNonTempWrite = false;
1107 if ( $this->getLBInfo( 'replica' ) === true ) {
1110 'Write operations are not allowed on replica database connections.'
1113 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1114 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1115 $reason = $this->getReadOnlyReason();
1116 if ( $reason !== false ) {
1117 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1119 # Set a flag indicating that writes have been done
1120 $this->lastWriteTime
= microtime( true );
1123 # Add trace comment to the begin of the sql string, right after the operator.
1124 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1125 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1127 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1128 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1129 && $this->isTransactableQuery( $sql )
1131 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1132 $this->trxAutomatic
= true;
1135 # Keep track of whether the transaction has write queries pending
1136 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1137 $this->trxDoneWrites
= true;
1138 $this->trxProfiler
->transactionWritingIn(
1139 $this->server
, $this->dbName
, $this->trxShortId
);
1142 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1143 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1146 # Send the query to the server and fetch any corresponding errors
1147 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1148 $lastError = $this->lastError();
1149 $lastErrno = $this->lastErrno();
1151 # Try reconnecting if the connection was lost
1152 if ( $ret === false && $this->wasConnectionLoss() ) {
1153 # Check if any meaningful session state was lost
1154 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1155 # Update session state tracking and try to restore the connection
1156 $reconnected = $this->replaceLostConnection( __METHOD__
);
1157 # Silently resend the query to the server if it is safe and possible
1158 if ( $reconnected && $recoverable ) {
1159 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1160 $lastError = $this->lastError();
1161 $lastErrno = $this->lastErrno();
1163 if ( $ret === false && $this->wasConnectionLoss() ) {
1164 # Query probably causes disconnects; reconnect and do not re-run it
1165 $this->replaceLostConnection( __METHOD__
);
1170 if ( $ret === false ) {
1171 if ( $this->trxLevel
) {
1172 if ( $this->wasKnownStatementRollbackError() ) {
1173 # We're ignoring an error that caused just the current query to be aborted.
1174 # But log the cause so we can log a deprecation notice if a caller actually
1176 $this->trxStatusIgnoredCause
= [ $lastError, $lastErrno, $fname ];
1178 # Either the query was aborted or all queries after BEGIN where aborted.
1179 # In the first case, the only options going forward are (a) ROLLBACK, or
1180 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1181 # option is ROLLBACK, since the snapshots would have been released.
1182 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1183 $this->trxStatusCause
=
1184 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1185 $tempIgnore = false; // cannot recover
1186 $this->trxStatusIgnoredCause
= null;
1190 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1193 return $this->resultObject( $ret );
1197 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1199 * @param string $sql Original SQL query
1200 * @param string $commentedSql SQL query with debugging/trace comment
1201 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1202 * @param string $fname Name of the calling function
1203 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1204 * object for a successful read query, or false on failure
1206 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1207 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1208 # generalizeSQL() will probably cut down the query to reasonable
1209 # logging size most of the time. The substr is really just a sanity check.
1211 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1213 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1216 # Include query transaction state
1217 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1219 $startTime = microtime( true );
1220 if ( $this->profiler
) {
1221 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1223 $this->affectedRowCount
= null;
1224 $ret = $this->doQuery( $commentedSql );
1225 $this->affectedRowCount
= $this->affectedRows();
1226 if ( $this->profiler
) {
1227 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1229 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1231 unset( $queryProfSection ); // profile out (if set)
1233 if ( $ret !== false ) {
1234 $this->lastPing
= $startTime;
1235 if ( $isWrite && $this->trxLevel
) {
1236 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1237 $this->trxWriteCallers
[] = $fname;
1241 if ( $sql === self
::PING_QUERY
) {
1242 $this->rttEstimate
= $queryRuntime;
1245 $this->trxProfiler
->recordQueryCompletion(
1246 $queryProf, $startTime, $isWrite, $this->affectedRows()
1248 $this->queryLogger
->debug( $sql, [
1250 'master' => $isMaster,
1251 'runtime' => $queryRuntime,
1258 * Update the estimated run-time of a query, not counting large row lock times
1260 * LoadBalancer can be set to rollback transactions that will create huge replication
1261 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1262 * queries, like inserting a row can take a long time due to row locking. This method
1263 * uses some simple heuristics to discount those cases.
1265 * @param string $sql A SQL write query
1266 * @param float $runtime Total runtime, including RTT
1267 * @param int $affected Affected row count
1269 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1270 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1271 $indicativeOfReplicaRuntime = true;
1272 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1273 $verb = $this->getQueryVerb( $sql );
1274 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1275 if ( $verb === 'INSERT' ) {
1276 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1277 } elseif ( $verb === 'REPLACE' ) {
1278 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1282 $this->trxWriteDuration +
= $runtime;
1283 $this->trxWriteQueryCount +
= 1;
1284 $this->trxWriteAffectedRows +
= $affected;
1285 if ( $indicativeOfReplicaRuntime ) {
1286 $this->trxWriteAdjDuration +
= $runtime;
1287 $this->trxWriteAdjQueryCount +
= 1;
1292 * @param string $sql
1293 * @param string $fname
1294 * @throws DBTransactionStateError
1296 private function assertTransactionStatus( $sql, $fname ) {
1297 if ( $this->getQueryVerb( $sql ) === 'ROLLBACK' ) { // transaction/savepoint
1301 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1302 throw new DBTransactionStateError(
1304 "Cannot execute query from $fname while transaction status is ERROR.",
1306 $this->trxStatusCause
1308 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1309 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1310 call_user_func( $this->deprecationLogger
,
1311 "Caller from $fname ignored an error originally raised from $iFname: " .
1312 "[$iLastErrno] $iLastError"
1314 $this->trxStatusIgnoredCause
= null;
1319 * Determine whether or not it is safe to retry queries after a database
1320 * connection is lost
1322 * @param string $sql SQL query
1323 * @param bool $priorWritesPending Whether there is a transaction open with
1324 * possible write queries or transaction pre-commit/idle callbacks
1325 * waiting on it to finish.
1326 * @return bool True if it is safe to retry the query, false otherwise
1328 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1329 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1330 # Dropped connections also mean that named locks are automatically released.
1331 # Only allow error suppression in autocommit mode or when the lost transaction
1332 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1333 if ( $this->namedLocksHeld
) {
1334 return false; // possible critical section violation
1335 } elseif ( $this->sessionTempTables
) {
1336 return false; // tables might be queried latter
1337 } elseif ( $sql === 'COMMIT' ) {
1338 return !$priorWritesPending; // nothing written anyway? (T127428)
1339 } elseif ( $sql === 'ROLLBACK' ) {
1340 return true; // transaction lost...which is also what was requested :)
1341 } elseif ( $this->explicitTrxActive() ) {
1342 return false; // don't drop atomocity and explicit snapshots
1343 } elseif ( $priorWritesPending ) {
1344 return false; // prior writes lost from implicit transaction
1351 * Clean things up after session (and thus transaction) loss
1353 private function handleSessionLoss() {
1354 // Clean up tracking of session-level things...
1355 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1356 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1357 $this->sessionTempTables
= [];
1358 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1359 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1360 $this->namedLocksHeld
= [];
1361 // Session loss implies transaction loss
1362 $this->handleTransactionLoss();
1366 * Clean things up after transaction loss
1368 private function handleTransactionLoss() {
1369 $this->trxLevel
= 0;
1370 $this->trxAtomicCounter
= 0;
1371 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1372 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1374 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1375 // If callback suppression is set then the array will remain unhandled.
1376 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1377 } catch ( Exception
$ex ) {
1378 // Already logged; move on...
1381 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1382 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1383 } catch ( Exception
$ex ) {
1384 // Already logged; move on...
1389 * Checks whether the cause of the error is detected to be a timeout.
1391 * It returns false by default, and not all engines support detecting this yet.
1392 * If this returns false, it will be treated as a generic query error.
1394 * @param string $error Error text
1395 * @param int $errno Error number
1398 protected function wasQueryTimeout( $error, $errno ) {
1403 * Report a query error. Log the error, and if neither the object ignore
1404 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1406 * @param string $error
1408 * @param string $sql
1409 * @param string $fname
1410 * @param bool $tempIgnore
1411 * @throws DBQueryError
1413 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1414 if ( $tempIgnore ) {
1415 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1417 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1424 * @param string $error
1425 * @param string|int $errno
1426 * @param string $sql
1427 * @param string $fname
1430 private function makeQueryException( $error, $errno, $sql, $fname ) {
1431 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1432 $this->queryLogger
->error(
1433 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1434 $this->getLogContext( [
1435 'method' => __METHOD__
,
1438 'sql1line' => $sql1line,
1442 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1443 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1444 if ( $wasQueryTimeout ) {
1445 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1447 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1453 public function freeResult( $res ) {
1456 public function selectField(
1457 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1459 if ( $var === '*' ) { // sanity
1460 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1463 if ( !is_array( $options ) ) {
1464 $options = [ $options ];
1467 $options['LIMIT'] = 1;
1469 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1470 if ( $res === false ||
!$this->numRows( $res ) ) {
1474 $row = $this->fetchRow( $res );
1476 if ( $row !== false ) {
1477 return reset( $row );
1483 public function selectFieldValues(
1484 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1486 if ( $var === '*' ) { // sanity
1487 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1488 } elseif ( !is_string( $var ) ) { // sanity
1489 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1492 if ( !is_array( $options ) ) {
1493 $options = [ $options ];
1496 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1497 if ( $res === false ) {
1502 foreach ( $res as $row ) {
1503 $values[] = $row->$var;
1510 * Returns an optional USE INDEX clause to go after the table, and a
1511 * string to go at the end of the query.
1513 * @param array $options Associative array of options to be turned into
1514 * an SQL query, valid keys are listed in the function.
1516 * @see Database::select()
1518 protected function makeSelectOptions( $options ) {
1519 $preLimitTail = $postLimitTail = '';
1524 foreach ( $options as $key => $option ) {
1525 if ( is_numeric( $key ) ) {
1526 $noKeyOptions[$option] = true;
1530 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1532 $preLimitTail .= $this->makeOrderBy( $options );
1534 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1535 $postLimitTail .= ' FOR UPDATE';
1538 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1539 $postLimitTail .= ' LOCK IN SHARE MODE';
1542 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1543 $startOpts .= 'DISTINCT';
1546 # Various MySQL extensions
1547 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1548 $startOpts .= ' /*! STRAIGHT_JOIN */';
1551 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1552 $startOpts .= ' HIGH_PRIORITY';
1555 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1556 $startOpts .= ' SQL_BIG_RESULT';
1559 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1560 $startOpts .= ' SQL_BUFFER_RESULT';
1563 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1564 $startOpts .= ' SQL_SMALL_RESULT';
1567 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1568 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1571 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1572 $startOpts .= ' SQL_CACHE';
1575 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1576 $startOpts .= ' SQL_NO_CACHE';
1579 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1580 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1584 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1585 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1590 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1594 * Returns an optional GROUP BY with an optional HAVING
1596 * @param array $options Associative array of options
1598 * @see Database::select()
1601 protected function makeGroupByWithHaving( $options ) {
1603 if ( isset( $options['GROUP BY'] ) ) {
1604 $gb = is_array( $options['GROUP BY'] )
1605 ?
implode( ',', $options['GROUP BY'] )
1606 : $options['GROUP BY'];
1607 $sql .= ' GROUP BY ' . $gb;
1609 if ( isset( $options['HAVING'] ) ) {
1610 $having = is_array( $options['HAVING'] )
1611 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1612 : $options['HAVING'];
1613 $sql .= ' HAVING ' . $having;
1620 * Returns an optional ORDER BY
1622 * @param array $options Associative array of options
1624 * @see Database::select()
1627 protected function makeOrderBy( $options ) {
1628 if ( isset( $options['ORDER BY'] ) ) {
1629 $ob = is_array( $options['ORDER BY'] )
1630 ?
implode( ',', $options['ORDER BY'] )
1631 : $options['ORDER BY'];
1633 return ' ORDER BY ' . $ob;
1639 public function select(
1640 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1642 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1644 return $this->query( $sql, $fname );
1647 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1648 $options = [], $join_conds = []
1650 if ( is_array( $vars ) ) {
1651 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1656 $options = (array)$options;
1657 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1658 ?
$options['USE INDEX']
1661 isset( $options['IGNORE INDEX'] ) &&
1662 is_array( $options['IGNORE INDEX'] )
1664 ?
$options['IGNORE INDEX']
1668 $this->selectOptionsIncludeLocking( $options ) &&
1669 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1671 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1672 // functions. Discourage use of such queries to encourage compatibility.
1674 $this->deprecationLogger
,
1675 __METHOD__
. ": aggregation used with a locking SELECT ($fname)."
1679 if ( is_array( $table ) ) {
1681 $this->tableNamesWithIndexClauseOrJOIN(
1682 $table, $useIndexes, $ignoreIndexes, $join_conds );
1683 } elseif ( $table != '' ) {
1685 $this->tableNamesWithIndexClauseOrJOIN(
1686 [ $table ], $useIndexes, $ignoreIndexes, [] );
1691 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1692 $this->makeSelectOptions( $options );
1694 if ( is_array( $conds ) ) {
1695 $conds = $this->makeList( $conds, self
::LIST_AND
);
1698 if ( $conds === null ||
$conds === false ) {
1699 $this->queryLogger
->warning(
1703 . ' with incorrect parameters: $conds must be a string or an array'
1708 if ( $conds === '' ) {
1709 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1710 } elseif ( is_string( $conds ) ) {
1711 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1712 "WHERE $conds $preLimitTail";
1714 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1717 if ( isset( $options['LIMIT'] ) ) {
1718 $sql = $this->limitResult( $sql, $options['LIMIT'],
1719 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1721 $sql = "$sql $postLimitTail";
1723 if ( isset( $options['EXPLAIN'] ) ) {
1724 $sql = 'EXPLAIN ' . $sql;
1730 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1731 $options = [], $join_conds = []
1733 $options = (array)$options;
1734 $options['LIMIT'] = 1;
1735 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1737 if ( $res === false ) {
1741 if ( !$this->numRows( $res ) ) {
1745 $obj = $this->fetchObject( $res );
1750 public function estimateRowCount(
1751 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1753 $conds = $this->normalizeConditions( $conds, $fname );
1754 $column = $this->extractSingleFieldFromList( $var );
1755 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1756 $conds[] = "$column IS NOT NULL";
1759 $res = $this->select(
1760 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1762 $row = $res ?
$this->fetchRow( $res ) : [];
1764 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1767 public function selectRowCount(
1768 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1770 $conds = $this->normalizeConditions( $conds, $fname );
1771 $column = $this->extractSingleFieldFromList( $var );
1772 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1773 $conds[] = "$column IS NOT NULL";
1776 $res = $this->select(
1778 'tmp_count' => $this->buildSelectSubquery(
1787 [ 'rowcount' => 'COUNT(*)' ],
1791 $row = $res ?
$this->fetchRow( $res ) : [];
1793 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1797 * @param string|array $options
1800 private function selectOptionsIncludeLocking( $options ) {
1801 $options = (array)$options;
1802 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1803 if ( in_array( $lock, $options, true ) ) {
1812 * @param array|string $fields
1813 * @param array|string $options
1816 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1817 foreach ( (array)$options as $key => $value ) {
1818 if ( is_string( $key ) ) {
1819 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1822 } elseif ( is_string( $value ) ) {
1823 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1829 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1830 foreach ( (array)$fields as $field ) {
1831 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1840 * @param array|string $conds
1841 * @param string $fname
1844 final protected function normalizeConditions( $conds, $fname ) {
1845 if ( $conds === null ||
$conds === false ) {
1846 $this->queryLogger
->warning(
1850 . ' with incorrect parameters: $conds must be a string or an array'
1855 if ( !is_array( $conds ) ) {
1856 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1863 * @param array|string $var Field parameter in the style of select()
1864 * @return string|null Column name or null; ignores aliases
1865 * @throws DBUnexpectedError Errors out if multiple columns are given
1867 final protected function extractSingleFieldFromList( $var ) {
1868 if ( is_array( $var ) ) {
1871 } elseif ( count( $var ) == 1 ) {
1872 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1874 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1884 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1885 * It's only slightly flawed. Don't use for anything important.
1887 * @param string $sql A SQL Query
1891 protected static function generalizeSQL( $sql ) {
1892 # This does the same as the regexp below would do, but in such a way
1893 # as to avoid crashing php on some large strings.
1894 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1896 $sql = str_replace( "\\\\", '', $sql );
1897 $sql = str_replace( "\\'", '', $sql );
1898 $sql = str_replace( "\\\"", '', $sql );
1899 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1900 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1902 # All newlines, tabs, etc replaced by single space
1903 $sql = preg_replace( '/\s+/', ' ', $sql );
1906 # except the ones surrounded by characters, e.g. l10n
1907 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1908 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1913 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1914 $info = $this->fieldInfo( $table, $field );
1919 public function indexExists( $table, $index, $fname = __METHOD__
) {
1920 if ( !$this->tableExists( $table ) ) {
1924 $info = $this->indexInfo( $table, $index, $fname );
1925 if ( is_null( $info ) ) {
1928 return $info !== false;
1932 public function tableExists( $table, $fname = __METHOD__
) {
1933 $tableRaw = $this->tableName( $table, 'raw' );
1934 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1935 return true; // already known to exist
1938 $table = $this->tableName( $table );
1939 $ignoreErrors = true;
1940 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1945 public function indexUnique( $table, $index ) {
1946 $indexInfo = $this->indexInfo( $table, $index );
1948 if ( !$indexInfo ) {
1952 return !$indexInfo[0]->Non_unique
;
1956 * Helper for Database::insert().
1958 * @param array $options
1961 protected function makeInsertOptions( $options ) {
1962 return implode( ' ', $options );
1965 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1966 # No rows to insert, easy just return now
1967 if ( !count( $a ) ) {
1971 $table = $this->tableName( $table );
1973 if ( !is_array( $options ) ) {
1974 $options = [ $options ];
1978 if ( isset( $options['fileHandle'] ) ) {
1979 $fh = $options['fileHandle'];
1981 $options = $this->makeInsertOptions( $options );
1983 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1985 $keys = array_keys( $a[0] );
1988 $keys = array_keys( $a );
1991 $sql = 'INSERT ' . $options .
1992 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1996 foreach ( $a as $row ) {
2002 $sql .= '(' . $this->makeList( $row ) . ')';
2005 $sql .= '(' . $this->makeList( $a ) . ')';
2008 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2010 } elseif ( $fh !== null ) {
2014 return (bool)$this->query( $sql, $fname );
2018 * Make UPDATE options array for Database::makeUpdateOptions
2020 * @param array $options
2023 protected function makeUpdateOptionsArray( $options ) {
2024 if ( !is_array( $options ) ) {
2025 $options = [ $options ];
2030 if ( in_array( 'IGNORE', $options ) ) {
2038 * Make UPDATE options for the Database::update function
2040 * @param array $options The options passed to Database::update
2043 protected function makeUpdateOptions( $options ) {
2044 $opts = $this->makeUpdateOptionsArray( $options );
2046 return implode( ' ', $opts );
2049 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2050 $table = $this->tableName( $table );
2051 $opts = $this->makeUpdateOptions( $options );
2052 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2054 if ( $conds !== [] && $conds !== '*' ) {
2055 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2058 return (bool)$this->query( $sql, $fname );
2061 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2062 if ( !is_array( $a ) ) {
2063 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2069 foreach ( $a as $field => $value ) {
2071 if ( $mode == self
::LIST_AND
) {
2073 } elseif ( $mode == self
::LIST_OR
) {
2082 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2083 $list .= "($value)";
2084 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2087 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2089 // Remove null from array to be handled separately if found
2090 $includeNull = false;
2091 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2092 $includeNull = true;
2093 unset( $value[$nullKey] );
2095 if ( count( $value ) == 0 && !$includeNull ) {
2096 throw new InvalidArgumentException(
2097 __METHOD__
. ": empty input for field $field" );
2098 } elseif ( count( $value ) == 0 ) {
2099 // only check if $field is null
2100 $list .= "$field IS NULL";
2102 // IN clause contains at least one valid element
2103 if ( $includeNull ) {
2104 // Group subconditions to ensure correct precedence
2107 if ( count( $value ) == 1 ) {
2108 // Special-case single values, as IN isn't terribly efficient
2109 // Don't necessarily assume the single key is 0; we don't
2110 // enforce linear numeric ordering on other arrays here.
2111 $value = array_values( $value )[0];
2112 $list .= $field . " = " . $this->addQuotes( $value );
2114 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2116 // if null present in array, append IS NULL
2117 if ( $includeNull ) {
2118 $list .= " OR $field IS NULL)";
2121 } elseif ( $value === null ) {
2122 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2123 $list .= "$field IS ";
2124 } elseif ( $mode == self
::LIST_SET
) {
2125 $list .= "$field = ";
2130 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2132 $list .= "$field = ";
2134 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2141 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2144 foreach ( $data as $base => $sub ) {
2145 if ( count( $sub ) ) {
2146 $conds[] = $this->makeList(
2147 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2153 return $this->makeList( $conds, self
::LIST_OR
);
2155 // Nothing to search for...
2160 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2164 public function bitNot( $field ) {
2168 public function bitAnd( $fieldLeft, $fieldRight ) {
2169 return "($fieldLeft & $fieldRight)";
2172 public function bitOr( $fieldLeft, $fieldRight ) {
2173 return "($fieldLeft | $fieldRight)";
2176 public function buildConcat( $stringList ) {
2177 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2180 public function buildGroupConcatField(
2181 $delim, $table, $field, $conds = '', $join_conds = []
2183 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2185 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2188 public function buildSubstring( $input, $startPosition, $length = null ) {
2189 $this->assertBuildSubstringParams( $startPosition, $length );
2190 $functionBody = "$input FROM $startPosition";
2191 if ( $length !== null ) {
2192 $functionBody .= " FOR $length";
2194 return 'SUBSTRING(' . $functionBody . ')';
2198 * Check type and bounds for parameters to self::buildSubstring()
2200 * All supported databases have substring functions that behave the same for
2201 * positive $startPosition and non-negative $length, but behaviors differ when
2202 * given 0 or negative $startPosition or negative $length. The simplest
2203 * solution to that is to just forbid those values.
2205 * @param int $startPosition
2206 * @param int|null $length
2209 protected function assertBuildSubstringParams( $startPosition, $length ) {
2210 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2211 throw new InvalidArgumentException(
2212 '$startPosition must be a positive integer'
2215 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2216 throw new InvalidArgumentException(
2217 '$length must be null or an integer greater than or equal to 0'
2222 public function buildStringCast( $field ) {
2226 public function buildIntegerCast( $field ) {
2227 return 'CAST( ' . $field . ' AS INTEGER )';
2230 public function buildSelectSubquery(
2231 $table, $vars, $conds = '', $fname = __METHOD__
,
2232 $options = [], $join_conds = []
2234 return new Subquery(
2235 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2239 public function databasesAreIndependent() {
2243 public function selectDB( $db ) {
2244 # Stub. Shouldn't cause serious problems if it's not overridden, but
2245 # if your database engine supports a concept similar to MySQL's
2246 # databases you may as well.
2247 $this->dbName
= $db;
2252 public function getDBname() {
2253 return $this->dbName
;
2256 public function getServer() {
2257 return $this->server
;
2260 public function tableName( $name, $format = 'quoted' ) {
2261 if ( $name instanceof Subquery
) {
2262 throw new DBUnexpectedError(
2264 __METHOD__
. ': got Subquery instance when expecting a string.'
2268 # Skip the entire process when we have a string quoted on both ends.
2269 # Note that we check the end so that we will still quote any use of
2270 # use of `database`.table. But won't break things if someone wants
2271 # to query a database table with a dot in the name.
2272 if ( $this->isQuotedIdentifier( $name ) ) {
2276 # Lets test for any bits of text that should never show up in a table
2277 # name. Basically anything like JOIN or ON which are actually part of
2278 # SQL queries, but may end up inside of the table value to combine
2279 # sql. Such as how the API is doing.
2280 # Note that we use a whitespace test rather than a \b test to avoid
2281 # any remote case where a word like on may be inside of a table name
2282 # surrounded by symbols which may be considered word breaks.
2283 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2284 $this->queryLogger
->warning(
2285 __METHOD__
. ": use of subqueries is not supported this way.",
2286 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2292 # Split database and table into proper variables.
2293 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2295 # Quote $table and apply the prefix if not quoted.
2296 # $tableName might be empty if this is called from Database::replaceVars()
2297 $tableName = "{$prefix}{$table}";
2298 if ( $format === 'quoted'
2299 && !$this->isQuotedIdentifier( $tableName )
2300 && $tableName !== ''
2302 $tableName = $this->addIdentifierQuotes( $tableName );
2305 # Quote $schema and $database and merge them with the table name if needed
2306 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2307 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2313 * Get the table components needed for a query given the currently selected database
2315 * @param string $name Table name in the form of db.schema.table, db.table, or table
2316 * @return array (DB name or "" for default, schema name, table prefix, table name)
2318 protected function qualifiedTableComponents( $name ) {
2319 # We reverse the explode so that database.table and table both output the correct table.
2320 $dbDetails = explode( '.', $name, 3 );
2321 if ( count( $dbDetails ) == 3 ) {
2322 list( $database, $schema, $table ) = $dbDetails;
2323 # We don't want any prefix added in this case
2325 } elseif ( count( $dbDetails ) == 2 ) {
2326 list( $database, $table ) = $dbDetails;
2327 # We don't want any prefix added in this case
2329 # In dbs that support it, $database may actually be the schema
2330 # but that doesn't affect any of the functionality here
2333 list( $table ) = $dbDetails;
2334 if ( isset( $this->tableAliases
[$table] ) ) {
2335 $database = $this->tableAliases
[$table]['dbname'];
2336 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2337 ?
$this->tableAliases
[$table]['schema']
2339 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2340 ?
$this->tableAliases
[$table]['prefix']
2341 : $this->tablePrefix
;
2344 $schema = $this->schema
; # Default schema
2345 $prefix = $this->tablePrefix
; # Default prefix
2349 return [ $database, $schema, $prefix, $table ];
2353 * @param string|null $namespace Database or schema
2354 * @param string $relation Name of table, view, sequence, etc...
2355 * @param string $format One of (raw, quoted)
2356 * @return string Relation name with quoted and merged $namespace as needed
2358 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2359 if ( strlen( $namespace ) ) {
2360 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2361 $namespace = $this->addIdentifierQuotes( $namespace );
2363 $relation = $namespace . '.' . $relation;
2369 public function tableNames() {
2370 $inArray = func_get_args();
2373 foreach ( $inArray as $name ) {
2374 $retVal[$name] = $this->tableName( $name );
2380 public function tableNamesN() {
2381 $inArray = func_get_args();
2384 foreach ( $inArray as $name ) {
2385 $retVal[] = $this->tableName( $name );
2392 * Get an aliased table name
2394 * This returns strings like "tableName AS newTableName" for aliased tables
2395 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2397 * @see Database::tableName()
2398 * @param string|Subquery $table Table name or object with a 'sql' field
2399 * @param string|bool $alias Table alias (optional)
2400 * @return string SQL name for aliased table. Will not alias a table to its own name
2402 protected function tableNameWithAlias( $table, $alias = false ) {
2403 if ( is_string( $table ) ) {
2404 $quotedTable = $this->tableName( $table );
2405 } elseif ( $table instanceof Subquery
) {
2406 $quotedTable = (string)$table;
2408 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2411 if ( !strlen( $alias ) ||
$alias === $table ) {
2412 if ( $table instanceof Subquery
) {
2413 throw new InvalidArgumentException( "Subquery table missing alias." );
2416 return $quotedTable;
2418 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2423 * Gets an array of aliased table names
2425 * @param array $tables [ [alias] => table ]
2426 * @return string[] See tableNameWithAlias()
2428 protected function tableNamesWithAlias( $tables ) {
2430 foreach ( $tables as $alias => $table ) {
2431 if ( is_numeric( $alias ) ) {
2434 $retval[] = $this->tableNameWithAlias( $table, $alias );
2441 * Get an aliased field name
2442 * e.g. fieldName AS newFieldName
2444 * @param string $name Field name
2445 * @param string|bool $alias Alias (optional)
2446 * @return string SQL name for aliased field. Will not alias a field to its own name
2448 protected function fieldNameWithAlias( $name, $alias = false ) {
2449 if ( !$alias ||
(string)$alias === (string)$name ) {
2452 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2457 * Gets an array of aliased field names
2459 * @param array $fields [ [alias] => field ]
2460 * @return string[] See fieldNameWithAlias()
2462 protected function fieldNamesWithAlias( $fields ) {
2464 foreach ( $fields as $alias => $field ) {
2465 if ( is_numeric( $alias ) ) {
2468 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2475 * Get the aliased table name clause for a FROM clause
2476 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2478 * @param array $tables ( [alias] => table )
2479 * @param array $use_index Same as for select()
2480 * @param array $ignore_index Same as for select()
2481 * @param array $join_conds Same as for select()
2484 protected function tableNamesWithIndexClauseOrJOIN(
2485 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2489 $use_index = (array)$use_index;
2490 $ignore_index = (array)$ignore_index;
2491 $join_conds = (array)$join_conds;
2493 foreach ( $tables as $alias => $table ) {
2494 if ( !is_string( $alias ) ) {
2495 // No alias? Set it equal to the table name
2499 if ( is_array( $table ) ) {
2500 // A parenthesized group
2501 if ( count( $table ) > 1 ) {
2502 $joinedTable = '(' .
2503 $this->tableNamesWithIndexClauseOrJOIN(
2504 $table, $use_index, $ignore_index, $join_conds ) . ')';
2507 $innerTable = reset( $table );
2508 $innerAlias = key( $table );
2509 $joinedTable = $this->tableNameWithAlias(
2511 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2515 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2518 // Is there a JOIN clause for this table?
2519 if ( isset( $join_conds[$alias] ) ) {
2520 list( $joinType, $conds ) = $join_conds[$alias];
2521 $tableClause = $joinType;
2522 $tableClause .= ' ' . $joinedTable;
2523 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2524 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2526 $tableClause .= ' ' . $use;
2529 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2530 $ignore = $this->ignoreIndexClause(
2531 implode( ',', (array)$ignore_index[$alias] ) );
2532 if ( $ignore != '' ) {
2533 $tableClause .= ' ' . $ignore;
2536 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2538 $tableClause .= ' ON (' . $on . ')';
2541 $retJOIN[] = $tableClause;
2542 } elseif ( isset( $use_index[$alias] ) ) {
2543 // Is there an INDEX clause for this table?
2544 $tableClause = $joinedTable;
2545 $tableClause .= ' ' . $this->useIndexClause(
2546 implode( ',', (array)$use_index[$alias] )
2549 $ret[] = $tableClause;
2550 } elseif ( isset( $ignore_index[$alias] ) ) {
2551 // Is there an INDEX clause for this table?
2552 $tableClause = $joinedTable;
2553 $tableClause .= ' ' . $this->ignoreIndexClause(
2554 implode( ',', (array)$ignore_index[$alias] )
2557 $ret[] = $tableClause;
2559 $tableClause = $joinedTable;
2561 $ret[] = $tableClause;
2565 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2566 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2567 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2569 // Compile our final table clause
2570 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2574 * Allows for index remapping in queries where this is not consistent across DBMS
2576 * @param string $index
2579 protected function indexName( $index ) {
2580 return isset( $this->indexAliases
[$index] )
2581 ?
$this->indexAliases
[$index]
2585 public function addQuotes( $s ) {
2586 if ( $s instanceof Blob
) {
2589 if ( $s === null ) {
2591 } elseif ( is_bool( $s ) ) {
2594 # This will also quote numeric values. This should be harmless,
2595 # and protects against weird problems that occur when they really
2596 # _are_ strings such as article titles and string->number->string
2597 # conversion is not 1:1.
2598 return "'" . $this->strencode( $s ) . "'";
2603 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2604 * MySQL uses `backticks` while basically everything else uses double quotes.
2605 * Since MySQL is the odd one out here the double quotes are our generic
2606 * and we implement backticks in DatabaseMysqlBase.
2611 public function addIdentifierQuotes( $s ) {
2612 return '"' . str_replace( '"', '""', $s ) . '"';
2616 * Returns if the given identifier looks quoted or not according to
2617 * the database convention for quoting identifiers .
2619 * @note Do not use this to determine if untrusted input is safe.
2620 * A malicious user can trick this function.
2621 * @param string $name
2624 public function isQuotedIdentifier( $name ) {
2625 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2630 * @param string $escapeChar
2633 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2634 return str_replace( [ $escapeChar, '%', '_' ],
2635 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2639 public function buildLike() {
2640 $params = func_get_args();
2642 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2643 $params = $params[0];
2648 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2649 // may escape backslashes, creating problems of double escaping. The `
2650 // character has good cross-DBMS compatibility, avoiding special operators
2651 // in MS SQL like ^ and %
2654 foreach ( $params as $value ) {
2655 if ( $value instanceof LikeMatch
) {
2656 $s .= $value->toString();
2658 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2663 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2666 public function anyChar() {
2667 return new LikeMatch( '_' );
2670 public function anyString() {
2671 return new LikeMatch( '%' );
2674 public function nextSequenceValue( $seqName ) {
2679 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2680 * is only needed because a) MySQL must be as efficient as possible due to
2681 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2682 * which index to pick. Anyway, other databases might have different
2683 * indexes on a given table. So don't bother overriding this unless you're
2685 * @param string $index
2688 public function useIndexClause( $index ) {
2693 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2694 * is only needed because a) MySQL must be as efficient as possible due to
2695 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2696 * which index to pick. Anyway, other databases might have different
2697 * indexes on a given table. So don't bother overriding this unless you're
2699 * @param string $index
2702 public function ignoreIndexClause( $index ) {
2706 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2707 if ( count( $rows ) == 0 ) {
2712 if ( !is_array( reset( $rows ) ) ) {
2717 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2718 $affectedRowCount = 0;
2719 foreach ( $rows as $row ) {
2720 // Delete rows which collide with this one
2721 $indexWhereClauses = [];
2722 foreach ( $uniqueIndexes as $index ) {
2723 $indexColumns = (array)$index;
2724 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2725 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2726 throw new DBUnexpectedError(
2728 'New record does not provide all values for unique key (' .
2729 implode( ', ', $indexColumns ) . ')'
2731 } elseif ( in_array( null, $indexRowValues, true ) ) {
2732 throw new DBUnexpectedError(
2734 'New record has a null value for unique key (' .
2735 implode( ', ', $indexColumns ) . ')'
2738 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2741 if ( $indexWhereClauses ) {
2742 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2743 $affectedRowCount +
= $this->affectedRows();
2746 // Now insert the row
2747 $this->insert( $table, $row, $fname );
2748 $affectedRowCount +
= $this->affectedRows();
2750 $this->endAtomic( $fname );
2751 $this->affectedRowCount
= $affectedRowCount;
2752 } catch ( Exception
$e ) {
2753 $this->cancelAtomic( $fname );
2759 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2762 * @param string $table Table name
2763 * @param array|string $rows Row(s) to insert
2764 * @param string $fname Caller function name
2766 * @return ResultWrapper
2768 protected function nativeReplace( $table, $rows, $fname ) {
2769 $table = $this->tableName( $table );
2772 if ( !is_array( reset( $rows ) ) ) {
2776 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2779 foreach ( $rows as $row ) {
2786 $sql .= '(' . $this->makeList( $row ) . ')';
2789 return $this->query( $sql, $fname );
2792 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2795 if ( !count( $rows ) ) {
2796 return true; // nothing to do
2799 if ( !is_array( reset( $rows ) ) ) {
2803 if ( count( $uniqueIndexes ) ) {
2804 $clauses = []; // list WHERE clauses that each identify a single row
2805 foreach ( $rows as $row ) {
2806 foreach ( $uniqueIndexes as $index ) {
2807 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2808 $rowKey = []; // unique key to this row
2809 foreach ( $index as $column ) {
2810 $rowKey[$column] = $row[$column];
2812 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2815 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2820 $affectedRowCount = 0;
2822 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2823 # Update any existing conflicting row(s)
2824 if ( $where !== false ) {
2825 $ok = $this->update( $table, $set, $where, $fname );
2826 $affectedRowCount +
= $this->affectedRows();
2830 # Now insert any non-conflicting row(s)
2831 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2832 $affectedRowCount +
= $this->affectedRows();
2833 $this->endAtomic( $fname );
2834 $this->affectedRowCount
= $affectedRowCount;
2835 } catch ( Exception
$e ) {
2836 $this->cancelAtomic( $fname );
2843 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2847 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2850 $delTable = $this->tableName( $delTable );
2851 $joinTable = $this->tableName( $joinTable );
2852 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2853 if ( $conds != '*' ) {
2854 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2858 $this->query( $sql, $fname );
2861 public function textFieldSize( $table, $field ) {
2862 $table = $this->tableName( $table );
2863 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2864 $res = $this->query( $sql, __METHOD__
);
2865 $row = $this->fetchObject( $res );
2869 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2878 public function delete( $table, $conds, $fname = __METHOD__
) {
2880 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2883 $table = $this->tableName( $table );
2884 $sql = "DELETE FROM $table";
2886 if ( $conds != '*' ) {
2887 if ( is_array( $conds ) ) {
2888 $conds = $this->makeList( $conds, self
::LIST_AND
);
2890 $sql .= ' WHERE ' . $conds;
2893 return $this->query( $sql, $fname );
2896 final public function insertSelect(
2897 $destTable, $srcTable, $varMap, $conds,
2898 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2900 static $hints = [ 'NO_AUTO_COLUMNS' ];
2902 $insertOptions = (array)$insertOptions;
2903 $selectOptions = (array)$selectOptions;
2905 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2906 // For massive migrations with downtime, we don't want to select everything
2907 // into memory and OOM, so do all this native on the server side if possible.
2908 return $this->nativeInsertSelect(
2914 array_diff( $insertOptions, $hints ),
2920 return $this->nonNativeInsertSelect(
2926 array_diff( $insertOptions, $hints ),
2933 * @param array $insertOptions INSERT options
2934 * @param array $selectOptions SELECT options
2935 * @return bool Whether an INSERT SELECT with these options will be replication safe
2938 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2943 * Implementation of insertSelect() based on select() and insert()
2945 * @see IDatabase::insertSelect()
2947 * @param string $destTable
2948 * @param string|array $srcTable
2949 * @param array $varMap
2950 * @param array $conds
2951 * @param string $fname
2952 * @param array $insertOptions
2953 * @param array $selectOptions
2954 * @param array $selectJoinConds
2957 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2958 $fname = __METHOD__
,
2959 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2961 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2962 // on only the master (without needing row-based-replication). It also makes it easy to
2963 // know how big the INSERT is going to be.
2965 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2966 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2968 $selectOptions[] = 'FOR UPDATE';
2969 $res = $this->select(
2970 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2977 $affectedRowCount = 0;
2978 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2981 foreach ( $res as $row ) {
2982 $rows[] = (array)$row;
2984 // Avoid inserts that are too huge
2985 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2986 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2990 $affectedRowCount +
= $this->affectedRows();
2994 if ( $rows && $ok ) {
2995 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2997 $affectedRowCount +
= $this->affectedRows();
3001 $this->endAtomic( $fname );
3002 $this->affectedRowCount
= $affectedRowCount;
3004 $this->cancelAtomic( $fname );
3007 } catch ( Exception
$e ) {
3008 $this->cancelAtomic( $fname );
3014 * Native server-side implementation of insertSelect() for situations where
3015 * we don't want to select everything into memory
3017 * @see IDatabase::insertSelect()
3018 * @param string $destTable
3019 * @param string|array $srcTable
3020 * @param array $varMap
3021 * @param array $conds
3022 * @param string $fname
3023 * @param array $insertOptions
3024 * @param array $selectOptions
3025 * @param array $selectJoinConds
3028 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3029 $fname = __METHOD__
,
3030 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3032 $destTable = $this->tableName( $destTable );
3034 if ( !is_array( $insertOptions ) ) {
3035 $insertOptions = [ $insertOptions ];
3038 $insertOptions = $this->makeInsertOptions( $insertOptions );
3040 $selectSql = $this->selectSQLText(
3042 array_values( $varMap ),
3049 $sql = "INSERT $insertOptions" .
3050 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3053 return $this->query( $sql, $fname );
3057 * Construct a LIMIT query with optional offset. This is used for query
3058 * pages. The SQL should be adjusted so that only the first $limit rows
3059 * are returned. If $offset is provided as well, then the first $offset
3060 * rows should be discarded, and the next $limit rows should be returned.
3061 * If the result of the query is not ordered, then the rows to be returned
3062 * are theoretically arbitrary.
3064 * $sql is expected to be a SELECT, if that makes a difference.
3066 * The version provided by default works in MySQL and SQLite. It will very
3067 * likely need to be overridden for most other DBMSes.
3069 * @param string $sql SQL query we will append the limit too
3070 * @param int $limit The SQL limit
3071 * @param int|bool $offset The SQL offset (default false)
3072 * @throws DBUnexpectedError
3075 public function limitResult( $sql, $limit, $offset = false ) {
3076 if ( !is_numeric( $limit ) ) {
3077 throw new DBUnexpectedError( $this,
3078 "Invalid non-numeric limit passed to limitResult()\n" );
3081 return "$sql LIMIT "
3082 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3086 public function unionSupportsOrderAndLimit() {
3087 return true; // True for almost every DB supported
3090 public function unionQueries( $sqls, $all ) {
3091 $glue = $all ?
') UNION ALL (' : ') UNION (';
3093 return '(' . implode( $glue, $sqls ) . ')';
3096 public function unionConditionPermutations(
3097 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3098 $options = [], $join_conds = []
3100 // First, build the Cartesian product of $permute_conds
3102 foreach ( $permute_conds as $field => $values ) {
3104 // Skip empty $values
3107 $values = array_unique( $values ); // For sanity
3109 foreach ( $conds as $cond ) {
3110 foreach ( $values as $value ) {
3111 $cond[$field] = $value;
3112 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3118 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3120 // If there's just one condition and no subordering, hand off to
3121 // selectSQLText directly.
3122 if ( count( $conds ) === 1 &&
3123 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3125 return $this->selectSQLText(
3126 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3130 // Otherwise, we need to pull out the order and limit to apply after
3131 // the union. Then build the SQL queries for each set of conditions in
3132 // $conds. Then union them together (using UNION ALL, because the
3133 // product *should* already be distinct).
3134 $orderBy = $this->makeOrderBy( $options );
3135 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
3136 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
3137 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3138 if ( !$this->unionSupportsOrderAndLimit() ) {
3139 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3141 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3142 $options['ORDER BY'] = $options['INNER ORDER BY'];
3144 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3145 // We need to increase the limit by the offset rather than
3146 // using the offset directly, otherwise it'll skip incorrectly
3147 // in the subqueries.
3148 $options['LIMIT'] = $limit +
$offset;
3149 unset( $options['OFFSET'] );
3154 foreach ( $conds as $cond ) {
3155 $sqls[] = $this->selectSQLText(
3156 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3159 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3160 if ( $limit !== null ) {
3161 $sql = $this->limitResult( $sql, $limit, $offset );
3167 public function conditional( $cond, $trueVal, $falseVal ) {
3168 if ( is_array( $cond ) ) {
3169 $cond = $this->makeList( $cond, self
::LIST_AND
);
3172 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3175 public function strreplace( $orig, $old, $new ) {
3176 return "REPLACE({$orig}, {$old}, {$new})";
3179 public function getServerUptime() {
3183 public function wasDeadlock() {
3187 public function wasLockTimeout() {
3191 public function wasConnectionLoss() {
3192 return $this->wasConnectionError( $this->lastErrno() );
3195 public function wasReadOnlyError() {
3199 public function wasErrorReissuable() {
3201 $this->wasDeadlock() ||
3202 $this->wasLockTimeout() ||
3203 $this->wasConnectionLoss()
3208 * Do not use this method outside of Database/DBError classes
3210 * @param int|string $errno
3211 * @return bool Whether the given query error was a connection drop
3213 public function wasConnectionError( $errno ) {
3218 * @return bool Whether it is safe to assume the given error only caused statement rollback
3219 * @note This is for backwards compatibility for callers catching DBError exceptions in
3220 * order to ignore problems like duplicate key errors or foriegn key violations
3223 protected function wasKnownStatementRollbackError() {
3224 return false; // don't know; it could have caused a transaction rollback
3227 public function deadlockLoop() {
3228 $args = func_get_args();
3229 $function = array_shift( $args );
3230 $tries = self
::DEADLOCK_TRIES
;
3232 $this->begin( __METHOD__
);
3235 /** @var Exception $e */
3239 $retVal = call_user_func_array( $function, $args );
3241 } catch ( DBQueryError
$e ) {
3242 if ( $this->wasDeadlock() ) {
3243 // Retry after a randomized delay
3244 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3246 // Throw the error back up
3250 } while ( --$tries > 0 );
3252 if ( $tries <= 0 ) {
3253 // Too many deadlocks; give up
3254 $this->rollback( __METHOD__
);
3257 $this->commit( __METHOD__
);
3263 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3264 # Real waits are implemented in the subclass.
3268 public function getReplicaPos() {
3273 public function getMasterPos() {
3278 public function serverIsReadOnly() {
3282 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3283 if ( !$this->trxLevel
) {
3284 throw new DBUnexpectedError( $this, "No transaction is active." );
3286 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3289 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3290 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3291 // Start an implicit transaction similar to how query() does
3292 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3293 $this->trxAutomatic
= true;
3296 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3297 if ( !$this->trxLevel
) {
3298 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3302 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3303 $this->onTransactionCommitOrIdle( $callback, $fname );
3306 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3307 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3308 // Start an implicit transaction similar to how query() does
3309 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3310 $this->trxAutomatic
= true;
3313 if ( $this->trxLevel
) {
3314 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3316 // No transaction is active nor will start implicitly, so make one for this callback
3317 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3319 call_user_func( $callback, $this );
3320 $this->endAtomic( __METHOD__
);
3321 } catch ( Exception
$e ) {
3322 $this->cancelAtomic( __METHOD__
);
3329 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3331 private function currentAtomicSectionId() {
3332 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3333 $levelInfo = end( $this->trxAtomicLevels
);
3335 return $levelInfo[1];
3342 * @param AtomicSectionIdentifier $old
3343 * @param AtomicSectionIdentifier $new
3345 private function reassignCallbacksForSection(
3346 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3348 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3349 if ( $info[2] === $old ) {
3350 $this->trxPreCommitCallbacks
[$key][2] = $new;
3353 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3354 if ( $info[2] === $old ) {
3355 $this->trxIdleCallbacks
[$key][2] = $new;
3358 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3359 if ( $info[2] === $old ) {
3360 $this->trxEndCallbacks
[$key][2] = $new;
3366 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3367 * @throws UnexpectedValueException
3369 private function modifyCallbacksForCancel( array $sectionIds ) {
3370 // Cancel the "on commit" callbacks owned by this savepoint
3371 $this->trxIdleCallbacks
= array_filter(
3372 $this->trxIdleCallbacks
,
3373 function ( $entry ) use ( $sectionIds ) {
3374 return !in_array( $entry[2], $sectionIds, true );
3377 $this->trxPreCommitCallbacks
= array_filter(
3378 $this->trxPreCommitCallbacks
,
3379 function ( $entry ) use ( $sectionIds ) {
3380 return !in_array( $entry[2], $sectionIds, true );
3383 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3384 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3385 if ( in_array( $entry[2], $sectionIds, true ) ) {
3386 $callback = $entry[0];
3387 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3388 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3394 final public function setTransactionListener( $name, callable
$callback = null ) {
3396 $this->trxRecurringCallbacks
[$name] = $callback;
3398 unset( $this->trxRecurringCallbacks
[$name] );
3403 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3405 * This method should not be used outside of Database/LoadBalancer
3407 * @param bool $suppress
3410 final public function setTrxEndCallbackSuppression( $suppress ) {
3411 $this->trxEndCallbacksSuppressed
= $suppress;
3415 * Actually consume and run any "on transaction idle/resolution" callbacks.
3417 * This method should not be used outside of Database/LoadBalancer
3419 * @param int $trigger IDatabase::TRIGGER_* constant
3420 * @return int Number of callbacks attempted
3424 public function runOnTransactionIdleCallbacks( $trigger ) {
3425 if ( $this->trxLevel
) { // sanity
3426 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open.' );
3429 if ( $this->trxEndCallbacksSuppressed
) {
3434 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3435 /** @var Exception $e */
3436 $e = null; // first exception
3437 do { // callbacks may add callbacks :)
3438 $callbacks = array_merge(
3439 $this->trxIdleCallbacks
,
3440 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3442 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3443 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3444 foreach ( $callbacks as $callback ) {
3446 list( $phpCallback ) = $callback;
3447 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3449 call_user_func( $phpCallback, $trigger, $this );
3450 } catch ( Exception
$ex ) {
3451 call_user_func( $this->errorLogger
, $ex );
3453 // Some callbacks may use startAtomic/endAtomic, so make sure
3454 // their transactions are ended so other callbacks don't fail
3455 if ( $this->trxLevel() ) {
3456 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3460 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3462 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3466 } while ( count( $this->trxIdleCallbacks
) );
3468 if ( $e instanceof Exception
) {
3469 throw $e; // re-throw any first exception
3476 * Actually consume and run any "on transaction pre-commit" callbacks.
3478 * This method should not be used outside of Database/LoadBalancer
3481 * @return int Number of callbacks attempted
3484 public function runOnTransactionPreCommitCallbacks() {
3487 $e = null; // first exception
3488 do { // callbacks may add callbacks :)
3489 $callbacks = $this->trxPreCommitCallbacks
;
3490 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3491 foreach ( $callbacks as $callback ) {
3494 list( $phpCallback ) = $callback;
3495 call_user_func( $phpCallback, $this );
3496 } catch ( Exception
$ex ) {
3497 call_user_func( $this->errorLogger
, $ex );
3501 } while ( count( $this->trxPreCommitCallbacks
) );
3503 if ( $e instanceof Exception
) {
3504 throw $e; // re-throw any first exception
3511 * Actually run any "transaction listener" callbacks.
3513 * This method should not be used outside of Database/LoadBalancer
3515 * @param int $trigger IDatabase::TRIGGER_* constant
3519 public function runTransactionListenerCallbacks( $trigger ) {
3520 if ( $this->trxEndCallbacksSuppressed
) {
3524 /** @var Exception $e */
3525 $e = null; // first exception
3527 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3529 $phpCallback( $trigger, $this );
3530 } catch ( Exception
$ex ) {
3531 call_user_func( $this->errorLogger
, $ex );
3536 if ( $e instanceof Exception
) {
3537 throw $e; // re-throw any first exception
3542 * Create a savepoint
3544 * This is used internally to implement atomic sections. It should not be
3548 * @param string $identifier Identifier for the savepoint
3549 * @param string $fname Calling function name
3551 protected function doSavepoint( $identifier, $fname ) {
3552 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3556 * Release a savepoint
3558 * This is used internally to implement atomic sections. It should not be
3562 * @param string $identifier Identifier for the savepoint
3563 * @param string $fname Calling function name
3565 protected function doReleaseSavepoint( $identifier, $fname ) {
3566 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3570 * Rollback to a savepoint
3572 * This is used internally to implement atomic sections. It should not be
3576 * @param string $identifier Identifier for the savepoint
3577 * @param string $fname Calling function name
3579 protected function doRollbackToSavepoint( $identifier, $fname ) {
3580 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3584 * @param string $fname
3587 private function nextSavepointId( $fname ) {
3588 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3589 if ( strlen( $savepointId ) > 30 ) {
3590 // 30 == Oracle's identifier length limit (pre 12c)
3591 // With a 22 character prefix, that puts the highest number at 99999999.
3592 throw new DBUnexpectedError(
3594 'There have been an excessively large number of atomic sections in a transaction'
3595 . " started by $this->trxFname (at $fname)"
3599 return $savepointId;
3602 final public function startAtomic(
3603 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3605 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3607 if ( !$this->trxLevel
) {
3608 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3609 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3610 // in all changes being in one transaction to keep requests transactional.
3611 if ( $this->getFlag( self
::DBO_TRX
) ) {
3612 // Since writes could happen in between the topmost atomic sections as part
3613 // of the transaction, those sections will need savepoints.
3614 $savepointId = $this->nextSavepointId( $fname );
3615 $this->doSavepoint( $savepointId, $fname );
3617 $this->trxAutomaticAtomic
= true;
3619 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3620 $savepointId = $this->nextSavepointId( $fname );
3621 $this->doSavepoint( $savepointId, $fname );
3624 $sectionId = new AtomicSectionIdentifier
;
3625 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3630 final public function endAtomic( $fname = __METHOD__
) {
3631 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3632 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3635 // Check if the current section matches $fname
3636 $pos = count( $this->trxAtomicLevels
) - 1;
3637 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3639 if ( $savedFname !== $fname ) {
3640 throw new DBUnexpectedError(
3642 "Invalid atomic section ended (got $fname but expected $savedFname)."
3646 // Remove the last section (no need to re-index the array)
3647 array_pop( $this->trxAtomicLevels
);
3649 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3650 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3651 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3652 $this->doReleaseSavepoint( $savepointId, $fname );
3655 // Hoist callback ownership for callbacks in the section that just ended;
3656 // all callbacks should have an owner that is present in trxAtomicLevels.
3657 $currentSectionId = $this->currentAtomicSectionId();
3658 if ( $currentSectionId ) {
3659 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3663 final public function cancelAtomic(
3664 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3666 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3667 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3670 if ( $sectionId !== null ) {
3671 // Find the (last) section with the given $sectionId
3673 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3674 if ( $asId === $sectionId ) {
3679 throw new DBUnexpectedError( "Atomic section not found (for $fname)" );
3681 // Remove all descendant sections and re-index the array
3683 $len = count( $this->trxAtomicLevels
);
3684 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3685 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3687 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3688 $this->modifyCallbacksForCancel( $excisedIds );
3691 // Check if the current section matches $fname
3692 $pos = count( $this->trxAtomicLevels
) - 1;
3693 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3695 if ( $savedFname !== $fname ) {
3696 throw new DBUnexpectedError(
3698 "Invalid atomic section ended (got $fname but expected $savedFname)."
3702 // Remove the last section (no need to re-index the array)
3703 array_pop( $this->trxAtomicLevels
);
3704 $this->modifyCallbacksForCancel( [ $savedSectionId ] );
3706 if ( $savepointId !== null ) {
3707 // Rollback the transaction to the state just before this atomic section
3708 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3709 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3711 $this->doRollbackToSavepoint( $savepointId, $fname );
3712 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3713 $this->trxStatusIgnoredCause
= null;
3715 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3716 // Put the transaction into an error state if it's not already in one
3717 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3718 $this->trxStatusCause
= new DBUnexpectedError(
3720 "Uncancelable atomic section canceled (got $fname)."
3724 $this->affectedRowCount
= 0; // for the sake of consistency
3727 final public function doAtomicSection(
3728 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3730 $sectionId = $this->startAtomic( $fname, $cancelable );
3732 $res = call_user_func_array( $callback, [ $this, $fname ] );
3733 } catch ( Exception
$e ) {
3734 $this->cancelAtomic( $fname, $sectionId );
3738 $this->endAtomic( $fname );
3743 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3744 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3745 if ( !in_array( $mode, $modes, true ) ) {
3746 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'." );
3749 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3750 if ( $this->trxLevel
) {
3751 if ( $this->trxAtomicLevels
) {
3752 $levels = $this->flatAtomicSectionList();
3753 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3754 throw new DBUnexpectedError( $this, $msg );
3755 } elseif ( !$this->trxAutomatic
) {
3756 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3757 throw new DBUnexpectedError( $this, $msg );
3759 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3760 throw new DBUnexpectedError( $this, $msg );
3762 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3763 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3764 throw new DBUnexpectedError( $this, $msg );
3767 // Avoid fatals if close() was called
3768 $this->assertOpen();
3770 $this->doBegin( $fname );
3771 $this->trxStatus
= self
::STATUS_TRX_OK
;
3772 $this->trxStatusIgnoredCause
= null;
3773 $this->trxAtomicCounter
= 0;
3774 $this->trxTimestamp
= microtime( true );
3775 $this->trxFname
= $fname;
3776 $this->trxDoneWrites
= false;
3777 $this->trxAutomaticAtomic
= false;
3778 $this->trxAtomicLevels
= [];
3779 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3780 $this->trxWriteDuration
= 0.0;
3781 $this->trxWriteQueryCount
= 0;
3782 $this->trxWriteAffectedRows
= 0;
3783 $this->trxWriteAdjDuration
= 0.0;
3784 $this->trxWriteAdjQueryCount
= 0;
3785 $this->trxWriteCallers
= [];
3786 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3787 // Get an estimate of the replication lag before any such queries.
3788 $this->trxReplicaLag
= null; // clear cached value first
3789 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3790 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3791 // caller will think its OK to muck around with the transaction just because startAtomic()
3792 // has not yet completed (e.g. setting trxAtomicLevels).
3793 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3797 * Issues the BEGIN command to the database server.
3799 * @see Database::begin()
3800 * @param string $fname
3802 protected function doBegin( $fname ) {
3803 $this->query( 'BEGIN', $fname );
3804 $this->trxLevel
= 1;
3807 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3808 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
3809 if ( !in_array( $flush, $modes, true ) ) {
3810 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'." );
3813 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3814 // There are still atomic sections open; this cannot be ignored
3815 $levels = $this->flatAtomicSectionList();
3816 throw new DBUnexpectedError(
3818 "$fname: Got COMMIT while atomic sections $levels are still open."
3822 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3823 if ( !$this->trxLevel
) {
3824 return; // nothing to do
3825 } elseif ( !$this->trxAutomatic
) {
3826 throw new DBUnexpectedError(
3828 "$fname: Flushing an explicit transaction, getting out of sync."
3832 if ( !$this->trxLevel
) {
3833 $this->queryLogger
->error(
3834 "$fname: No transaction to commit, something got out of sync." );
3835 return; // nothing to do
3836 } elseif ( $this->trxAutomatic
) {
3837 throw new DBUnexpectedError(
3839 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3844 // Avoid fatals if close() was called
3845 $this->assertOpen();
3847 $this->runOnTransactionPreCommitCallbacks();
3848 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3849 $this->doCommit( $fname );
3850 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3851 if ( $this->trxDoneWrites
) {
3852 $this->lastWriteTime
= microtime( true );
3853 $this->trxProfiler
->transactionWritingOut(
3858 $this->trxWriteAffectedRows
3862 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
3863 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
3864 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3865 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3870 * Issues the COMMIT command to the database server.
3872 * @see Database::commit()
3873 * @param string $fname
3875 protected function doCommit( $fname ) {
3876 if ( $this->trxLevel
) {
3877 $this->query( 'COMMIT', $fname );
3878 $this->trxLevel
= 0;
3882 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3883 $trxActive = $this->trxLevel
;
3885 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3886 if ( $this->getFlag( self
::DBO_TRX
) ) {
3887 throw new DBUnexpectedError(
3889 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3895 // Avoid fatals if close() was called
3896 $this->assertOpen();
3898 $this->doRollback( $fname );
3899 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3900 $this->trxAtomicLevels
= [];
3901 if ( $this->trxDoneWrites
) {
3902 $this->trxProfiler
->transactionWritingOut(
3910 // Clear any commit-dependant callbacks. They might even be present
3911 // only due to transaction rounds, with no SQL transaction being active
3912 $this->trxIdleCallbacks
= [];
3913 $this->trxPreCommitCallbacks
= [];
3915 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
3916 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
3918 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3919 } catch ( Exception
$e ) {
3920 // already logged; finish and let LoadBalancer move on during mass-rollback
3923 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3924 } catch ( Exception
$e ) {
3925 // already logged; let LoadBalancer move on during mass-rollback
3928 $this->affectedRowCount
= 0; // for the sake of consistency
3933 * Issues the ROLLBACK command to the database server.
3935 * @see Database::rollback()
3936 * @param string $fname
3938 protected function doRollback( $fname ) {
3939 if ( $this->trxLevel
) {
3940 # Disconnects cause rollback anyway, so ignore those errors
3941 $ignoreErrors = true;
3942 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3943 $this->trxLevel
= 0;
3947 public function flushSnapshot( $fname = __METHOD__
) {
3948 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3949 // This only flushes transactions to clear snapshots, not to write data
3950 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3951 throw new DBUnexpectedError(
3953 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3957 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3960 public function explicitTrxActive() {
3961 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3964 public function duplicateTableStructure(
3965 $oldName, $newName, $temporary = false, $fname = __METHOD__
3967 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3970 public function listTables( $prefix = null, $fname = __METHOD__
) {
3971 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3974 public function listViews( $prefix = null, $fname = __METHOD__
) {
3975 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3978 public function timestamp( $ts = 0 ) {
3979 $t = new ConvertibleTimestamp( $ts );
3980 // Let errors bubble up to avoid putting garbage in the DB
3981 return $t->getTimestamp( TS_MW
);
3984 public function timestampOrNull( $ts = null ) {
3985 if ( is_null( $ts ) ) {
3988 return $this->timestamp( $ts );
3992 public function affectedRows() {
3993 return ( $this->affectedRowCount
=== null )
3994 ?
$this->fetchAffectedRowCount() // default to driver value
3995 : $this->affectedRowCount
;
3999 * @return int Number of retrieved rows according to the driver
4001 abstract protected function fetchAffectedRowCount();
4004 * Take the result from a query, and wrap it in a ResultWrapper if
4005 * necessary. Boolean values are passed through as is, to indicate success
4006 * of write queries or failure.
4008 * Once upon a time, Database::query() returned a bare MySQL result
4009 * resource, and it was necessary to call this function to convert it to
4010 * a wrapper. Nowadays, raw database objects are never exposed to external
4011 * callers, so this is unnecessary in external code.
4013 * @param bool|ResultWrapper|resource|object $result
4014 * @return bool|ResultWrapper
4016 protected function resultObject( $result ) {
4019 } elseif ( $result instanceof ResultWrapper
) {
4021 } elseif ( $result === true ) {
4022 // Successful write query
4025 return new ResultWrapper( $this, $result );
4029 public function ping( &$rtt = null ) {
4030 // Avoid hitting the server if it was hit recently
4031 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
4032 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
4033 $rtt = $this->rttEstimate
;
4034 return true; // don't care about $rtt
4038 // This will reconnect if possible or return false if not
4039 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4040 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
4041 $this->restoreFlags( self
::RESTORE_PRIOR
);
4044 $rtt = $this->rttEstimate
;
4051 * Close any existing (dead) database connection and open a new connection
4053 * @param string $fname
4054 * @return bool True if new connection is opened successfully, false if error
4056 protected function replaceLostConnection( $fname ) {
4057 $this->closeConnection();
4058 $this->opened
= false;
4059 $this->conn
= false;
4061 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4062 $this->lastPing
= microtime( true );
4065 $this->connLogger
->warning(
4066 $fname . ': lost connection to {dbserver}; reconnected',
4068 'dbserver' => $this->getServer(),
4069 'trace' => ( new RuntimeException() )->getTraceAsString()
4072 } catch ( DBConnectionError
$e ) {
4075 $this->connLogger
->error(
4076 $fname . ': lost connection to {dbserver} permanently',
4077 [ 'dbserver' => $this->getServer() ]
4081 $this->handleSessionLoss();
4086 public function getSessionLagStatus() {
4087 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4091 * Get the replica DB lag when the current transaction started
4093 * This is useful when transactions might use snapshot isolation
4094 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4095 * is this lag plus transaction duration. If they don't, it is still
4096 * safe to be pessimistic. This returns null if there is no transaction.
4098 * This returns null if the lag status for this transaction was not yet recorded.
4100 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4103 final protected function getRecordedTransactionLagStatus() {
4104 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
4105 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4110 * Get a replica DB lag estimate for this server
4112 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4115 protected function getApproximateLagStatus() {
4117 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4118 'since' => microtime( true )
4123 * Merge the result of getSessionLagStatus() for several DBs
4124 * using the most pessimistic values to estimate the lag of
4125 * any data derived from them in combination
4127 * This is information is useful for caching modules
4129 * @see WANObjectCache::set()
4130 * @see WANObjectCache::getWithSetCallback()
4132 * @param IDatabase $db1
4133 * @param IDatabase $db2 [optional]
4134 * @return array Map of values:
4135 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4136 * - since: oldest UNIX timestamp of any of the DB lag estimates
4137 * - pending: whether any of the DBs have uncommitted changes
4141 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4142 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4143 foreach ( func_get_args() as $db ) {
4144 /** @var IDatabase $db */
4145 $status = $db->getSessionLagStatus();
4146 if ( $status['lag'] === false ) {
4147 $res['lag'] = false;
4148 } elseif ( $res['lag'] !== false ) {
4149 $res['lag'] = max( $res['lag'], $status['lag'] );
4151 $res['since'] = min( $res['since'], $status['since'] );
4152 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4158 public function getLag() {
4162 public function maxListLen() {
4166 public function encodeBlob( $b ) {
4170 public function decodeBlob( $b ) {
4171 if ( $b instanceof Blob
) {
4177 public function setSessionOptions( array $options ) {
4180 public function sourceFile(
4182 callable
$lineCallback = null,
4183 callable
$resultCallback = null,
4185 callable
$inputCallback = null
4187 Wikimedia\
suppressWarnings();
4188 $fp = fopen( $filename, 'r' );
4189 Wikimedia\restoreWarnings
();
4191 if ( false === $fp ) {
4192 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4196 $fname = __METHOD__
. "( $filename )";
4200 $error = $this->sourceStream(
4201 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4202 } catch ( Exception
$e ) {
4212 public function setSchemaVars( $vars ) {
4213 $this->schemaVars
= $vars;
4216 public function sourceStream(
4218 callable
$lineCallback = null,
4219 callable
$resultCallback = null,
4220 $fname = __METHOD__
,
4221 callable
$inputCallback = null
4223 $delimiterReset = new ScopedCallback(
4224 function ( $delimiter ) {
4225 $this->delimiter
= $delimiter;
4227 [ $this->delimiter
]
4231 while ( !feof( $fp ) ) {
4232 if ( $lineCallback ) {
4233 call_user_func( $lineCallback );
4236 $line = trim( fgets( $fp ) );
4238 if ( $line == '' ) {
4242 if ( '-' == $line[0] && '-' == $line[1] ) {
4250 $done = $this->streamStatementEnd( $cmd, $line );
4254 if ( $done ||
feof( $fp ) ) {
4255 $cmd = $this->replaceVars( $cmd );
4257 if ( $inputCallback ) {
4258 $callbackResult = call_user_func( $inputCallback, $cmd );
4260 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4261 $cmd = $callbackResult;
4266 $res = $this->query( $cmd, $fname );
4268 if ( $resultCallback ) {
4269 call_user_func( $resultCallback, $res, $this );
4272 if ( false === $res ) {
4273 $err = $this->lastError();
4275 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4282 ScopedCallback
::consume( $delimiterReset );
4287 * Called by sourceStream() to check if we've reached a statement end
4289 * @param string &$sql SQL assembled so far
4290 * @param string &$newLine New line about to be added to $sql
4291 * @return bool Whether $newLine contains end of the statement
4293 public function streamStatementEnd( &$sql, &$newLine ) {
4294 if ( $this->delimiter
) {
4296 $newLine = preg_replace(
4297 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4298 if ( $newLine != $prev ) {
4307 * Database independent variable replacement. Replaces a set of variables
4308 * in an SQL statement with their contents as given by $this->getSchemaVars().
4310 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4312 * - '{$var}' should be used for text and is passed through the database's
4314 * - `{$var}` should be used for identifiers (e.g. table and database names).
4315 * It is passed through the database's addIdentifierQuotes method which
4316 * can be overridden if the database uses something other than backticks.
4317 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4318 * database's tableName method.
4319 * - / *i* / passes the name that follows through the database's indexName method.
4320 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4321 * its use should be avoided. In 1.24 and older, string encoding was applied.
4323 * @param string $ins SQL statement to replace variables in
4324 * @return string The new SQL statement with variables replaced
4326 protected function replaceVars( $ins ) {
4327 $vars = $this->getSchemaVars();
4328 return preg_replace_callback(
4330 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4331 \'\{\$ (\w+) }\' | # 3. addQuotes
4332 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4333 /\*\$ (\w+) \*/ # 5. leave unencoded
4335 function ( $m ) use ( $vars ) {
4336 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4337 // check for both nonexistent keys *and* the empty string.
4338 if ( isset( $m[1] ) && $m[1] !== '' ) {
4339 if ( $m[1] === 'i' ) {
4340 return $this->indexName( $m[2] );
4342 return $this->tableName( $m[2] );
4344 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4345 return $this->addQuotes( $vars[$m[3]] );
4346 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4347 return $this->addIdentifierQuotes( $vars[$m[4]] );
4348 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4349 return $vars[$m[5]];
4359 * Get schema variables. If none have been set via setSchemaVars(), then
4360 * use some defaults from the current object.
4364 protected function getSchemaVars() {
4365 if ( $this->schemaVars
) {
4366 return $this->schemaVars
;
4368 return $this->getDefaultSchemaVars();
4373 * Get schema variables to use if none have been set via setSchemaVars().
4375 * Override this in derived classes to provide variables for tables.sql
4376 * and SQL patch files.
4380 protected function getDefaultSchemaVars() {
4384 public function lockIsFree( $lockName, $method ) {
4385 // RDBMs methods for checking named locks may or may not count this thread itself.
4386 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4387 // the behavior choosen by the interface for this method.
4388 return !isset( $this->namedLocksHeld
[$lockName] );
4391 public function lock( $lockName, $method, $timeout = 5 ) {
4392 $this->namedLocksHeld
[$lockName] = 1;
4397 public function unlock( $lockName, $method ) {
4398 unset( $this->namedLocksHeld
[$lockName] );
4403 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4404 if ( $this->writesOrCallbacksPending() ) {
4405 // This only flushes transactions to clear snapshots, not to write data
4406 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4407 throw new DBUnexpectedError(
4409 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4413 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4417 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4418 if ( $this->trxLevel() ) {
4419 // There is a good chance an exception was thrown, causing any early return
4420 // from the caller. Let any error handler get a chance to issue rollback().
4421 // If there isn't one, let the error bubble up and trigger server-side rollback.
4422 $this->onTransactionResolution(
4423 function () use ( $lockKey, $fname ) {
4424 $this->unlock( $lockKey, $fname );
4429 $this->unlock( $lockKey, $fname );
4433 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4438 public function namedLocksEnqueue() {
4442 public function tableLocksHaveTransactionScope() {
4446 final public function lockTables( array $read, array $write, $method ) {
4447 if ( $this->writesOrCallbacksPending() ) {
4448 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4451 if ( $this->tableLocksHaveTransactionScope() ) {
4452 $this->startAtomic( $method );
4455 return $this->doLockTables( $read, $write, $method );
4459 * Helper function for lockTables() that handles the actual table locking
4461 * @param array $read Array of tables to lock for read access
4462 * @param array $write Array of tables to lock for write access
4463 * @param string $method Name of caller
4466 protected function doLockTables( array $read, array $write, $method ) {
4470 final public function unlockTables( $method ) {
4471 if ( $this->tableLocksHaveTransactionScope() ) {
4472 $this->endAtomic( $method );
4474 return true; // locks released on COMMIT/ROLLBACK
4477 return $this->doUnlockTables( $method );
4481 * Helper function for unlockTables() that handles the actual table unlocking
4483 * @param string $method Name of caller
4486 protected function doUnlockTables( $method ) {
4492 * @param string $tableName
4493 * @param string $fName
4494 * @return bool|ResultWrapper
4497 public function dropTable( $tableName, $fName = __METHOD__
) {
4498 if ( !$this->tableExists( $tableName, $fName ) ) {
4501 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4503 return $this->query( $sql, $fName );
4506 public function getInfinity() {
4510 public function encodeExpiry( $expiry ) {
4511 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4512 ?
$this->getInfinity()
4513 : $this->timestamp( $expiry );
4516 public function decodeExpiry( $expiry, $format = TS_MW
) {
4517 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4521 return ConvertibleTimestamp
::convert( $format, $expiry );
4524 public function setBigSelects( $value = true ) {
4528 public function isReadOnly() {
4529 return ( $this->getReadOnlyReason() !== false );
4533 * @return string|bool Reason this DB is read-only or false if it is not
4535 protected function getReadOnlyReason() {
4536 $reason = $this->getLBInfo( 'readOnlyReason' );
4538 return is_string( $reason ) ?
$reason : false;
4541 public function setTableAliases( array $aliases ) {
4542 $this->tableAliases
= $aliases;
4545 public function setIndexAliases( array $aliases ) {
4546 $this->indexAliases
= $aliases;
4550 * Get the underlying binding connection handle
4552 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4553 * This catches broken callers than catch and ignore disconnection exceptions.
4554 * Unlike checking isOpen(), this is safe to call inside of open().
4557 * @throws DBUnexpectedError
4560 protected function getBindingHandle() {
4561 if ( !$this->conn
) {
4562 throw new DBUnexpectedError(
4564 'DB connection was already closed or the connection dropped.'
4575 public function __toString() {
4576 return (string)$this->conn
;
4580 * Make sure that copies do not share the same client binding handle
4581 * @throws DBConnectionError
4583 public function __clone() {
4584 $this->connLogger
->warning(
4585 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4586 ( new RuntimeException() )->getTraceAsString()
4589 if ( $this->isOpen() ) {
4590 // Open a new connection resource without messing with the old one
4591 $this->opened
= false;
4592 $this->conn
= false;
4593 $this->trxEndCallbacks
= []; // don't copy
4594 $this->handleSessionLoss(); // no trx or locks anymore
4595 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4596 $this->lastPing
= microtime( true );
4601 * Called by serialize. Throw an exception when DB connection is serialized.
4602 * This causes problems on some database engines because the connection is
4603 * not restored on unserialize.
4605 public function __sleep() {
4606 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4607 'the connection is not restored on wakeup.' );
4611 * Run a few simple sanity checks and close dangling connections
4613 public function __destruct() {
4614 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4615 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4618 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4619 if ( $danglingWriters ) {
4620 $fnames = implode( ', ', $danglingWriters );
4621 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4624 if ( $this->conn
) {
4625 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4626 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4627 Wikimedia\
suppressWarnings();
4628 $this->closeConnection();
4629 Wikimedia\restoreWarnings
();
4630 $this->conn
= false;
4631 $this->opened
= false;
4637 * @deprecated since 1.28
4639 class_alias( Database
::class, 'DatabaseBase' );
4642 * @deprecated since 1.29
4644 class_alias( Database
::class, 'Database' );