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 Bitfield 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;
221 * @note exceptions for missing libraries/drivers should be thrown in initConnection()
222 * @param array $params Parameters passed from Database::factory()
224 protected function __construct( array $params ) {
225 foreach ( [ 'host', 'user', 'password', 'dbname', 'schema', 'tablePrefix' ] as $name ) {
226 $this->connectionParams
[$name] = $params[$name];
229 $this->cliMode
= $params['cliMode'];
230 // Agent name is added to SQL queries in a comment, so make sure it can't break out
231 $this->agent
= str_replace( '/', '-', $params['agent'] );
233 $this->flags
= $params['flags'];
234 if ( $this->flags
& self
::DBO_DEFAULT
) {
235 if ( $this->cliMode
) {
236 $this->flags
&= ~self
::DBO_TRX
;
238 $this->flags |
= self
::DBO_TRX
;
241 // Disregard deprecated DBO_IGNORE flag (T189999)
242 $this->flags
&= ~self
::DBO_IGNORE
;
244 $this->connectionVariables
= $params['variables'];
246 $this->srvCache
= $params['srvCache'] ??
new HashBagOStuff();
248 $this->profiler
= is_callable( $params['profiler'] ) ?
$params['profiler'] : null;
249 $this->trxProfiler
= $params['trxProfiler'];
250 $this->connLogger
= $params['connLogger'];
251 $this->queryLogger
= $params['queryLogger'];
252 $this->errorLogger
= $params['errorLogger'];
253 $this->deprecationLogger
= $params['deprecationLogger'];
255 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
256 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
259 // Set initial dummy domain until open() sets the final DB/prefix
260 $this->currentDomain
= new DatabaseDomain(
261 $params['dbname'] != '' ?
$params['dbname'] : null,
262 $params['schema'] != '' ?
$params['schema'] : null,
263 $params['tablePrefix']
268 * Initialize the connection to the database over the wire (or to local files)
270 * @throws LogicException
271 * @throws InvalidArgumentException
272 * @throws DBConnectionError
275 final public function initConnection() {
276 if ( $this->isOpen() ) {
277 throw new LogicException( __METHOD__
. ': already connected' );
279 // Establish the connection
280 $this->doInitConnection();
284 * Actually connect to the database over the wire (or to local files)
286 * @throws InvalidArgumentException
287 * @throws DBConnectionError
290 protected function doInitConnection() {
291 if ( strlen( $this->connectionParams
['user'] ) ) {
293 $this->connectionParams
['host'],
294 $this->connectionParams
['user'],
295 $this->connectionParams
['password'],
296 $this->connectionParams
['dbname'],
297 $this->connectionParams
['schema'],
298 $this->connectionParams
['tablePrefix']
301 throw new InvalidArgumentException( "No database user provided" );
306 * Open a new connection to the database (closing any existing one)
308 * @param string|null $server Database server host
309 * @param string|null $user Database user name
310 * @param string|null $password Database user password
311 * @param string|null $dbName Database name
312 * @param string|null $schema Database schema name
313 * @param string $tablePrefix Table prefix
314 * @throws DBConnectionError
316 abstract protected function open( $server, $user, $password, $dbName, $schema, $tablePrefix );
319 * Construct a Database subclass instance given a database type and parameters
321 * This also connects to the database immediately upon object construction
323 * @param string $type A possible DB type (sqlite, mysql, postgres,...)
324 * @param array $params Parameter map with keys:
325 * - host : The hostname of the DB server
326 * - user : The name of the database user the client operates under
327 * - password : The password for the database user
328 * - dbname : The name of the database to use where queries do not specify one.
329 * The database must exist or an error might be thrown. Setting this to the empty string
330 * will avoid any such errors and make the handle have no implicit database scope. This is
331 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
332 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
333 * in which user names and such are defined, e.g. users are database-specific in Postgres.
334 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
335 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
336 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
337 * recognized in queries. This can be used in place of schemas for handle site farms.
338 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
339 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
340 * flag in place UNLESS this this database simply acts as a key/value store.
341 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
342 * 'mysqli' driver; the old one 'mysql' has been removed.
343 * - variables: Optional map of session variables to set after connecting. This can be
344 * used to adjust lock timeouts or encoding modes and the like.
345 * - connLogger: Optional PSR-3 logger interface instance.
346 * - queryLogger: Optional PSR-3 logger interface instance.
347 * - profiler : Optional callback that takes a section name argument and returns
348 * a ScopedCallback instance that ends the profile section in its destructor.
349 * These will be called in query(), using a simplified version of the SQL that
350 * also includes the agent as a SQL comment.
351 * - trxProfiler: Optional TransactionProfiler instance.
352 * - errorLogger: Optional callback that takes an Exception and logs it.
353 * - deprecationLogger: Optional callback that takes a string and logs it.
354 * - cliMode: Whether to consider the execution context that of a CLI script.
355 * - agent: Optional name used to identify the end-user in query profiling/logging.
356 * - srvCache: Optional BagOStuff instance to an APC-style cache.
357 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
358 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
359 * @return Database|null If the database driver or extension cannot be found
360 * @throws InvalidArgumentException If the database driver or extension cannot be found
363 final public static function factory( $type, $params = [], $connect = self
::NEW_CONNECTED
) {
364 $class = self
::getClass( $type, $params['driver'] ??
null );
366 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
376 'cliMode' => ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' ),
377 'agent' => basename( $_SERVER['SCRIPT_NAME'] ) . '@' . gethostname()
380 $normalizedParams = [
382 'host' => strlen( $params['host'] ) ?
$params['host'] : null,
383 'user' => strlen( $params['user'] ) ?
$params['user'] : null,
384 'password' => is_string( $params['password'] ) ?
$params['password'] : null,
385 'dbname' => strlen( $params['dbname'] ) ?
$params['dbname'] : null,
386 'schema' => strlen( $params['schema'] ) ?
$params['schema'] : null,
387 'tablePrefix' => (string)$params['tablePrefix'],
388 'flags' => (int)$params['flags'],
389 'variables' => $params['variables'],
390 'cliMode' => (bool)$params['cliMode'],
391 'agent' => (string)$params['agent'],
392 // Objects and callbacks
393 'profiler' => $params['profiler'] ??
null,
394 'trxProfiler' => $params['trxProfiler'] ??
new TransactionProfiler(),
395 'connLogger' => $params['connLogger'] ??
new NullLogger(),
396 'queryLogger' => $params['queryLogger'] ??
new NullLogger(),
397 'errorLogger' => $params['errorLogger'] ??
function ( Exception
$e ) {
398 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
400 'deprecationLogger' => $params['deprecationLogger'] ??
function ( $msg ) {
401 trigger_error( $msg, E_USER_DEPRECATED
);
405 /** @var Database $conn */
406 $conn = new $class( $normalizedParams );
407 if ( $connect === self
::NEW_CONNECTED
) {
408 $conn->initConnection();
418 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
419 * @param string|null $driver Optional name of a specific DB client driver
420 * @return array Map of (Database::ATTR_* constant => value) for all such constants
421 * @throws InvalidArgumentException
424 final public static function attributesFromType( $dbType, $driver = null ) {
426 self
::ATTR_DB_LEVEL_LOCKING
=> false,
427 self
::ATTR_SCHEMAS_AS_TABLE_GROUPS
=> false
430 $class = self
::getClass( $dbType, $driver );
432 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
436 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
437 * @param string|null $driver Optional name of a specific DB client driver
438 * @return string Database subclass name to use
439 * @throws InvalidArgumentException
441 private static function getClass( $dbType, $driver = null ) {
442 // For database types with built-in support, the below maps type to IDatabase
443 // implementations. For types with multipe driver implementations (PHP extensions),
444 // an array can be used, keyed by extension name. In case of an array, the
445 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
446 // we auto-detect the first available driver. For types without built-in support,
447 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
448 static $builtinTypes = [
449 'mssql' => DatabaseMssql
::class,
450 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
451 'sqlite' => DatabaseSqlite
::class,
452 'postgres' => DatabasePostgres
::class,
455 $dbType = strtolower( $dbType );
458 if ( isset( $builtinTypes[$dbType] ) ) {
459 $possibleDrivers = $builtinTypes[$dbType];
460 if ( is_string( $possibleDrivers ) ) {
461 $class = $possibleDrivers;
462 } elseif ( (string)$driver !== '' ) {
463 if ( !isset( $possibleDrivers[$driver] ) ) {
464 throw new InvalidArgumentException( __METHOD__
.
465 " type '$dbType' does not support driver '{$driver}'" );
468 $class = $possibleDrivers[$driver];
470 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
471 if ( extension_loaded( $posDriver ) ) {
472 $class = $possibleClass;
478 $class = 'Database' . ucfirst( $dbType );
481 if ( $class === false ) {
482 throw new InvalidArgumentException( __METHOD__
.
483 " no viable database extension found for type '$dbType'" );
490 * @return array Map of (Database::ATTR_* constant => value
493 protected static function getAttributes() {
498 * Set the PSR-3 logger interface to use for query logging. (The logger
499 * interfaces for connection logging and error logging can be set with the
502 * @param LoggerInterface $logger
504 public function setLogger( LoggerInterface
$logger ) {
505 $this->queryLogger
= $logger;
508 public function getServerInfo() {
509 return $this->getServerVersion();
512 public function bufferResults( $buffer = null ) {
513 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
514 if ( $buffer !== null ) {
516 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
517 : $this->setFlag( self
::DBO_NOBUFFER
);
523 final public function trxLevel() {
524 return ( $this->trxShortId
!= '' ) ?
1 : 0;
527 public function trxTimestamp() {
528 return $this->trxLevel() ?
$this->trxTimestamp
: null;
532 * @return int One of the STATUS_TRX_* class constants
535 public function trxStatus() {
536 return $this->trxStatus
;
539 public function tablePrefix( $prefix = null ) {
540 $old = $this->currentDomain
->getTablePrefix();
541 if ( $prefix !== null ) {
542 $this->currentDomain
= new DatabaseDomain(
543 $this->currentDomain
->getDatabase(),
544 $this->currentDomain
->getSchema(),
552 public function dbSchema( $schema = null ) {
553 if ( strlen( $schema ) && $this->getDBname() === null ) {
554 throw new DBUnexpectedError( $this, "Cannot set schema to '$schema'; no database set" );
557 $old = $this->currentDomain
->getSchema();
558 if ( $schema !== null ) {
559 $this->currentDomain
= new DatabaseDomain(
560 $this->currentDomain
->getDatabase(),
561 // DatabaseDomain uses null for unspecified schemas
562 strlen( $schema ) ?
$schema : null,
563 $this->currentDomain
->getTablePrefix()
571 * @return string Schema to use to qualify relations in queries
573 protected function relationSchemaQualifier() {
574 return $this->dbSchema();
577 public function getLBInfo( $name = null ) {
578 if ( is_null( $name ) ) {
579 return $this->lbInfo
;
582 if ( array_key_exists( $name, $this->lbInfo
) ) {
583 return $this->lbInfo
[$name];
589 public function setLBInfo( $nameOrArray, $value = null ) {
590 if ( is_array( $nameOrArray ) ) {
591 $this->lbInfo
= $nameOrArray;
592 } elseif ( is_string( $nameOrArray ) ) {
593 if ( $value !== null ) {
594 $this->lbInfo
[$nameOrArray] = $value;
596 unset( $this->lbInfo
[$nameOrArray] );
599 throw new InvalidArgumentException( "Got non-string key" );
603 public function setLazyMasterHandle( IDatabase
$conn ) {
604 $this->lazyMasterHandle
= $conn;
608 * @return IDatabase|null
609 * @see setLazyMasterHandle()
612 protected function getLazyMasterHandle() {
613 return $this->lazyMasterHandle
;
616 public function implicitOrderby() {
620 public function lastQuery() {
621 return $this->lastQuery
;
624 public function lastDoneWrites() {
625 return $this->lastWriteTime ?
: false;
628 public function writesPending() {
629 return $this->trxLevel() && $this->trxDoneWrites
;
632 public function writesOrCallbacksPending() {
633 return $this->trxLevel() && (
634 $this->trxDoneWrites ||
635 $this->trxIdleCallbacks ||
636 $this->trxPreCommitCallbacks ||
637 $this->trxEndCallbacks ||
638 $this->trxSectionCancelCallbacks
642 public function preCommitCallbacksPending() {
643 return $this->trxLevel() && $this->trxPreCommitCallbacks
;
647 * @return string|null
649 final protected function getTransactionRoundId() {
650 // If transaction round participation is enabled, see if one is active
651 if ( $this->getFlag( self
::DBO_TRX
) ) {
652 $id = $this->getLBInfo( 'trxRoundId' );
654 return is_string( $id ) ?
$id : null;
660 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
661 if ( !$this->trxLevel() ) {
663 } elseif ( !$this->trxDoneWrites
) {
668 case self
::ESTIMATE_DB_APPLY
:
669 return $this->pingAndCalculateLastTrxApplyTime();
670 default: // everything
671 return $this->trxWriteDuration
;
676 * @return float Time to apply writes to replicas based on trxWrite* fields
678 private function pingAndCalculateLastTrxApplyTime() {
681 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
682 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
683 // For omitted queries, make them count as something at least
684 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
685 $applyTime +
= self
::$TINY_WRITE_SEC * $omitted;
690 public function pendingWriteCallers() {
691 return $this->trxLevel() ?
$this->trxWriteCallers
: [];
694 public function pendingWriteRowsAffected() {
695 return $this->trxWriteAffectedRows
;
699 * List the methods that have write queries or callbacks for the current transaction
701 * This method should not be used outside of Database/LoadBalancer
706 public function pendingWriteAndCallbackCallers() {
707 $fnames = $this->pendingWriteCallers();
709 $this->trxIdleCallbacks
,
710 $this->trxPreCommitCallbacks
,
711 $this->trxEndCallbacks
,
712 $this->trxSectionCancelCallbacks
714 foreach ( $callbacks as $callback ) {
715 $fnames[] = $callback[1];
725 private function flatAtomicSectionList() {
726 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
727 return $accum === null ?
$v[0] : "$accum, " . $v[0];
731 public function isOpen() {
732 return (bool)$this->conn
;
735 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
736 if ( ( $flag & self
::DBO_IGNORE
) ) {
737 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed" );
740 if ( $remember === self
::REMEMBER_PRIOR
) {
741 array_push( $this->priorFlags
, $this->flags
);
743 $this->flags |
= $flag;
746 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
747 if ( ( $flag & self
::DBO_IGNORE
) ) {
748 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed" );
751 if ( $remember === self
::REMEMBER_PRIOR
) {
752 array_push( $this->priorFlags
, $this->flags
);
754 $this->flags
&= ~
$flag;
757 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
758 if ( !$this->priorFlags
) {
762 if ( $state === self
::RESTORE_INITIAL
) {
763 $this->flags
= reset( $this->priorFlags
);
764 $this->priorFlags
= [];
766 $this->flags
= array_pop( $this->priorFlags
);
770 public function getFlag( $flag ) {
771 return (bool)( $this->flags
& $flag );
774 public function getDomainID() {
775 return $this->currentDomain
->getId();
779 * Get information about an index into an object
780 * @param string $table Table name
781 * @param string $index Index name
782 * @param string $fname Calling function name
783 * @return mixed Database-specific index description class or false if the index does not exist
785 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
788 * Wrapper for addslashes()
790 * @param string $s String to be slashed.
791 * @return string Slashed string.
793 abstract function strencode( $s );
796 * Set a custom error handler for logging errors during database connection
798 protected function installErrorHandler() {
799 $this->lastPhpError
= false;
800 $this->htmlErrors
= ini_set( 'html_errors', '0' );
801 set_error_handler( [ $this, 'connectionErrorLogger' ] );
805 * Restore the previous error handler and return the last PHP error for this DB
807 * @return bool|string
809 protected function restoreErrorHandler() {
810 restore_error_handler();
811 if ( $this->htmlErrors
!== false ) {
812 ini_set( 'html_errors', $this->htmlErrors
);
815 return $this->getLastPHPError();
819 * @return string|bool Last PHP error for this DB (typically connection errors)
821 protected function getLastPHPError() {
822 if ( $this->lastPhpError
) {
823 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->lastPhpError
);
824 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
833 * Error handler for logging errors during database connection
834 * This method should not be used outside of Database classes
837 * @param string $errstr
839 public function connectionErrorLogger( $errno, $errstr ) {
840 $this->lastPhpError
= $errstr;
844 * Create a log context to pass to PSR-3 logger functions.
846 * @param array $extras Additional data to add to context
849 protected function getLogContext( array $extras = [] ) {
852 'db_server' => $this->server
,
853 'db_name' => $this->getDBname(),
854 'db_user' => $this->user
,
860 final public function close() {
861 $exception = null; // error to throw after disconnecting
863 $wasOpen = (bool)$this->conn
;
864 // This should mostly do nothing if the connection is already closed
866 // Roll back any dangling transaction first
867 if ( $this->trxLevel() ) {
868 if ( $this->trxAtomicLevels
) {
869 // Cannot let incomplete atomic sections be committed
870 $levels = $this->flatAtomicSectionList();
871 $exception = new DBUnexpectedError(
873 __METHOD__
. ": atomic sections $levels are still open"
875 } elseif ( $this->trxAutomatic
) {
876 // Only the connection manager can commit non-empty DBO_TRX transactions
877 // (empty ones we can silently roll back)
878 if ( $this->writesOrCallbacksPending() ) {
879 $exception = new DBUnexpectedError(
882 ": mass commit/rollback of peer transaction required (DBO_TRX set)"
886 // Manual transactions should have been committed or rolled
887 // back, even if empty.
888 $exception = new DBUnexpectedError(
890 __METHOD__
. ": transaction is still open (from {$this->trxFname})"
894 if ( $this->trxEndCallbacksSuppressed
) {
895 $exception = $exception ?
: new DBUnexpectedError(
897 __METHOD__
. ': callbacks are suppressed; cannot properly commit'
901 // Rollback the changes and run any callbacks as needed
902 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
905 // Close the actual connection in the binding handle
906 $closed = $this->closeConnection();
908 $closed = true; // already closed; nothing to do
913 // Throw any unexpected errors after having disconnected
914 if ( $exception instanceof Exception
) {
918 // Note that various subclasses call close() at the start of open(), which itself is
919 // called by replaceLostConnection(). In that case, just because onTransactionResolution()
920 // callbacks are pending does not mean that an exception should be thrown. Rather, they
921 // will be executed after the reconnection step.
923 // Sanity check that no callbacks are dangling
924 $fnames = $this->pendingWriteAndCallbackCallers();
926 throw new RuntimeException(
927 "Transaction callbacks are still pending: " . implode( ', ', $fnames )
936 * Make sure there is an open connection handle (alive or not) as a sanity check
938 * This guards against fatal errors to the binding handle not being defined
939 * in cases where open() was never called or close() was already called
941 * @throws DBUnexpectedError
943 final protected function assertHasConnectionHandle() {
944 if ( !$this->isOpen() ) {
945 throw new DBUnexpectedError( $this, "DB connection was already closed" );
950 * Make sure that this server is not marked as a replica nor read-only as a sanity check
952 * @throws DBReadOnlyRoleError
953 * @throws DBReadOnlyError
955 protected function assertIsWritableMaster() {
956 if ( $this->getLBInfo( 'replica' ) === true ) {
957 throw new DBReadOnlyRoleError(
959 'Write operations are not allowed on replica database connections'
962 $reason = $this->getReadOnlyReason();
963 if ( $reason !== false ) {
964 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
969 * Closes underlying database connection
971 * @return bool Whether connection was closed successfully
973 abstract protected function closeConnection();
976 * Run a query and return a DBMS-dependent wrapper or boolean
978 * This is meant to handle the basic command of actually sending a query to the
979 * server via the driver. No implicit transaction, reconnection, nor retry logic
980 * should happen here. The higher level query() method is designed to handle those
981 * sorts of concerns. This method should not trigger such higher level methods.
983 * The lastError() and lastErrno() methods should meaningfully reflect what error,
984 * if any, occured during the last call to this method. Methods like executeQuery(),
985 * query(), select(), insert(), update(), delete(), and upsert() implement their calls
986 * to doQuery() such that an immediately subsequent call to lastError()/lastErrno()
987 * meaningfully reflects any error that occured during that public query method call.
989 * For SELECT queries, this returns either:
990 * - a) A driver-specific value/resource, only on success. This can be iterated
991 * over by calling fetchObject()/fetchRow() until there are no more rows.
992 * Alternatively, the result can be passed to resultObject() to obtain an
993 * IResultWrapper instance which can then be iterated over via "foreach".
994 * - b) False, on any query failure
996 * For non-SELECT queries, this returns either:
997 * - a) A driver-specific value/resource, only on success
998 * - b) True, only on success (e.g. no meaningful result other than "OK")
999 * - c) False, on any query failure
1001 * @param string $sql SQL query
1002 * @return mixed|bool An object, resource, or true on success; false on failure
1004 abstract protected function doQuery( $sql );
1007 * Determine whether a query writes to the DB. When in doubt, this returns true.
1011 * - Subsequent web requests should not need to wait for replication from
1012 * the master position seen by this web request, unless this request made
1013 * changes to the master. This is handled by ChronologyProtector by checking
1014 * doneWrites() at the end of the request. doneWrites() returns true if any
1015 * query set lastWriteTime; which query() does based on isWriteQuery().
1017 * - Reject write queries to replica DBs, in query().
1019 * @param string $sql
1022 protected function isWriteQuery( $sql ) {
1023 // BEGIN and COMMIT queries are considered read queries here.
1024 // Database backends and drivers (MySQL, MariaDB, php-mysqli) generally
1025 // treat these as write queries, in that their results have "affected rows"
1026 // as meta data as from writes, instead of "num rows" as from reads.
1027 // But, we treat them as read queries because when reading data (from
1028 // either replica or master) we use transactions to enable repeatable-read
1029 // snapshots, which ensures we get consistent results from the same snapshot
1030 // for all queries within a request. Use cases:
1031 // - Treating these as writes would trigger ChronologyProtector (see method doc).
1032 // - We use this method to reject writes to replicas, but we need to allow
1033 // use of transactions on replicas for read snapshots. This is fine given
1034 // that transactions by themselves don't make changes, only actual writes
1035 // within the transaction matter, which we still detect.
1037 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SAVEPOINT|RELEASE|SET|SHOW|EXPLAIN|USE|\(SELECT)\b/i',
1043 * @param string $sql
1044 * @return string|null
1046 protected function getQueryVerb( $sql ) {
1047 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1051 * Determine whether a SQL statement is sensitive to isolation level.
1053 * A SQL statement is considered transactable if its result could vary
1054 * depending on the transaction isolation level. Operational commands
1055 * such as 'SET' and 'SHOW' are not considered to be transactable.
1057 * Main purpose: Used by query() to decide whether to begin a transaction
1058 * before the current query (in DBO_TRX mode, on by default).
1060 * @param string $sql
1063 protected function isTransactableQuery( $sql ) {
1065 $this->getQueryVerb( $sql ),
1066 [ 'BEGIN', 'ROLLBACK', 'COMMIT', 'SET', 'SHOW', 'CREATE', 'ALTER', 'USE', 'SHOW' ],
1072 * @param string $sql A SQL query
1073 * @param bool $pseudoPermanent Treat any table from CREATE TEMPORARY as pseudo-permanent
1074 * @return array A n-tuple of:
1075 * - int|null: A self::TEMP_* constant for temp table operations or null otherwise
1076 * - string|null: The name of the new temporary table $sql creates, or null
1077 * - string|null: The name of the temporary table that $sql drops, or null
1079 protected function getTempWrites( $sql, $pseudoPermanent ) {
1080 static $qt = '[`"\']?(\w+)[`"\']?'; // quoted table
1083 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?' . $qt . '/i',
1087 $type = $pseudoPermanent ? self
::$TEMP_PSEUDO_PERMANENT : self
::$TEMP_NORMAL;
1089 return [ $type, $matches[1], null ];
1090 } elseif ( preg_match(
1091 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1095 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, $matches[1] ];
1096 } elseif ( preg_match(
1097 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?' . $qt . '/i',
1101 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1102 } elseif ( preg_match(
1103 '/^(?:(?:INSERT|REPLACE)\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+' . $qt . '/i',
1107 return [ $this->sessionTempTables
[$matches[1]] ??
null, null, null ];
1110 return [ null, null, null ];
1114 * @param IResultWrapper|bool $ret
1115 * @param int|null $tmpType TEMP_NORMAL or TEMP_PSEUDO_PERMANENT
1116 * @param string|null $tmpNew Name of created temp table
1117 * @param string|null $tmpDel Name of dropped temp table
1119 protected function registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel ) {
1120 if ( $ret !== false ) {
1121 if ( $tmpNew !== null ) {
1122 $this->sessionTempTables
[$tmpNew] = $tmpType;
1124 if ( $tmpDel !== null ) {
1125 unset( $this->sessionTempTables
[$tmpDel] );
1130 public function query( $sql, $fname = __METHOD__
, $flags = 0 ) {
1131 $flags = (int)$flags; // b/c; this field used to be a bool
1132 // Sanity check that the SQL query is appropriate in the current context and is
1133 // allowed for an outside caller (e.g. does not break transaction/session tracking).
1134 $this->assertQueryIsCurrentlyAllowed( $sql, $fname );
1136 // Send the query to the server and fetch any corresponding errors
1137 list( $ret, $err, $errno, $unignorable ) = $this->executeQuery( $sql, $fname, $flags );
1138 if ( $ret === false ) {
1139 $ignoreErrors = $this->hasFlags( $flags, self
::QUERY_SILENCE_ERRORS
);
1140 // Throw an error unless both the ignore flag was set and a rollback is not needed
1141 $this->reportQueryError( $err, $errno, $sql, $fname, $ignoreErrors && !$unignorable );
1144 return $this->resultObject( $ret );
1148 * Execute a query, retrying it if there is a recoverable connection loss
1150 * This is similar to query() except:
1151 * - It does not prevent all non-ROLLBACK queries if there is a corrupted transaction
1152 * - It does not disallow raw queries that are supposed to use dedicated IDatabase methods
1153 * - It does not throw exceptions for common error cases
1155 * This is meant for internal use with Database subclasses.
1157 * @param string $sql Original SQL query
1158 * @param string $fname Name of the calling function
1159 * @param int $flags Bitfield of class QUERY_* constants
1160 * @return array An n-tuple of:
1161 * - mixed|bool: An object, resource, or true on success; false on failure
1162 * - string: The result of calling lastError()
1163 * - int: The result of calling lastErrno()
1164 * - bool: Whether a rollback is needed to allow future non-rollback queries
1165 * @throws DBUnexpectedError
1167 final protected function executeQuery( $sql, $fname, $flags ) {
1168 $this->assertHasConnectionHandle();
1170 $priorTransaction = $this->trxLevel();
1172 if ( $this->isWriteQuery( $sql ) ) {
1173 // In theory, non-persistent writes are allowed in read-only mode, but due to things
1174 // like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1175 $this->assertIsWritableMaster();
1176 // Do not treat temporary table writes as "meaningful writes" since they are only
1177 // visible to one session and are not permanent. Profile them as reads. Integration
1178 // tests can override this behavior via $flags.
1179 $pseudoPermanent = $this->hasFlags( $flags, self
::QUERY_PSEUDO_PERMANENT
);
1180 list( $tmpType, $tmpNew, $tmpDel ) = $this->getTempWrites( $sql, $pseudoPermanent );
1181 $isPermWrite = ( $tmpType !== self
::$TEMP_NORMAL );
1182 // DBConnRef uses QUERY_REPLICA_ROLE to enforce the replica role for raw SQL queries
1183 if ( $isPermWrite && $this->hasFlags( $flags, self
::QUERY_REPLICA_ROLE
) ) {
1184 throw new DBReadOnlyRoleError( $this, "Cannot write; target role is DB_REPLICA" );
1187 // No permanent writes in this query
1188 $isPermWrite = false;
1189 // No temporary tables written to either
1190 list( $tmpType, $tmpNew, $tmpDel ) = [ null, null, null ];
1193 // Add trace comment to the begin of the sql string, right after the operator.
1194 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1195 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1197 // Send the query to the server and fetch any corresponding errors.
1198 // This also doubles as a "ping" to see if the connection was dropped.
1199 list( $ret, $err, $errno, $recoverableSR, $recoverableCL, $reconnected ) =
1200 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1202 // Check if the query failed due to a recoverable connection loss
1203 $allowRetry = !$this->hasFlags( $flags, self
::QUERY_NO_RETRY
);
1204 if ( $ret === false && $recoverableCL && $reconnected && $allowRetry ) {
1205 // Silently resend the query to the server since it is safe and possible
1206 list( $ret, $err, $errno, $recoverableSR, $recoverableCL ) =
1207 $this->executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags );
1210 // Register creation and dropping of temporary tables
1211 $this->registerTempWrites( $ret, $tmpType, $tmpNew, $tmpDel );
1213 $corruptedTrx = false;
1215 if ( $ret === false ) {
1216 if ( $priorTransaction ) {
1217 if ( $recoverableSR ) {
1218 # We're ignoring an error that caused just the current query to be aborted.
1219 # But log the cause so we can log a deprecation notice if a caller actually
1221 $this->trxStatusIgnoredCause
= [ $err, $errno, $fname ];
1222 } elseif ( !$recoverableCL ) {
1223 # Either the query was aborted or all queries after BEGIN where aborted.
1224 # In the first case, the only options going forward are (a) ROLLBACK, or
1225 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1226 # option is ROLLBACK, since the snapshots would have been released.
1227 $corruptedTrx = true; // cannot recover
1228 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1229 $this->trxStatusCause
=
1230 $this->getQueryExceptionAndLog( $err, $errno, $sql, $fname );
1231 $this->trxStatusIgnoredCause
= null;
1236 return [ $ret, $err, $errno, $corruptedTrx ];
1240 * Wrapper for doQuery() that handles DBO_TRX, profiling, logging, affected row count
1241 * tracking, and reconnects (without retry) on query failure due to connection loss
1243 * @param string $sql Original SQL query
1244 * @param string $commentedSql SQL query with debugging/trace comment
1245 * @param bool $isPermWrite Whether the query is a (non-temporary table) write
1246 * @param string $fname Name of the calling function
1247 * @param int $flags Bitfield of class QUERY_* constants
1248 * @return array An n-tuple of:
1249 * - mixed|bool: An object, resource, or true on success; false on failure
1250 * - string: The result of calling lastError()
1251 * - int: The result of calling lastErrno()
1252 * - bool: Whether a statement rollback error occured
1253 * - bool: Whether a disconnect *both* happened *and* was recoverable
1254 * - bool: Whether a reconnection attempt was *both* made *and* succeeded
1255 * @throws DBUnexpectedError
1257 private function executeQueryAttempt( $sql, $commentedSql, $isPermWrite, $fname, $flags ) {
1258 $priorWritesPending = $this->writesOrCallbacksPending();
1260 if ( ( $flags & self
::QUERY_IGNORE_DBO_TRX
) == 0 ) {
1261 $this->beginIfImplied( $sql, $fname );
1264 // Keep track of whether the transaction has write queries pending
1265 if ( $isPermWrite ) {
1266 $this->lastWriteTime
= microtime( true );
1267 if ( $this->trxLevel() && !$this->trxDoneWrites
) {
1268 $this->trxDoneWrites
= true;
1269 $this->trxProfiler
->transactionWritingIn(
1270 $this->server
, $this->getDomainID(), $this->trxShortId
);
1274 $prefix = !is_null( $this->getLBInfo( 'master' ) ) ?
'query-m: ' : 'query: ';
1275 $generalizedSql = new GeneralizedSql( $sql, $this->trxShortId
, $prefix );
1277 $startTime = microtime( true );
1278 $ps = $this->profiler
1279 ?
( $this->profiler
)( $generalizedSql->stringify() )
1281 $this->affectedRowCount
= null;
1282 $this->lastQuery
= $sql;
1283 $ret = $this->doQuery( $commentedSql );
1284 $lastError = $this->lastError();
1285 $lastErrno = $this->lastErrno();
1287 $this->affectedRowCount
= $this->affectedRows();
1288 unset( $ps ); // profile out (if set)
1289 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1291 $recoverableSR = false; // recoverable statement rollback?
1292 $recoverableCL = false; // recoverable connection loss?
1293 $reconnected = false; // reconnection both attempted and succeeded?
1295 if ( $ret !== false ) {
1296 $this->lastPing
= $startTime;
1297 if ( $isPermWrite && $this->trxLevel() ) {
1298 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1299 $this->trxWriteCallers
[] = $fname;
1301 } elseif ( $this->wasConnectionError( $lastErrno ) ) {
1302 # Check if no meaningful session state was lost
1303 $recoverableCL = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1304 # Update session state tracking and try to restore the connection
1305 $reconnected = $this->replaceLostConnection( __METHOD__
);
1307 # Check if only the last query was rolled back
1308 $recoverableSR = $this->wasKnownStatementRollbackError();
1311 if ( $sql === self
::$PING_QUERY ) {
1312 $this->lastRoundTripEstimate
= $queryRuntime;
1315 $this->trxProfiler
->recordQueryCompletion(
1319 $isPermWrite ?
$this->affectedRows() : $this->numRows( $ret )
1322 // Avoid the overhead of logging calls unless debug mode is enabled
1323 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1324 $this->queryLogger
->debug(
1325 "{method} [{runtime}s]: $sql",
1328 'db_host' => $this->getServer(),
1329 'domain' => $this->getDomainID(),
1330 'runtime' => round( $queryRuntime, 3 )
1335 return [ $ret, $lastError, $lastErrno, $recoverableSR, $recoverableCL, $reconnected ];
1339 * Start an implicit transaction if DBO_TRX is enabled and no transaction is active
1341 * @param string $sql
1342 * @param string $fname
1344 private function beginIfImplied( $sql, $fname ) {
1346 !$this->trxLevel() &&
1347 $this->getFlag( self
::DBO_TRX
) &&
1348 $this->isTransactableQuery( $sql )
1350 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1351 $this->trxAutomatic
= true;
1356 * Update the estimated run-time of a query, not counting large row lock times
1358 * LoadBalancer can be set to rollback transactions that will create huge replication
1359 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1360 * queries, like inserting a row can take a long time due to row locking. This method
1361 * uses some simple heuristics to discount those cases.
1363 * @param string $sql A SQL write query
1364 * @param float $runtime Total runtime, including RTT
1365 * @param int $affected Affected row count
1367 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1368 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1369 $indicativeOfReplicaRuntime = true;
1370 if ( $runtime > self
::$SLOW_WRITE_SEC ) {
1371 $verb = $this->getQueryVerb( $sql );
1372 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1373 if ( $verb === 'INSERT' ) {
1374 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS;
1375 } elseif ( $verb === 'REPLACE' ) {
1376 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::$SMALL_WRITE_ROWS / 2;
1380 $this->trxWriteDuration +
= $runtime;
1381 $this->trxWriteQueryCount +
= 1;
1382 $this->trxWriteAffectedRows +
= $affected;
1383 if ( $indicativeOfReplicaRuntime ) {
1384 $this->trxWriteAdjDuration +
= $runtime;
1385 $this->trxWriteAdjQueryCount +
= 1;
1390 * Error out if the DB is not in a valid state for a query via query()
1392 * @param string $sql
1393 * @param string $fname
1394 * @throws DBTransactionStateError
1396 private function assertQueryIsCurrentlyAllowed( $sql, $fname ) {
1397 $verb = $this->getQueryVerb( $sql );
1398 if ( $verb === 'USE' ) {
1399 throw new DBUnexpectedError( $this, "Got USE query; use selectDomain() instead" );
1402 if ( $verb === 'ROLLBACK' ) { // transaction/savepoint
1406 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1407 throw new DBTransactionStateError(
1409 "Cannot execute query from $fname while transaction status is ERROR",
1411 $this->trxStatusCause
1413 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1414 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1415 call_user_func( $this->deprecationLogger
,
1416 "Caller from $fname ignored an error originally raised from $iFname: " .
1417 "[$iLastErrno] $iLastError"
1419 $this->trxStatusIgnoredCause
= null;
1423 public function assertNoOpenTransactions() {
1424 if ( $this->explicitTrxActive() ) {
1425 throw new DBTransactionError(
1427 "Explicit transaction still active. A caller may have caught an error. "
1428 . "Open transactions: " . $this->flatAtomicSectionList()
1434 * Determine whether it is safe to retry queries after a database connection is lost
1436 * @param string $sql SQL query
1437 * @param bool $priorWritesPending Whether there is a transaction open with
1438 * possible write queries or transaction pre-commit/idle callbacks
1439 * waiting on it to finish.
1440 * @return bool True if it is safe to retry the query, false otherwise
1442 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1443 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1444 # Dropped connections also mean that named locks are automatically released.
1445 # Only allow error suppression in autocommit mode or when the lost transaction
1446 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1447 if ( $this->sessionNamedLocks
) {
1448 return false; // possible critical section violation
1449 } elseif ( $this->sessionTempTables
) {
1450 return false; // tables might be queried latter
1451 } elseif ( $sql === 'COMMIT' ) {
1452 return !$priorWritesPending; // nothing written anyway? (T127428)
1453 } elseif ( $sql === 'ROLLBACK' ) {
1454 return true; // transaction lost...which is also what was requested :)
1455 } elseif ( $this->explicitTrxActive() ) {
1456 return false; // don't drop atomocity and explicit snapshots
1457 } elseif ( $priorWritesPending ) {
1458 return false; // prior writes lost from implicit transaction
1465 * Clean things up after session (and thus transaction) loss before reconnect
1467 private function handleSessionLossPreconnect() {
1468 // Clean up tracking of session-level things...
1469 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1470 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1471 $this->sessionTempTables
= [];
1472 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1473 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1474 $this->sessionNamedLocks
= [];
1475 // Session loss implies transaction loss
1476 $oldTrxShortId = $this->consumeTrxShortId();
1477 $this->trxAtomicCounter
= 0;
1478 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1479 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1480 // @note: leave trxRecurringCallbacks in place
1481 if ( $this->trxDoneWrites
) {
1482 $this->trxProfiler
->transactionWritingOut(
1484 $this->getDomainID(),
1486 $this->pendingWriteQueryDuration( self
::ESTIMATE_TOTAL
),
1487 $this->trxWriteAffectedRows
1493 * Clean things up after session (and thus transaction) loss after reconnect
1495 private function handleSessionLossPostconnect() {
1497 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1498 // If callback suppression is set then the array will remain unhandled.
1499 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1500 } catch ( Exception
$ex ) {
1501 // Already logged; move on...
1504 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1505 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1506 } catch ( Exception
$ex ) {
1507 // Already logged; move on...
1512 * Reset the transaction ID and return the old one
1514 * @return string The old transaction ID or the empty string if there wasn't one
1516 private function consumeTrxShortId() {
1517 $old = $this->trxShortId
;
1518 $this->trxShortId
= '';
1524 * Checks whether the cause of the error is detected to be a timeout.
1526 * It returns false by default, and not all engines support detecting this yet.
1527 * If this returns false, it will be treated as a generic query error.
1529 * @param string $error Error text
1530 * @param int $errno Error number
1533 protected function wasQueryTimeout( $error, $errno ) {
1538 * Report a query error. Log the error, and if neither the object ignore
1539 * flag nor the $ignoreErrors flag is set, throw a DBQueryError.
1541 * @param string $error
1543 * @param string $sql
1544 * @param string $fname
1545 * @param bool $ignore
1546 * @throws DBQueryError
1548 public function reportQueryError( $error, $errno, $sql, $fname, $ignore = false ) {
1550 $this->queryLogger
->debug( "SQL ERROR (ignored): $error" );
1552 $exception = $this->getQueryExceptionAndLog( $error, $errno, $sql, $fname );
1559 * @param string $error
1560 * @param string|int $errno
1561 * @param string $sql
1562 * @param string $fname
1565 private function getQueryExceptionAndLog( $error, $errno, $sql, $fname ) {
1566 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1567 $this->queryLogger
->error(
1568 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1569 $this->getLogContext( [
1570 'method' => __METHOD__
,
1573 'sql1line' => $sql1line,
1575 'trace' => ( new RuntimeException() )->getTraceAsString()
1578 $this->queryLogger
->debug( "SQL ERROR: " . $error . "" );
1579 if ( $this->wasQueryTimeout( $error, $errno ) ) {
1580 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1581 } elseif ( $this->wasConnectionError( $errno ) ) {
1582 $e = new DBQueryDisconnectedError( $this, $error, $errno, $sql, $fname );
1584 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1590 public function freeResult( $res ) {
1593 public function selectField(
1594 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1596 if ( $var === '*' ) { // sanity
1597 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1600 if ( !is_array( $options ) ) {
1601 $options = [ $options ];
1604 $options['LIMIT'] = 1;
1606 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1607 if ( $res === false ) {
1608 throw new DBUnexpectedError( $this, "Got false from select()" );
1611 $row = $this->fetchRow( $res );
1612 if ( $row === false ) {
1616 return reset( $row );
1619 public function selectFieldValues(
1620 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1622 if ( $var === '*' ) { // sanity
1623 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1624 } elseif ( !is_string( $var ) ) { // sanity
1625 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1628 if ( !is_array( $options ) ) {
1629 $options = [ $options ];
1632 $res = $this->select( $table, [ 'value' => $var ], $cond, $fname, $options, $join_conds );
1633 if ( $res === false ) {
1634 throw new DBUnexpectedError( $this, "Got false from select()" );
1638 foreach ( $res as $row ) {
1639 $values[] = $row->value
;
1646 * Returns an optional USE INDEX clause to go after the table, and a
1647 * string to go at the end of the query.
1649 * @param array $options Associative array of options to be turned into
1650 * an SQL query, valid keys are listed in the function.
1652 * @see Database::select()
1654 protected function makeSelectOptions( $options ) {
1655 $preLimitTail = $postLimitTail = '';
1660 foreach ( $options as $key => $option ) {
1661 if ( is_numeric( $key ) ) {
1662 $noKeyOptions[$option] = true;
1666 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1668 $preLimitTail .= $this->makeOrderBy( $options );
1670 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1671 $postLimitTail .= ' FOR UPDATE';
1674 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1675 $postLimitTail .= ' LOCK IN SHARE MODE';
1678 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1679 $startOpts .= 'DISTINCT';
1682 # Various MySQL extensions
1683 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1684 $startOpts .= ' /*! STRAIGHT_JOIN */';
1687 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1688 $startOpts .= ' HIGH_PRIORITY';
1691 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1692 $startOpts .= ' SQL_BIG_RESULT';
1695 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1696 $startOpts .= ' SQL_BUFFER_RESULT';
1699 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1700 $startOpts .= ' SQL_SMALL_RESULT';
1703 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1704 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1707 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1708 $startOpts .= ' SQL_CACHE';
1711 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1712 $startOpts .= ' SQL_NO_CACHE';
1715 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1716 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1720 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1721 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1726 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1730 * Returns an optional GROUP BY with an optional HAVING
1732 * @param array $options Associative array of options
1734 * @see Database::select()
1737 protected function makeGroupByWithHaving( $options ) {
1739 if ( isset( $options['GROUP BY'] ) ) {
1740 $gb = is_array( $options['GROUP BY'] )
1741 ?
implode( ',', $options['GROUP BY'] )
1742 : $options['GROUP BY'];
1743 $sql .= ' GROUP BY ' . $gb;
1745 if ( isset( $options['HAVING'] ) ) {
1746 $having = is_array( $options['HAVING'] )
1747 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1748 : $options['HAVING'];
1749 $sql .= ' HAVING ' . $having;
1756 * Returns an optional ORDER BY
1758 * @param array $options Associative array of options
1760 * @see Database::select()
1763 protected function makeOrderBy( $options ) {
1764 if ( isset( $options['ORDER BY'] ) ) {
1765 $ob = is_array( $options['ORDER BY'] )
1766 ?
implode( ',', $options['ORDER BY'] )
1767 : $options['ORDER BY'];
1769 return ' ORDER BY ' . $ob;
1775 public function select(
1776 $table, $vars, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1778 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1780 return $this->query( $sql, $fname );
1783 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1784 $options = [], $join_conds = []
1786 if ( is_array( $vars ) ) {
1787 $fields = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1792 $options = (array)$options;
1793 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1794 ?
$options['USE INDEX']
1797 isset( $options['IGNORE INDEX'] ) &&
1798 is_array( $options['IGNORE INDEX'] )
1800 ?
$options['IGNORE INDEX']
1804 $this->selectOptionsIncludeLocking( $options ) &&
1805 $this->selectFieldsOrOptionsAggregate( $vars, $options )
1807 // Some DB types (postgres/oracle) disallow FOR UPDATE with aggregate
1808 // functions. Discourage use of such queries to encourage compatibility.
1810 $this->deprecationLogger
,
1811 __METHOD__
. ": aggregation used with a locking SELECT ($fname)"
1815 if ( is_array( $table ) ) {
1817 $this->tableNamesWithIndexClauseOrJOIN(
1818 $table, $useIndexes, $ignoreIndexes, $join_conds );
1819 } elseif ( $table != '' ) {
1821 $this->tableNamesWithIndexClauseOrJOIN(
1822 [ $table ], $useIndexes, $ignoreIndexes, [] );
1827 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1828 $this->makeSelectOptions( $options );
1830 if ( is_array( $conds ) ) {
1831 $conds = $this->makeList( $conds, self
::LIST_AND
);
1834 if ( $conds === null ||
$conds === false ) {
1835 $this->queryLogger
->warning(
1839 . ' with incorrect parameters: $conds must be a string or an array'
1844 if ( $conds === '' ||
$conds === '*' ) {
1845 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex $preLimitTail";
1846 } elseif ( is_string( $conds ) ) {
1847 $sql = "SELECT $startOpts $fields $from $useIndex $ignoreIndex " .
1848 "WHERE $conds $preLimitTail";
1850 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1853 if ( isset( $options['LIMIT'] ) ) {
1854 $sql = $this->limitResult( $sql, $options['LIMIT'],
1855 $options['OFFSET'] ??
false );
1857 $sql = "$sql $postLimitTail";
1859 if ( isset( $options['EXPLAIN'] ) ) {
1860 $sql = 'EXPLAIN ' . $sql;
1866 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1867 $options = [], $join_conds = []
1869 $options = (array)$options;
1870 $options['LIMIT'] = 1;
1872 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1873 if ( $res === false ) {
1874 throw new DBUnexpectedError( $this, "Got false from select()" );
1877 if ( !$this->numRows( $res ) ) {
1881 return $this->fetchObject( $res );
1884 public function estimateRowCount(
1885 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1887 $conds = $this->normalizeConditions( $conds, $fname );
1888 $column = $this->extractSingleFieldFromList( $var );
1889 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1890 $conds[] = "$column IS NOT NULL";
1893 $res = $this->select(
1894 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1896 $row = $res ?
$this->fetchRow( $res ) : [];
1898 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1901 public function selectRowCount(
1902 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1904 $conds = $this->normalizeConditions( $conds, $fname );
1905 $column = $this->extractSingleFieldFromList( $var );
1906 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1907 $conds[] = "$column IS NOT NULL";
1910 $res = $this->select(
1912 'tmp_count' => $this->buildSelectSubquery(
1921 [ 'rowcount' => 'COUNT(*)' ],
1925 $row = $res ?
$this->fetchRow( $res ) : [];
1927 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1931 * @param string|array $options
1934 private function selectOptionsIncludeLocking( $options ) {
1935 $options = (array)$options;
1936 foreach ( [ 'FOR UPDATE', 'LOCK IN SHARE MODE' ] as $lock ) {
1937 if ( in_array( $lock, $options, true ) ) {
1946 * @param array|string $fields
1947 * @param array|string $options
1950 private function selectFieldsOrOptionsAggregate( $fields, $options ) {
1951 foreach ( (array)$options as $key => $value ) {
1952 if ( is_string( $key ) ) {
1953 if ( preg_match( '/^(?:GROUP BY|HAVING)$/i', $key ) ) {
1956 } elseif ( is_string( $value ) ) {
1957 if ( preg_match( '/^(?:DISTINCT|DISTINCTROW)$/i', $value ) ) {
1963 $regex = '/^(?:COUNT|MIN|MAX|SUM|GROUP_CONCAT|LISTAGG|ARRAY_AGG)\s*\\(/i';
1964 foreach ( (array)$fields as $field ) {
1965 if ( is_string( $field ) && preg_match( $regex, $field ) ) {
1974 * @param array|string $conds
1975 * @param string $fname
1978 final protected function normalizeConditions( $conds, $fname ) {
1979 if ( $conds === null ||
$conds === false ) {
1980 $this->queryLogger
->warning(
1984 . ' with incorrect parameters: $conds must be a string or an array'
1989 if ( !is_array( $conds ) ) {
1990 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1997 * @param array|string $var Field parameter in the style of select()
1998 * @return string|null Column name or null; ignores aliases
1999 * @throws DBUnexpectedError Errors out if multiple columns are given
2001 final protected function extractSingleFieldFromList( $var ) {
2002 if ( is_array( $var ) ) {
2005 } elseif ( count( $var ) == 1 ) {
2006 $column = $var[0] ??
reset( $var );
2008 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns' );
2017 public function lockForUpdate(
2018 $table, $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
2020 if ( !$this->trxLevel() && !$this->getFlag( self
::DBO_TRX
) ) {
2021 throw new DBUnexpectedError(
2023 __METHOD__
. ': no transaction is active nor is DBO_TRX set'
2027 $options = (array)$options;
2028 $options[] = 'FOR UPDATE';
2030 return $this->selectRowCount( $table, '*', $conds, $fname, $options, $join_conds );
2033 public function fieldExists( $table, $field, $fname = __METHOD__
) {
2034 $info = $this->fieldInfo( $table, $field );
2039 public function indexExists( $table, $index, $fname = __METHOD__
) {
2040 if ( !$this->tableExists( $table ) ) {
2044 $info = $this->indexInfo( $table, $index, $fname );
2045 if ( is_null( $info ) ) {
2048 return $info !== false;
2052 abstract public function tableExists( $table, $fname = __METHOD__
);
2054 public function indexUnique( $table, $index ) {
2055 $indexInfo = $this->indexInfo( $table, $index );
2057 if ( !$indexInfo ) {
2061 return !$indexInfo[0]->Non_unique
;
2065 * Helper for Database::insert().
2067 * @param array $options
2070 protected function makeInsertOptions( $options ) {
2071 return implode( ' ', $options );
2074 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
2075 # No rows to insert, easy just return now
2076 if ( !count( $a ) ) {
2080 $table = $this->tableName( $table );
2082 if ( !is_array( $options ) ) {
2083 $options = [ $options ];
2086 $options = $this->makeInsertOptions( $options );
2088 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2090 $keys = array_keys( $a[0] );
2093 $keys = array_keys( $a );
2096 $sql = 'INSERT ' . $options .
2097 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2101 foreach ( $a as $row ) {
2107 $sql .= '(' . $this->makeList( $row ) . ')';
2110 $sql .= '(' . $this->makeList( $a ) . ')';
2113 $this->query( $sql, $fname );
2119 * Make UPDATE options array for Database::makeUpdateOptions
2121 * @param array $options
2124 protected function makeUpdateOptionsArray( $options ) {
2125 if ( !is_array( $options ) ) {
2126 $options = [ $options ];
2131 if ( in_array( 'IGNORE', $options ) ) {
2139 * Make UPDATE options for the Database::update function
2141 * @param array $options The options passed to Database::update
2144 protected function makeUpdateOptions( $options ) {
2145 $opts = $this->makeUpdateOptionsArray( $options );
2147 return implode( ' ', $opts );
2150 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
2151 $table = $this->tableName( $table );
2152 $opts = $this->makeUpdateOptions( $options );
2153 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2155 if ( $conds !== [] && $conds !== '*' ) {
2156 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2159 $this->query( $sql, $fname );
2164 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2165 if ( !is_array( $a ) ) {
2166 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2172 foreach ( $a as $field => $value ) {
2174 if ( $mode == self
::LIST_AND
) {
2176 } elseif ( $mode == self
::LIST_OR
) {
2185 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2186 $list .= "($value)";
2187 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2190 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2192 // Remove null from array to be handled separately if found
2193 $includeNull = false;
2194 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2195 $includeNull = true;
2196 unset( $value[$nullKey] );
2198 if ( count( $value ) == 0 && !$includeNull ) {
2199 throw new InvalidArgumentException(
2200 __METHOD__
. ": empty input for field $field" );
2201 } elseif ( count( $value ) == 0 ) {
2202 // only check if $field is null
2203 $list .= "$field IS NULL";
2205 // IN clause contains at least one valid element
2206 if ( $includeNull ) {
2207 // Group subconditions to ensure correct precedence
2210 if ( count( $value ) == 1 ) {
2211 // Special-case single values, as IN isn't terribly efficient
2212 // Don't necessarily assume the single key is 0; we don't
2213 // enforce linear numeric ordering on other arrays here.
2214 $value = array_values( $value )[0];
2215 $list .= $field . " = " . $this->addQuotes( $value );
2217 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2219 // if null present in array, append IS NULL
2220 if ( $includeNull ) {
2221 $list .= " OR $field IS NULL)";
2224 } elseif ( $value === null ) {
2225 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2226 $list .= "$field IS ";
2227 } elseif ( $mode == self
::LIST_SET
) {
2228 $list .= "$field = ";
2233 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2235 $list .= "$field = ";
2237 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2244 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2247 foreach ( $data as $base => $sub ) {
2248 if ( count( $sub ) ) {
2249 $conds[] = $this->makeList(
2250 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2256 return $this->makeList( $conds, self
::LIST_OR
);
2258 // Nothing to search for...
2263 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2267 public function bitNot( $field ) {
2271 public function bitAnd( $fieldLeft, $fieldRight ) {
2272 return "($fieldLeft & $fieldRight)";
2275 public function bitOr( $fieldLeft, $fieldRight ) {
2276 return "($fieldLeft | $fieldRight)";
2279 public function buildConcat( $stringList ) {
2280 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2283 public function buildGroupConcatField(
2284 $delim, $table, $field, $conds = '', $join_conds = []
2286 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2288 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2291 public function buildSubstring( $input, $startPosition, $length = null ) {
2292 $this->assertBuildSubstringParams( $startPosition, $length );
2293 $functionBody = "$input FROM $startPosition";
2294 if ( $length !== null ) {
2295 $functionBody .= " FOR $length";
2297 return 'SUBSTRING(' . $functionBody . ')';
2301 * Check type and bounds for parameters to self::buildSubstring()
2303 * All supported databases have substring functions that behave the same for
2304 * positive $startPosition and non-negative $length, but behaviors differ when
2305 * given 0 or negative $startPosition or negative $length. The simplest
2306 * solution to that is to just forbid those values.
2308 * @param int $startPosition
2309 * @param int|null $length
2312 protected function assertBuildSubstringParams( $startPosition, $length ) {
2313 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2314 throw new InvalidArgumentException(
2315 '$startPosition must be a positive integer'
2318 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2319 throw new InvalidArgumentException(
2320 '$length must be null or an integer greater than or equal to 0'
2325 public function buildStringCast( $field ) {
2326 // In theory this should work for any standards-compliant
2327 // SQL implementation, although it may not be the best way to do it.
2328 return "CAST( $field AS CHARACTER )";
2331 public function buildIntegerCast( $field ) {
2332 return 'CAST( ' . $field . ' AS INTEGER )';
2335 public function buildSelectSubquery(
2336 $table, $vars, $conds = '', $fname = __METHOD__
,
2337 $options = [], $join_conds = []
2339 return new Subquery(
2340 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2344 public function databasesAreIndependent() {
2348 final public function selectDB( $db ) {
2349 $this->selectDomain( new DatabaseDomain(
2351 $this->currentDomain
->getSchema(),
2352 $this->currentDomain
->getTablePrefix()
2358 final public function selectDomain( $domain ) {
2359 $this->doSelectDomain( DatabaseDomain
::newFromId( $domain ) );
2362 protected function doSelectDomain( DatabaseDomain
$domain ) {
2363 $this->currentDomain
= $domain;
2366 public function getDBname() {
2367 return $this->currentDomain
->getDatabase();
2370 public function getServer() {
2371 return $this->server
;
2374 public function tableName( $name, $format = 'quoted' ) {
2375 if ( $name instanceof Subquery
) {
2376 throw new DBUnexpectedError(
2378 __METHOD__
. ': got Subquery instance when expecting a string'
2382 # Skip the entire process when we have a string quoted on both ends.
2383 # Note that we check the end so that we will still quote any use of
2384 # use of `database`.table. But won't break things if someone wants
2385 # to query a database table with a dot in the name.
2386 if ( $this->isQuotedIdentifier( $name ) ) {
2390 # Lets test for any bits of text that should never show up in a table
2391 # name. Basically anything like JOIN or ON which are actually part of
2392 # SQL queries, but may end up inside of the table value to combine
2393 # sql. Such as how the API is doing.
2394 # Note that we use a whitespace test rather than a \b test to avoid
2395 # any remote case where a word like on may be inside of a table name
2396 # surrounded by symbols which may be considered word breaks.
2397 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2398 $this->queryLogger
->warning(
2399 __METHOD__
. ": use of subqueries is not supported this way",
2400 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2406 # Split database and table into proper variables.
2407 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2409 # Quote $table and apply the prefix if not quoted.
2410 # $tableName might be empty if this is called from Database::replaceVars()
2411 $tableName = "{$prefix}{$table}";
2412 if ( $format === 'quoted'
2413 && !$this->isQuotedIdentifier( $tableName )
2414 && $tableName !== ''
2416 $tableName = $this->addIdentifierQuotes( $tableName );
2419 # Quote $schema and $database and merge them with the table name if needed
2420 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2421 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2427 * Get the table components needed for a query given the currently selected database
2429 * @param string $name Table name in the form of db.schema.table, db.table, or table
2430 * @return array (DB name or "" for default, schema name, table prefix, table name)
2432 protected function qualifiedTableComponents( $name ) {
2433 # We reverse the explode so that database.table and table both output the correct table.
2434 $dbDetails = explode( '.', $name, 3 );
2435 if ( count( $dbDetails ) == 3 ) {
2436 list( $database, $schema, $table ) = $dbDetails;
2437 # We don't want any prefix added in this case
2439 } elseif ( count( $dbDetails ) == 2 ) {
2440 list( $database, $table ) = $dbDetails;
2441 # We don't want any prefix added in this case
2443 # In dbs that support it, $database may actually be the schema
2444 # but that doesn't affect any of the functionality here
2447 list( $table ) = $dbDetails;
2448 if ( isset( $this->tableAliases
[$table] ) ) {
2449 $database = $this->tableAliases
[$table]['dbname'];
2450 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2451 ?
$this->tableAliases
[$table]['schema']
2452 : $this->relationSchemaQualifier();
2453 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2454 ?
$this->tableAliases
[$table]['prefix']
2455 : $this->tablePrefix();
2458 $schema = $this->relationSchemaQualifier(); # Default schema
2459 $prefix = $this->tablePrefix(); # Default prefix
2463 return [ $database, $schema, $prefix, $table ];
2467 * @param string|null $namespace Database or schema
2468 * @param string $relation Name of table, view, sequence, etc...
2469 * @param string $format One of (raw, quoted)
2470 * @return string Relation name with quoted and merged $namespace as needed
2472 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2473 if ( strlen( $namespace ) ) {
2474 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2475 $namespace = $this->addIdentifierQuotes( $namespace );
2477 $relation = $namespace . '.' . $relation;
2483 public function tableNames() {
2484 $inArray = func_get_args();
2487 foreach ( $inArray as $name ) {
2488 $retVal[$name] = $this->tableName( $name );
2494 public function tableNamesN() {
2495 $inArray = func_get_args();
2498 foreach ( $inArray as $name ) {
2499 $retVal[] = $this->tableName( $name );
2506 * Get an aliased table name
2508 * This returns strings like "tableName AS newTableName" for aliased tables
2509 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2511 * @see Database::tableName()
2512 * @param string|Subquery $table Table name or object with a 'sql' field
2513 * @param string|bool $alias Table alias (optional)
2514 * @return string SQL name for aliased table. Will not alias a table to its own name
2516 protected function tableNameWithAlias( $table, $alias = false ) {
2517 if ( is_string( $table ) ) {
2518 $quotedTable = $this->tableName( $table );
2519 } elseif ( $table instanceof Subquery
) {
2520 $quotedTable = (string)$table;
2522 throw new InvalidArgumentException( "Table must be a string or Subquery" );
2525 if ( $alias === false ||
$alias === $table ) {
2526 if ( $table instanceof Subquery
) {
2527 throw new InvalidArgumentException( "Subquery table missing alias" );
2530 return $quotedTable;
2532 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2537 * Gets an array of aliased table names
2539 * @param array $tables [ [alias] => table ]
2540 * @return string[] See tableNameWithAlias()
2542 protected function tableNamesWithAlias( $tables ) {
2544 foreach ( $tables as $alias => $table ) {
2545 if ( is_numeric( $alias ) ) {
2548 $retval[] = $this->tableNameWithAlias( $table, $alias );
2555 * Get an aliased field name
2556 * e.g. fieldName AS newFieldName
2558 * @param string $name Field name
2559 * @param string|bool $alias Alias (optional)
2560 * @return string SQL name for aliased field. Will not alias a field to its own name
2562 protected function fieldNameWithAlias( $name, $alias = false ) {
2563 if ( !$alias ||
(string)$alias === (string)$name ) {
2566 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2571 * Gets an array of aliased field names
2573 * @param array $fields [ [alias] => field ]
2574 * @return string[] See fieldNameWithAlias()
2576 protected function fieldNamesWithAlias( $fields ) {
2578 foreach ( $fields as $alias => $field ) {
2579 if ( is_numeric( $alias ) ) {
2582 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2589 * Get the aliased table name clause for a FROM clause
2590 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2592 * @param array $tables ( [alias] => table )
2593 * @param array $use_index Same as for select()
2594 * @param array $ignore_index Same as for select()
2595 * @param array $join_conds Same as for select()
2598 protected function tableNamesWithIndexClauseOrJOIN(
2599 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2603 $use_index = (array)$use_index;
2604 $ignore_index = (array)$ignore_index;
2605 $join_conds = (array)$join_conds;
2607 foreach ( $tables as $alias => $table ) {
2608 if ( !is_string( $alias ) ) {
2609 // No alias? Set it equal to the table name
2613 if ( is_array( $table ) ) {
2614 // A parenthesized group
2615 if ( count( $table ) > 1 ) {
2616 $joinedTable = '(' .
2617 $this->tableNamesWithIndexClauseOrJOIN(
2618 $table, $use_index, $ignore_index, $join_conds ) . ')';
2621 $innerTable = reset( $table );
2622 $innerAlias = key( $table );
2623 $joinedTable = $this->tableNameWithAlias(
2625 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2629 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2632 // Is there a JOIN clause for this table?
2633 if ( isset( $join_conds[$alias] ) ) {
2634 list( $joinType, $conds ) = $join_conds[$alias];
2635 $tableClause = $joinType;
2636 $tableClause .= ' ' . $joinedTable;
2637 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2638 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2640 $tableClause .= ' ' . $use;
2643 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2644 $ignore = $this->ignoreIndexClause(
2645 implode( ',', (array)$ignore_index[$alias] ) );
2646 if ( $ignore != '' ) {
2647 $tableClause .= ' ' . $ignore;
2650 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2652 $tableClause .= ' ON (' . $on . ')';
2655 $retJOIN[] = $tableClause;
2656 } elseif ( isset( $use_index[$alias] ) ) {
2657 // Is there an INDEX clause for this table?
2658 $tableClause = $joinedTable;
2659 $tableClause .= ' ' . $this->useIndexClause(
2660 implode( ',', (array)$use_index[$alias] )
2663 $ret[] = $tableClause;
2664 } elseif ( isset( $ignore_index[$alias] ) ) {
2665 // Is there an INDEX clause for this table?
2666 $tableClause = $joinedTable;
2667 $tableClause .= ' ' . $this->ignoreIndexClause(
2668 implode( ',', (array)$ignore_index[$alias] )
2671 $ret[] = $tableClause;
2673 $tableClause = $joinedTable;
2675 $ret[] = $tableClause;
2679 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2680 $implicitJoins = implode( ',', $ret );
2681 $explicitJoins = implode( ' ', $retJOIN );
2683 // Compile our final table clause
2684 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2688 * Allows for index remapping in queries where this is not consistent across DBMS
2690 * @param string $index
2693 protected function indexName( $index ) {
2694 return $this->indexAliases
[$index] ??
$index;
2697 public function addQuotes( $s ) {
2698 if ( $s instanceof Blob
) {
2701 if ( $s === null ) {
2703 } elseif ( is_bool( $s ) ) {
2706 # This will also quote numeric values. This should be harmless,
2707 # and protects against weird problems that occur when they really
2708 # _are_ strings such as article titles and string->number->string
2709 # conversion is not 1:1.
2710 return "'" . $this->strencode( $s ) . "'";
2714 public function addIdentifierQuotes( $s ) {
2715 return '"' . str_replace( '"', '""', $s ) . '"';
2719 * Returns if the given identifier looks quoted or not according to
2720 * the database convention for quoting identifiers .
2722 * @note Do not use this to determine if untrusted input is safe.
2723 * A malicious user can trick this function.
2724 * @param string $name
2727 public function isQuotedIdentifier( $name ) {
2728 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2733 * @param string $escapeChar
2736 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2737 return str_replace( [ $escapeChar, '%', '_' ],
2738 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2742 public function buildLike( $param, ...$params ) {
2743 if ( is_array( $param ) ) {
2746 $params = func_get_args();
2751 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2752 // may escape backslashes, creating problems of double escaping. The `
2753 // character has good cross-DBMS compatibility, avoiding special operators
2754 // in MS SQL like ^ and %
2757 foreach ( $params as $value ) {
2758 if ( $value instanceof LikeMatch
) {
2759 $s .= $value->toString();
2761 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2766 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2769 public function anyChar() {
2770 return new LikeMatch( '_' );
2773 public function anyString() {
2774 return new LikeMatch( '%' );
2777 public function nextSequenceValue( $seqName ) {
2782 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2783 * is only needed because a) MySQL must be as efficient as possible due to
2784 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2785 * which index to pick. Anyway, other databases might have different
2786 * indexes on a given table. So don't bother overriding this unless you're
2788 * @param string $index
2791 public function useIndexClause( $index ) {
2796 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2797 * is only needed because a) MySQL must be as efficient as possible due to
2798 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2799 * which index to pick. Anyway, other databases might have different
2800 * indexes on a given table. So don't bother overriding this unless you're
2802 * @param string $index
2805 public function ignoreIndexClause( $index ) {
2809 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2810 if ( count( $rows ) == 0 ) {
2814 $uniqueIndexes = (array)$uniqueIndexes;
2816 if ( !is_array( reset( $rows ) ) ) {
2821 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2822 $affectedRowCount = 0;
2823 foreach ( $rows as $row ) {
2824 // Delete rows which collide with this one
2825 $indexWhereClauses = [];
2826 foreach ( $uniqueIndexes as $index ) {
2827 $indexColumns = (array)$index;
2828 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2829 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2830 throw new DBUnexpectedError(
2832 'New record does not provide all values for unique key (' .
2833 implode( ', ', $indexColumns ) . ')'
2835 } elseif ( in_array( null, $indexRowValues, true ) ) {
2836 throw new DBUnexpectedError(
2838 'New record has a null value for unique key (' .
2839 implode( ', ', $indexColumns ) . ')'
2842 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2845 if ( $indexWhereClauses ) {
2846 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2847 $affectedRowCount +
= $this->affectedRows();
2850 // Now insert the row
2851 $this->insert( $table, $row, $fname );
2852 $affectedRowCount +
= $this->affectedRows();
2854 $this->endAtomic( $fname );
2855 $this->affectedRowCount
= $affectedRowCount;
2856 } catch ( Exception
$e ) {
2857 $this->cancelAtomic( $fname );
2863 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2866 * @param string $table Table name
2867 * @param array|string $rows Row(s) to insert
2868 * @param string $fname Caller function name
2870 protected function nativeReplace( $table, $rows, $fname ) {
2871 $table = $this->tableName( $table );
2874 if ( !is_array( reset( $rows ) ) ) {
2878 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2881 foreach ( $rows as $row ) {
2888 $sql .= '(' . $this->makeList( $row ) . ')';
2891 $this->query( $sql, $fname );
2894 public function upsert( $table, array $rows, $uniqueIndexes, array $set,
2897 if ( $rows === [] ) {
2898 return true; // nothing to do
2901 $uniqueIndexes = (array)$uniqueIndexes;
2902 if ( !is_array( reset( $rows ) ) ) {
2906 if ( count( $uniqueIndexes ) ) {
2907 $clauses = []; // list WHERE clauses that each identify a single row
2908 foreach ( $rows as $row ) {
2909 foreach ( $uniqueIndexes as $index ) {
2910 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2911 $rowKey = []; // unique key to this row
2912 foreach ( $index as $column ) {
2913 $rowKey[$column] = $row[$column];
2915 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2918 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2923 $affectedRowCount = 0;
2925 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2926 # Update any existing conflicting row(s)
2927 if ( $where !== false ) {
2928 $this->update( $table, $set, $where, $fname );
2929 $affectedRowCount +
= $this->affectedRows();
2931 # Now insert any non-conflicting row(s)
2932 $this->insert( $table, $rows, $fname, [ 'IGNORE' ] );
2933 $affectedRowCount +
= $this->affectedRows();
2934 $this->endAtomic( $fname );
2935 $this->affectedRowCount
= $affectedRowCount;
2936 } catch ( Exception
$e ) {
2937 $this->cancelAtomic( $fname );
2944 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2948 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2951 $delTable = $this->tableName( $delTable );
2952 $joinTable = $this->tableName( $joinTable );
2953 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2954 if ( $conds != '*' ) {
2955 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2959 $this->query( $sql, $fname );
2962 public function textFieldSize( $table, $field ) {
2963 $table = $this->tableName( $table );
2964 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\"";
2965 $res = $this->query( $sql, __METHOD__
);
2966 $row = $this->fetchObject( $res );
2970 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2979 public function delete( $table, $conds, $fname = __METHOD__
) {
2981 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2984 $table = $this->tableName( $table );
2985 $sql = "DELETE FROM $table";
2987 if ( $conds != '*' ) {
2988 if ( is_array( $conds ) ) {
2989 $conds = $this->makeList( $conds, self
::LIST_AND
);
2991 $sql .= ' WHERE ' . $conds;
2994 $this->query( $sql, $fname );
2999 final public function insertSelect(
3000 $destTable, $srcTable, $varMap, $conds,
3001 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3003 static $hints = [ 'NO_AUTO_COLUMNS' ];
3005 $insertOptions = (array)$insertOptions;
3006 $selectOptions = (array)$selectOptions;
3008 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
3009 // For massive migrations with downtime, we don't want to select everything
3010 // into memory and OOM, so do all this native on the server side if possible.
3011 $this->nativeInsertSelect(
3017 array_diff( $insertOptions, $hints ),
3022 $this->nonNativeInsertSelect(
3028 array_diff( $insertOptions, $hints ),
3038 * @param array $insertOptions INSERT options
3039 * @param array $selectOptions SELECT options
3040 * @return bool Whether an INSERT SELECT with these options will be replication safe
3043 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
3048 * Implementation of insertSelect() based on select() and insert()
3050 * @see IDatabase::insertSelect()
3052 * @param string $destTable
3053 * @param string|array $srcTable
3054 * @param array $varMap
3055 * @param array $conds
3056 * @param string $fname
3057 * @param array $insertOptions
3058 * @param array $selectOptions
3059 * @param array $selectJoinConds
3061 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3062 $fname = __METHOD__
,
3063 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3065 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
3066 // on only the master (without needing row-based-replication). It also makes it easy to
3067 // know how big the INSERT is going to be.
3069 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
3070 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
3072 $selectOptions[] = 'FOR UPDATE';
3073 $res = $this->select(
3074 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
3081 $affectedRowCount = 0;
3082 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3085 foreach ( $res as $row ) {
3086 $rows[] = (array)$row;
3088 // Avoid inserts that are too huge
3089 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
3090 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3094 $affectedRowCount +
= $this->affectedRows();
3098 if ( $rows && $ok ) {
3099 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
3101 $affectedRowCount +
= $this->affectedRows();
3105 $this->endAtomic( $fname );
3106 $this->affectedRowCount
= $affectedRowCount;
3108 $this->cancelAtomic( $fname );
3110 } catch ( Exception
$e ) {
3111 $this->cancelAtomic( $fname );
3117 * Native server-side implementation of insertSelect() for situations where
3118 * we don't want to select everything into memory
3120 * @see IDatabase::insertSelect()
3121 * @param string $destTable
3122 * @param string|array $srcTable
3123 * @param array $varMap
3124 * @param array $conds
3125 * @param string $fname
3126 * @param array $insertOptions
3127 * @param array $selectOptions
3128 * @param array $selectJoinConds
3130 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
3131 $fname = __METHOD__
,
3132 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
3134 $destTable = $this->tableName( $destTable );
3136 if ( !is_array( $insertOptions ) ) {
3137 $insertOptions = [ $insertOptions ];
3140 $insertOptions = $this->makeInsertOptions( $insertOptions );
3142 $selectSql = $this->selectSQLText(
3144 array_values( $varMap ),
3151 $sql = "INSERT $insertOptions" .
3152 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3155 $this->query( $sql, $fname );
3158 public function limitResult( $sql, $limit, $offset = false ) {
3159 if ( !is_numeric( $limit ) ) {
3160 throw new DBUnexpectedError(
3162 "Invalid non-numeric limit passed to " . __METHOD__
3165 // This version works in MySQL and SQLite. It will very likely need to be
3166 // overridden for most other RDBMS subclasses.
3167 return "$sql LIMIT "
3168 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3172 public function unionSupportsOrderAndLimit() {
3173 return true; // True for almost every DB supported
3176 public function unionQueries( $sqls, $all ) {
3177 $glue = $all ?
') UNION ALL (' : ') UNION (';
3179 return '(' . implode( $glue, $sqls ) . ')';
3182 public function unionConditionPermutations(
3183 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3184 $options = [], $join_conds = []
3186 // First, build the Cartesian product of $permute_conds
3188 foreach ( $permute_conds as $field => $values ) {
3190 // Skip empty $values
3193 $values = array_unique( $values ); // For sanity
3195 foreach ( $conds as $cond ) {
3196 foreach ( $values as $value ) {
3197 $cond[$field] = $value;
3198 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3204 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3206 // If there's just one condition and no subordering, hand off to
3207 // selectSQLText directly.
3208 if ( count( $conds ) === 1 &&
3209 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3211 return $this->selectSQLText(
3212 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3216 // Otherwise, we need to pull out the order and limit to apply after
3217 // the union. Then build the SQL queries for each set of conditions in
3218 // $conds. Then union them together (using UNION ALL, because the
3219 // product *should* already be distinct).
3220 $orderBy = $this->makeOrderBy( $options );
3221 $limit = $options['LIMIT'] ??
null;
3222 $offset = $options['OFFSET'] ??
false;
3223 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3224 if ( !$this->unionSupportsOrderAndLimit() ) {
3225 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3227 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3228 $options['ORDER BY'] = $options['INNER ORDER BY'];
3230 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3231 // We need to increase the limit by the offset rather than
3232 // using the offset directly, otherwise it'll skip incorrectly
3233 // in the subqueries.
3234 $options['LIMIT'] = $limit +
$offset;
3235 unset( $options['OFFSET'] );
3240 foreach ( $conds as $cond ) {
3241 $sqls[] = $this->selectSQLText(
3242 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3245 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3246 if ( $limit !== null ) {
3247 $sql = $this->limitResult( $sql, $limit, $offset );
3253 public function conditional( $cond, $trueVal, $falseVal ) {
3254 if ( is_array( $cond ) ) {
3255 $cond = $this->makeList( $cond, self
::LIST_AND
);
3258 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3261 public function strreplace( $orig, $old, $new ) {
3262 return "REPLACE({$orig}, {$old}, {$new})";
3265 public function getServerUptime() {
3269 public function wasDeadlock() {
3273 public function wasLockTimeout() {
3277 public function wasConnectionLoss() {
3278 return $this->wasConnectionError( $this->lastErrno() );
3281 public function wasReadOnlyError() {
3285 public function wasErrorReissuable() {
3287 $this->wasDeadlock() ||
3288 $this->wasLockTimeout() ||
3289 $this->wasConnectionLoss()
3294 * Do not use this method outside of Database/DBError classes
3296 * @param int|string $errno
3297 * @return bool Whether the given query error was a connection drop
3299 public function wasConnectionError( $errno ) {
3304 * @return bool Whether it is known that the last query error only caused statement rollback
3305 * @note This is for backwards compatibility for callers catching DBError exceptions in
3306 * order to ignore problems like duplicate key errors or foriegn key violations
3309 protected function wasKnownStatementRollbackError() {
3310 return false; // don't know; it could have caused a transaction rollback
3313 public function deadlockLoop() {
3314 $args = func_get_args();
3315 $function = array_shift( $args );
3316 $tries = self
::$DEADLOCK_TRIES;
3318 $this->begin( __METHOD__
);
3321 /** @var Exception $e */
3325 $retVal = $function( ...$args );
3327 } catch ( DBQueryError
$e ) {
3328 if ( $this->wasDeadlock() ) {
3329 // Retry after a randomized delay
3330 usleep( mt_rand( self
::$DEADLOCK_DELAY_MIN, self
::$DEADLOCK_DELAY_MAX ) );
3332 // Throw the error back up
3336 } while ( --$tries > 0 );
3338 if ( $tries <= 0 ) {
3339 // Too many deadlocks; give up
3340 $this->rollback( __METHOD__
);
3343 $this->commit( __METHOD__
);
3349 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3350 # Real waits are implemented in the subclass.
3354 public function getReplicaPos() {
3359 public function getMasterPos() {
3364 public function serverIsReadOnly() {
3368 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3369 if ( !$this->trxLevel() ) {
3370 throw new DBUnexpectedError( $this, "No transaction is active" );
3372 $this->trxEndCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3375 final public function onTransactionCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3376 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3377 // Start an implicit transaction similar to how query() does
3378 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3379 $this->trxAutomatic
= true;
3382 $this->trxIdleCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3383 if ( !$this->trxLevel() ) {
3384 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3388 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3389 $this->onTransactionCommitOrIdle( $callback, $fname );
3392 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3393 if ( !$this->trxLevel() && $this->getTransactionRoundId() ) {
3394 // Start an implicit transaction similar to how query() does
3395 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3396 $this->trxAutomatic
= true;
3399 if ( $this->trxLevel() ) {
3400 $this->trxPreCommitCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3402 // No transaction is active nor will start implicitly, so make one for this callback
3403 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3406 $this->endAtomic( __METHOD__
);
3407 } catch ( Exception
$e ) {
3408 $this->cancelAtomic( __METHOD__
);
3414 final public function onAtomicSectionCancel( callable
$callback, $fname = __METHOD__
) {
3415 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3416 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3418 $this->trxSectionCancelCallbacks
[] = [ $callback, $fname, $this->currentAtomicSectionId() ];
3422 * @return AtomicSectionIdentifier|null ID of the topmost atomic section level
3424 private function currentAtomicSectionId() {
3425 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
3426 $levelInfo = end( $this->trxAtomicLevels
);
3428 return $levelInfo[1];
3435 * Hoist callback ownership for callbacks in a section to a parent section.
3436 * All callbacks should have an owner that is present in trxAtomicLevels.
3437 * @param AtomicSectionIdentifier $old
3438 * @param AtomicSectionIdentifier $new
3440 private function reassignCallbacksForSection(
3441 AtomicSectionIdentifier
$old, AtomicSectionIdentifier
$new
3443 foreach ( $this->trxPreCommitCallbacks
as $key => $info ) {
3444 if ( $info[2] === $old ) {
3445 $this->trxPreCommitCallbacks
[$key][2] = $new;
3448 foreach ( $this->trxIdleCallbacks
as $key => $info ) {
3449 if ( $info[2] === $old ) {
3450 $this->trxIdleCallbacks
[$key][2] = $new;
3453 foreach ( $this->trxEndCallbacks
as $key => $info ) {
3454 if ( $info[2] === $old ) {
3455 $this->trxEndCallbacks
[$key][2] = $new;
3458 foreach ( $this->trxSectionCancelCallbacks
as $key => $info ) {
3459 if ( $info[2] === $old ) {
3460 $this->trxSectionCancelCallbacks
[$key][2] = $new;
3466 * Update callbacks that were owned by cancelled atomic sections.
3468 * Callbacks for "on commit" should never be run if they're owned by a
3469 * section that won't be committed.
3471 * Callbacks for "on resolution" need to reflect that the section was
3472 * rolled back, even if the transaction as a whole commits successfully.
3474 * Callbacks for "on section cancel" should already have been consumed,
3475 * but errors during the cancellation itself can prevent that while still
3476 * destroying the section. Hoist any such callbacks to the new top section,
3477 * which we assume will itself have to be cancelled or rolled back to
3478 * resolve the error.
3480 * @param AtomicSectionIdentifier[] $sectionIds ID of an actual savepoint
3481 * @param AtomicSectionIdentifier|null $newSectionId New top section ID.
3482 * @throws UnexpectedValueException
3484 private function modifyCallbacksForCancel(
3485 array $sectionIds, AtomicSectionIdentifier
$newSectionId = null
3487 // Cancel the "on commit" callbacks owned by this savepoint
3488 $this->trxIdleCallbacks
= array_filter(
3489 $this->trxIdleCallbacks
,
3490 function ( $entry ) use ( $sectionIds ) {
3491 return !in_array( $entry[2], $sectionIds, true );
3494 $this->trxPreCommitCallbacks
= array_filter(
3495 $this->trxPreCommitCallbacks
,
3496 function ( $entry ) use ( $sectionIds ) {
3497 return !in_array( $entry[2], $sectionIds, true );
3500 // Make "on resolution" callbacks owned by this savepoint to perceive a rollback
3501 foreach ( $this->trxEndCallbacks
as $key => $entry ) {
3502 if ( in_array( $entry[2], $sectionIds, true ) ) {
3503 $callback = $entry[0];
3504 $this->trxEndCallbacks
[$key][0] = function () use ( $callback ) {
3505 // @phan-suppress-next-line PhanInfiniteRecursion No recursion at all here, phan is confused
3506 return $callback( self
::TRIGGER_ROLLBACK
, $this );
3508 // This "on resolution" callback no longer belongs to a section.
3509 $this->trxEndCallbacks
[$key][2] = null;
3512 // Hoist callback ownership for section cancel callbacks to the new top section
3513 foreach ( $this->trxSectionCancelCallbacks
as $key => $entry ) {
3514 if ( in_array( $entry[2], $sectionIds, true ) ) {
3515 $this->trxSectionCancelCallbacks
[$key][2] = $newSectionId;
3520 final public function setTransactionListener( $name, callable
$callback = null ) {
3522 $this->trxRecurringCallbacks
[$name] = $callback;
3524 unset( $this->trxRecurringCallbacks
[$name] );
3529 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3531 * This method should not be used outside of Database/LoadBalancer
3533 * @param bool $suppress
3536 final public function setTrxEndCallbackSuppression( $suppress ) {
3537 $this->trxEndCallbacksSuppressed
= $suppress;
3541 * Actually consume and run any "on transaction idle/resolution" callbacks.
3543 * This method should not be used outside of Database/LoadBalancer
3545 * @param int $trigger IDatabase::TRIGGER_* constant
3546 * @return int Number of callbacks attempted
3550 public function runOnTransactionIdleCallbacks( $trigger ) {
3551 if ( $this->trxLevel() ) { // sanity
3552 throw new DBUnexpectedError( $this, __METHOD__
. ': a transaction is still open' );
3555 if ( $this->trxEndCallbacksSuppressed
) {
3560 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3561 /** @var Exception $e */
3562 $e = null; // first exception
3563 do { // callbacks may add callbacks :)
3564 $callbacks = array_merge(
3565 $this->trxIdleCallbacks
,
3566 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3568 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3569 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3571 // Only run trxSectionCancelCallbacks on rollback, not commit.
3572 // But always consume them.
3573 if ( $trigger === self
::TRIGGER_ROLLBACK
) {
3574 $callbacks = array_merge( $callbacks, $this->trxSectionCancelCallbacks
);
3576 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3578 foreach ( $callbacks as $callback ) {
3580 list( $phpCallback ) = $callback;
3581 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3583 // @phan-suppress-next-line PhanParamTooManyCallable
3584 call_user_func( $phpCallback, $trigger, $this );
3585 } catch ( Exception
$ex ) {
3586 call_user_func( $this->errorLogger
, $ex );
3588 // Some callbacks may use startAtomic/endAtomic, so make sure
3589 // their transactions are ended so other callbacks don't fail
3590 if ( $this->trxLevel() ) {
3591 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3595 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3597 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3601 } while ( count( $this->trxIdleCallbacks
) );
3603 if ( $e instanceof Exception
) {
3604 throw $e; // re-throw any first exception
3611 * Actually consume and run any "on transaction pre-commit" callbacks.
3613 * This method should not be used outside of Database/LoadBalancer
3616 * @return int Number of callbacks attempted
3619 public function runOnTransactionPreCommitCallbacks() {
3622 $e = null; // first exception
3623 do { // callbacks may add callbacks :)
3624 $callbacks = $this->trxPreCommitCallbacks
;
3625 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3626 foreach ( $callbacks as $callback ) {
3629 list( $phpCallback ) = $callback;
3630 $phpCallback( $this );
3631 } catch ( Exception
$ex ) {
3632 ( $this->errorLogger
)( $ex );
3636 } while ( count( $this->trxPreCommitCallbacks
) );
3638 if ( $e instanceof Exception
) {
3639 throw $e; // re-throw any first exception
3646 * Actually run any "atomic section cancel" callbacks.
3648 * @param int $trigger IDatabase::TRIGGER_* constant
3649 * @param AtomicSectionIdentifier[]|null $sectionIds Section IDs to cancel,
3650 * null on transaction rollback
3652 private function runOnAtomicSectionCancelCallbacks(
3653 $trigger, array $sectionIds = null
3655 /** @var Exception|Throwable $e */
3656 $e = null; // first exception
3660 $callbacks = $this->trxSectionCancelCallbacks
;
3661 $this->trxSectionCancelCallbacks
= []; // consumed (recursion guard)
3662 foreach ( $callbacks as $entry ) {
3663 if ( $sectionIds === null ||
in_array( $entry[2], $sectionIds, true ) ) {
3665 $entry[0]( $trigger, $this );
3666 } catch ( Exception
$ex ) {
3667 ( $this->errorLogger
)( $ex );
3669 } catch ( Throwable
$ex ) {
3674 $notCancelled[] = $entry;
3677 } while ( count( $this->trxSectionCancelCallbacks
) );
3678 $this->trxSectionCancelCallbacks
= $notCancelled;
3680 if ( $e !== null ) {
3681 throw $e; // re-throw any first Exception/Throwable
3686 * Actually run any "transaction listener" callbacks.
3688 * This method should not be used outside of Database/LoadBalancer
3690 * @param int $trigger IDatabase::TRIGGER_* constant
3694 public function runTransactionListenerCallbacks( $trigger ) {
3695 if ( $this->trxEndCallbacksSuppressed
) {
3699 /** @var Exception $e */
3700 $e = null; // first exception
3702 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3704 $phpCallback( $trigger, $this );
3705 } catch ( Exception
$ex ) {
3706 ( $this->errorLogger
)( $ex );
3711 if ( $e instanceof Exception
) {
3712 throw $e; // re-throw any first exception
3717 * Create a savepoint
3719 * This is used internally to implement atomic sections. It should not be
3723 * @param string $identifier Identifier for the savepoint
3724 * @param string $fname Calling function name
3726 protected function doSavepoint( $identifier, $fname ) {
3727 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3731 * Release a savepoint
3733 * This is used internally to implement atomic sections. It should not be
3737 * @param string $identifier Identifier for the savepoint
3738 * @param string $fname Calling function name
3740 protected function doReleaseSavepoint( $identifier, $fname ) {
3741 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3745 * Rollback to a savepoint
3747 * This is used internally to implement atomic sections. It should not be
3751 * @param string $identifier Identifier for the savepoint
3752 * @param string $fname Calling function name
3754 protected function doRollbackToSavepoint( $identifier, $fname ) {
3755 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3759 * @param string $fname
3762 private function nextSavepointId( $fname ) {
3763 $savepointId = self
::$SAVEPOINT_PREFIX . ++
$this->trxAtomicCounter
;
3764 if ( strlen( $savepointId ) > 30 ) {
3765 // 30 == Oracle's identifier length limit (pre 12c)
3766 // With a 22 character prefix, that puts the highest number at 99999999.
3767 throw new DBUnexpectedError(
3769 'There have been an excessively large number of atomic sections in a transaction'
3770 . " started by $this->trxFname (at $fname)"
3774 return $savepointId;
3777 final public function startAtomic(
3778 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3780 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ? self
::$NOT_APPLICABLE : null;
3782 if ( !$this->trxLevel() ) {
3783 $this->begin( $fname, self
::TRANSACTION_INTERNAL
); // sets trxAutomatic
3784 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3785 // in all changes being in one transaction to keep requests transactional.
3786 if ( $this->getFlag( self
::DBO_TRX
) ) {
3787 // Since writes could happen in between the topmost atomic sections as part
3788 // of the transaction, those sections will need savepoints.
3789 $savepointId = $this->nextSavepointId( $fname );
3790 $this->doSavepoint( $savepointId, $fname );
3792 $this->trxAutomaticAtomic
= true;
3794 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3795 $savepointId = $this->nextSavepointId( $fname );
3796 $this->doSavepoint( $savepointId, $fname );
3799 $sectionId = new AtomicSectionIdentifier
;
3800 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3801 $this->queryLogger
->debug( 'startAtomic: entering level ' .
3802 ( count( $this->trxAtomicLevels
) - 1 ) . " ($fname)" );
3807 final public function endAtomic( $fname = __METHOD__
) {
3808 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3809 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3812 // Check if the current section matches $fname
3813 $pos = count( $this->trxAtomicLevels
) - 1;
3814 list( $savedFname, $sectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3815 $this->queryLogger
->debug( "endAtomic: leaving level $pos ($fname)" );
3817 if ( $savedFname !== $fname ) {
3818 throw new DBUnexpectedError(
3820 "Invalid atomic section ended (got $fname but expected $savedFname)"
3824 // Remove the last section (no need to re-index the array)
3825 array_pop( $this->trxAtomicLevels
);
3827 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3828 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3829 } elseif ( $savepointId !== null && $savepointId !== self
::$NOT_APPLICABLE ) {
3830 $this->doReleaseSavepoint( $savepointId, $fname );
3833 // Hoist callback ownership for callbacks in the section that just ended;
3834 // all callbacks should have an owner that is present in trxAtomicLevels.
3835 $currentSectionId = $this->currentAtomicSectionId();
3836 if ( $currentSectionId ) {
3837 $this->reassignCallbacksForSection( $sectionId, $currentSectionId );
3841 final public function cancelAtomic(
3842 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3844 if ( !$this->trxLevel() ||
!$this->trxAtomicLevels
) {
3845 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)" );
3849 $newTopSection = $this->currentAtomicSectionId();
3851 $excisedFnames = [];
3852 if ( $sectionId !== null ) {
3853 // Find the (last) section with the given $sectionId
3855 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3856 if ( $asId === $sectionId ) {
3861 throw new DBUnexpectedError( $this, "Atomic section not found (for $fname)" );
3863 // Remove all descendant sections and re-index the array
3864 $len = count( $this->trxAtomicLevels
);
3865 for ( $i = $pos +
1; $i < $len; ++
$i ) {
3866 $excisedFnames[] = $this->trxAtomicLevels
[$i][0];
3867 $excisedIds[] = $this->trxAtomicLevels
[$i][1];
3869 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3870 $newTopSection = $this->currentAtomicSectionId();
3873 // Check if the current section matches $fname
3874 $pos = count( $this->trxAtomicLevels
) - 1;
3875 list( $savedFname, $savedSectionId, $savepointId ) = $this->trxAtomicLevels
[$pos];
3877 if ( $excisedFnames ) {
3878 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname) " .
3879 "and descendants " . implode( ', ', $excisedFnames ) );
3881 $this->queryLogger
->debug( "cancelAtomic: canceling level $pos ($savedFname)" );
3884 if ( $savedFname !== $fname ) {
3885 throw new DBUnexpectedError(
3887 "Invalid atomic section ended (got $fname but expected $savedFname)"
3891 // Remove the last section (no need to re-index the array)
3892 array_pop( $this->trxAtomicLevels
);
3893 $excisedIds[] = $savedSectionId;
3894 $newTopSection = $this->currentAtomicSectionId();
3896 if ( $savepointId !== null ) {
3897 // Rollback the transaction to the state just before this atomic section
3898 if ( $savepointId === self
::$NOT_APPLICABLE ) {
3899 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3900 // Note: rollback() will run trxSectionCancelCallbacks
3902 $this->doRollbackToSavepoint( $savepointId, $fname );
3903 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3904 $this->trxStatusIgnoredCause
= null;
3906 // Run trxSectionCancelCallbacks now.
3907 $this->runOnAtomicSectionCancelCallbacks( self
::TRIGGER_CANCEL
, $excisedIds );
3909 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3910 // Put the transaction into an error state if it's not already in one
3911 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3912 $this->trxStatusCause
= new DBUnexpectedError(
3914 "Uncancelable atomic section canceled (got $fname)"
3918 // Fix up callbacks owned by the sections that were just cancelled.
3919 // All callbacks should have an owner that is present in trxAtomicLevels.
3920 $this->modifyCallbacksForCancel( $excisedIds, $newTopSection );
3923 $this->affectedRowCount
= 0; // for the sake of consistency
3926 final public function doAtomicSection(
3927 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3929 $sectionId = $this->startAtomic( $fname, $cancelable );
3931 $res = $callback( $this, $fname );
3932 } catch ( Exception
$e ) {
3933 $this->cancelAtomic( $fname, $sectionId );
3937 $this->endAtomic( $fname );
3942 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3943 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3944 if ( !in_array( $mode, $modes, true ) ) {
3945 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'" );
3948 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3949 if ( $this->trxLevel() ) {
3950 if ( $this->trxAtomicLevels
) {
3951 $levels = $this->flatAtomicSectionList();
3952 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open";
3953 throw new DBUnexpectedError( $this, $msg );
3954 } elseif ( !$this->trxAutomatic
) {
3955 $msg = "$fname: Explicit transaction already active (from {$this->trxFname})";
3956 throw new DBUnexpectedError( $this, $msg );
3958 $msg = "$fname: Implicit transaction already active (from {$this->trxFname})";
3959 throw new DBUnexpectedError( $this, $msg );
3961 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3962 $msg = "$fname: Implicit transaction expected (DBO_TRX set)";
3963 throw new DBUnexpectedError( $this, $msg );
3966 $this->assertHasConnectionHandle();
3968 $this->doBegin( $fname );
3969 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3970 $this->trxStatus
= self
::STATUS_TRX_OK
;
3971 $this->trxStatusIgnoredCause
= null;
3972 $this->trxAtomicCounter
= 0;
3973 $this->trxTimestamp
= microtime( true );
3974 $this->trxFname
= $fname;
3975 $this->trxDoneWrites
= false;
3976 $this->trxAutomaticAtomic
= false;
3977 $this->trxAtomicLevels
= [];
3978 $this->trxWriteDuration
= 0.0;
3979 $this->trxWriteQueryCount
= 0;
3980 $this->trxWriteAffectedRows
= 0;
3981 $this->trxWriteAdjDuration
= 0.0;
3982 $this->trxWriteAdjQueryCount
= 0;
3983 $this->trxWriteCallers
= [];
3984 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3985 // Get an estimate of the replication lag before any such queries.
3986 $this->trxReplicaLag
= null; // clear cached value first
3987 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3988 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3989 // caller will think its OK to muck around with the transaction just because startAtomic()
3990 // has not yet completed (e.g. setting trxAtomicLevels).
3991 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3995 * Issues the BEGIN command to the database server.
3997 * @see Database::begin()
3998 * @param string $fname
4001 protected function doBegin( $fname ) {
4002 $this->query( 'BEGIN', $fname );
4005 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4006 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
4007 if ( !in_array( $flush, $modes, true ) ) {
4008 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'" );
4011 if ( $this->trxLevel() && $this->trxAtomicLevels
) {
4012 // There are still atomic sections open; this cannot be ignored
4013 $levels = $this->flatAtomicSectionList();
4014 throw new DBUnexpectedError(
4016 "$fname: Got COMMIT while atomic sections $levels are still open"
4020 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
4021 if ( !$this->trxLevel() ) {
4022 return; // nothing to do
4023 } elseif ( !$this->trxAutomatic
) {
4024 throw new DBUnexpectedError(
4026 "$fname: Flushing an explicit transaction, getting out of sync"
4029 } elseif ( !$this->trxLevel() ) {
4030 $this->queryLogger
->error(
4031 "$fname: No transaction to commit, something got out of sync" );
4032 return; // nothing to do
4033 } elseif ( $this->trxAutomatic
) {
4034 throw new DBUnexpectedError(
4036 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)"
4040 $this->assertHasConnectionHandle();
4042 $this->runOnTransactionPreCommitCallbacks();
4044 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
4045 $this->doCommit( $fname );
4046 $oldTrxShortId = $this->consumeTrxShortId();
4047 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4049 if ( $this->trxDoneWrites
) {
4050 $this->lastWriteTime
= microtime( true );
4051 $this->trxProfiler
->transactionWritingOut(
4053 $this->getDomainID(),
4056 $this->trxWriteAffectedRows
4060 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4061 if ( $flush !== self
::FLUSHING_ALL_PEERS
) {
4062 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
4063 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
4068 * Issues the COMMIT command to the database server.
4070 * @see Database::commit()
4071 * @param string $fname
4074 protected function doCommit( $fname ) {
4075 if ( $this->trxLevel() ) {
4076 $this->query( 'COMMIT', $fname );
4080 final public function rollback( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4081 $trxActive = $this->trxLevel();
4083 if ( $flush !== self
::FLUSHING_INTERNAL
4084 && $flush !== self
::FLUSHING_ALL_PEERS
4085 && $this->getFlag( self
::DBO_TRX
)
4087 throw new DBUnexpectedError(
4089 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)"
4094 $this->assertHasConnectionHandle();
4096 $this->doRollback( $fname );
4097 $oldTrxShortId = $this->consumeTrxShortId();
4098 $this->trxStatus
= self
::STATUS_TRX_NONE
;
4099 $this->trxAtomicLevels
= [];
4100 // Estimate the RTT via a query now that trxStatus is OK
4101 $writeTime = $this->pingAndCalculateLastTrxApplyTime();
4103 if ( $this->trxDoneWrites
) {
4104 $this->trxProfiler
->transactionWritingOut(
4106 $this->getDomainID(),
4109 $this->trxWriteAffectedRows
4114 // Clear any commit-dependant callbacks. They might even be present
4115 // only due to transaction rounds, with no SQL transaction being active
4116 $this->trxIdleCallbacks
= [];
4117 $this->trxPreCommitCallbacks
= [];
4119 // With FLUSHING_ALL_PEERS, callbacks will be explicitly run later
4120 if ( $trxActive && $flush !== self
::FLUSHING_ALL_PEERS
) {
4122 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
4123 } catch ( Exception
$e ) {
4124 // already logged; finish and let LoadBalancer move on during mass-rollback
4127 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
4128 } catch ( Exception
$e ) {
4129 // already logged; let LoadBalancer move on during mass-rollback
4132 $this->affectedRowCount
= 0; // for the sake of consistency
4137 * Issues the ROLLBACK command to the database server.
4139 * @see Database::rollback()
4140 * @param string $fname
4143 protected function doRollback( $fname ) {
4144 if ( $this->trxLevel() ) {
4145 # Disconnects cause rollback anyway, so ignore those errors
4146 $ignoreErrors = true;
4147 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
4151 public function flushSnapshot( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
4152 if ( $this->explicitTrxActive() ) {
4153 // Committing this transaction would break callers that assume it is still open
4154 throw new DBUnexpectedError(
4156 "$fname: Cannot flush snapshot; " .
4157 "explicit transaction '{$this->trxFname}' is still open"
4159 } elseif ( $this->writesOrCallbacksPending() ) {
4160 // This only flushes transactions to clear snapshots, not to write data
4161 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4162 throw new DBUnexpectedError(
4164 "$fname: Cannot flush snapshot; " .
4165 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4168 $this->trxLevel() &&
4169 $this->getTransactionRoundId() &&
4170 $flush !== self
::FLUSHING_INTERNAL
&&
4171 $flush !== self
::FLUSHING_ALL_PEERS
4173 $this->queryLogger
->warning(
4174 "$fname: Expected mass snapshot flush of all peer transactions " .
4175 "in the explicit transactions round '{$this->getTransactionRoundId()}'",
4176 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4180 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4183 public function explicitTrxActive() {
4184 return $this->trxLevel() && ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
4187 public function duplicateTableStructure(
4188 $oldName, $newName, $temporary = false, $fname = __METHOD__
4190 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4193 public function listTables( $prefix = null, $fname = __METHOD__
) {
4194 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4197 public function listViews( $prefix = null, $fname = __METHOD__
) {
4198 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
4201 public function timestamp( $ts = 0 ) {
4202 $t = new ConvertibleTimestamp( $ts );
4203 // Let errors bubble up to avoid putting garbage in the DB
4204 return $t->getTimestamp( TS_MW
);
4207 public function timestampOrNull( $ts = null ) {
4208 if ( is_null( $ts ) ) {
4211 return $this->timestamp( $ts );
4215 public function affectedRows() {
4216 return ( $this->affectedRowCount
=== null )
4217 ?
$this->fetchAffectedRowCount() // default to driver value
4218 : $this->affectedRowCount
;
4222 * @return int Number of retrieved rows according to the driver
4224 abstract protected function fetchAffectedRowCount();
4227 * Take a query result and wrap it in an iterable result wrapper if necessary.
4228 * Booleans are passed through as-is to indicate success/failure of write queries.
4230 * Once upon a time, Database::query() returned a bare MySQL result
4231 * resource, and it was necessary to call this function to convert it to
4232 * a wrapper. Nowadays, raw database objects are never exposed to external
4233 * callers, so this is unnecessary in external code.
4235 * @param bool|IResultWrapper|resource $result
4236 * @return bool|IResultWrapper
4238 protected function resultObject( $result ) {
4240 return false; // failed query
4241 } elseif ( $result instanceof IResultWrapper
) {
4243 } elseif ( $result === true ) {
4244 return $result; // succesful write query
4246 return new ResultWrapper( $this, $result );
4250 public function ping( &$rtt = null ) {
4251 // Avoid hitting the server if it was hit recently
4252 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::$PING_TTL ) {
4253 if ( !func_num_args() ||
$this->lastRoundTripEstimate
> 0 ) {
4254 $rtt = $this->lastRoundTripEstimate
;
4255 return true; // don't care about $rtt
4259 // This will reconnect if possible or return false if not
4260 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
4261 $ok = ( $this->query( self
::$PING_QUERY, __METHOD__
, true ) !== false );
4262 $this->restoreFlags( self
::RESTORE_PRIOR
);
4265 $rtt = $this->lastRoundTripEstimate
;
4272 * Close any existing (dead) database connection and open a new connection
4274 * @param string $fname
4275 * @return bool True if new connection is opened successfully, false if error
4277 protected function replaceLostConnection( $fname ) {
4278 $this->closeConnection();
4279 $this->conn
= false;
4281 $this->handleSessionLossPreconnect();
4288 $this->currentDomain
->getDatabase(),
4289 $this->currentDomain
->getSchema(),
4290 $this->tablePrefix()
4292 $this->lastPing
= microtime( true );
4295 $this->connLogger
->warning(
4296 $fname . ': lost connection to {dbserver}; reconnected',
4298 'dbserver' => $this->getServer(),
4299 'trace' => ( new RuntimeException() )->getTraceAsString()
4302 } catch ( DBConnectionError
$e ) {
4305 $this->connLogger
->error(
4306 $fname . ': lost connection to {dbserver} permanently',
4307 [ 'dbserver' => $this->getServer() ]
4311 $this->handleSessionLossPostconnect();
4316 public function getSessionLagStatus() {
4317 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
4321 * Get the replica DB lag when the current transaction started
4323 * This is useful when transactions might use snapshot isolation
4324 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
4325 * is this lag plus transaction duration. If they don't, it is still
4326 * safe to be pessimistic. This returns null if there is no transaction.
4328 * This returns null if the lag status for this transaction was not yet recorded.
4330 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
4333 final protected function getRecordedTransactionLagStatus() {
4334 return ( $this->trxLevel() && $this->trxReplicaLag
!== null )
4335 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
4340 * Get a replica DB lag estimate for this server
4342 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
4345 protected function getApproximateLagStatus() {
4347 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
4348 'since' => microtime( true )
4353 * Merge the result of getSessionLagStatus() for several DBs
4354 * using the most pessimistic values to estimate the lag of
4355 * any data derived from them in combination
4357 * This is information is useful for caching modules
4359 * @see WANObjectCache::set()
4360 * @see WANObjectCache::getWithSetCallback()
4362 * @param IDatabase $db1
4363 * @param IDatabase|null $db2 [optional]
4364 * @return array Map of values:
4365 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
4366 * - since: oldest UNIX timestamp of any of the DB lag estimates
4367 * - pending: whether any of the DBs have uncommitted changes
4371 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
4372 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
4373 foreach ( func_get_args() as $db ) {
4374 /** @var IDatabase $db */
4375 $status = $db->getSessionLagStatus();
4376 if ( $status['lag'] === false ) {
4377 $res['lag'] = false;
4378 } elseif ( $res['lag'] !== false ) {
4379 $res['lag'] = max( $res['lag'], $status['lag'] );
4381 $res['since'] = min( $res['since'], $status['since'] );
4382 $res['pending'] = $res['pending'] ?
: $db->writesPending();
4388 public function getLag() {
4389 if ( $this->getLBInfo( 'master' ) ) {
4390 return 0; // this is the master
4391 } elseif ( $this->getLBInfo( 'is static' ) ) {
4392 return 0; // static dataset
4395 return $this->doGetLag();
4398 protected function doGetLag() {
4402 public function maxListLen() {
4406 public function encodeBlob( $b ) {
4410 public function decodeBlob( $b ) {
4411 if ( $b instanceof Blob
) {
4417 public function setSessionOptions( array $options ) {
4420 public function sourceFile(
4422 callable
$lineCallback = null,
4423 callable
$resultCallback = null,
4425 callable
$inputCallback = null
4427 AtEase
::suppressWarnings();
4428 $fp = fopen( $filename, 'r' );
4429 AtEase
::restoreWarnings();
4431 if ( $fp === false ) {
4432 throw new RuntimeException( "Could not open \"{$filename}\"" );
4436 $fname = __METHOD__
. "( $filename )";
4440 $error = $this->sourceStream(
4441 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4442 } catch ( Exception
$e ) {
4452 public function setSchemaVars( $vars ) {
4453 $this->schemaVars
= $vars;
4456 public function sourceStream(
4458 callable
$lineCallback = null,
4459 callable
$resultCallback = null,
4460 $fname = __METHOD__
,
4461 callable
$inputCallback = null
4463 $delimiterReset = new ScopedCallback(
4464 function ( $delimiter ) {
4465 $this->delimiter
= $delimiter;
4467 [ $this->delimiter
]
4471 while ( !feof( $fp ) ) {
4472 if ( $lineCallback ) {
4473 call_user_func( $lineCallback );
4476 $line = trim( fgets( $fp ) );
4478 if ( $line == '' ) {
4482 if ( $line[0] == '-' && $line[1] == '-' ) {
4490 $done = $this->streamStatementEnd( $cmd, $line );
4494 if ( $done ||
feof( $fp ) ) {
4495 $cmd = $this->replaceVars( $cmd );
4497 if ( $inputCallback ) {
4498 $callbackResult = $inputCallback( $cmd );
4500 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4501 $cmd = $callbackResult;
4506 $res = $this->query( $cmd, $fname );
4508 if ( $resultCallback ) {
4509 $resultCallback( $res, $this );
4512 if ( $res === false ) {
4513 $err = $this->lastError();
4515 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4522 ScopedCallback
::consume( $delimiterReset );
4527 * Called by sourceStream() to check if we've reached a statement end
4529 * @param string &$sql SQL assembled so far
4530 * @param string &$newLine New line about to be added to $sql
4531 * @return bool Whether $newLine contains end of the statement
4533 public function streamStatementEnd( &$sql, &$newLine ) {
4534 if ( $this->delimiter
) {
4536 $newLine = preg_replace(
4537 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4538 if ( $newLine != $prev ) {
4547 * Database independent variable replacement. Replaces a set of variables
4548 * in an SQL statement with their contents as given by $this->getSchemaVars().
4550 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4552 * - '{$var}' should be used for text and is passed through the database's
4554 * - `{$var}` should be used for identifiers (e.g. table and database names).
4555 * It is passed through the database's addIdentifierQuotes method which
4556 * can be overridden if the database uses something other than backticks.
4557 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4558 * database's tableName method.
4559 * - / *i* / passes the name that follows through the database's indexName method.
4560 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4561 * its use should be avoided. In 1.24 and older, string encoding was applied.
4563 * @param string $ins SQL statement to replace variables in
4564 * @return string The new SQL statement with variables replaced
4566 protected function replaceVars( $ins ) {
4567 $vars = $this->getSchemaVars();
4568 return preg_replace_callback(
4570 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4571 \'\{\$ (\w+) }\' | # 3. addQuotes
4572 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4573 /\*\$ (\w+) \*/ # 5. leave unencoded
4575 function ( $m ) use ( $vars ) {
4576 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4577 // check for both nonexistent keys *and* the empty string.
4578 if ( isset( $m[1] ) && $m[1] !== '' ) {
4579 if ( $m[1] === 'i' ) {
4580 return $this->indexName( $m[2] );
4582 return $this->tableName( $m[2] );
4584 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4585 return $this->addQuotes( $vars[$m[3]] );
4586 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4587 return $this->addIdentifierQuotes( $vars[$m[4]] );
4588 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4589 return $vars[$m[5]];
4599 * Get schema variables. If none have been set via setSchemaVars(), then
4600 * use some defaults from the current object.
4604 protected function getSchemaVars() {
4605 if ( $this->schemaVars
) {
4606 return $this->schemaVars
;
4608 return $this->getDefaultSchemaVars();
4613 * Get schema variables to use if none have been set via setSchemaVars().
4615 * Override this in derived classes to provide variables for tables.sql
4616 * and SQL patch files.
4620 protected function getDefaultSchemaVars() {
4624 public function lockIsFree( $lockName, $method ) {
4625 // RDBMs methods for checking named locks may or may not count this thread itself.
4626 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4627 // the behavior choosen by the interface for this method.
4628 return !isset( $this->sessionNamedLocks
[$lockName] );
4631 public function lock( $lockName, $method, $timeout = 5 ) {
4632 $this->sessionNamedLocks
[$lockName] = 1;
4637 public function unlock( $lockName, $method ) {
4638 unset( $this->sessionNamedLocks
[$lockName] );
4643 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4644 if ( $this->writesOrCallbacksPending() ) {
4645 // This only flushes transactions to clear snapshots, not to write data
4646 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4647 throw new DBUnexpectedError(
4649 "$fname: Cannot flush pre-lock snapshot; " .
4650 "writes from transaction {$this->trxFname} are still pending ($fnames)"
4654 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4658 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4659 if ( $this->trxLevel() ) {
4660 // There is a good chance an exception was thrown, causing any early return
4661 // from the caller. Let any error handler get a chance to issue rollback().
4662 // If there isn't one, let the error bubble up and trigger server-side rollback.
4663 $this->onTransactionResolution(
4664 function () use ( $lockKey, $fname ) {
4665 $this->unlock( $lockKey, $fname );
4670 $this->unlock( $lockKey, $fname );
4674 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4679 public function namedLocksEnqueue() {
4683 public function tableLocksHaveTransactionScope() {
4687 final public function lockTables( array $read, array $write, $method ) {
4688 if ( $this->writesOrCallbacksPending() ) {
4689 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending" );
4692 if ( $this->tableLocksHaveTransactionScope() ) {
4693 $this->startAtomic( $method );
4696 return $this->doLockTables( $read, $write, $method );
4700 * Helper function for lockTables() that handles the actual table locking
4702 * @param array $read Array of tables to lock for read access
4703 * @param array $write Array of tables to lock for write access
4704 * @param string $method Name of caller
4707 protected function doLockTables( array $read, array $write, $method ) {
4711 final public function unlockTables( $method ) {
4712 if ( $this->tableLocksHaveTransactionScope() ) {
4713 $this->endAtomic( $method );
4715 return true; // locks released on COMMIT/ROLLBACK
4718 return $this->doUnlockTables( $method );
4722 * Helper function for unlockTables() that handles the actual table unlocking
4724 * @param string $method Name of caller
4727 protected function doUnlockTables( $method ) {
4733 * @param string $tableName
4734 * @param string $fName
4735 * @return bool|IResultWrapper
4738 public function dropTable( $tableName, $fName = __METHOD__
) {
4739 if ( !$this->tableExists( $tableName, $fName ) ) {
4742 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4744 return $this->query( $sql, $fName );
4747 public function getInfinity() {
4751 public function encodeExpiry( $expiry ) {
4752 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4753 ?
$this->getInfinity()
4754 : $this->timestamp( $expiry );
4757 public function decodeExpiry( $expiry, $format = TS_MW
) {
4758 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4762 return ConvertibleTimestamp
::convert( $format, $expiry );
4765 public function setBigSelects( $value = true ) {
4769 public function isReadOnly() {
4770 return ( $this->getReadOnlyReason() !== false );
4774 * @return string|bool Reason this DB is read-only or false if it is not
4776 protected function getReadOnlyReason() {
4777 $reason = $this->getLBInfo( 'readOnlyReason' );
4778 if ( is_string( $reason ) ) {
4780 } elseif ( $this->getLBInfo( 'replica' ) ) {
4781 return "Server is configured in the role of a read-only replica database.";
4787 public function setTableAliases( array $aliases ) {
4788 $this->tableAliases
= $aliases;
4791 public function setIndexAliases( array $aliases ) {
4792 $this->indexAliases
= $aliases;
4800 protected function hasFlags( $field, $flags ) {
4801 return ( ( $field & $flags ) === $flags );
4805 * Get the underlying binding connection handle
4807 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4808 * This catches broken callers than catch and ignore disconnection exceptions.
4809 * Unlike checking isOpen(), this is safe to call inside of open().
4812 * @throws DBUnexpectedError
4815 protected function getBindingHandle() {
4816 if ( !$this->conn
) {
4817 throw new DBUnexpectedError(
4819 'DB connection was already closed or the connection dropped'
4826 public function __toString() {
4827 // spl_object_id is PHP >= 7.2
4828 $id = function_exists( 'spl_object_id' )
4829 ?
spl_object_id( $this )
4830 : spl_object_hash( $this );
4832 $description = $this->getType() . ' object #' . $id;
4833 if ( is_resource( $this->conn
) ) {
4834 $description .= ' (' . (string)$this->conn
. ')'; // "resource id #<ID>"
4835 } elseif ( is_object( $this->conn
) ) {
4836 // spl_object_id is PHP >= 7.2
4837 $handleId = function_exists( 'spl_object_id' )
4838 ?
spl_object_id( $this->conn
)
4839 : spl_object_hash( $this->conn
);
4840 $description .= " (handle id #$handleId)";
4843 return $description;
4847 * Make sure that copies do not share the same client binding handle
4848 * @throws DBConnectionError
4850 public function __clone() {
4851 $this->connLogger
->warning(
4852 "Cloning " . static::class . " is not recommended; forking connection",
4853 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
4856 if ( $this->isOpen() ) {
4857 // Open a new connection resource without messing with the old one
4858 $this->conn
= false;
4859 $this->trxEndCallbacks
= []; // don't copy
4860 $this->trxSectionCancelCallbacks
= []; // don't copy
4861 $this->handleSessionLossPreconnect(); // no trx or locks anymore
4866 $this->currentDomain
->getDatabase(),
4867 $this->currentDomain
->getSchema(),
4868 $this->tablePrefix()
4870 $this->lastPing
= microtime( true );
4875 * Called by serialize. Throw an exception when DB connection is serialized.
4876 * This causes problems on some database engines because the connection is
4877 * not restored on unserialize.
4879 public function __sleep() {
4880 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4881 'the connection is not restored on wakeup' );
4885 * Run a few simple sanity checks and close dangling connections
4887 public function __destruct() {
4888 if ( $this->trxLevel() && $this->trxDoneWrites
) {
4889 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})" );
4892 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4893 if ( $danglingWriters ) {
4894 $fnames = implode( ', ', $danglingWriters );
4895 trigger_error( "DB transaction writes or callbacks still pending ($fnames)" );
4898 if ( $this->conn
) {
4899 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4900 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4901 AtEase
::suppressWarnings();
4902 $this->closeConnection();
4903 AtEase
::restoreWarnings();
4910 * @deprecated since 1.28
4912 class_alias( Database
::class, 'DatabaseBase' );
4915 * @deprecated since 1.29
4917 class_alias( Database
::class, 'Database' );