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 * Either 1 if a transaction is active or 0 otherwise.
156 * The other Trx fields may not be meaningfull if this is 0.
160 protected $trxLevel = 0;
162 * Either a short hexidecimal string if a transaction is active or ""
165 * @see Database::trxLevel
167 protected $trxShortId = '';
169 * The UNIX time that the transaction started. Callers can assume that if
170 * snapshot isolation is used, then the data is *at least* up to date to that
171 * point (possibly more up-to-date since the first SELECT defines the snapshot).
174 * @see Database::trxLevel
176 private $trxTimestamp = null;
177 /** @var float Lag estimate at the time of BEGIN */
178 private $trxReplicaLag = null;
180 * Remembers the function name given for starting the most recent transaction via begin().
181 * Used to provide additional context for error reporting.
184 * @see Database::trxLevel
186 private $trxFname = null;
188 * Record if possible write queries were done in the last transaction started
191 * @see Database::trxLevel
193 private $trxDoneWrites = false;
195 * Record if the current transaction was started implicitly due to DBO_TRX being set.
198 * @see Database::trxLevel
200 private $trxAutomatic = false;
202 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
206 private $trxAtomicCounter = 0;
208 * Array of levels of atomicity within transactions
212 private $trxAtomicLevels = [];
214 * Record if the current transaction was started implicitly by Database::startAtomic
218 private $trxAutomaticAtomic = false;
220 * Track the write query callers of the current transaction
224 private $trxWriteCallers = [];
226 * @var float Seconds spent in write queries for the current transaction
228 private $trxWriteDuration = 0.0;
230 * @var int Number of write queries for the current transaction
232 private $trxWriteQueryCount = 0;
234 * @var int Number of rows affected by write queries for the current transaction
236 private $trxWriteAffectedRows = 0;
238 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
240 private $trxWriteAdjDuration = 0.0;
242 * @var int Number of write queries counted in trxWriteAdjDuration
244 private $trxWriteAdjQueryCount = 0;
246 * @var float RTT time estimate
248 private $rttEstimate = 0.0;
250 /** @var array Map of (name => 1) for locks obtained via lock() */
251 private $namedLocksHeld = [];
252 /** @var array Map of (table name => 1) for TEMPORARY tables */
253 protected $sessionTempTables = [];
255 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
256 private $lazyMasterHandle;
258 /** @var float UNIX timestamp */
259 protected $lastPing = 0.0;
261 /** @var int[] Prior flags member variable values */
262 private $priorFlags = [];
264 /** @var object|string Class name or object With profileIn/profileOut methods */
266 /** @var TransactionProfiler */
267 protected $trxProfiler;
270 protected $nonNativeInsertSelectBatchSize = 10000;
272 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
273 const STATUS_TRX_ERROR
= 1;
274 /** @var int Transaction is active and in a normal state */
275 const STATUS_TRX_OK
= 2;
276 /** @var int No transaction is active */
277 const STATUS_TRX_NONE
= 3;
280 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
281 * @param array $params Parameters passed from Database::factory()
283 protected function __construct( array $params ) {
284 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
285 $this->connectionParams
[$name] = $params[$name];
288 $this->schema
= $params['schema'];
289 $this->tablePrefix
= $params['tablePrefix'];
291 $this->cliMode
= $params['cliMode'];
292 // Agent name is added to SQL queries in a comment, so make sure it can't break out
293 $this->agent
= str_replace( '/', '-', $params['agent'] );
295 $this->flags
= $params['flags'];
296 if ( $this->flags
& self
::DBO_DEFAULT
) {
297 if ( $this->cliMode
) {
298 $this->flags
&= ~self
::DBO_TRX
;
300 $this->flags |
= self
::DBO_TRX
;
303 // Disregard deprecated DBO_IGNORE flag (T189999)
304 $this->flags
&= ~self
::DBO_IGNORE
;
306 $this->sessionVars
= $params['variables'];
308 $this->srvCache
= isset( $params['srvCache'] )
309 ?
$params['srvCache']
310 : new HashBagOStuff();
312 $this->profiler
= $params['profiler'];
313 $this->trxProfiler
= $params['trxProfiler'];
314 $this->connLogger
= $params['connLogger'];
315 $this->queryLogger
= $params['queryLogger'];
316 $this->errorLogger
= $params['errorLogger'];
317 $this->deprecationLogger
= $params['deprecationLogger'];
319 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
320 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
323 // Set initial dummy domain until open() sets the final DB/prefix
324 $this->currentDomain
= DatabaseDomain
::newUnspecified();
328 * Initialize the connection to the database over the wire (or to local files)
330 * @throws LogicException
331 * @throws InvalidArgumentException
332 * @throws DBConnectionError
335 final public function initConnection() {
336 if ( $this->isOpen() ) {
337 throw new LogicException( __METHOD__
. ': already connected.' );
339 // Establish the connection
340 $this->doInitConnection();
341 // Set the domain object after open() sets the relevant fields
342 if ( $this->dbName
!= '' ) {
343 // Domains with server scope but a table prefix are not used by IDatabase classes
344 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
349 * Actually connect to the database over the wire (or to local files)
351 * @throws InvalidArgumentException
352 * @throws DBConnectionError
355 protected function doInitConnection() {
356 if ( strlen( $this->connectionParams
['user'] ) ) {
358 $this->connectionParams
['host'],
359 $this->connectionParams
['user'],
360 $this->connectionParams
['password'],
361 $this->connectionParams
['dbname']
364 throw new InvalidArgumentException( "No database user provided." );
369 * Construct a Database subclass instance given a database type and parameters
371 * This also connects to the database immediately upon object construction
373 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
374 * @param array $p Parameter map with keys:
375 * - host : The hostname of the DB server
376 * - user : The name of the database user the client operates under
377 * - password : The password for the database user
378 * - dbname : The name of the database to use where queries do not specify one.
379 * The database must exist or an error might be thrown. Setting this to the empty string
380 * will avoid any such errors and make the handle have no implicit database scope. This is
381 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
382 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
383 * in which user names and such are defined, e.g. users are database-specific in Postgres.
384 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
385 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
386 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
387 * recognized in queries. This can be used in place of schemas for handle site farms.
388 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
389 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
390 * flag in place UNLESS this this database simply acts as a key/value store.
391 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
392 * 'mysqli' driver; the old one 'mysql' has been removed.
393 * - variables: Optional map of session variables to set after connecting. This can be
394 * used to adjust lock timeouts or encoding modes and the like.
395 * - connLogger: Optional PSR-3 logger interface instance.
396 * - queryLogger: Optional PSR-3 logger interface instance.
397 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
398 * These will be called in query(), using a simplified version of the SQL that also
399 * includes the agent as a SQL comment.
400 * - trxProfiler: Optional TransactionProfiler instance.
401 * - errorLogger: Optional callback that takes an Exception and logs it.
402 * - deprecationLogger: Optional callback that takes a string and logs it.
403 * - cliMode: Whether to consider the execution context that of a CLI script.
404 * - agent: Optional name used to identify the end-user in query profiling/logging.
405 * - srvCache: Optional BagOStuff instance to an APC-style cache.
406 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
407 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
408 * @return Database|null If the database driver or extension cannot be found
409 * @throws InvalidArgumentException If the database driver or extension cannot be found
412 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
413 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
415 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
416 // Resolve some defaults for b/c
417 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
418 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
419 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
420 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
421 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
422 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
423 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
424 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
425 $p['cliMode'] = isset( $p['cliMode'] )
427 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
428 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
429 if ( !isset( $p['connLogger'] ) ) {
430 $p['connLogger'] = new NullLogger();
432 if ( !isset( $p['queryLogger'] ) ) {
433 $p['queryLogger'] = new NullLogger();
435 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
436 if ( !isset( $p['trxProfiler'] ) ) {
437 $p['trxProfiler'] = new TransactionProfiler();
439 if ( !isset( $p['errorLogger'] ) ) {
440 $p['errorLogger'] = function ( Exception
$e ) {
441 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
444 if ( !isset( $p['deprecationLogger'] ) ) {
445 $p['deprecationLogger'] = function ( $msg ) {
446 trigger_error( $msg, E_USER_DEPRECATED
);
450 /** @var Database $conn */
451 $conn = new $class( $p );
452 if ( $connect == self
::NEW_CONNECTED
) {
453 $conn->initConnection();
463 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
464 * @param string|null $driver Optional name of a specific DB client driver
465 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
466 * @throws InvalidArgumentException
469 final public static function attributesFromType( $dbType, $driver = null ) {
470 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
472 $class = self
::getClass( $dbType, $driver );
474 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
478 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
479 * @param string|null $driver Optional name of a specific DB client driver
480 * @return string Database subclass name to use
481 * @throws InvalidArgumentException
483 private static function getClass( $dbType, $driver = null ) {
484 // For database types with built-in support, the below maps type to IDatabase
485 // implementations. For types with multipe driver implementations (PHP extensions),
486 // an array can be used, keyed by extension name. In case of an array, the
487 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
488 // we auto-detect the first available driver. For types without built-in support,
489 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
490 static $builtinTypes = [
491 'mssql' => DatabaseMssql
::class,
492 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
493 'sqlite' => DatabaseSqlite
::class,
494 'postgres' => DatabasePostgres
::class,
497 $dbType = strtolower( $dbType );
500 if ( isset( $builtinTypes[$dbType] ) ) {
501 $possibleDrivers = $builtinTypes[$dbType];
502 if ( is_string( $possibleDrivers ) ) {
503 $class = $possibleDrivers;
505 if ( (string)$driver !== '' ) {
506 if ( !isset( $possibleDrivers[$driver] ) ) {
507 throw new InvalidArgumentException( __METHOD__
.
508 " type '$dbType' does not support driver '{$driver}'" );
510 $class = $possibleDrivers[$driver];
513 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
514 if ( extension_loaded( $posDriver ) ) {
515 $class = $possibleClass;
522 $class = 'Database' . ucfirst( $dbType );
525 if ( $class === false ) {
526 throw new InvalidArgumentException( __METHOD__
.
527 " no viable database extension found for type '$dbType'" );
534 * @return array Map of (Database::ATTRIBUTE_* constant => value
537 protected static function getAttributes() {
542 * Set the PSR-3 logger interface to use for query logging. (The logger
543 * interfaces for connection logging and error logging can be set with the
546 * @param LoggerInterface $logger
548 public function setLogger( LoggerInterface
$logger ) {
549 $this->queryLogger
= $logger;
552 public function getServerInfo() {
553 return $this->getServerVersion();
556 public function bufferResults( $buffer = null ) {
557 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
558 if ( $buffer !== null ) {
560 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
561 : $this->setFlag( self
::DBO_NOBUFFER
);
567 public function trxLevel() {
568 return $this->trxLevel
;
571 public function trxTimestamp() {
572 return $this->trxLevel ?
$this->trxTimestamp
: null;
576 * @return int One of the STATUS_TRX_* class constants
579 public function trxStatus() {
580 return $this->trxStatus
;
583 public function tablePrefix( $prefix = null ) {
584 $old = $this->tablePrefix
;
585 if ( $prefix !== null ) {
586 $this->tablePrefix
= $prefix;
587 $this->currentDomain
= ( $this->dbName
!= '' )
588 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
589 : DatabaseDomain
::newUnspecified();
595 public function dbSchema( $schema = null ) {
596 $old = $this->schema
;
597 if ( $schema !== null ) {
598 $this->schema
= $schema;
604 public function getLBInfo( $name = null ) {
605 if ( is_null( $name ) ) {
606 return $this->lbInfo
;
608 if ( array_key_exists( $name, $this->lbInfo
) ) {
609 return $this->lbInfo
[$name];
616 public function setLBInfo( $name, $value = null ) {
617 if ( is_null( $value ) ) {
618 $this->lbInfo
= $name;
620 $this->lbInfo
[$name] = $value;
624 public function setLazyMasterHandle( IDatabase
$conn ) {
625 $this->lazyMasterHandle
= $conn;
629 * @return IDatabase|null
630 * @see setLazyMasterHandle()
633 protected function getLazyMasterHandle() {
634 return $this->lazyMasterHandle
;
637 public function implicitGroupby() {
641 public function implicitOrderby() {
645 public function lastQuery() {
646 return $this->lastQuery
;
649 public function doneWrites() {
650 return (bool)$this->lastWriteTime
;
653 public function lastDoneWrites() {
654 return $this->lastWriteTime ?
: false;
657 public function writesPending() {
658 return $this->trxLevel
&& $this->trxDoneWrites
;
661 public function writesOrCallbacksPending() {
662 return $this->trxLevel
&& (
663 $this->trxDoneWrites ||
664 $this->trxIdleCallbacks ||
665 $this->trxPreCommitCallbacks ||
666 $this->trxEndCallbacks
671 * @return string|null
673 final protected function getTransactionRoundId() {
674 // If transaction round participation is enabled, see if one is active
675 if ( $this->getFlag( self
::DBO_TRX
) ) {
676 $id = $this->getLBInfo( 'trxRoundId' );
678 return is_string( $id ) ?
$id : null;
684 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
685 if ( !$this->trxLevel
) {
687 } elseif ( !$this->trxDoneWrites
) {
692 case self
::ESTIMATE_DB_APPLY
:
694 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
695 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
696 // For omitted queries, make them count as something at least
697 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
698 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
701 default: // everything
702 return $this->trxWriteDuration
;
706 public function pendingWriteCallers() {
707 return $this->trxLevel ?
$this->trxWriteCallers
: [];
710 public function pendingWriteRowsAffected() {
711 return $this->trxWriteAffectedRows
;
715 * Get the list of method names that have pending write queries or callbacks
716 * for this transaction
720 protected function pendingWriteAndCallbackCallers() {
721 if ( !$this->trxLevel
) {
725 $fnames = $this->trxWriteCallers
;
727 $this->trxIdleCallbacks
,
728 $this->trxPreCommitCallbacks
,
729 $this->trxEndCallbacks
731 foreach ( $callbacks as $callback ) {
732 $fnames[] = $callback[1];
742 private function flatAtomicSectionList() {
743 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
744 return $accum === null ?
$v[0] : "$accum, " . $v[0];
748 public function isOpen() {
749 return $this->opened
;
752 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
753 if ( ( $flag & self
::DBO_IGNORE
) ) {
754 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
757 if ( $remember === self
::REMEMBER_PRIOR
) {
758 array_push( $this->priorFlags
, $this->flags
);
760 $this->flags |
= $flag;
763 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
764 if ( ( $flag & self
::DBO_IGNORE
) ) {
765 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
768 if ( $remember === self
::REMEMBER_PRIOR
) {
769 array_push( $this->priorFlags
, $this->flags
);
771 $this->flags
&= ~
$flag;
774 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
775 if ( !$this->priorFlags
) {
779 if ( $state === self
::RESTORE_INITIAL
) {
780 $this->flags
= reset( $this->priorFlags
);
781 $this->priorFlags
= [];
783 $this->flags
= array_pop( $this->priorFlags
);
787 public function getFlag( $flag ) {
788 return !!( $this->flags
& $flag );
792 * @param string $name Class field name
794 * @deprecated Since 1.28
796 public function getProperty( $name ) {
800 public function getDomainID() {
801 return $this->currentDomain
->getId();
804 final public function getWikiID() {
805 return $this->getDomainID();
809 * Get information about an index into an object
810 * @param string $table Table name
811 * @param string $index Index name
812 * @param string $fname Calling function name
813 * @return mixed Database-specific index description class or false if the index does not exist
815 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
818 * Wrapper for addslashes()
820 * @param string $s String to be slashed.
821 * @return string Slashed string.
823 abstract function strencode( $s );
826 * Set a custom error handler for logging errors during database connection
828 protected function installErrorHandler() {
829 $this->phpError
= false;
830 $this->htmlErrors
= ini_set( 'html_errors', '0' );
831 set_error_handler( [ $this, 'connectionErrorLogger' ] );
835 * Restore the previous error handler and return the last PHP error for this DB
837 * @return bool|string
839 protected function restoreErrorHandler() {
840 restore_error_handler();
841 if ( $this->htmlErrors
!== false ) {
842 ini_set( 'html_errors', $this->htmlErrors
);
845 return $this->getLastPHPError();
849 * @return string|bool Last PHP error for this DB (typically connection errors)
851 protected function getLastPHPError() {
852 if ( $this->phpError
) {
853 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
854 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
863 * Error handler for logging errors during database connection
864 * This method should not be used outside of Database classes
867 * @param string $errstr
869 public function connectionErrorLogger( $errno, $errstr ) {
870 $this->phpError
= $errstr;
874 * Create a log context to pass to PSR-3 logger functions.
876 * @param array $extras Additional data to add to context
879 protected function getLogContext( array $extras = [] ) {
882 'db_server' => $this->server
,
883 'db_name' => $this->dbName
,
884 'db_user' => $this->user
,
890 final public function close() {
891 $exception = null; // error to throw after disconnecting
894 // Resolve any dangling transaction first
895 if ( $this->trxLevel
) {
896 // Meaningful transactions should ideally have been resolved by now
897 if ( $this->writesOrCallbacksPending() ) {
898 $this->queryLogger
->warning(
899 __METHOD__
. ": writes or callbacks still pending.",
900 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
902 // Cannot let incomplete atomic sections be committed
903 if ( $this->trxAtomicLevels
) {
904 $levels = $this->flatAtomicSectionList();
905 $exception = new DBUnexpectedError(
907 __METHOD__
. ": atomic sections $levels are still open."
909 // Check if it is possible to properly commit and trigger callbacks
910 } elseif ( $this->trxEndCallbacksSuppressed
) {
911 $exception = new DBUnexpectedError(
913 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
917 // Commit or rollback the changes and run any callbacks as needed
918 if ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& !$exception ) {
919 $this->commit( __METHOD__
, self
::TRANSACTION_INTERNAL
);
921 $this->rollback( __METHOD__
, self
::TRANSACTION_INTERNAL
);
924 // Close the actual connection in the binding handle
925 $closed = $this->closeConnection();
928 $closed = true; // already closed; nothing to do
931 $this->opened
= false;
933 // Throw any unexpected errors after having disconnected
934 if ( $exception instanceof Exception
) {
938 // Sanity check that no callbacks are dangling
940 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
942 throw new RuntimeException(
943 "Transaction callbacks are still pending:\n" .
944 implode( ', ', $this->pendingWriteAndCallbackCallers() )
952 * Make sure isOpen() returns true as a sanity check
954 * @throws DBUnexpectedError
956 protected function assertOpen() {
957 if ( !$this->isOpen() ) {
958 throw new DBUnexpectedError( $this, "DB connection was already closed." );
963 * Closes underlying database connection
965 * @return bool Whether connection was closed successfully
967 abstract protected function closeConnection();
970 * @param string $error Fallback error message, used if none is given by DB
971 * @throws DBConnectionError
973 public function reportConnectionError( $error = 'Unknown error' ) {
974 $myError = $this->lastError();
980 throw new DBConnectionError( $this, $error );
984 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
986 * This might return things, such as mysqli_result, that do not formally implement
987 * IResultWrapper, but nonetheless implement all of its methods correctly
989 * @param string $sql SQL query.
990 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
992 abstract protected function doQuery( $sql );
995 * Determine whether a query writes to the DB.
996 * Should return true if unsure.
1001 protected function isWriteQuery( $sql ) {
1003 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1007 * @param string $sql
1008 * @return string|null
1010 protected function getQueryVerb( $sql ) {
1011 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1015 * Determine whether a SQL statement is sensitive to isolation level.
1016 * A SQL statement is considered transactable if its result could vary
1017 * depending on the transaction isolation level. Operational commands
1018 * such as 'SET' and 'SHOW' are not considered to be transactable.
1020 * @param string $sql
1023 protected function isTransactableQuery( $sql ) {
1025 $this->getQueryVerb( $sql ),
1026 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1032 * @param string $sql A SQL query
1033 * @return bool Whether $sql is SQL for TEMPORARY table operation
1035 protected function registerTempTableOperation( $sql ) {
1037 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1041 $this->sessionTempTables
[$matches[1]] = 1;
1044 } elseif ( preg_match(
1045 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1049 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1050 unset( $this->sessionTempTables
[$matches[1]] );
1053 } elseif ( preg_match(
1054 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1058 return isset( $this->sessionTempTables
[$matches[1]] );
1059 } elseif ( preg_match(
1060 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1064 return isset( $this->sessionTempTables
[$matches[1]] );
1070 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1071 $this->assertTransactionStatus( $sql, $fname );
1073 $priorWritesPending = $this->writesOrCallbacksPending();
1074 $this->lastQuery
= $sql;
1076 $isWrite = $this->isWriteQuery( $sql );
1078 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1080 $isNonTempWrite = false;
1084 if ( $this->getLBInfo( 'replica' ) === true ) {
1087 'Write operations are not allowed on replica database connections.'
1090 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1091 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1092 $reason = $this->getReadOnlyReason();
1093 if ( $reason !== false ) {
1094 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1096 # Set a flag indicating that writes have been done
1097 $this->lastWriteTime
= microtime( true );
1100 # Add trace comment to the begin of the sql string, right after the operator.
1101 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1102 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1104 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1105 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1106 && $this->isTransactableQuery( $sql )
1108 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1109 $this->trxAutomatic
= true;
1112 # Keep track of whether the transaction has write queries pending
1113 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1114 $this->trxDoneWrites
= true;
1115 $this->trxProfiler
->transactionWritingIn(
1116 $this->server
, $this->dbName
, $this->trxShortId
);
1119 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1120 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1123 # Avoid fatals if close() was called
1124 $this->assertOpen();
1126 # Send the query to the server and fetch any corresponding errors
1127 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1128 $lastError = $this->lastError();
1129 $lastErrno = $this->lastErrno();
1131 # Try reconnecting if the connection was lost
1132 if ( $ret === false && $this->wasConnectionLoss() ) {
1133 # Check if any meaningful session state was lost
1134 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1135 # Update session state tracking and try to restore the connection
1136 $reconnected = $this->replaceLostConnection( __METHOD__
);
1137 # Silently resend the query to the server if it is safe and possible
1138 if ( $reconnected && $recoverable ) {
1139 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1140 $lastError = $this->lastError();
1141 $lastErrno = $this->lastErrno();
1143 if ( $ret === false && $this->wasConnectionLoss() ) {
1144 # Query probably causes disconnects; reconnect and do not re-run it
1145 $this->replaceLostConnection( __METHOD__
);
1150 if ( $ret === false ) {
1151 if ( $this->trxLevel
&& !$this->wasKnownStatementRollbackError() ) {
1152 # Either the query was aborted or all queries after BEGIN where aborted.
1153 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1154 # In the first case, the only options going forward are (a) ROLLBACK, or
1155 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1156 # option is ROLLBACK, since the snapshots would have been released.
1157 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1158 $this->trxStatusCause
=
1159 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1160 $tempIgnore = false; // cannot recover
1162 # Nothing prior was there to lose from the transaction,
1163 # so just roll it back.
1164 $this->doRollback( __METHOD__
. " ($fname)" );
1165 $this->trxStatus
= self
::STATUS_TRX_OK
;
1169 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1172 return $this->resultObject( $ret );
1176 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1178 * @param string $sql Original SQL query
1179 * @param string $commentedSql SQL query with debugging/trace comment
1180 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1181 * @param string $fname Name of the calling function
1182 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1183 * object for a successful read query, or false on failure
1185 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1186 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1187 # generalizeSQL() will probably cut down the query to reasonable
1188 # logging size most of the time. The substr is really just a sanity check.
1190 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1192 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1195 # Include query transaction state
1196 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1198 $startTime = microtime( true );
1199 if ( $this->profiler
) {
1200 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1202 $this->affectedRowCount
= null;
1203 $ret = $this->doQuery( $commentedSql );
1204 $this->affectedRowCount
= $this->affectedRows();
1205 if ( $this->profiler
) {
1206 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1208 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1210 unset( $queryProfSection ); // profile out (if set)
1212 if ( $ret !== false ) {
1213 $this->lastPing
= $startTime;
1214 if ( $isWrite && $this->trxLevel
) {
1215 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1216 $this->trxWriteCallers
[] = $fname;
1220 if ( $sql === self
::PING_QUERY
) {
1221 $this->rttEstimate
= $queryRuntime;
1224 $this->trxProfiler
->recordQueryCompletion(
1225 $queryProf, $startTime, $isWrite, $this->affectedRows()
1227 $this->queryLogger
->debug( $sql, [
1229 'master' => $isMaster,
1230 'runtime' => $queryRuntime,
1237 * Update the estimated run-time of a query, not counting large row lock times
1239 * LoadBalancer can be set to rollback transactions that will create huge replication
1240 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1241 * queries, like inserting a row can take a long time due to row locking. This method
1242 * uses some simple heuristics to discount those cases.
1244 * @param string $sql A SQL write query
1245 * @param float $runtime Total runtime, including RTT
1246 * @param int $affected Affected row count
1248 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1249 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1250 $indicativeOfReplicaRuntime = true;
1251 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1252 $verb = $this->getQueryVerb( $sql );
1253 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1254 if ( $verb === 'INSERT' ) {
1255 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1256 } elseif ( $verb === 'REPLACE' ) {
1257 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1261 $this->trxWriteDuration +
= $runtime;
1262 $this->trxWriteQueryCount +
= 1;
1263 $this->trxWriteAffectedRows +
= $affected;
1264 if ( $indicativeOfReplicaRuntime ) {
1265 $this->trxWriteAdjDuration +
= $runtime;
1266 $this->trxWriteAdjQueryCount +
= 1;
1271 * @param string $sql
1272 * @param string $fname
1273 * @throws DBTransactionStateError
1275 private function assertTransactionStatus( $sql, $fname ) {
1277 $this->trxStatus
< self
::STATUS_TRX_OK
&&
1278 $this->getQueryVerb( $sql ) !== 'ROLLBACK' // transaction/savepoint
1280 throw new DBTransactionStateError(
1282 "Cannot execute query from $fname while transaction status is ERROR. ",
1284 $this->trxStatusCause
1290 * Determine whether or not it is safe to retry queries after a database
1291 * connection is lost
1293 * @param string $sql SQL query
1294 * @param bool $priorWritesPending Whether there is a transaction open with
1295 * possible write queries or transaction pre-commit/idle callbacks
1296 * waiting on it to finish.
1297 * @return bool True if it is safe to retry the query, false otherwise
1299 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1300 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1301 # Dropped connections also mean that named locks are automatically released.
1302 # Only allow error suppression in autocommit mode or when the lost transaction
1303 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1304 if ( $this->namedLocksHeld
) {
1305 return false; // possible critical section violation
1306 } elseif ( $this->sessionTempTables
) {
1307 return false; // tables might be queried latter
1308 } elseif ( $sql === 'COMMIT' ) {
1309 return !$priorWritesPending; // nothing written anyway? (T127428)
1310 } elseif ( $sql === 'ROLLBACK' ) {
1311 return true; // transaction lost...which is also what was requested :)
1312 } elseif ( $this->explicitTrxActive() ) {
1313 return false; // don't drop atomocity and explicit snapshots
1314 } elseif ( $priorWritesPending ) {
1315 return false; // prior writes lost from implicit transaction
1322 * Clean things up after session (and thus transaction) loss
1324 private function handleSessionLoss() {
1325 // Clean up tracking of session-level things...
1326 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1327 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1328 $this->sessionTempTables
= [];
1329 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1330 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1331 $this->namedLocksHeld
= [];
1332 // Session loss implies transaction loss
1333 $this->handleTransactionLoss();
1337 * Clean things up after transaction loss
1339 private function handleTransactionLoss() {
1340 $this->trxLevel
= 0;
1341 $this->trxAtomicCounter
= 0;
1342 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1343 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1345 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1346 // If callback suppression is set then the array will remain unhandled.
1347 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1348 } catch ( Exception
$ex ) {
1349 // Already logged; move on...
1352 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1353 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1354 } catch ( Exception
$ex ) {
1355 // Already logged; move on...
1360 * Checks whether the cause of the error is detected to be a timeout.
1362 * It returns false by default, and not all engines support detecting this yet.
1363 * If this returns false, it will be treated as a generic query error.
1365 * @param string $error Error text
1366 * @param int $errno Error number
1369 protected function wasQueryTimeout( $error, $errno ) {
1374 * Report a query error. Log the error, and if neither the object ignore
1375 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1377 * @param string $error
1379 * @param string $sql
1380 * @param string $fname
1381 * @param bool $tempIgnore
1382 * @throws DBQueryError
1384 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1385 if ( $tempIgnore ) {
1386 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1388 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1395 * @param string $error
1396 * @param string|int $errno
1397 * @param string $sql
1398 * @param string $fname
1401 private function makeQueryException( $error, $errno, $sql, $fname ) {
1402 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1403 $this->queryLogger
->error(
1404 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1405 $this->getLogContext( [
1406 'method' => __METHOD__
,
1409 'sql1line' => $sql1line,
1413 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1414 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1415 if ( $wasQueryTimeout ) {
1416 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1418 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1424 public function freeResult( $res ) {
1427 public function selectField(
1428 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1430 if ( $var === '*' ) { // sanity
1431 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1434 if ( !is_array( $options ) ) {
1435 $options = [ $options ];
1438 $options['LIMIT'] = 1;
1440 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1441 if ( $res === false ||
!$this->numRows( $res ) ) {
1445 $row = $this->fetchRow( $res );
1447 if ( $row !== false ) {
1448 return reset( $row );
1454 public function selectFieldValues(
1455 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1457 if ( $var === '*' ) { // sanity
1458 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1459 } elseif ( !is_string( $var ) ) { // sanity
1460 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1463 if ( !is_array( $options ) ) {
1464 $options = [ $options ];
1467 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1468 if ( $res === false ) {
1473 foreach ( $res as $row ) {
1474 $values[] = $row->$var;
1481 * Returns an optional USE INDEX clause to go after the table, and a
1482 * string to go at the end of the query.
1484 * @param array $options Associative array of options to be turned into
1485 * an SQL query, valid keys are listed in the function.
1487 * @see Database::select()
1489 protected function makeSelectOptions( $options ) {
1490 $preLimitTail = $postLimitTail = '';
1495 foreach ( $options as $key => $option ) {
1496 if ( is_numeric( $key ) ) {
1497 $noKeyOptions[$option] = true;
1501 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1503 $preLimitTail .= $this->makeOrderBy( $options );
1505 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1506 $postLimitTail .= ' FOR UPDATE';
1509 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1510 $postLimitTail .= ' LOCK IN SHARE MODE';
1513 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1514 $startOpts .= 'DISTINCT';
1517 # Various MySQL extensions
1518 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1519 $startOpts .= ' /*! STRAIGHT_JOIN */';
1522 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1523 $startOpts .= ' HIGH_PRIORITY';
1526 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1527 $startOpts .= ' SQL_BIG_RESULT';
1530 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1531 $startOpts .= ' SQL_BUFFER_RESULT';
1534 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1535 $startOpts .= ' SQL_SMALL_RESULT';
1538 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1539 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1542 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1543 $startOpts .= ' SQL_CACHE';
1546 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1547 $startOpts .= ' SQL_NO_CACHE';
1550 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1551 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1555 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1556 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1561 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1565 * Returns an optional GROUP BY with an optional HAVING
1567 * @param array $options Associative array of options
1569 * @see Database::select()
1572 protected function makeGroupByWithHaving( $options ) {
1574 if ( isset( $options['GROUP BY'] ) ) {
1575 $gb = is_array( $options['GROUP BY'] )
1576 ?
implode( ',', $options['GROUP BY'] )
1577 : $options['GROUP BY'];
1578 $sql .= ' GROUP BY ' . $gb;
1580 if ( isset( $options['HAVING'] ) ) {
1581 $having = is_array( $options['HAVING'] )
1582 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1583 : $options['HAVING'];
1584 $sql .= ' HAVING ' . $having;
1591 * Returns an optional ORDER BY
1593 * @param array $options Associative array of options
1595 * @see Database::select()
1598 protected function makeOrderBy( $options ) {
1599 if ( isset( $options['ORDER BY'] ) ) {
1600 $ob = is_array( $options['ORDER BY'] )
1601 ?
implode( ',', $options['ORDER BY'] )
1602 : $options['ORDER BY'];
1604 return ' ORDER BY ' . $ob;
1610 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1611 $options = [], $join_conds = [] ) {
1612 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1614 return $this->query( $sql, $fname );
1617 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1618 $options = [], $join_conds = []
1620 if ( is_array( $vars ) ) {
1621 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1624 $options = (array)$options;
1625 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1626 ?
$options['USE INDEX']
1629 isset( $options['IGNORE INDEX'] ) &&
1630 is_array( $options['IGNORE INDEX'] )
1632 ?
$options['IGNORE INDEX']
1635 if ( is_array( $table ) ) {
1637 $this->tableNamesWithIndexClauseOrJOIN(
1638 $table, $useIndexes, $ignoreIndexes, $join_conds );
1639 } elseif ( $table != '' ) {
1641 $this->tableNamesWithIndexClauseOrJOIN(
1642 [ $table ], $useIndexes, $ignoreIndexes, [] );
1647 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1648 $this->makeSelectOptions( $options );
1650 if ( is_array( $conds ) ) {
1651 $conds = $this->makeList( $conds, self
::LIST_AND
);
1654 if ( $conds === null ||
$conds === false ) {
1655 $this->queryLogger
->warning(
1659 . ' with incorrect parameters: $conds must be a string or an array'
1664 if ( $conds === '' ) {
1665 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1666 } elseif ( is_string( $conds ) ) {
1667 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1668 "WHERE $conds $preLimitTail";
1670 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1673 if ( isset( $options['LIMIT'] ) ) {
1674 $sql = $this->limitResult( $sql, $options['LIMIT'],
1675 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1677 $sql = "$sql $postLimitTail";
1679 if ( isset( $options['EXPLAIN'] ) ) {
1680 $sql = 'EXPLAIN ' . $sql;
1686 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1687 $options = [], $join_conds = []
1689 $options = (array)$options;
1690 $options['LIMIT'] = 1;
1691 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1693 if ( $res === false ) {
1697 if ( !$this->numRows( $res ) ) {
1701 $obj = $this->fetchObject( $res );
1706 public function estimateRowCount(
1707 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1709 $conds = $this->normalizeConditions( $conds, $fname );
1710 $column = $this->extractSingleFieldFromList( $var );
1711 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1712 $conds[] = "$column IS NOT NULL";
1715 $res = $this->select(
1716 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1718 $row = $res ?
$this->fetchRow( $res ) : [];
1720 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1723 public function selectRowCount(
1724 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1726 $conds = $this->normalizeConditions( $conds, $fname );
1727 $column = $this->extractSingleFieldFromList( $var );
1728 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1729 $conds[] = "$column IS NOT NULL";
1732 $res = $this->select(
1734 'tmp_count' => $this->buildSelectSubquery(
1743 [ 'rowcount' => 'COUNT(*)' ],
1747 $row = $res ?
$this->fetchRow( $res ) : [];
1749 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1753 * @param array|string $conds
1754 * @param string $fname
1757 final protected function normalizeConditions( $conds, $fname ) {
1758 if ( $conds === null ||
$conds === false ) {
1759 $this->queryLogger
->warning(
1763 . ' with incorrect parameters: $conds must be a string or an array'
1768 if ( !is_array( $conds ) ) {
1769 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1776 * @param array|string $var Field parameter in the style of select()
1777 * @return string|null Column name or null; ignores aliases
1778 * @throws DBUnexpectedError Errors out if multiple columns are given
1780 final protected function extractSingleFieldFromList( $var ) {
1781 if ( is_array( $var ) ) {
1784 } elseif ( count( $var ) == 1 ) {
1785 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1787 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1797 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1798 * It's only slightly flawed. Don't use for anything important.
1800 * @param string $sql A SQL Query
1804 protected static function generalizeSQL( $sql ) {
1805 # This does the same as the regexp below would do, but in such a way
1806 # as to avoid crashing php on some large strings.
1807 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1809 $sql = str_replace( "\\\\", '', $sql );
1810 $sql = str_replace( "\\'", '', $sql );
1811 $sql = str_replace( "\\\"", '', $sql );
1812 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1813 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1815 # All newlines, tabs, etc replaced by single space
1816 $sql = preg_replace( '/\s+/', ' ', $sql );
1819 # except the ones surrounded by characters, e.g. l10n
1820 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1821 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1826 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1827 $info = $this->fieldInfo( $table, $field );
1832 public function indexExists( $table, $index, $fname = __METHOD__
) {
1833 if ( !$this->tableExists( $table ) ) {
1837 $info = $this->indexInfo( $table, $index, $fname );
1838 if ( is_null( $info ) ) {
1841 return $info !== false;
1845 public function tableExists( $table, $fname = __METHOD__
) {
1846 $tableRaw = $this->tableName( $table, 'raw' );
1847 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1848 return true; // already known to exist
1851 $table = $this->tableName( $table );
1852 $ignoreErrors = true;
1853 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1858 public function indexUnique( $table, $index ) {
1859 $indexInfo = $this->indexInfo( $table, $index );
1861 if ( !$indexInfo ) {
1865 return !$indexInfo[0]->Non_unique
;
1869 * Helper for Database::insert().
1871 * @param array $options
1874 protected function makeInsertOptions( $options ) {
1875 return implode( ' ', $options );
1878 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1879 # No rows to insert, easy just return now
1880 if ( !count( $a ) ) {
1884 $table = $this->tableName( $table );
1886 if ( !is_array( $options ) ) {
1887 $options = [ $options ];
1891 if ( isset( $options['fileHandle'] ) ) {
1892 $fh = $options['fileHandle'];
1894 $options = $this->makeInsertOptions( $options );
1896 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1898 $keys = array_keys( $a[0] );
1901 $keys = array_keys( $a );
1904 $sql = 'INSERT ' . $options .
1905 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1909 foreach ( $a as $row ) {
1915 $sql .= '(' . $this->makeList( $row ) . ')';
1918 $sql .= '(' . $this->makeList( $a ) . ')';
1921 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1923 } elseif ( $fh !== null ) {
1927 return (bool)$this->query( $sql, $fname );
1931 * Make UPDATE options array for Database::makeUpdateOptions
1933 * @param array $options
1936 protected function makeUpdateOptionsArray( $options ) {
1937 if ( !is_array( $options ) ) {
1938 $options = [ $options ];
1943 if ( in_array( 'IGNORE', $options ) ) {
1951 * Make UPDATE options for the Database::update function
1953 * @param array $options The options passed to Database::update
1956 protected function makeUpdateOptions( $options ) {
1957 $opts = $this->makeUpdateOptionsArray( $options );
1959 return implode( ' ', $opts );
1962 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1963 $table = $this->tableName( $table );
1964 $opts = $this->makeUpdateOptions( $options );
1965 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1967 if ( $conds !== [] && $conds !== '*' ) {
1968 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1971 return (bool)$this->query( $sql, $fname );
1974 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1975 if ( !is_array( $a ) ) {
1976 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1982 foreach ( $a as $field => $value ) {
1984 if ( $mode == self
::LIST_AND
) {
1986 } elseif ( $mode == self
::LIST_OR
) {
1995 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1996 $list .= "($value)";
1997 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2000 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2002 // Remove null from array to be handled separately if found
2003 $includeNull = false;
2004 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2005 $includeNull = true;
2006 unset( $value[$nullKey] );
2008 if ( count( $value ) == 0 && !$includeNull ) {
2009 throw new InvalidArgumentException(
2010 __METHOD__
. ": empty input for field $field" );
2011 } elseif ( count( $value ) == 0 ) {
2012 // only check if $field is null
2013 $list .= "$field IS NULL";
2015 // IN clause contains at least one valid element
2016 if ( $includeNull ) {
2017 // Group subconditions to ensure correct precedence
2020 if ( count( $value ) == 1 ) {
2021 // Special-case single values, as IN isn't terribly efficient
2022 // Don't necessarily assume the single key is 0; we don't
2023 // enforce linear numeric ordering on other arrays here.
2024 $value = array_values( $value )[0];
2025 $list .= $field . " = " . $this->addQuotes( $value );
2027 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2029 // if null present in array, append IS NULL
2030 if ( $includeNull ) {
2031 $list .= " OR $field IS NULL)";
2034 } elseif ( $value === null ) {
2035 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2036 $list .= "$field IS ";
2037 } elseif ( $mode == self
::LIST_SET
) {
2038 $list .= "$field = ";
2043 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2045 $list .= "$field = ";
2047 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2054 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2057 foreach ( $data as $base => $sub ) {
2058 if ( count( $sub ) ) {
2059 $conds[] = $this->makeList(
2060 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2066 return $this->makeList( $conds, self
::LIST_OR
);
2068 // Nothing to search for...
2073 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2077 public function bitNot( $field ) {
2081 public function bitAnd( $fieldLeft, $fieldRight ) {
2082 return "($fieldLeft & $fieldRight)";
2085 public function bitOr( $fieldLeft, $fieldRight ) {
2086 return "($fieldLeft | $fieldRight)";
2089 public function buildConcat( $stringList ) {
2090 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2093 public function buildGroupConcatField(
2094 $delim, $table, $field, $conds = '', $join_conds = []
2096 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2098 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2101 public function buildSubstring( $input, $startPosition, $length = null ) {
2102 $this->assertBuildSubstringParams( $startPosition, $length );
2103 $functionBody = "$input FROM $startPosition";
2104 if ( $length !== null ) {
2105 $functionBody .= " FOR $length";
2107 return 'SUBSTRING(' . $functionBody . ')';
2111 * Check type and bounds for parameters to self::buildSubstring()
2113 * All supported databases have substring functions that behave the same for
2114 * positive $startPosition and non-negative $length, but behaviors differ when
2115 * given 0 or negative $startPosition or negative $length. The simplest
2116 * solution to that is to just forbid those values.
2118 * @param int $startPosition
2119 * @param int|null $length
2122 protected function assertBuildSubstringParams( $startPosition, $length ) {
2123 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2124 throw new InvalidArgumentException(
2125 '$startPosition must be a positive integer'
2128 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2129 throw new InvalidArgumentException(
2130 '$length must be null or an integer greater than or equal to 0'
2135 public function buildStringCast( $field ) {
2139 public function buildIntegerCast( $field ) {
2140 return 'CAST( ' . $field . ' AS INTEGER )';
2143 public function buildSelectSubquery(
2144 $table, $vars, $conds = '', $fname = __METHOD__
,
2145 $options = [], $join_conds = []
2147 return new Subquery(
2148 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2152 public function databasesAreIndependent() {
2156 public function selectDB( $db ) {
2157 # Stub. Shouldn't cause serious problems if it's not overridden, but
2158 # if your database engine supports a concept similar to MySQL's
2159 # databases you may as well.
2160 $this->dbName
= $db;
2165 public function getDBname() {
2166 return $this->dbName
;
2169 public function getServer() {
2170 return $this->server
;
2173 public function tableName( $name, $format = 'quoted' ) {
2174 if ( $name instanceof Subquery
) {
2175 throw new DBUnexpectedError(
2177 __METHOD__
. ': got Subquery instance when expecting a string.'
2181 # Skip the entire process when we have a string quoted on both ends.
2182 # Note that we check the end so that we will still quote any use of
2183 # use of `database`.table. But won't break things if someone wants
2184 # to query a database table with a dot in the name.
2185 if ( $this->isQuotedIdentifier( $name ) ) {
2189 # Lets test for any bits of text that should never show up in a table
2190 # name. Basically anything like JOIN or ON which are actually part of
2191 # SQL queries, but may end up inside of the table value to combine
2192 # sql. Such as how the API is doing.
2193 # Note that we use a whitespace test rather than a \b test to avoid
2194 # any remote case where a word like on may be inside of a table name
2195 # surrounded by symbols which may be considered word breaks.
2196 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2197 $this->queryLogger
->warning(
2198 __METHOD__
. ": use of subqueries is not supported this way.",
2199 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2205 # Split database and table into proper variables.
2206 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2208 # Quote $table and apply the prefix if not quoted.
2209 # $tableName might be empty if this is called from Database::replaceVars()
2210 $tableName = "{$prefix}{$table}";
2211 if ( $format === 'quoted'
2212 && !$this->isQuotedIdentifier( $tableName )
2213 && $tableName !== ''
2215 $tableName = $this->addIdentifierQuotes( $tableName );
2218 # Quote $schema and $database and merge them with the table name if needed
2219 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2220 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2226 * Get the table components needed for a query given the currently selected database
2228 * @param string $name Table name in the form of db.schema.table, db.table, or table
2229 * @return array (DB name or "" for default, schema name, table prefix, table name)
2231 protected function qualifiedTableComponents( $name ) {
2232 # We reverse the explode so that database.table and table both output the correct table.
2233 $dbDetails = explode( '.', $name, 3 );
2234 if ( count( $dbDetails ) == 3 ) {
2235 list( $database, $schema, $table ) = $dbDetails;
2236 # We don't want any prefix added in this case
2238 } elseif ( count( $dbDetails ) == 2 ) {
2239 list( $database, $table ) = $dbDetails;
2240 # We don't want any prefix added in this case
2242 # In dbs that support it, $database may actually be the schema
2243 # but that doesn't affect any of the functionality here
2246 list( $table ) = $dbDetails;
2247 if ( isset( $this->tableAliases
[$table] ) ) {
2248 $database = $this->tableAliases
[$table]['dbname'];
2249 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2250 ?
$this->tableAliases
[$table]['schema']
2252 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2253 ?
$this->tableAliases
[$table]['prefix']
2254 : $this->tablePrefix
;
2257 $schema = $this->schema
; # Default schema
2258 $prefix = $this->tablePrefix
; # Default prefix
2262 return [ $database, $schema, $prefix, $table ];
2266 * @param string|null $namespace Database or schema
2267 * @param string $relation Name of table, view, sequence, etc...
2268 * @param string $format One of (raw, quoted)
2269 * @return string Relation name with quoted and merged $namespace as needed
2271 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2272 if ( strlen( $namespace ) ) {
2273 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2274 $namespace = $this->addIdentifierQuotes( $namespace );
2276 $relation = $namespace . '.' . $relation;
2282 public function tableNames() {
2283 $inArray = func_get_args();
2286 foreach ( $inArray as $name ) {
2287 $retVal[$name] = $this->tableName( $name );
2293 public function tableNamesN() {
2294 $inArray = func_get_args();
2297 foreach ( $inArray as $name ) {
2298 $retVal[] = $this->tableName( $name );
2305 * Get an aliased table name
2307 * This returns strings like "tableName AS newTableName" for aliased tables
2308 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2310 * @see Database::tableName()
2311 * @param string|Subquery $table Table name or object with a 'sql' field
2312 * @param string|bool $alias Table alias (optional)
2313 * @return string SQL name for aliased table. Will not alias a table to its own name
2315 protected function tableNameWithAlias( $table, $alias = false ) {
2316 if ( is_string( $table ) ) {
2317 $quotedTable = $this->tableName( $table );
2318 } elseif ( $table instanceof Subquery
) {
2319 $quotedTable = (string)$table;
2321 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2324 if ( !strlen( $alias ) ||
$alias === $table ) {
2325 if ( $table instanceof Subquery
) {
2326 throw new InvalidArgumentException( "Subquery table missing alias." );
2329 return $quotedTable;
2331 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2336 * Gets an array of aliased table names
2338 * @param array $tables [ [alias] => table ]
2339 * @return string[] See tableNameWithAlias()
2341 protected function tableNamesWithAlias( $tables ) {
2343 foreach ( $tables as $alias => $table ) {
2344 if ( is_numeric( $alias ) ) {
2347 $retval[] = $this->tableNameWithAlias( $table, $alias );
2354 * Get an aliased field name
2355 * e.g. fieldName AS newFieldName
2357 * @param string $name Field name
2358 * @param string|bool $alias Alias (optional)
2359 * @return string SQL name for aliased field. Will not alias a field to its own name
2361 protected function fieldNameWithAlias( $name, $alias = false ) {
2362 if ( !$alias ||
(string)$alias === (string)$name ) {
2365 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2370 * Gets an array of aliased field names
2372 * @param array $fields [ [alias] => field ]
2373 * @return string[] See fieldNameWithAlias()
2375 protected function fieldNamesWithAlias( $fields ) {
2377 foreach ( $fields as $alias => $field ) {
2378 if ( is_numeric( $alias ) ) {
2381 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2388 * Get the aliased table name clause for a FROM clause
2389 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2391 * @param array $tables ( [alias] => table )
2392 * @param array $use_index Same as for select()
2393 * @param array $ignore_index Same as for select()
2394 * @param array $join_conds Same as for select()
2397 protected function tableNamesWithIndexClauseOrJOIN(
2398 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2402 $use_index = (array)$use_index;
2403 $ignore_index = (array)$ignore_index;
2404 $join_conds = (array)$join_conds;
2406 foreach ( $tables as $alias => $table ) {
2407 if ( !is_string( $alias ) ) {
2408 // No alias? Set it equal to the table name
2412 if ( is_array( $table ) ) {
2413 // A parenthesized group
2414 if ( count( $table ) > 1 ) {
2415 $joinedTable = '(' .
2416 $this->tableNamesWithIndexClauseOrJOIN(
2417 $table, $use_index, $ignore_index, $join_conds ) . ')';
2420 $innerTable = reset( $table );
2421 $innerAlias = key( $table );
2422 $joinedTable = $this->tableNameWithAlias(
2424 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2428 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2431 // Is there a JOIN clause for this table?
2432 if ( isset( $join_conds[$alias] ) ) {
2433 list( $joinType, $conds ) = $join_conds[$alias];
2434 $tableClause = $joinType;
2435 $tableClause .= ' ' . $joinedTable;
2436 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2437 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2439 $tableClause .= ' ' . $use;
2442 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2443 $ignore = $this->ignoreIndexClause(
2444 implode( ',', (array)$ignore_index[$alias] ) );
2445 if ( $ignore != '' ) {
2446 $tableClause .= ' ' . $ignore;
2449 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2451 $tableClause .= ' ON (' . $on . ')';
2454 $retJOIN[] = $tableClause;
2455 } elseif ( isset( $use_index[$alias] ) ) {
2456 // Is there an INDEX clause for this table?
2457 $tableClause = $joinedTable;
2458 $tableClause .= ' ' . $this->useIndexClause(
2459 implode( ',', (array)$use_index[$alias] )
2462 $ret[] = $tableClause;
2463 } elseif ( isset( $ignore_index[$alias] ) ) {
2464 // Is there an INDEX clause for this table?
2465 $tableClause = $joinedTable;
2466 $tableClause .= ' ' . $this->ignoreIndexClause(
2467 implode( ',', (array)$ignore_index[$alias] )
2470 $ret[] = $tableClause;
2472 $tableClause = $joinedTable;
2474 $ret[] = $tableClause;
2478 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2479 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2480 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2482 // Compile our final table clause
2483 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2487 * Allows for index remapping in queries where this is not consistent across DBMS
2489 * @param string $index
2492 protected function indexName( $index ) {
2493 return isset( $this->indexAliases
[$index] )
2494 ?
$this->indexAliases
[$index]
2498 public function addQuotes( $s ) {
2499 if ( $s instanceof Blob
) {
2502 if ( $s === null ) {
2504 } elseif ( is_bool( $s ) ) {
2507 # This will also quote numeric values. This should be harmless,
2508 # and protects against weird problems that occur when they really
2509 # _are_ strings such as article titles and string->number->string
2510 # conversion is not 1:1.
2511 return "'" . $this->strencode( $s ) . "'";
2516 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2517 * MySQL uses `backticks` while basically everything else uses double quotes.
2518 * Since MySQL is the odd one out here the double quotes are our generic
2519 * and we implement backticks in DatabaseMysqlBase.
2524 public function addIdentifierQuotes( $s ) {
2525 return '"' . str_replace( '"', '""', $s ) . '"';
2529 * Returns if the given identifier looks quoted or not according to
2530 * the database convention for quoting identifiers .
2532 * @note Do not use this to determine if untrusted input is safe.
2533 * A malicious user can trick this function.
2534 * @param string $name
2537 public function isQuotedIdentifier( $name ) {
2538 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2543 * @param string $escapeChar
2546 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2547 return str_replace( [ $escapeChar, '%', '_' ],
2548 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2552 public function buildLike() {
2553 $params = func_get_args();
2555 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2556 $params = $params[0];
2561 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2562 // may escape backslashes, creating problems of double escaping. The `
2563 // character has good cross-DBMS compatibility, avoiding special operators
2564 // in MS SQL like ^ and %
2567 foreach ( $params as $value ) {
2568 if ( $value instanceof LikeMatch
) {
2569 $s .= $value->toString();
2571 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2576 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2579 public function anyChar() {
2580 return new LikeMatch( '_' );
2583 public function anyString() {
2584 return new LikeMatch( '%' );
2587 public function nextSequenceValue( $seqName ) {
2592 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2593 * is only needed because a) MySQL must be as efficient as possible due to
2594 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2595 * which index to pick. Anyway, other databases might have different
2596 * indexes on a given table. So don't bother overriding this unless you're
2598 * @param string $index
2601 public function useIndexClause( $index ) {
2606 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2607 * is only needed because a) MySQL must be as efficient as possible due to
2608 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2609 * which index to pick. Anyway, other databases might have different
2610 * indexes on a given table. So don't bother overriding this unless you're
2612 * @param string $index
2615 public function ignoreIndexClause( $index ) {
2619 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2620 if ( count( $rows ) == 0 ) {
2625 if ( !is_array( reset( $rows ) ) ) {
2630 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2631 $affectedRowCount = 0;
2632 foreach ( $rows as $row ) {
2633 // Delete rows which collide with this one
2634 $indexWhereClauses = [];
2635 foreach ( $uniqueIndexes as $index ) {
2636 $indexColumns = (array)$index;
2637 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2638 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2639 throw new DBUnexpectedError(
2641 'New record does not provide all values for unique key (' .
2642 implode( ', ', $indexColumns ) . ')'
2644 } elseif ( in_array( null, $indexRowValues, true ) ) {
2645 throw new DBUnexpectedError(
2647 'New record has a null value for unique key (' .
2648 implode( ', ', $indexColumns ) . ')'
2651 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2654 if ( $indexWhereClauses ) {
2655 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2656 $affectedRowCount +
= $this->affectedRows();
2659 // Now insert the row
2660 $this->insert( $table, $row, $fname );
2661 $affectedRowCount +
= $this->affectedRows();
2663 $this->endAtomic( $fname );
2664 $this->affectedRowCount
= $affectedRowCount;
2665 } catch ( Exception
$e ) {
2666 $this->cancelAtomic( $fname );
2672 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2675 * @param string $table Table name
2676 * @param array|string $rows Row(s) to insert
2677 * @param string $fname Caller function name
2679 * @return ResultWrapper
2681 protected function nativeReplace( $table, $rows, $fname ) {
2682 $table = $this->tableName( $table );
2685 if ( !is_array( reset( $rows ) ) ) {
2689 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2692 foreach ( $rows as $row ) {
2699 $sql .= '(' . $this->makeList( $row ) . ')';
2702 return $this->query( $sql, $fname );
2705 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2708 if ( !count( $rows ) ) {
2709 return true; // nothing to do
2712 if ( !is_array( reset( $rows ) ) ) {
2716 if ( count( $uniqueIndexes ) ) {
2717 $clauses = []; // list WHERE clauses that each identify a single row
2718 foreach ( $rows as $row ) {
2719 foreach ( $uniqueIndexes as $index ) {
2720 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2721 $rowKey = []; // unique key to this row
2722 foreach ( $index as $column ) {
2723 $rowKey[$column] = $row[$column];
2725 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2728 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2733 $affectedRowCount = 0;
2735 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2736 # Update any existing conflicting row(s)
2737 if ( $where !== false ) {
2738 $ok = $this->update( $table, $set, $where, $fname );
2739 $affectedRowCount +
= $this->affectedRows();
2743 # Now insert any non-conflicting row(s)
2744 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2745 $affectedRowCount +
= $this->affectedRows();
2746 $this->endAtomic( $fname );
2747 $this->affectedRowCount
= $affectedRowCount;
2748 } catch ( Exception
$e ) {
2749 $this->cancelAtomic( $fname );
2756 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2760 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2763 $delTable = $this->tableName( $delTable );
2764 $joinTable = $this->tableName( $joinTable );
2765 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2766 if ( $conds != '*' ) {
2767 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2771 $this->query( $sql, $fname );
2774 public function textFieldSize( $table, $field ) {
2775 $table = $this->tableName( $table );
2776 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2777 $res = $this->query( $sql, __METHOD__
);
2778 $row = $this->fetchObject( $res );
2782 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2791 public function delete( $table, $conds, $fname = __METHOD__
) {
2793 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2796 $table = $this->tableName( $table );
2797 $sql = "DELETE FROM $table";
2799 if ( $conds != '*' ) {
2800 if ( is_array( $conds ) ) {
2801 $conds = $this->makeList( $conds, self
::LIST_AND
);
2803 $sql .= ' WHERE ' . $conds;
2806 return $this->query( $sql, $fname );
2809 final public function insertSelect(
2810 $destTable, $srcTable, $varMap, $conds,
2811 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2813 static $hints = [ 'NO_AUTO_COLUMNS' ];
2815 $insertOptions = (array)$insertOptions;
2816 $selectOptions = (array)$selectOptions;
2818 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2819 // For massive migrations with downtime, we don't want to select everything
2820 // into memory and OOM, so do all this native on the server side if possible.
2821 return $this->nativeInsertSelect(
2827 array_diff( $insertOptions, $hints ),
2833 return $this->nonNativeInsertSelect(
2839 array_diff( $insertOptions, $hints ),
2846 * @param array $insertOptions INSERT options
2847 * @param array $selectOptions SELECT options
2848 * @return bool Whether an INSERT SELECT with these options will be replication safe
2851 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2856 * Implementation of insertSelect() based on select() and insert()
2858 * @see IDatabase::insertSelect()
2860 * @param string $destTable
2861 * @param string|array $srcTable
2862 * @param array $varMap
2863 * @param array $conds
2864 * @param string $fname
2865 * @param array $insertOptions
2866 * @param array $selectOptions
2867 * @param array $selectJoinConds
2870 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2871 $fname = __METHOD__
,
2872 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2874 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2875 // on only the master (without needing row-based-replication). It also makes it easy to
2876 // know how big the INSERT is going to be.
2878 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2879 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2881 $selectOptions[] = 'FOR UPDATE';
2882 $res = $this->select(
2883 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2890 $affectedRowCount = 0;
2891 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2894 foreach ( $res as $row ) {
2895 $rows[] = (array)$row;
2897 // Avoid inserts that are too huge
2898 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2899 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2903 $affectedRowCount +
= $this->affectedRows();
2907 if ( $rows && $ok ) {
2908 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2910 $affectedRowCount +
= $this->affectedRows();
2914 $this->endAtomic( $fname );
2915 $this->affectedRowCount
= $affectedRowCount;
2917 $this->cancelAtomic( $fname );
2920 } catch ( Exception
$e ) {
2921 $this->cancelAtomic( $fname );
2927 * Native server-side implementation of insertSelect() for situations where
2928 * we don't want to select everything into memory
2930 * @see IDatabase::insertSelect()
2931 * @param string $destTable
2932 * @param string|array $srcTable
2933 * @param array $varMap
2934 * @param array $conds
2935 * @param string $fname
2936 * @param array $insertOptions
2937 * @param array $selectOptions
2938 * @param array $selectJoinConds
2941 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2942 $fname = __METHOD__
,
2943 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2945 $destTable = $this->tableName( $destTable );
2947 if ( !is_array( $insertOptions ) ) {
2948 $insertOptions = [ $insertOptions ];
2951 $insertOptions = $this->makeInsertOptions( $insertOptions );
2953 $selectSql = $this->selectSQLText(
2955 array_values( $varMap ),
2962 $sql = "INSERT $insertOptions" .
2963 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2966 return $this->query( $sql, $fname );
2970 * Construct a LIMIT query with optional offset. This is used for query
2971 * pages. The SQL should be adjusted so that only the first $limit rows
2972 * are returned. If $offset is provided as well, then the first $offset
2973 * rows should be discarded, and the next $limit rows should be returned.
2974 * If the result of the query is not ordered, then the rows to be returned
2975 * are theoretically arbitrary.
2977 * $sql is expected to be a SELECT, if that makes a difference.
2979 * The version provided by default works in MySQL and SQLite. It will very
2980 * likely need to be overridden for most other DBMSes.
2982 * @param string $sql SQL query we will append the limit too
2983 * @param int $limit The SQL limit
2984 * @param int|bool $offset The SQL offset (default false)
2985 * @throws DBUnexpectedError
2988 public function limitResult( $sql, $limit, $offset = false ) {
2989 if ( !is_numeric( $limit ) ) {
2990 throw new DBUnexpectedError( $this,
2991 "Invalid non-numeric limit passed to limitResult()\n" );
2994 return "$sql LIMIT "
2995 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2999 public function unionSupportsOrderAndLimit() {
3000 return true; // True for almost every DB supported
3003 public function unionQueries( $sqls, $all ) {
3004 $glue = $all ?
') UNION ALL (' : ') UNION (';
3006 return '(' . implode( $glue, $sqls ) . ')';
3009 public function unionConditionPermutations(
3010 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3011 $options = [], $join_conds = []
3013 // First, build the Cartesian product of $permute_conds
3015 foreach ( $permute_conds as $field => $values ) {
3017 // Skip empty $values
3020 $values = array_unique( $values ); // For sanity
3022 foreach ( $conds as $cond ) {
3023 foreach ( $values as $value ) {
3024 $cond[$field] = $value;
3025 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3031 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3033 // If there's just one condition and no subordering, hand off to
3034 // selectSQLText directly.
3035 if ( count( $conds ) === 1 &&
3036 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3038 return $this->selectSQLText(
3039 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3043 // Otherwise, we need to pull out the order and limit to apply after
3044 // the union. Then build the SQL queries for each set of conditions in
3045 // $conds. Then union them together (using UNION ALL, because the
3046 // product *should* already be distinct).
3047 $orderBy = $this->makeOrderBy( $options );
3048 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
3049 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
3050 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3051 if ( !$this->unionSupportsOrderAndLimit() ) {
3052 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3054 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3055 $options['ORDER BY'] = $options['INNER ORDER BY'];
3057 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3058 // We need to increase the limit by the offset rather than
3059 // using the offset directly, otherwise it'll skip incorrectly
3060 // in the subqueries.
3061 $options['LIMIT'] = $limit +
$offset;
3062 unset( $options['OFFSET'] );
3067 foreach ( $conds as $cond ) {
3068 $sqls[] = $this->selectSQLText(
3069 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3072 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3073 if ( $limit !== null ) {
3074 $sql = $this->limitResult( $sql, $limit, $offset );
3080 public function conditional( $cond, $trueVal, $falseVal ) {
3081 if ( is_array( $cond ) ) {
3082 $cond = $this->makeList( $cond, self
::LIST_AND
);
3085 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3088 public function strreplace( $orig, $old, $new ) {
3089 return "REPLACE({$orig}, {$old}, {$new})";
3092 public function getServerUptime() {
3096 public function wasDeadlock() {
3100 public function wasLockTimeout() {
3104 public function wasConnectionLoss() {
3105 return $this->wasConnectionError( $this->lastErrno() );
3108 public function wasReadOnlyError() {
3112 public function wasErrorReissuable() {
3114 $this->wasDeadlock() ||
3115 $this->wasLockTimeout() ||
3116 $this->wasConnectionLoss()
3121 * Do not use this method outside of Database/DBError classes
3123 * @param int|string $errno
3124 * @return bool Whether the given query error was a connection drop
3126 public function wasConnectionError( $errno ) {
3131 * @return bool Whether it is safe to assume the given error only caused statement rollback
3132 * @note This is for backwards compatibility for callers catching DBError exceptions in
3133 * order to ignore problems like duplicate key errors or foriegn key violations
3136 protected function wasKnownStatementRollbackError() {
3137 return false; // don't know; it could have caused a transaction rollback
3140 public function deadlockLoop() {
3141 $args = func_get_args();
3142 $function = array_shift( $args );
3143 $tries = self
::DEADLOCK_TRIES
;
3145 $this->begin( __METHOD__
);
3148 /** @var Exception $e */
3152 $retVal = call_user_func_array( $function, $args );
3154 } catch ( DBQueryError
$e ) {
3155 if ( $this->wasDeadlock() ) {
3156 // Retry after a randomized delay
3157 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3159 // Throw the error back up
3163 } while ( --$tries > 0 );
3165 if ( $tries <= 0 ) {
3166 // Too many deadlocks; give up
3167 $this->rollback( __METHOD__
);
3170 $this->commit( __METHOD__
);
3176 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3177 # Real waits are implemented in the subclass.
3181 public function getReplicaPos() {
3186 public function getMasterPos() {
3191 public function serverIsReadOnly() {
3195 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3196 if ( !$this->trxLevel
) {
3197 throw new DBUnexpectedError( $this, "No transaction is active." );
3199 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3202 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3203 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3204 // Start an implicit transaction similar to how query() does
3205 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3206 $this->trxAutomatic
= true;
3209 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3210 if ( !$this->trxLevel
) {
3211 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3215 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3216 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3217 // Start an implicit transaction similar to how query() does
3218 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3219 $this->trxAutomatic
= true;
3222 if ( $this->trxLevel
) {
3223 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3225 // No transaction is active nor will start implicitly, so make one for this callback
3226 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3228 call_user_func( $callback );
3229 $this->endAtomic( __METHOD__
);
3230 } catch ( Exception
$e ) {
3231 $this->cancelAtomic( __METHOD__
);
3237 final public function setTransactionListener( $name, callable
$callback = null ) {
3239 $this->trxRecurringCallbacks
[$name] = $callback;
3241 unset( $this->trxRecurringCallbacks
[$name] );
3246 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3248 * This method should not be used outside of Database/LoadBalancer
3250 * @param bool $suppress
3253 final public function setTrxEndCallbackSuppression( $suppress ) {
3254 $this->trxEndCallbacksSuppressed
= $suppress;
3258 * Actually run and consume any "on transaction idle/resolution" callbacks.
3260 * This method should not be used outside of Database/LoadBalancer
3262 * @param int $trigger IDatabase::TRIGGER_* constant
3266 public function runOnTransactionIdleCallbacks( $trigger ) {
3267 if ( $this->trxEndCallbacksSuppressed
) {
3271 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3272 /** @var Exception $e */
3273 $e = null; // first exception
3274 do { // callbacks may add callbacks :)
3275 $callbacks = array_merge(
3276 $this->trxIdleCallbacks
,
3277 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3279 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3280 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3281 foreach ( $callbacks as $callback ) {
3283 list( $phpCallback ) = $callback;
3284 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3285 call_user_func_array( $phpCallback, [ $trigger ] );
3287 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3289 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3291 } catch ( Exception
$ex ) {
3292 call_user_func( $this->errorLogger
, $ex );
3294 // Some callbacks may use startAtomic/endAtomic, so make sure
3295 // their transactions are ended so other callbacks don't fail
3296 if ( $this->trxLevel() ) {
3297 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3301 } while ( count( $this->trxIdleCallbacks
) );
3303 if ( $e instanceof Exception
) {
3304 throw $e; // re-throw any first exception
3309 * Actually run and consume any "on transaction pre-commit" callbacks.
3311 * This method should not be used outside of Database/LoadBalancer
3316 public function runOnTransactionPreCommitCallbacks() {
3317 $e = null; // first exception
3318 do { // callbacks may add callbacks :)
3319 $callbacks = $this->trxPreCommitCallbacks
;
3320 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3321 foreach ( $callbacks as $callback ) {
3323 list( $phpCallback ) = $callback;
3324 call_user_func( $phpCallback );
3325 } catch ( Exception
$ex ) {
3326 call_user_func( $this->errorLogger
, $ex );
3330 } while ( count( $this->trxPreCommitCallbacks
) );
3332 if ( $e instanceof Exception
) {
3333 throw $e; // re-throw any first exception
3338 * Actually run any "transaction listener" callbacks.
3340 * This method should not be used outside of Database/LoadBalancer
3342 * @param int $trigger IDatabase::TRIGGER_* constant
3346 public function runTransactionListenerCallbacks( $trigger ) {
3347 if ( $this->trxEndCallbacksSuppressed
) {
3351 /** @var Exception $e */
3352 $e = null; // first exception
3354 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3356 $phpCallback( $trigger, $this );
3357 } catch ( Exception
$ex ) {
3358 call_user_func( $this->errorLogger
, $ex );
3363 if ( $e instanceof Exception
) {
3364 throw $e; // re-throw any first exception
3369 * Create a savepoint
3371 * This is used internally to implement atomic sections. It should not be
3375 * @param string $identifier Identifier for the savepoint
3376 * @param string $fname Calling function name
3378 protected function doSavepoint( $identifier, $fname ) {
3379 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3383 * Release a savepoint
3385 * This is used internally to implement atomic sections. It should not be
3389 * @param string $identifier Identifier for the savepoint
3390 * @param string $fname Calling function name
3392 protected function doReleaseSavepoint( $identifier, $fname ) {
3393 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3397 * Rollback to a savepoint
3399 * This is used internally to implement atomic sections. It should not be
3403 * @param string $identifier Identifier for the savepoint
3404 * @param string $fname Calling function name
3406 protected function doRollbackToSavepoint( $identifier, $fname ) {
3407 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3410 final public function startAtomic(
3411 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3413 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3414 if ( !$this->trxLevel
) {
3415 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3416 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3417 // in all changes being in one transaction to keep requests transactional.
3418 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3419 $this->trxAutomaticAtomic
= true;
3421 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3422 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3423 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3424 $this->queryLogger
->warning(
3425 'There have been an excessively large number of atomic sections in a transaction'
3426 . " started by $this->trxFname, reusing IDs (at $fname)",
3427 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3429 $this->trxAtomicCounter
= 0;
3430 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3432 $this->doSavepoint( $savepointId, $fname );
3435 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3438 final public function endAtomic( $fname = __METHOD__
) {
3439 if ( !$this->trxLevel
) {
3440 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3443 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3444 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3445 if ( $savedFname !== $fname ) {
3446 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3449 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3450 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3451 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3452 $this->doReleaseSavepoint( $savepointId, $fname );
3456 final public function cancelAtomic( $fname = __METHOD__
) {
3457 if ( !$this->trxLevel
) {
3458 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3461 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3462 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3463 if ( $savedFname !== $fname ) {
3464 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3466 if ( !$savepointId ) {
3467 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3470 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3471 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3472 } elseif ( $savepointId !== 'n/a' ) {
3473 $this->doRollbackToSavepoint( $savepointId, $fname );
3474 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3477 $this->affectedRowCount
= 0; // for the sake of consistency
3480 final public function doAtomicSection( $fname, callable
$callback ) {
3481 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3483 $res = call_user_func_array( $callback, [ $this, $fname ] );
3484 } catch ( Exception
$e ) {
3485 $this->cancelAtomic( $fname );
3488 $this->endAtomic( $fname );
3493 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3494 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3495 if ( $this->trxLevel
) {
3496 if ( $this->trxAtomicLevels
) {
3497 $levels = $this->flatAtomicSectionList();
3498 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3499 throw new DBUnexpectedError( $this, $msg );
3500 } elseif ( !$this->trxAutomatic
) {
3501 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3502 throw new DBUnexpectedError( $this, $msg );
3504 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3505 throw new DBUnexpectedError( $this, $msg );
3507 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3508 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3509 throw new DBUnexpectedError( $this, $msg );
3512 // Avoid fatals if close() was called
3513 $this->assertOpen();
3515 $this->doBegin( $fname );
3516 $this->trxStatus
= self
::STATUS_TRX_OK
;
3517 $this->trxAtomicCounter
= 0;
3518 $this->trxTimestamp
= microtime( true );
3519 $this->trxFname
= $fname;
3520 $this->trxDoneWrites
= false;
3521 $this->trxAutomaticAtomic
= false;
3522 $this->trxAtomicLevels
= [];
3523 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3524 $this->trxWriteDuration
= 0.0;
3525 $this->trxWriteQueryCount
= 0;
3526 $this->trxWriteAffectedRows
= 0;
3527 $this->trxWriteAdjDuration
= 0.0;
3528 $this->trxWriteAdjQueryCount
= 0;
3529 $this->trxWriteCallers
= [];
3530 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3531 // Get an estimate of the replication lag before any such queries.
3532 $this->trxReplicaLag
= null; // clear cached value first
3533 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3534 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3535 // caller will think its OK to muck around with the transaction just because startAtomic()
3536 // has not yet completed (e.g. setting trxAtomicLevels).
3537 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3541 * Issues the BEGIN command to the database server.
3543 * @see Database::begin()
3544 * @param string $fname
3546 protected function doBegin( $fname ) {
3547 $this->query( 'BEGIN', $fname );
3548 $this->trxLevel
= 1;
3551 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3552 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3553 // There are still atomic sections open. This cannot be ignored
3554 $levels = $this->flatAtomicSectionList();
3555 throw new DBUnexpectedError(
3557 "$fname: Got COMMIT while atomic sections $levels are still open."
3561 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3562 if ( !$this->trxLevel
) {
3563 return; // nothing to do
3564 } elseif ( !$this->trxAutomatic
) {
3565 throw new DBUnexpectedError(
3567 "$fname: Flushing an explicit transaction, getting out of sync."
3571 if ( !$this->trxLevel
) {
3572 $this->queryLogger
->error(
3573 "$fname: No transaction to commit, something got out of sync." );
3574 return; // nothing to do
3575 } elseif ( $this->trxAutomatic
) {
3576 throw new DBUnexpectedError(
3578 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3583 // Avoid fatals if close() was called
3584 $this->assertOpen();
3586 $this->runOnTransactionPreCommitCallbacks();
3587 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3588 $this->doCommit( $fname );
3589 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3590 if ( $this->trxDoneWrites
) {
3591 $this->lastWriteTime
= microtime( true );
3592 $this->trxProfiler
->transactionWritingOut(
3597 $this->trxWriteAffectedRows
3601 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3602 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3606 * Issues the COMMIT command to the database server.
3608 * @see Database::commit()
3609 * @param string $fname
3611 protected function doCommit( $fname ) {
3612 if ( $this->trxLevel
) {
3613 $this->query( 'COMMIT', $fname );
3614 $this->trxLevel
= 0;
3618 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3619 $trxActive = $this->trxLevel
;
3621 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3622 if ( $this->getFlag( self
::DBO_TRX
) ) {
3623 throw new DBUnexpectedError(
3625 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3631 // Avoid fatals if close() was called
3632 $this->assertOpen();
3634 $this->doRollback( $fname );
3635 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3636 $this->trxAtomicLevels
= [];
3637 if ( $this->trxDoneWrites
) {
3638 $this->trxProfiler
->transactionWritingOut(
3646 // Clear any commit-dependant callbacks. They might even be present
3647 // only due to transaction rounds, with no SQL transaction being active
3648 $this->trxIdleCallbacks
= [];
3649 $this->trxPreCommitCallbacks
= [];
3653 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3654 } catch ( Exception
$e ) {
3655 // already logged; finish and let LoadBalancer move on during mass-rollback
3658 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3659 } catch ( Exception
$e ) {
3660 // already logged; let LoadBalancer move on during mass-rollback
3663 $this->affectedRowCount
= 0; // for the sake of consistency
3668 * Issues the ROLLBACK command to the database server.
3670 * @see Database::rollback()
3671 * @param string $fname
3673 protected function doRollback( $fname ) {
3674 if ( $this->trxLevel
) {
3675 # Disconnects cause rollback anyway, so ignore those errors
3676 $ignoreErrors = true;
3677 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3678 $this->trxLevel
= 0;
3682 public function flushSnapshot( $fname = __METHOD__
) {
3683 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3684 // This only flushes transactions to clear snapshots, not to write data
3685 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3686 throw new DBUnexpectedError(
3688 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3692 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3695 public function explicitTrxActive() {
3696 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3699 public function duplicateTableStructure(
3700 $oldName, $newName, $temporary = false, $fname = __METHOD__
3702 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3705 public function listTables( $prefix = null, $fname = __METHOD__
) {
3706 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3709 public function listViews( $prefix = null, $fname = __METHOD__
) {
3710 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3713 public function timestamp( $ts = 0 ) {
3714 $t = new ConvertibleTimestamp( $ts );
3715 // Let errors bubble up to avoid putting garbage in the DB
3716 return $t->getTimestamp( TS_MW
);
3719 public function timestampOrNull( $ts = null ) {
3720 if ( is_null( $ts ) ) {
3723 return $this->timestamp( $ts );
3727 public function affectedRows() {
3728 return ( $this->affectedRowCount
=== null )
3729 ?
$this->fetchAffectedRowCount() // default to driver value
3730 : $this->affectedRowCount
;
3734 * @return int Number of retrieved rows according to the driver
3736 abstract protected function fetchAffectedRowCount();
3739 * Take the result from a query, and wrap it in a ResultWrapper if
3740 * necessary. Boolean values are passed through as is, to indicate success
3741 * of write queries or failure.
3743 * Once upon a time, Database::query() returned a bare MySQL result
3744 * resource, and it was necessary to call this function to convert it to
3745 * a wrapper. Nowadays, raw database objects are never exposed to external
3746 * callers, so this is unnecessary in external code.
3748 * @param bool|ResultWrapper|resource|object $result
3749 * @return bool|ResultWrapper
3751 protected function resultObject( $result ) {
3754 } elseif ( $result instanceof ResultWrapper
) {
3756 } elseif ( $result === true ) {
3757 // Successful write query
3760 return new ResultWrapper( $this, $result );
3764 public function ping( &$rtt = null ) {
3765 // Avoid hitting the server if it was hit recently
3766 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3767 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3768 $rtt = $this->rttEstimate
;
3769 return true; // don't care about $rtt
3773 // This will reconnect if possible or return false if not
3774 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3775 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3776 $this->restoreFlags( self
::RESTORE_PRIOR
);
3779 $rtt = $this->rttEstimate
;
3786 * Close any existing (dead) database connection and open a new connection
3788 * @param string $fname
3789 * @return bool True if new connection is opened successfully, false if error
3791 protected function replaceLostConnection( $fname ) {
3792 $this->closeConnection();
3793 $this->opened
= false;
3794 $this->conn
= false;
3796 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3797 $this->lastPing
= microtime( true );
3800 $this->connLogger
->warning(
3801 $fname . ': lost connection to {dbserver}; reconnected',
3803 'dbserver' => $this->getServer(),
3804 'trace' => ( new RuntimeException() )->getTraceAsString()
3807 } catch ( DBConnectionError
$e ) {
3810 $this->connLogger
->error(
3811 $fname . ': lost connection to {dbserver} permanently',
3812 [ 'dbserver' => $this->getServer() ]
3816 $this->handleSessionLoss();
3821 public function getSessionLagStatus() {
3822 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3826 * Get the replica DB lag when the current transaction started
3828 * This is useful when transactions might use snapshot isolation
3829 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3830 * is this lag plus transaction duration. If they don't, it is still
3831 * safe to be pessimistic. This returns null if there is no transaction.
3833 * This returns null if the lag status for this transaction was not yet recorded.
3835 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3838 final protected function getRecordedTransactionLagStatus() {
3839 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
3840 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3845 * Get a replica DB lag estimate for this server
3847 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3850 protected function getApproximateLagStatus() {
3852 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3853 'since' => microtime( true )
3858 * Merge the result of getSessionLagStatus() for several DBs
3859 * using the most pessimistic values to estimate the lag of
3860 * any data derived from them in combination
3862 * This is information is useful for caching modules
3864 * @see WANObjectCache::set()
3865 * @see WANObjectCache::getWithSetCallback()
3867 * @param IDatabase $db1
3868 * @param IDatabase $db2 [optional]
3869 * @return array Map of values:
3870 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3871 * - since: oldest UNIX timestamp of any of the DB lag estimates
3872 * - pending: whether any of the DBs have uncommitted changes
3876 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3877 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3878 foreach ( func_get_args() as $db ) {
3879 /** @var IDatabase $db */
3880 $status = $db->getSessionLagStatus();
3881 if ( $status['lag'] === false ) {
3882 $res['lag'] = false;
3883 } elseif ( $res['lag'] !== false ) {
3884 $res['lag'] = max( $res['lag'], $status['lag'] );
3886 $res['since'] = min( $res['since'], $status['since'] );
3887 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3893 public function getLag() {
3897 public function maxListLen() {
3901 public function encodeBlob( $b ) {
3905 public function decodeBlob( $b ) {
3906 if ( $b instanceof Blob
) {
3912 public function setSessionOptions( array $options ) {
3915 public function sourceFile(
3917 callable
$lineCallback = null,
3918 callable
$resultCallback = null,
3920 callable
$inputCallback = null
3922 Wikimedia\
suppressWarnings();
3923 $fp = fopen( $filename, 'r' );
3924 Wikimedia\restoreWarnings
();
3926 if ( false === $fp ) {
3927 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3931 $fname = __METHOD__
. "( $filename )";
3935 $error = $this->sourceStream(
3936 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3937 } catch ( Exception
$e ) {
3947 public function setSchemaVars( $vars ) {
3948 $this->schemaVars
= $vars;
3951 public function sourceStream(
3953 callable
$lineCallback = null,
3954 callable
$resultCallback = null,
3955 $fname = __METHOD__
,
3956 callable
$inputCallback = null
3958 $delimiterReset = new ScopedCallback(
3959 function ( $delimiter ) {
3960 $this->delimiter
= $delimiter;
3962 [ $this->delimiter
]
3966 while ( !feof( $fp ) ) {
3967 if ( $lineCallback ) {
3968 call_user_func( $lineCallback );
3971 $line = trim( fgets( $fp ) );
3973 if ( $line == '' ) {
3977 if ( '-' == $line[0] && '-' == $line[1] ) {
3985 $done = $this->streamStatementEnd( $cmd, $line );
3989 if ( $done ||
feof( $fp ) ) {
3990 $cmd = $this->replaceVars( $cmd );
3992 if ( $inputCallback ) {
3993 $callbackResult = call_user_func( $inputCallback, $cmd );
3995 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3996 $cmd = $callbackResult;
4001 $res = $this->query( $cmd, $fname );
4003 if ( $resultCallback ) {
4004 call_user_func( $resultCallback, $res, $this );
4007 if ( false === $res ) {
4008 $err = $this->lastError();
4010 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4017 ScopedCallback
::consume( $delimiterReset );
4022 * Called by sourceStream() to check if we've reached a statement end
4024 * @param string &$sql SQL assembled so far
4025 * @param string &$newLine New line about to be added to $sql
4026 * @return bool Whether $newLine contains end of the statement
4028 public function streamStatementEnd( &$sql, &$newLine ) {
4029 if ( $this->delimiter
) {
4031 $newLine = preg_replace(
4032 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4033 if ( $newLine != $prev ) {
4042 * Database independent variable replacement. Replaces a set of variables
4043 * in an SQL statement with their contents as given by $this->getSchemaVars().
4045 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4047 * - '{$var}' should be used for text and is passed through the database's
4049 * - `{$var}` should be used for identifiers (e.g. table and database names).
4050 * It is passed through the database's addIdentifierQuotes method which
4051 * can be overridden if the database uses something other than backticks.
4052 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4053 * database's tableName method.
4054 * - / *i* / passes the name that follows through the database's indexName method.
4055 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4056 * its use should be avoided. In 1.24 and older, string encoding was applied.
4058 * @param string $ins SQL statement to replace variables in
4059 * @return string The new SQL statement with variables replaced
4061 protected function replaceVars( $ins ) {
4062 $vars = $this->getSchemaVars();
4063 return preg_replace_callback(
4065 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4066 \'\{\$ (\w+) }\' | # 3. addQuotes
4067 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4068 /\*\$ (\w+) \*/ # 5. leave unencoded
4070 function ( $m ) use ( $vars ) {
4071 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4072 // check for both nonexistent keys *and* the empty string.
4073 if ( isset( $m[1] ) && $m[1] !== '' ) {
4074 if ( $m[1] === 'i' ) {
4075 return $this->indexName( $m[2] );
4077 return $this->tableName( $m[2] );
4079 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4080 return $this->addQuotes( $vars[$m[3]] );
4081 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4082 return $this->addIdentifierQuotes( $vars[$m[4]] );
4083 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4084 return $vars[$m[5]];
4094 * Get schema variables. If none have been set via setSchemaVars(), then
4095 * use some defaults from the current object.
4099 protected function getSchemaVars() {
4100 if ( $this->schemaVars
) {
4101 return $this->schemaVars
;
4103 return $this->getDefaultSchemaVars();
4108 * Get schema variables to use if none have been set via setSchemaVars().
4110 * Override this in derived classes to provide variables for tables.sql
4111 * and SQL patch files.
4115 protected function getDefaultSchemaVars() {
4119 public function lockIsFree( $lockName, $method ) {
4120 // RDBMs methods for checking named locks may or may not count this thread itself.
4121 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4122 // the behavior choosen by the interface for this method.
4123 return !isset( $this->namedLocksHeld
[$lockName] );
4126 public function lock( $lockName, $method, $timeout = 5 ) {
4127 $this->namedLocksHeld
[$lockName] = 1;
4132 public function unlock( $lockName, $method ) {
4133 unset( $this->namedLocksHeld
[$lockName] );
4138 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4139 if ( $this->writesOrCallbacksPending() ) {
4140 // This only flushes transactions to clear snapshots, not to write data
4141 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4142 throw new DBUnexpectedError(
4144 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4148 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4152 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4153 if ( $this->trxLevel() ) {
4154 // There is a good chance an exception was thrown, causing any early return
4155 // from the caller. Let any error handler get a chance to issue rollback().
4156 // If there isn't one, let the error bubble up and trigger server-side rollback.
4157 $this->onTransactionResolution(
4158 function () use ( $lockKey, $fname ) {
4159 $this->unlock( $lockKey, $fname );
4164 $this->unlock( $lockKey, $fname );
4168 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4173 public function namedLocksEnqueue() {
4177 public function tableLocksHaveTransactionScope() {
4181 final public function lockTables( array $read, array $write, $method ) {
4182 if ( $this->writesOrCallbacksPending() ) {
4183 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4186 if ( $this->tableLocksHaveTransactionScope() ) {
4187 $this->startAtomic( $method );
4190 return $this->doLockTables( $read, $write, $method );
4194 * Helper function for lockTables() that handles the actual table locking
4196 * @param array $read Array of tables to lock for read access
4197 * @param array $write Array of tables to lock for write access
4198 * @param string $method Name of caller
4201 protected function doLockTables( array $read, array $write, $method ) {
4205 final public function unlockTables( $method ) {
4206 if ( $this->tableLocksHaveTransactionScope() ) {
4207 $this->endAtomic( $method );
4209 return true; // locks released on COMMIT/ROLLBACK
4212 return $this->doUnlockTables( $method );
4216 * Helper function for unlockTables() that handles the actual table unlocking
4218 * @param string $method Name of caller
4221 protected function doUnlockTables( $method ) {
4227 * @param string $tableName
4228 * @param string $fName
4229 * @return bool|ResultWrapper
4232 public function dropTable( $tableName, $fName = __METHOD__
) {
4233 if ( !$this->tableExists( $tableName, $fName ) ) {
4236 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4238 return $this->query( $sql, $fName );
4241 public function getInfinity() {
4245 public function encodeExpiry( $expiry ) {
4246 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4247 ?
$this->getInfinity()
4248 : $this->timestamp( $expiry );
4251 public function decodeExpiry( $expiry, $format = TS_MW
) {
4252 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4256 return ConvertibleTimestamp
::convert( $format, $expiry );
4259 public function setBigSelects( $value = true ) {
4263 public function isReadOnly() {
4264 return ( $this->getReadOnlyReason() !== false );
4268 * @return string|bool Reason this DB is read-only or false if it is not
4270 protected function getReadOnlyReason() {
4271 $reason = $this->getLBInfo( 'readOnlyReason' );
4273 return is_string( $reason ) ?
$reason : false;
4276 public function setTableAliases( array $aliases ) {
4277 $this->tableAliases
= $aliases;
4280 public function setIndexAliases( array $aliases ) {
4281 $this->indexAliases
= $aliases;
4285 * Get the underlying binding connection handle
4287 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4288 * This catches broken callers than catch and ignore disconnection exceptions.
4289 * Unlike checking isOpen(), this is safe to call inside of open().
4292 * @throws DBUnexpectedError
4295 protected function getBindingHandle() {
4296 if ( !$this->conn
) {
4297 throw new DBUnexpectedError(
4299 'DB connection was already closed or the connection dropped.'
4310 public function __toString() {
4311 return (string)$this->conn
;
4315 * Make sure that copies do not share the same client binding handle
4316 * @throws DBConnectionError
4318 public function __clone() {
4319 $this->connLogger
->warning(
4320 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4321 ( new RuntimeException() )->getTraceAsString()
4324 if ( $this->isOpen() ) {
4325 // Open a new connection resource without messing with the old one
4326 $this->opened
= false;
4327 $this->conn
= false;
4328 $this->trxEndCallbacks
= []; // don't copy
4329 $this->handleSessionLoss(); // no trx or locks anymore
4330 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4331 $this->lastPing
= microtime( true );
4336 * Called by serialize. Throw an exception when DB connection is serialized.
4337 * This causes problems on some database engines because the connection is
4338 * not restored on unserialize.
4340 public function __sleep() {
4341 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4342 'the connection is not restored on wakeup.' );
4346 * Run a few simple sanity checks and close dangling connections
4348 public function __destruct() {
4349 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4350 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4353 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4354 if ( $danglingWriters ) {
4355 $fnames = implode( ', ', $danglingWriters );
4356 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4359 if ( $this->conn
) {
4360 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4361 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4362 Wikimedia\
suppressWarnings();
4363 $this->closeConnection();
4364 Wikimedia\restoreWarnings
();
4365 $this->conn
= false;
4366 $this->opened
= false;
4371 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4372 class_alias( Database
::class, 'Database' ); // b/c global alias