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
;
33 use Wikimedia\AtEase\AtEase
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
44 * Relational database abstraction object
49 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
50 /** @var string Server that this instance is currently connected to */
52 /** @var string User that this instance is currently connected under the name of */
54 /** @var string Password used to establish the current connection */
56 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
57 protected $tableAliases = [];
58 /** @var string[] Map of (index alias => index) */
59 protected $indexAliases = [];
60 /** @var bool Whether this PHP instance is for a CLI script */
62 /** @var string Agent name for query profiling */
64 /** @var int Bit field of class DBO_* constants */
66 /** @var array LoadBalancer tracking information */
67 protected $lbInfo = [];
68 /** @var array|bool Variables use for schema element placeholders */
69 protected $schemaVars = false;
70 /** @var array Parameters used by initConnection() to establish a connection */
71 protected $connectionParams = [];
72 /** @var array SQL variables values to use for all new connections */
73 protected $connectionVariables = [];
74 /** @var string Current SQL query delimiter */
75 protected $delimiter = ';';
76 /** @var string|bool|null Stashed value of html_errors INI setting */
77 protected $htmlErrors;
78 /** @var int Row batch size to use for emulated INSERT SELECT queries */
79 protected $nonNativeInsertSelectBatchSize = 10000;
81 /** @var BagOStuff APC cache */
83 /** @var LoggerInterface */
84 protected $connLogger;
85 /** @var LoggerInterface */
86 protected $queryLogger;
87 /** @var callable Error logging callback */
88 protected $errorLogger;
89 /** @var callable Deprecation logging callback */
90 protected $deprecationLogger;
91 /** @var callable|null */
93 /** @var TransactionProfiler */
94 protected $trxProfiler;
95 /** @var DatabaseDomain */
96 protected $currentDomain;
97 /** @var object|resource|null Database connection */
100 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
101 private $lazyMasterHandle;
103 /** @var array Map of (name => 1) for locks obtained via lock() */
104 protected $sessionNamedLocks = [];
105 /** @var array Map of (table name => 1) for TEMPORARY tables */
106 protected $sessionTempTables = [];
108 /** @var string ID of the active transaction or the empty string otherwise */
109 protected $trxShortId = '';
110 /** @var int Transaction status */
111 protected $trxStatus = self
::STATUS_TRX_NONE
;
112 /** @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR */
113 protected $trxStatusCause;
114 /** @var array|null Error details of the last statement-only rollback */
115 private $trxStatusIgnoredCause;
116 /** @var float|null UNIX timestamp at the time of BEGIN for the last transaction */
117 private $trxTimestamp = null;
118 /** @var float Replication lag estimate at the time of BEGIN for the last transaction */
119 private $trxReplicaLag = null;
120 /** @var string Name of the function that start the last transaction */
121 private $trxFname = null;
122 /** @var bool Whether possible write queries were done in the last transaction started */
123 private $trxDoneWrites = false;
124 /** @var bool Whether the current transaction was started implicitly due to DBO_TRX */
125 private $trxAutomatic = false;
126 /** @var int Counter for atomic savepoint identifiers (reset with each transaction) */
127 private $trxAtomicCounter = 0;
128 /** @var array List of (name, unique ID, savepoint ID) for each active atomic section level */
129 private $trxAtomicLevels = [];
130 /** @var bool Whether the current transaction was started implicitly by startAtomic() */
131 private $trxAutomaticAtomic = false;
132 /** @var string[] Write query callers of the current transaction */
133 private $trxWriteCallers = [];
134 /** @var float Seconds spent in write queries for the current transaction */
135 private $trxWriteDuration = 0.0;
136 /** @var int Number of write queries for the current transaction */
137 private $trxWriteQueryCount = 0;
138 /** @var int Number of rows affected by write queries for the current transaction */
139 private $trxWriteAffectedRows = 0;
140 /** @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries */
141 private $trxWriteAdjDuration = 0.0;
142 /** @var int Number of write queries counted in trxWriteAdjDuration */
143 private $trxWriteAdjQueryCount = 0;
144 /** @var array[] List of (callable, method name, atomic section id) */
145 private $trxIdleCallbacks = [];
146 /** @var array[] List of (callable, method name, atomic section id) */
147 private $trxPreCommitCallbacks = [];
148 /** @var array[] List of (callable, method name, atomic section id) */
149 private $trxEndCallbacks = [];
150 /** @var array[] List of (callable, method name, atomic section id) */
151 private $trxSectionCancelCallbacks = [];
152 /** @var callable[] Map of (name => callable) */
153 private $trxRecurringCallbacks = [];
154 /** @var bool Whether to suppress triggering of transaction end callbacks */
155 private $trxEndCallbacksSuppressed = false;
157 /** @var int[] Prior flags member variable values */
158 private $priorFlags = [];
160 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
161 protected $affectedRowCount;
163 /** @var float UNIX timestamp */
164 private $lastPing = 0.0;
165 /** @var string The last SQL query attempted */
166 private $lastQuery = '';
167 /** @var float|bool UNIX timestamp of last write query */
168 private $lastWriteTime = false;
169 /** @var string|bool */
170 private $lastPhpError = false;
171 /** @var float Query rount trip time estimate */
172 private $lastRoundTripEstimate = 0.0;
174 /** @var string Lock granularity is on the level of the entire database */
175 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
176 /** @var string The SCHEMA keyword refers to a grouping of tables in a database */
177 const ATTR_SCHEMAS_AS_TABLE_GROUPS
= 'supports-schemas';
179 /** @var int New Database instance will not be connected yet when returned */
180 const NEW_UNCONNECTED
= 0;
181 /** @var int New Database instance will already be connected when returned */
182 const NEW_CONNECTED
= 1;
184 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
185 const STATUS_TRX_ERROR
= 1;
186 /** @var int Transaction is active and in a normal state */
187 const STATUS_TRX_OK
= 2;
188 /** @var int No transaction is active */
189 const STATUS_TRX_NONE
= 3;
191 /** @var string Idiom used when a cancelable atomic section started the transaction */
192 private static $NOT_APPLICABLE = 'n/a';
193 /** @var string Prefix to the atomic section counter used to make savepoint IDs */
194 private static $SAVEPOINT_PREFIX = 'wikimedia_rdbms_atomic';
196 /** @var int Writes to this temporary table do not affect lastDoneWrites() */
197 private static $TEMP_NORMAL = 1;
198 /** @var int Writes to this temporary table effect lastDoneWrites() */
199 private static $TEMP_PSEUDO_PERMANENT = 2;
201 /** @var int Number of times to re-try an operation in case of deadlock */
202 private static $DEADLOCK_TRIES = 4;
203 /** @var int Minimum time to wait before retry, in microseconds */
204 private static $DEADLOCK_DELAY_MIN = 500000;
205 /** @var int Maximum time to wait before retry */
206 private static $DEADLOCK_DELAY_MAX = 1500000;
208 /** @var int How long before it is worth doing a dummy query to test the connection */
209 private static $PING_TTL = 1.0;
210 /** @var string Dummy SQL query */
211 private static $PING_QUERY = 'SELECT 1 AS ping';
213 /** @var float Guess of how many seconds it takes to replicate a small insert */
214 private static $TINY_WRITE_SEC = 0.010;
215 /** @var float Consider a write slow if it took more than this many seconds */
216 private static $SLOW_WRITE_SEC = 0.500;
217 /** @var float Assume an insert of this many rows or less should be fast to replicate */
218 private static $SMALL_WRITE_ROWS = 100;
220 /** @var string[] List of DBO_* flags that can be changed after connection */
221 protected static $MUTABLE_FLAGS = [
227 /** @var int Bit field of all DBO_* flags that can be changed after connection */
228 protected static $DBO_MUTABLE = (
229 self
::DBO_DEBUG | self
::DBO_NOBUFFER | self
::DBO_TRX | self
::DBO_DDLMODE
233 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
234 * @param array $params Parameters passed from Database::factory()
236 protected function __construct( array $params ) {
237 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
238 $this->connectionParams
[$name] = $params[$name];
241 $this->cliMode
= $params['cliMode'];
242 // Agent name is added to SQL queries in a comment, so make sure it can't break out
243 $this->agent
= str_replace( '/', '-', $params['agent'] );
245 $this->flags
= $params['flags'];
246 if ( $this->flags
& self
::DBO_DEFAULT
) {
247 if ( $this->cliMode
) {
248 $this->flags
&= ~self
::DBO_TRX
;
250 $this->flags |
= self
::DBO_TRX
;
253 // Disregard deprecated DBO_IGNORE flag (T189999)
254 $this->flags
&= ~self
::DBO_IGNORE
;
256 $this->connectionVariables
= $params['variables'];
258 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
260 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
261 $this->trxProfiler
= $params['trxProfiler'];
262 $this->connLogger
= $params['connLogger'];
263 $this->queryLogger
= $params['queryLogger'];
264 $this->errorLogger
= $params['errorLogger'];
265 $this->deprecationLogger
= $params['deprecationLogger'];
267 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
268 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
271 // Set initial dummy domain until open() sets the final DB/prefix
272 $this->currentDomain
= new DatabaseDomain(
273 $params['dbname'] != '' ?
$params['dbname'] : null,
274 $params['schema'] != '' ?
$params['schema'] : null,
275 $params['tablePrefix']
280 * Initialize the connection to the database over the wire (or to local files)
282 * @throws LogicException
283 * @throws InvalidArgumentException
284 * @throws DBConnectionError
287 final public function initConnection() {
288 if ( $this->isOpen() ) {
289 throw new LogicException( __METHOD__
. ': already connected' );
291 // Establish the connection
292 $this->doInitConnection();
296 * Actually connect to the database over the wire (or to local files)
298 * @throws DBConnectionError
301 protected function doInitConnection() {
303 $this->connectionParams
['host'],
304 $this->connectionParams
['user'],
305 $this->connectionParams
['password'],
306 $this->connectionParams
['dbname'],
307 $this->connectionParams
['schema'],
308 $this->connectionParams
['tablePrefix']
313 * Open a new connection to the database (closing any existing one)
315 * @param string|null $server Database server host
316 * @param string|null $user Database user name
317 * @param string|null $password Database user password
318 * @param string|null $dbName Database name
319 * @param string|null $schema Database schema name
320 * @param string $tablePrefix Table prefix
321 * @throws DBConnectionError
323 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
326 * Construct a Database subclass instance given a database type and parameters
328 * This also connects to the database immediately upon object construction
330 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
331 * @param array $params Parameter map with keys:
332 * - host : The hostname of the DB server
333 * - user : The name of the database user the client operates under
334 * - password : The password for the database user
335 * - dbname : The name of the database to use where queries do not specify one.
336 * The database must exist or an error might be thrown. Setting this to the empty string
337 * will avoid any such errors and make the handle have no implicit database scope. This is
338 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
339 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
340 * in which user names and such are defined, e.g. users are database-specific in Postgres.
341 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
342 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
343 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
344 * recognized in queries. This can be used in place of schemas for handle site farms.
345 * - flags : Optional bit field of DBO_* constants that define connection, protocol,
346 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
347 * flag in place UNLESS this this database simply acts as a key/value store.
348 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
349 * 'mysqli' driver; the old one 'mysql' has been removed.
350 * - variables: Optional map of session variables to set after connecting. This can be
351 * used to adjust lock timeouts or encoding modes and the like.
352 * - connLogger: Optional PSR-3 logger interface instance.
353 * - queryLogger: Optional PSR-3 logger interface instance.
354 * - profiler : Optional callback that takes a section name argument and returns
355 * a ScopedCallback instance that ends the profile section in its destructor.
356 * These will be called in query(), using a simplified version of the SQL that
357 * also includes the agent as a SQL comment.
358 * - trxProfiler: Optional TransactionProfiler instance.
359 * - errorLogger: Optional callback that takes an Exception and logs it.
360 * - deprecationLogger: Optional callback that takes a string and logs it.
361 * - cliMode: Whether to consider the execution context that of a CLI script.
362 * - agent: Optional name used to identify the end-user in query profiling/logging.
363 * - srvCache: Optional BagOStuff instance to an APC-style cache.
364 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
365 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
366 * @return Database|null If the database driver or extension cannot be found
367 * @throws InvalidArgumentException If the database driver or extension cannot be found
370 final public static function factory( $type, $params = [], $connect = self
::NEW_CONNECTED
) {
371 $class = self
::getClass( $type, $params['driver'] ??
null );
373 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
383 'cliMode' => ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ),
384 'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname()
387 $normalizedParams = [
389 'host' => strlen( $params['host'] ) ?
$params['host'] : null,
390 'user' => strlen( $params['user'] ) ?
$params['user'] : null,
391 'password' => is_string( $params['password'] ) ?
$params['password'] : null,
392 'dbname' => strlen( $params['dbname'] ) ?
$params['dbname'] : null,
393 'schema' => strlen( $params['schema'] ) ?
$params['schema'] : null,
394 'tablePrefix' => (string)$params['tablePrefix'],
395 'flags' => (int)$params['flags'],
396 'variables' => $params['variables'],
397 'cliMode' => (bool)$params['cliMode'],
398 'agent' => (string)$params['agent'],
399 // Objects and callbacks
400 'profiler' => $params['profiler'] ??
null,
401 'trxProfiler' => $params['trxProfiler'] ??
new TransactionProfiler(),
402 'connLogger' => $params['connLogger'] ??
new NullLogger(),
403 'queryLogger' => $params['queryLogger'] ??
new NullLogger(),
404 'errorLogger' => $params['errorLogger'] ??
function ( Exception
$e ) {
405 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
407 'deprecationLogger' => $params['deprecationLogger'] ??
function ( $msg ) {
408 trigger_error( $msg, E_USER_DEPRECATED
);
412 /** @var Database $conn */
413 $conn = new $class( $normalizedParams );
414 if ( $connect === self
::NEW_CONNECTED
) {
415 $conn->initConnection();
425 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
426 * @param string|null $driver Optional name of a specific DB client driver
427 * @return array Map of (Database::ATTR_* constant => value) for all such constants
428 * @throws InvalidArgumentException
431 final public static function attributesFromType( $dbType, $driver = null ) {
433 self
::ATTR_DB_LEVEL_LOCKING
=> false,
434 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
437 $class = self
::getClass( $dbType, $driver );
439 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
443 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
444 * @param string|null $driver Optional name of a specific DB client driver
445 * @return string Database subclass name to use
446 * @throws InvalidArgumentException
448 private static function getClass( $dbType, $driver = null ) {
449 // For database types with built-in support, the below maps type to IDatabase
450 // implementations. For types with multipe driver implementations (PHP extensions),
451 // an array can be used, keyed by extension name. In case of an array, the
452 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
453 // we auto-detect the first available driver. For types without built-in support,
454 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
455 static $builtinTypes = [
456 'mssql' => DatabaseMssql
::class,
457 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
458 'sqlite' => DatabaseSqlite
::class,
459 'postgres' => DatabasePostgres
::class,
462 $dbType = strtolower( $dbType );
465 if ( isset( $builtinTypes[$dbType] ) ) {
466 $possibleDrivers = $builtinTypes[$dbType];
467 if ( is_string( $possibleDrivers ) ) {
468 $class = $possibleDrivers;
469 } elseif ( (string)$driver !== '' ) {
470 if ( !isset( $possibleDrivers[$driver] ) ) {
471 throw new InvalidArgumentException( __METHOD__
.
472 " type '$dbType' does not support driver '{$driver}'" );
475 $class = $possibleDrivers[$driver];
477 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
478 if ( extension_loaded( $posDriver ) ) {
479 $class = $possibleClass;
485 $class = 'Database' . ucfirst( $dbType );
488 if ( $class === false ) {
489 throw new InvalidArgumentException( __METHOD__
.
490 " no viable database extension found for type '$dbType'" );
497 * @return array Map of (Database::ATTR_* constant => value
500 protected static function getAttributes() {
505 * Set the PSR-3 logger interface to use for query logging. (The logger
506 * interfaces for connection logging and error logging can be set with the
509 * @param LoggerInterface $logger
511 public function setLogger( LoggerInterface
$logger ) {
512 $this->queryLogger
= $logger;
515 public function getServerInfo() {
516 return $this->getServerVersion();
519 public function bufferResults( $buffer = null ) {
520 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
521 if ( $buffer !== null ) {
523 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
524 : $this->setFlag( self
::DBO_NOBUFFER
);
530 final public function trxLevel() {
531 return ( $this->trxShortId
!= '' ) ?
1 : 0;
534 public function trxTimestamp() {
535 return $this->trxLevel() ?
$this->trxTimestamp
: null;
539 * @return int One of the STATUS_TRX_* class constants
542 public function trxStatus() {
543 return $this->trxStatus
;
546 public function tablePrefix( $prefix = null ) {
547 $old = $this->currentDomain
->getTablePrefix();
548 if ( $prefix !== null ) {
549 $this->currentDomain
= new DatabaseDomain(
550 $this->currentDomain
->getDatabase(),
551 $this->currentDomain
->getSchema(),
559 public function dbSchema( $schema = null ) {
560 if ( strlen( $schema ) && $this->getDBname() === null ) {
561 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
564 $old = $this->currentDomain
->getSchema();
565 if ( $schema !== null ) {
566 $this->currentDomain
= new DatabaseDomain(
567 $this->currentDomain
->getDatabase(),
568 // DatabaseDomain uses null for unspecified schemas
569 strlen( $schema ) ?
$schema : null,
570 $this->currentDomain
->getTablePrefix()
578 * @return string Schema to use to qualify relations in queries
580 protected function relationSchemaQualifier() {
581 return $this->dbSchema();
584 public function getLBInfo( $name = null ) {
585 if ( is_null( $name ) ) {
586 return $this->lbInfo
;
589 if ( array_key_exists( $name, $this->lbInfo
) ) {
590 return $this->lbInfo
[$name];
596 public function setLBInfo( $nameOrArray, $value = null ) {
597 if ( is_array( $nameOrArray ) ) {
598 $this->lbInfo
= $nameOrArray;
599 } elseif ( is_string( $nameOrArray ) ) {
600 if ( $value !== null ) {
601 $this->lbInfo
[$nameOrArray] = $value;
603 unset( $this->lbInfo
[$nameOrArray] );
606 throw new InvalidArgumentException( "Got non-string key" );
610 public function setLazyMasterHandle( IDatabase
$conn ) {
611 $this->lazyMasterHandle
= $conn;
615 * @return IDatabase|null
616 * @see setLazyMasterHandle()
619 protected function getLazyMasterHandle() {
620 return $this->lazyMasterHandle
;
623 public function implicitGroupby() {
627 public function implicitOrderby() {
631 public function lastQuery() {
632 return $this->lastQuery
;
635 public function doneWrites() {
636 return (bool)$this->lastWriteTime
;
639 public function lastDoneWrites() {
640 return $this->lastWriteTime ?
: false;
643 public function writesPending() {
644 return $this->trxLevel() && $this->trxDoneWrites
;
647 public function writesOrCallbacksPending() {
648 return $this->trxLevel() && (
649 $this->trxDoneWrites ||
650 $this->trxIdleCallbacks ||
651 $this->trxPreCommitCallbacks ||
652 $this->trxEndCallbacks ||
653 $this->trxSectionCancelCallbacks
657 public function preCommitCallbacksPending() {
658 return $this->trxLevel() && $this->trxPreCommitCallbacks
;
662 * @return string|null
664 final protected function getTransactionRoundId() {
665 // If transaction round participation is enabled, see if one is active
666 if ( $this->getFlag( self
::DBO_TRX
) ) {
667 $id = $this->getLBInfo( 'trxRoundId' );
669 return is_string( $id ) ?
$id : null;
675 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
676 if ( !$this->trxLevel() ) {
678 } elseif ( !$this->trxDoneWrites
) {
683 case self
::ESTIMATE_DB_APPLY
:
684 return $this->pingAndCalculateLastTrxApplyTime();
685 default: // everything
686 return $this->trxWriteDuration
;
691 * @return float Time to apply writes to replicas based on trxWrite* fields
693 private function pingAndCalculateLastTrxApplyTime() {
696 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
697 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
698 // For omitted queries, make them count as something at least
699 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
700 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
705 public function pendingWriteCallers() {
706 return $this->trxLevel() ?
$this->trxWriteCallers
: [];
709 public function pendingWriteRowsAffected() {
710 return $this->trxWriteAffectedRows
;
714 * List the methods that have write queries or callbacks for the current transaction
716 * This method should not be used outside of Database/LoadBalancer
721 public function pendingWriteAndCallbackCallers() {
722 $fnames = $this->pendingWriteCallers();
724 $this->trxIdleCallbacks
,
725 $this->trxPreCommitCallbacks
,
726 $this->trxEndCallbacks
,
727 $this->trxSectionCancelCallbacks
729 foreach ( $callbacks as $callback ) {
730 $fnames[] = $callback[1];
740 private function flatAtomicSectionList() {
741 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
742 return $accum === null ?
$v[0] : "$accum, " . $v[0];
746 public function isOpen() {
747 return (bool)$this->conn
;
750 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
751 if ( $flag & ~
static::$DBO_MUTABLE ) {
752 throw new DBUnexpectedError(
754 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
758 if ( $remember === self
::REMEMBER_PRIOR
) {
759 array_push( $this->priorFlags
, $this->flags
);
762 $this->flags |
= $flag;
765 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
766 if ( $flag & ~
static::$DBO_MUTABLE ) {
767 throw new DBUnexpectedError(
769 "Got $flag (allowed: " . implode( ', ', static::$MUTABLE_FLAGS ) . ')'
773 if ( $remember === self
::REMEMBER_PRIOR
) {
774 array_push( $this->priorFlags
, $this->flags
);
777 $this->flags
&= ~
$flag;
780 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
781 if ( !$this->priorFlags
) {
785 if ( $state === self
::RESTORE_INITIAL
) {
786 $this->flags
= reset( $this->priorFlags
);
787 $this->priorFlags
= [];
789 $this->flags
= array_pop( $this->priorFlags
);
793 public function getFlag( $flag ) {
794 return ( ( $this->flags
& $flag ) === $flag );
798 * @param string $name Class field name
800 * @deprecated Since 1.28
802 public function getProperty( $name ) {
806 public function getDomainID() {
807 return $this->currentDomain
->getId();
810 final public function getWikiID() {
811 return $this->getDomainID();
815 * Get information about an index into an object
816 * @param string $table Table name
817 * @param string $index Index name
818 * @param string $fname Calling function name
819 * @return mixed Database-specific index description class or false if the index does not exist
821 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
824 * Wrapper for addslashes()
826 * @param string $s String to be slashed.
827 * @return string Slashed string.
829 abstract function strencode( $s );
832 * Set a custom error handler for logging errors during database connection
834 protected function installErrorHandler() {
835 $this->lastPhpError
= false;
836 $this->htmlErrors
= ini_set( 'html_errors', '0' );
837 set_error_handler( [ $this, 'connectionErrorLogger' ] );
841 * Restore the previous error handler and return the last PHP error for this DB
843 * @return bool|string
845 protected function restoreErrorHandler() {
846 restore_error_handler();
847 if ( $this->htmlErrors
!== false ) {
848 ini_set( 'html_errors', $this->htmlErrors
);
851 return $this->getLastPHPError();
855 * @return string|bool Last PHP error for this DB (typically connection errors)
857 protected function getLastPHPError() {
858 if ( $this->lastPhpError
) {
859 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
860 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
869 * Error handler for logging errors during database connection
870 * This method should not be used outside of Database classes
873 * @param string $errstr
875 public function connectionErrorLogger( $errno, $errstr ) {
876 $this->lastPhpError
= $errstr;
880 * Create a log context to pass to PSR-3 logger functions.
882 * @param array $extras Additional data to add to context
885 protected function getLogContext( array $extras = [] ) {
888 'db_server' => $this->server
,
889 'db_name' => $this->getDBname(),
890 'db_user' => $this->user
,
896 final public function close() {
897 $exception = null; // error to throw after disconnecting
899 $wasOpen = (bool)$this->conn
;
900 // This should mostly do nothing if the connection is already closed
902 // Roll back any dangling transaction first
903 if ( $this->trxLevel() ) {
904 if ( $this->trxAtomicLevels
) {
905 // Cannot let incomplete atomic sections be committed
906 $levels = $this->flatAtomicSectionList();
907 $exception = new DBUnexpectedError(
909 __METHOD__
. ": atomic sections $levels are still open"
911 } elseif ( $this->trxAutomatic
) {
912 // Only the connection manager can commit non-empty DBO_TRX transactions
913 // (empty ones we can silently roll back)
914 if ( $this->writesOrCallbacksPending() ) {
915 $exception = new DBUnexpectedError(
918 ": mass commit/rollback of peer transaction required (DBO_TRX set)"
922 // Manual transactions should have been committed or rolled
923 // back, even if empty.
924 $exception = new DBUnexpectedError(
926 __METHOD__
. ": transaction is still open (from {$this->trxFname})"
930 if ( $this->trxEndCallbacksSuppressed
) {
931 $exception = $exception ?
: new DBUnexpectedError(
933 __METHOD__
. ': callbacks are suppressed; cannot properly commit'
937 // Rollback the changes and run any callbacks as needed
938 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
941 // Close the actual connection in the binding handle
942 $closed = $this->closeConnection();
944 $closed = true; // already closed; nothing to do
949 // Throw any unexpected errors after having disconnected
950 if ( $exception instanceof Exception
) {
954 // Note that various subclasses call close() at the start of open(), which itself is
955 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
956 // callbacks are pending does not mean that an exception should be thrown. Rather, they
957 // will be executed after the reconnection step.
959 // Sanity check that no callbacks are dangling
960 $fnames = $this->pendingWriteAndCallbackCallers();
962 throw new RuntimeException(
963 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
972 * Make sure there is an open connection handle (alive or not) as a sanity check
974 * This guards against fatal errors to the binding handle not being defined
975 * in cases where open() was never called or close() was already called
977 * @throws DBUnexpectedError
979 final protected function assertHasConnectionHandle() {
980 if ( !$this->isOpen() ) {
981 throw new DBUnexpectedError( $this, "DB connection was already closed" );
986 * Make sure that this server is not marked as a replica nor read-only as a sanity check
988 * @throws DBReadOnlyRoleError
989 * @throws DBReadOnlyError
991 protected function assertIsWritableMaster() {
992 if ( $this->getLBInfo( 'replica' ) === true ) {
993 throw new DBReadOnlyRoleError(
995 'Write operations are not allowed on replica database connections'
998 $reason = $this->getReadOnlyReason();
999 if ( $reason !== false ) {
1000 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1005 * Closes underlying database connection
1007 * @return bool Whether connection was closed successfully
1009 abstract protected function closeConnection();
1012 * Run a query and return a DBMS-dependent wrapper or boolean
1014 * This is meant to handle the basic command of actually sending a query to the
1015 * server via the driver. No implicit transaction, reconnection, nor retry logic
1016 * should happen here. The higher level query() method is designed to handle those
1017 * sorts of concerns. This method should not trigger such higher level methods.
1019 * The lastError() and lastErrno() methods should meaningfully reflect what error,
1020 * if any, occured during the last call to this method. Methods like executeQuery(),
1021 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
1022 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
1023 * meaningfully reflects any error that occured during that public query method call.
1025 * For SELECT queries, this returns either:
1026 * - a) A driver-specific value/resource, only on success. This can be iterated
1027 * over by calling fetchObject()/fetchRow() until there are no more rows.
1028 * Alternatively, the result can be passed to resultObject() to obtain an
1029 * IResultWrapper instance which can then be iterated over via "foreach".
1030 * - b) False, on any query failure
1032 * For non-SELECT queries, this returns either:
1033 * - a) A driver-specific value/resource, only on success
1034 * - b) True, only on success (e.g. no meaningful result other than "OK")
1035 * - c) False, on any query failure
1037 * @param string $sql SQL query
1038 * @return mixed|bool An object, resource, or true on success; false on failure
1040 abstract protected function doQuery( $sql );
1043 * Determine whether a query writes to the DB. When in doubt, this returns true.
1047 * - Subsequent web requests should not need to wait for replication from
1048 * the master position seen by this web request, unless this request made
1049 * changes to the master. This is handled by ChronologyProtector by checking
1050 * doneWrites() at the end of the request. doneWrites() returns true if any
1051 * query set lastWriteTime; which query() does based on isWriteQuery().
1053 * - Reject write queries to replica DBs, in query().
1055 * @param string $sql
1058 protected function isWriteQuery( $sql ) {
1059 // BEGIN and COMMIT queries are considered read queries here.
1060 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1061 // treat these as write queries, in that their results have "affected rows"
1062 // as meta data as from writes, instead of "num rows" as from reads.
1063 // But, we treat them as read queries because when reading data (from
1064 // either replica or master) we use transactions to enable repeatable-read
1065 // snapshots, which ensures we get consistent results from the same snapshot
1066 // for all queries within a request. Use cases:
1067 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1068 // - We use this method to reject writes to replicas, but we need to allow
1069 // use of transactions on replicas for read snapshots. This is fine given
1070 // that transactions by themselves don't make changes, only actual writes
1071 // within the transaction matter, which we still detect.
1073 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1079 * @param string $sql
1080 * @return string|null
1082 protected function getQueryVerb( $sql ) {
1083 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1087 * Determine whether a SQL statement is sensitive to isolation level.
1089 * A SQL statement is considered transactable if its result could vary
1090 * depending on the transaction isolation level. Operational commands
1091 * such as 'SET' and 'SHOW' are not considered to be transactable.
1093 * Main purpose: Used by query() to decide whether to begin a transaction
1094 * before the current query (in DBO_TRX mode, on by default).
1096 * @param string $sql
1099 protected function isTransactableQuery( $sql ) {
1101 $this->getQueryVerb( $sql ),
1102 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1108 * @param string $sql A SQL query
1109 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1110 * @return array A n-tuple of:
1111 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1112 * - string|null: The name of the new temporary table $sql creates, or null
1113 * - string|null: The name of the temporary table that $sql drops, or null
1115 protected function getTempWrites( $sql, $pseudoPermanent ) {
1116 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1119 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1123 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1125 return [ $type, $matches[1], null ];
1126 } elseif ( preg_match(
1127 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1131 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, $matches[1] ];
1132 } elseif ( preg_match(
1133 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1137 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1138 } elseif ( preg_match(
1139 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1143 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1146 return [ null, null, null ];
1150 * @param IResultWrapper|bool $ret
1151 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1152 * @param string|null $tmpNew Name of created temp table
1153 * @param string|null $tmpDel Name of dropped temp table
1155 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1156 if ( $ret !== false ) {
1157 if ( $tmpNew !== null ) {
1158 $this->sessionTempTables
[$tmpNew] = $tmpType;
1160 if ( $tmpDel !== null ) {
1161 unset( $this->sessionTempTables
[$tmpDel] );
1166 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1167 $flags = (int)$flags; // b/c; this field used to be a bool
1168 // Sanity check that the SQL query is appropriate in the current context and is
1169 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1170 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1172 // Send the query to the server and fetch any corresponding errors
1173 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1174 if ( $ret === false ) {
1175 $ignoreErrors = $this->hasFlags( $flags, self
::QUERY_SILENCE_ERRORS
);
1176 // Throw an error unless both the ignore flag was set and a rollback is not needed
1177 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1180 return $this->resultObject( $ret );
1184 * Execute a query, retrying it if there is a recoverable connection loss
1186 * This is similar to query() except:
1187 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1188 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1189 * - It does not throw exceptions for common error cases
1191 * This is meant for internal use with Database subclasses.
1193 * @param string $sql Original SQL query
1194 * @param string $fname Name of the calling function
1195 * @param int $flags Bit field of class QUERY_* constants
1196 * @return array An n-tuple of:
1197 * - mixed|bool: An object, resource, or true on success; false on failure
1198 * - string: The result of calling lastError()
1199 * - int: The result of calling lastErrno()
1200 * - bool: Whether a rollback is needed to allow future non-rollback queries
1201 * @throws DBUnexpectedError
1203 final protected function executeQuery( $sql, $fname, $flags ) {
1204 $this->assertHasConnectionHandle();
1206 $priorTransaction = $this->trxLevel();
1208 if ( $this->isWriteQuery( $sql ) ) {
1209 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1210 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1211 $this->assertIsWritableMaster();
1212 // Do not treat temporary table writes as "meaningful writes" since they are only
1213 // visible to one session and are not permanent. Profile them as reads. Integration
1214 // tests can override this behavior via $flags.
1215 $pseudoPermanent = $this->hasFlags( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1216 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1217 $isPermWrite = ( $tmpType !== self
::$TEMP_NORMAL );
1218 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1219 if ( $isPermWrite && $this->hasFlags( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1220 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1223 // No permanent writes in this query
1224 $isPermWrite = false;
1225 // No temporary tables written to either
1226 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1229 // Add trace comment to the begin of the sql string, right after the operator.
1230 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1231 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1233 // Send the query to the server and fetch any corresponding errors.
1234 // This also doubles as a "ping" to see if the connection was dropped.
1235 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1236 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1238 // Check if the query failed due to a recoverable connection loss
1239 $allowRetry = !$this->hasFlags( $flags, self
::QUERY_NO_RETRY
);
1240 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1241 // Silently resend the query to the server since it is safe and possible
1242 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1243 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1246 // Register creation and dropping of temporary tables
1247 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1249 $corruptedTrx = false;
1251 if ( $ret === false ) {
1252 if ( $priorTransaction ) {
1253 if ( $recoverableSR ) {
1254 # We're ignoring an error that caused just the current query to be aborted.
1255 # But log the cause so we can log a deprecation notice if a caller actually
1257 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1258 } elseif ( !$recoverableCL ) {
1259 # Either the query was aborted or all queries after BEGIN where aborted.
1260 # In the first case, the only options going forward are (a) ROLLBACK, or
1261 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1262 # option is ROLLBACK, since the snapshots would have been released.
1263 $corruptedTrx = true; // cannot recover
1264 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1265 $this->trxStatusCause
=
1266 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1267 $this->trxStatusIgnoredCause
= null;
1272 return [ $ret, $err, $errno, $corruptedTrx ];
1276 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1277 * tracking, and reconnects (without retry) on query failure due to connection loss
1279 * @param string $sql Original SQL query
1280 * @param string $commentedSql SQL query with debugging/trace comment
1281 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1282 * @param string $fname Name of the calling function
1283 * @param int $flags Bit field of class QUERY_* constants
1284 * @return array An n-tuple of:
1285 * - mixed|bool: An object, resource, or true on success; false on failure
1286 * - string: The result of calling lastError()
1287 * - int: The result of calling lastErrno()
1288 * - bool: Whether a statement rollback error occured
1289 * - bool: Whether a disconnect *both* happened *and* was recoverable
1290 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1291 * @throws DBUnexpectedError
1293 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1294 $priorWritesPending = $this->writesOrCallbacksPending();
1296 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1297 $this->beginIfImplied( $sql, $fname );
1300 // Keep track of whether the transaction has write queries pending
1301 if ( $isPermWrite ) {
1302 $this->lastWriteTime
= microtime( true );
1303 if ( $this->trxLevel() && !$this->trxDoneWrites
) {
1304 $this->trxDoneWrites
= true;
1305 $this->trxProfiler
->transactionWritingIn(
1306 $this->server
, $this->getDomainID(), $this->trxShortId
);
1310 $prefix = !is_null( $this->getLBInfo( 'master' ) ) ?
'query-m: ' : 'query: ';
1311 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1313 $startTime = microtime( true );
1314 $ps = $this->profiler
1315 ?
( $this->profiler
)( $generalizedSql->stringify() )
1317 $this->affectedRowCount
= null;
1318 $this->lastQuery
= $sql;
1319 $ret = $this->doQuery( $commentedSql );
1320 $lastError = $this->lastError();
1321 $lastErrno = $this->lastErrno();
1323 $this->affectedRowCount
= $this->affectedRows();
1324 unset( $ps ); // profile out (if set)
1325 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1327 $recoverableSR = false; // recoverable statement rollback?
1328 $recoverableCL = false; // recoverable connection loss?
1329 $reconnected = false; // reconnection both attempted and succeeded?
1331 if ( $ret !== false ) {
1332 $this->lastPing
= $startTime;
1333 if ( $isPermWrite && $this->trxLevel() ) {
1334 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1335 $this->trxWriteCallers
[] = $fname;
1337 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1338 # Check if no meaningful session state was lost
1339 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1340 # Update session state tracking and try to restore the connection
1341 $reconnected = $this->replaceLostConnection( __METHOD__
);
1343 # Check if only the last query was rolled back
1344 $recoverableSR = $this->wasKnownStatementRollbackError();
1347 if ( $sql === self
::$PING_QUERY ) {
1348 $this->lastRoundTripEstimate
= $queryRuntime;
1351 $this->trxProfiler
->recordQueryCompletion(
1355 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1358 // Avoid the overhead of logging calls unless debug mode is enabled
1359 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1360 $this->queryLogger
->debug(
1361 "{method} [{runtime}s]: $sql",
1364 'db_host' => $this->getServer(),
1365 'domain' => $this->getDomainID(),
1366 'runtime' => round( $queryRuntime, 3 )
1371 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1375 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1377 * @param string $sql
1378 * @param string $fname
1380 private function beginIfImplied( $sql, $fname ) {
1382 !$this->trxLevel() &&
1383 $this->getFlag( self
::DBO_TRX
) &&
1384 $this->isTransactableQuery( $sql )
1386 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1387 $this->trxAutomatic
= true;
1392 * Update the estimated run-time of a query, not counting large row lock times
1394 * LoadBalancer can be set to rollback transactions that will create huge replication
1395 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1396 * queries, like inserting a row can take a long time due to row locking. This method
1397 * uses some simple heuristics to discount those cases.
1399 * @param string $sql A SQL write query
1400 * @param float $runtime Total runtime, including RTT
1401 * @param int $affected Affected row count
1403 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1404 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1405 $indicativeOfReplicaRuntime = true;
1406 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1407 $verb = $this->getQueryVerb( $sql );
1408 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1409 if ( $verb === 'INSERT' ) {
1410 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1411 } elseif ( $verb === 'REPLACE' ) {
1412 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1416 $this->trxWriteDuration +
= $runtime;
1417 $this->trxWriteQueryCount +
= 1;
1418 $this->trxWriteAffectedRows +
= $affected;
1419 if ( $indicativeOfReplicaRuntime ) {
1420 $this->trxWriteAdjDuration +
= $runtime;
1421 $this->trxWriteAdjQueryCount +
= 1;
1426 * Error out if the DB is not in a valid state for a query via query()
1428 * @param string $sql
1429 * @param string $fname
1430 * @throws DBTransactionStateError
1432 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1433 $verb = $this->getQueryVerb( $sql );
1434 if ( $verb === 'USE' ) {
1435 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1438 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1442 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1443 throw new DBTransactionStateError(
1445 "Cannot execute query from $fname while transaction status is ERROR",
1447 $this->trxStatusCause
1449 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1450 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1451 call_user_func( $this->deprecationLogger
,
1452 "Caller from $fname ignored an error originally raised from $iFname: " .
1453 "[$iLastErrno] $iLastError"
1455 $this->trxStatusIgnoredCause
= null;
1459 public function assertNoOpenTransactions() {
1460 if ( $this->explicitTrxActive() ) {
1461 throw new DBTransactionError(
1463 "Explicit transaction still active. A caller may have caught an error. "
1464 . "Open transactions: " . $this->flatAtomicSectionList()
1470 * Determine whether it is safe to retry queries after a database connection is lost
1472 * @param string $sql SQL query
1473 * @param bool $priorWritesPending Whether there is a transaction open with
1474 * possible write queries or transaction pre-commit/idle callbacks
1475 * waiting on it to finish.
1476 * @return bool True if it is safe to retry the query, false otherwise
1478 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1479 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1480 # Dropped connections also mean that named locks are automatically released.
1481 # Only allow error suppression in autocommit mode or when the lost transaction
1482 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1483 if ( $this->sessionNamedLocks
) {
1484 return false; // possible critical section violation
1485 } elseif ( $this->sessionTempTables
) {
1486 return false; // tables might be queried latter
1487 } elseif ( $sql === 'COMMIT' ) {
1488 return !$priorWritesPending; // nothing written anyway? (T127428)
1489 } elseif ( $sql === 'ROLLBACK' ) {
1490 return true; // transaction lost...which is also what was requested :)
1491 } elseif ( $this->explicitTrxActive() ) {
1492 return false; // don't drop atomocity and explicit snapshots
1493 } elseif ( $priorWritesPending ) {
1494 return false; // prior writes lost from implicit transaction
1501 * Clean things up after session (and thus transaction) loss before reconnect
1503 private function handleSessionLossPreconnect() {
1504 // Clean up tracking of session-level things...
1505 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1506 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1507 $this->sessionTempTables
= [];
1508 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1509 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1510 $this->sessionNamedLocks
= [];
1511 // Session loss implies transaction loss
1512 $oldTrxShortId = $this->consumeTrxShortId();
1513 $this->trxAtomicCounter
= 0;
1514 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1515 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1516 // @note: leave trxRecurringCallbacks in place
1517 if ( $this->trxDoneWrites
) {
1518 $this->trxProfiler
->transactionWritingOut(
1520 $this->getDomainID(),
1522 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1523 $this->trxWriteAffectedRows
1529 * Clean things up after session (and thus transaction) loss after reconnect
1531 private function handleSessionLossPostconnect() {
1533 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1534 // If callback suppression is set then the array will remain unhandled.
1535 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1536 } catch ( Exception
$ex ) {
1537 // Already logged; move on...
1540 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1541 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1542 } catch ( Exception
$ex ) {
1543 // Already logged; move on...
1548 * Reset the transaction ID and return the old one
1550 * @return string The old transaction ID or the empty string if there wasn't one
1552 private function consumeTrxShortId() {
1553 $old = $this->trxShortId
;
1554 $this->trxShortId
= '';
1560 * Checks whether the cause of the error is detected to be a timeout.
1562 * It returns false by default, and not all engines support detecting this yet.
1563 * If this returns false, it will be treated as a generic query error.
1565 * @param string $error Error text
1566 * @param int $errno Error number
1569 protected function wasQueryTimeout( $error, $errno ) {
1574 * Report a query error. Log the error, and if neither the object ignore
1575 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1577 * @param string $error
1579 * @param string $sql
1580 * @param string $fname
1581 * @param bool $ignore
1582 * @throws DBQueryError
1584 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1586 $this->queryLogger
->debug( "SQL ERROR (ignored): $error" );
1588 throw $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1593 * @param string $error
1594 * @param string|int $errno
1595 * @param string $sql
1596 * @param string $fname
1599 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1600 $this->queryLogger
->error(
1601 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1602 $this->getLogContext( [
1603 'method' => __METHOD__
,
1606 'sql1line' => mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 ),
1608 'trace' => ( new RuntimeException() )->getTraceAsString()
1612 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1613 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1614 } elseif ( $this->wasConnectionError( $errno ) ) {
1615 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1617 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1624 * @param string $error
1625 * @return DBConnectionError
1627 final protected function newExceptionAfterConnectError( $error ) {
1628 // Connection was not fully initialized and is not safe for use
1631 $this->connLogger
->error(
1632 "Error connecting to {db_server} as user {db_user}: {error}",
1633 $this->getLogContext( [
1635 'trace' => ( new RuntimeException() )->getTraceAsString()
1639 return new DBConnectionError( $this, $error );
1642 public function freeResult( $res ) {
1645 public function selectField(
1646 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1648 if ( $var === '*' ) { // sanity
1649 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1652 if ( !is_array( $options ) ) {
1653 $options = [ $options ];
1656 $options['LIMIT'] = 1;
1658 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1659 if ( $res === false ) {
1660 throw new DBUnexpectedError( $this, "Got false from select()" );
1663 $row = $this->fetchRow( $res );
1664 if ( $row === false ) {
1668 return reset( $row );
1671 public function selectFieldValues(
1672 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1674 if ( $var === '*' ) { // sanity
1675 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1676 } elseif ( !is_string( $var ) ) { // sanity
1677 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1680 if ( !is_array( $options ) ) {
1681 $options = [ $options ];
1684 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1685 if ( $res === false ) {
1686 throw new DBUnexpectedError( $this, "Got false from select()" );
1690 foreach ( $res as $row ) {
1691 $values[] = $row->value
;
1698 * Returns an optional USE INDEX clause to go after the table, and a
1699 * string to go at the end of the query.
1701 * @param array $options Associative array of options to be turned into
1702 * an SQL query, valid keys are listed in the function.
1704 * @see Database::select()
1706 protected function makeSelectOptions( $options ) {
1707 $preLimitTail = $postLimitTail = '';
1712 foreach ( $options as $key => $option ) {
1713 if ( is_numeric( $key ) ) {
1714 $noKeyOptions[$option] = true;
1718 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1720 $preLimitTail .= $this->makeOrderBy( $options );
1722 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1723 $postLimitTail .= ' FOR UPDATE';
1726 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1727 $postLimitTail .= ' LOCK IN SHARE MODE';
1730 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1731 $startOpts .= 'DISTINCT';
1734 # Various MySQL extensions
1735 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1736 $startOpts .= ' /*! STRAIGHT_JOIN */';
1739 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1740 $startOpts .= ' HIGH_PRIORITY';
1743 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1744 $startOpts .= ' SQL_BIG_RESULT';
1747 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1748 $startOpts .= ' SQL_BUFFER_RESULT';
1751 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1752 $startOpts .= ' SQL_SMALL_RESULT';
1755 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1756 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1759 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1760 $startOpts .= ' SQL_CACHE';
1763 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1764 $startOpts .= ' SQL_NO_CACHE';
1767 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1768 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1772 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1773 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1778 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1782 * Returns an optional GROUP BY with an optional HAVING
1784 * @param array $options Associative array of options
1786 * @see Database::select()
1789 protected function makeGroupByWithHaving( $options ) {
1791 if ( isset( $options['GROUP BY'] ) ) {
1792 $gb = is_array( $options['GROUP BY'] )
1793 ?
implode( ',', $options['GROUP BY'] )
1794 : $options['GROUP BY'];
1795 $sql .= ' GROUP BY ' . $gb;
1797 if ( isset( $options['HAVING'] ) ) {
1798 $having = is_array( $options['HAVING'] )
1799 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1800 : $options['HAVING'];
1801 $sql .= ' HAVING ' . $having;
1808 * Returns an optional ORDER BY
1810 * @param array $options Associative array of options
1812 * @see Database::select()
1815 protected function makeOrderBy( $options ) {
1816 if ( isset( $options['ORDER BY'] ) ) {
1817 $ob = is_array( $options['ORDER BY'] )
1818 ?
implode( ',', $options['ORDER BY'] )
1819 : $options['ORDER BY'];
1821 return ' ORDER BY ' . $ob;
1827 public function select(
1828 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1830 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1832 return $this->query( $sql, $fname );
1835 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1836 $options = [], $join_conds = []
1838 if ( is_array( $vars ) ) {
1839 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1844 $options = (array)$options;
1845 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1846 ?
$options['USE INDEX']
1849 isset( $options['IGNORE INDEX'] ) &&
1850 is_array( $options['IGNORE INDEX'] )
1852 ?
$options['IGNORE INDEX']
1856 $this->selectOptionsIncludeLocking( $options ) &&
1857 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1859 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1860 // functions. Discourage use of such queries to encourage compatibility.
1862 $this->deprecationLogger
,
1863 __METHOD__
. ": aggregation used with a locking SELECT ($fname)"
1867 if ( is_array( $table ) ) {
1869 $this->tableNamesWithIndexClauseOrJOIN(
1870 $table, $useIndexes, $ignoreIndexes, $join_conds );
1871 } elseif ( $table != '' ) {
1873 $this->tableNamesWithIndexClauseOrJOIN(
1874 [ $table ], $useIndexes, $ignoreIndexes, [] );
1879 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1880 $this->makeSelectOptions( $options );
1882 if ( is_array( $conds ) ) {
1883 $conds = $this->makeList( $conds, self
::LIST_AND
);
1886 if ( $conds === null ||
$conds === false ) {
1887 $this->queryLogger
->warning(
1891 . ' with incorrect parameters: $conds must be a string or an array'
1896 if ( $conds === '' ||
$conds === '*' ) {
1897 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1898 } elseif ( is_string( $conds ) ) {
1899 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1900 "WHERE $conds $preLimitTail";
1902 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1905 if ( isset( $options['LIMIT'] ) ) {
1906 $sql = $this->limitResult( $sql, $options['LIMIT'],
1907 $options['OFFSET'] ??
false );
1909 $sql = "$sql $postLimitTail";
1911 if ( isset( $options['EXPLAIN'] ) ) {
1912 $sql = 'EXPLAIN ' . $sql;
1918 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1919 $options = [], $join_conds = []
1921 $options = (array)$options;
1922 $options['LIMIT'] = 1;
1924 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1925 if ( $res === false ) {
1926 throw new DBUnexpectedError( $this, "Got false from select()" );
1929 if ( !$this->numRows( $res ) ) {
1933 return $this->fetchObject( $res );
1936 public function estimateRowCount(
1937 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1939 $conds = $this->normalizeConditions( $conds, $fname );
1940 $column = $this->extractSingleFieldFromList( $var );
1941 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1942 $conds[] = "$column IS NOT NULL";
1945 $res = $this->select(
1946 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1948 $row = $res ?
$this->fetchRow( $res ) : [];
1950 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1953 public function selectRowCount(
1954 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1956 $conds = $this->normalizeConditions( $conds, $fname );
1957 $column = $this->extractSingleFieldFromList( $var );
1958 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1959 $conds[] = "$column IS NOT NULL";
1962 $res = $this->select(
1964 'tmp_count' => $this->buildSelectSubquery(
1973 [ 'rowcount' => 'COUNT(*)' ],
1977 $row = $res ?
$this->fetchRow( $res ) : [];
1979 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1983 * @param string|array $options
1986 private function selectOptionsIncludeLocking( $options ) {
1987 $options = (array)$options;
1988 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1989 if ( in_array( $lock, $options, true ) ) {
1998 * @param array|string $fields
1999 * @param array|string $options
2002 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
2003 foreach ( (array)$options as $key => $value ) {
2004 if ( is_string( $key ) ) {
2005 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
2008 } elseif ( is_string( $value ) ) {
2009 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
2015 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
2016 foreach ( (array)$fields as $field ) {
2017 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
2026 * @param array|string $conds
2027 * @param string $fname
2030 final protected function normalizeConditions( $conds, $fname ) {
2031 if ( $conds === null ||
$conds === false ) {
2032 $this->queryLogger
->warning(
2036 . ' with incorrect parameters: $conds must be a string or an array'
2041 if ( !is_array( $conds ) ) {
2042 $conds = ( $conds === '' ) ?
[] : [ $conds ];
2049 * @param array|string $var Field parameter in the style of select()
2050 * @return string|null Column name or null; ignores aliases
2051 * @throws DBUnexpectedError Errors out if multiple columns are given
2053 final protected function extractSingleFieldFromList( $var ) {
2054 if ( is_array( $var ) ) {
2057 } elseif ( count( $var ) == 1 ) {
2058 $column = $var[0] ??
reset( $var );
2060 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns' );
2069 public function lockForUpdate(
2070 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2072 if ( !$this->trxLevel() && !$this->getFlag( self
::DBO_TRX
) ) {
2073 throw new DBUnexpectedError(
2075 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2079 $options = (array)$options;
2080 $options[] = 'FOR UPDATE';
2082 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2085 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2086 $info = $this->fieldInfo( $table, $field );
2091 public function indexExists( $table, $index, $fname = __METHOD__
) {
2092 if ( !$this->tableExists( $table ) ) {
2096 $info = $this->indexInfo( $table, $index, $fname );
2097 if ( is_null( $info ) ) {
2100 return $info !== false;
2104 abstract public function tableExists( $table, $fname = __METHOD__
);
2106 public function indexUnique( $table, $index ) {
2107 $indexInfo = $this->indexInfo( $table, $index );
2109 if ( !$indexInfo ) {
2113 return !$indexInfo[0]->Non_unique
;
2117 * Helper for Database::insert().
2119 * @param array $options
2122 protected function makeInsertOptions( $options ) {
2123 return implode( ' ', $options );
2126 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2127 # No rows to insert, easy just return now
2128 if ( !count( $a ) ) {
2132 $table = $this->tableName( $table );
2134 if ( !is_array( $options ) ) {
2135 $options = [ $options ];
2138 $options = $this->makeInsertOptions( $options );
2140 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2142 $keys = array_keys( $a[0] );
2145 $keys = array_keys( $a );
2148 $sql = 'INSERT ' . $options .
2149 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2153 foreach ( $a as $row ) {
2159 $sql .= '(' . $this->makeList( $row ) . ')';
2162 $sql .= '(' . $this->makeList( $a ) . ')';
2165 $this->query( $sql, $fname );
2171 * Make UPDATE options array for Database::makeUpdateOptions
2173 * @param array $options
2176 protected function makeUpdateOptionsArray( $options ) {
2177 if ( !is_array( $options ) ) {
2178 $options = [ $options ];
2183 if ( in_array( 'IGNORE', $options ) ) {
2191 * Make UPDATE options for the Database::update function
2193 * @param array $options The options passed to Database::update
2196 protected function makeUpdateOptions( $options ) {
2197 $opts = $this->makeUpdateOptionsArray( $options );
2199 return implode( ' ', $opts );
2202 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2203 $table = $this->tableName( $table );
2204 $opts = $this->makeUpdateOptions( $options );
2205 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2207 if ( $conds !== [] && $conds !== '*' ) {
2208 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2211 $this->query( $sql, $fname );
2216 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2217 if ( !is_array( $a ) ) {
2218 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2224 foreach ( $a as $field => $value ) {
2226 if ( $mode == self
::LIST_AND
) {
2228 } elseif ( $mode == self
::LIST_OR
) {
2237 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2238 $list .= "($value)";
2239 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2242 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2244 // Remove null from array to be handled separately if found
2245 $includeNull = false;
2246 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2247 $includeNull = true;
2248 unset( $value[$nullKey] );
2250 if ( count( $value ) == 0 && !$includeNull ) {
2251 throw new InvalidArgumentException(
2252 __METHOD__
. ": empty input for field $field" );
2253 } elseif ( count( $value ) == 0 ) {
2254 // only check if $field is null
2255 $list .= "$field IS NULL";
2257 // IN clause contains at least one valid element
2258 if ( $includeNull ) {
2259 // Group subconditions to ensure correct precedence
2262 if ( count( $value ) == 1 ) {
2263 // Special-case single values, as IN isn't terribly efficient
2264 // Don't necessarily assume the single key is 0; we don't
2265 // enforce linear numeric ordering on other arrays here.
2266 $value = array_values( $value )[0];
2267 $list .= $field . " = " . $this->addQuotes( $value );
2269 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2271 // if null present in array, append IS NULL
2272 if ( $includeNull ) {
2273 $list .= " OR $field IS NULL)";
2276 } elseif ( $value === null ) {
2277 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2278 $list .= "$field IS ";
2279 } elseif ( $mode == self
::LIST_SET
) {
2280 $list .= "$field = ";
2285 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2287 $list .= "$field = ";
2289 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2296 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2299 foreach ( $data as $base => $sub ) {
2300 if ( count( $sub ) ) {
2301 $conds[] = $this->makeList(
2302 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2308 return $this->makeList( $conds, self
::LIST_OR
);
2310 // Nothing to search for...
2315 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2319 public function bitNot( $field ) {
2323 public function bitAnd( $fieldLeft, $fieldRight ) {
2324 return "($fieldLeft & $fieldRight)";
2327 public function bitOr( $fieldLeft, $fieldRight ) {
2328 return "($fieldLeft | $fieldRight)";
2331 public function buildConcat( $stringList ) {
2332 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2335 public function buildGroupConcatField(
2336 $delim, $table, $field, $conds = '', $join_conds = []
2338 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2340 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2343 public function buildSubstring( $input, $startPosition, $length = null ) {
2344 $this->assertBuildSubstringParams( $startPosition, $length );
2345 $functionBody = "$input FROM $startPosition";
2346 if ( $length !== null ) {
2347 $functionBody .= " FOR $length";
2349 return 'SUBSTRING(' . $functionBody . ')';
2353 * Check type and bounds for parameters to self::buildSubstring()
2355 * All supported databases have substring functions that behave the same for
2356 * positive $startPosition and non-negative $length, but behaviors differ when
2357 * given 0 or negative $startPosition or negative $length. The simplest
2358 * solution to that is to just forbid those values.
2360 * @param int $startPosition
2361 * @param int|null $length
2364 protected function assertBuildSubstringParams( $startPosition, $length ) {
2365 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2366 throw new InvalidArgumentException(
2367 '$startPosition must be a positive integer'
2370 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2371 throw new InvalidArgumentException(
2372 '$length must be null or an integer greater than or equal to 0'
2377 public function buildStringCast( $field ) {
2378 // In theory this should work for any standards-compliant
2379 // SQL implementation, although it may not be the best way to do it.
2380 return "CAST( $field AS CHARACTER )";
2383 public function buildIntegerCast( $field ) {
2384 return 'CAST( ' . $field . ' AS INTEGER )';
2387 public function buildSelectSubquery(
2388 $table, $vars, $conds = '', $fname = __METHOD__
,
2389 $options = [], $join_conds = []
2391 return new Subquery(
2392 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2396 public function databasesAreIndependent() {
2400 final public function selectDB( $db ) {
2401 $this->selectDomain( new DatabaseDomain(
2403 $this->currentDomain
->getSchema(),
2404 $this->currentDomain
->getTablePrefix()
2410 final public function selectDomain( $domain ) {
2411 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2414 protected function doSelectDomain( DatabaseDomain
$domain ) {
2415 $this->currentDomain
= $domain;
2418 public function getDBname() {
2419 return $this->currentDomain
->getDatabase();
2422 public function getServer() {
2423 return $this->server
;
2426 public function tableName( $name, $format = 'quoted' ) {
2427 if ( $name instanceof Subquery
) {
2428 throw new DBUnexpectedError(
2430 __METHOD__
. ': got Subquery instance when expecting a string'
2434 # Skip the entire process when we have a string quoted on both ends.
2435 # Note that we check the end so that we will still quote any use of
2436 # use of `database`.table. But won't break things if someone wants
2437 # to query a database table with a dot in the name.
2438 if ( $this->isQuotedIdentifier( $name ) ) {
2442 # Lets test for any bits of text that should never show up in a table
2443 # name. Basically anything like JOIN or ON which are actually part of
2444 # SQL queries, but may end up inside of the table value to combine
2445 # sql. Such as how the API is doing.
2446 # Note that we use a whitespace test rather than a \b test to avoid
2447 # any remote case where a word like on may be inside of a table name
2448 # surrounded by symbols which may be considered word breaks.
2449 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2450 $this->queryLogger
->warning(
2451 __METHOD__
. ": use of subqueries is not supported this way",
2452 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2458 # Split database and table into proper variables.
2459 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2461 # Quote $table and apply the prefix if not quoted.
2462 # $tableName might be empty if this is called from Database::replaceVars()
2463 $tableName = "{$prefix}{$table}";
2464 if ( $format === 'quoted'
2465 && !$this->isQuotedIdentifier( $tableName )
2466 && $tableName !== ''
2468 $tableName = $this->addIdentifierQuotes( $tableName );
2471 # Quote $schema and $database and merge them with the table name if needed
2472 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2473 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2479 * Get the table components needed for a query given the currently selected database
2481 * @param string $name Table name in the form of db.schema.table, db.table, or table
2482 * @return array (DB name or "" for default, schema name, table prefix, table name)
2484 protected function qualifiedTableComponents( $name ) {
2485 # We reverse the explode so that database.table and table both output the correct table.
2486 $dbDetails = explode( '.', $name, 3 );
2487 if ( count( $dbDetails ) == 3 ) {
2488 list( $database, $schema, $table ) = $dbDetails;
2489 # We don't want any prefix added in this case
2491 } elseif ( count( $dbDetails ) == 2 ) {
2492 list( $database, $table ) = $dbDetails;
2493 # We don't want any prefix added in this case
2495 # In dbs that support it, $database may actually be the schema
2496 # but that doesn't affect any of the functionality here
2499 list( $table ) = $dbDetails;
2500 if ( isset( $this->tableAliases
[$table] ) ) {
2501 $database = $this->tableAliases
[$table]['dbname'];
2502 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2503 ?
$this->tableAliases
[$table]['schema']
2504 : $this->relationSchemaQualifier();
2505 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2506 ?
$this->tableAliases
[$table]['prefix']
2507 : $this->tablePrefix();
2510 $schema = $this->relationSchemaQualifier(); # Default schema
2511 $prefix = $this->tablePrefix(); # Default prefix
2515 return [ $database, $schema, $prefix, $table ];
2519 * @param string|null $namespace Database or schema
2520 * @param string $relation Name of table, view, sequence, etc...
2521 * @param string $format One of (raw, quoted)
2522 * @return string Relation name with quoted and merged $namespace as needed
2524 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2525 if ( strlen( $namespace ) ) {
2526 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2527 $namespace = $this->addIdentifierQuotes( $namespace );
2529 $relation = $namespace . '.' . $relation;
2535 public function tableNames() {
2536 $inArray = func_get_args();
2539 foreach ( $inArray as $name ) {
2540 $retVal[$name] = $this->tableName( $name );
2546 public function tableNamesN() {
2547 $inArray = func_get_args();
2550 foreach ( $inArray as $name ) {
2551 $retVal[] = $this->tableName( $name );
2558 * Get an aliased table name
2560 * This returns strings like "tableName AS newTableName" for aliased tables
2561 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2563 * @see Database::tableName()
2564 * @param string|Subquery $table Table name or object with a 'sql' field
2565 * @param string|bool $alias Table alias (optional)
2566 * @return string SQL name for aliased table. Will not alias a table to its own name
2568 protected function tableNameWithAlias( $table, $alias = false ) {
2569 if ( is_string( $table ) ) {
2570 $quotedTable = $this->tableName( $table );
2571 } elseif ( $table instanceof Subquery
) {
2572 $quotedTable = (string)$table;
2574 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2577 if ( $alias === false ||
$alias === $table ) {
2578 if ( $table instanceof Subquery
) {
2579 throw new InvalidArgumentException( "Subquery table missing alias" );
2582 return $quotedTable;
2584 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2589 * Gets an array of aliased table names
2591 * @param array $tables [ [alias] => table ]
2592 * @return string[] See tableNameWithAlias()
2594 protected function tableNamesWithAlias( $tables ) {
2596 foreach ( $tables as $alias => $table ) {
2597 if ( is_numeric( $alias ) ) {
2600 $retval[] = $this->tableNameWithAlias( $table, $alias );
2607 * Get an aliased field name
2608 * e.g. fieldName AS newFieldName
2610 * @param string $name Field name
2611 * @param string|bool $alias Alias (optional)
2612 * @return string SQL name for aliased field. Will not alias a field to its own name
2614 protected function fieldNameWithAlias( $name, $alias = false ) {
2615 if ( !$alias ||
(string)$alias === (string)$name ) {
2618 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2623 * Gets an array of aliased field names
2625 * @param array $fields [ [alias] => field ]
2626 * @return string[] See fieldNameWithAlias()
2628 protected function fieldNamesWithAlias( $fields ) {
2630 foreach ( $fields as $alias => $field ) {
2631 if ( is_numeric( $alias ) ) {
2634 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2641 * Get the aliased table name clause for a FROM clause
2642 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2644 * @param array $tables ( [alias] => table )
2645 * @param array $use_index Same as for select()
2646 * @param array $ignore_index Same as for select()
2647 * @param array $join_conds Same as for select()
2650 protected function tableNamesWithIndexClauseOrJOIN(
2651 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2655 $use_index = (array)$use_index;
2656 $ignore_index = (array)$ignore_index;
2657 $join_conds = (array)$join_conds;
2659 foreach ( $tables as $alias => $table ) {
2660 if ( !is_string( $alias ) ) {
2661 // No alias? Set it equal to the table name
2665 if ( is_array( $table ) ) {
2666 // A parenthesized group
2667 if ( count( $table ) > 1 ) {
2668 $joinedTable = '(' .
2669 $this->tableNamesWithIndexClauseOrJOIN(
2670 $table, $use_index, $ignore_index, $join_conds ) . ')';
2673 $innerTable = reset( $table );
2674 $innerAlias = key( $table );
2675 $joinedTable = $this->tableNameWithAlias(
2677 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2681 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2684 // Is there a JOIN clause for this table?
2685 if ( isset( $join_conds[$alias] ) ) {
2686 list( $joinType, $conds ) = $join_conds[$alias];
2687 $tableClause = $joinType;
2688 $tableClause .= ' ' . $joinedTable;
2689 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2690 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2692 $tableClause .= ' ' . $use;
2695 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2696 $ignore = $this->ignoreIndexClause(
2697 implode( ',', (array)$ignore_index[$alias] ) );
2698 if ( $ignore != '' ) {
2699 $tableClause .= ' ' . $ignore;
2702 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2704 $tableClause .= ' ON (' . $on . ')';
2707 $retJOIN[] = $tableClause;
2708 } elseif ( isset( $use_index[$alias] ) ) {
2709 // Is there an INDEX clause for this table?
2710 $tableClause = $joinedTable;
2711 $tableClause .= ' ' . $this->useIndexClause(
2712 implode( ',', (array)$use_index[$alias] )
2715 $ret[] = $tableClause;
2716 } elseif ( isset( $ignore_index[$alias] ) ) {
2717 // Is there an INDEX clause for this table?
2718 $tableClause = $joinedTable;
2719 $tableClause .= ' ' . $this->ignoreIndexClause(
2720 implode( ',', (array)$ignore_index[$alias] )
2723 $ret[] = $tableClause;
2725 $tableClause = $joinedTable;
2727 $ret[] = $tableClause;
2731 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2732 $implicitJoins = implode( ',', $ret );
2733 $explicitJoins = implode( ' ', $retJOIN );
2735 // Compile our final table clause
2736 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2740 * Allows for index remapping in queries where this is not consistent across DBMS
2742 * @param string $index
2745 protected function indexName( $index ) {
2746 return $this->indexAliases
[$index] ??
$index;
2749 public function addQuotes( $s ) {
2750 if ( $s instanceof Blob
) {
2753 if ( $s === null ) {
2755 } elseif ( is_bool( $s ) ) {
2758 # This will also quote numeric values. This should be harmless,
2759 # and protects against weird problems that occur when they really
2760 # _are_ strings such as article titles and string->number->string
2761 # conversion is not 1:1.
2762 return "'" . $this->strencode( $s ) . "'";
2766 public function addIdentifierQuotes( $s ) {
2767 return '"' . str_replace( '"', '""', $s ) . '"';
2771 * Returns if the given identifier looks quoted or not according to
2772 * the database convention for quoting identifiers .
2774 * @note Do not use this to determine if untrusted input is safe.
2775 * A malicious user can trick this function.
2776 * @param string $name
2779 public function isQuotedIdentifier( $name ) {
2780 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2785 * @param string $escapeChar
2788 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2789 return str_replace( [ $escapeChar, '%', '_' ],
2790 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2794 public function buildLike( $param, ...$params ) {
2795 if ( is_array( $param ) ) {
2798 $params = func_get_args();
2803 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2804 // may escape backslashes, creating problems of double escaping. The `
2805 // character has good cross-DBMS compatibility, avoiding special operators
2806 // in MS SQL like ^ and %
2809 foreach ( $params as $value ) {
2810 if ( $value instanceof LikeMatch
) {
2811 $s .= $value->toString();
2813 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2818 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2821 public function anyChar() {
2822 return new LikeMatch( '_' );
2825 public function anyString() {
2826 return new LikeMatch( '%' );
2829 public function nextSequenceValue( $seqName ) {
2834 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2835 * is only needed because a) MySQL must be as efficient as possible due to
2836 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2837 * which index to pick. Anyway, other databases might have different
2838 * indexes on a given table. So don't bother overriding this unless you're
2840 * @param string $index
2843 public function useIndexClause( $index ) {
2848 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2849 * is only needed because a) MySQL must be as efficient as possible due to
2850 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2851 * which index to pick. Anyway, other databases might have different
2852 * indexes on a given table. So don't bother overriding this unless you're
2854 * @param string $index
2857 public function ignoreIndexClause( $index ) {
2861 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2862 if ( count( $rows ) == 0 ) {
2866 $uniqueIndexes = (array)$uniqueIndexes;
2868 if ( !is_array( reset( $rows ) ) ) {
2873 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2874 $affectedRowCount = 0;
2875 foreach ( $rows as $row ) {
2876 // Delete rows which collide with this one
2877 $indexWhereClauses = [];
2878 foreach ( $uniqueIndexes as $index ) {
2879 $indexColumns = (array)$index;
2880 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2881 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2882 throw new DBUnexpectedError(
2884 'New record does not provide all values for unique key (' .
2885 implode( ', ', $indexColumns ) . ')'
2887 } elseif ( in_array( null, $indexRowValues, true ) ) {
2888 throw new DBUnexpectedError(
2890 'New record has a null value for unique key (' .
2891 implode( ', ', $indexColumns ) . ')'
2894 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2897 if ( $indexWhereClauses ) {
2898 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2899 $affectedRowCount +
= $this->affectedRows();
2902 // Now insert the row
2903 $this->insert( $table, $row, $fname );
2904 $affectedRowCount +
= $this->affectedRows();
2906 $this->endAtomic( $fname );
2907 $this->affectedRowCount
= $affectedRowCount;
2908 } catch ( Exception
$e ) {
2909 $this->cancelAtomic( $fname );
2915 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2918 * @param string $table Table name
2919 * @param array|string $rows Row(s) to insert
2920 * @param string $fname Caller function name
2922 protected function nativeReplace( $table, $rows, $fname ) {
2923 $table = $this->tableName( $table );
2926 if ( !is_array( reset( $rows ) ) ) {
2930 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2933 foreach ( $rows as $row ) {
2940 $sql .= '(' . $this->makeList( $row ) . ')';
2943 $this->query( $sql, $fname );
2946 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2949 if ( $rows === [] ) {
2950 return true; // nothing to do
2953 $uniqueIndexes = (array)$uniqueIndexes;
2954 if ( !is_array( reset( $rows ) ) ) {
2958 if ( count( $uniqueIndexes ) ) {
2959 $clauses = []; // list WHERE clauses that each identify a single row
2960 foreach ( $rows as $row ) {
2961 foreach ( $uniqueIndexes as $index ) {
2962 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2963 $rowKey = []; // unique key to this row
2964 foreach ( $index as $column ) {
2965 $rowKey[$column] = $row[$column];
2967 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2970 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2975 $affectedRowCount = 0;
2977 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2978 # Update any existing conflicting row(s)
2979 if ( $where !== false ) {
2980 $this->update( $table, $set, $where, $fname );
2981 $affectedRowCount +
= $this->affectedRows();
2983 # Now insert any non-conflicting row(s)
2984 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2985 $affectedRowCount +
= $this->affectedRows();
2986 $this->endAtomic( $fname );
2987 $this->affectedRowCount
= $affectedRowCount;
2988 } catch ( Exception
$e ) {
2989 $this->cancelAtomic( $fname );
2996 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3000 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
3003 $delTable = $this->tableName( $delTable );
3004 $joinTable = $this->tableName( $joinTable );
3005 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3006 if ( $conds != '*' ) {
3007 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
3011 $this->query( $sql, $fname );
3014 public function textFieldSize( $table, $field ) {
3015 $table = $this->tableName( $table );
3016 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
3017 $res = $this->query( $sql, __METHOD__
);
3018 $row = $this->fetchObject( $res );
3022 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3031 public function delete( $table, $conds, $fname = __METHOD__
) {
3033 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
3036 $table = $this->tableName( $table );
3037 $sql = "DELETE FROM $table";
3039 if ( $conds != '*' ) {
3040 if ( is_array( $conds ) ) {
3041 $conds = $this->makeList( $conds, self
::LIST_AND
);
3043 $sql .= ' WHERE ' . $conds;
3046 $this->query( $sql, $fname );
3051 final public function insertSelect(
3052 $destTable, $srcTable, $varMap, $conds,
3053 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3055 static $hints = [ 'NO_AUTO_COLUMNS' ];
3057 $insertOptions = (array)$insertOptions;
3058 $selectOptions = (array)$selectOptions;
3060 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3061 // For massive migrations with downtime, we don't want to select everything
3062 // into memory and OOM, so do all this native on the server side if possible.
3063 $this->nativeInsertSelect(
3069 array_diff( $insertOptions, $hints ),
3074 $this->nonNativeInsertSelect(
3080 array_diff( $insertOptions, $hints ),
3090 * @param array $insertOptions INSERT options
3091 * @param array $selectOptions SELECT options
3092 * @return bool Whether an INSERT SELECT with these options will be replication safe
3095 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3100 * Implementation of insertSelect() based on select() and insert()
3102 * @see IDatabase::insertSelect()
3104 * @param string $destTable
3105 * @param string|array $srcTable
3106 * @param array $varMap
3107 * @param array $conds
3108 * @param string $fname
3109 * @param array $insertOptions
3110 * @param array $selectOptions
3111 * @param array $selectJoinConds
3113 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3114 $fname = __METHOD__
,
3115 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3117 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3118 // on only the master (without needing row-based-replication). It also makes it easy to
3119 // know how big the INSERT is going to be.
3121 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3122 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3124 $selectOptions[] = 'FOR UPDATE';
3125 $res = $this->select(
3126 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3133 $affectedRowCount = 0;
3134 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3137 foreach ( $res as $row ) {
3138 $rows[] = (array)$row;
3140 // Avoid inserts that are too huge
3141 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3142 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3146 $affectedRowCount +
= $this->affectedRows();
3150 if ( $rows && $ok ) {
3151 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3153 $affectedRowCount +
= $this->affectedRows();
3157 $this->endAtomic( $fname );
3158 $this->affectedRowCount
= $affectedRowCount;
3160 $this->cancelAtomic( $fname );
3162 } catch ( Exception
$e ) {
3163 $this->cancelAtomic( $fname );
3169 * Native server-side implementation of insertSelect() for situations where
3170 * we don't want to select everything into memory
3172 * @see IDatabase::insertSelect()
3173 * @param string $destTable
3174 * @param string|array $srcTable
3175 * @param array $varMap
3176 * @param array $conds
3177 * @param string $fname
3178 * @param array $insertOptions
3179 * @param array $selectOptions
3180 * @param array $selectJoinConds
3182 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3183 $fname = __METHOD__
,
3184 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3186 $destTable = $this->tableName( $destTable );
3188 if ( !is_array( $insertOptions ) ) {
3189 $insertOptions = [ $insertOptions ];
3192 $insertOptions = $this->makeInsertOptions( $insertOptions );
3194 $selectSql = $this->selectSQLText(
3196 array_values( $varMap ),
3203 $sql = "INSERT $insertOptions" .
3204 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3207 $this->query( $sql, $fname );
3210 public function limitResult( $sql, $limit, $offset = false ) {
3211 if ( !is_numeric( $limit ) ) {
3212 throw new DBUnexpectedError(
3214 "Invalid non-numeric limit passed to " . __METHOD__
3217 // This version works in MySQL and SQLite. It will very likely need to be
3218 // overridden for most other RDBMS subclasses.
3219 return "$sql LIMIT "
3220 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3224 public function unionSupportsOrderAndLimit() {
3225 return true; // True for almost every DB supported
3228 public function unionQueries( $sqls, $all ) {
3229 $glue = $all ?
') UNION ALL (' : ') UNION (';
3231 return '(' . implode( $glue, $sqls ) . ')';
3234 public function unionConditionPermutations(
3235 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3236 $options = [], $join_conds = []
3238 // First, build the Cartesian product of $permute_conds
3240 foreach ( $permute_conds as $field => $values ) {
3242 // Skip empty $values
3245 $values = array_unique( $values ); // For sanity
3247 foreach ( $conds as $cond ) {
3248 foreach ( $values as $value ) {
3249 $cond[$field] = $value;
3250 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3256 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3258 // If there's just one condition and no subordering, hand off to
3259 // selectSQLText directly.
3260 if ( count( $conds ) === 1 &&
3261 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3263 return $this->selectSQLText(
3264 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3268 // Otherwise, we need to pull out the order and limit to apply after
3269 // the union. Then build the SQL queries for each set of conditions in
3270 // $conds. Then union them together (using UNION ALL, because the
3271 // product *should* already be distinct).
3272 $orderBy = $this->makeOrderBy( $options );
3273 $limit = $options['LIMIT'] ??
null;
3274 $offset = $options['OFFSET'] ??
false;
3275 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3276 if ( !$this->unionSupportsOrderAndLimit() ) {
3277 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3279 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3280 $options['ORDER BY'] = $options['INNER ORDER BY'];
3282 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3283 // We need to increase the limit by the offset rather than
3284 // using the offset directly, otherwise it'll skip incorrectly
3285 // in the subqueries.
3286 $options['LIMIT'] = $limit +
$offset;
3287 unset( $options['OFFSET'] );
3292 foreach ( $conds as $cond ) {
3293 $sqls[] = $this->selectSQLText(
3294 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3297 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3298 if ( $limit !== null ) {
3299 $sql = $this->limitResult( $sql, $limit, $offset );
3305 public function conditional( $cond, $trueVal, $falseVal ) {
3306 if ( is_array( $cond ) ) {
3307 $cond = $this->makeList( $cond, self
::LIST_AND
);
3310 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3313 public function strreplace( $orig, $old, $new ) {
3314 return "REPLACE({$orig}, {$old}, {$new})";
3317 public function getServerUptime() {
3321 public function wasDeadlock() {
3325 public function wasLockTimeout() {
3329 public function wasConnectionLoss() {
3330 return $this->wasConnectionError( $this->lastErrno() );
3333 public function wasReadOnlyError() {
3337 public function wasErrorReissuable() {
3339 $this->wasDeadlock() ||
3340 $this->wasLockTimeout() ||
3341 $this->wasConnectionLoss()
3346 * Do not use this method outside of Database/DBError classes
3348 * @param int|string $errno
3349 * @return bool Whether the given query error was a connection drop
3351 public function wasConnectionError( $errno ) {
3356 * @return bool Whether it is known that the last query error only caused statement rollback
3357 * @note This is for backwards compatibility for callers catching DBError exceptions in
3358 * order to ignore problems like duplicate key errors or foriegn key violations
3361 protected function wasKnownStatementRollbackError() {
3362 return false; // don't know; it could have caused a transaction rollback
3365 public function deadlockLoop() {
3366 $args = func_get_args();
3367 $function = array_shift( $args );
3368 $tries = self
::$DEADLOCK_TRIES;
3370 $this->begin( __METHOD__
);
3373 /** @var Exception $e */
3377 $retVal = $function( ...$args );
3379 } catch ( DBQueryError
$e ) {
3380 if ( $this->wasDeadlock() ) {
3381 // Retry after a randomized delay
3382 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3384 // Throw the error back up
3388 } while ( --$tries > 0 );
3390 if ( $tries <= 0 ) {
3391 // Too many deadlocks; give up
3392 $this->rollback( __METHOD__
);
3395 $this->commit( __METHOD__
);
3401 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3402 # Real waits are implemented in the subclass.
3406 public function getReplicaPos() {
3411 public function getMasterPos() {
3416 public function serverIsReadOnly() {
3420 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3421 if ( !$this->trxLevel() ) {
3422 throw new DBUnexpectedError( $this, "No transaction is active" );
3424 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3427 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3428 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3429 // Start an implicit transaction similar to how query() does
3430 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3431 $this->trxAutomatic
= true;
3434 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3435 if ( !$this->trxLevel() ) {
3436 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3440 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3441 $this->onTransactionCommitOrIdle( $callback, $fname );
3444 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3445 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3446 // Start an implicit transaction similar to how query() does
3447 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3448 $this->trxAutomatic
= true;
3451 if ( $this->trxLevel() ) {
3452 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3454 // No transaction is active nor will start implicitly, so make one for this callback
3455 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3458 $this->endAtomic( __METHOD__
);
3459 } catch ( Exception
$e ) {
3460 $this->cancelAtomic( __METHOD__
);
3466 final public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
3467 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3468 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3470 $this->trxSectionCancelCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3474 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3476 private function currentAtomicSectionId() {
3477 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
3478 $levelInfo = end( $this->trxAtomicLevels
);
3480 return $levelInfo[1];
3487 * Hoist callback ownership for callbacks in a section to a parent section.
3488 * All callbacks should have an owner that is present in trxAtomicLevels.
3489 * @param AtomicSectionIdentifier $old
3490 * @param AtomicSectionIdentifier $new
3492 private function reassignCallbacksForSection(
3493 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3495 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3496 if ( $info[2] === $old ) {
3497 $this->trxPreCommitCallbacks
[$key][2] = $new;
3500 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3501 if ( $info[2] === $old ) {
3502 $this->trxIdleCallbacks
[$key][2] = $new;
3505 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3506 if ( $info[2] === $old ) {
3507 $this->trxEndCallbacks
[$key][2] = $new;
3510 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3511 if ( $info[2] === $old ) {
3512 $this->trxSectionCancelCallbacks
[$key][2] = $new;
3518 * Update callbacks that were owned by cancelled atomic sections.
3520 * Callbacks for "on commit" should never be run if they're owned by a
3521 * section that won't be committed.
3523 * Callbacks for "on resolution" need to reflect that the section was
3524 * rolled back, even if the transaction as a whole commits successfully.
3526 * Callbacks for "on section cancel" should already have been consumed,
3527 * but errors during the cancellation itself can prevent that while still
3528 * destroying the section. Hoist any such callbacks to the new top section,
3529 * which we assume will itself have to be cancelled or rolled back to
3530 * resolve the error.
3532 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3533 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3534 * @throws UnexpectedValueException
3536 private function modifyCallbacksForCancel(
3537 array $sectionIds, AtomicSectionIdentifier
$newSectionId = null
3539 // Cancel the "on commit" callbacks owned by this savepoint
3540 $this->trxIdleCallbacks
= array_filter(
3541 $this->trxIdleCallbacks
,
3542 function ( $entry ) use ( $sectionIds ) {
3543 return !in_array( $entry[2], $sectionIds, true );
3546 $this->trxPreCommitCallbacks
= array_filter(
3547 $this->trxPreCommitCallbacks
,
3548 function ( $entry ) use ( $sectionIds ) {
3549 return !in_array( $entry[2], $sectionIds, true );
3552 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3553 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3554 if ( in_array( $entry[2], $sectionIds, true ) ) {
3555 $callback = $entry[0];
3556 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3557 // @phan-suppress-next-line PhanInfiniteRecursion No recursion at all here, phan is confused
3558 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3560 // This "on resolution" callback no longer belongs to a section.
3561 $this->trxEndCallbacks
[$key][2] = null;
3564 // Hoist callback ownership for section cancel callbacks to the new top section
3565 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3566 if ( in_array( $entry[2], $sectionIds, true ) ) {
3567 $this->trxSectionCancelCallbacks
[$key][2] = $newSectionId;
3572 final public function setTransactionListener( $name, callable
$callback = null ) {
3574 $this->trxRecurringCallbacks
[$name] = $callback;
3576 unset( $this->trxRecurringCallbacks
[$name] );
3581 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3583 * This method should not be used outside of Database/LoadBalancer
3585 * @param bool $suppress
3588 final public function setTrxEndCallbackSuppression( $suppress ) {
3589 $this->trxEndCallbacksSuppressed
= $suppress;
3593 * Actually consume and run any "on transaction idle/resolution" callbacks.
3595 * This method should not be used outside of Database/LoadBalancer
3597 * @param int $trigger IDatabase::TRIGGER_* constant
3598 * @return int Number of callbacks attempted
3602 public function runOnTransactionIdleCallbacks( $trigger ) {
3603 if ( $this->trxLevel() ) { // sanity
3604 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open' );
3607 if ( $this->trxEndCallbacksSuppressed
) {
3612 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3613 /** @var Exception $e */
3614 $e = null; // first exception
3615 do { // callbacks may add callbacks :)
3616 $callbacks = array_merge(
3617 $this->trxIdleCallbacks
,
3618 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3620 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3621 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3623 // Only run trxSectionCancelCallbacks on rollback, not commit.
3624 // But always consume them.
3625 if ( $trigger === self
::TRIGGER_ROLLBACK
) {
3626 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks
);
3628 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3630 foreach ( $callbacks as $callback ) {
3632 list( $phpCallback ) = $callback;
3633 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3635 // @phan-suppress-next-line PhanParamTooManyCallable
3636 call_user_func( $phpCallback, $trigger, $this );
3637 } catch ( Exception
$ex ) {
3638 call_user_func( $this->errorLogger
, $ex );
3640 // Some callbacks may use startAtomic/endAtomic, so make sure
3641 // their transactions are ended so other callbacks don't fail
3642 if ( $this->trxLevel() ) {
3643 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3647 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3649 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3653 } while ( count( $this->trxIdleCallbacks
) );
3655 if ( $e instanceof Exception
) {
3656 throw $e; // re-throw any first exception
3663 * Actually consume and run any "on transaction pre-commit" callbacks.
3665 * This method should not be used outside of Database/LoadBalancer
3668 * @return int Number of callbacks attempted
3671 public function runOnTransactionPreCommitCallbacks() {
3674 $e = null; // first exception
3675 do { // callbacks may add callbacks :)
3676 $callbacks = $this->trxPreCommitCallbacks
;
3677 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3678 foreach ( $callbacks as $callback ) {
3681 list( $phpCallback ) = $callback;
3682 $phpCallback( $this );
3683 } catch ( Exception
$ex ) {
3684 ( $this->errorLogger
)( $ex );
3688 } while ( count( $this->trxPreCommitCallbacks
) );
3690 if ( $e instanceof Exception
) {
3691 throw $e; // re-throw any first exception
3698 * Actually run any "atomic section cancel" callbacks.
3700 * @param int $trigger IDatabase::TRIGGER_* constant
3701 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3702 * null on transaction rollback
3704 private function runOnAtomicSectionCancelCallbacks(
3705 $trigger, array $sectionIds = null
3707 /** @var Exception|Throwable $e */
3708 $e = null; // first exception
3712 $callbacks = $this->trxSectionCancelCallbacks
;
3713 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3714 foreach ( $callbacks as $entry ) {
3715 if ( $sectionIds === null ||
in_array( $entry[2], $sectionIds, true ) ) {
3717 $entry[0]( $trigger, $this );
3718 } catch ( Exception
$ex ) {
3719 ( $this->errorLogger
)( $ex );
3721 } catch ( Throwable
$ex ) {
3726 $notCancelled[] = $entry;
3729 } while ( count( $this->trxSectionCancelCallbacks
) );
3730 $this->trxSectionCancelCallbacks
= $notCancelled;
3732 if ( $e !== null ) {
3733 throw $e; // re-throw any first Exception/Throwable
3738 * Actually run any "transaction listener" callbacks.
3740 * This method should not be used outside of Database/LoadBalancer
3742 * @param int $trigger IDatabase::TRIGGER_* constant
3746 public function runTransactionListenerCallbacks( $trigger ) {
3747 if ( $this->trxEndCallbacksSuppressed
) {
3751 /** @var Exception $e */
3752 $e = null; // first exception
3754 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3756 $phpCallback( $trigger, $this );
3757 } catch ( Exception
$ex ) {
3758 ( $this->errorLogger
)( $ex );
3763 if ( $e instanceof Exception
) {
3764 throw $e; // re-throw any first exception
3769 * Create a savepoint
3771 * This is used internally to implement atomic sections. It should not be
3775 * @param string $identifier Identifier for the savepoint
3776 * @param string $fname Calling function name
3778 protected function doSavepoint( $identifier, $fname ) {
3779 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3783 * Release a savepoint
3785 * This is used internally to implement atomic sections. It should not be
3789 * @param string $identifier Identifier for the savepoint
3790 * @param string $fname Calling function name
3792 protected function doReleaseSavepoint( $identifier, $fname ) {
3793 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3797 * Rollback to a savepoint
3799 * This is used internally to implement atomic sections. It should not be
3803 * @param string $identifier Identifier for the savepoint
3804 * @param string $fname Calling function name
3806 protected function doRollbackToSavepoint( $identifier, $fname ) {
3807 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3811 * @param string $fname
3814 private function nextSavepointId( $fname ) {
3815 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3816 if ( strlen( $savepointId ) > 30 ) {
3817 // 30 == Oracle's identifier length limit (pre 12c)
3818 // With a 22 character prefix, that puts the highest number at 99999999.
3819 throw new DBUnexpectedError(
3821 'There have been an excessively large number of atomic sections in a transaction'
3822 . " started by $this->trxFname (at $fname)"
3826 return $savepointId;
3829 final public function startAtomic(
3830 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3832 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3834 if ( !$this->trxLevel() ) {
3835 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3836 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3837 // in all changes being in one transaction to keep requests transactional.
3838 if ( $this->getFlag( self
::DBO_TRX
) ) {
3839 // Since writes could happen in between the topmost atomic sections as part
3840 // of the transaction, those sections will need savepoints.
3841 $savepointId = $this->nextSavepointId( $fname );
3842 $this->doSavepoint( $savepointId, $fname );
3844 $this->trxAutomaticAtomic
= true;
3846 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3847 $savepointId = $this->nextSavepointId( $fname );
3848 $this->doSavepoint( $savepointId, $fname );
3851 $sectionId = new AtomicSectionIdentifier
;
3852 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3853 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3854 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3859 final public function endAtomic( $fname = __METHOD__
) {
3860 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3861 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3864 // Check if the current section matches $fname
3865 $pos = count( $this->trxAtomicLevels
) - 1;
3866 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3867 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3869 if ( $savedFname !== $fname ) {
3870 throw new DBUnexpectedError(
3872 "Invalid atomic section ended (got $fname but expected $savedFname)"
3876 // Remove the last section (no need to re-index the array)
3877 array_pop( $this->trxAtomicLevels
);
3879 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3880 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3881 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3882 $this->doReleaseSavepoint( $savepointId, $fname );
3885 // Hoist callback ownership for callbacks in the section that just ended;
3886 // all callbacks should have an owner that is present in trxAtomicLevels.
3887 $currentSectionId = $this->currentAtomicSectionId();
3888 if ( $currentSectionId ) {
3889 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3893 final public function cancelAtomic(
3894 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3896 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3897 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3901 $newTopSection = $this->currentAtomicSectionId();
3903 $excisedFnames = [];
3904 if ( $sectionId !== null ) {
3905 // Find the (last) section with the given $sectionId
3907 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3908 if ( $asId === $sectionId ) {
3913 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3915 // Remove all descendant sections and re-index the array
3916 $len = count( $this->trxAtomicLevels
);
3917 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3918 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3919 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3921 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3922 $newTopSection = $this->currentAtomicSectionId();
3925 // Check if the current section matches $fname
3926 $pos = count( $this->trxAtomicLevels
) - 1;
3927 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3929 if ( $excisedFnames ) {
3930 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3931 "and descendants " . implode( ', ', $excisedFnames ) );
3933 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3936 if ( $savedFname !== $fname ) {
3937 throw new DBUnexpectedError(
3939 "Invalid atomic section ended (got $fname but expected $savedFname)"
3943 // Remove the last section (no need to re-index the array)
3944 array_pop( $this->trxAtomicLevels
);
3945 $excisedIds[] = $savedSectionId;
3946 $newTopSection = $this->currentAtomicSectionId();
3948 if ( $savepointId !== null ) {
3949 // Rollback the transaction to the state just before this atomic section
3950 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3951 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3952 // Note: rollback() will run trxSectionCancelCallbacks
3954 $this->doRollbackToSavepoint( $savepointId, $fname );
3955 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3956 $this->trxStatusIgnoredCause
= null;
3958 // Run trxSectionCancelCallbacks now.
3959 $this->runOnAtomicSectionCancelCallbacks( self
::TRIGGER_CANCEL
, $excisedIds );
3961 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3962 // Put the transaction into an error state if it's not already in one
3963 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3964 $this->trxStatusCause
= new DBUnexpectedError(
3966 "Uncancelable atomic section canceled (got $fname)"
3970 // Fix up callbacks owned by the sections that were just cancelled.
3971 // All callbacks should have an owner that is present in trxAtomicLevels.
3972 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3975 $this->affectedRowCount
= 0; // for the sake of consistency
3978 final public function doAtomicSection(
3979 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3981 $sectionId = $this->startAtomic( $fname, $cancelable );
3983 $res = $callback( $this, $fname );
3984 } catch ( Exception
$e ) {
3985 $this->cancelAtomic( $fname, $sectionId );
3989 $this->endAtomic( $fname );
3994 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3995 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3996 if ( !in_array( $mode, $modes, true ) ) {
3997 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
4000 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
4001 if ( $this->trxLevel() ) {
4002 if ( $this->trxAtomicLevels
) {
4003 $levels = $this->flatAtomicSectionList();
4004 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open";
4005 throw new DBUnexpectedError( $this, $msg );
4006 } elseif ( !$this->trxAutomatic
) {
4007 $msg = "$fname: Explicit transaction already active (from {$this->trxFname})";
4008 throw new DBUnexpectedError( $this, $msg );
4010 $msg = "$fname: Implicit transaction already active (from {$this->trxFname})";
4011 throw new DBUnexpectedError( $this, $msg );
4013 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
4014 $msg = "$fname: Implicit transaction expected (DBO_TRX set)";
4015 throw new DBUnexpectedError( $this, $msg );
4018 $this->assertHasConnectionHandle();
4020 $this->doBegin( $fname );
4021 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
4022 $this->trxStatus
= self
::STATUS_TRX_OK
;
4023 $this->trxStatusIgnoredCause
= null;
4024 $this->trxAtomicCounter
= 0;
4025 $this->trxTimestamp
= microtime( true );
4026 $this->trxFname
= $fname;
4027 $this->trxDoneWrites
= false;
4028 $this->trxAutomaticAtomic
= false;
4029 $this->trxAtomicLevels
= [];
4030 $this->trxWriteDuration
= 0.0;
4031 $this->trxWriteQueryCount
= 0;
4032 $this->trxWriteAffectedRows
= 0;
4033 $this->trxWriteAdjDuration
= 0.0;
4034 $this->trxWriteAdjQueryCount
= 0;
4035 $this->trxWriteCallers
= [];
4036 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
4037 // Get an estimate of the replication lag before any such queries.
4038 $this->trxReplicaLag
= null; // clear cached value first
4039 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
4040 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
4041 // caller will think its OK to muck around with the transaction just because startAtomic()
4042 // has not yet completed (e.g. setting trxAtomicLevels).
4043 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
4047 * Issues the BEGIN command to the database server.
4049 * @see Database::begin()
4050 * @param string $fname
4053 protected function doBegin( $fname ) {
4054 $this->query( 'BEGIN', $fname );
4057 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4058 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
4059 if ( !in_array( $flush, $modes, true ) ) {
4060 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4063 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
4064 // There are still atomic sections open; this cannot be ignored
4065 $levels = $this->flatAtomicSectionList();
4066 throw new DBUnexpectedError(
4068 "$fname: Got COMMIT while atomic sections $levels are still open"
4072 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
4073 if ( !$this->trxLevel() ) {
4074 return; // nothing to do
4075 } elseif ( !$this->trxAutomatic
) {
4076 throw new DBUnexpectedError(
4078 "$fname: Flushing an explicit transaction, getting out of sync"
4081 } elseif ( !$this->trxLevel() ) {
4082 $this->queryLogger
->error(
4083 "$fname: No transaction to commit, something got out of sync" );
4084 return; // nothing to do
4085 } elseif ( $this->trxAutomatic
) {
4086 throw new DBUnexpectedError(
4088 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)"
4092 $this->assertHasConnectionHandle();
4094 $this->runOnTransactionPreCommitCallbacks();
4096 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
4097 $this->doCommit( $fname );
4098 $oldTrxShortId = $this->consumeTrxShortId();
4099 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4101 if ( $this->trxDoneWrites
) {
4102 $this->lastWriteTime
= microtime( true );
4103 $this->trxProfiler
->transactionWritingOut(
4105 $this->getDomainID(),
4108 $this->trxWriteAffectedRows
4112 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4113 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4114 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4115 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4120 * Issues the COMMIT command to the database server.
4122 * @see Database::commit()
4123 * @param string $fname
4126 protected function doCommit( $fname ) {
4127 if ( $this->trxLevel() ) {
4128 $this->query( 'COMMIT', $fname );
4132 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4133 $trxActive = $this->trxLevel();
4135 if ( $flush !== self
::FLUSHING_INTERNAL
4136 && $flush !== self
::FLUSHING_ALL_PEERS
4137 && $this->getFlag( self
::DBO_TRX
)
4139 throw new DBUnexpectedError(
4141 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4146 $this->assertHasConnectionHandle();
4148 $this->doRollback( $fname );
4149 $oldTrxShortId = $this->consumeTrxShortId();
4150 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4151 $this->trxAtomicLevels
= [];
4152 // Estimate the RTT via a query now that trxStatus is OK
4153 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4155 if ( $this->trxDoneWrites
) {
4156 $this->trxProfiler
->transactionWritingOut(
4158 $this->getDomainID(),
4161 $this->trxWriteAffectedRows
4166 // Clear any commit-dependant callbacks. They might even be present
4167 // only due to transaction rounds, with no SQL transaction being active
4168 $this->trxIdleCallbacks
= [];
4169 $this->trxPreCommitCallbacks
= [];
4171 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4172 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4174 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4175 } catch ( Exception
$e ) {
4176 // already logged; finish and let LoadBalancer move on during mass-rollback
4179 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4180 } catch ( Exception
$e ) {
4181 // already logged; let LoadBalancer move on during mass-rollback
4184 $this->affectedRowCount
= 0; // for the sake of consistency
4189 * Issues the ROLLBACK command to the database server.
4191 * @see Database::rollback()
4192 * @param string $fname
4195 protected function doRollback( $fname ) {
4196 if ( $this->trxLevel() ) {
4197 # Disconnects cause rollback anyway, so ignore those errors
4198 $ignoreErrors = true;
4199 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4203 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4204 if ( $this->explicitTrxActive() ) {
4205 // Committing this transaction would break callers that assume it is still open
4206 throw new DBUnexpectedError(
4208 "$fname: Cannot flush snapshot; " .
4209 "explicit transaction '{$this->trxFname}' is still open"
4211 } elseif ( $this->writesOrCallbacksPending() ) {
4212 // This only flushes transactions to clear snapshots, not to write data
4213 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4214 throw new DBUnexpectedError(
4216 "$fname: Cannot flush snapshot; " .
4217 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4220 $this->trxLevel() &&
4221 $this->getTransactionRoundId() &&
4222 $flush !== self
::FLUSHING_INTERNAL
&&
4223 $flush !== self
::FLUSHING_ALL_PEERS
4225 $this->queryLogger
->warning(
4226 "$fname: Expected mass snapshot flush of all peer transactions " .
4227 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4228 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4232 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4235 public function explicitTrxActive() {
4236 return $this->trxLevel() && ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4239 public function duplicateTableStructure(
4240 $oldName, $newName, $temporary = false, $fname = __METHOD__
4242 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4245 public function listTables( $prefix = null, $fname = __METHOD__
) {
4246 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4249 public function listViews( $prefix = null, $fname = __METHOD__
) {
4250 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4253 public function timestamp( $ts = 0 ) {
4254 $t = new ConvertibleTimestamp( $ts );
4255 // Let errors bubble up to avoid putting garbage in the DB
4256 return $t->getTimestamp( TS_MW
);
4259 public function timestampOrNull( $ts = null ) {
4260 if ( is_null( $ts ) ) {
4263 return $this->timestamp( $ts );
4267 public function affectedRows() {
4268 return ( $this->affectedRowCount
=== null )
4269 ?
$this->fetchAffectedRowCount() // default to driver value
4270 : $this->affectedRowCount
;
4274 * @return int Number of retrieved rows according to the driver
4276 abstract protected function fetchAffectedRowCount();
4279 * Take a query result and wrap it in an iterable result wrapper if necessary.
4280 * Booleans are passed through as-is to indicate success/failure of write queries.
4282 * Once upon a time, Database::query() returned a bare MySQL result
4283 * resource, and it was necessary to call this function to convert it to
4284 * a wrapper. Nowadays, raw database objects are never exposed to external
4285 * callers, so this is unnecessary in external code.
4287 * @param bool|IResultWrapper|resource $result
4288 * @return bool|IResultWrapper
4290 protected function resultObject( $result ) {
4292 return false; // failed query
4293 } elseif ( $result instanceof IResultWrapper
) {
4295 } elseif ( $result === true ) {
4296 return $result; // succesful write query
4298 return new ResultWrapper( $this, $result );
4302 public function ping( &$rtt = null ) {
4303 // Avoid hitting the server if it was hit recently
4304 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4305 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4306 $rtt = $this->lastRoundTripEstimate
;
4307 return true; // don't care about $rtt
4311 // This will reconnect if possible or return false if not
4312 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4313 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, true ) !== false );
4314 $this->restoreFlags( self
::RESTORE_PRIOR
);
4317 $rtt = $this->lastRoundTripEstimate
;
4324 * Close any existing (dead) database connection and open a new connection
4326 * @param string $fname
4327 * @return bool True if new connection is opened successfully, false if error
4329 protected function replaceLostConnection( $fname ) {
4330 $this->closeConnection();
4333 $this->handleSessionLossPreconnect();
4340 $this->currentDomain
->getDatabase(),
4341 $this->currentDomain
->getSchema(),
4342 $this->tablePrefix()
4344 $this->lastPing
= microtime( true );
4347 $this->connLogger
->warning(
4348 $fname . ': lost connection to {dbserver}; reconnected',
4350 'dbserver' => $this->getServer(),
4351 'trace' => ( new RuntimeException() )->getTraceAsString()
4354 } catch ( DBConnectionError
$e ) {
4357 $this->connLogger
->error(
4358 $fname . ': lost connection to {dbserver} permanently',
4359 [ 'dbserver' => $this->getServer() ]
4363 $this->handleSessionLossPostconnect();
4368 public function getSessionLagStatus() {
4369 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4373 * Get the replica DB lag when the current transaction started
4375 * This is useful when transactions might use snapshot isolation
4376 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4377 * is this lag plus transaction duration. If they don't, it is still
4378 * safe to be pessimistic. This returns null if there is no transaction.
4380 * This returns null if the lag status for this transaction was not yet recorded.
4382 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4385 final protected function getRecordedTransactionLagStatus() {
4386 return ( $this->trxLevel() && $this->trxReplicaLag
!== null )
4387 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4392 * Get a replica DB lag estimate for this server
4394 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4397 protected function getApproximateLagStatus() {
4399 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4400 'since' => microtime( true )
4405 * Merge the result of getSessionLagStatus() for several DBs
4406 * using the most pessimistic values to estimate the lag of
4407 * any data derived from them in combination
4409 * This is information is useful for caching modules
4411 * @see WANObjectCache::set()
4412 * @see WANObjectCache::getWithSetCallback()
4414 * @param IDatabase $db1
4415 * @param IDatabase|null $db2 [optional]
4416 * @return array Map of values:
4417 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4418 * - since: oldest UNIX timestamp of any of the DB lag estimates
4419 * - pending: whether any of the DBs have uncommitted changes
4423 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4424 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4425 foreach ( func_get_args() as $db ) {
4426 /** @var IDatabase $db */
4427 $status = $db->getSessionLagStatus();
4428 if ( $status['lag'] === false ) {
4429 $res['lag'] = false;
4430 } elseif ( $res['lag'] !== false ) {
4431 $res['lag'] = max( $res['lag'], $status['lag'] );
4433 $res['since'] = min( $res['since'], $status['since'] );
4434 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4440 public function getLag() {
4441 if ( $this->getLBInfo( 'master' ) ) {
4442 return 0; // this is the master
4443 } elseif ( $this->getLBInfo( 'is static' ) ) {
4444 return 0; // static dataset
4447 return $this->doGetLag();
4450 protected function doGetLag() {
4454 public function maxListLen() {
4458 public function encodeBlob( $b ) {
4462 public function decodeBlob( $b ) {
4463 if ( $b instanceof Blob
) {
4469 public function setSessionOptions( array $options ) {
4472 public function sourceFile(
4474 callable
$lineCallback = null,
4475 callable
$resultCallback = null,
4477 callable
$inputCallback = null
4479 AtEase
::suppressWarnings();
4480 $fp = fopen( $filename, 'r' );
4481 AtEase
::restoreWarnings();
4483 if ( $fp === false ) {
4484 throw new RuntimeException( "Could not open \"{$filename}\"" );
4488 $fname = __METHOD__
. "( $filename )";
4492 $error = $this->sourceStream(
4493 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4494 } catch ( Exception
$e ) {
4504 public function setSchemaVars( $vars ) {
4505 $this->schemaVars
= $vars;
4508 public function sourceStream(
4510 callable
$lineCallback = null,
4511 callable
$resultCallback = null,
4512 $fname = __METHOD__
,
4513 callable
$inputCallback = null
4515 $delimiterReset = new ScopedCallback(
4516 function ( $delimiter ) {
4517 $this->delimiter
= $delimiter;
4519 [ $this->delimiter
]
4523 while ( !feof( $fp ) ) {
4524 if ( $lineCallback ) {
4525 call_user_func( $lineCallback );
4528 $line = trim( fgets( $fp ) );
4530 if ( $line == '' ) {
4534 if ( $line[0] == '-' && $line[1] == '-' ) {
4542 $done = $this->streamStatementEnd( $cmd, $line );
4546 if ( $done ||
feof( $fp ) ) {
4547 $cmd = $this->replaceVars( $cmd );
4549 if ( $inputCallback ) {
4550 $callbackResult = $inputCallback( $cmd );
4552 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4553 $cmd = $callbackResult;
4558 $res = $this->query( $cmd, $fname );
4560 if ( $resultCallback ) {
4561 $resultCallback( $res, $this );
4564 if ( $res === false ) {
4565 $err = $this->lastError();
4567 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4574 ScopedCallback
::consume( $delimiterReset );
4579 * Called by sourceStream() to check if we've reached a statement end
4581 * @param string &$sql SQL assembled so far
4582 * @param string &$newLine New line about to be added to $sql
4583 * @return bool Whether $newLine contains end of the statement
4585 public function streamStatementEnd( &$sql, &$newLine ) {
4586 if ( $this->delimiter
) {
4588 $newLine = preg_replace(
4589 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4590 if ( $newLine != $prev ) {
4599 * Database independent variable replacement. Replaces a set of variables
4600 * in an SQL statement with their contents as given by $this->getSchemaVars().
4602 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4604 * - '{$var}' should be used for text and is passed through the database's
4606 * - `{$var}` should be used for identifiers (e.g. table and database names).
4607 * It is passed through the database's addIdentifierQuotes method which
4608 * can be overridden if the database uses something other than backticks.
4609 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4610 * database's tableName method.
4611 * - / *i* / passes the name that follows through the database's indexName method.
4612 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4613 * its use should be avoided. In 1.24 and older, string encoding was applied.
4615 * @param string $ins SQL statement to replace variables in
4616 * @return string The new SQL statement with variables replaced
4618 protected function replaceVars( $ins ) {
4619 $vars = $this->getSchemaVars();
4620 return preg_replace_callback(
4622 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4623 \'\{\$ (\w+) }\' | # 3. addQuotes
4624 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4625 /\*\$ (\w+) \*/ # 5. leave unencoded
4627 function ( $m ) use ( $vars ) {
4628 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4629 // check for both nonexistent keys *and* the empty string.
4630 if ( isset( $m[1] ) && $m[1] !== '' ) {
4631 if ( $m[1] === 'i' ) {
4632 return $this->indexName( $m[2] );
4634 return $this->tableName( $m[2] );
4636 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4637 return $this->addQuotes( $vars[$m[3]] );
4638 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4639 return $this->addIdentifierQuotes( $vars[$m[4]] );
4640 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4641 return $vars[$m[5]];
4651 * Get schema variables. If none have been set via setSchemaVars(), then
4652 * use some defaults from the current object.
4656 protected function getSchemaVars() {
4657 if ( $this->schemaVars
) {
4658 return $this->schemaVars
;
4660 return $this->getDefaultSchemaVars();
4665 * Get schema variables to use if none have been set via setSchemaVars().
4667 * Override this in derived classes to provide variables for tables.sql
4668 * and SQL patch files.
4672 protected function getDefaultSchemaVars() {
4676 public function lockIsFree( $lockName, $method ) {
4677 // RDBMs methods for checking named locks may or may not count this thread itself.
4678 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4679 // the behavior choosen by the interface for this method.
4680 return !isset( $this->sessionNamedLocks
[$lockName] );
4683 public function lock( $lockName, $method, $timeout = 5 ) {
4684 $this->sessionNamedLocks
[$lockName] = 1;
4689 public function unlock( $lockName, $method ) {
4690 unset( $this->sessionNamedLocks
[$lockName] );
4695 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4696 if ( $this->writesOrCallbacksPending() ) {
4697 // This only flushes transactions to clear snapshots, not to write data
4698 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4699 throw new DBUnexpectedError(
4701 "$fname: Cannot flush pre-lock snapshot; " .
4702 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4706 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4710 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4711 if ( $this->trxLevel() ) {
4712 // There is a good chance an exception was thrown, causing any early return
4713 // from the caller. Let any error handler get a chance to issue rollback().
4714 // If there isn't one, let the error bubble up and trigger server-side rollback.
4715 $this->onTransactionResolution(
4716 function () use ( $lockKey, $fname ) {
4717 $this->unlock( $lockKey, $fname );
4722 $this->unlock( $lockKey, $fname );
4726 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4731 public function namedLocksEnqueue() {
4735 public function tableLocksHaveTransactionScope() {
4739 final public function lockTables( array $read, array $write, $method ) {
4740 if ( $this->writesOrCallbacksPending() ) {
4741 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4744 if ( $this->tableLocksHaveTransactionScope() ) {
4745 $this->startAtomic( $method );
4748 return $this->doLockTables( $read, $write, $method );
4752 * Helper function for lockTables() that handles the actual table locking
4754 * @param array $read Array of tables to lock for read access
4755 * @param array $write Array of tables to lock for write access
4756 * @param string $method Name of caller
4759 protected function doLockTables( array $read, array $write, $method ) {
4763 final public function unlockTables( $method ) {
4764 if ( $this->tableLocksHaveTransactionScope() ) {
4765 $this->endAtomic( $method );
4767 return true; // locks released on COMMIT/ROLLBACK
4770 return $this->doUnlockTables( $method );
4774 * Helper function for unlockTables() that handles the actual table unlocking
4776 * @param string $method Name of caller
4779 protected function doUnlockTables( $method ) {
4785 * @param string $tableName
4786 * @param string $fName
4787 * @return bool|IResultWrapper
4790 public function dropTable( $tableName, $fName = __METHOD__
) {
4791 if ( !$this->tableExists( $tableName, $fName ) ) {
4794 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4796 return $this->query( $sql, $fName );
4799 public function getInfinity() {
4803 public function encodeExpiry( $expiry ) {
4804 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4805 ?
$this->getInfinity()
4806 : $this->timestamp( $expiry );
4809 public function decodeExpiry( $expiry, $format = TS_MW
) {
4810 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4814 return ConvertibleTimestamp
::convert( $format, $expiry );
4817 public function setBigSelects( $value = true ) {
4821 public function isReadOnly() {
4822 return ( $this->getReadOnlyReason() !== false );
4826 * @return string|bool Reason this DB is read-only or false if it is not
4828 protected function getReadOnlyReason() {
4829 $reason = $this->getLBInfo( 'readOnlyReason' );
4830 if ( is_string( $reason ) ) {
4832 } elseif ( $this->getLBInfo( 'replica' ) ) {
4833 return "Server is configured in the role of a read-only replica database.";
4839 public function setTableAliases( array $aliases ) {
4840 $this->tableAliases
= $aliases;
4843 public function setIndexAliases( array $aliases ) {
4844 $this->indexAliases
= $aliases;
4852 protected function hasFlags( $field, $flags ) {
4853 return ( ( $field & $flags ) === $flags );
4857 * Get the underlying binding connection handle
4859 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4860 * This catches broken callers than catch and ignore disconnection exceptions.
4861 * Unlike checking isOpen(), this is safe to call inside of open().
4864 * @throws DBUnexpectedError
4867 protected function getBindingHandle() {
4868 if ( !$this->conn
) {
4869 throw new DBUnexpectedError(
4871 'DB connection was already closed or the connection dropped'
4878 public function __toString() {
4879 // spl_object_id is PHP >= 7.2
4880 $id = function_exists( 'spl_object_id' )
4881 ?
spl_object_id( $this )
4882 : spl_object_hash( $this );
4884 $description = $this->getType() . ' object #' . $id;
4885 if ( is_resource( $this->conn
) ) {
4886 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4887 } elseif ( is_object( $this->conn
) ) {
4888 // spl_object_id is PHP >= 7.2
4889 $handleId = function_exists( 'spl_object_id' )
4890 ?
spl_object_id( $this->conn
)
4891 : spl_object_hash( $this->conn
);
4892 $description .= " (handle id #$handleId)";
4895 return $description;
4899 * Make sure that copies do not share the same client binding handle
4900 * @throws DBConnectionError
4902 public function __clone() {
4903 $this->connLogger
->warning(
4904 "Cloning " . static::class . " is not recommended; forking connection",
4905 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4908 if ( $this->isOpen() ) {
4909 // Open a new connection resource without messing with the old one
4911 $this->trxEndCallbacks
= []; // don't copy
4912 $this->trxSectionCancelCallbacks
= []; // don't copy
4913 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4918 $this->currentDomain
->getDatabase(),
4919 $this->currentDomain
->getSchema(),
4920 $this->tablePrefix()
4922 $this->lastPing
= microtime( true );
4927 * Called by serialize. Throw an exception when DB connection is serialized.
4928 * This causes problems on some database engines because the connection is
4929 * not restored on unserialize.
4931 public function __sleep() {
4932 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4933 'the connection is not restored on wakeup' );
4937 * Run a few simple sanity checks and close dangling connections
4939 public function __destruct() {
4940 if ( $this->trxLevel() && $this->trxDoneWrites
) {
4941 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4944 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4945 if ( $danglingWriters ) {
4946 $fnames = implode( ', ', $danglingWriters );
4947 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4950 if ( $this->conn
) {
4951 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4952 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4953 AtEase
::suppressWarnings();
4954 $this->closeConnection();
4955 AtEase
::restoreWarnings();
4962 * @deprecated since 1.28
4964 class_alias( Database
::class, 'DatabaseBase' );
4967 * @deprecated since 1.29
4969 class_alias( Database
::class, 'Database' );