3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
38 use UnexpectedValueException
;
43 * Relational database abstraction object
48 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
49 /** Number of times to re-try an operation in case of deadlock */
50 const DEADLOCK_TRIES
= 4;
51 /** Minimum time to wait before retry, in microseconds */
52 const DEADLOCK_DELAY_MIN
= 500000;
53 /** Maximum time to wait before retry */
54 const DEADLOCK_DELAY_MAX
= 1500000;
56 /** How long before it is worth doing a dummy query to test the connection */
58 const PING_QUERY
= 'SELECT 1 AS ping';
60 const TINY_WRITE_SEC
= 0.010;
61 const SLOW_WRITE_SEC
= 0.500;
62 const SMALL_WRITE_ROWS
= 100;
64 /** @var string Whether lock granularity is on the level of the entire database */
65 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
67 /** @var int New Database instance will not be connected yet when returned */
68 const NEW_UNCONNECTED
= 0;
69 /** @var int New Database instance will already be connected when returned */
70 const NEW_CONNECTED
= 1;
72 /** @var string SQL query */
73 protected $lastQuery = '';
74 /** @var float|bool UNIX timestamp of last write query */
75 protected $lastWriteTime = false;
76 /** @var string|bool */
77 protected $phpError = false;
78 /** @var string Server that this instance is currently connected to */
80 /** @var string User that this instance is currently connected under the name of */
82 /** @var string Password used to establish the current connection */
84 /** @var string Database that this instance is currently connected to */
86 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
87 protected $tableAliases = [];
88 /** @var string[] Map of (index alias => index) */
89 protected $indexAliases = [];
90 /** @var bool Whether this PHP instance is for a CLI script */
92 /** @var string Agent name for query profiling */
94 /** @var array Parameters used by initConnection() to establish a connection */
95 protected $connectionParams = [];
96 /** @var BagOStuff APC cache */
98 /** @var LoggerInterface */
99 protected $connLogger;
100 /** @var LoggerInterface */
101 protected $queryLogger;
102 /** @var callback Error logging callback */
103 protected $errorLogger;
104 /** @var callback Deprecation logging callback */
105 protected $deprecationLogger;
107 /** @var resource|null Database connection */
108 protected $conn = null;
110 protected $opened = false;
112 /** @var array[] List of (callable, method name) */
113 protected $trxIdleCallbacks = [];
114 /** @var array[] List of (callable, method name) */
115 protected $trxPreCommitCallbacks = [];
116 /** @var array[] List of (callable, method name) */
117 protected $trxEndCallbacks = [];
118 /** @var callable[] Map of (name => callable) */
119 protected $trxRecurringCallbacks = [];
120 /** @var bool Whether to suppress triggering of transaction end callbacks */
121 protected $trxEndCallbacksSuppressed = false;
124 protected $tablePrefix = '';
126 protected $schema = '';
130 protected $lbInfo = [];
131 /** @var array|bool */
132 protected $schemaVars = false;
134 protected $sessionVars = [];
135 /** @var array|null */
136 protected $preparedArgs;
137 /** @var string|bool|null Stashed value of html_errors INI setting */
138 protected $htmlErrors;
140 protected $delimiter = ';';
141 /** @var DatabaseDomain */
142 protected $currentDomain;
143 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
144 protected $affectedRowCount;
147 * @var int Transaction status
149 protected $trxStatus = self
::STATUS_TRX_NONE
;
151 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
153 protected $trxStatusCause;
155 * @var array|null If wasKnownStatementRollbackError() prevented trxStatus from being set,
156 * the relevant details are stored here.
158 protected $trxStatusIgnoredCause;
160 * Either 1 if a transaction is active or 0 otherwise.
161 * The other Trx fields may not be meaningfull if this is 0.
165 protected $trxLevel = 0;
167 * Either a short hexidecimal string if a transaction is active or ""
170 * @see Database::trxLevel
172 protected $trxShortId = '';
174 * The UNIX time that the transaction started. Callers can assume that if
175 * snapshot isolation is used, then the data is *at least* up to date to that
176 * point (possibly more up-to-date since the first SELECT defines the snapshot).
179 * @see Database::trxLevel
181 private $trxTimestamp = null;
182 /** @var float Lag estimate at the time of BEGIN */
183 private $trxReplicaLag = null;
185 * Remembers the function name given for starting the most recent transaction via begin().
186 * Used to provide additional context for error reporting.
189 * @see Database::trxLevel
191 private $trxFname = null;
193 * Record if possible write queries were done in the last transaction started
196 * @see Database::trxLevel
198 private $trxDoneWrites = false;
200 * Record if the current transaction was started implicitly due to DBO_TRX being set.
203 * @see Database::trxLevel
205 private $trxAutomatic = false;
207 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
211 private $trxAtomicCounter = 0;
213 * Array of levels of atomicity within transactions
215 * @var array List of (name, unique ID, savepoint ID)
217 private $trxAtomicLevels = [];
219 * Record if the current transaction was started implicitly by Database::startAtomic
223 private $trxAutomaticAtomic = false;
225 * Track the write query callers of the current transaction
229 private $trxWriteCallers = [];
231 * @var float Seconds spent in write queries for the current transaction
233 private $trxWriteDuration = 0.0;
235 * @var int Number of write queries for the current transaction
237 private $trxWriteQueryCount = 0;
239 * @var int Number of rows affected by write queries for the current transaction
241 private $trxWriteAffectedRows = 0;
243 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
245 private $trxWriteAdjDuration = 0.0;
247 * @var int Number of write queries counted in trxWriteAdjDuration
249 private $trxWriteAdjQueryCount = 0;
251 * @var float RTT time estimate
253 private $rttEstimate = 0.0;
255 /** @var array Map of (name => 1) for locks obtained via lock() */
256 private $namedLocksHeld = [];
257 /** @var array Map of (table name => 1) for TEMPORARY tables */
258 protected $sessionTempTables = [];
260 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
261 private $lazyMasterHandle;
263 /** @var float UNIX timestamp */
264 protected $lastPing = 0.0;
266 /** @var int[] Prior flags member variable values */
267 private $priorFlags = [];
269 /** @var object|string Class name or object With profileIn/profileOut methods */
271 /** @var TransactionProfiler */
272 protected $trxProfiler;
275 protected $nonNativeInsertSelectBatchSize = 10000;
277 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
278 const STATUS_TRX_ERROR
= 1;
279 /** @var int Transaction is active and in a normal state */
280 const STATUS_TRX_OK
= 2;
281 /** @var int No transaction is active */
282 const STATUS_TRX_NONE
= 3;
285 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
286 * @param array $params Parameters passed from Database::factory()
288 protected function __construct( array $params ) {
289 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
290 $this->connectionParams
[$name] = $params[$name];
293 $this->schema
= $params['schema'];
294 $this->tablePrefix
= $params['tablePrefix'];
296 $this->cliMode
= $params['cliMode'];
297 // Agent name is added to SQL queries in a comment, so make sure it can't break out
298 $this->agent
= str_replace( '/', '-', $params['agent'] );
300 $this->flags
= $params['flags'];
301 if ( $this->flags
& self
::DBO_DEFAULT
) {
302 if ( $this->cliMode
) {
303 $this->flags
&= ~self
::DBO_TRX
;
305 $this->flags |
= self
::DBO_TRX
;
308 // Disregard deprecated DBO_IGNORE flag (T189999)
309 $this->flags
&= ~self
::DBO_IGNORE
;
311 $this->sessionVars
= $params['variables'];
313 $this->srvCache
= isset( $params['srvCache'] )
314 ?
$params['srvCache']
315 : new HashBagOStuff();
317 $this->profiler
= $params['profiler'];
318 $this->trxProfiler
= $params['trxProfiler'];
319 $this->connLogger
= $params['connLogger'];
320 $this->queryLogger
= $params['queryLogger'];
321 $this->errorLogger
= $params['errorLogger'];
322 $this->deprecationLogger
= $params['deprecationLogger'];
324 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
325 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
328 // Set initial dummy domain until open() sets the final DB/prefix
329 $this->currentDomain
= DatabaseDomain
::newUnspecified();
333 * Initialize the connection to the database over the wire (or to local files)
335 * @throws LogicException
336 * @throws InvalidArgumentException
337 * @throws DBConnectionError
340 final public function initConnection() {
341 if ( $this->isOpen() ) {
342 throw new LogicException( __METHOD__
. ': already connected.' );
344 // Establish the connection
345 $this->doInitConnection();
346 // Set the domain object after open() sets the relevant fields
347 if ( $this->dbName
!= '' ) {
348 // Domains with server scope but a table prefix are not used by IDatabase classes
349 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
354 * Actually connect to the database over the wire (or to local files)
356 * @throws InvalidArgumentException
357 * @throws DBConnectionError
360 protected function doInitConnection() {
361 if ( strlen( $this->connectionParams
['user'] ) ) {
363 $this->connectionParams
['host'],
364 $this->connectionParams
['user'],
365 $this->connectionParams
['password'],
366 $this->connectionParams
['dbname']
369 throw new InvalidArgumentException( "No database user provided." );
374 * Construct a Database subclass instance given a database type and parameters
376 * This also connects to the database immediately upon object construction
378 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
379 * @param array $p Parameter map with keys:
380 * - host : The hostname of the DB server
381 * - user : The name of the database user the client operates under
382 * - password : The password for the database user
383 * - dbname : The name of the database to use where queries do not specify one.
384 * The database must exist or an error might be thrown. Setting this to the empty string
385 * will avoid any such errors and make the handle have no implicit database scope. This is
386 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
387 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
388 * in which user names and such are defined, e.g. users are database-specific in Postgres.
389 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
390 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
391 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
392 * recognized in queries. This can be used in place of schemas for handle site farms.
393 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
394 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
395 * flag in place UNLESS this this database simply acts as a key/value store.
396 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
397 * 'mysqli' driver; the old one 'mysql' has been removed.
398 * - variables: Optional map of session variables to set after connecting. This can be
399 * used to adjust lock timeouts or encoding modes and the like.
400 * - connLogger: Optional PSR-3 logger interface instance.
401 * - queryLogger: Optional PSR-3 logger interface instance.
402 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
403 * These will be called in query(), using a simplified version of the SQL that also
404 * includes the agent as a SQL comment.
405 * - trxProfiler: Optional TransactionProfiler instance.
406 * - errorLogger: Optional callback that takes an Exception and logs it.
407 * - deprecationLogger: Optional callback that takes a string and logs it.
408 * - cliMode: Whether to consider the execution context that of a CLI script.
409 * - agent: Optional name used to identify the end-user in query profiling/logging.
410 * - srvCache: Optional BagOStuff instance to an APC-style cache.
411 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
412 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
413 * @return Database|null If the database driver or extension cannot be found
414 * @throws InvalidArgumentException If the database driver or extension cannot be found
417 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
418 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
420 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
421 // Resolve some defaults for b/c
422 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
423 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
424 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
425 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
426 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
427 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
428 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
429 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
430 $p['cliMode'] = isset( $p['cliMode'] )
432 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
433 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
434 if ( !isset( $p['connLogger'] ) ) {
435 $p['connLogger'] = new NullLogger();
437 if ( !isset( $p['queryLogger'] ) ) {
438 $p['queryLogger'] = new NullLogger();
440 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
441 if ( !isset( $p['trxProfiler'] ) ) {
442 $p['trxProfiler'] = new TransactionProfiler();
444 if ( !isset( $p['errorLogger'] ) ) {
445 $p['errorLogger'] = function ( Exception
$e ) {
446 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
449 if ( !isset( $p['deprecationLogger'] ) ) {
450 $p['deprecationLogger'] = function ( $msg ) {
451 trigger_error( $msg, E_USER_DEPRECATED
);
455 /** @var Database $conn */
456 $conn = new $class( $p );
457 if ( $connect == self
::NEW_CONNECTED
) {
458 $conn->initConnection();
468 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
469 * @param string|null $driver Optional name of a specific DB client driver
470 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
471 * @throws InvalidArgumentException
474 final public static function attributesFromType( $dbType, $driver = null ) {
475 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
477 $class = self
::getClass( $dbType, $driver );
479 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
483 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
484 * @param string|null $driver Optional name of a specific DB client driver
485 * @return string Database subclass name to use
486 * @throws InvalidArgumentException
488 private static function getClass( $dbType, $driver = null ) {
489 // For database types with built-in support, the below maps type to IDatabase
490 // implementations. For types with multipe driver implementations (PHP extensions),
491 // an array can be used, keyed by extension name. In case of an array, the
492 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
493 // we auto-detect the first available driver. For types without built-in support,
494 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
495 static $builtinTypes = [
496 'mssql' => DatabaseMssql
::class,
497 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
498 'sqlite' => DatabaseSqlite
::class,
499 'postgres' => DatabasePostgres
::class,
502 $dbType = strtolower( $dbType );
505 if ( isset( $builtinTypes[$dbType] ) ) {
506 $possibleDrivers = $builtinTypes[$dbType];
507 if ( is_string( $possibleDrivers ) ) {
508 $class = $possibleDrivers;
510 if ( (string)$driver !== '' ) {
511 if ( !isset( $possibleDrivers[$driver] ) ) {
512 throw new InvalidArgumentException( __METHOD__
.
513 " type '$dbType' does not support driver '{$driver}'" );
515 $class = $possibleDrivers[$driver];
518 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
519 if ( extension_loaded( $posDriver ) ) {
520 $class = $possibleClass;
527 $class = 'Database' . ucfirst( $dbType );
530 if ( $class === false ) {
531 throw new InvalidArgumentException( __METHOD__
.
532 " no viable database extension found for type '$dbType'" );
539 * @return array Map of (Database::ATTRIBUTE_* constant => value
542 protected static function getAttributes() {
547 * Set the PSR-3 logger interface to use for query logging. (The logger
548 * interfaces for connection logging and error logging can be set with the
551 * @param LoggerInterface $logger
553 public function setLogger( LoggerInterface
$logger ) {
554 $this->queryLogger
= $logger;
557 public function getServerInfo() {
558 return $this->getServerVersion();
561 public function bufferResults( $buffer = null ) {
562 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
563 if ( $buffer !== null ) {
565 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
566 : $this->setFlag( self
::DBO_NOBUFFER
);
572 public function trxLevel() {
573 return $this->trxLevel
;
576 public function trxTimestamp() {
577 return $this->trxLevel ?
$this->trxTimestamp
: null;
581 * @return int One of the STATUS_TRX_* class constants
584 public function trxStatus() {
585 return $this->trxStatus
;
588 public function tablePrefix( $prefix = null ) {
589 $old = $this->tablePrefix
;
590 if ( $prefix !== null ) {
591 $this->tablePrefix
= $prefix;
592 $this->currentDomain
= ( $this->dbName
!= '' )
593 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
594 : DatabaseDomain
::newUnspecified();
600 public function dbSchema( $schema = null ) {
601 $old = $this->schema
;
602 if ( $schema !== null ) {
603 $this->schema
= $schema;
609 public function getLBInfo( $name = null ) {
610 if ( is_null( $name ) ) {
611 return $this->lbInfo
;
613 if ( array_key_exists( $name, $this->lbInfo
) ) {
614 return $this->lbInfo
[$name];
621 public function setLBInfo( $name, $value = null ) {
622 if ( is_null( $value ) ) {
623 $this->lbInfo
= $name;
625 $this->lbInfo
[$name] = $value;
629 public function setLazyMasterHandle( IDatabase
$conn ) {
630 $this->lazyMasterHandle
= $conn;
634 * @return IDatabase|null
635 * @see setLazyMasterHandle()
638 protected function getLazyMasterHandle() {
639 return $this->lazyMasterHandle
;
642 public function implicitGroupby() {
646 public function implicitOrderby() {
650 public function lastQuery() {
651 return $this->lastQuery
;
654 public function doneWrites() {
655 return (bool)$this->lastWriteTime
;
658 public function lastDoneWrites() {
659 return $this->lastWriteTime ?
: false;
662 public function writesPending() {
663 return $this->trxLevel
&& $this->trxDoneWrites
;
666 public function writesOrCallbacksPending() {
667 return $this->trxLevel
&& (
668 $this->trxDoneWrites ||
669 $this->trxIdleCallbacks ||
670 $this->trxPreCommitCallbacks ||
671 $this->trxEndCallbacks
676 * @return string|null
678 final protected function getTransactionRoundId() {
679 // If transaction round participation is enabled, see if one is active
680 if ( $this->getFlag( self
::DBO_TRX
) ) {
681 $id = $this->getLBInfo( 'trxRoundId' );
683 return is_string( $id ) ?
$id : null;
689 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
690 if ( !$this->trxLevel
) {
692 } elseif ( !$this->trxDoneWrites
) {
697 case self
::ESTIMATE_DB_APPLY
:
699 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
700 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
701 // For omitted queries, make them count as something at least
702 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
703 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
706 default: // everything
707 return $this->trxWriteDuration
;
711 public function pendingWriteCallers() {
712 return $this->trxLevel ?
$this->trxWriteCallers
: [];
715 public function pendingWriteRowsAffected() {
716 return $this->trxWriteAffectedRows
;
720 * Get the list of method names that have pending write queries or callbacks
721 * for this transaction
725 protected function pendingWriteAndCallbackCallers() {
726 if ( !$this->trxLevel
) {
730 $fnames = $this->trxWriteCallers
;
732 $this->trxIdleCallbacks
,
733 $this->trxPreCommitCallbacks
,
734 $this->trxEndCallbacks
736 foreach ( $callbacks as $callback ) {
737 $fnames[] = $callback[1];
747 private function flatAtomicSectionList() {
748 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
749 return $accum === null ?
$v[0] : "$accum, " . $v[0];
753 public function isOpen() {
754 return $this->opened
;
757 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
758 if ( ( $flag & self
::DBO_IGNORE
) ) {
759 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
762 if ( $remember === self
::REMEMBER_PRIOR
) {
763 array_push( $this->priorFlags
, $this->flags
);
765 $this->flags |
= $flag;
768 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
769 if ( ( $flag & self
::DBO_IGNORE
) ) {
770 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
773 if ( $remember === self
::REMEMBER_PRIOR
) {
774 array_push( $this->priorFlags
, $this->flags
);
776 $this->flags
&= ~
$flag;
779 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
780 if ( !$this->priorFlags
) {
784 if ( $state === self
::RESTORE_INITIAL
) {
785 $this->flags
= reset( $this->priorFlags
);
786 $this->priorFlags
= [];
788 $this->flags
= array_pop( $this->priorFlags
);
792 public function getFlag( $flag ) {
793 return !!( $this->flags
& $flag );
797 * @param string $name Class field name
799 * @deprecated Since 1.28
801 public function getProperty( $name ) {
805 public function getDomainID() {
806 return $this->currentDomain
->getId();
809 final public function getWikiID() {
810 return $this->getDomainID();
814 * Get information about an index into an object
815 * @param string $table Table name
816 * @param string $index Index name
817 * @param string $fname Calling function name
818 * @return mixed Database-specific index description class or false if the index does not exist
820 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
823 * Wrapper for addslashes()
825 * @param string $s String to be slashed.
826 * @return string Slashed string.
828 abstract function strencode( $s );
831 * Set a custom error handler for logging errors during database connection
833 protected function installErrorHandler() {
834 $this->phpError
= false;
835 $this->htmlErrors
= ini_set( 'html_errors', '0' );
836 set_error_handler( [ $this, 'connectionErrorLogger' ] );
840 * Restore the previous error handler and return the last PHP error for this DB
842 * @return bool|string
844 protected function restoreErrorHandler() {
845 restore_error_handler();
846 if ( $this->htmlErrors
!== false ) {
847 ini_set( 'html_errors', $this->htmlErrors
);
850 return $this->getLastPHPError();
854 * @return string|bool Last PHP error for this DB (typically connection errors)
856 protected function getLastPHPError() {
857 if ( $this->phpError
) {
858 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
859 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
868 * Error handler for logging errors during database connection
869 * This method should not be used outside of Database classes
872 * @param string $errstr
874 public function connectionErrorLogger( $errno, $errstr ) {
875 $this->phpError
= $errstr;
879 * Create a log context to pass to PSR-3 logger functions.
881 * @param array $extras Additional data to add to context
884 protected function getLogContext( array $extras = [] ) {
887 'db_server' => $this->server
,
888 'db_name' => $this->dbName
,
889 'db_user' => $this->user
,
895 final public function close() {
896 $exception = null; // error to throw after disconnecting
899 // Resolve any dangling transaction first
900 if ( $this->trxLevel
) {
901 // Meaningful transactions should ideally have been resolved by now
902 if ( $this->writesOrCallbacksPending() ) {
903 $this->queryLogger
->warning(
904 __METHOD__
. ": writes or callbacks still pending.",
905 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
907 // Cannot let incomplete atomic sections be committed
908 if ( $this->trxAtomicLevels
) {
909 $levels = $this->flatAtomicSectionList();
910 $exception = new DBUnexpectedError(
912 __METHOD__
. ": atomic sections $levels are still open."
914 // Check if it is possible to properly commit and trigger callbacks
915 } elseif ( $this->trxEndCallbacksSuppressed
) {
916 $exception = new DBUnexpectedError(
918 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
922 // Commit or rollback the changes and run any callbacks as needed
923 if ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& !$exception ) {
924 $this->commit( __METHOD__
, self
::TRANSACTION_INTERNAL
);
926 $this->rollback( __METHOD__
, self
::TRANSACTION_INTERNAL
);
929 // Close the actual connection in the binding handle
930 $closed = $this->closeConnection();
933 $closed = true; // already closed; nothing to do
936 $this->opened
= false;
938 // Throw any unexpected errors after having disconnected
939 if ( $exception instanceof Exception
) {
943 // Sanity check that no callbacks are dangling
945 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
947 throw new RuntimeException(
948 "Transaction callbacks are still pending:\n" .
949 implode( ', ', $this->pendingWriteAndCallbackCallers() )
957 * Make sure isOpen() returns true as a sanity check
959 * @throws DBUnexpectedError
961 protected function assertOpen() {
962 if ( !$this->isOpen() ) {
963 throw new DBUnexpectedError( $this, "DB connection was already closed." );
968 * Closes underlying database connection
970 * @return bool Whether connection was closed successfully
972 abstract protected function closeConnection();
975 * @param string $error Fallback error message, used if none is given by DB
976 * @throws DBConnectionError
978 public function reportConnectionError( $error = 'Unknown error' ) {
979 $myError = $this->lastError();
985 throw new DBConnectionError( $this, $error );
989 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
991 * This might return things, such as mysqli_result, that do not formally implement
992 * IResultWrapper, but nonetheless implement all of its methods correctly
994 * @param string $sql SQL query.
995 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
997 abstract protected function doQuery( $sql );
1000 * Determine whether a query writes to the DB.
1001 * Should return true if unsure.
1003 * @param string $sql
1006 protected function isWriteQuery( $sql ) {
1008 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1012 * @param string $sql
1013 * @return string|null
1015 protected function getQueryVerb( $sql ) {
1016 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1020 * Determine whether a SQL statement is sensitive to isolation level.
1021 * A SQL statement is considered transactable if its result could vary
1022 * depending on the transaction isolation level. Operational commands
1023 * such as 'SET' and 'SHOW' are not considered to be transactable.
1025 * @param string $sql
1028 protected function isTransactableQuery( $sql ) {
1030 $this->getQueryVerb( $sql ),
1031 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1037 * @param string $sql A SQL query
1038 * @return bool Whether $sql is SQL for TEMPORARY table operation
1040 protected function registerTempTableOperation( $sql ) {
1042 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1046 $this->sessionTempTables
[$matches[1]] = 1;
1049 } elseif ( preg_match(
1050 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1054 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1055 unset( $this->sessionTempTables
[$matches[1]] );
1058 } elseif ( preg_match(
1059 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1063 return isset( $this->sessionTempTables
[$matches[1]] );
1064 } elseif ( preg_match(
1065 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1069 return isset( $this->sessionTempTables
[$matches[1]] );
1075 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1076 $this->assertTransactionStatus( $sql, $fname );
1078 # Avoid fatals if close() was called
1079 $this->assertOpen();
1081 $priorWritesPending = $this->writesOrCallbacksPending();
1082 $this->lastQuery
= $sql;
1084 $isWrite = $this->isWriteQuery( $sql );
1086 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1088 $isNonTempWrite = false;
1092 if ( $this->getLBInfo( 'replica' ) === true ) {
1095 'Write operations are not allowed on replica database connections.'
1098 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1099 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1100 $reason = $this->getReadOnlyReason();
1101 if ( $reason !== false ) {
1102 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1104 # Set a flag indicating that writes have been done
1105 $this->lastWriteTime
= microtime( true );
1108 # Add trace comment to the begin of the sql string, right after the operator.
1109 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1110 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1112 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1113 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1114 && $this->isTransactableQuery( $sql )
1116 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1117 $this->trxAutomatic
= true;
1120 # Keep track of whether the transaction has write queries pending
1121 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1122 $this->trxDoneWrites
= true;
1123 $this->trxProfiler
->transactionWritingIn(
1124 $this->server
, $this->dbName
, $this->trxShortId
);
1127 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1128 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1131 # Send the query to the server and fetch any corresponding errors
1132 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1133 $lastError = $this->lastError();
1134 $lastErrno = $this->lastErrno();
1136 # Try reconnecting if the connection was lost
1137 if ( $ret === false && $this->wasConnectionLoss() ) {
1138 # Check if any meaningful session state was lost
1139 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1140 # Update session state tracking and try to restore the connection
1141 $reconnected = $this->replaceLostConnection( __METHOD__
);
1142 # Silently resend the query to the server if it is safe and possible
1143 if ( $reconnected && $recoverable ) {
1144 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1145 $lastError = $this->lastError();
1146 $lastErrno = $this->lastErrno();
1148 if ( $ret === false && $this->wasConnectionLoss() ) {
1149 # Query probably causes disconnects; reconnect and do not re-run it
1150 $this->replaceLostConnection( __METHOD__
);
1155 if ( $ret === false ) {
1156 if ( $this->trxLevel
) {
1157 if ( !$this->wasKnownStatementRollbackError() ) {
1158 # Either the query was aborted or all queries after BEGIN where aborted.
1159 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1160 # In the first case, the only options going forward are (a) ROLLBACK, or
1161 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1162 # option is ROLLBACK, since the snapshots would have been released.
1163 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1164 $this->trxStatusCause
=
1165 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1166 $tempIgnore = false; // cannot recover
1168 # Nothing prior was there to lose from the transaction,
1169 # so just roll it back.
1170 $this->doRollback( __METHOD__
. " ($fname)" );
1171 $this->trxStatus
= self
::STATUS_TRX_OK
;
1173 $this->trxStatusIgnoredCause
= null;
1175 # We're ignoring an error that caused just the current query to be aborted.
1176 # But log the cause so we can log a deprecation notice if a
1177 # caller actually does ignore it.
1178 $this->trxStatusIgnoredCause
= [ $lastError, $lastErrno, $fname ];
1182 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1185 return $this->resultObject( $ret );
1189 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1191 * @param string $sql Original SQL query
1192 * @param string $commentedSql SQL query with debugging/trace comment
1193 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1194 * @param string $fname Name of the calling function
1195 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1196 * object for a successful read query, or false on failure
1198 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1199 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1200 # generalizeSQL() will probably cut down the query to reasonable
1201 # logging size most of the time. The substr is really just a sanity check.
1203 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1205 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1208 # Include query transaction state
1209 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1211 $startTime = microtime( true );
1212 if ( $this->profiler
) {
1213 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1215 $this->affectedRowCount
= null;
1216 $ret = $this->doQuery( $commentedSql );
1217 $this->affectedRowCount
= $this->affectedRows();
1218 if ( $this->profiler
) {
1219 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1221 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1223 unset( $queryProfSection ); // profile out (if set)
1225 if ( $ret !== false ) {
1226 $this->lastPing
= $startTime;
1227 if ( $isWrite && $this->trxLevel
) {
1228 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1229 $this->trxWriteCallers
[] = $fname;
1233 if ( $sql === self
::PING_QUERY
) {
1234 $this->rttEstimate
= $queryRuntime;
1237 $this->trxProfiler
->recordQueryCompletion(
1238 $queryProf, $startTime, $isWrite, $this->affectedRows()
1240 $this->queryLogger
->debug( $sql, [
1242 'master' => $isMaster,
1243 'runtime' => $queryRuntime,
1250 * Update the estimated run-time of a query, not counting large row lock times
1252 * LoadBalancer can be set to rollback transactions that will create huge replication
1253 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1254 * queries, like inserting a row can take a long time due to row locking. This method
1255 * uses some simple heuristics to discount those cases.
1257 * @param string $sql A SQL write query
1258 * @param float $runtime Total runtime, including RTT
1259 * @param int $affected Affected row count
1261 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1262 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1263 $indicativeOfReplicaRuntime = true;
1264 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1265 $verb = $this->getQueryVerb( $sql );
1266 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1267 if ( $verb === 'INSERT' ) {
1268 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1269 } elseif ( $verb === 'REPLACE' ) {
1270 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1274 $this->trxWriteDuration +
= $runtime;
1275 $this->trxWriteQueryCount +
= 1;
1276 $this->trxWriteAffectedRows +
= $affected;
1277 if ( $indicativeOfReplicaRuntime ) {
1278 $this->trxWriteAdjDuration +
= $runtime;
1279 $this->trxWriteAdjQueryCount +
= 1;
1284 * @param string $sql
1285 * @param string $fname
1286 * @throws DBTransactionStateError
1288 private function assertTransactionStatus( $sql, $fname ) {
1289 if ( $this->getQueryVerb( $sql ) === 'ROLLBACK' ) { // transaction/savepoint
1293 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1294 throw new DBTransactionStateError(
1296 "Cannot execute query from $fname while transaction status is ERROR.",
1298 $this->trxStatusCause
1300 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1301 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1302 call_user_func( $this->deprecationLogger
,
1303 "Caller from $fname ignored an error originally raised from $iFname: " .
1304 "[$iLastErrno] $iLastError"
1306 $this->trxStatusIgnoredCause
= null;
1311 * Determine whether or not it is safe to retry queries after a database
1312 * connection is lost
1314 * @param string $sql SQL query
1315 * @param bool $priorWritesPending Whether there is a transaction open with
1316 * possible write queries or transaction pre-commit/idle callbacks
1317 * waiting on it to finish.
1318 * @return bool True if it is safe to retry the query, false otherwise
1320 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1321 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1322 # Dropped connections also mean that named locks are automatically released.
1323 # Only allow error suppression in autocommit mode or when the lost transaction
1324 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1325 if ( $this->namedLocksHeld
) {
1326 return false; // possible critical section violation
1327 } elseif ( $this->sessionTempTables
) {
1328 return false; // tables might be queried latter
1329 } elseif ( $sql === 'COMMIT' ) {
1330 return !$priorWritesPending; // nothing written anyway? (T127428)
1331 } elseif ( $sql === 'ROLLBACK' ) {
1332 return true; // transaction lost...which is also what was requested :)
1333 } elseif ( $this->explicitTrxActive() ) {
1334 return false; // don't drop atomocity and explicit snapshots
1335 } elseif ( $priorWritesPending ) {
1336 return false; // prior writes lost from implicit transaction
1343 * Clean things up after session (and thus transaction) loss
1345 private function handleSessionLoss() {
1346 // Clean up tracking of session-level things...
1347 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1348 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1349 $this->sessionTempTables
= [];
1350 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1351 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1352 $this->namedLocksHeld
= [];
1353 // Session loss implies transaction loss
1354 $this->handleTransactionLoss();
1358 * Clean things up after transaction loss
1360 private function handleTransactionLoss() {
1361 $this->trxLevel
= 0;
1362 $this->trxAtomicCounter
= 0;
1363 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1364 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1366 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1367 // If callback suppression is set then the array will remain unhandled.
1368 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1369 } catch ( Exception
$ex ) {
1370 // Already logged; move on...
1373 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1374 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1375 } catch ( Exception
$ex ) {
1376 // Already logged; move on...
1381 * Checks whether the cause of the error is detected to be a timeout.
1383 * It returns false by default, and not all engines support detecting this yet.
1384 * If this returns false, it will be treated as a generic query error.
1386 * @param string $error Error text
1387 * @param int $errno Error number
1390 protected function wasQueryTimeout( $error, $errno ) {
1395 * Report a query error. Log the error, and if neither the object ignore
1396 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1398 * @param string $error
1400 * @param string $sql
1401 * @param string $fname
1402 * @param bool $tempIgnore
1403 * @throws DBQueryError
1405 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1406 if ( $tempIgnore ) {
1407 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1409 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1416 * @param string $error
1417 * @param string|int $errno
1418 * @param string $sql
1419 * @param string $fname
1422 private function makeQueryException( $error, $errno, $sql, $fname ) {
1423 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1424 $this->queryLogger
->error(
1425 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1426 $this->getLogContext( [
1427 'method' => __METHOD__
,
1430 'sql1line' => $sql1line,
1434 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1435 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1436 if ( $wasQueryTimeout ) {
1437 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1439 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1445 public function freeResult( $res ) {
1448 public function selectField(
1449 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1451 if ( $var === '*' ) { // sanity
1452 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1455 if ( !is_array( $options ) ) {
1456 $options = [ $options ];
1459 $options['LIMIT'] = 1;
1461 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1462 if ( $res === false ||
!$this->numRows( $res ) ) {
1466 $row = $this->fetchRow( $res );
1468 if ( $row !== false ) {
1469 return reset( $row );
1475 public function selectFieldValues(
1476 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1478 if ( $var === '*' ) { // sanity
1479 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1480 } elseif ( !is_string( $var ) ) { // sanity
1481 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1484 if ( !is_array( $options ) ) {
1485 $options = [ $options ];
1488 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1489 if ( $res === false ) {
1494 foreach ( $res as $row ) {
1495 $values[] = $row->$var;
1502 * Returns an optional USE INDEX clause to go after the table, and a
1503 * string to go at the end of the query.
1505 * @param array $options Associative array of options to be turned into
1506 * an SQL query, valid keys are listed in the function.
1508 * @see Database::select()
1510 protected function makeSelectOptions( $options ) {
1511 $preLimitTail = $postLimitTail = '';
1516 foreach ( $options as $key => $option ) {
1517 if ( is_numeric( $key ) ) {
1518 $noKeyOptions[$option] = true;
1522 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1524 $preLimitTail .= $this->makeOrderBy( $options );
1526 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1527 $postLimitTail .= ' FOR UPDATE';
1530 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1531 $postLimitTail .= ' LOCK IN SHARE MODE';
1534 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1535 $startOpts .= 'DISTINCT';
1538 # Various MySQL extensions
1539 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1540 $startOpts .= ' /*! STRAIGHT_JOIN */';
1543 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1544 $startOpts .= ' HIGH_PRIORITY';
1547 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1548 $startOpts .= ' SQL_BIG_RESULT';
1551 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1552 $startOpts .= ' SQL_BUFFER_RESULT';
1555 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1556 $startOpts .= ' SQL_SMALL_RESULT';
1559 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1560 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1563 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1564 $startOpts .= ' SQL_CACHE';
1567 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1568 $startOpts .= ' SQL_NO_CACHE';
1571 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1572 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1576 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1577 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1582 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1586 * Returns an optional GROUP BY with an optional HAVING
1588 * @param array $options Associative array of options
1590 * @see Database::select()
1593 protected function makeGroupByWithHaving( $options ) {
1595 if ( isset( $options['GROUP BY'] ) ) {
1596 $gb = is_array( $options['GROUP BY'] )
1597 ?
implode( ',', $options['GROUP BY'] )
1598 : $options['GROUP BY'];
1599 $sql .= ' GROUP BY ' . $gb;
1601 if ( isset( $options['HAVING'] ) ) {
1602 $having = is_array( $options['HAVING'] )
1603 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1604 : $options['HAVING'];
1605 $sql .= ' HAVING ' . $having;
1612 * Returns an optional ORDER BY
1614 * @param array $options Associative array of options
1616 * @see Database::select()
1619 protected function makeOrderBy( $options ) {
1620 if ( isset( $options['ORDER BY'] ) ) {
1621 $ob = is_array( $options['ORDER BY'] )
1622 ?
implode( ',', $options['ORDER BY'] )
1623 : $options['ORDER BY'];
1625 return ' ORDER BY ' . $ob;
1631 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1632 $options = [], $join_conds = [] ) {
1633 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1635 return $this->query( $sql, $fname );
1638 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1639 $options = [], $join_conds = []
1641 if ( is_array( $vars ) ) {
1642 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1645 $options = (array)$options;
1646 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1647 ?
$options['USE INDEX']
1650 isset( $options['IGNORE INDEX'] ) &&
1651 is_array( $options['IGNORE INDEX'] )
1653 ?
$options['IGNORE INDEX']
1656 if ( is_array( $table ) ) {
1658 $this->tableNamesWithIndexClauseOrJOIN(
1659 $table, $useIndexes, $ignoreIndexes, $join_conds );
1660 } elseif ( $table != '' ) {
1662 $this->tableNamesWithIndexClauseOrJOIN(
1663 [ $table ], $useIndexes, $ignoreIndexes, [] );
1668 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1669 $this->makeSelectOptions( $options );
1671 if ( is_array( $conds ) ) {
1672 $conds = $this->makeList( $conds, self
::LIST_AND
);
1675 if ( $conds === null ||
$conds === false ) {
1676 $this->queryLogger
->warning(
1680 . ' with incorrect parameters: $conds must be a string or an array'
1685 if ( $conds === '' ) {
1686 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1687 } elseif ( is_string( $conds ) ) {
1688 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1689 "WHERE $conds $preLimitTail";
1691 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1694 if ( isset( $options['LIMIT'] ) ) {
1695 $sql = $this->limitResult( $sql, $options['LIMIT'],
1696 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1698 $sql = "$sql $postLimitTail";
1700 if ( isset( $options['EXPLAIN'] ) ) {
1701 $sql = 'EXPLAIN ' . $sql;
1707 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1708 $options = [], $join_conds = []
1710 $options = (array)$options;
1711 $options['LIMIT'] = 1;
1712 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1714 if ( $res === false ) {
1718 if ( !$this->numRows( $res ) ) {
1722 $obj = $this->fetchObject( $res );
1727 public function estimateRowCount(
1728 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1730 $conds = $this->normalizeConditions( $conds, $fname );
1731 $column = $this->extractSingleFieldFromList( $var );
1732 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1733 $conds[] = "$column IS NOT NULL";
1736 $res = $this->select(
1737 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1739 $row = $res ?
$this->fetchRow( $res ) : [];
1741 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1744 public function selectRowCount(
1745 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1747 $conds = $this->normalizeConditions( $conds, $fname );
1748 $column = $this->extractSingleFieldFromList( $var );
1749 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1750 $conds[] = "$column IS NOT NULL";
1753 $res = $this->select(
1755 'tmp_count' => $this->buildSelectSubquery(
1764 [ 'rowcount' => 'COUNT(*)' ],
1768 $row = $res ?
$this->fetchRow( $res ) : [];
1770 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1774 * @param array|string $conds
1775 * @param string $fname
1778 final protected function normalizeConditions( $conds, $fname ) {
1779 if ( $conds === null ||
$conds === false ) {
1780 $this->queryLogger
->warning(
1784 . ' with incorrect parameters: $conds must be a string or an array'
1789 if ( !is_array( $conds ) ) {
1790 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1797 * @param array|string $var Field parameter in the style of select()
1798 * @return string|null Column name or null; ignores aliases
1799 * @throws DBUnexpectedError Errors out if multiple columns are given
1801 final protected function extractSingleFieldFromList( $var ) {
1802 if ( is_array( $var ) ) {
1805 } elseif ( count( $var ) == 1 ) {
1806 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1808 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1818 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1819 * It's only slightly flawed. Don't use for anything important.
1821 * @param string $sql A SQL Query
1825 protected static function generalizeSQL( $sql ) {
1826 # This does the same as the regexp below would do, but in such a way
1827 # as to avoid crashing php on some large strings.
1828 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1830 $sql = str_replace( "\\\\", '', $sql );
1831 $sql = str_replace( "\\'", '', $sql );
1832 $sql = str_replace( "\\\"", '', $sql );
1833 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1834 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1836 # All newlines, tabs, etc replaced by single space
1837 $sql = preg_replace( '/\s+/', ' ', $sql );
1840 # except the ones surrounded by characters, e.g. l10n
1841 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1842 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1847 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1848 $info = $this->fieldInfo( $table, $field );
1853 public function indexExists( $table, $index, $fname = __METHOD__
) {
1854 if ( !$this->tableExists( $table ) ) {
1858 $info = $this->indexInfo( $table, $index, $fname );
1859 if ( is_null( $info ) ) {
1862 return $info !== false;
1866 public function tableExists( $table, $fname = __METHOD__
) {
1867 $tableRaw = $this->tableName( $table, 'raw' );
1868 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1869 return true; // already known to exist
1872 $table = $this->tableName( $table );
1873 $ignoreErrors = true;
1874 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1879 public function indexUnique( $table, $index ) {
1880 $indexInfo = $this->indexInfo( $table, $index );
1882 if ( !$indexInfo ) {
1886 return !$indexInfo[0]->Non_unique
;
1890 * Helper for Database::insert().
1892 * @param array $options
1895 protected function makeInsertOptions( $options ) {
1896 return implode( ' ', $options );
1899 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1900 # No rows to insert, easy just return now
1901 if ( !count( $a ) ) {
1905 $table = $this->tableName( $table );
1907 if ( !is_array( $options ) ) {
1908 $options = [ $options ];
1912 if ( isset( $options['fileHandle'] ) ) {
1913 $fh = $options['fileHandle'];
1915 $options = $this->makeInsertOptions( $options );
1917 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1919 $keys = array_keys( $a[0] );
1922 $keys = array_keys( $a );
1925 $sql = 'INSERT ' . $options .
1926 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1930 foreach ( $a as $row ) {
1936 $sql .= '(' . $this->makeList( $row ) . ')';
1939 $sql .= '(' . $this->makeList( $a ) . ')';
1942 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1944 } elseif ( $fh !== null ) {
1948 return (bool)$this->query( $sql, $fname );
1952 * Make UPDATE options array for Database::makeUpdateOptions
1954 * @param array $options
1957 protected function makeUpdateOptionsArray( $options ) {
1958 if ( !is_array( $options ) ) {
1959 $options = [ $options ];
1964 if ( in_array( 'IGNORE', $options ) ) {
1972 * Make UPDATE options for the Database::update function
1974 * @param array $options The options passed to Database::update
1977 protected function makeUpdateOptions( $options ) {
1978 $opts = $this->makeUpdateOptionsArray( $options );
1980 return implode( ' ', $opts );
1983 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1984 $table = $this->tableName( $table );
1985 $opts = $this->makeUpdateOptions( $options );
1986 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1988 if ( $conds !== [] && $conds !== '*' ) {
1989 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1992 return (bool)$this->query( $sql, $fname );
1995 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1996 if ( !is_array( $a ) ) {
1997 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2003 foreach ( $a as $field => $value ) {
2005 if ( $mode == self
::LIST_AND
) {
2007 } elseif ( $mode == self
::LIST_OR
) {
2016 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2017 $list .= "($value)";
2018 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2021 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2023 // Remove null from array to be handled separately if found
2024 $includeNull = false;
2025 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2026 $includeNull = true;
2027 unset( $value[$nullKey] );
2029 if ( count( $value ) == 0 && !$includeNull ) {
2030 throw new InvalidArgumentException(
2031 __METHOD__
. ": empty input for field $field" );
2032 } elseif ( count( $value ) == 0 ) {
2033 // only check if $field is null
2034 $list .= "$field IS NULL";
2036 // IN clause contains at least one valid element
2037 if ( $includeNull ) {
2038 // Group subconditions to ensure correct precedence
2041 if ( count( $value ) == 1 ) {
2042 // Special-case single values, as IN isn't terribly efficient
2043 // Don't necessarily assume the single key is 0; we don't
2044 // enforce linear numeric ordering on other arrays here.
2045 $value = array_values( $value )[0];
2046 $list .= $field . " = " . $this->addQuotes( $value );
2048 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2050 // if null present in array, append IS NULL
2051 if ( $includeNull ) {
2052 $list .= " OR $field IS NULL)";
2055 } elseif ( $value === null ) {
2056 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2057 $list .= "$field IS ";
2058 } elseif ( $mode == self
::LIST_SET
) {
2059 $list .= "$field = ";
2064 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2066 $list .= "$field = ";
2068 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2075 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2078 foreach ( $data as $base => $sub ) {
2079 if ( count( $sub ) ) {
2080 $conds[] = $this->makeList(
2081 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2087 return $this->makeList( $conds, self
::LIST_OR
);
2089 // Nothing to search for...
2094 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2098 public function bitNot( $field ) {
2102 public function bitAnd( $fieldLeft, $fieldRight ) {
2103 return "($fieldLeft & $fieldRight)";
2106 public function bitOr( $fieldLeft, $fieldRight ) {
2107 return "($fieldLeft | $fieldRight)";
2110 public function buildConcat( $stringList ) {
2111 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2114 public function buildGroupConcatField(
2115 $delim, $table, $field, $conds = '', $join_conds = []
2117 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2119 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2122 public function buildSubstring( $input, $startPosition, $length = null ) {
2123 $this->assertBuildSubstringParams( $startPosition, $length );
2124 $functionBody = "$input FROM $startPosition";
2125 if ( $length !== null ) {
2126 $functionBody .= " FOR $length";
2128 return 'SUBSTRING(' . $functionBody . ')';
2132 * Check type and bounds for parameters to self::buildSubstring()
2134 * All supported databases have substring functions that behave the same for
2135 * positive $startPosition and non-negative $length, but behaviors differ when
2136 * given 0 or negative $startPosition or negative $length. The simplest
2137 * solution to that is to just forbid those values.
2139 * @param int $startPosition
2140 * @param int|null $length
2143 protected function assertBuildSubstringParams( $startPosition, $length ) {
2144 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2145 throw new InvalidArgumentException(
2146 '$startPosition must be a positive integer'
2149 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2150 throw new InvalidArgumentException(
2151 '$length must be null or an integer greater than or equal to 0'
2156 public function buildStringCast( $field ) {
2160 public function buildIntegerCast( $field ) {
2161 return 'CAST( ' . $field . ' AS INTEGER )';
2164 public function buildSelectSubquery(
2165 $table, $vars, $conds = '', $fname = __METHOD__
,
2166 $options = [], $join_conds = []
2168 return new Subquery(
2169 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2173 public function databasesAreIndependent() {
2177 public function selectDB( $db ) {
2178 # Stub. Shouldn't cause serious problems if it's not overridden, but
2179 # if your database engine supports a concept similar to MySQL's
2180 # databases you may as well.
2181 $this->dbName
= $db;
2186 public function getDBname() {
2187 return $this->dbName
;
2190 public function getServer() {
2191 return $this->server
;
2194 public function tableName( $name, $format = 'quoted' ) {
2195 if ( $name instanceof Subquery
) {
2196 throw new DBUnexpectedError(
2198 __METHOD__
. ': got Subquery instance when expecting a string.'
2202 # Skip the entire process when we have a string quoted on both ends.
2203 # Note that we check the end so that we will still quote any use of
2204 # use of `database`.table. But won't break things if someone wants
2205 # to query a database table with a dot in the name.
2206 if ( $this->isQuotedIdentifier( $name ) ) {
2210 # Lets test for any bits of text that should never show up in a table
2211 # name. Basically anything like JOIN or ON which are actually part of
2212 # SQL queries, but may end up inside of the table value to combine
2213 # sql. Such as how the API is doing.
2214 # Note that we use a whitespace test rather than a \b test to avoid
2215 # any remote case where a word like on may be inside of a table name
2216 # surrounded by symbols which may be considered word breaks.
2217 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2218 $this->queryLogger
->warning(
2219 __METHOD__
. ": use of subqueries is not supported this way.",
2220 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2226 # Split database and table into proper variables.
2227 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2229 # Quote $table and apply the prefix if not quoted.
2230 # $tableName might be empty if this is called from Database::replaceVars()
2231 $tableName = "{$prefix}{$table}";
2232 if ( $format === 'quoted'
2233 && !$this->isQuotedIdentifier( $tableName )
2234 && $tableName !== ''
2236 $tableName = $this->addIdentifierQuotes( $tableName );
2239 # Quote $schema and $database and merge them with the table name if needed
2240 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2241 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2247 * Get the table components needed for a query given the currently selected database
2249 * @param string $name Table name in the form of db.schema.table, db.table, or table
2250 * @return array (DB name or "" for default, schema name, table prefix, table name)
2252 protected function qualifiedTableComponents( $name ) {
2253 # We reverse the explode so that database.table and table both output the correct table.
2254 $dbDetails = explode( '.', $name, 3 );
2255 if ( count( $dbDetails ) == 3 ) {
2256 list( $database, $schema, $table ) = $dbDetails;
2257 # We don't want any prefix added in this case
2259 } elseif ( count( $dbDetails ) == 2 ) {
2260 list( $database, $table ) = $dbDetails;
2261 # We don't want any prefix added in this case
2263 # In dbs that support it, $database may actually be the schema
2264 # but that doesn't affect any of the functionality here
2267 list( $table ) = $dbDetails;
2268 if ( isset( $this->tableAliases
[$table] ) ) {
2269 $database = $this->tableAliases
[$table]['dbname'];
2270 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2271 ?
$this->tableAliases
[$table]['schema']
2273 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2274 ?
$this->tableAliases
[$table]['prefix']
2275 : $this->tablePrefix
;
2278 $schema = $this->schema
; # Default schema
2279 $prefix = $this->tablePrefix
; # Default prefix
2283 return [ $database, $schema, $prefix, $table ];
2287 * @param string|null $namespace Database or schema
2288 * @param string $relation Name of table, view, sequence, etc...
2289 * @param string $format One of (raw, quoted)
2290 * @return string Relation name with quoted and merged $namespace as needed
2292 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2293 if ( strlen( $namespace ) ) {
2294 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2295 $namespace = $this->addIdentifierQuotes( $namespace );
2297 $relation = $namespace . '.' . $relation;
2303 public function tableNames() {
2304 $inArray = func_get_args();
2307 foreach ( $inArray as $name ) {
2308 $retVal[$name] = $this->tableName( $name );
2314 public function tableNamesN() {
2315 $inArray = func_get_args();
2318 foreach ( $inArray as $name ) {
2319 $retVal[] = $this->tableName( $name );
2326 * Get an aliased table name
2328 * This returns strings like "tableName AS newTableName" for aliased tables
2329 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2331 * @see Database::tableName()
2332 * @param string|Subquery $table Table name or object with a 'sql' field
2333 * @param string|bool $alias Table alias (optional)
2334 * @return string SQL name for aliased table. Will not alias a table to its own name
2336 protected function tableNameWithAlias( $table, $alias = false ) {
2337 if ( is_string( $table ) ) {
2338 $quotedTable = $this->tableName( $table );
2339 } elseif ( $table instanceof Subquery
) {
2340 $quotedTable = (string)$table;
2342 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2345 if ( !strlen( $alias ) ||
$alias === $table ) {
2346 if ( $table instanceof Subquery
) {
2347 throw new InvalidArgumentException( "Subquery table missing alias." );
2350 return $quotedTable;
2352 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2357 * Gets an array of aliased table names
2359 * @param array $tables [ [alias] => table ]
2360 * @return string[] See tableNameWithAlias()
2362 protected function tableNamesWithAlias( $tables ) {
2364 foreach ( $tables as $alias => $table ) {
2365 if ( is_numeric( $alias ) ) {
2368 $retval[] = $this->tableNameWithAlias( $table, $alias );
2375 * Get an aliased field name
2376 * e.g. fieldName AS newFieldName
2378 * @param string $name Field name
2379 * @param string|bool $alias Alias (optional)
2380 * @return string SQL name for aliased field. Will not alias a field to its own name
2382 protected function fieldNameWithAlias( $name, $alias = false ) {
2383 if ( !$alias ||
(string)$alias === (string)$name ) {
2386 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2391 * Gets an array of aliased field names
2393 * @param array $fields [ [alias] => field ]
2394 * @return string[] See fieldNameWithAlias()
2396 protected function fieldNamesWithAlias( $fields ) {
2398 foreach ( $fields as $alias => $field ) {
2399 if ( is_numeric( $alias ) ) {
2402 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2409 * Get the aliased table name clause for a FROM clause
2410 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2412 * @param array $tables ( [alias] => table )
2413 * @param array $use_index Same as for select()
2414 * @param array $ignore_index Same as for select()
2415 * @param array $join_conds Same as for select()
2418 protected function tableNamesWithIndexClauseOrJOIN(
2419 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2423 $use_index = (array)$use_index;
2424 $ignore_index = (array)$ignore_index;
2425 $join_conds = (array)$join_conds;
2427 foreach ( $tables as $alias => $table ) {
2428 if ( !is_string( $alias ) ) {
2429 // No alias? Set it equal to the table name
2433 if ( is_array( $table ) ) {
2434 // A parenthesized group
2435 if ( count( $table ) > 1 ) {
2436 $joinedTable = '(' .
2437 $this->tableNamesWithIndexClauseOrJOIN(
2438 $table, $use_index, $ignore_index, $join_conds ) . ')';
2441 $innerTable = reset( $table );
2442 $innerAlias = key( $table );
2443 $joinedTable = $this->tableNameWithAlias(
2445 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2449 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2452 // Is there a JOIN clause for this table?
2453 if ( isset( $join_conds[$alias] ) ) {
2454 list( $joinType, $conds ) = $join_conds[$alias];
2455 $tableClause = $joinType;
2456 $tableClause .= ' ' . $joinedTable;
2457 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2458 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2460 $tableClause .= ' ' . $use;
2463 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2464 $ignore = $this->ignoreIndexClause(
2465 implode( ',', (array)$ignore_index[$alias] ) );
2466 if ( $ignore != '' ) {
2467 $tableClause .= ' ' . $ignore;
2470 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2472 $tableClause .= ' ON (' . $on . ')';
2475 $retJOIN[] = $tableClause;
2476 } elseif ( isset( $use_index[$alias] ) ) {
2477 // Is there an INDEX clause for this table?
2478 $tableClause = $joinedTable;
2479 $tableClause .= ' ' . $this->useIndexClause(
2480 implode( ',', (array)$use_index[$alias] )
2483 $ret[] = $tableClause;
2484 } elseif ( isset( $ignore_index[$alias] ) ) {
2485 // Is there an INDEX clause for this table?
2486 $tableClause = $joinedTable;
2487 $tableClause .= ' ' . $this->ignoreIndexClause(
2488 implode( ',', (array)$ignore_index[$alias] )
2491 $ret[] = $tableClause;
2493 $tableClause = $joinedTable;
2495 $ret[] = $tableClause;
2499 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2500 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2501 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2503 // Compile our final table clause
2504 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2508 * Allows for index remapping in queries where this is not consistent across DBMS
2510 * @param string $index
2513 protected function indexName( $index ) {
2514 return isset( $this->indexAliases
[$index] )
2515 ?
$this->indexAliases
[$index]
2519 public function addQuotes( $s ) {
2520 if ( $s instanceof Blob
) {
2523 if ( $s === null ) {
2525 } elseif ( is_bool( $s ) ) {
2528 # This will also quote numeric values. This should be harmless,
2529 # and protects against weird problems that occur when they really
2530 # _are_ strings such as article titles and string->number->string
2531 # conversion is not 1:1.
2532 return "'" . $this->strencode( $s ) . "'";
2537 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2538 * MySQL uses `backticks` while basically everything else uses double quotes.
2539 * Since MySQL is the odd one out here the double quotes are our generic
2540 * and we implement backticks in DatabaseMysqlBase.
2545 public function addIdentifierQuotes( $s ) {
2546 return '"' . str_replace( '"', '""', $s ) . '"';
2550 * Returns if the given identifier looks quoted or not according to
2551 * the database convention for quoting identifiers .
2553 * @note Do not use this to determine if untrusted input is safe.
2554 * A malicious user can trick this function.
2555 * @param string $name
2558 public function isQuotedIdentifier( $name ) {
2559 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2564 * @param string $escapeChar
2567 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2568 return str_replace( [ $escapeChar, '%', '_' ],
2569 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2573 public function buildLike() {
2574 $params = func_get_args();
2576 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2577 $params = $params[0];
2582 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2583 // may escape backslashes, creating problems of double escaping. The `
2584 // character has good cross-DBMS compatibility, avoiding special operators
2585 // in MS SQL like ^ and %
2588 foreach ( $params as $value ) {
2589 if ( $value instanceof LikeMatch
) {
2590 $s .= $value->toString();
2592 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2597 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2600 public function anyChar() {
2601 return new LikeMatch( '_' );
2604 public function anyString() {
2605 return new LikeMatch( '%' );
2608 public function nextSequenceValue( $seqName ) {
2613 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2614 * is only needed because a) MySQL must be as efficient as possible due to
2615 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2616 * which index to pick. Anyway, other databases might have different
2617 * indexes on a given table. So don't bother overriding this unless you're
2619 * @param string $index
2622 public function useIndexClause( $index ) {
2627 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2628 * is only needed because a) MySQL must be as efficient as possible due to
2629 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2630 * which index to pick. Anyway, other databases might have different
2631 * indexes on a given table. So don't bother overriding this unless you're
2633 * @param string $index
2636 public function ignoreIndexClause( $index ) {
2640 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2641 if ( count( $rows ) == 0 ) {
2646 if ( !is_array( reset( $rows ) ) ) {
2651 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2652 $affectedRowCount = 0;
2653 foreach ( $rows as $row ) {
2654 // Delete rows which collide with this one
2655 $indexWhereClauses = [];
2656 foreach ( $uniqueIndexes as $index ) {
2657 $indexColumns = (array)$index;
2658 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2659 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2660 throw new DBUnexpectedError(
2662 'New record does not provide all values for unique key (' .
2663 implode( ', ', $indexColumns ) . ')'
2665 } elseif ( in_array( null, $indexRowValues, true ) ) {
2666 throw new DBUnexpectedError(
2668 'New record has a null value for unique key (' .
2669 implode( ', ', $indexColumns ) . ')'
2672 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2675 if ( $indexWhereClauses ) {
2676 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2677 $affectedRowCount +
= $this->affectedRows();
2680 // Now insert the row
2681 $this->insert( $table, $row, $fname );
2682 $affectedRowCount +
= $this->affectedRows();
2684 $this->endAtomic( $fname );
2685 $this->affectedRowCount
= $affectedRowCount;
2686 } catch ( Exception
$e ) {
2687 $this->cancelAtomic( $fname );
2693 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2696 * @param string $table Table name
2697 * @param array|string $rows Row(s) to insert
2698 * @param string $fname Caller function name
2700 * @return ResultWrapper
2702 protected function nativeReplace( $table, $rows, $fname ) {
2703 $table = $this->tableName( $table );
2706 if ( !is_array( reset( $rows ) ) ) {
2710 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2713 foreach ( $rows as $row ) {
2720 $sql .= '(' . $this->makeList( $row ) . ')';
2723 return $this->query( $sql, $fname );
2726 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2729 if ( !count( $rows ) ) {
2730 return true; // nothing to do
2733 if ( !is_array( reset( $rows ) ) ) {
2737 if ( count( $uniqueIndexes ) ) {
2738 $clauses = []; // list WHERE clauses that each identify a single row
2739 foreach ( $rows as $row ) {
2740 foreach ( $uniqueIndexes as $index ) {
2741 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2742 $rowKey = []; // unique key to this row
2743 foreach ( $index as $column ) {
2744 $rowKey[$column] = $row[$column];
2746 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2749 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2754 $affectedRowCount = 0;
2756 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2757 # Update any existing conflicting row(s)
2758 if ( $where !== false ) {
2759 $ok = $this->update( $table, $set, $where, $fname );
2760 $affectedRowCount +
= $this->affectedRows();
2764 # Now insert any non-conflicting row(s)
2765 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2766 $affectedRowCount +
= $this->affectedRows();
2767 $this->endAtomic( $fname );
2768 $this->affectedRowCount
= $affectedRowCount;
2769 } catch ( Exception
$e ) {
2770 $this->cancelAtomic( $fname );
2777 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2781 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2784 $delTable = $this->tableName( $delTable );
2785 $joinTable = $this->tableName( $joinTable );
2786 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2787 if ( $conds != '*' ) {
2788 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2792 $this->query( $sql, $fname );
2795 public function textFieldSize( $table, $field ) {
2796 $table = $this->tableName( $table );
2797 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2798 $res = $this->query( $sql, __METHOD__
);
2799 $row = $this->fetchObject( $res );
2803 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2812 public function delete( $table, $conds, $fname = __METHOD__
) {
2814 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2817 $table = $this->tableName( $table );
2818 $sql = "DELETE FROM $table";
2820 if ( $conds != '*' ) {
2821 if ( is_array( $conds ) ) {
2822 $conds = $this->makeList( $conds, self
::LIST_AND
);
2824 $sql .= ' WHERE ' . $conds;
2827 return $this->query( $sql, $fname );
2830 final public function insertSelect(
2831 $destTable, $srcTable, $varMap, $conds,
2832 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2834 static $hints = [ 'NO_AUTO_COLUMNS' ];
2836 $insertOptions = (array)$insertOptions;
2837 $selectOptions = (array)$selectOptions;
2839 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2840 // For massive migrations with downtime, we don't want to select everything
2841 // into memory and OOM, so do all this native on the server side if possible.
2842 return $this->nativeInsertSelect(
2848 array_diff( $insertOptions, $hints ),
2854 return $this->nonNativeInsertSelect(
2860 array_diff( $insertOptions, $hints ),
2867 * @param array $insertOptions INSERT options
2868 * @param array $selectOptions SELECT options
2869 * @return bool Whether an INSERT SELECT with these options will be replication safe
2872 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2877 * Implementation of insertSelect() based on select() and insert()
2879 * @see IDatabase::insertSelect()
2881 * @param string $destTable
2882 * @param string|array $srcTable
2883 * @param array $varMap
2884 * @param array $conds
2885 * @param string $fname
2886 * @param array $insertOptions
2887 * @param array $selectOptions
2888 * @param array $selectJoinConds
2891 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2892 $fname = __METHOD__
,
2893 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2895 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2896 // on only the master (without needing row-based-replication). It also makes it easy to
2897 // know how big the INSERT is going to be.
2899 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2900 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2902 $selectOptions[] = 'FOR UPDATE';
2903 $res = $this->select(
2904 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2911 $affectedRowCount = 0;
2912 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2915 foreach ( $res as $row ) {
2916 $rows[] = (array)$row;
2918 // Avoid inserts that are too huge
2919 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2920 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2924 $affectedRowCount +
= $this->affectedRows();
2928 if ( $rows && $ok ) {
2929 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2931 $affectedRowCount +
= $this->affectedRows();
2935 $this->endAtomic( $fname );
2936 $this->affectedRowCount
= $affectedRowCount;
2938 $this->cancelAtomic( $fname );
2941 } catch ( Exception
$e ) {
2942 $this->cancelAtomic( $fname );
2948 * Native server-side implementation of insertSelect() for situations where
2949 * we don't want to select everything into memory
2951 * @see IDatabase::insertSelect()
2952 * @param string $destTable
2953 * @param string|array $srcTable
2954 * @param array $varMap
2955 * @param array $conds
2956 * @param string $fname
2957 * @param array $insertOptions
2958 * @param array $selectOptions
2959 * @param array $selectJoinConds
2962 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2963 $fname = __METHOD__
,
2964 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2966 $destTable = $this->tableName( $destTable );
2968 if ( !is_array( $insertOptions ) ) {
2969 $insertOptions = [ $insertOptions ];
2972 $insertOptions = $this->makeInsertOptions( $insertOptions );
2974 $selectSql = $this->selectSQLText(
2976 array_values( $varMap ),
2983 $sql = "INSERT $insertOptions" .
2984 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2987 return $this->query( $sql, $fname );
2991 * Construct a LIMIT query with optional offset. This is used for query
2992 * pages. The SQL should be adjusted so that only the first $limit rows
2993 * are returned. If $offset is provided as well, then the first $offset
2994 * rows should be discarded, and the next $limit rows should be returned.
2995 * If the result of the query is not ordered, then the rows to be returned
2996 * are theoretically arbitrary.
2998 * $sql is expected to be a SELECT, if that makes a difference.
3000 * The version provided by default works in MySQL and SQLite. It will very
3001 * likely need to be overridden for most other DBMSes.
3003 * @param string $sql SQL query we will append the limit too
3004 * @param int $limit The SQL limit
3005 * @param int|bool $offset The SQL offset (default false)
3006 * @throws DBUnexpectedError
3009 public function limitResult( $sql, $limit, $offset = false ) {
3010 if ( !is_numeric( $limit ) ) {
3011 throw new DBUnexpectedError( $this,
3012 "Invalid non-numeric limit passed to limitResult()\n" );
3015 return "$sql LIMIT "
3016 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3020 public function unionSupportsOrderAndLimit() {
3021 return true; // True for almost every DB supported
3024 public function unionQueries( $sqls, $all ) {
3025 $glue = $all ?
') UNION ALL (' : ') UNION (';
3027 return '(' . implode( $glue, $sqls ) . ')';
3030 public function unionConditionPermutations(
3031 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3032 $options = [], $join_conds = []
3034 // First, build the Cartesian product of $permute_conds
3036 foreach ( $permute_conds as $field => $values ) {
3038 // Skip empty $values
3041 $values = array_unique( $values ); // For sanity
3043 foreach ( $conds as $cond ) {
3044 foreach ( $values as $value ) {
3045 $cond[$field] = $value;
3046 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3052 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3054 // If there's just one condition and no subordering, hand off to
3055 // selectSQLText directly.
3056 if ( count( $conds ) === 1 &&
3057 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3059 return $this->selectSQLText(
3060 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3064 // Otherwise, we need to pull out the order and limit to apply after
3065 // the union. Then build the SQL queries for each set of conditions in
3066 // $conds. Then union them together (using UNION ALL, because the
3067 // product *should* already be distinct).
3068 $orderBy = $this->makeOrderBy( $options );
3069 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
3070 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
3071 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3072 if ( !$this->unionSupportsOrderAndLimit() ) {
3073 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3075 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3076 $options['ORDER BY'] = $options['INNER ORDER BY'];
3078 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3079 // We need to increase the limit by the offset rather than
3080 // using the offset directly, otherwise it'll skip incorrectly
3081 // in the subqueries.
3082 $options['LIMIT'] = $limit +
$offset;
3083 unset( $options['OFFSET'] );
3088 foreach ( $conds as $cond ) {
3089 $sqls[] = $this->selectSQLText(
3090 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3093 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3094 if ( $limit !== null ) {
3095 $sql = $this->limitResult( $sql, $limit, $offset );
3101 public function conditional( $cond, $trueVal, $falseVal ) {
3102 if ( is_array( $cond ) ) {
3103 $cond = $this->makeList( $cond, self
::LIST_AND
);
3106 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3109 public function strreplace( $orig, $old, $new ) {
3110 return "REPLACE({$orig}, {$old}, {$new})";
3113 public function getServerUptime() {
3117 public function wasDeadlock() {
3121 public function wasLockTimeout() {
3125 public function wasConnectionLoss() {
3126 return $this->wasConnectionError( $this->lastErrno() );
3129 public function wasReadOnlyError() {
3133 public function wasErrorReissuable() {
3135 $this->wasDeadlock() ||
3136 $this->wasLockTimeout() ||
3137 $this->wasConnectionLoss()
3142 * Do not use this method outside of Database/DBError classes
3144 * @param int|string $errno
3145 * @return bool Whether the given query error was a connection drop
3147 public function wasConnectionError( $errno ) {
3152 * @return bool Whether it is safe to assume the given error only caused statement rollback
3153 * @note This is for backwards compatibility for callers catching DBError exceptions in
3154 * order to ignore problems like duplicate key errors or foriegn key violations
3157 protected function wasKnownStatementRollbackError() {
3158 return false; // don't know; it could have caused a transaction rollback
3161 public function deadlockLoop() {
3162 $args = func_get_args();
3163 $function = array_shift( $args );
3164 $tries = self
::DEADLOCK_TRIES
;
3166 $this->begin( __METHOD__
);
3169 /** @var Exception $e */
3173 $retVal = call_user_func_array( $function, $args );
3175 } catch ( DBQueryError
$e ) {
3176 if ( $this->wasDeadlock() ) {
3177 // Retry after a randomized delay
3178 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3180 // Throw the error back up
3184 } while ( --$tries > 0 );
3186 if ( $tries <= 0 ) {
3187 // Too many deadlocks; give up
3188 $this->rollback( __METHOD__
);
3191 $this->commit( __METHOD__
);
3197 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3198 # Real waits are implemented in the subclass.
3202 public function getReplicaPos() {
3207 public function getMasterPos() {
3212 public function serverIsReadOnly() {
3216 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3217 if ( !$this->trxLevel
) {
3218 throw new DBUnexpectedError( $this, "No transaction is active." );
3220 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3223 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3224 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3225 // Start an implicit transaction similar to how query() does
3226 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3227 $this->trxAutomatic
= true;
3230 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3231 if ( !$this->trxLevel
) {
3232 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3236 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3237 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3238 // Start an implicit transaction similar to how query() does
3239 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3240 $this->trxAutomatic
= true;
3243 if ( $this->trxLevel
) {
3244 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3246 // No transaction is active nor will start implicitly, so make one for this callback
3247 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3249 call_user_func( $callback );
3250 $this->endAtomic( __METHOD__
);
3251 } catch ( Exception
$e ) {
3252 $this->cancelAtomic( __METHOD__
);
3258 final public function setTransactionListener( $name, callable
$callback = null ) {
3260 $this->trxRecurringCallbacks
[$name] = $callback;
3262 unset( $this->trxRecurringCallbacks
[$name] );
3267 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3269 * This method should not be used outside of Database/LoadBalancer
3271 * @param bool $suppress
3274 final public function setTrxEndCallbackSuppression( $suppress ) {
3275 $this->trxEndCallbacksSuppressed
= $suppress;
3279 * Actually run and consume any "on transaction idle/resolution" callbacks.
3281 * This method should not be used outside of Database/LoadBalancer
3283 * @param int $trigger IDatabase::TRIGGER_* constant
3287 public function runOnTransactionIdleCallbacks( $trigger ) {
3288 if ( $this->trxEndCallbacksSuppressed
) {
3292 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3293 /** @var Exception $e */
3294 $e = null; // first exception
3295 do { // callbacks may add callbacks :)
3296 $callbacks = array_merge(
3297 $this->trxIdleCallbacks
,
3298 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3300 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3301 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3302 foreach ( $callbacks as $callback ) {
3304 list( $phpCallback ) = $callback;
3305 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3306 call_user_func_array( $phpCallback, [ $trigger ] );
3308 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3310 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3312 } catch ( Exception
$ex ) {
3313 call_user_func( $this->errorLogger
, $ex );
3315 // Some callbacks may use startAtomic/endAtomic, so make sure
3316 // their transactions are ended so other callbacks don't fail
3317 if ( $this->trxLevel() ) {
3318 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3322 } while ( count( $this->trxIdleCallbacks
) );
3324 if ( $e instanceof Exception
) {
3325 throw $e; // re-throw any first exception
3330 * Actually run and consume any "on transaction pre-commit" callbacks.
3332 * This method should not be used outside of Database/LoadBalancer
3337 public function runOnTransactionPreCommitCallbacks() {
3338 $e = null; // first exception
3339 do { // callbacks may add callbacks :)
3340 $callbacks = $this->trxPreCommitCallbacks
;
3341 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3342 foreach ( $callbacks as $callback ) {
3344 list( $phpCallback ) = $callback;
3345 call_user_func( $phpCallback );
3346 } catch ( Exception
$ex ) {
3347 call_user_func( $this->errorLogger
, $ex );
3351 } while ( count( $this->trxPreCommitCallbacks
) );
3353 if ( $e instanceof Exception
) {
3354 throw $e; // re-throw any first exception
3359 * Actually run any "transaction listener" callbacks.
3361 * This method should not be used outside of Database/LoadBalancer
3363 * @param int $trigger IDatabase::TRIGGER_* constant
3367 public function runTransactionListenerCallbacks( $trigger ) {
3368 if ( $this->trxEndCallbacksSuppressed
) {
3372 /** @var Exception $e */
3373 $e = null; // first exception
3375 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3377 $phpCallback( $trigger, $this );
3378 } catch ( Exception
$ex ) {
3379 call_user_func( $this->errorLogger
, $ex );
3384 if ( $e instanceof Exception
) {
3385 throw $e; // re-throw any first exception
3390 * Create a savepoint
3392 * This is used internally to implement atomic sections. It should not be
3396 * @param string $identifier Identifier for the savepoint
3397 * @param string $fname Calling function name
3399 protected function doSavepoint( $identifier, $fname ) {
3400 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3404 * Release a savepoint
3406 * This is used internally to implement atomic sections. It should not be
3410 * @param string $identifier Identifier for the savepoint
3411 * @param string $fname Calling function name
3413 protected function doReleaseSavepoint( $identifier, $fname ) {
3414 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3418 * Rollback to a savepoint
3420 * This is used internally to implement atomic sections. It should not be
3424 * @param string $identifier Identifier for the savepoint
3425 * @param string $fname Calling function name
3427 protected function doRollbackToSavepoint( $identifier, $fname ) {
3428 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3431 final public function startAtomic(
3432 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3434 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3435 if ( !$this->trxLevel
) {
3436 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3437 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3438 // in all changes being in one transaction to keep requests transactional.
3439 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3440 $this->trxAutomaticAtomic
= true;
3442 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3443 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3444 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3445 $this->queryLogger
->warning(
3446 'There have been an excessively large number of atomic sections in a transaction'
3447 . " started by $this->trxFname, reusing IDs (at $fname)",
3448 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3450 $this->trxAtomicCounter
= 0;
3451 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3453 $this->doSavepoint( $savepointId, $fname );
3456 $sectionId = new AtomicSectionIdentifier
;
3457 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3462 final public function endAtomic( $fname = __METHOD__
) {
3463 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3464 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3467 // Check if the current section matches $fname
3468 $pos = count( $this->trxAtomicLevels
) - 1;
3469 list( $savedFname, , $savepointId ) = $this->trxAtomicLevels
[$pos];
3471 if ( $savedFname !== $fname ) {
3472 throw new DBUnexpectedError(
3474 "Invalid atomic section ended (got $fname but expected $savedFname)."
3478 // Remove the last section and re-index the array
3479 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos );
3481 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3482 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3483 } elseif ( $savepointId !== null && $savepointId !== 'n/a' ) {
3484 $this->doReleaseSavepoint( $savepointId, $fname );
3488 final public function cancelAtomic(
3489 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3491 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3492 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3495 if ( $sectionId !== null ) {
3496 // Find the (last) section with the given $sectionId
3498 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3499 if ( $asId === $sectionId ) {
3504 throw new DBUnexpectedError( "Atomic section not found (for $fname)" );
3506 // Remove all descendant sections and re-index the array
3507 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3510 // Check if the current section matches $fname
3511 $pos = count( $this->trxAtomicLevels
) - 1;
3512 list( $savedFname, , $savepointId ) = $this->trxAtomicLevels
[$pos];
3514 if ( $savedFname !== $fname ) {
3515 throw new DBUnexpectedError(
3517 "Invalid atomic section ended (got $fname but expected $savedFname)."
3521 // Remove the last section and re-index the array
3522 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos );
3524 if ( $savepointId !== null ) {
3525 // Rollback the transaction to the state just before this atomic section
3526 if ( $savepointId === 'n/a' ) {
3527 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3529 $this->doRollbackToSavepoint( $savepointId, $fname );
3530 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3531 $this->trxStatusIgnoredCause
= null;
3533 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3534 // Put the transaction into an error state if it's not already in one
3535 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3536 $this->trxStatusCause
= new DBUnexpectedError(
3538 "Uncancelable atomic section canceled (got $fname)."
3542 $this->affectedRowCount
= 0; // for the sake of consistency
3545 final public function doAtomicSection(
3546 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3548 $sectionId = $this->startAtomic( $fname, $cancelable );
3550 $res = call_user_func_array( $callback, [ $this, $fname ] );
3551 } catch ( Exception
$e ) {
3552 $this->cancelAtomic( $fname, $sectionId );
3556 $this->endAtomic( $fname );
3561 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3562 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3563 if ( $this->trxLevel
) {
3564 if ( $this->trxAtomicLevels
) {
3565 $levels = $this->flatAtomicSectionList();
3566 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3567 throw new DBUnexpectedError( $this, $msg );
3568 } elseif ( !$this->trxAutomatic
) {
3569 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3570 throw new DBUnexpectedError( $this, $msg );
3572 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3573 throw new DBUnexpectedError( $this, $msg );
3575 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3576 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3577 throw new DBUnexpectedError( $this, $msg );
3580 // Avoid fatals if close() was called
3581 $this->assertOpen();
3583 $this->doBegin( $fname );
3584 $this->trxStatus
= self
::STATUS_TRX_OK
;
3585 $this->trxStatusIgnoredCause
= null;
3586 $this->trxAtomicCounter
= 0;
3587 $this->trxTimestamp
= microtime( true );
3588 $this->trxFname
= $fname;
3589 $this->trxDoneWrites
= false;
3590 $this->trxAutomaticAtomic
= false;
3591 $this->trxAtomicLevels
= [];
3592 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3593 $this->trxWriteDuration
= 0.0;
3594 $this->trxWriteQueryCount
= 0;
3595 $this->trxWriteAffectedRows
= 0;
3596 $this->trxWriteAdjDuration
= 0.0;
3597 $this->trxWriteAdjQueryCount
= 0;
3598 $this->trxWriteCallers
= [];
3599 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3600 // Get an estimate of the replication lag before any such queries.
3601 $this->trxReplicaLag
= null; // clear cached value first
3602 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3603 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3604 // caller will think its OK to muck around with the transaction just because startAtomic()
3605 // has not yet completed (e.g. setting trxAtomicLevels).
3606 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3610 * Issues the BEGIN command to the database server.
3612 * @see Database::begin()
3613 * @param string $fname
3615 protected function doBegin( $fname ) {
3616 $this->query( 'BEGIN', $fname );
3617 $this->trxLevel
= 1;
3620 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3621 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3622 // There are still atomic sections open. This cannot be ignored
3623 $levels = $this->flatAtomicSectionList();
3624 throw new DBUnexpectedError(
3626 "$fname: Got COMMIT while atomic sections $levels are still open."
3630 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3631 if ( !$this->trxLevel
) {
3632 return; // nothing to do
3633 } elseif ( !$this->trxAutomatic
) {
3634 throw new DBUnexpectedError(
3636 "$fname: Flushing an explicit transaction, getting out of sync."
3640 if ( !$this->trxLevel
) {
3641 $this->queryLogger
->error(
3642 "$fname: No transaction to commit, something got out of sync." );
3643 return; // nothing to do
3644 } elseif ( $this->trxAutomatic
) {
3645 throw new DBUnexpectedError(
3647 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3652 // Avoid fatals if close() was called
3653 $this->assertOpen();
3655 $this->runOnTransactionPreCommitCallbacks();
3656 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3657 $this->doCommit( $fname );
3658 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3659 if ( $this->trxDoneWrites
) {
3660 $this->lastWriteTime
= microtime( true );
3661 $this->trxProfiler
->transactionWritingOut(
3666 $this->trxWriteAffectedRows
3670 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3671 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3675 * Issues the COMMIT command to the database server.
3677 * @see Database::commit()
3678 * @param string $fname
3680 protected function doCommit( $fname ) {
3681 if ( $this->trxLevel
) {
3682 $this->query( 'COMMIT', $fname );
3683 $this->trxLevel
= 0;
3687 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3688 $trxActive = $this->trxLevel
;
3690 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3691 if ( $this->getFlag( self
::DBO_TRX
) ) {
3692 throw new DBUnexpectedError(
3694 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3700 // Avoid fatals if close() was called
3701 $this->assertOpen();
3703 $this->doRollback( $fname );
3704 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3705 $this->trxAtomicLevels
= [];
3706 if ( $this->trxDoneWrites
) {
3707 $this->trxProfiler
->transactionWritingOut(
3715 // Clear any commit-dependant callbacks. They might even be present
3716 // only due to transaction rounds, with no SQL transaction being active
3717 $this->trxIdleCallbacks
= [];
3718 $this->trxPreCommitCallbacks
= [];
3722 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3723 } catch ( Exception
$e ) {
3724 // already logged; finish and let LoadBalancer move on during mass-rollback
3727 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3728 } catch ( Exception
$e ) {
3729 // already logged; let LoadBalancer move on during mass-rollback
3732 $this->affectedRowCount
= 0; // for the sake of consistency
3737 * Issues the ROLLBACK command to the database server.
3739 * @see Database::rollback()
3740 * @param string $fname
3742 protected function doRollback( $fname ) {
3743 if ( $this->trxLevel
) {
3744 # Disconnects cause rollback anyway, so ignore those errors
3745 $ignoreErrors = true;
3746 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3747 $this->trxLevel
= 0;
3751 public function flushSnapshot( $fname = __METHOD__
) {
3752 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3753 // This only flushes transactions to clear snapshots, not to write data
3754 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3755 throw new DBUnexpectedError(
3757 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3761 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3764 public function explicitTrxActive() {
3765 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3768 public function duplicateTableStructure(
3769 $oldName, $newName, $temporary = false, $fname = __METHOD__
3771 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3774 public function listTables( $prefix = null, $fname = __METHOD__
) {
3775 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3778 public function listViews( $prefix = null, $fname = __METHOD__
) {
3779 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3782 public function timestamp( $ts = 0 ) {
3783 $t = new ConvertibleTimestamp( $ts );
3784 // Let errors bubble up to avoid putting garbage in the DB
3785 return $t->getTimestamp( TS_MW
);
3788 public function timestampOrNull( $ts = null ) {
3789 if ( is_null( $ts ) ) {
3792 return $this->timestamp( $ts );
3796 public function affectedRows() {
3797 return ( $this->affectedRowCount
=== null )
3798 ?
$this->fetchAffectedRowCount() // default to driver value
3799 : $this->affectedRowCount
;
3803 * @return int Number of retrieved rows according to the driver
3805 abstract protected function fetchAffectedRowCount();
3808 * Take the result from a query, and wrap it in a ResultWrapper if
3809 * necessary. Boolean values are passed through as is, to indicate success
3810 * of write queries or failure.
3812 * Once upon a time, Database::query() returned a bare MySQL result
3813 * resource, and it was necessary to call this function to convert it to
3814 * a wrapper. Nowadays, raw database objects are never exposed to external
3815 * callers, so this is unnecessary in external code.
3817 * @param bool|ResultWrapper|resource|object $result
3818 * @return bool|ResultWrapper
3820 protected function resultObject( $result ) {
3823 } elseif ( $result instanceof ResultWrapper
) {
3825 } elseif ( $result === true ) {
3826 // Successful write query
3829 return new ResultWrapper( $this, $result );
3833 public function ping( &$rtt = null ) {
3834 // Avoid hitting the server if it was hit recently
3835 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3836 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3837 $rtt = $this->rttEstimate
;
3838 return true; // don't care about $rtt
3842 // This will reconnect if possible or return false if not
3843 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3844 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3845 $this->restoreFlags( self
::RESTORE_PRIOR
);
3848 $rtt = $this->rttEstimate
;
3855 * Close any existing (dead) database connection and open a new connection
3857 * @param string $fname
3858 * @return bool True if new connection is opened successfully, false if error
3860 protected function replaceLostConnection( $fname ) {
3861 $this->closeConnection();
3862 $this->opened
= false;
3863 $this->conn
= false;
3865 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3866 $this->lastPing
= microtime( true );
3869 $this->connLogger
->warning(
3870 $fname . ': lost connection to {dbserver}; reconnected',
3872 'dbserver' => $this->getServer(),
3873 'trace' => ( new RuntimeException() )->getTraceAsString()
3876 } catch ( DBConnectionError
$e ) {
3879 $this->connLogger
->error(
3880 $fname . ': lost connection to {dbserver} permanently',
3881 [ 'dbserver' => $this->getServer() ]
3885 $this->handleSessionLoss();
3890 public function getSessionLagStatus() {
3891 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3895 * Get the replica DB lag when the current transaction started
3897 * This is useful when transactions might use snapshot isolation
3898 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3899 * is this lag plus transaction duration. If they don't, it is still
3900 * safe to be pessimistic. This returns null if there is no transaction.
3902 * This returns null if the lag status for this transaction was not yet recorded.
3904 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3907 final protected function getRecordedTransactionLagStatus() {
3908 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
3909 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3914 * Get a replica DB lag estimate for this server
3916 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3919 protected function getApproximateLagStatus() {
3921 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3922 'since' => microtime( true )
3927 * Merge the result of getSessionLagStatus() for several DBs
3928 * using the most pessimistic values to estimate the lag of
3929 * any data derived from them in combination
3931 * This is information is useful for caching modules
3933 * @see WANObjectCache::set()
3934 * @see WANObjectCache::getWithSetCallback()
3936 * @param IDatabase $db1
3937 * @param IDatabase $db2 [optional]
3938 * @return array Map of values:
3939 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3940 * - since: oldest UNIX timestamp of any of the DB lag estimates
3941 * - pending: whether any of the DBs have uncommitted changes
3945 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3946 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3947 foreach ( func_get_args() as $db ) {
3948 /** @var IDatabase $db */
3949 $status = $db->getSessionLagStatus();
3950 if ( $status['lag'] === false ) {
3951 $res['lag'] = false;
3952 } elseif ( $res['lag'] !== false ) {
3953 $res['lag'] = max( $res['lag'], $status['lag'] );
3955 $res['since'] = min( $res['since'], $status['since'] );
3956 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3962 public function getLag() {
3966 public function maxListLen() {
3970 public function encodeBlob( $b ) {
3974 public function decodeBlob( $b ) {
3975 if ( $b instanceof Blob
) {
3981 public function setSessionOptions( array $options ) {
3984 public function sourceFile(
3986 callable
$lineCallback = null,
3987 callable
$resultCallback = null,
3989 callable
$inputCallback = null
3991 Wikimedia\
suppressWarnings();
3992 $fp = fopen( $filename, 'r' );
3993 Wikimedia\restoreWarnings
();
3995 if ( false === $fp ) {
3996 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4000 $fname = __METHOD__
. "( $filename )";
4004 $error = $this->sourceStream(
4005 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4006 } catch ( Exception
$e ) {
4016 public function setSchemaVars( $vars ) {
4017 $this->schemaVars
= $vars;
4020 public function sourceStream(
4022 callable
$lineCallback = null,
4023 callable
$resultCallback = null,
4024 $fname = __METHOD__
,
4025 callable
$inputCallback = null
4027 $delimiterReset = new ScopedCallback(
4028 function ( $delimiter ) {
4029 $this->delimiter
= $delimiter;
4031 [ $this->delimiter
]
4035 while ( !feof( $fp ) ) {
4036 if ( $lineCallback ) {
4037 call_user_func( $lineCallback );
4040 $line = trim( fgets( $fp ) );
4042 if ( $line == '' ) {
4046 if ( '-' == $line[0] && '-' == $line[1] ) {
4054 $done = $this->streamStatementEnd( $cmd, $line );
4058 if ( $done ||
feof( $fp ) ) {
4059 $cmd = $this->replaceVars( $cmd );
4061 if ( $inputCallback ) {
4062 $callbackResult = call_user_func( $inputCallback, $cmd );
4064 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4065 $cmd = $callbackResult;
4070 $res = $this->query( $cmd, $fname );
4072 if ( $resultCallback ) {
4073 call_user_func( $resultCallback, $res, $this );
4076 if ( false === $res ) {
4077 $err = $this->lastError();
4079 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4086 ScopedCallback
::consume( $delimiterReset );
4091 * Called by sourceStream() to check if we've reached a statement end
4093 * @param string &$sql SQL assembled so far
4094 * @param string &$newLine New line about to be added to $sql
4095 * @return bool Whether $newLine contains end of the statement
4097 public function streamStatementEnd( &$sql, &$newLine ) {
4098 if ( $this->delimiter
) {
4100 $newLine = preg_replace(
4101 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4102 if ( $newLine != $prev ) {
4111 * Database independent variable replacement. Replaces a set of variables
4112 * in an SQL statement with their contents as given by $this->getSchemaVars().
4114 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4116 * - '{$var}' should be used for text and is passed through the database's
4118 * - `{$var}` should be used for identifiers (e.g. table and database names).
4119 * It is passed through the database's addIdentifierQuotes method which
4120 * can be overridden if the database uses something other than backticks.
4121 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4122 * database's tableName method.
4123 * - / *i* / passes the name that follows through the database's indexName method.
4124 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4125 * its use should be avoided. In 1.24 and older, string encoding was applied.
4127 * @param string $ins SQL statement to replace variables in
4128 * @return string The new SQL statement with variables replaced
4130 protected function replaceVars( $ins ) {
4131 $vars = $this->getSchemaVars();
4132 return preg_replace_callback(
4134 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4135 \'\{\$ (\w+) }\' | # 3. addQuotes
4136 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4137 /\*\$ (\w+) \*/ # 5. leave unencoded
4139 function ( $m ) use ( $vars ) {
4140 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4141 // check for both nonexistent keys *and* the empty string.
4142 if ( isset( $m[1] ) && $m[1] !== '' ) {
4143 if ( $m[1] === 'i' ) {
4144 return $this->indexName( $m[2] );
4146 return $this->tableName( $m[2] );
4148 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4149 return $this->addQuotes( $vars[$m[3]] );
4150 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4151 return $this->addIdentifierQuotes( $vars[$m[4]] );
4152 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4153 return $vars[$m[5]];
4163 * Get schema variables. If none have been set via setSchemaVars(), then
4164 * use some defaults from the current object.
4168 protected function getSchemaVars() {
4169 if ( $this->schemaVars
) {
4170 return $this->schemaVars
;
4172 return $this->getDefaultSchemaVars();
4177 * Get schema variables to use if none have been set via setSchemaVars().
4179 * Override this in derived classes to provide variables for tables.sql
4180 * and SQL patch files.
4184 protected function getDefaultSchemaVars() {
4188 public function lockIsFree( $lockName, $method ) {
4189 // RDBMs methods for checking named locks may or may not count this thread itself.
4190 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4191 // the behavior choosen by the interface for this method.
4192 return !isset( $this->namedLocksHeld
[$lockName] );
4195 public function lock( $lockName, $method, $timeout = 5 ) {
4196 $this->namedLocksHeld
[$lockName] = 1;
4201 public function unlock( $lockName, $method ) {
4202 unset( $this->namedLocksHeld
[$lockName] );
4207 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4208 if ( $this->writesOrCallbacksPending() ) {
4209 // This only flushes transactions to clear snapshots, not to write data
4210 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4211 throw new DBUnexpectedError(
4213 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4217 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4221 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4222 if ( $this->trxLevel() ) {
4223 // There is a good chance an exception was thrown, causing any early return
4224 // from the caller. Let any error handler get a chance to issue rollback().
4225 // If there isn't one, let the error bubble up and trigger server-side rollback.
4226 $this->onTransactionResolution(
4227 function () use ( $lockKey, $fname ) {
4228 $this->unlock( $lockKey, $fname );
4233 $this->unlock( $lockKey, $fname );
4237 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4242 public function namedLocksEnqueue() {
4246 public function tableLocksHaveTransactionScope() {
4250 final public function lockTables( array $read, array $write, $method ) {
4251 if ( $this->writesOrCallbacksPending() ) {
4252 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4255 if ( $this->tableLocksHaveTransactionScope() ) {
4256 $this->startAtomic( $method );
4259 return $this->doLockTables( $read, $write, $method );
4263 * Helper function for lockTables() that handles the actual table locking
4265 * @param array $read Array of tables to lock for read access
4266 * @param array $write Array of tables to lock for write access
4267 * @param string $method Name of caller
4270 protected function doLockTables( array $read, array $write, $method ) {
4274 final public function unlockTables( $method ) {
4275 if ( $this->tableLocksHaveTransactionScope() ) {
4276 $this->endAtomic( $method );
4278 return true; // locks released on COMMIT/ROLLBACK
4281 return $this->doUnlockTables( $method );
4285 * Helper function for unlockTables() that handles the actual table unlocking
4287 * @param string $method Name of caller
4290 protected function doUnlockTables( $method ) {
4296 * @param string $tableName
4297 * @param string $fName
4298 * @return bool|ResultWrapper
4301 public function dropTable( $tableName, $fName = __METHOD__
) {
4302 if ( !$this->tableExists( $tableName, $fName ) ) {
4305 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4307 return $this->query( $sql, $fName );
4310 public function getInfinity() {
4314 public function encodeExpiry( $expiry ) {
4315 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4316 ?
$this->getInfinity()
4317 : $this->timestamp( $expiry );
4320 public function decodeExpiry( $expiry, $format = TS_MW
) {
4321 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4325 return ConvertibleTimestamp
::convert( $format, $expiry );
4328 public function setBigSelects( $value = true ) {
4332 public function isReadOnly() {
4333 return ( $this->getReadOnlyReason() !== false );
4337 * @return string|bool Reason this DB is read-only or false if it is not
4339 protected function getReadOnlyReason() {
4340 $reason = $this->getLBInfo( 'readOnlyReason' );
4342 return is_string( $reason ) ?
$reason : false;
4345 public function setTableAliases( array $aliases ) {
4346 $this->tableAliases
= $aliases;
4349 public function setIndexAliases( array $aliases ) {
4350 $this->indexAliases
= $aliases;
4354 * Get the underlying binding connection handle
4356 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4357 * This catches broken callers than catch and ignore disconnection exceptions.
4358 * Unlike checking isOpen(), this is safe to call inside of open().
4361 * @throws DBUnexpectedError
4364 protected function getBindingHandle() {
4365 if ( !$this->conn
) {
4366 throw new DBUnexpectedError(
4368 'DB connection was already closed or the connection dropped.'
4379 public function __toString() {
4380 return (string)$this->conn
;
4384 * Make sure that copies do not share the same client binding handle
4385 * @throws DBConnectionError
4387 public function __clone() {
4388 $this->connLogger
->warning(
4389 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4390 ( new RuntimeException() )->getTraceAsString()
4393 if ( $this->isOpen() ) {
4394 // Open a new connection resource without messing with the old one
4395 $this->opened
= false;
4396 $this->conn
= false;
4397 $this->trxEndCallbacks
= []; // don't copy
4398 $this->handleSessionLoss(); // no trx or locks anymore
4399 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4400 $this->lastPing
= microtime( true );
4405 * Called by serialize. Throw an exception when DB connection is serialized.
4406 * This causes problems on some database engines because the connection is
4407 * not restored on unserialize.
4409 public function __sleep() {
4410 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4411 'the connection is not restored on wakeup.' );
4415 * Run a few simple sanity checks and close dangling connections
4417 public function __destruct() {
4418 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4419 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4422 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4423 if ( $danglingWriters ) {
4424 $fnames = implode( ', ', $danglingWriters );
4425 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4428 if ( $this->conn
) {
4429 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4430 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4431 Wikimedia\
suppressWarnings();
4432 $this->closeConnection();
4433 Wikimedia\restoreWarnings
();
4434 $this->conn
= false;
4435 $this->opened
= false;
4440 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4441 class_alias( Database
::class, 'Database' ); // b/c global alias