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 array[] Map of (table => (dbname, schema, prefix) map) */
85 protected $tableAliases = [];
86 /** @var string[] Map of (index alias => index) */
87 protected $indexAliases = [];
88 /** @var bool Whether this PHP instance is for a CLI script */
90 /** @var string Agent name for query profiling */
92 /** @var array Parameters used by initConnection() to establish a connection */
93 protected $connectionParams = [];
94 /** @var BagOStuff APC cache */
96 /** @var LoggerInterface */
97 protected $connLogger;
98 /** @var LoggerInterface */
99 protected $queryLogger;
100 /** @var callable Error logging callback */
101 protected $errorLogger;
102 /** @var callable Deprecation logging callback */
103 protected $deprecationLogger;
105 /** @var resource|null Database connection */
106 protected $conn = null;
108 protected $opened = false;
110 /** @var array[] List of (callable, method name, atomic section id) */
111 protected $trxIdleCallbacks = [];
112 /** @var array[] List of (callable, method name, atomic section id) */
113 protected $trxPreCommitCallbacks = [];
114 /** @var array[] List of (callable, method name, atomic section id) */
115 protected $trxEndCallbacks = [];
116 /** @var callable[] Map of (name => callable) */
117 protected $trxRecurringCallbacks = [];
118 /** @var bool Whether to suppress triggering of transaction end callbacks */
119 protected $trxEndCallbacksSuppressed = false;
124 protected $lbInfo = [];
125 /** @var array|bool */
126 protected $schemaVars = false;
128 protected $sessionVars = [];
129 /** @var array|null */
130 protected $preparedArgs;
131 /** @var string|bool|null Stashed value of html_errors INI setting */
132 protected $htmlErrors;
134 protected $delimiter = ';';
135 /** @var DatabaseDomain */
136 protected $currentDomain;
137 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
138 protected $affectedRowCount;
141 * @var int Transaction status
143 protected $trxStatus = self
::STATUS_TRX_NONE
;
145 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
147 protected $trxStatusCause;
149 * @var array|null If wasKnownStatementRollbackError() prevented trxStatus from being set,
150 * the relevant details are stored here.
152 protected $trxStatusIgnoredCause;
154 * Either 1 if a transaction is active or 0 otherwise.
155 * The other Trx fields may not be meaningfull if this is 0.
159 protected $trxLevel = 0;
161 * Either a short hexidecimal string if a transaction is active or ""
164 * @see Database::trxLevel
166 protected $trxShortId = '';
168 * The UNIX time that the transaction started. Callers can assume that if
169 * snapshot isolation is used, then the data is *at least* up to date to that
170 * point (possibly more up-to-date since the first SELECT defines the snapshot).
173 * @see Database::trxLevel
175 private $trxTimestamp = null;
176 /** @var float Lag estimate at the time of BEGIN */
177 private $trxReplicaLag = null;
179 * Remembers the function name given for starting the most recent transaction via begin().
180 * Used to provide additional context for error reporting.
183 * @see Database::trxLevel
185 private $trxFname = null;
187 * Record if possible write queries were done in the last transaction started
190 * @see Database::trxLevel
192 private $trxDoneWrites = false;
194 * Record if the current transaction was started implicitly due to DBO_TRX being set.
197 * @see Database::trxLevel
199 private $trxAutomatic = false;
201 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
205 private $trxAtomicCounter = 0;
207 * Array of levels of atomicity within transactions
209 * @var array List of (name, unique ID, savepoint ID)
211 private $trxAtomicLevels = [];
213 * Record if the current transaction was started implicitly by Database::startAtomic
217 private $trxAutomaticAtomic = false;
219 * Track the write query callers of the current transaction
223 private $trxWriteCallers = [];
225 * @var float Seconds spent in write queries for the current transaction
227 private $trxWriteDuration = 0.0;
229 * @var int Number of write queries for the current transaction
231 private $trxWriteQueryCount = 0;
233 * @var int Number of rows affected by write queries for the current transaction
235 private $trxWriteAffectedRows = 0;
237 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
239 private $trxWriteAdjDuration = 0.0;
241 * @var int Number of write queries counted in trxWriteAdjDuration
243 private $trxWriteAdjQueryCount = 0;
245 * @var float RTT time estimate
247 private $rttEstimate = 0.0;
249 /** @var array Map of (name => 1) for locks obtained via lock() */
250 private $namedLocksHeld = [];
251 /** @var array Map of (table name => 1) for TEMPORARY tables */
252 protected $sessionTempTables = [];
254 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
255 private $lazyMasterHandle;
257 /** @var float UNIX timestamp */
258 protected $lastPing = 0.0;
260 /** @var int[] Prior flags member variable values */
261 private $priorFlags = [];
263 /** @var mixed Class name or object With profileIn/profileOut methods */
265 /** @var TransactionProfiler */
266 protected $trxProfiler;
269 protected $nonNativeInsertSelectBatchSize = 10000;
271 /** @var string Idiom used when a cancelable atomic section started the transaction */
272 private static $NOT_APPLICABLE = 'n/a';
273 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
274 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
276 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
277 const STATUS_TRX_ERROR
= 1;
278 /** @var int Transaction is active and in a normal state */
279 const STATUS_TRX_OK
= 2;
280 /** @var int No transaction is active */
281 const STATUS_TRX_NONE
= 3;
284 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
285 * @param array $params Parameters passed from Database::factory()
287 protected function __construct( array $params ) {
288 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
289 $this->connectionParams
[$name] = $params[$name];
292 $this->cliMode
= $params['cliMode'];
293 // Agent name is added to SQL queries in a comment, so make sure it can't break out
294 $this->agent
= str_replace( '/', '-', $params['agent'] );
296 $this->flags
= $params['flags'];
297 if ( $this->flags
& self
::DBO_DEFAULT
) {
298 if ( $this->cliMode
) {
299 $this->flags
&= ~self
::DBO_TRX
;
301 $this->flags |
= self
::DBO_TRX
;
304 // Disregard deprecated DBO_IGNORE flag (T189999)
305 $this->flags
&= ~self
::DBO_IGNORE
;
307 $this->sessionVars
= $params['variables'];
309 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
311 $this->profiler
= $params['profiler'];
312 $this->trxProfiler
= $params['trxProfiler'];
313 $this->connLogger
= $params['connLogger'];
314 $this->queryLogger
= $params['queryLogger'];
315 $this->errorLogger
= $params['errorLogger'];
316 $this->deprecationLogger
= $params['deprecationLogger'];
318 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
319 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
322 // Set initial dummy domain until open() sets the final DB/prefix
323 $this->currentDomain
= new DatabaseDomain(
324 $params['dbname'] != '' ?
$params['dbname'] : null,
325 $params['schema'] != '' ?
$params['schema'] : null,
326 $params['tablePrefix']
331 * Initialize the connection to the database over the wire (or to local files)
333 * @throws LogicException
334 * @throws InvalidArgumentException
335 * @throws DBConnectionError
338 final public function initConnection() {
339 if ( $this->isOpen() ) {
340 throw new LogicException( __METHOD__
. ': already connected.' );
342 // Establish the connection
343 $this->doInitConnection();
347 * Actually connect to the database over the wire (or to local files)
349 * @throws InvalidArgumentException
350 * @throws DBConnectionError
353 protected function doInitConnection() {
354 if ( strlen( $this->connectionParams
['user'] ) ) {
356 $this->connectionParams
['host'],
357 $this->connectionParams
['user'],
358 $this->connectionParams
['password'],
359 $this->connectionParams
['dbname'],
360 $this->connectionParams
['schema'],
361 $this->connectionParams
['tablePrefix']
364 throw new InvalidArgumentException( "No database user provided." );
369 * Open a new connection to the database (closing any existing one)
371 * @param string $server Database server host
372 * @param string $user Database user name
373 * @param string $password Database user password
374 * @param string $dbName Database name
375 * @param string|null $schema Database schema name
376 * @param string $tablePrefix Table prefix
378 * @throws DBConnectionError
380 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
383 * Construct a Database subclass instance given a database type and parameters
385 * This also connects to the database immediately upon object construction
387 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
388 * @param array $p Parameter map with keys:
389 * - host : The hostname of the DB server
390 * - user : The name of the database user the client operates under
391 * - password : The password for the database user
392 * - dbname : The name of the database to use where queries do not specify one.
393 * The database must exist or an error might be thrown. Setting this to the empty string
394 * will avoid any such errors and make the handle have no implicit database scope. This is
395 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
396 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
397 * in which user names and such are defined, e.g. users are database-specific in Postgres.
398 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
399 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
400 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
401 * recognized in queries. This can be used in place of schemas for handle site farms.
402 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
403 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
404 * flag in place UNLESS this this database simply acts as a key/value store.
405 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
406 * 'mysqli' driver; the old one 'mysql' has been removed.
407 * - variables: Optional map of session variables to set after connecting. This can be
408 * used to adjust lock timeouts or encoding modes and the like.
409 * - connLogger: Optional PSR-3 logger interface instance.
410 * - queryLogger: Optional PSR-3 logger interface instance.
411 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
412 * These will be called in query(), using a simplified version of the SQL that also
413 * includes the agent as a SQL comment.
414 * - trxProfiler: Optional TransactionProfiler instance.
415 * - errorLogger: Optional callback that takes an Exception and logs it.
416 * - deprecationLogger: Optional callback that takes a string and logs it.
417 * - cliMode: Whether to consider the execution context that of a CLI script.
418 * - agent: Optional name used to identify the end-user in query profiling/logging.
419 * - srvCache: Optional BagOStuff instance to an APC-style cache.
420 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
421 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
422 * @return Database|null If the database driver or extension cannot be found
423 * @throws InvalidArgumentException If the database driver or extension cannot be found
426 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
427 $class = self
::getClass( $dbType, $p['driver'] ??
null );
429 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
430 // Resolve some defaults for b/c
431 $p['host'] = $p['host'] ??
false;
432 $p['user'] = $p['user'] ??
false;
433 $p['password'] = $p['password'] ??
false;
434 $p['dbname'] = $p['dbname'] ??
false;
435 $p['flags'] = $p['flags'] ??
0;
436 $p['variables'] = $p['variables'] ??
[];
437 $p['tablePrefix'] = $p['tablePrefix'] ??
'';
438 $p['schema'] = $p['schema'] ??
null;
439 $p['cliMode'] = $p['cliMode'] ??
( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
440 $p['agent'] = $p['agent'] ??
'';
441 if ( !isset( $p['connLogger'] ) ) {
442 $p['connLogger'] = new NullLogger();
444 if ( !isset( $p['queryLogger'] ) ) {
445 $p['queryLogger'] = new NullLogger();
447 $p['profiler'] = $p['profiler'] ??
null;
448 if ( !isset( $p['trxProfiler'] ) ) {
449 $p['trxProfiler'] = new TransactionProfiler();
451 if ( !isset( $p['errorLogger'] ) ) {
452 $p['errorLogger'] = function ( Exception
$e ) {
453 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
456 if ( !isset( $p['deprecationLogger'] ) ) {
457 $p['deprecationLogger'] = function ( $msg ) {
458 trigger_error( $msg, E_USER_DEPRECATED
);
462 /** @var Database $conn */
463 $conn = new $class( $p );
464 if ( $connect == self
::NEW_CONNECTED
) {
465 $conn->initConnection();
475 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
476 * @param string|null $driver Optional name of a specific DB client driver
477 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
478 * @throws InvalidArgumentException
481 final public static function attributesFromType( $dbType, $driver = null ) {
482 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
484 $class = self
::getClass( $dbType, $driver );
486 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
490 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
491 * @param string|null $driver Optional name of a specific DB client driver
492 * @return string Database subclass name to use
493 * @throws InvalidArgumentException
495 private static function getClass( $dbType, $driver = null ) {
496 // For database types with built-in support, the below maps type to IDatabase
497 // implementations. For types with multipe driver implementations (PHP extensions),
498 // an array can be used, keyed by extension name. In case of an array, the
499 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
500 // we auto-detect the first available driver. For types without built-in support,
501 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
502 static $builtinTypes = [
503 'mssql' => DatabaseMssql
::class,
504 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
505 'sqlite' => DatabaseSqlite
::class,
506 'postgres' => DatabasePostgres
::class,
509 $dbType = strtolower( $dbType );
512 if ( isset( $builtinTypes[$dbType] ) ) {
513 $possibleDrivers = $builtinTypes[$dbType];
514 if ( is_string( $possibleDrivers ) ) {
515 $class = $possibleDrivers;
517 if ( (string)$driver !== '' ) {
518 if ( !isset( $possibleDrivers[$driver] ) ) {
519 throw new InvalidArgumentException( __METHOD__
.
520 " type '$dbType' does not support driver '{$driver}'" );
522 $class = $possibleDrivers[$driver];
525 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
526 if ( extension_loaded( $posDriver ) ) {
527 $class = $possibleClass;
534 $class = 'Database' . ucfirst( $dbType );
537 if ( $class === false ) {
538 throw new InvalidArgumentException( __METHOD__
.
539 " no viable database extension found for type '$dbType'" );
546 * @return array Map of (Database::ATTRIBUTE_* constant => value
549 protected static function getAttributes() {
554 * Set the PSR-3 logger interface to use for query logging. (The logger
555 * interfaces for connection logging and error logging can be set with the
558 * @param LoggerInterface $logger
560 public function setLogger( LoggerInterface
$logger ) {
561 $this->queryLogger
= $logger;
564 public function getServerInfo() {
565 return $this->getServerVersion();
568 public function bufferResults( $buffer = null ) {
569 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
570 if ( $buffer !== null ) {
572 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
573 : $this->setFlag( self
::DBO_NOBUFFER
);
579 public function trxLevel() {
580 return $this->trxLevel
;
583 public function trxTimestamp() {
584 return $this->trxLevel ?
$this->trxTimestamp
: null;
588 * @return int One of the STATUS_TRX_* class constants
591 public function trxStatus() {
592 return $this->trxStatus
;
595 public function tablePrefix( $prefix = null ) {
596 $old = $this->currentDomain
->getTablePrefix();
597 if ( $prefix !== null ) {
598 $this->currentDomain
= new DatabaseDomain(
599 $this->currentDomain
->getDatabase(),
600 $this->currentDomain
->getSchema(),
608 public function dbSchema( $schema = null ) {
609 $old = $this->currentDomain
->getSchema();
610 if ( $schema !== null ) {
611 $this->currentDomain
= new DatabaseDomain(
612 $this->currentDomain
->getDatabase(),
613 // DatabaseDomain uses null for unspecified schemas
614 strlen( $schema ) ?
$schema : null,
615 $this->currentDomain
->getTablePrefix()
623 * @return string Schema to use to qualify relations in queries
625 protected function relationSchemaQualifier() {
626 return $this->dbSchema();
629 public function getLBInfo( $name = null ) {
630 if ( is_null( $name ) ) {
631 return $this->lbInfo
;
633 if ( array_key_exists( $name, $this->lbInfo
) ) {
634 return $this->lbInfo
[$name];
641 public function setLBInfo( $name, $value = null ) {
642 if ( is_null( $value ) ) {
643 $this->lbInfo
= $name;
645 $this->lbInfo
[$name] = $value;
649 public function setLazyMasterHandle( IDatabase
$conn ) {
650 $this->lazyMasterHandle
= $conn;
654 * @return IDatabase|null
655 * @see setLazyMasterHandle()
658 protected function getLazyMasterHandle() {
659 return $this->lazyMasterHandle
;
662 public function implicitGroupby() {
666 public function implicitOrderby() {
670 public function lastQuery() {
671 return $this->lastQuery
;
674 public function doneWrites() {
675 return (bool)$this->lastWriteTime
;
678 public function lastDoneWrites() {
679 return $this->lastWriteTime ?
: false;
682 public function writesPending() {
683 return $this->trxLevel
&& $this->trxDoneWrites
;
686 public function writesOrCallbacksPending() {
687 return $this->trxLevel
&& (
688 $this->trxDoneWrites ||
689 $this->trxIdleCallbacks ||
690 $this->trxPreCommitCallbacks ||
691 $this->trxEndCallbacks
695 public function preCommitCallbacksPending() {
696 return $this->trxLevel
&& $this->trxPreCommitCallbacks
;
700 * @return string|null
702 final protected function getTransactionRoundId() {
703 // If transaction round participation is enabled, see if one is active
704 if ( $this->getFlag( self
::DBO_TRX
) ) {
705 $id = $this->getLBInfo( 'trxRoundId' );
707 return is_string( $id ) ?
$id : null;
713 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
714 if ( !$this->trxLevel
) {
716 } elseif ( !$this->trxDoneWrites
) {
721 case self
::ESTIMATE_DB_APPLY
:
722 return $this->pingAndCalculateLastTrxApplyTime();
723 default: // everything
724 return $this->trxWriteDuration
;
729 * @return float Time to apply writes to replicas based on trxWrite* fields
731 private function pingAndCalculateLastTrxApplyTime() {
734 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
735 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
736 // For omitted queries, make them count as something at least
737 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
738 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
743 public function pendingWriteCallers() {
744 return $this->trxLevel ?
$this->trxWriteCallers
: [];
747 public function pendingWriteRowsAffected() {
748 return $this->trxWriteAffectedRows
;
752 * List the methods that have write queries or callbacks for the current transaction
754 * This method should not be used outside of Database/LoadBalancer
759 public function pendingWriteAndCallbackCallers() {
760 $fnames = $this->pendingWriteCallers();
762 $this->trxIdleCallbacks
,
763 $this->trxPreCommitCallbacks
,
764 $this->trxEndCallbacks
766 foreach ( $callbacks as $callback ) {
767 $fnames[] = $callback[1];
777 private function flatAtomicSectionList() {
778 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
779 return $accum === null ?
$v[0] : "$accum, " . $v[0];
783 public function isOpen() {
784 return $this->opened
;
787 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
788 if ( ( $flag & self
::DBO_IGNORE
) ) {
789 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
792 if ( $remember === self
::REMEMBER_PRIOR
) {
793 array_push( $this->priorFlags
, $this->flags
);
795 $this->flags |
= $flag;
798 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
799 if ( ( $flag & self
::DBO_IGNORE
) ) {
800 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
803 if ( $remember === self
::REMEMBER_PRIOR
) {
804 array_push( $this->priorFlags
, $this->flags
);
806 $this->flags
&= ~
$flag;
809 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
810 if ( !$this->priorFlags
) {
814 if ( $state === self
::RESTORE_INITIAL
) {
815 $this->flags
= reset( $this->priorFlags
);
816 $this->priorFlags
= [];
818 $this->flags
= array_pop( $this->priorFlags
);
822 public function getFlag( $flag ) {
823 return (bool)( $this->flags
& $flag );
827 * @param string $name Class field name
829 * @deprecated Since 1.28
831 public function getProperty( $name ) {
835 public function getDomainID() {
836 return $this->currentDomain
->getId();
839 final public function getWikiID() {
840 return $this->getDomainID();
844 * Get information about an index into an object
845 * @param string $table Table name
846 * @param string $index Index name
847 * @param string $fname Calling function name
848 * @return mixed Database-specific index description class or false if the index does not exist
850 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
853 * Wrapper for addslashes()
855 * @param string $s String to be slashed.
856 * @return string Slashed string.
858 abstract function strencode( $s );
861 * Set a custom error handler for logging errors during database connection
863 protected function installErrorHandler() {
864 $this->phpError
= false;
865 $this->htmlErrors
= ini_set( 'html_errors', '0' );
866 set_error_handler( [ $this, 'connectionErrorLogger' ] );
870 * Restore the previous error handler and return the last PHP error for this DB
872 * @return bool|string
874 protected function restoreErrorHandler() {
875 restore_error_handler();
876 if ( $this->htmlErrors
!== false ) {
877 ini_set( 'html_errors', $this->htmlErrors
);
880 return $this->getLastPHPError();
884 * @return string|bool Last PHP error for this DB (typically connection errors)
886 protected function getLastPHPError() {
887 if ( $this->phpError
) {
888 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
889 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
898 * Error handler for logging errors during database connection
899 * This method should not be used outside of Database classes
902 * @param string $errstr
904 public function connectionErrorLogger( $errno, $errstr ) {
905 $this->phpError
= $errstr;
909 * Create a log context to pass to PSR-3 logger functions.
911 * @param array $extras Additional data to add to context
914 protected function getLogContext( array $extras = [] ) {
917 'db_server' => $this->server
,
918 'db_name' => $this->getDBname(),
919 'db_user' => $this->user
,
925 final public function close() {
926 $exception = null; // error to throw after disconnecting
929 // Roll back any dangling transaction first
930 if ( $this->trxLevel
) {
931 if ( $this->trxAtomicLevels
) {
932 // Cannot let incomplete atomic sections be committed
933 $levels = $this->flatAtomicSectionList();
934 $exception = new DBUnexpectedError(
936 __METHOD__
. ": atomic sections $levels are still open."
938 } elseif ( $this->trxAutomatic
) {
939 // Only the connection manager can commit non-empty DBO_TRX transactions
940 // (empty ones we can silently roll back)
941 if ( $this->writesOrCallbacksPending() ) {
942 $exception = new DBUnexpectedError(
945 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
949 // Manual transactions should have been committed or rolled
950 // back, even if empty.
951 $exception = new DBUnexpectedError(
953 __METHOD__
. ": transaction is still open (from {$this->trxFname})."
957 if ( $this->trxEndCallbacksSuppressed
) {
958 $exception = $exception ?
: new DBUnexpectedError(
960 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
964 // Rollback the changes and run any callbacks as needed
965 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
968 // Close the actual connection in the binding handle
969 $closed = $this->closeConnection();
972 $closed = true; // already closed; nothing to do
975 $this->opened
= false;
977 // Throw any unexpected errors after having disconnected
978 if ( $exception instanceof Exception
) {
982 // Sanity check that no callbacks are dangling
983 $fnames = $this->pendingWriteAndCallbackCallers();
985 throw new RuntimeException(
986 "Transaction callbacks are still pending:\n" . implode( ', ', $fnames )
994 * Make sure there is an open connection handle (alive or not) as a sanity check
996 * This guards against fatal errors to the binding handle not being defined
997 * in cases where open() was never called or close() was already called
999 * @throws DBUnexpectedError
1001 protected function assertHasConnectionHandle() {
1002 if ( !$this->isOpen() ) {
1003 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1008 * Make sure that this server is not marked as a replica nor read-only as a sanity check
1010 * @throws DBUnexpectedError
1012 protected function assertIsWritableMaster() {
1013 if ( $this->getLBInfo( 'replica' ) === true ) {
1014 throw new DBUnexpectedError(
1016 'Write operations are not allowed on replica database connections.'
1019 $reason = $this->getReadOnlyReason();
1020 if ( $reason !== false ) {
1021 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1026 * Closes underlying database connection
1028 * @return bool Whether connection was closed successfully
1030 abstract protected function closeConnection();
1033 * @deprecated since 1.32
1034 * @param string $error Fallback message, if none is given by DB
1035 * @throws DBConnectionError
1037 public function reportConnectionError( $error = 'Unknown error' ) {
1038 call_user_func( $this->deprecationLogger
, 'Use of ' . __METHOD__
. ' is deprecated.' );
1039 throw new DBConnectionError( $this, $this->lastError() ?
: $error );
1043 * Run a query and return a DBMS-dependent wrapper or boolean
1045 * For SELECT queries, this returns either:
1046 * - a) A driver-specific value/resource, only on success. This can be iterated
1047 * over by calling fetchObject()/fetchRow() until there are no more rows.
1048 * Alternatively, the result can be passed to resultObject() to obtain a
1049 * ResultWrapper instance which can then be iterated over via "foreach".
1050 * - b) False, on any query failure
1052 * For non-SELECT queries, this returns either:
1053 * - a) A driver-specific value/resource, only on success
1054 * - b) True, only on success (e.g. no meaningful result other than "OK")
1055 * - c) False, on any query failure
1057 * @param string $sql SQL query
1058 * @return mixed|bool An object, resource, or true on success; false on failure
1060 abstract protected function doQuery( $sql );
1063 * Determine whether a query writes to the DB. When in doubt, this returns true.
1067 * - Subsequent web requests should not need to wait for replication from
1068 * the master position seen by this web request, unless this request made
1069 * changes to the master. This is handled by ChronologyProtector by checking
1070 * doneWrites() at the end of the request. doneWrites() returns true if any
1071 * query set lastWriteTime; which query() does based on isWriteQuery().
1073 * - Reject write queries to replica DBs, in query().
1075 * @param string $sql
1078 protected function isWriteQuery( $sql ) {
1079 // BEGIN and COMMIT queries are considered read queries here.
1080 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1081 // treat these as write queries, in that their results have "affected rows"
1082 // as meta data as from writes, instead of "num rows" as from reads.
1083 // But, we treat them as read queries because when reading data (from
1084 // either replica or master) we use transactions to enable repeatable-read
1085 // snapshots, which ensures we get consistent results from the same snapshot
1086 // for all queries within a request. Use cases:
1087 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1088 // - We use this method to reject writes to replicas, but we need to allow
1089 // use of transactions on replicas for read snapshots. This fine given
1090 // that transactions by themselves don't make changes, only actual writes
1091 // within the transaction matter, which we still detect.
1093 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|\(SELECT)\b/i',
1099 * @param string $sql
1100 * @return string|null
1102 protected function getQueryVerb( $sql ) {
1103 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1107 * Determine whether a SQL statement is sensitive to isolation level.
1109 * A SQL statement is considered transactable if its result could vary
1110 * depending on the transaction isolation level. Operational commands
1111 * such as 'SET' and 'SHOW' are not considered to be transactable.
1113 * Main purpose: Used by query() to decide whether to begin a transaction
1114 * before the current query (in DBO_TRX mode, on by default).
1116 * @param string $sql
1119 protected function isTransactableQuery( $sql ) {
1121 $this->getQueryVerb( $sql ),
1122 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER' ],
1128 * @param string $sql A SQL query
1129 * @return bool Whether $sql is SQL for TEMPORARY table operation
1131 protected function registerTempTableOperation( $sql ) {
1133 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1137 $this->sessionTempTables
[$matches[1]] = 1;
1140 } elseif ( preg_match(
1141 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1145 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1146 unset( $this->sessionTempTables
[$matches[1]] );
1149 } elseif ( preg_match(
1150 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1154 return isset( $this->sessionTempTables
[$matches[1]] );
1155 } elseif ( preg_match(
1156 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1160 return isset( $this->sessionTempTables
[$matches[1]] );
1166 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1167 $this->assertTransactionStatus( $sql, $fname );
1168 $this->assertHasConnectionHandle();
1170 $priorTransaction = $this->trxLevel
;
1171 $priorWritesPending = $this->writesOrCallbacksPending();
1172 $this->lastQuery
= $sql;
1174 if ( $this->isWriteQuery( $sql ) ) {
1175 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1176 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1177 $this->assertIsWritableMaster();
1178 # Avoid treating temporary table operations as meaningful "writes"
1179 $isEffectiveWrite = !$this->registerTempTableOperation( $sql );
1181 $isEffectiveWrite = false;
1184 # Add trace comment to the begin of the sql string, right after the operator.
1185 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1186 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1188 # Send the query to the server and fetch any corresponding errors
1189 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1190 $lastError = $this->lastError();
1191 $lastErrno = $this->lastErrno();
1193 $recoverableSR = false; // recoverable statement rollback?
1194 $recoverableCL = false; // recoverable connection loss?
1196 if ( $ret === false && $this->wasConnectionLoss() ) {
1197 # Check if no meaningful session state was lost
1198 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1199 # Update session state tracking and try to restore the connection
1200 $reconnected = $this->replaceLostConnection( __METHOD__
);
1201 # Silently resend the query to the server if it is safe and possible
1202 if ( $recoverableCL && $reconnected ) {
1203 $ret = $this->attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname );
1204 $lastError = $this->lastError();
1205 $lastErrno = $this->lastErrno();
1207 if ( $ret === false && $this->wasConnectionLoss() ) {
1208 # Query probably causes disconnects; reconnect and do not re-run it
1209 $this->replaceLostConnection( __METHOD__
);
1211 $recoverableCL = false; // connection does not need recovering
1212 $recoverableSR = $this->wasKnownStatementRollbackError();
1216 $recoverableSR = $this->wasKnownStatementRollbackError();
1219 if ( $ret === false ) {
1220 if ( $priorTransaction ) {
1221 if ( $recoverableSR ) {
1222 # We're ignoring an error that caused just the current query to be aborted.
1223 # But log the cause so we can log a deprecation notice if a caller actually
1225 $this->trxStatusIgnoredCause
= [ $lastError, $lastErrno, $fname ];
1226 } elseif ( !$recoverableCL ) {
1227 # Either the query was aborted or all queries after BEGIN where aborted.
1228 # In the first case, the only options going forward are (a) ROLLBACK, or
1229 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1230 # option is ROLLBACK, since the snapshots would have been released.
1231 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1232 $this->trxStatusCause
=
1233 $this->getQueryExceptionAndLog( $lastError, $lastErrno, $sql, $fname );
1234 $tempIgnore = false; // cannot recover
1235 $this->trxStatusIgnoredCause
= null;
1239 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1242 return $this->resultObject( $ret );
1246 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1248 * @param string $sql Original SQL query
1249 * @param string $commentedSql SQL query with debugging/trace comment
1250 * @param bool $isEffectiveWrite Whether the query is a (non-temporary table) write
1251 * @param string $fname Name of the calling function
1252 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1253 * object for a successful read query, or false on failure
1255 private function attemptQuery( $sql, $commentedSql, $isEffectiveWrite, $fname ) {
1256 $this->beginIfImplied( $sql, $fname );
1258 # Keep track of whether the transaction has write queries pending
1259 if ( $isEffectiveWrite ) {
1260 $this->lastWriteTime
= microtime( true );
1261 if ( $this->trxLevel
&& !$this->trxDoneWrites
) {
1262 $this->trxDoneWrites
= true;
1263 $this->trxProfiler
->transactionWritingIn(
1264 $this->server
, $this->getDomainID(), $this->trxShortId
);
1268 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1269 $this->queryLogger
->debug( "{$this->getDomainID()} {$commentedSql}" );
1272 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1273 # generalizeSQL() will probably cut down the query to reasonable
1274 # logging size most of the time. The substr is really just a sanity check.
1276 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1278 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1281 # Include query transaction state
1282 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1284 $startTime = microtime( true );
1285 if ( $this->profiler
) {
1286 $this->profiler
->profileIn( $queryProf );
1288 $this->affectedRowCount
= null;
1289 $ret = $this->doQuery( $commentedSql );
1290 $this->affectedRowCount
= $this->affectedRows();
1291 if ( $this->profiler
) {
1292 $this->profiler
->profileOut( $queryProf );
1294 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1296 unset( $queryProfSection ); // profile out (if set)
1298 if ( $ret !== false ) {
1299 $this->lastPing
= $startTime;
1300 if ( $isEffectiveWrite && $this->trxLevel
) {
1301 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1302 $this->trxWriteCallers
[] = $fname;
1306 if ( $sql === self
::PING_QUERY
) {
1307 $this->rttEstimate
= $queryRuntime;
1310 $this->trxProfiler
->recordQueryCompletion(
1314 $isEffectiveWrite ?
$this->affectedRows() : $this->numRows( $ret )
1316 $this->queryLogger
->debug( $sql, [
1318 'master' => $isMaster,
1319 'runtime' => $queryRuntime,
1326 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1328 * @param string $sql
1329 * @param string $fname
1331 private function beginIfImplied( $sql, $fname ) {
1334 $this->getFlag( self
::DBO_TRX
) &&
1335 $this->isTransactableQuery( $sql )
1337 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1338 $this->trxAutomatic
= true;
1343 * Update the estimated run-time of a query, not counting large row lock times
1345 * LoadBalancer can be set to rollback transactions that will create huge replication
1346 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1347 * queries, like inserting a row can take a long time due to row locking. This method
1348 * uses some simple heuristics to discount those cases.
1350 * @param string $sql A SQL write query
1351 * @param float $runtime Total runtime, including RTT
1352 * @param int $affected Affected row count
1354 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1355 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1356 $indicativeOfReplicaRuntime = true;
1357 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1358 $verb = $this->getQueryVerb( $sql );
1359 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1360 if ( $verb === 'INSERT' ) {
1361 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1362 } elseif ( $verb === 'REPLACE' ) {
1363 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1367 $this->trxWriteDuration +
= $runtime;
1368 $this->trxWriteQueryCount +
= 1;
1369 $this->trxWriteAffectedRows +
= $affected;
1370 if ( $indicativeOfReplicaRuntime ) {
1371 $this->trxWriteAdjDuration +
= $runtime;
1372 $this->trxWriteAdjQueryCount +
= 1;
1377 * Error out if the DB is not in a valid state for a query via query()
1379 * @param string $sql
1380 * @param string $fname
1381 * @throws DBTransactionStateError
1383 private function assertTransactionStatus( $sql, $fname ) {
1384 $verb = $this->getQueryVerb( $sql );
1385 if ( $verb === 'USE' ) {
1386 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead." );
1389 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1393 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1394 throw new DBTransactionStateError(
1396 "Cannot execute query from $fname while transaction status is ERROR.",
1398 $this->trxStatusCause
1400 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1401 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1402 call_user_func( $this->deprecationLogger
,
1403 "Caller from $fname ignored an error originally raised from $iFname: " .
1404 "[$iLastErrno] $iLastError"
1406 $this->trxStatusIgnoredCause
= null;
1410 public function assertNoOpenTransactions() {
1411 if ( $this->explicitTrxActive() ) {
1412 throw new DBTransactionError(
1414 "Explicit transaction still active. A caller may have caught an error. "
1415 . "Open transactions: " . $this->flatAtomicSectionList()
1421 * Determine whether it is safe to retry queries after a database connection is lost
1423 * @param string $sql SQL query
1424 * @param bool $priorWritesPending Whether there is a transaction open with
1425 * possible write queries or transaction pre-commit/idle callbacks
1426 * waiting on it to finish.
1427 * @return bool True if it is safe to retry the query, false otherwise
1429 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1430 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1431 # Dropped connections also mean that named locks are automatically released.
1432 # Only allow error suppression in autocommit mode or when the lost transaction
1433 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1434 if ( $this->namedLocksHeld
) {
1435 return false; // possible critical section violation
1436 } elseif ( $this->sessionTempTables
) {
1437 return false; // tables might be queried latter
1438 } elseif ( $sql === 'COMMIT' ) {
1439 return !$priorWritesPending; // nothing written anyway? (T127428)
1440 } elseif ( $sql === 'ROLLBACK' ) {
1441 return true; // transaction lost...which is also what was requested :)
1442 } elseif ( $this->explicitTrxActive() ) {
1443 return false; // don't drop atomocity and explicit snapshots
1444 } elseif ( $priorWritesPending ) {
1445 return false; // prior writes lost from implicit transaction
1452 * Clean things up after session (and thus transaction) loss
1454 private function handleSessionLoss() {
1455 // Clean up tracking of session-level things...
1456 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1457 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1458 $this->sessionTempTables
= [];
1459 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1460 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1461 $this->namedLocksHeld
= [];
1462 // Session loss implies transaction loss
1463 $this->handleTransactionLoss();
1467 * Clean things up after transaction loss
1469 private function handleTransactionLoss() {
1470 if ( $this->trxDoneWrites
) {
1471 $this->trxProfiler
->transactionWritingOut(
1473 $this->getDomainID(),
1475 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1476 $this->trxWriteAffectedRows
1479 $this->trxLevel
= 0;
1480 $this->trxAtomicCounter
= 0;
1481 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1482 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1484 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1485 // If callback suppression is set then the array will remain unhandled.
1486 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1487 } catch ( Exception
$ex ) {
1488 // Already logged; move on...
1491 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1492 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1493 } catch ( Exception
$ex ) {
1494 // Already logged; move on...
1499 * Checks whether the cause of the error is detected to be a timeout.
1501 * It returns false by default, and not all engines support detecting this yet.
1502 * If this returns false, it will be treated as a generic query error.
1504 * @param string $error Error text
1505 * @param int $errno Error number
1508 protected function wasQueryTimeout( $error, $errno ) {
1513 * Report a query error. Log the error, and if neither the object ignore
1514 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1516 * @param string $error
1518 * @param string $sql
1519 * @param string $fname
1520 * @param bool $tempIgnore
1521 * @throws DBQueryError
1523 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1524 if ( $tempIgnore ) {
1525 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1527 $exception = $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1534 * @param string $error
1535 * @param string|int $errno
1536 * @param string $sql
1537 * @param string $fname
1540 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1541 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1542 $this->queryLogger
->error(
1543 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1544 $this->getLogContext( [
1545 'method' => __METHOD__
,
1548 'sql1line' => $sql1line,
1550 'trace' => ( new RuntimeException() )->getTraceAsString()
1553 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1554 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1555 if ( $wasQueryTimeout ) {
1556 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1558 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1564 public function freeResult( $res ) {
1567 public function selectField(
1568 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1570 if ( $var === '*' ) { // sanity
1571 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1574 if ( !is_array( $options ) ) {
1575 $options = [ $options ];
1578 $options['LIMIT'] = 1;
1580 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1581 if ( $res === false ||
!$this->numRows( $res ) ) {
1585 $row = $this->fetchRow( $res );
1587 if ( $row !== false ) {
1588 return reset( $row );
1594 public function selectFieldValues(
1595 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1597 if ( $var === '*' ) { // sanity
1598 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1599 } elseif ( !is_string( $var ) ) { // sanity
1600 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1603 if ( !is_array( $options ) ) {
1604 $options = [ $options ];
1607 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1608 if ( $res === false ) {
1613 foreach ( $res as $row ) {
1614 $values[] = $row->value
;
1621 * Returns an optional USE INDEX clause to go after the table, and a
1622 * string to go at the end of the query.
1624 * @param array $options Associative array of options to be turned into
1625 * an SQL query, valid keys are listed in the function.
1627 * @see Database::select()
1629 protected function makeSelectOptions( $options ) {
1630 $preLimitTail = $postLimitTail = '';
1635 foreach ( $options as $key => $option ) {
1636 if ( is_numeric( $key ) ) {
1637 $noKeyOptions[$option] = true;
1641 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1643 $preLimitTail .= $this->makeOrderBy( $options );
1645 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1646 $postLimitTail .= ' FOR UPDATE';
1649 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1650 $postLimitTail .= ' LOCK IN SHARE MODE';
1653 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1654 $startOpts .= 'DISTINCT';
1657 # Various MySQL extensions
1658 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1659 $startOpts .= ' /*! STRAIGHT_JOIN */';
1662 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1663 $startOpts .= ' HIGH_PRIORITY';
1666 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1667 $startOpts .= ' SQL_BIG_RESULT';
1670 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1671 $startOpts .= ' SQL_BUFFER_RESULT';
1674 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1675 $startOpts .= ' SQL_SMALL_RESULT';
1678 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1679 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1682 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1683 $startOpts .= ' SQL_CACHE';
1686 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1687 $startOpts .= ' SQL_NO_CACHE';
1690 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1691 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1695 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1696 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1701 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1705 * Returns an optional GROUP BY with an optional HAVING
1707 * @param array $options Associative array of options
1709 * @see Database::select()
1712 protected function makeGroupByWithHaving( $options ) {
1714 if ( isset( $options['GROUP BY'] ) ) {
1715 $gb = is_array( $options['GROUP BY'] )
1716 ?
implode( ',', $options['GROUP BY'] )
1717 : $options['GROUP BY'];
1718 $sql .= ' GROUP BY ' . $gb;
1720 if ( isset( $options['HAVING'] ) ) {
1721 $having = is_array( $options['HAVING'] )
1722 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1723 : $options['HAVING'];
1724 $sql .= ' HAVING ' . $having;
1731 * Returns an optional ORDER BY
1733 * @param array $options Associative array of options
1735 * @see Database::select()
1738 protected function makeOrderBy( $options ) {
1739 if ( isset( $options['ORDER BY'] ) ) {
1740 $ob = is_array( $options['ORDER BY'] )
1741 ?
implode( ',', $options['ORDER BY'] )
1742 : $options['ORDER BY'];
1744 return ' ORDER BY ' . $ob;
1750 public function select(
1751 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1753 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1755 return $this->query( $sql, $fname );
1758 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1759 $options = [], $join_conds = []
1761 if ( is_array( $vars ) ) {
1762 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1767 $options = (array)$options;
1768 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1769 ?
$options['USE INDEX']
1772 isset( $options['IGNORE INDEX'] ) &&
1773 is_array( $options['IGNORE INDEX'] )
1775 ?
$options['IGNORE INDEX']
1779 $this->selectOptionsIncludeLocking( $options ) &&
1780 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1782 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1783 // functions. Discourage use of such queries to encourage compatibility.
1785 $this->deprecationLogger
,
1786 __METHOD__
. ": aggregation used with a locking SELECT ($fname)."
1790 if ( is_array( $table ) ) {
1792 $this->tableNamesWithIndexClauseOrJOIN(
1793 $table, $useIndexes, $ignoreIndexes, $join_conds );
1794 } elseif ( $table != '' ) {
1796 $this->tableNamesWithIndexClauseOrJOIN(
1797 [ $table ], $useIndexes, $ignoreIndexes, [] );
1802 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1803 $this->makeSelectOptions( $options );
1805 if ( is_array( $conds ) ) {
1806 $conds = $this->makeList( $conds, self
::LIST_AND
);
1809 if ( $conds === null ||
$conds === false ) {
1810 $this->queryLogger
->warning(
1814 . ' with incorrect parameters: $conds must be a string or an array'
1819 if ( $conds === '' ||
$conds === '*' ) {
1820 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1821 } elseif ( is_string( $conds ) ) {
1822 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1823 "WHERE $conds $preLimitTail";
1825 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1828 if ( isset( $options['LIMIT'] ) ) {
1829 $sql = $this->limitResult( $sql, $options['LIMIT'],
1830 $options['OFFSET'] ??
false );
1832 $sql = "$sql $postLimitTail";
1834 if ( isset( $options['EXPLAIN'] ) ) {
1835 $sql = 'EXPLAIN ' . $sql;
1841 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1842 $options = [], $join_conds = []
1844 $options = (array)$options;
1845 $options['LIMIT'] = 1;
1846 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1848 if ( $res === false ) {
1852 if ( !$this->numRows( $res ) ) {
1856 $obj = $this->fetchObject( $res );
1861 public function estimateRowCount(
1862 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1864 $conds = $this->normalizeConditions( $conds, $fname );
1865 $column = $this->extractSingleFieldFromList( $var );
1866 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1867 $conds[] = "$column IS NOT NULL";
1870 $res = $this->select(
1871 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1873 $row = $res ?
$this->fetchRow( $res ) : [];
1875 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1878 public function selectRowCount(
1879 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1881 $conds = $this->normalizeConditions( $conds, $fname );
1882 $column = $this->extractSingleFieldFromList( $var );
1883 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1884 $conds[] = "$column IS NOT NULL";
1887 $res = $this->select(
1889 'tmp_count' => $this->buildSelectSubquery(
1898 [ 'rowcount' => 'COUNT(*)' ],
1902 $row = $res ?
$this->fetchRow( $res ) : [];
1904 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1908 * @param string|array $options
1911 private function selectOptionsIncludeLocking( $options ) {
1912 $options = (array)$options;
1913 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1914 if ( in_array( $lock, $options, true ) ) {
1923 * @param array|string $fields
1924 * @param array|string $options
1927 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1928 foreach ( (array)$options as $key => $value ) {
1929 if ( is_string( $key ) ) {
1930 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1933 } elseif ( is_string( $value ) ) {
1934 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1940 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1941 foreach ( (array)$fields as $field ) {
1942 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1951 * @param array|string $conds
1952 * @param string $fname
1955 final protected function normalizeConditions( $conds, $fname ) {
1956 if ( $conds === null ||
$conds === false ) {
1957 $this->queryLogger
->warning(
1961 . ' with incorrect parameters: $conds must be a string or an array'
1966 if ( !is_array( $conds ) ) {
1967 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1974 * @param array|string $var Field parameter in the style of select()
1975 * @return string|null Column name or null; ignores aliases
1976 * @throws DBUnexpectedError Errors out if multiple columns are given
1978 final protected function extractSingleFieldFromList( $var ) {
1979 if ( is_array( $var ) ) {
1982 } elseif ( count( $var ) == 1 ) {
1983 $column = $var[0] ??
reset( $var );
1985 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1994 public function lockForUpdate(
1995 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1997 if ( !$this->trxLevel
&& !$this->getFlag( self
::DBO_TRX
) ) {
1998 throw new DBUnexpectedError(
2000 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2004 $options = (array)$options;
2005 $options[] = 'FOR UPDATE';
2007 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2011 * Removes most variables from an SQL query and replaces them with X or N for numbers.
2012 * It's only slightly flawed. Don't use for anything important.
2014 * @param string $sql A SQL Query
2018 protected static function generalizeSQL( $sql ) {
2019 # This does the same as the regexp below would do, but in such a way
2020 # as to avoid crashing php on some large strings.
2021 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
2023 $sql = str_replace( "\\\\", '', $sql );
2024 $sql = str_replace( "\\'", '', $sql );
2025 $sql = str_replace( "\\\"", '', $sql );
2026 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
2027 $sql = preg_replace( '/".*"/s', "'X'", $sql );
2029 # All newlines, tabs, etc replaced by single space
2030 $sql = preg_replace( '/\s+/', ' ', $sql );
2033 # except the ones surrounded by characters, e.g. l10n
2034 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
2035 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
2040 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2041 $info = $this->fieldInfo( $table, $field );
2046 public function indexExists( $table, $index, $fname = __METHOD__
) {
2047 if ( !$this->tableExists( $table ) ) {
2051 $info = $this->indexInfo( $table, $index, $fname );
2052 if ( is_null( $info ) ) {
2055 return $info !== false;
2059 abstract public function tableExists( $table, $fname = __METHOD__
);
2061 public function indexUnique( $table, $index ) {
2062 $indexInfo = $this->indexInfo( $table, $index );
2064 if ( !$indexInfo ) {
2068 return !$indexInfo[0]->Non_unique
;
2072 * Helper for Database::insert().
2074 * @param array $options
2077 protected function makeInsertOptions( $options ) {
2078 return implode( ' ', $options );
2081 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2082 # No rows to insert, easy just return now
2083 if ( !count( $a ) ) {
2087 $table = $this->tableName( $table );
2089 if ( !is_array( $options ) ) {
2090 $options = [ $options ];
2093 $options = $this->makeInsertOptions( $options );
2095 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2097 $keys = array_keys( $a[0] );
2100 $keys = array_keys( $a );
2103 $sql = 'INSERT ' . $options .
2104 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2108 foreach ( $a as $row ) {
2114 $sql .= '(' . $this->makeList( $row ) . ')';
2117 $sql .= '(' . $this->makeList( $a ) . ')';
2120 $this->query( $sql, $fname );
2126 * Make UPDATE options array for Database::makeUpdateOptions
2128 * @param array $options
2131 protected function makeUpdateOptionsArray( $options ) {
2132 if ( !is_array( $options ) ) {
2133 $options = [ $options ];
2138 if ( in_array( 'IGNORE', $options ) ) {
2146 * Make UPDATE options for the Database::update function
2148 * @param array $options The options passed to Database::update
2151 protected function makeUpdateOptions( $options ) {
2152 $opts = $this->makeUpdateOptionsArray( $options );
2154 return implode( ' ', $opts );
2157 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2158 $table = $this->tableName( $table );
2159 $opts = $this->makeUpdateOptions( $options );
2160 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2162 if ( $conds !== [] && $conds !== '*' ) {
2163 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2166 $this->query( $sql, $fname );
2171 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2172 if ( !is_array( $a ) ) {
2173 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2179 foreach ( $a as $field => $value ) {
2181 if ( $mode == self
::LIST_AND
) {
2183 } elseif ( $mode == self
::LIST_OR
) {
2192 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2193 $list .= "($value)";
2194 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2197 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2199 // Remove null from array to be handled separately if found
2200 $includeNull = false;
2201 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2202 $includeNull = true;
2203 unset( $value[$nullKey] );
2205 if ( count( $value ) == 0 && !$includeNull ) {
2206 throw new InvalidArgumentException(
2207 __METHOD__
. ": empty input for field $field" );
2208 } elseif ( count( $value ) == 0 ) {
2209 // only check if $field is null
2210 $list .= "$field IS NULL";
2212 // IN clause contains at least one valid element
2213 if ( $includeNull ) {
2214 // Group subconditions to ensure correct precedence
2217 if ( count( $value ) == 1 ) {
2218 // Special-case single values, as IN isn't terribly efficient
2219 // Don't necessarily assume the single key is 0; we don't
2220 // enforce linear numeric ordering on other arrays here.
2221 $value = array_values( $value )[0];
2222 $list .= $field . " = " . $this->addQuotes( $value );
2224 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2226 // if null present in array, append IS NULL
2227 if ( $includeNull ) {
2228 $list .= " OR $field IS NULL)";
2231 } elseif ( $value === null ) {
2232 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2233 $list .= "$field IS ";
2234 } elseif ( $mode == self
::LIST_SET
) {
2235 $list .= "$field = ";
2240 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2242 $list .= "$field = ";
2244 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2251 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2254 foreach ( $data as $base => $sub ) {
2255 if ( count( $sub ) ) {
2256 $conds[] = $this->makeList(
2257 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2263 return $this->makeList( $conds, self
::LIST_OR
);
2265 // Nothing to search for...
2270 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2274 public function bitNot( $field ) {
2278 public function bitAnd( $fieldLeft, $fieldRight ) {
2279 return "($fieldLeft & $fieldRight)";
2282 public function bitOr( $fieldLeft, $fieldRight ) {
2283 return "($fieldLeft | $fieldRight)";
2286 public function buildConcat( $stringList ) {
2287 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2290 public function buildGroupConcatField(
2291 $delim, $table, $field, $conds = '', $join_conds = []
2293 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2295 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2298 public function buildSubstring( $input, $startPosition, $length = null ) {
2299 $this->assertBuildSubstringParams( $startPosition, $length );
2300 $functionBody = "$input FROM $startPosition";
2301 if ( $length !== null ) {
2302 $functionBody .= " FOR $length";
2304 return 'SUBSTRING(' . $functionBody . ')';
2308 * Check type and bounds for parameters to self::buildSubstring()
2310 * All supported databases have substring functions that behave the same for
2311 * positive $startPosition and non-negative $length, but behaviors differ when
2312 * given 0 or negative $startPosition or negative $length. The simplest
2313 * solution to that is to just forbid those values.
2315 * @param int $startPosition
2316 * @param int|null $length
2319 protected function assertBuildSubstringParams( $startPosition, $length ) {
2320 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2321 throw new InvalidArgumentException(
2322 '$startPosition must be a positive integer'
2325 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2326 throw new InvalidArgumentException(
2327 '$length must be null or an integer greater than or equal to 0'
2332 public function buildStringCast( $field ) {
2333 // In theory this should work for any standards-compliant
2334 // SQL implementation, although it may not be the best way to do it.
2335 return "CAST( $field AS CHARACTER )";
2338 public function buildIntegerCast( $field ) {
2339 return 'CAST( ' . $field . ' AS INTEGER )';
2342 public function buildSelectSubquery(
2343 $table, $vars, $conds = '', $fname = __METHOD__
,
2344 $options = [], $join_conds = []
2346 return new Subquery(
2347 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2351 public function databasesAreIndependent() {
2355 final public function selectDB( $db ) {
2356 $this->selectDomain( new DatabaseDomain(
2358 $this->currentDomain
->getSchema(),
2359 $this->currentDomain
->getTablePrefix()
2365 final public function selectDomain( $domain ) {
2366 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2369 protected function doSelectDomain( DatabaseDomain
$domain ) {
2370 $this->currentDomain
= $domain;
2373 public function getDBname() {
2374 return $this->currentDomain
->getDatabase();
2377 public function getServer() {
2378 return $this->server
;
2381 public function tableName( $name, $format = 'quoted' ) {
2382 if ( $name instanceof Subquery
) {
2383 throw new DBUnexpectedError(
2385 __METHOD__
. ': got Subquery instance when expecting a string.'
2389 # Skip the entire process when we have a string quoted on both ends.
2390 # Note that we check the end so that we will still quote any use of
2391 # use of `database`.table. But won't break things if someone wants
2392 # to query a database table with a dot in the name.
2393 if ( $this->isQuotedIdentifier( $name ) ) {
2397 # Lets test for any bits of text that should never show up in a table
2398 # name. Basically anything like JOIN or ON which are actually part of
2399 # SQL queries, but may end up inside of the table value to combine
2400 # sql. Such as how the API is doing.
2401 # Note that we use a whitespace test rather than a \b test to avoid
2402 # any remote case where a word like on may be inside of a table name
2403 # surrounded by symbols which may be considered word breaks.
2404 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2405 $this->queryLogger
->warning(
2406 __METHOD__
. ": use of subqueries is not supported this way.",
2407 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2413 # Split database and table into proper variables.
2414 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2416 # Quote $table and apply the prefix if not quoted.
2417 # $tableName might be empty if this is called from Database::replaceVars()
2418 $tableName = "{$prefix}{$table}";
2419 if ( $format === 'quoted'
2420 && !$this->isQuotedIdentifier( $tableName )
2421 && $tableName !== ''
2423 $tableName = $this->addIdentifierQuotes( $tableName );
2426 # Quote $schema and $database and merge them with the table name if needed
2427 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2428 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2434 * Get the table components needed for a query given the currently selected database
2436 * @param string $name Table name in the form of db.schema.table, db.table, or table
2437 * @return array (DB name or "" for default, schema name, table prefix, table name)
2439 protected function qualifiedTableComponents( $name ) {
2440 # We reverse the explode so that database.table and table both output the correct table.
2441 $dbDetails = explode( '.', $name, 3 );
2442 if ( count( $dbDetails ) == 3 ) {
2443 list( $database, $schema, $table ) = $dbDetails;
2444 # We don't want any prefix added in this case
2446 } elseif ( count( $dbDetails ) == 2 ) {
2447 list( $database, $table ) = $dbDetails;
2448 # We don't want any prefix added in this case
2450 # In dbs that support it, $database may actually be the schema
2451 # but that doesn't affect any of the functionality here
2454 list( $table ) = $dbDetails;
2455 if ( isset( $this->tableAliases
[$table] ) ) {
2456 $database = $this->tableAliases
[$table]['dbname'];
2457 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2458 ?
$this->tableAliases
[$table]['schema']
2459 : $this->relationSchemaQualifier();
2460 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2461 ?
$this->tableAliases
[$table]['prefix']
2462 : $this->tablePrefix();
2465 $schema = $this->relationSchemaQualifier(); # Default schema
2466 $prefix = $this->tablePrefix(); # Default prefix
2470 return [ $database, $schema, $prefix, $table ];
2474 * @param string|null $namespace Database or schema
2475 * @param string $relation Name of table, view, sequence, etc...
2476 * @param string $format One of (raw, quoted)
2477 * @return string Relation name with quoted and merged $namespace as needed
2479 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2480 if ( strlen( $namespace ) ) {
2481 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2482 $namespace = $this->addIdentifierQuotes( $namespace );
2484 $relation = $namespace . '.' . $relation;
2490 public function tableNames() {
2491 $inArray = func_get_args();
2494 foreach ( $inArray as $name ) {
2495 $retVal[$name] = $this->tableName( $name );
2501 public function tableNamesN() {
2502 $inArray = func_get_args();
2505 foreach ( $inArray as $name ) {
2506 $retVal[] = $this->tableName( $name );
2513 * Get an aliased table name
2515 * This returns strings like "tableName AS newTableName" for aliased tables
2516 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2518 * @see Database::tableName()
2519 * @param string|Subquery $table Table name or object with a 'sql' field
2520 * @param string|bool $alias Table alias (optional)
2521 * @return string SQL name for aliased table. Will not alias a table to its own name
2523 protected function tableNameWithAlias( $table, $alias = false ) {
2524 if ( is_string( $table ) ) {
2525 $quotedTable = $this->tableName( $table );
2526 } elseif ( $table instanceof Subquery
) {
2527 $quotedTable = (string)$table;
2529 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2532 if ( !strlen( $alias ) ||
$alias === $table ) {
2533 if ( $table instanceof Subquery
) {
2534 throw new InvalidArgumentException( "Subquery table missing alias." );
2537 return $quotedTable;
2539 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2544 * Gets an array of aliased table names
2546 * @param array $tables [ [alias] => table ]
2547 * @return string[] See tableNameWithAlias()
2549 protected function tableNamesWithAlias( $tables ) {
2551 foreach ( $tables as $alias => $table ) {
2552 if ( is_numeric( $alias ) ) {
2555 $retval[] = $this->tableNameWithAlias( $table, $alias );
2562 * Get an aliased field name
2563 * e.g. fieldName AS newFieldName
2565 * @param string $name Field name
2566 * @param string|bool $alias Alias (optional)
2567 * @return string SQL name for aliased field. Will not alias a field to its own name
2569 protected function fieldNameWithAlias( $name, $alias = false ) {
2570 if ( !$alias ||
(string)$alias === (string)$name ) {
2573 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2578 * Gets an array of aliased field names
2580 * @param array $fields [ [alias] => field ]
2581 * @return string[] See fieldNameWithAlias()
2583 protected function fieldNamesWithAlias( $fields ) {
2585 foreach ( $fields as $alias => $field ) {
2586 if ( is_numeric( $alias ) ) {
2589 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2596 * Get the aliased table name clause for a FROM clause
2597 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2599 * @param array $tables ( [alias] => table )
2600 * @param array $use_index Same as for select()
2601 * @param array $ignore_index Same as for select()
2602 * @param array $join_conds Same as for select()
2605 protected function tableNamesWithIndexClauseOrJOIN(
2606 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2610 $use_index = (array)$use_index;
2611 $ignore_index = (array)$ignore_index;
2612 $join_conds = (array)$join_conds;
2614 foreach ( $tables as $alias => $table ) {
2615 if ( !is_string( $alias ) ) {
2616 // No alias? Set it equal to the table name
2620 if ( is_array( $table ) ) {
2621 // A parenthesized group
2622 if ( count( $table ) > 1 ) {
2623 $joinedTable = '(' .
2624 $this->tableNamesWithIndexClauseOrJOIN(
2625 $table, $use_index, $ignore_index, $join_conds ) . ')';
2628 $innerTable = reset( $table );
2629 $innerAlias = key( $table );
2630 $joinedTable = $this->tableNameWithAlias(
2632 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2636 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2639 // Is there a JOIN clause for this table?
2640 if ( isset( $join_conds[$alias] ) ) {
2641 list( $joinType, $conds ) = $join_conds[$alias];
2642 $tableClause = $joinType;
2643 $tableClause .= ' ' . $joinedTable;
2644 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2645 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2647 $tableClause .= ' ' . $use;
2650 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2651 $ignore = $this->ignoreIndexClause(
2652 implode( ',', (array)$ignore_index[$alias] ) );
2653 if ( $ignore != '' ) {
2654 $tableClause .= ' ' . $ignore;
2657 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2659 $tableClause .= ' ON (' . $on . ')';
2662 $retJOIN[] = $tableClause;
2663 } elseif ( isset( $use_index[$alias] ) ) {
2664 // Is there an INDEX clause for this table?
2665 $tableClause = $joinedTable;
2666 $tableClause .= ' ' . $this->useIndexClause(
2667 implode( ',', (array)$use_index[$alias] )
2670 $ret[] = $tableClause;
2671 } elseif ( isset( $ignore_index[$alias] ) ) {
2672 // Is there an INDEX clause for this table?
2673 $tableClause = $joinedTable;
2674 $tableClause .= ' ' . $this->ignoreIndexClause(
2675 implode( ',', (array)$ignore_index[$alias] )
2678 $ret[] = $tableClause;
2680 $tableClause = $joinedTable;
2682 $ret[] = $tableClause;
2686 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2687 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2688 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2690 // Compile our final table clause
2691 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2695 * Allows for index remapping in queries where this is not consistent across DBMS
2697 * @param string $index
2700 protected function indexName( $index ) {
2701 return $this->indexAliases
[$index] ??
$index;
2704 public function addQuotes( $s ) {
2705 if ( $s instanceof Blob
) {
2708 if ( $s === null ) {
2710 } elseif ( is_bool( $s ) ) {
2713 # This will also quote numeric values. This should be harmless,
2714 # and protects against weird problems that occur when they really
2715 # _are_ strings such as article titles and string->number->string
2716 # conversion is not 1:1.
2717 return "'" . $this->strencode( $s ) . "'";
2721 public function addIdentifierQuotes( $s ) {
2722 return '"' . str_replace( '"', '""', $s ) . '"';
2726 * Returns if the given identifier looks quoted or not according to
2727 * the database convention for quoting identifiers .
2729 * @note Do not use this to determine if untrusted input is safe.
2730 * A malicious user can trick this function.
2731 * @param string $name
2734 public function isQuotedIdentifier( $name ) {
2735 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2740 * @param string $escapeChar
2743 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2744 return str_replace( [ $escapeChar, '%', '_' ],
2745 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2749 public function buildLike() {
2750 $params = func_get_args();
2752 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2753 $params = $params[0];
2758 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2759 // may escape backslashes, creating problems of double escaping. The `
2760 // character has good cross-DBMS compatibility, avoiding special operators
2761 // in MS SQL like ^ and %
2764 foreach ( $params as $value ) {
2765 if ( $value instanceof LikeMatch
) {
2766 $s .= $value->toString();
2768 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2773 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2776 public function anyChar() {
2777 return new LikeMatch( '_' );
2780 public function anyString() {
2781 return new LikeMatch( '%' );
2784 public function nextSequenceValue( $seqName ) {
2789 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2790 * is only needed because a) MySQL must be as efficient as possible due to
2791 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2792 * which index to pick. Anyway, other databases might have different
2793 * indexes on a given table. So don't bother overriding this unless you're
2795 * @param string $index
2798 public function useIndexClause( $index ) {
2803 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2804 * is only needed because a) MySQL must be as efficient as possible due to
2805 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2806 * which index to pick. Anyway, other databases might have different
2807 * indexes on a given table. So don't bother overriding this unless you're
2809 * @param string $index
2812 public function ignoreIndexClause( $index ) {
2816 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2817 if ( count( $rows ) == 0 ) {
2821 $uniqueIndexes = (array)$uniqueIndexes;
2823 if ( !is_array( reset( $rows ) ) ) {
2828 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2829 $affectedRowCount = 0;
2830 foreach ( $rows as $row ) {
2831 // Delete rows which collide with this one
2832 $indexWhereClauses = [];
2833 foreach ( $uniqueIndexes as $index ) {
2834 $indexColumns = (array)$index;
2835 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2836 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2837 throw new DBUnexpectedError(
2839 'New record does not provide all values for unique key (' .
2840 implode( ', ', $indexColumns ) . ')'
2842 } elseif ( in_array( null, $indexRowValues, true ) ) {
2843 throw new DBUnexpectedError(
2845 'New record has a null value for unique key (' .
2846 implode( ', ', $indexColumns ) . ')'
2849 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2852 if ( $indexWhereClauses ) {
2853 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2854 $affectedRowCount +
= $this->affectedRows();
2857 // Now insert the row
2858 $this->insert( $table, $row, $fname );
2859 $affectedRowCount +
= $this->affectedRows();
2861 $this->endAtomic( $fname );
2862 $this->affectedRowCount
= $affectedRowCount;
2863 } catch ( Exception
$e ) {
2864 $this->cancelAtomic( $fname );
2870 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2873 * @param string $table Table name
2874 * @param array|string $rows Row(s) to insert
2875 * @param string $fname Caller function name
2877 protected function nativeReplace( $table, $rows, $fname ) {
2878 $table = $this->tableName( $table );
2881 if ( !is_array( reset( $rows ) ) ) {
2885 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2888 foreach ( $rows as $row ) {
2895 $sql .= '(' . $this->makeList( $row ) . ')';
2898 $this->query( $sql, $fname );
2901 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2904 if ( $rows === [] ) {
2905 return true; // nothing to do
2908 $uniqueIndexes = (array)$uniqueIndexes;
2909 if ( !is_array( reset( $rows ) ) ) {
2913 if ( count( $uniqueIndexes ) ) {
2914 $clauses = []; // list WHERE clauses that each identify a single row
2915 foreach ( $rows as $row ) {
2916 foreach ( $uniqueIndexes as $index ) {
2917 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2918 $rowKey = []; // unique key to this row
2919 foreach ( $index as $column ) {
2920 $rowKey[$column] = $row[$column];
2922 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2925 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2930 $affectedRowCount = 0;
2932 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2933 # Update any existing conflicting row(s)
2934 if ( $where !== false ) {
2935 $this->update( $table, $set, $where, $fname );
2936 $affectedRowCount +
= $this->affectedRows();
2938 # Now insert any non-conflicting row(s)
2939 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2940 $affectedRowCount +
= $this->affectedRows();
2941 $this->endAtomic( $fname );
2942 $this->affectedRowCount
= $affectedRowCount;
2943 } catch ( Exception
$e ) {
2944 $this->cancelAtomic( $fname );
2951 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2955 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2958 $delTable = $this->tableName( $delTable );
2959 $joinTable = $this->tableName( $joinTable );
2960 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2961 if ( $conds != '*' ) {
2962 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2966 $this->query( $sql, $fname );
2969 public function textFieldSize( $table, $field ) {
2970 $table = $this->tableName( $table );
2971 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2972 $res = $this->query( $sql, __METHOD__
);
2973 $row = $this->fetchObject( $res );
2977 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2986 public function delete( $table, $conds, $fname = __METHOD__
) {
2988 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2991 $table = $this->tableName( $table );
2992 $sql = "DELETE FROM $table";
2994 if ( $conds != '*' ) {
2995 if ( is_array( $conds ) ) {
2996 $conds = $this->makeList( $conds, self
::LIST_AND
);
2998 $sql .= ' WHERE ' . $conds;
3001 $this->query( $sql, $fname );
3006 final public function insertSelect(
3007 $destTable, $srcTable, $varMap, $conds,
3008 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3010 static $hints = [ 'NO_AUTO_COLUMNS' ];
3012 $insertOptions = (array)$insertOptions;
3013 $selectOptions = (array)$selectOptions;
3015 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3016 // For massive migrations with downtime, we don't want to select everything
3017 // into memory and OOM, so do all this native on the server side if possible.
3018 $this->nativeInsertSelect(
3024 array_diff( $insertOptions, $hints ),
3029 $this->nonNativeInsertSelect(
3035 array_diff( $insertOptions, $hints ),
3045 * @param array $insertOptions INSERT options
3046 * @param array $selectOptions SELECT options
3047 * @return bool Whether an INSERT SELECT with these options will be replication safe
3050 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3055 * Implementation of insertSelect() based on select() and insert()
3057 * @see IDatabase::insertSelect()
3059 * @param string $destTable
3060 * @param string|array $srcTable
3061 * @param array $varMap
3062 * @param array $conds
3063 * @param string $fname
3064 * @param array $insertOptions
3065 * @param array $selectOptions
3066 * @param array $selectJoinConds
3068 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3069 $fname = __METHOD__
,
3070 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3072 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3073 // on only the master (without needing row-based-replication). It also makes it easy to
3074 // know how big the INSERT is going to be.
3076 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3077 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3079 $selectOptions[] = 'FOR UPDATE';
3080 $res = $this->select(
3081 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3088 $affectedRowCount = 0;
3089 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3092 foreach ( $res as $row ) {
3093 $rows[] = (array)$row;
3095 // Avoid inserts that are too huge
3096 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3097 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3101 $affectedRowCount +
= $this->affectedRows();
3105 if ( $rows && $ok ) {
3106 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3108 $affectedRowCount +
= $this->affectedRows();
3112 $this->endAtomic( $fname );
3113 $this->affectedRowCount
= $affectedRowCount;
3115 $this->cancelAtomic( $fname );
3117 } catch ( Exception
$e ) {
3118 $this->cancelAtomic( $fname );
3124 * Native server-side implementation of insertSelect() for situations where
3125 * we don't want to select everything into memory
3127 * @see IDatabase::insertSelect()
3128 * @param string $destTable
3129 * @param string|array $srcTable
3130 * @param array $varMap
3131 * @param array $conds
3132 * @param string $fname
3133 * @param array $insertOptions
3134 * @param array $selectOptions
3135 * @param array $selectJoinConds
3137 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3138 $fname = __METHOD__
,
3139 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3141 $destTable = $this->tableName( $destTable );
3143 if ( !is_array( $insertOptions ) ) {
3144 $insertOptions = [ $insertOptions ];
3147 $insertOptions = $this->makeInsertOptions( $insertOptions );
3149 $selectSql = $this->selectSQLText(
3151 array_values( $varMap ),
3158 $sql = "INSERT $insertOptions" .
3159 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3162 $this->query( $sql, $fname );
3166 * Construct a LIMIT query with optional offset. This is used for query
3167 * pages. The SQL should be adjusted so that only the first $limit rows
3168 * are returned. If $offset is provided as well, then the first $offset
3169 * rows should be discarded, and the next $limit rows should be returned.
3170 * If the result of the query is not ordered, then the rows to be returned
3171 * are theoretically arbitrary.
3173 * $sql is expected to be a SELECT, if that makes a difference.
3175 * The version provided by default works in MySQL and SQLite. It will very
3176 * likely need to be overridden for most other DBMSes.
3178 * @param string $sql SQL query we will append the limit too
3179 * @param int $limit The SQL limit
3180 * @param int|bool $offset The SQL offset (default false)
3181 * @throws DBUnexpectedError
3184 public function limitResult( $sql, $limit, $offset = false ) {
3185 if ( !is_numeric( $limit ) ) {
3186 throw new DBUnexpectedError( $this,
3187 "Invalid non-numeric limit passed to limitResult()\n" );
3190 return "$sql LIMIT "
3191 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3195 public function unionSupportsOrderAndLimit() {
3196 return true; // True for almost every DB supported
3199 public function unionQueries( $sqls, $all ) {
3200 $glue = $all ?
') UNION ALL (' : ') UNION (';
3202 return '(' . implode( $glue, $sqls ) . ')';
3205 public function unionConditionPermutations(
3206 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3207 $options = [], $join_conds = []
3209 // First, build the Cartesian product of $permute_conds
3211 foreach ( $permute_conds as $field => $values ) {
3213 // Skip empty $values
3216 $values = array_unique( $values ); // For sanity
3218 foreach ( $conds as $cond ) {
3219 foreach ( $values as $value ) {
3220 $cond[$field] = $value;
3221 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3227 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3229 // If there's just one condition and no subordering, hand off to
3230 // selectSQLText directly.
3231 if ( count( $conds ) === 1 &&
3232 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3234 return $this->selectSQLText(
3235 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3239 // Otherwise, we need to pull out the order and limit to apply after
3240 // the union. Then build the SQL queries for each set of conditions in
3241 // $conds. Then union them together (using UNION ALL, because the
3242 // product *should* already be distinct).
3243 $orderBy = $this->makeOrderBy( $options );
3244 $limit = $options['LIMIT'] ??
null;
3245 $offset = $options['OFFSET'] ??
false;
3246 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3247 if ( !$this->unionSupportsOrderAndLimit() ) {
3248 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3250 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3251 $options['ORDER BY'] = $options['INNER ORDER BY'];
3253 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3254 // We need to increase the limit by the offset rather than
3255 // using the offset directly, otherwise it'll skip incorrectly
3256 // in the subqueries.
3257 $options['LIMIT'] = $limit +
$offset;
3258 unset( $options['OFFSET'] );
3263 foreach ( $conds as $cond ) {
3264 $sqls[] = $this->selectSQLText(
3265 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3268 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3269 if ( $limit !== null ) {
3270 $sql = $this->limitResult( $sql, $limit, $offset );
3276 public function conditional( $cond, $trueVal, $falseVal ) {
3277 if ( is_array( $cond ) ) {
3278 $cond = $this->makeList( $cond, self
::LIST_AND
);
3281 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3284 public function strreplace( $orig, $old, $new ) {
3285 return "REPLACE({$orig}, {$old}, {$new})";
3288 public function getServerUptime() {
3292 public function wasDeadlock() {
3296 public function wasLockTimeout() {
3300 public function wasConnectionLoss() {
3301 return $this->wasConnectionError( $this->lastErrno() );
3304 public function wasReadOnlyError() {
3308 public function wasErrorReissuable() {
3310 $this->wasDeadlock() ||
3311 $this->wasLockTimeout() ||
3312 $this->wasConnectionLoss()
3317 * Do not use this method outside of Database/DBError classes
3319 * @param int|string $errno
3320 * @return bool Whether the given query error was a connection drop
3322 public function wasConnectionError( $errno ) {
3327 * @return bool Whether it is known that the last query error only caused statement rollback
3328 * @note This is for backwards compatibility for callers catching DBError exceptions in
3329 * order to ignore problems like duplicate key errors or foriegn key violations
3332 protected function wasKnownStatementRollbackError() {
3333 return false; // don't know; it could have caused a transaction rollback
3336 public function deadlockLoop() {
3337 $args = func_get_args();
3338 $function = array_shift( $args );
3339 $tries = self
::DEADLOCK_TRIES
;
3341 $this->begin( __METHOD__
);
3344 /** @var Exception $e */
3348 $retVal = $function( ...$args );
3350 } catch ( DBQueryError
$e ) {
3351 if ( $this->wasDeadlock() ) {
3352 // Retry after a randomized delay
3353 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3355 // Throw the error back up
3359 } while ( --$tries > 0 );
3361 if ( $tries <= 0 ) {
3362 // Too many deadlocks; give up
3363 $this->rollback( __METHOD__
);
3366 $this->commit( __METHOD__
);
3372 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3373 # Real waits are implemented in the subclass.
3377 public function getReplicaPos() {
3382 public function getMasterPos() {
3387 public function serverIsReadOnly() {
3391 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3392 if ( !$this->trxLevel
) {
3393 throw new DBUnexpectedError( $this, "No transaction is active." );
3395 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3398 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3399 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3400 // Start an implicit transaction similar to how query() does
3401 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3402 $this->trxAutomatic
= true;
3405 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3406 if ( !$this->trxLevel
) {
3407 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3411 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3412 $this->onTransactionCommitOrIdle( $callback, $fname );
3415 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3416 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3417 // Start an implicit transaction similar to how query() does
3418 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3419 $this->trxAutomatic
= true;
3422 if ( $this->trxLevel
) {
3423 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3425 // No transaction is active nor will start implicitly, so make one for this callback
3426 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3429 $this->endAtomic( __METHOD__
);
3430 } catch ( Exception
$e ) {
3431 $this->cancelAtomic( __METHOD__
);
3438 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3440 private function currentAtomicSectionId() {
3441 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3442 $levelInfo = end( $this->trxAtomicLevels
);
3444 return $levelInfo[1];
3451 * @param AtomicSectionIdentifier $old
3452 * @param AtomicSectionIdentifier $new
3454 private function reassignCallbacksForSection(
3455 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3457 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3458 if ( $info[2] === $old ) {
3459 $this->trxPreCommitCallbacks
[$key][2] = $new;
3462 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3463 if ( $info[2] === $old ) {
3464 $this->trxIdleCallbacks
[$key][2] = $new;
3467 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3468 if ( $info[2] === $old ) {
3469 $this->trxEndCallbacks
[$key][2] = $new;
3475 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3476 * @throws UnexpectedValueException
3478 private function modifyCallbacksForCancel( array $sectionIds ) {
3479 // Cancel the "on commit" callbacks owned by this savepoint
3480 $this->trxIdleCallbacks
= array_filter(
3481 $this->trxIdleCallbacks
,
3482 function ( $entry ) use ( $sectionIds ) {
3483 return !in_array( $entry[2], $sectionIds, true );
3486 $this->trxPreCommitCallbacks
= array_filter(
3487 $this->trxPreCommitCallbacks
,
3488 function ( $entry ) use ( $sectionIds ) {
3489 return !in_array( $entry[2], $sectionIds, true );
3492 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3493 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3494 if ( in_array( $entry[2], $sectionIds, true ) ) {
3495 $callback = $entry[0];
3496 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3497 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3503 final public function setTransactionListener( $name, callable
$callback = null ) {
3505 $this->trxRecurringCallbacks
[$name] = $callback;
3507 unset( $this->trxRecurringCallbacks
[$name] );
3512 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3514 * This method should not be used outside of Database/LoadBalancer
3516 * @param bool $suppress
3519 final public function setTrxEndCallbackSuppression( $suppress ) {
3520 $this->trxEndCallbacksSuppressed
= $suppress;
3524 * Actually consume and run any "on transaction idle/resolution" callbacks.
3526 * This method should not be used outside of Database/LoadBalancer
3528 * @param int $trigger IDatabase::TRIGGER_* constant
3529 * @return int Number of callbacks attempted
3533 public function runOnTransactionIdleCallbacks( $trigger ) {
3534 if ( $this->trxLevel
) { // sanity
3535 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open.' );
3538 if ( $this->trxEndCallbacksSuppressed
) {
3543 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3544 /** @var Exception $e */
3545 $e = null; // first exception
3546 do { // callbacks may add callbacks :)
3547 $callbacks = array_merge(
3548 $this->trxIdleCallbacks
,
3549 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3551 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3552 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3553 foreach ( $callbacks as $callback ) {
3555 list( $phpCallback ) = $callback;
3556 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3558 call_user_func( $phpCallback, $trigger, $this );
3559 } catch ( Exception
$ex ) {
3560 call_user_func( $this->errorLogger
, $ex );
3562 // Some callbacks may use startAtomic/endAtomic, so make sure
3563 // their transactions are ended so other callbacks don't fail
3564 if ( $this->trxLevel() ) {
3565 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3569 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3571 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3575 } while ( count( $this->trxIdleCallbacks
) );
3577 if ( $e instanceof Exception
) {
3578 throw $e; // re-throw any first exception
3585 * Actually consume and run any "on transaction pre-commit" callbacks.
3587 * This method should not be used outside of Database/LoadBalancer
3590 * @return int Number of callbacks attempted
3593 public function runOnTransactionPreCommitCallbacks() {
3596 $e = null; // first exception
3597 do { // callbacks may add callbacks :)
3598 $callbacks = $this->trxPreCommitCallbacks
;
3599 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3600 foreach ( $callbacks as $callback ) {
3603 list( $phpCallback ) = $callback;
3604 $phpCallback( $this );
3605 } catch ( Exception
$ex ) {
3606 ( $this->errorLogger
)( $ex );
3610 } while ( count( $this->trxPreCommitCallbacks
) );
3612 if ( $e instanceof Exception
) {
3613 throw $e; // re-throw any first exception
3620 * Actually run any "transaction listener" callbacks.
3622 * This method should not be used outside of Database/LoadBalancer
3624 * @param int $trigger IDatabase::TRIGGER_* constant
3628 public function runTransactionListenerCallbacks( $trigger ) {
3629 if ( $this->trxEndCallbacksSuppressed
) {
3633 /** @var Exception $e */
3634 $e = null; // first exception
3636 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3638 $phpCallback( $trigger, $this );
3639 } catch ( Exception
$ex ) {
3640 ( $this->errorLogger
)( $ex );
3645 if ( $e instanceof Exception
) {
3646 throw $e; // re-throw any first exception
3651 * Create a savepoint
3653 * This is used internally to implement atomic sections. It should not be
3657 * @param string $identifier Identifier for the savepoint
3658 * @param string $fname Calling function name
3660 protected function doSavepoint( $identifier, $fname ) {
3661 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3665 * Release a savepoint
3667 * This is used internally to implement atomic sections. It should not be
3671 * @param string $identifier Identifier for the savepoint
3672 * @param string $fname Calling function name
3674 protected function doReleaseSavepoint( $identifier, $fname ) {
3675 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3679 * Rollback to a savepoint
3681 * This is used internally to implement atomic sections. It should not be
3685 * @param string $identifier Identifier for the savepoint
3686 * @param string $fname Calling function name
3688 protected function doRollbackToSavepoint( $identifier, $fname ) {
3689 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3693 * @param string $fname
3696 private function nextSavepointId( $fname ) {
3697 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3698 if ( strlen( $savepointId ) > 30 ) {
3699 // 30 == Oracle's identifier length limit (pre 12c)
3700 // With a 22 character prefix, that puts the highest number at 99999999.
3701 throw new DBUnexpectedError(
3703 'There have been an excessively large number of atomic sections in a transaction'
3704 . " started by $this->trxFname (at $fname)"
3708 return $savepointId;
3711 final public function startAtomic(
3712 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3714 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3716 if ( !$this->trxLevel
) {
3717 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3718 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3719 // in all changes being in one transaction to keep requests transactional.
3720 if ( $this->getFlag( self
::DBO_TRX
) ) {
3721 // Since writes could happen in between the topmost atomic sections as part
3722 // of the transaction, those sections will need savepoints.
3723 $savepointId = $this->nextSavepointId( $fname );
3724 $this->doSavepoint( $savepointId, $fname );
3726 $this->trxAutomaticAtomic
= true;
3728 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3729 $savepointId = $this->nextSavepointId( $fname );
3730 $this->doSavepoint( $savepointId, $fname );
3733 $sectionId = new AtomicSectionIdentifier
;
3734 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3735 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3736 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3741 final public function endAtomic( $fname = __METHOD__
) {
3742 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3743 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3746 // Check if the current section matches $fname
3747 $pos = count( $this->trxAtomicLevels
) - 1;
3748 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3749 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3751 if ( $savedFname !== $fname ) {
3752 throw new DBUnexpectedError(
3754 "Invalid atomic section ended (got $fname but expected $savedFname)."
3758 // Remove the last section (no need to re-index the array)
3759 array_pop( $this->trxAtomicLevels
);
3761 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3762 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3763 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3764 $this->doReleaseSavepoint( $savepointId, $fname );
3767 // Hoist callback ownership for callbacks in the section that just ended;
3768 // all callbacks should have an owner that is present in trxAtomicLevels.
3769 $currentSectionId = $this->currentAtomicSectionId();
3770 if ( $currentSectionId ) {
3771 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3775 final public function cancelAtomic(
3776 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3778 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3779 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3782 $excisedFnames = [];
3783 if ( $sectionId !== null ) {
3784 // Find the (last) section with the given $sectionId
3786 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3787 if ( $asId === $sectionId ) {
3792 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3794 // Remove all descendant sections and re-index the array
3796 $len = count( $this->trxAtomicLevels
);
3797 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3798 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3799 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3801 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3802 $this->modifyCallbacksForCancel( $excisedIds );
3805 // Check if the current section matches $fname
3806 $pos = count( $this->trxAtomicLevels
) - 1;
3807 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3809 if ( $excisedFnames ) {
3810 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3811 "and descendants " . implode( ', ', $excisedFnames ) );
3813 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3816 if ( $savedFname !== $fname ) {
3817 throw new DBUnexpectedError(
3819 "Invalid atomic section ended (got $fname but expected $savedFname)."
3823 // Remove the last section (no need to re-index the array)
3824 array_pop( $this->trxAtomicLevels
);
3825 $this->modifyCallbacksForCancel( [ $savedSectionId ] );
3827 if ( $savepointId !== null ) {
3828 // Rollback the transaction to the state just before this atomic section
3829 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3830 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3832 $this->doRollbackToSavepoint( $savepointId, $fname );
3833 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3834 $this->trxStatusIgnoredCause
= null;
3836 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3837 // Put the transaction into an error state if it's not already in one
3838 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3839 $this->trxStatusCause
= new DBUnexpectedError(
3841 "Uncancelable atomic section canceled (got $fname)."
3845 $this->affectedRowCount
= 0; // for the sake of consistency
3848 final public function doAtomicSection(
3849 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3851 $sectionId = $this->startAtomic( $fname, $cancelable );
3853 $res = $callback( $this, $fname );
3854 } catch ( Exception
$e ) {
3855 $this->cancelAtomic( $fname, $sectionId );
3859 $this->endAtomic( $fname );
3864 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3865 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3866 if ( !in_array( $mode, $modes, true ) ) {
3867 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'." );
3870 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3871 if ( $this->trxLevel
) {
3872 if ( $this->trxAtomicLevels
) {
3873 $levels = $this->flatAtomicSectionList();
3874 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3875 throw new DBUnexpectedError( $this, $msg );
3876 } elseif ( !$this->trxAutomatic
) {
3877 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3878 throw new DBUnexpectedError( $this, $msg );
3880 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3881 throw new DBUnexpectedError( $this, $msg );
3883 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3884 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3885 throw new DBUnexpectedError( $this, $msg );
3888 $this->assertHasConnectionHandle();
3890 $this->doBegin( $fname );
3891 $this->trxStatus
= self
::STATUS_TRX_OK
;
3892 $this->trxStatusIgnoredCause
= null;
3893 $this->trxAtomicCounter
= 0;
3894 $this->trxTimestamp
= microtime( true );
3895 $this->trxFname
= $fname;
3896 $this->trxDoneWrites
= false;
3897 $this->trxAutomaticAtomic
= false;
3898 $this->trxAtomicLevels
= [];
3899 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3900 $this->trxWriteDuration
= 0.0;
3901 $this->trxWriteQueryCount
= 0;
3902 $this->trxWriteAffectedRows
= 0;
3903 $this->trxWriteAdjDuration
= 0.0;
3904 $this->trxWriteAdjQueryCount
= 0;
3905 $this->trxWriteCallers
= [];
3906 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3907 // Get an estimate of the replication lag before any such queries.
3908 $this->trxReplicaLag
= null; // clear cached value first
3909 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3910 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3911 // caller will think its OK to muck around with the transaction just because startAtomic()
3912 // has not yet completed (e.g. setting trxAtomicLevels).
3913 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3917 * Issues the BEGIN command to the database server.
3919 * @see Database::begin()
3920 * @param string $fname
3922 protected function doBegin( $fname ) {
3923 $this->query( 'BEGIN', $fname );
3924 $this->trxLevel
= 1;
3927 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3928 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
3929 if ( !in_array( $flush, $modes, true ) ) {
3930 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'." );
3933 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3934 // There are still atomic sections open; this cannot be ignored
3935 $levels = $this->flatAtomicSectionList();
3936 throw new DBUnexpectedError(
3938 "$fname: Got COMMIT while atomic sections $levels are still open."
3942 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3943 if ( !$this->trxLevel
) {
3944 return; // nothing to do
3945 } elseif ( !$this->trxAutomatic
) {
3946 throw new DBUnexpectedError(
3948 "$fname: Flushing an explicit transaction, getting out of sync."
3952 if ( !$this->trxLevel
) {
3953 $this->queryLogger
->error(
3954 "$fname: No transaction to commit, something got out of sync." );
3955 return; // nothing to do
3956 } elseif ( $this->trxAutomatic
) {
3957 throw new DBUnexpectedError(
3959 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3964 $this->assertHasConnectionHandle();
3966 $this->runOnTransactionPreCommitCallbacks();
3968 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3969 $this->doCommit( $fname );
3970 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3972 if ( $this->trxDoneWrites
) {
3973 $this->lastWriteTime
= microtime( true );
3974 $this->trxProfiler
->transactionWritingOut(
3976 $this->getDomainID(),
3979 $this->trxWriteAffectedRows
3983 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
3984 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
3985 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3986 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3991 * Issues the COMMIT command to the database server.
3993 * @see Database::commit()
3994 * @param string $fname
3996 protected function doCommit( $fname ) {
3997 if ( $this->trxLevel
) {
3998 $this->query( 'COMMIT', $fname );
3999 $this->trxLevel
= 0;
4003 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
4004 $trxActive = $this->trxLevel
;
4006 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
4007 if ( $this->getFlag( self
::DBO_TRX
) ) {
4008 throw new DBUnexpectedError(
4010 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
4016 $this->assertHasConnectionHandle();
4018 $this->doRollback( $fname );
4019 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4020 $this->trxAtomicLevels
= [];
4021 // Estimate the RTT via a query now that trxStatus is OK
4022 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4024 if ( $this->trxDoneWrites
) {
4025 $this->trxProfiler
->transactionWritingOut(
4027 $this->getDomainID(),
4030 $this->trxWriteAffectedRows
4035 // Clear any commit-dependant callbacks. They might even be present
4036 // only due to transaction rounds, with no SQL transaction being active
4037 $this->trxIdleCallbacks
= [];
4038 $this->trxPreCommitCallbacks
= [];
4040 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4041 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4043 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4044 } catch ( Exception
$e ) {
4045 // already logged; finish and let LoadBalancer move on during mass-rollback
4048 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4049 } catch ( Exception
$e ) {
4050 // already logged; let LoadBalancer move on during mass-rollback
4053 $this->affectedRowCount
= 0; // for the sake of consistency
4058 * Issues the ROLLBACK command to the database server.
4060 * @see Database::rollback()
4061 * @param string $fname
4063 protected function doRollback( $fname ) {
4064 if ( $this->trxLevel
) {
4065 # Disconnects cause rollback anyway, so ignore those errors
4066 $ignoreErrors = true;
4067 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4068 $this->trxLevel
= 0;
4072 public function flushSnapshot( $fname = __METHOD__
) {
4073 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
4074 // This only flushes transactions to clear snapshots, not to write data
4075 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4076 throw new DBUnexpectedError(
4078 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
4082 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4085 public function explicitTrxActive() {
4086 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4089 public function duplicateTableStructure(
4090 $oldName, $newName, $temporary = false, $fname = __METHOD__
4092 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4095 public function listTables( $prefix = null, $fname = __METHOD__
) {
4096 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4099 public function listViews( $prefix = null, $fname = __METHOD__
) {
4100 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4103 public function timestamp( $ts = 0 ) {
4104 $t = new ConvertibleTimestamp( $ts );
4105 // Let errors bubble up to avoid putting garbage in the DB
4106 return $t->getTimestamp( TS_MW
);
4109 public function timestampOrNull( $ts = null ) {
4110 if ( is_null( $ts ) ) {
4113 return $this->timestamp( $ts );
4117 public function affectedRows() {
4118 return ( $this->affectedRowCount
=== null )
4119 ?
$this->fetchAffectedRowCount() // default to driver value
4120 : $this->affectedRowCount
;
4124 * @return int Number of retrieved rows according to the driver
4126 abstract protected function fetchAffectedRowCount();
4129 * Take the result from a query, and wrap it in a ResultWrapper if
4130 * necessary. Boolean values are passed through as is, to indicate success
4131 * of write queries or failure.
4133 * Once upon a time, Database::query() returned a bare MySQL result
4134 * resource, and it was necessary to call this function to convert it to
4135 * a wrapper. Nowadays, raw database objects are never exposed to external
4136 * callers, so this is unnecessary in external code.
4138 * @param bool|ResultWrapper|resource $result
4139 * @return bool|ResultWrapper
4141 protected function resultObject( $result ) {
4144 } elseif ( $result instanceof ResultWrapper
) {
4146 } elseif ( $result === true ) {
4147 // Successful write query
4150 return new ResultWrapper( $this, $result );
4154 public function ping( &$rtt = null ) {
4155 // Avoid hitting the server if it was hit recently
4156 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
4157 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
4158 $rtt = $this->rttEstimate
;
4159 return true; // don't care about $rtt
4163 // This will reconnect if possible or return false if not
4164 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4165 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
4166 $this->restoreFlags( self
::RESTORE_PRIOR
);
4169 $rtt = $this->rttEstimate
;
4176 * Close any existing (dead) database connection and open a new connection
4178 * @param string $fname
4179 * @return bool True if new connection is opened successfully, false if error
4181 protected function replaceLostConnection( $fname ) {
4182 $this->closeConnection();
4183 $this->opened
= false;
4184 $this->conn
= false;
4192 $this->tablePrefix()
4194 $this->lastPing
= microtime( true );
4197 $this->connLogger
->warning(
4198 $fname . ': lost connection to {dbserver}; reconnected',
4200 'dbserver' => $this->getServer(),
4201 'trace' => ( new RuntimeException() )->getTraceAsString()
4204 } catch ( DBConnectionError
$e ) {
4207 $this->connLogger
->error(
4208 $fname . ': lost connection to {dbserver} permanently',
4209 [ 'dbserver' => $this->getServer() ]
4213 $this->handleSessionLoss();
4218 public function getSessionLagStatus() {
4219 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4223 * Get the replica DB lag when the current transaction started
4225 * This is useful when transactions might use snapshot isolation
4226 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4227 * is this lag plus transaction duration. If they don't, it is still
4228 * safe to be pessimistic. This returns null if there is no transaction.
4230 * This returns null if the lag status for this transaction was not yet recorded.
4232 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4235 final protected function getRecordedTransactionLagStatus() {
4236 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
4237 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4242 * Get a replica DB lag estimate for this server
4244 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4247 protected function getApproximateLagStatus() {
4249 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4250 'since' => microtime( true )
4255 * Merge the result of getSessionLagStatus() for several DBs
4256 * using the most pessimistic values to estimate the lag of
4257 * any data derived from them in combination
4259 * This is information is useful for caching modules
4261 * @see WANObjectCache::set()
4262 * @see WANObjectCache::getWithSetCallback()
4264 * @param IDatabase $db1
4265 * @param IDatabase|null $db2 [optional]
4266 * @return array Map of values:
4267 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4268 * - since: oldest UNIX timestamp of any of the DB lag estimates
4269 * - pending: whether any of the DBs have uncommitted changes
4273 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4274 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4275 foreach ( func_get_args() as $db ) {
4276 /** @var IDatabase $db */
4277 $status = $db->getSessionLagStatus();
4278 if ( $status['lag'] === false ) {
4279 $res['lag'] = false;
4280 } elseif ( $res['lag'] !== false ) {
4281 $res['lag'] = max( $res['lag'], $status['lag'] );
4283 $res['since'] = min( $res['since'], $status['since'] );
4284 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4290 public function getLag() {
4294 public function maxListLen() {
4298 public function encodeBlob( $b ) {
4302 public function decodeBlob( $b ) {
4303 if ( $b instanceof Blob
) {
4309 public function setSessionOptions( array $options ) {
4312 public function sourceFile(
4314 callable
$lineCallback = null,
4315 callable
$resultCallback = null,
4317 callable
$inputCallback = null
4319 Wikimedia\
suppressWarnings();
4320 $fp = fopen( $filename, 'r' );
4321 Wikimedia\restoreWarnings
();
4323 if ( $fp === false ) {
4324 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4328 $fname = __METHOD__
. "( $filename )";
4332 $error = $this->sourceStream(
4333 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4334 } catch ( Exception
$e ) {
4344 public function setSchemaVars( $vars ) {
4345 $this->schemaVars
= $vars;
4348 public function sourceStream(
4350 callable
$lineCallback = null,
4351 callable
$resultCallback = null,
4352 $fname = __METHOD__
,
4353 callable
$inputCallback = null
4355 $delimiterReset = new ScopedCallback(
4356 function ( $delimiter ) {
4357 $this->delimiter
= $delimiter;
4359 [ $this->delimiter
]
4363 while ( !feof( $fp ) ) {
4364 if ( $lineCallback ) {
4365 call_user_func( $lineCallback );
4368 $line = trim( fgets( $fp ) );
4370 if ( $line == '' ) {
4374 if ( $line[0] == '-' && $line[1] == '-' ) {
4382 $done = $this->streamStatementEnd( $cmd, $line );
4386 if ( $done ||
feof( $fp ) ) {
4387 $cmd = $this->replaceVars( $cmd );
4389 if ( $inputCallback ) {
4390 $callbackResult = $inputCallback( $cmd );
4392 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4393 $cmd = $callbackResult;
4398 $res = $this->query( $cmd, $fname );
4400 if ( $resultCallback ) {
4401 $resultCallback( $res, $this );
4404 if ( $res === false ) {
4405 $err = $this->lastError();
4407 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4414 ScopedCallback
::consume( $delimiterReset );
4419 * Called by sourceStream() to check if we've reached a statement end
4421 * @param string &$sql SQL assembled so far
4422 * @param string &$newLine New line about to be added to $sql
4423 * @return bool Whether $newLine contains end of the statement
4425 public function streamStatementEnd( &$sql, &$newLine ) {
4426 if ( $this->delimiter
) {
4428 $newLine = preg_replace(
4429 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4430 if ( $newLine != $prev ) {
4439 * Database independent variable replacement. Replaces a set of variables
4440 * in an SQL statement with their contents as given by $this->getSchemaVars().
4442 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4444 * - '{$var}' should be used for text and is passed through the database's
4446 * - `{$var}` should be used for identifiers (e.g. table and database names).
4447 * It is passed through the database's addIdentifierQuotes method which
4448 * can be overridden if the database uses something other than backticks.
4449 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4450 * database's tableName method.
4451 * - / *i* / passes the name that follows through the database's indexName method.
4452 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4453 * its use should be avoided. In 1.24 and older, string encoding was applied.
4455 * @param string $ins SQL statement to replace variables in
4456 * @return string The new SQL statement with variables replaced
4458 protected function replaceVars( $ins ) {
4459 $vars = $this->getSchemaVars();
4460 return preg_replace_callback(
4462 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4463 \'\{\$ (\w+) }\' | # 3. addQuotes
4464 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4465 /\*\$ (\w+) \*/ # 5. leave unencoded
4467 function ( $m ) use ( $vars ) {
4468 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4469 // check for both nonexistent keys *and* the empty string.
4470 if ( isset( $m[1] ) && $m[1] !== '' ) {
4471 if ( $m[1] === 'i' ) {
4472 return $this->indexName( $m[2] );
4474 return $this->tableName( $m[2] );
4476 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4477 return $this->addQuotes( $vars[$m[3]] );
4478 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4479 return $this->addIdentifierQuotes( $vars[$m[4]] );
4480 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4481 return $vars[$m[5]];
4491 * Get schema variables. If none have been set via setSchemaVars(), then
4492 * use some defaults from the current object.
4496 protected function getSchemaVars() {
4497 if ( $this->schemaVars
) {
4498 return $this->schemaVars
;
4500 return $this->getDefaultSchemaVars();
4505 * Get schema variables to use if none have been set via setSchemaVars().
4507 * Override this in derived classes to provide variables for tables.sql
4508 * and SQL patch files.
4512 protected function getDefaultSchemaVars() {
4516 public function lockIsFree( $lockName, $method ) {
4517 // RDBMs methods for checking named locks may or may not count this thread itself.
4518 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4519 // the behavior choosen by the interface for this method.
4520 return !isset( $this->namedLocksHeld
[$lockName] );
4523 public function lock( $lockName, $method, $timeout = 5 ) {
4524 $this->namedLocksHeld
[$lockName] = 1;
4529 public function unlock( $lockName, $method ) {
4530 unset( $this->namedLocksHeld
[$lockName] );
4535 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4536 if ( $this->writesOrCallbacksPending() ) {
4537 // This only flushes transactions to clear snapshots, not to write data
4538 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4539 throw new DBUnexpectedError(
4541 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4545 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4549 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4550 if ( $this->trxLevel() ) {
4551 // There is a good chance an exception was thrown, causing any early return
4552 // from the caller. Let any error handler get a chance to issue rollback().
4553 // If there isn't one, let the error bubble up and trigger server-side rollback.
4554 $this->onTransactionResolution(
4555 function () use ( $lockKey, $fname ) {
4556 $this->unlock( $lockKey, $fname );
4561 $this->unlock( $lockKey, $fname );
4565 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4570 public function namedLocksEnqueue() {
4574 public function tableLocksHaveTransactionScope() {
4578 final public function lockTables( array $read, array $write, $method ) {
4579 if ( $this->writesOrCallbacksPending() ) {
4580 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4583 if ( $this->tableLocksHaveTransactionScope() ) {
4584 $this->startAtomic( $method );
4587 return $this->doLockTables( $read, $write, $method );
4591 * Helper function for lockTables() that handles the actual table locking
4593 * @param array $read Array of tables to lock for read access
4594 * @param array $write Array of tables to lock for write access
4595 * @param string $method Name of caller
4598 protected function doLockTables( array $read, array $write, $method ) {
4602 final public function unlockTables( $method ) {
4603 if ( $this->tableLocksHaveTransactionScope() ) {
4604 $this->endAtomic( $method );
4606 return true; // locks released on COMMIT/ROLLBACK
4609 return $this->doUnlockTables( $method );
4613 * Helper function for unlockTables() that handles the actual table unlocking
4615 * @param string $method Name of caller
4618 protected function doUnlockTables( $method ) {
4624 * @param string $tableName
4625 * @param string $fName
4626 * @return bool|ResultWrapper
4629 public function dropTable( $tableName, $fName = __METHOD__
) {
4630 if ( !$this->tableExists( $tableName, $fName ) ) {
4633 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4635 return $this->query( $sql, $fName );
4638 public function getInfinity() {
4642 public function encodeExpiry( $expiry ) {
4643 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4644 ?
$this->getInfinity()
4645 : $this->timestamp( $expiry );
4648 public function decodeExpiry( $expiry, $format = TS_MW
) {
4649 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4653 return ConvertibleTimestamp
::convert( $format, $expiry );
4656 public function setBigSelects( $value = true ) {
4660 public function isReadOnly() {
4661 return ( $this->getReadOnlyReason() !== false );
4665 * @return string|bool Reason this DB is read-only or false if it is not
4667 protected function getReadOnlyReason() {
4668 $reason = $this->getLBInfo( 'readOnlyReason' );
4670 return is_string( $reason ) ?
$reason : false;
4673 public function setTableAliases( array $aliases ) {
4674 $this->tableAliases
= $aliases;
4677 public function setIndexAliases( array $aliases ) {
4678 $this->indexAliases
= $aliases;
4682 * Get the underlying binding connection handle
4684 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4685 * This catches broken callers than catch and ignore disconnection exceptions.
4686 * Unlike checking isOpen(), this is safe to call inside of open().
4689 * @throws DBUnexpectedError
4692 protected function getBindingHandle() {
4693 if ( !$this->conn
) {
4694 throw new DBUnexpectedError(
4696 'DB connection was already closed or the connection dropped.'
4707 public function __toString() {
4708 return (string)$this->conn
;
4712 * Make sure that copies do not share the same client binding handle
4713 * @throws DBConnectionError
4715 public function __clone() {
4716 $this->connLogger
->warning(
4717 "Cloning " . static::class . " is not recommended; forking connection:\n" .
4718 ( new RuntimeException() )->getTraceAsString()
4721 if ( $this->isOpen() ) {
4722 // Open a new connection resource without messing with the old one
4723 $this->opened
= false;
4724 $this->conn
= false;
4725 $this->trxEndCallbacks
= []; // don't copy
4726 $this->handleSessionLoss(); // no trx or locks anymore
4733 $this->tablePrefix()
4735 $this->lastPing
= microtime( true );
4740 * Called by serialize. Throw an exception when DB connection is serialized.
4741 * This causes problems on some database engines because the connection is
4742 * not restored on unserialize.
4744 public function __sleep() {
4745 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4746 'the connection is not restored on wakeup.' );
4750 * Run a few simple sanity checks and close dangling connections
4752 public function __destruct() {
4753 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4754 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4757 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4758 if ( $danglingWriters ) {
4759 $fnames = implode( ', ', $danglingWriters );
4760 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4763 if ( $this->conn
) {
4764 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4765 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4766 Wikimedia\
suppressWarnings();
4767 $this->closeConnection();
4768 Wikimedia\restoreWarnings
();
4769 $this->conn
= false;
4770 $this->opened
= false;
4776 * @deprecated since 1.28
4778 class_alias( Database
::class, 'DatabaseBase' );
4781 * @deprecated since 1.29
4783 class_alias( Database
::class, 'Database' );