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
;
42 * Relational database abstraction object
47 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
48 /** Number of times to re-try an operation in case of deadlock */
49 const DEADLOCK_TRIES
= 4;
50 /** Minimum time to wait before retry, in microseconds */
51 const DEADLOCK_DELAY_MIN
= 500000;
52 /** Maximum time to wait before retry */
53 const DEADLOCK_DELAY_MAX
= 1500000;
55 /** How long before it is worth doing a dummy query to test the connection */
57 const PING_QUERY
= 'SELECT 1 AS ping';
59 const TINY_WRITE_SEC
= 0.010;
60 const SLOW_WRITE_SEC
= 0.500;
61 const SMALL_WRITE_ROWS
= 100;
63 /** @var string Whether lock granularity is on the level of the entire database */
64 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
66 /** @var int New Database instance will not be connected yet when returned */
67 const NEW_UNCONNECTED
= 0;
68 /** @var int New Database instance will already be connected when returned */
69 const NEW_CONNECTED
= 1;
71 /** @var string SQL query */
72 protected $lastQuery = '';
73 /** @var float|bool UNIX timestamp of last write query */
74 protected $lastWriteTime = false;
75 /** @var string|bool */
76 protected $phpError = false;
77 /** @var string Server that this instance is currently connected to */
79 /** @var string User that this instance is currently connected under the name of */
81 /** @var string Password used to establish the current connection */
83 /** @var string Database that this instance is currently connected to */
85 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
86 protected $tableAliases = [];
87 /** @var string[] Map of (index alias => index) */
88 protected $indexAliases = [];
89 /** @var bool Whether this PHP instance is for a CLI script */
91 /** @var string Agent name for query profiling */
93 /** @var array Parameters used by initConnection() to establish a connection */
94 protected $connectionParams = [];
95 /** @var BagOStuff APC cache */
97 /** @var LoggerInterface */
98 protected $connLogger;
99 /** @var LoggerInterface */
100 protected $queryLogger;
101 /** @var callback Error logging callback */
102 protected $errorLogger;
104 /** @var resource|null Database connection */
105 protected $conn = null;
107 protected $opened = false;
109 /** @var array[] List of (callable, method name) */
110 protected $trxIdleCallbacks = [];
111 /** @var array[] List of (callable, method name) */
112 protected $trxPreCommitCallbacks = [];
113 /** @var array[] List of (callable, method name) */
114 protected $trxEndCallbacks = [];
115 /** @var callable[] Map of (name => callable) */
116 protected $trxRecurringCallbacks = [];
117 /** @var bool Whether to suppress triggering of transaction end callbacks */
118 protected $trxEndCallbacksSuppressed = false;
121 protected $tablePrefix = '';
123 protected $schema = '';
127 protected $lbInfo = [];
128 /** @var array|bool */
129 protected $schemaVars = false;
131 protected $sessionVars = [];
132 /** @var array|null */
133 protected $preparedArgs;
134 /** @var string|bool|null Stashed value of html_errors INI setting */
135 protected $htmlErrors;
137 protected $delimiter = ';';
138 /** @var DatabaseDomain */
139 protected $currentDomain;
140 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
141 protected $affectedRowCount;
144 * Either 1 if a transaction is active or 0 otherwise.
145 * The other Trx fields may not be meaningfull if this is 0.
149 protected $trxLevel = 0;
151 * Either a short hexidecimal string if a transaction is active or ""
154 * @see Database::trxLevel
156 protected $trxShortId = '';
158 * The UNIX time that the transaction started. Callers can assume that if
159 * snapshot isolation is used, then the data is *at least* up to date to that
160 * point (possibly more up-to-date since the first SELECT defines the snapshot).
163 * @see Database::trxLevel
165 private $trxTimestamp = null;
166 /** @var float Lag estimate at the time of BEGIN */
167 private $trxReplicaLag = null;
169 * Remembers the function name given for starting the most recent transaction via begin().
170 * Used to provide additional context for error reporting.
173 * @see Database::trxLevel
175 private $trxFname = null;
177 * Record if possible write queries were done in the last transaction started
180 * @see Database::trxLevel
182 private $trxDoneWrites = false;
184 * Record if the current transaction was started implicitly due to DBO_TRX being set.
187 * @see Database::trxLevel
189 private $trxAutomatic = false;
191 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
195 private $trxAtomicCounter = 0;
197 * Array of levels of atomicity within transactions
201 private $trxAtomicLevels = [];
203 * Record if the current transaction was started implicitly by Database::startAtomic
207 private $trxAutomaticAtomic = false;
209 * Track the write query callers of the current transaction
213 private $trxWriteCallers = [];
215 * @var float Seconds spent in write queries for the current transaction
217 private $trxWriteDuration = 0.0;
219 * @var int Number of write queries for the current transaction
221 private $trxWriteQueryCount = 0;
223 * @var int Number of rows affected by write queries for the current transaction
225 private $trxWriteAffectedRows = 0;
227 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
229 private $trxWriteAdjDuration = 0.0;
231 * @var int Number of write queries counted in trxWriteAdjDuration
233 private $trxWriteAdjQueryCount = 0;
235 * @var float RTT time estimate
237 private $rttEstimate = 0.0;
239 /** @var array Map of (name => 1) for locks obtained via lock() */
240 private $namedLocksHeld = [];
241 /** @var array Map of (table name => 1) for TEMPORARY tables */
242 protected $sessionTempTables = [];
244 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
245 private $lazyMasterHandle;
247 /** @var float UNIX timestamp */
248 protected $lastPing = 0.0;
250 /** @var int[] Prior flags member variable values */
251 private $priorFlags = [];
253 /** @var object|string Class name or object With profileIn/profileOut methods */
255 /** @var TransactionProfiler */
256 protected $trxProfiler;
259 protected $nonNativeInsertSelectBatchSize = 10000;
262 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
263 * @param array $params Parameters passed from Database::factory()
265 protected function __construct( array $params ) {
266 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
267 $this->connectionParams
[$name] = $params[$name];
270 $this->schema
= $params['schema'];
271 $this->tablePrefix
= $params['tablePrefix'];
273 $this->cliMode
= $params['cliMode'];
274 // Agent name is added to SQL queries in a comment, so make sure it can't break out
275 $this->agent
= str_replace( '/', '-', $params['agent'] );
277 $this->flags
= $params['flags'];
278 if ( $this->flags
& self
::DBO_DEFAULT
) {
279 if ( $this->cliMode
) {
280 $this->flags
&= ~self
::DBO_TRX
;
282 $this->flags |
= self
::DBO_TRX
;
286 $this->sessionVars
= $params['variables'];
288 $this->srvCache
= isset( $params['srvCache'] )
289 ?
$params['srvCache']
290 : new HashBagOStuff();
292 $this->profiler
= $params['profiler'];
293 $this->trxProfiler
= $params['trxProfiler'];
294 $this->connLogger
= $params['connLogger'];
295 $this->queryLogger
= $params['queryLogger'];
296 $this->errorLogger
= $params['errorLogger'];
298 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
299 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
302 // Set initial dummy domain until open() sets the final DB/prefix
303 $this->currentDomain
= DatabaseDomain
::newUnspecified();
307 * Initialize the connection to the database over the wire (or to local files)
309 * @throws LogicException
310 * @throws InvalidArgumentException
311 * @throws DBConnectionError
314 final public function initConnection() {
315 if ( $this->isOpen() ) {
316 throw new LogicException( __METHOD__
. ': already connected.' );
318 // Establish the connection
319 $this->doInitConnection();
320 // Set the domain object after open() sets the relevant fields
321 if ( $this->dbName
!= '' ) {
322 // Domains with server scope but a table prefix are not used by IDatabase classes
323 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
328 * Actually connect to the database over the wire (or to local files)
330 * @throws InvalidArgumentException
331 * @throws DBConnectionError
334 protected function doInitConnection() {
335 if ( strlen( $this->connectionParams
['user'] ) ) {
337 $this->connectionParams
['host'],
338 $this->connectionParams
['user'],
339 $this->connectionParams
['password'],
340 $this->connectionParams
['dbname']
343 throw new InvalidArgumentException( "No database user provided." );
348 * Construct a Database subclass instance given a database type and parameters
350 * This also connects to the database immediately upon object construction
352 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
353 * @param array $p Parameter map with keys:
354 * - host : The hostname of the DB server
355 * - user : The name of the database user the client operates under
356 * - password : The password for the database user
357 * - dbname : The name of the database to use where queries do not specify one.
358 * The database must exist or an error might be thrown. Setting this to the empty string
359 * will avoid any such errors and make the handle have no implicit database scope. This is
360 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
361 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
362 * in which user names and such are defined, e.g. users are database-specific in Postgres.
363 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
364 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
365 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
366 * recognized in queries. This can be used in place of schemas for handle site farms.
367 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
368 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
369 * flag in place UNLESS this this database simply acts as a key/value store.
370 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
371 * 'mysqli' driver; the old one 'mysql' has been removed.
372 * - variables: Optional map of session variables to set after connecting. This can be
373 * used to adjust lock timeouts or encoding modes and the like.
374 * - connLogger: Optional PSR-3 logger interface instance.
375 * - queryLogger: Optional PSR-3 logger interface instance.
376 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
377 * These will be called in query(), using a simplified version of the SQL that also
378 * includes the agent as a SQL comment.
379 * - trxProfiler: Optional TransactionProfiler instance.
380 * - errorLogger: Optional callback that takes an Exception and logs it.
381 * - cliMode: Whether to consider the execution context that of a CLI script.
382 * - agent: Optional name used to identify the end-user in query profiling/logging.
383 * - srvCache: Optional BagOStuff instance to an APC-style cache.
384 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
385 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
386 * @return Database|null If the database driver or extension cannot be found
387 * @throws InvalidArgumentException If the database driver or extension cannot be found
390 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
391 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
393 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
394 // Resolve some defaults for b/c
395 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
396 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
397 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
398 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
399 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
400 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
401 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
402 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
403 $p['cliMode'] = isset( $p['cliMode'] )
405 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
406 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
407 if ( !isset( $p['connLogger'] ) ) {
408 $p['connLogger'] = new NullLogger();
410 if ( !isset( $p['queryLogger'] ) ) {
411 $p['queryLogger'] = new NullLogger();
413 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
414 if ( !isset( $p['trxProfiler'] ) ) {
415 $p['trxProfiler'] = new TransactionProfiler();
417 if ( !isset( $p['errorLogger'] ) ) {
418 $p['errorLogger'] = function ( Exception
$e ) {
419 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
423 /** @var Database $conn */
424 $conn = new $class( $p );
425 if ( $connect == self
::NEW_CONNECTED
) {
426 $conn->initConnection();
436 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
437 * @param string|null $driver Optional name of a specific DB client driver
438 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
439 * @throws InvalidArgumentException
442 final public static function attributesFromType( $dbType, $driver = null ) {
443 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
445 $class = self
::getClass( $dbType, $driver );
447 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
451 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
452 * @param string|null $driver Optional name of a specific DB client driver
453 * @return string Database subclass name to use
454 * @throws InvalidArgumentException
456 private static function getClass( $dbType, $driver = null ) {
457 // For database types with built-in support, the below maps type to IDatabase
458 // implementations. For types with multipe driver implementations (PHP extensions),
459 // an array can be used, keyed by extension name. In case of an array, the
460 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
461 // we auto-detect the first available driver. For types without built-in support,
462 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
463 static $builtinTypes = [
464 'mssql' => DatabaseMssql
::class,
465 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
466 'sqlite' => DatabaseSqlite
::class,
467 'postgres' => DatabasePostgres
::class,
470 $dbType = strtolower( $dbType );
473 if ( isset( $builtinTypes[$dbType] ) ) {
474 $possibleDrivers = $builtinTypes[$dbType];
475 if ( is_string( $possibleDrivers ) ) {
476 $class = $possibleDrivers;
478 if ( (string)$driver !== '' ) {
479 if ( !isset( $possibleDrivers[$driver] ) ) {
480 throw new InvalidArgumentException( __METHOD__
.
481 " type '$dbType' does not support driver '{$driver}'" );
483 $class = $possibleDrivers[$driver];
486 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
487 if ( extension_loaded( $posDriver ) ) {
488 $class = $possibleClass;
495 $class = 'Database' . ucfirst( $dbType );
498 if ( $class === false ) {
499 throw new InvalidArgumentException( __METHOD__
.
500 " no viable database extension found for type '$dbType'" );
507 * @return array Map of (Database::ATTRIBUTE_* constant => value
510 protected static function getAttributes() {
515 * Set the PSR-3 logger interface to use for query logging. (The logger
516 * interfaces for connection logging and error logging can be set with the
519 * @param LoggerInterface $logger
521 public function setLogger( LoggerInterface
$logger ) {
522 $this->queryLogger
= $logger;
525 public function getServerInfo() {
526 return $this->getServerVersion();
529 public function bufferResults( $buffer = null ) {
530 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
531 if ( $buffer !== null ) {
533 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
534 : $this->setFlag( self
::DBO_NOBUFFER
);
541 * Turns on (false) or off (true) the automatic generation and sending
542 * of a "we're sorry, but there has been a database error" page on
543 * database errors. Default is on (false). When turned off, the
544 * code should use lastErrno() and lastError() to handle the
545 * situation as appropriate.
547 * Do not use this function outside of the Database classes.
549 * @param null|bool $ignoreErrors
550 * @return bool The previous value of the flag.
552 protected function ignoreErrors( $ignoreErrors = null ) {
553 $res = $this->getFlag( self
::DBO_IGNORE
);
554 if ( $ignoreErrors !== null ) {
555 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
556 if ( $ignoreErrors ) {
557 $this->flags |
= self
::DBO_IGNORE
;
559 $this->flags
&= ~self
::DBO_IGNORE
;
566 public function trxLevel() {
567 return $this->trxLevel
;
570 public function trxTimestamp() {
571 return $this->trxLevel ?
$this->trxTimestamp
: null;
574 public function tablePrefix( $prefix = null ) {
575 $old = $this->tablePrefix
;
576 if ( $prefix !== null ) {
577 $this->tablePrefix
= $prefix;
578 $this->currentDomain
= ( $this->dbName
!= '' )
579 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
580 : DatabaseDomain
::newUnspecified();
586 public function dbSchema( $schema = null ) {
587 $old = $this->schema
;
588 if ( $schema !== null ) {
589 $this->schema
= $schema;
595 public function getLBInfo( $name = null ) {
596 if ( is_null( $name ) ) {
597 return $this->lbInfo
;
599 if ( array_key_exists( $name, $this->lbInfo
) ) {
600 return $this->lbInfo
[$name];
607 public function setLBInfo( $name, $value = null ) {
608 if ( is_null( $value ) ) {
609 $this->lbInfo
= $name;
611 $this->lbInfo
[$name] = $value;
615 public function setLazyMasterHandle( IDatabase
$conn ) {
616 $this->lazyMasterHandle
= $conn;
620 * @return IDatabase|null
621 * @see setLazyMasterHandle()
624 protected function getLazyMasterHandle() {
625 return $this->lazyMasterHandle
;
628 public function implicitGroupby() {
632 public function implicitOrderby() {
636 public function lastQuery() {
637 return $this->lastQuery
;
640 public function doneWrites() {
641 return (bool)$this->lastWriteTime
;
644 public function lastDoneWrites() {
645 return $this->lastWriteTime ?
: false;
648 public function writesPending() {
649 return $this->trxLevel
&& $this->trxDoneWrites
;
652 public function writesOrCallbacksPending() {
653 return $this->trxLevel
&& (
654 $this->trxDoneWrites ||
655 $this->trxIdleCallbacks ||
656 $this->trxPreCommitCallbacks ||
657 $this->trxEndCallbacks
661 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
662 if ( !$this->trxLevel
) {
664 } elseif ( !$this->trxDoneWrites
) {
669 case self
::ESTIMATE_DB_APPLY
:
671 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
672 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
673 // For omitted queries, make them count as something at least
674 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
675 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
678 default: // everything
679 return $this->trxWriteDuration
;
683 public function pendingWriteCallers() {
684 return $this->trxLevel ?
$this->trxWriteCallers
: [];
687 public function pendingWriteRowsAffected() {
688 return $this->trxWriteAffectedRows
;
692 * Get the list of method names that have pending write queries or callbacks
693 * for this transaction
697 protected function pendingWriteAndCallbackCallers() {
698 if ( !$this->trxLevel
) {
702 $fnames = $this->trxWriteCallers
;
704 $this->trxIdleCallbacks
,
705 $this->trxPreCommitCallbacks
,
706 $this->trxEndCallbacks
708 foreach ( $callbacks as $callback ) {
709 $fnames[] = $callback[1];
716 public function isOpen() {
717 return $this->opened
;
720 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
721 if ( ( $flag & self
::DBO_IGNORE
) ) {
722 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
725 if ( $remember === self
::REMEMBER_PRIOR
) {
726 array_push( $this->priorFlags
, $this->flags
);
728 $this->flags |
= $flag;
731 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
732 if ( ( $flag & self
::DBO_IGNORE
) ) {
733 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
736 if ( $remember === self
::REMEMBER_PRIOR
) {
737 array_push( $this->priorFlags
, $this->flags
);
739 $this->flags
&= ~
$flag;
742 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
743 if ( !$this->priorFlags
) {
747 if ( $state === self
::RESTORE_INITIAL
) {
748 $this->flags
= reset( $this->priorFlags
);
749 $this->priorFlags
= [];
751 $this->flags
= array_pop( $this->priorFlags
);
755 public function getFlag( $flag ) {
756 return !!( $this->flags
& $flag );
760 * @param string $name Class field name
762 * @deprecated Since 1.28
764 public function getProperty( $name ) {
768 public function getDomainID() {
769 return $this->currentDomain
->getId();
772 final public function getWikiID() {
773 return $this->getDomainID();
777 * Get information about an index into an object
778 * @param string $table Table name
779 * @param string $index Index name
780 * @param string $fname Calling function name
781 * @return mixed Database-specific index description class or false if the index does not exist
783 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
786 * Wrapper for addslashes()
788 * @param string $s String to be slashed.
789 * @return string Slashed string.
791 abstract function strencode( $s );
794 * Set a custom error handler for logging errors during database connection
796 protected function installErrorHandler() {
797 $this->phpError
= false;
798 $this->htmlErrors
= ini_set( 'html_errors', '0' );
799 set_error_handler( [ $this, 'connectionErrorLogger' ] );
803 * Restore the previous error handler and return the last PHP error for this DB
805 * @return bool|string
807 protected function restoreErrorHandler() {
808 restore_error_handler();
809 if ( $this->htmlErrors
!== false ) {
810 ini_set( 'html_errors', $this->htmlErrors
);
813 return $this->getLastPHPError();
817 * @return string|bool Last PHP error for this DB (typically connection errors)
819 protected function getLastPHPError() {
820 if ( $this->phpError
) {
821 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
822 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
831 * Error handler for logging errors during database connection
832 * This method should not be used outside of Database classes
835 * @param string $errstr
837 public function connectionErrorLogger( $errno, $errstr ) {
838 $this->phpError
= $errstr;
842 * Create a log context to pass to PSR-3 logger functions.
844 * @param array $extras Additional data to add to context
847 protected function getLogContext( array $extras = [] ) {
850 'db_server' => $this->server
,
851 'db_name' => $this->dbName
,
852 'db_user' => $this->user
,
858 public function close() {
860 // Resolve any dangling transaction first
861 if ( $this->trxLevel() ) {
862 // Meaningful transactions should ideally have been resolved by now
863 if ( $this->writesOrCallbacksPending() ) {
864 $this->queryLogger
->warning(
865 __METHOD__
. ": writes or callbacks still pending.",
866 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
869 // Check if it is possible to properly commit and trigger callbacks
870 if ( $this->trxEndCallbacksSuppressed
) {
871 throw new DBUnexpectedError(
873 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
876 // Commit the changes and run any callbacks as needed
877 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
879 // Close the actual connection in the binding handle
880 $closed = $this->closeConnection();
882 // Sanity check that no callbacks are dangling
884 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
886 throw new RuntimeException( "Transaction callbacks still pending." );
889 $closed = true; // already closed; nothing to do
892 $this->opened
= false;
898 * Make sure isOpen() returns true as a sanity check
900 * @throws DBUnexpectedError
902 protected function assertOpen() {
903 if ( !$this->isOpen() ) {
904 throw new DBUnexpectedError( $this, "DB connection was already closed." );
909 * Closes underlying database connection
911 * @return bool Whether connection was closed successfully
913 abstract protected function closeConnection();
915 public function reportConnectionError( $error = 'Unknown error' ) {
916 $myError = $this->lastError();
922 throw new DBConnectionError( $this, $error );
926 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
928 * This might return things, such as mysqli_result, that do not formally implement
929 * IResultWrapper, but nonetheless implement all of its methods correctly
931 * @param string $sql SQL query.
932 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
934 abstract protected function doQuery( $sql );
937 * Determine whether a query writes to the DB.
938 * Should return true if unsure.
943 protected function isWriteQuery( $sql ) {
945 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
950 * @return string|null
952 protected function getQueryVerb( $sql ) {
953 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
957 * Determine whether a SQL statement is sensitive to isolation level.
958 * A SQL statement is considered transactable if its result could vary
959 * depending on the transaction isolation level. Operational commands
960 * such as 'SET' and 'SHOW' are not considered to be transactable.
965 protected function isTransactableQuery( $sql ) {
967 $this->getQueryVerb( $sql ),
968 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
974 * @param string $sql A SQL query
975 * @return bool Whether $sql is SQL for TEMPORARY table operation
977 protected function registerTempTableOperation( $sql ) {
979 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
983 $this->sessionTempTables
[$matches[1]] = 1;
986 } elseif ( preg_match(
987 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
991 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
992 unset( $this->sessionTempTables
[$matches[1]] );
995 } elseif ( preg_match(
996 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1000 return isset( $this->sessionTempTables
[$matches[1]] );
1001 } elseif ( preg_match(
1002 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1006 return isset( $this->sessionTempTables
[$matches[1]] );
1012 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1013 $priorWritesPending = $this->writesOrCallbacksPending();
1014 $this->lastQuery
= $sql;
1016 $isWrite = $this->isWriteQuery( $sql );
1018 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1020 $isNonTempWrite = false;
1024 if ( $this->getLBInfo( 'replica' ) === true ) {
1027 'Write operations are not allowed on replica database connections.'
1030 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1031 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1032 $reason = $this->getReadOnlyReason();
1033 if ( $reason !== false ) {
1034 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1036 # Set a flag indicating that writes have been done
1037 $this->lastWriteTime
= microtime( true );
1040 # Add trace comment to the begin of the sql string, right after the operator.
1041 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1042 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1044 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1045 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1046 && $this->isTransactableQuery( $sql )
1048 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1049 $this->trxAutomatic
= true;
1052 # Keep track of whether the transaction has write queries pending
1053 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1054 $this->trxDoneWrites
= true;
1055 $this->trxProfiler
->transactionWritingIn(
1056 $this->server
, $this->dbName
, $this->trxShortId
);
1059 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1060 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1063 # Avoid fatals if close() was called
1064 $this->assertOpen();
1066 # Send the query to the server
1067 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1069 # Try reconnecting if the connection was lost
1070 if ( false === $ret && $this->wasConnectionLoss() ) {
1071 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1072 # Stash the last error values before anything might clear them
1073 $lastError = $this->lastError();
1074 $lastErrno = $this->lastErrno();
1075 # Update state tracking to reflect transaction loss due to disconnection
1076 $this->handleSessionLoss();
1077 if ( $this->reconnect() ) {
1078 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1079 $params = [ 'dbserver' => $this->getServer() ];
1080 $this->connLogger
->warning( $msg, $params );
1081 $this->queryLogger
->warning( $msg, $params +
1082 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1084 if ( $recoverable ) {
1085 # Should be safe to silently retry the query
1086 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1088 # Callers may catch the exception and continue to use the DB
1089 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1092 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1093 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1097 if ( false === $ret ) {
1098 # Deadlocks cause the entire transaction to abort, not just the statement.
1099 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1100 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1101 if ( $this->wasDeadlock() ) {
1102 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1103 $tempIgnore = false; // not recoverable
1105 # Update state tracking to reflect transaction loss
1106 $this->handleSessionLoss();
1109 $this->reportQueryError(
1110 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1113 $res = $this->resultObject( $ret );
1119 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1121 * @param string $sql Original SQL query
1122 * @param string $commentedSql SQL query with debugging/trace comment
1123 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1124 * @param string $fname Name of the calling function
1125 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1126 * object for a successful read query, or false on failure
1128 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1129 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1130 # generalizeSQL() will probably cut down the query to reasonable
1131 # logging size most of the time. The substr is really just a sanity check.
1133 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1135 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1138 # Include query transaction state
1139 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1141 $startTime = microtime( true );
1142 if ( $this->profiler
) {
1143 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1145 $this->affectedRowCount
= null;
1146 $ret = $this->doQuery( $commentedSql );
1147 $this->affectedRowCount
= $this->affectedRows();
1148 if ( $this->profiler
) {
1149 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1151 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1153 unset( $queryProfSection ); // profile out (if set)
1155 if ( $ret !== false ) {
1156 $this->lastPing
= $startTime;
1157 if ( $isWrite && $this->trxLevel
) {
1158 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1159 $this->trxWriteCallers
[] = $fname;
1163 if ( $sql === self
::PING_QUERY
) {
1164 $this->rttEstimate
= $queryRuntime;
1167 $this->trxProfiler
->recordQueryCompletion(
1168 $queryProf, $startTime, $isWrite, $this->affectedRows()
1170 $this->queryLogger
->debug( $sql, [
1172 'master' => $isMaster,
1173 'runtime' => $queryRuntime,
1180 * Update the estimated run-time of a query, not counting large row lock times
1182 * LoadBalancer can be set to rollback transactions that will create huge replication
1183 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1184 * queries, like inserting a row can take a long time due to row locking. This method
1185 * uses some simple heuristics to discount those cases.
1187 * @param string $sql A SQL write query
1188 * @param float $runtime Total runtime, including RTT
1189 * @param int $affected Affected row count
1191 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1192 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1193 $indicativeOfReplicaRuntime = true;
1194 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1195 $verb = $this->getQueryVerb( $sql );
1196 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1197 if ( $verb === 'INSERT' ) {
1198 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1199 } elseif ( $verb === 'REPLACE' ) {
1200 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1204 $this->trxWriteDuration +
= $runtime;
1205 $this->trxWriteQueryCount +
= 1;
1206 $this->trxWriteAffectedRows +
= $affected;
1207 if ( $indicativeOfReplicaRuntime ) {
1208 $this->trxWriteAdjDuration +
= $runtime;
1209 $this->trxWriteAdjQueryCount +
= 1;
1214 * Determine whether or not it is safe to retry queries after a database
1215 * connection is lost
1217 * @param string $sql SQL query
1218 * @param bool $priorWritesPending Whether there is a transaction open with
1219 * possible write queries or transaction pre-commit/idle callbacks
1220 * waiting on it to finish.
1221 * @return bool True if it is safe to retry the query, false otherwise
1223 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1224 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1225 # Dropped connections also mean that named locks are automatically released.
1226 # Only allow error suppression in autocommit mode or when the lost transaction
1227 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1228 if ( $this->namedLocksHeld
) {
1229 return false; // possible critical section violation
1230 } elseif ( $sql === 'COMMIT' ) {
1231 return !$priorWritesPending; // nothing written anyway? (T127428)
1232 } elseif ( $sql === 'ROLLBACK' ) {
1233 return true; // transaction lost...which is also what was requested :)
1234 } elseif ( $this->explicitTrxActive() ) {
1235 return false; // don't drop atomocity
1236 } elseif ( $priorWritesPending ) {
1237 return false; // prior writes lost from implicit transaction
1244 * Clean things up after transaction loss due to disconnection
1246 * @return null|Exception
1248 private function handleSessionLoss() {
1249 $this->trxLevel
= 0;
1250 $this->trxAtomicCounter
= 0;
1251 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1252 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1253 $this->sessionTempTables
= [];
1254 $this->namedLocksHeld
= [];
1256 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1259 // Handle callbacks in trxEndCallbacks
1260 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1261 } catch ( Exception
$ex ) {
1262 // Already logged; move on...
1266 // Handle callbacks in trxRecurringCallbacks
1267 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1268 } catch ( Exception
$ex ) {
1269 // Already logged; move on...
1277 * Checks whether the cause of the error is detected to be a timeout.
1279 * It returns false by default, and not all engines support detecting this yet.
1280 * If this returns false, it will be treated as a generic query error.
1282 * @param string $error Error text
1283 * @param int $errno Error number
1286 protected function wasQueryTimeout( $error, $errno ) {
1290 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1291 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1292 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1294 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1295 $this->queryLogger
->error(
1296 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1297 $this->getLogContext( [
1298 'method' => __METHOD__
,
1301 'sql1line' => $sql1line,
1305 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1306 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1307 if ( $wasQueryTimeout ) {
1308 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1310 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1315 public function freeResult( $res ) {
1318 public function selectField(
1319 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1321 if ( $var === '*' ) { // sanity
1322 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1325 if ( !is_array( $options ) ) {
1326 $options = [ $options ];
1329 $options['LIMIT'] = 1;
1331 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1332 if ( $res === false ||
!$this->numRows( $res ) ) {
1336 $row = $this->fetchRow( $res );
1338 if ( $row !== false ) {
1339 return reset( $row );
1345 public function selectFieldValues(
1346 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1348 if ( $var === '*' ) { // sanity
1349 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1350 } elseif ( !is_string( $var ) ) { // sanity
1351 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1354 if ( !is_array( $options ) ) {
1355 $options = [ $options ];
1358 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1359 if ( $res === false ) {
1364 foreach ( $res as $row ) {
1365 $values[] = $row->$var;
1372 * Returns an optional USE INDEX clause to go after the table, and a
1373 * string to go at the end of the query.
1375 * @param array $options Associative array of options to be turned into
1376 * an SQL query, valid keys are listed in the function.
1378 * @see Database::select()
1380 protected function makeSelectOptions( $options ) {
1381 $preLimitTail = $postLimitTail = '';
1386 foreach ( $options as $key => $option ) {
1387 if ( is_numeric( $key ) ) {
1388 $noKeyOptions[$option] = true;
1392 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1394 $preLimitTail .= $this->makeOrderBy( $options );
1396 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1397 $postLimitTail .= ' FOR UPDATE';
1400 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1401 $postLimitTail .= ' LOCK IN SHARE MODE';
1404 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1405 $startOpts .= 'DISTINCT';
1408 # Various MySQL extensions
1409 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1410 $startOpts .= ' /*! STRAIGHT_JOIN */';
1413 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1414 $startOpts .= ' HIGH_PRIORITY';
1417 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1418 $startOpts .= ' SQL_BIG_RESULT';
1421 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1422 $startOpts .= ' SQL_BUFFER_RESULT';
1425 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1426 $startOpts .= ' SQL_SMALL_RESULT';
1429 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1430 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1433 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1434 $startOpts .= ' SQL_CACHE';
1437 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1438 $startOpts .= ' SQL_NO_CACHE';
1441 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1442 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1446 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1447 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1452 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1456 * Returns an optional GROUP BY with an optional HAVING
1458 * @param array $options Associative array of options
1460 * @see Database::select()
1463 protected function makeGroupByWithHaving( $options ) {
1465 if ( isset( $options['GROUP BY'] ) ) {
1466 $gb = is_array( $options['GROUP BY'] )
1467 ?
implode( ',', $options['GROUP BY'] )
1468 : $options['GROUP BY'];
1469 $sql .= ' GROUP BY ' . $gb;
1471 if ( isset( $options['HAVING'] ) ) {
1472 $having = is_array( $options['HAVING'] )
1473 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1474 : $options['HAVING'];
1475 $sql .= ' HAVING ' . $having;
1482 * Returns an optional ORDER BY
1484 * @param array $options Associative array of options
1486 * @see Database::select()
1489 protected function makeOrderBy( $options ) {
1490 if ( isset( $options['ORDER BY'] ) ) {
1491 $ob = is_array( $options['ORDER BY'] )
1492 ?
implode( ',', $options['ORDER BY'] )
1493 : $options['ORDER BY'];
1495 return ' ORDER BY ' . $ob;
1501 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1502 $options = [], $join_conds = [] ) {
1503 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1505 return $this->query( $sql, $fname );
1508 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1509 $options = [], $join_conds = []
1511 if ( is_array( $vars ) ) {
1512 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1515 $options = (array)$options;
1516 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1517 ?
$options['USE INDEX']
1520 isset( $options['IGNORE INDEX'] ) &&
1521 is_array( $options['IGNORE INDEX'] )
1523 ?
$options['IGNORE INDEX']
1526 if ( is_array( $table ) ) {
1528 $this->tableNamesWithIndexClauseOrJOIN(
1529 $table, $useIndexes, $ignoreIndexes, $join_conds );
1530 } elseif ( $table != '' ) {
1532 $this->tableNamesWithIndexClauseOrJOIN(
1533 [ $table ], $useIndexes, $ignoreIndexes, [] );
1538 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1539 $this->makeSelectOptions( $options );
1541 if ( is_array( $conds ) ) {
1542 $conds = $this->makeList( $conds, self
::LIST_AND
);
1545 if ( $conds === null ||
$conds === false ) {
1546 $this->queryLogger
->warning(
1550 . ' with incorrect parameters: $conds must be a string or an array'
1555 if ( $conds === '' ) {
1556 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1557 } elseif ( is_string( $conds ) ) {
1558 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1559 "WHERE $conds $preLimitTail";
1561 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1564 if ( isset( $options['LIMIT'] ) ) {
1565 $sql = $this->limitResult( $sql, $options['LIMIT'],
1566 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1568 $sql = "$sql $postLimitTail";
1570 if ( isset( $options['EXPLAIN'] ) ) {
1571 $sql = 'EXPLAIN ' . $sql;
1577 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1578 $options = [], $join_conds = []
1580 $options = (array)$options;
1581 $options['LIMIT'] = 1;
1582 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1584 if ( $res === false ) {
1588 if ( !$this->numRows( $res ) ) {
1592 $obj = $this->fetchObject( $res );
1597 public function estimateRowCount(
1598 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1600 $conds = $this->normalizeConditions( $conds, $fname );
1601 $column = $this->extractSingleFieldFromList( $var );
1602 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1603 $conds[] = "$column IS NOT NULL";
1606 $res = $this->select(
1607 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1609 $row = $res ?
$this->fetchRow( $res ) : [];
1611 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1614 public function selectRowCount(
1615 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1617 $conds = $this->normalizeConditions( $conds, $fname );
1618 $column = $this->extractSingleFieldFromList( $var );
1619 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1620 $conds[] = "$column IS NOT NULL";
1623 $res = $this->select(
1625 'tmp_count' => $this->buildSelectSubquery(
1634 [ 'rowcount' => 'COUNT(*)' ],
1638 $row = $res ?
$this->fetchRow( $res ) : [];
1640 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1644 * @param array|string $conds
1645 * @param string $fname
1648 final protected function normalizeConditions( $conds, $fname ) {
1649 if ( $conds === null ||
$conds === false ) {
1650 $this->queryLogger
->warning(
1654 . ' with incorrect parameters: $conds must be a string or an array'
1659 if ( !is_array( $conds ) ) {
1660 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1667 * @param array|string $var Field parameter in the style of select()
1668 * @return string|null Column name or null; ignores aliases
1669 * @throws DBUnexpectedError Errors out if multiple columns are given
1671 final protected function extractSingleFieldFromList( $var ) {
1672 if ( is_array( $var ) ) {
1675 } elseif ( count( $var ) == 1 ) {
1676 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1678 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1688 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1689 * It's only slightly flawed. Don't use for anything important.
1691 * @param string $sql A SQL Query
1695 protected static function generalizeSQL( $sql ) {
1696 # This does the same as the regexp below would do, but in such a way
1697 # as to avoid crashing php on some large strings.
1698 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1700 $sql = str_replace( "\\\\", '', $sql );
1701 $sql = str_replace( "\\'", '', $sql );
1702 $sql = str_replace( "\\\"", '', $sql );
1703 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1704 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1706 # All newlines, tabs, etc replaced by single space
1707 $sql = preg_replace( '/\s+/', ' ', $sql );
1710 # except the ones surrounded by characters, e.g. l10n
1711 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1712 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1717 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1718 $info = $this->fieldInfo( $table, $field );
1723 public function indexExists( $table, $index, $fname = __METHOD__
) {
1724 if ( !$this->tableExists( $table ) ) {
1728 $info = $this->indexInfo( $table, $index, $fname );
1729 if ( is_null( $info ) ) {
1732 return $info !== false;
1736 public function tableExists( $table, $fname = __METHOD__
) {
1737 $tableRaw = $this->tableName( $table, 'raw' );
1738 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1739 return true; // already known to exist
1742 $table = $this->tableName( $table );
1743 $ignoreErrors = true;
1744 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1749 public function indexUnique( $table, $index ) {
1750 $indexInfo = $this->indexInfo( $table, $index );
1752 if ( !$indexInfo ) {
1756 return !$indexInfo[0]->Non_unique
;
1760 * Helper for Database::insert().
1762 * @param array $options
1765 protected function makeInsertOptions( $options ) {
1766 return implode( ' ', $options );
1769 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1770 # No rows to insert, easy just return now
1771 if ( !count( $a ) ) {
1775 $table = $this->tableName( $table );
1777 if ( !is_array( $options ) ) {
1778 $options = [ $options ];
1782 if ( isset( $options['fileHandle'] ) ) {
1783 $fh = $options['fileHandle'];
1785 $options = $this->makeInsertOptions( $options );
1787 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1789 $keys = array_keys( $a[0] );
1792 $keys = array_keys( $a );
1795 $sql = 'INSERT ' . $options .
1796 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1800 foreach ( $a as $row ) {
1806 $sql .= '(' . $this->makeList( $row ) . ')';
1809 $sql .= '(' . $this->makeList( $a ) . ')';
1812 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1814 } elseif ( $fh !== null ) {
1818 return (bool)$this->query( $sql, $fname );
1822 * Make UPDATE options array for Database::makeUpdateOptions
1824 * @param array $options
1827 protected function makeUpdateOptionsArray( $options ) {
1828 if ( !is_array( $options ) ) {
1829 $options = [ $options ];
1834 if ( in_array( 'IGNORE', $options ) ) {
1842 * Make UPDATE options for the Database::update function
1844 * @param array $options The options passed to Database::update
1847 protected function makeUpdateOptions( $options ) {
1848 $opts = $this->makeUpdateOptionsArray( $options );
1850 return implode( ' ', $opts );
1853 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1854 $table = $this->tableName( $table );
1855 $opts = $this->makeUpdateOptions( $options );
1856 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1858 if ( $conds !== [] && $conds !== '*' ) {
1859 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1862 return (bool)$this->query( $sql, $fname );
1865 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1866 if ( !is_array( $a ) ) {
1867 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1873 foreach ( $a as $field => $value ) {
1875 if ( $mode == self
::LIST_AND
) {
1877 } elseif ( $mode == self
::LIST_OR
) {
1886 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1887 $list .= "($value)";
1888 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1891 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1893 // Remove null from array to be handled separately if found
1894 $includeNull = false;
1895 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1896 $includeNull = true;
1897 unset( $value[$nullKey] );
1899 if ( count( $value ) == 0 && !$includeNull ) {
1900 throw new InvalidArgumentException(
1901 __METHOD__
. ": empty input for field $field" );
1902 } elseif ( count( $value ) == 0 ) {
1903 // only check if $field is null
1904 $list .= "$field IS NULL";
1906 // IN clause contains at least one valid element
1907 if ( $includeNull ) {
1908 // Group subconditions to ensure correct precedence
1911 if ( count( $value ) == 1 ) {
1912 // Special-case single values, as IN isn't terribly efficient
1913 // Don't necessarily assume the single key is 0; we don't
1914 // enforce linear numeric ordering on other arrays here.
1915 $value = array_values( $value )[0];
1916 $list .= $field . " = " . $this->addQuotes( $value );
1918 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1920 // if null present in array, append IS NULL
1921 if ( $includeNull ) {
1922 $list .= " OR $field IS NULL)";
1925 } elseif ( $value === null ) {
1926 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1927 $list .= "$field IS ";
1928 } elseif ( $mode == self
::LIST_SET
) {
1929 $list .= "$field = ";
1934 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1936 $list .= "$field = ";
1938 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1945 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1948 foreach ( $data as $base => $sub ) {
1949 if ( count( $sub ) ) {
1950 $conds[] = $this->makeList(
1951 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1957 return $this->makeList( $conds, self
::LIST_OR
);
1959 // Nothing to search for...
1964 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1968 public function bitNot( $field ) {
1972 public function bitAnd( $fieldLeft, $fieldRight ) {
1973 return "($fieldLeft & $fieldRight)";
1976 public function bitOr( $fieldLeft, $fieldRight ) {
1977 return "($fieldLeft | $fieldRight)";
1980 public function buildConcat( $stringList ) {
1981 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1984 public function buildGroupConcatField(
1985 $delim, $table, $field, $conds = '', $join_conds = []
1987 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1989 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1992 public function buildSubstring( $input, $startPosition, $length = null ) {
1993 $this->assertBuildSubstringParams( $startPosition, $length );
1994 $functionBody = "$input FROM $startPosition";
1995 if ( $length !== null ) {
1996 $functionBody .= " FOR $length";
1998 return 'SUBSTRING(' . $functionBody . ')';
2002 * Check type and bounds for parameters to self::buildSubstring()
2004 * All supported databases have substring functions that behave the same for
2005 * positive $startPosition and non-negative $length, but behaviors differ when
2006 * given 0 or negative $startPosition or negative $length. The simplest
2007 * solution to that is to just forbid those values.
2009 * @param int $startPosition
2010 * @param int|null $length
2013 protected function assertBuildSubstringParams( $startPosition, $length ) {
2014 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2015 throw new InvalidArgumentException(
2016 '$startPosition must be a positive integer'
2019 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2020 throw new InvalidArgumentException(
2021 '$length must be null or an integer greater than or equal to 0'
2026 public function buildStringCast( $field ) {
2030 public function buildIntegerCast( $field ) {
2031 return 'CAST( ' . $field . ' AS INTEGER )';
2034 public function buildSelectSubquery(
2035 $table, $vars, $conds = '', $fname = __METHOD__
,
2036 $options = [], $join_conds = []
2038 return new Subquery(
2039 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2043 public function databasesAreIndependent() {
2047 public function selectDB( $db ) {
2048 # Stub. Shouldn't cause serious problems if it's not overridden, but
2049 # if your database engine supports a concept similar to MySQL's
2050 # databases you may as well.
2051 $this->dbName
= $db;
2056 public function getDBname() {
2057 return $this->dbName
;
2060 public function getServer() {
2061 return $this->server
;
2064 public function tableName( $name, $format = 'quoted' ) {
2065 if ( $name instanceof Subquery
) {
2066 throw new DBUnexpectedError(
2068 __METHOD__
. ': got Subquery instance when expecting a string.'
2072 # Skip the entire process when we have a string quoted on both ends.
2073 # Note that we check the end so that we will still quote any use of
2074 # use of `database`.table. But won't break things if someone wants
2075 # to query a database table with a dot in the name.
2076 if ( $this->isQuotedIdentifier( $name ) ) {
2080 # Lets test for any bits of text that should never show up in a table
2081 # name. Basically anything like JOIN or ON which are actually part of
2082 # SQL queries, but may end up inside of the table value to combine
2083 # sql. Such as how the API is doing.
2084 # Note that we use a whitespace test rather than a \b test to avoid
2085 # any remote case where a word like on may be inside of a table name
2086 # surrounded by symbols which may be considered word breaks.
2087 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2088 $this->queryLogger
->warning(
2089 __METHOD__
. ": use of subqueries is not supported this way.",
2090 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2096 # Split database and table into proper variables.
2097 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2099 # Quote $table and apply the prefix if not quoted.
2100 # $tableName might be empty if this is called from Database::replaceVars()
2101 $tableName = "{$prefix}{$table}";
2102 if ( $format === 'quoted'
2103 && !$this->isQuotedIdentifier( $tableName )
2104 && $tableName !== ''
2106 $tableName = $this->addIdentifierQuotes( $tableName );
2109 # Quote $schema and $database and merge them with the table name if needed
2110 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2111 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2117 * Get the table components needed for a query given the currently selected database
2119 * @param string $name Table name in the form of db.schema.table, db.table, or table
2120 * @return array (DB name or "" for default, schema name, table prefix, table name)
2122 protected function qualifiedTableComponents( $name ) {
2123 # We reverse the explode so that database.table and table both output the correct table.
2124 $dbDetails = explode( '.', $name, 3 );
2125 if ( count( $dbDetails ) == 3 ) {
2126 list( $database, $schema, $table ) = $dbDetails;
2127 # We don't want any prefix added in this case
2129 } elseif ( count( $dbDetails ) == 2 ) {
2130 list( $database, $table ) = $dbDetails;
2131 # We don't want any prefix added in this case
2133 # In dbs that support it, $database may actually be the schema
2134 # but that doesn't affect any of the functionality here
2137 list( $table ) = $dbDetails;
2138 if ( isset( $this->tableAliases
[$table] ) ) {
2139 $database = $this->tableAliases
[$table]['dbname'];
2140 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2141 ?
$this->tableAliases
[$table]['schema']
2143 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2144 ?
$this->tableAliases
[$table]['prefix']
2145 : $this->tablePrefix
;
2148 $schema = $this->schema
; # Default schema
2149 $prefix = $this->tablePrefix
; # Default prefix
2153 return [ $database, $schema, $prefix, $table ];
2157 * @param string|null $namespace Database or schema
2158 * @param string $relation Name of table, view, sequence, etc...
2159 * @param string $format One of (raw, quoted)
2160 * @return string Relation name with quoted and merged $namespace as needed
2162 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2163 if ( strlen( $namespace ) ) {
2164 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2165 $namespace = $this->addIdentifierQuotes( $namespace );
2167 $relation = $namespace . '.' . $relation;
2173 public function tableNames() {
2174 $inArray = func_get_args();
2177 foreach ( $inArray as $name ) {
2178 $retVal[$name] = $this->tableName( $name );
2184 public function tableNamesN() {
2185 $inArray = func_get_args();
2188 foreach ( $inArray as $name ) {
2189 $retVal[] = $this->tableName( $name );
2196 * Get an aliased table name
2198 * This returns strings like "tableName AS newTableName" for aliased tables
2199 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2201 * @see Database::tableName()
2202 * @param string|Subquery $table Table name or object with a 'sql' field
2203 * @param string|bool $alias Table alias (optional)
2204 * @return string SQL name for aliased table. Will not alias a table to its own name
2206 protected function tableNameWithAlias( $table, $alias = false ) {
2207 if ( is_string( $table ) ) {
2208 $quotedTable = $this->tableName( $table );
2209 } elseif ( $table instanceof Subquery
) {
2210 $quotedTable = (string)$table;
2212 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2215 if ( !strlen( $alias ) ||
$alias === $table ) {
2216 if ( $table instanceof Subquery
) {
2217 throw new InvalidArgumentException( "Subquery table missing alias." );
2220 return $quotedTable;
2222 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2227 * Gets an array of aliased table names
2229 * @param array $tables [ [alias] => table ]
2230 * @return string[] See tableNameWithAlias()
2232 protected function tableNamesWithAlias( $tables ) {
2234 foreach ( $tables as $alias => $table ) {
2235 if ( is_numeric( $alias ) ) {
2238 $retval[] = $this->tableNameWithAlias( $table, $alias );
2245 * Get an aliased field name
2246 * e.g. fieldName AS newFieldName
2248 * @param string $name Field name
2249 * @param string|bool $alias Alias (optional)
2250 * @return string SQL name for aliased field. Will not alias a field to its own name
2252 protected function fieldNameWithAlias( $name, $alias = false ) {
2253 if ( !$alias ||
(string)$alias === (string)$name ) {
2256 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2261 * Gets an array of aliased field names
2263 * @param array $fields [ [alias] => field ]
2264 * @return string[] See fieldNameWithAlias()
2266 protected function fieldNamesWithAlias( $fields ) {
2268 foreach ( $fields as $alias => $field ) {
2269 if ( is_numeric( $alias ) ) {
2272 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2279 * Get the aliased table name clause for a FROM clause
2280 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2282 * @param array $tables ( [alias] => table )
2283 * @param array $use_index Same as for select()
2284 * @param array $ignore_index Same as for select()
2285 * @param array $join_conds Same as for select()
2288 protected function tableNamesWithIndexClauseOrJOIN(
2289 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2293 $use_index = (array)$use_index;
2294 $ignore_index = (array)$ignore_index;
2295 $join_conds = (array)$join_conds;
2297 foreach ( $tables as $alias => $table ) {
2298 if ( !is_string( $alias ) ) {
2299 // No alias? Set it equal to the table name
2303 if ( is_array( $table ) ) {
2304 // A parenthesized group
2305 if ( count( $table ) > 1 ) {
2306 $joinedTable = '(' .
2307 $this->tableNamesWithIndexClauseOrJOIN(
2308 $table, $use_index, $ignore_index, $join_conds ) . ')';
2311 $innerTable = reset( $table );
2312 $innerAlias = key( $table );
2313 $joinedTable = $this->tableNameWithAlias(
2315 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2319 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2322 // Is there a JOIN clause for this table?
2323 if ( isset( $join_conds[$alias] ) ) {
2324 list( $joinType, $conds ) = $join_conds[$alias];
2325 $tableClause = $joinType;
2326 $tableClause .= ' ' . $joinedTable;
2327 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2328 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2330 $tableClause .= ' ' . $use;
2333 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2334 $ignore = $this->ignoreIndexClause(
2335 implode( ',', (array)$ignore_index[$alias] ) );
2336 if ( $ignore != '' ) {
2337 $tableClause .= ' ' . $ignore;
2340 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2342 $tableClause .= ' ON (' . $on . ')';
2345 $retJOIN[] = $tableClause;
2346 } elseif ( isset( $use_index[$alias] ) ) {
2347 // Is there an INDEX clause for this table?
2348 $tableClause = $joinedTable;
2349 $tableClause .= ' ' . $this->useIndexClause(
2350 implode( ',', (array)$use_index[$alias] )
2353 $ret[] = $tableClause;
2354 } elseif ( isset( $ignore_index[$alias] ) ) {
2355 // Is there an INDEX clause for this table?
2356 $tableClause = $joinedTable;
2357 $tableClause .= ' ' . $this->ignoreIndexClause(
2358 implode( ',', (array)$ignore_index[$alias] )
2361 $ret[] = $tableClause;
2363 $tableClause = $joinedTable;
2365 $ret[] = $tableClause;
2369 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2370 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2371 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2373 // Compile our final table clause
2374 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2378 * Allows for index remapping in queries where this is not consistent across DBMS
2380 * @param string $index
2383 protected function indexName( $index ) {
2384 return isset( $this->indexAliases
[$index] )
2385 ?
$this->indexAliases
[$index]
2389 public function addQuotes( $s ) {
2390 if ( $s instanceof Blob
) {
2393 if ( $s === null ) {
2395 } elseif ( is_bool( $s ) ) {
2398 # This will also quote numeric values. This should be harmless,
2399 # and protects against weird problems that occur when they really
2400 # _are_ strings such as article titles and string->number->string
2401 # conversion is not 1:1.
2402 return "'" . $this->strencode( $s ) . "'";
2407 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2408 * MySQL uses `backticks` while basically everything else uses double quotes.
2409 * Since MySQL is the odd one out here the double quotes are our generic
2410 * and we implement backticks in DatabaseMysqlBase.
2415 public function addIdentifierQuotes( $s ) {
2416 return '"' . str_replace( '"', '""', $s ) . '"';
2420 * Returns if the given identifier looks quoted or not according to
2421 * the database convention for quoting identifiers .
2423 * @note Do not use this to determine if untrusted input is safe.
2424 * A malicious user can trick this function.
2425 * @param string $name
2428 public function isQuotedIdentifier( $name ) {
2429 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2434 * @param string $escapeChar
2437 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2438 return str_replace( [ $escapeChar, '%', '_' ],
2439 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2443 public function buildLike() {
2444 $params = func_get_args();
2446 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2447 $params = $params[0];
2452 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2453 // may escape backslashes, creating problems of double escaping. The `
2454 // character has good cross-DBMS compatibility, avoiding special operators
2455 // in MS SQL like ^ and %
2458 foreach ( $params as $value ) {
2459 if ( $value instanceof LikeMatch
) {
2460 $s .= $value->toString();
2462 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2467 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2470 public function anyChar() {
2471 return new LikeMatch( '_' );
2474 public function anyString() {
2475 return new LikeMatch( '%' );
2478 public function nextSequenceValue( $seqName ) {
2483 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2484 * is only needed because a) MySQL must be as efficient as possible due to
2485 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2486 * which index to pick. Anyway, other databases might have different
2487 * indexes on a given table. So don't bother overriding this unless you're
2489 * @param string $index
2492 public function useIndexClause( $index ) {
2497 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2498 * is only needed because a) MySQL must be as efficient as possible due to
2499 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2500 * which index to pick. Anyway, other databases might have different
2501 * indexes on a given table. So don't bother overriding this unless you're
2503 * @param string $index
2506 public function ignoreIndexClause( $index ) {
2510 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2511 if ( count( $rows ) == 0 ) {
2516 if ( !is_array( reset( $rows ) ) ) {
2521 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2522 $affectedRowCount = 0;
2523 foreach ( $rows as $row ) {
2524 // Delete rows which collide with this one
2525 $indexWhereClauses = [];
2526 foreach ( $uniqueIndexes as $index ) {
2527 $indexColumns = (array)$index;
2528 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2529 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2530 throw new DBUnexpectedError(
2532 'New record does not provide all values for unique key (' .
2533 implode( ', ', $indexColumns ) . ')'
2535 } elseif ( in_array( null, $indexRowValues, true ) ) {
2536 throw new DBUnexpectedError(
2538 'New record has a null value for unique key (' .
2539 implode( ', ', $indexColumns ) . ')'
2542 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2545 if ( $indexWhereClauses ) {
2546 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2547 $affectedRowCount +
= $this->affectedRows();
2550 // Now insert the row
2551 $this->insert( $table, $row, $fname );
2552 $affectedRowCount +
= $this->affectedRows();
2554 $this->endAtomic( $fname );
2555 $this->affectedRowCount
= $affectedRowCount;
2556 } catch ( Exception
$e ) {
2557 $this->cancelAtomic( $fname );
2563 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2566 * @param string $table Table name
2567 * @param array|string $rows Row(s) to insert
2568 * @param string $fname Caller function name
2570 * @return ResultWrapper
2572 protected function nativeReplace( $table, $rows, $fname ) {
2573 $table = $this->tableName( $table );
2576 if ( !is_array( reset( $rows ) ) ) {
2580 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2583 foreach ( $rows as $row ) {
2590 $sql .= '(' . $this->makeList( $row ) . ')';
2593 return $this->query( $sql, $fname );
2596 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2599 if ( !count( $rows ) ) {
2600 return true; // nothing to do
2603 if ( !is_array( reset( $rows ) ) ) {
2607 if ( count( $uniqueIndexes ) ) {
2608 $clauses = []; // list WHERE clauses that each identify a single row
2609 foreach ( $rows as $row ) {
2610 foreach ( $uniqueIndexes as $index ) {
2611 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2612 $rowKey = []; // unique key to this row
2613 foreach ( $index as $column ) {
2614 $rowKey[$column] = $row[$column];
2616 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2619 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2624 $affectedRowCount = 0;
2626 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2627 # Update any existing conflicting row(s)
2628 if ( $where !== false ) {
2629 $ok = $this->update( $table, $set, $where, $fname );
2630 $affectedRowCount +
= $this->affectedRows();
2634 # Now insert any non-conflicting row(s)
2635 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2636 $affectedRowCount +
= $this->affectedRows();
2637 $this->endAtomic( $fname );
2638 $this->affectedRowCount
= $affectedRowCount;
2639 } catch ( Exception
$e ) {
2640 $this->cancelAtomic( $fname );
2647 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2651 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2654 $delTable = $this->tableName( $delTable );
2655 $joinTable = $this->tableName( $joinTable );
2656 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2657 if ( $conds != '*' ) {
2658 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2662 $this->query( $sql, $fname );
2665 public function textFieldSize( $table, $field ) {
2666 $table = $this->tableName( $table );
2667 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2668 $res = $this->query( $sql, __METHOD__
);
2669 $row = $this->fetchObject( $res );
2673 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2682 public function delete( $table, $conds, $fname = __METHOD__
) {
2684 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2687 $table = $this->tableName( $table );
2688 $sql = "DELETE FROM $table";
2690 if ( $conds != '*' ) {
2691 if ( is_array( $conds ) ) {
2692 $conds = $this->makeList( $conds, self
::LIST_AND
);
2694 $sql .= ' WHERE ' . $conds;
2697 return $this->query( $sql, $fname );
2700 final public function insertSelect(
2701 $destTable, $srcTable, $varMap, $conds,
2702 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2704 static $hints = [ 'NO_AUTO_COLUMNS' ];
2706 $insertOptions = (array)$insertOptions;
2707 $selectOptions = (array)$selectOptions;
2709 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2710 // For massive migrations with downtime, we don't want to select everything
2711 // into memory and OOM, so do all this native on the server side if possible.
2712 return $this->nativeInsertSelect(
2718 array_diff( $insertOptions, $hints ),
2724 return $this->nonNativeInsertSelect(
2730 array_diff( $insertOptions, $hints ),
2737 * @param array $insertOptions INSERT options
2738 * @param array $selectOptions SELECT options
2739 * @return bool Whether an INSERT SELECT with these options will be replication safe
2742 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2747 * Implementation of insertSelect() based on select() and insert()
2749 * @see IDatabase::insertSelect()
2751 * @param string $destTable
2752 * @param string|array $srcTable
2753 * @param array $varMap
2754 * @param array $conds
2755 * @param string $fname
2756 * @param array $insertOptions
2757 * @param array $selectOptions
2758 * @param array $selectJoinConds
2761 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2762 $fname = __METHOD__
,
2763 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2765 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2766 // on only the master (without needing row-based-replication). It also makes it easy to
2767 // know how big the INSERT is going to be.
2769 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2770 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2772 $selectOptions[] = 'FOR UPDATE';
2773 $res = $this->select(
2774 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2781 $affectedRowCount = 0;
2782 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2785 foreach ( $res as $row ) {
2786 $rows[] = (array)$row;
2788 // Avoid inserts that are too huge
2789 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2790 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2794 $affectedRowCount +
= $this->affectedRows();
2798 if ( $rows && $ok ) {
2799 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2801 $affectedRowCount +
= $this->affectedRows();
2805 $this->endAtomic( $fname );
2806 $this->affectedRowCount
= $affectedRowCount;
2808 $this->cancelAtomic( $fname );
2811 } catch ( Exception
$e ) {
2812 $this->cancelAtomic( $fname );
2818 * Native server-side implementation of insertSelect() for situations where
2819 * we don't want to select everything into memory
2821 * @see IDatabase::insertSelect()
2822 * @param string $destTable
2823 * @param string|array $srcTable
2824 * @param array $varMap
2825 * @param array $conds
2826 * @param string $fname
2827 * @param array $insertOptions
2828 * @param array $selectOptions
2829 * @param array $selectJoinConds
2832 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2833 $fname = __METHOD__
,
2834 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2836 $destTable = $this->tableName( $destTable );
2838 if ( !is_array( $insertOptions ) ) {
2839 $insertOptions = [ $insertOptions ];
2842 $insertOptions = $this->makeInsertOptions( $insertOptions );
2844 $selectSql = $this->selectSQLText(
2846 array_values( $varMap ),
2853 $sql = "INSERT $insertOptions" .
2854 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2857 return $this->query( $sql, $fname );
2861 * Construct a LIMIT query with optional offset. This is used for query
2862 * pages. The SQL should be adjusted so that only the first $limit rows
2863 * are returned. If $offset is provided as well, then the first $offset
2864 * rows should be discarded, and the next $limit rows should be returned.
2865 * If the result of the query is not ordered, then the rows to be returned
2866 * are theoretically arbitrary.
2868 * $sql is expected to be a SELECT, if that makes a difference.
2870 * The version provided by default works in MySQL and SQLite. It will very
2871 * likely need to be overridden for most other DBMSes.
2873 * @param string $sql SQL query we will append the limit too
2874 * @param int $limit The SQL limit
2875 * @param int|bool $offset The SQL offset (default false)
2876 * @throws DBUnexpectedError
2879 public function limitResult( $sql, $limit, $offset = false ) {
2880 if ( !is_numeric( $limit ) ) {
2881 throw new DBUnexpectedError( $this,
2882 "Invalid non-numeric limit passed to limitResult()\n" );
2885 return "$sql LIMIT "
2886 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2890 public function unionSupportsOrderAndLimit() {
2891 return true; // True for almost every DB supported
2894 public function unionQueries( $sqls, $all ) {
2895 $glue = $all ?
') UNION ALL (' : ') UNION (';
2897 return '(' . implode( $glue, $sqls ) . ')';
2900 public function unionConditionPermutations(
2901 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2902 $options = [], $join_conds = []
2904 // First, build the Cartesian product of $permute_conds
2906 foreach ( $permute_conds as $field => $values ) {
2908 // Skip empty $values
2911 $values = array_unique( $values ); // For sanity
2913 foreach ( $conds as $cond ) {
2914 foreach ( $values as $value ) {
2915 $cond[$field] = $value;
2916 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2922 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2924 // If there's just one condition and no subordering, hand off to
2925 // selectSQLText directly.
2926 if ( count( $conds ) === 1 &&
2927 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2929 return $this->selectSQLText(
2930 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2934 // Otherwise, we need to pull out the order and limit to apply after
2935 // the union. Then build the SQL queries for each set of conditions in
2936 // $conds. Then union them together (using UNION ALL, because the
2937 // product *should* already be distinct).
2938 $orderBy = $this->makeOrderBy( $options );
2939 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2940 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2941 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2942 if ( !$this->unionSupportsOrderAndLimit() ) {
2943 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2945 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2946 $options['ORDER BY'] = $options['INNER ORDER BY'];
2948 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2949 // We need to increase the limit by the offset rather than
2950 // using the offset directly, otherwise it'll skip incorrectly
2951 // in the subqueries.
2952 $options['LIMIT'] = $limit +
$offset;
2953 unset( $options['OFFSET'] );
2958 foreach ( $conds as $cond ) {
2959 $sqls[] = $this->selectSQLText(
2960 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2963 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2964 if ( $limit !== null ) {
2965 $sql = $this->limitResult( $sql, $limit, $offset );
2971 public function conditional( $cond, $trueVal, $falseVal ) {
2972 if ( is_array( $cond ) ) {
2973 $cond = $this->makeList( $cond, self
::LIST_AND
);
2976 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2979 public function strreplace( $orig, $old, $new ) {
2980 return "REPLACE({$orig}, {$old}, {$new})";
2983 public function getServerUptime() {
2987 public function wasDeadlock() {
2991 public function wasLockTimeout() {
2995 public function wasConnectionLoss() {
2996 return $this->wasConnectionError( $this->lastErrno() );
2999 public function wasReadOnlyError() {
3003 public function wasErrorReissuable() {
3005 $this->wasDeadlock() ||
3006 $this->wasLockTimeout() ||
3007 $this->wasConnectionLoss()
3012 * Do not use this method outside of Database/DBError classes
3014 * @param int|string $errno
3015 * @return bool Whether the given query error was a connection drop
3017 public function wasConnectionError( $errno ) {
3021 public function deadlockLoop() {
3022 $args = func_get_args();
3023 $function = array_shift( $args );
3024 $tries = self
::DEADLOCK_TRIES
;
3026 $this->begin( __METHOD__
);
3029 /** @var Exception $e */
3033 $retVal = call_user_func_array( $function, $args );
3035 } catch ( DBQueryError
$e ) {
3036 if ( $this->wasDeadlock() ) {
3037 // Retry after a randomized delay
3038 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3040 // Throw the error back up
3044 } while ( --$tries > 0 );
3046 if ( $tries <= 0 ) {
3047 // Too many deadlocks; give up
3048 $this->rollback( __METHOD__
);
3051 $this->commit( __METHOD__
);
3057 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3058 # Real waits are implemented in the subclass.
3062 public function getReplicaPos() {
3067 public function getMasterPos() {
3072 public function serverIsReadOnly() {
3076 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3077 if ( !$this->trxLevel
) {
3078 throw new DBUnexpectedError( $this, "No transaction is active." );
3080 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3083 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3084 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3085 if ( !$this->trxLevel
) {
3086 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3090 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3091 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
3092 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3093 // an implicit commit of all peer databases. This is true even if a transaction has
3094 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3095 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3097 // No transaction is active nor will start implicitly, so make one for this callback
3098 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3100 call_user_func( $callback );
3101 $this->endAtomic( __METHOD__
);
3102 } catch ( Exception
$e ) {
3103 $this->cancelAtomic( __METHOD__
);
3109 final public function setTransactionListener( $name, callable
$callback = null ) {
3111 $this->trxRecurringCallbacks
[$name] = $callback;
3113 unset( $this->trxRecurringCallbacks
[$name] );
3118 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3120 * This method should not be used outside of Database/LoadBalancer
3122 * @param bool $suppress
3125 final public function setTrxEndCallbackSuppression( $suppress ) {
3126 $this->trxEndCallbacksSuppressed
= $suppress;
3130 * Actually run and consume any "on transaction idle/resolution" callbacks.
3132 * This method should not be used outside of Database/LoadBalancer
3134 * @param int $trigger IDatabase::TRIGGER_* constant
3138 public function runOnTransactionIdleCallbacks( $trigger ) {
3139 if ( $this->trxEndCallbacksSuppressed
) {
3143 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3144 /** @var Exception $e */
3145 $e = null; // first exception
3146 do { // callbacks may add callbacks :)
3147 $callbacks = array_merge(
3148 $this->trxIdleCallbacks
,
3149 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3151 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3152 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3153 foreach ( $callbacks as $callback ) {
3155 list( $phpCallback ) = $callback;
3156 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3157 call_user_func_array( $phpCallback, [ $trigger ] );
3159 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3161 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3163 } catch ( Exception
$ex ) {
3164 call_user_func( $this->errorLogger
, $ex );
3166 // Some callbacks may use startAtomic/endAtomic, so make sure
3167 // their transactions are ended so other callbacks don't fail
3168 if ( $this->trxLevel() ) {
3169 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3173 } while ( count( $this->trxIdleCallbacks
) );
3175 if ( $e instanceof Exception
) {
3176 throw $e; // re-throw any first exception
3181 * Actually run and consume any "on transaction pre-commit" callbacks.
3183 * This method should not be used outside of Database/LoadBalancer
3188 public function runOnTransactionPreCommitCallbacks() {
3189 $e = null; // first exception
3190 do { // callbacks may add callbacks :)
3191 $callbacks = $this->trxPreCommitCallbacks
;
3192 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3193 foreach ( $callbacks as $callback ) {
3195 list( $phpCallback ) = $callback;
3196 call_user_func( $phpCallback );
3197 } catch ( Exception
$ex ) {
3198 call_user_func( $this->errorLogger
, $ex );
3202 } while ( count( $this->trxPreCommitCallbacks
) );
3204 if ( $e instanceof Exception
) {
3205 throw $e; // re-throw any first exception
3210 * Actually run any "transaction listener" callbacks.
3212 * This method should not be used outside of Database/LoadBalancer
3214 * @param int $trigger IDatabase::TRIGGER_* constant
3218 public function runTransactionListenerCallbacks( $trigger ) {
3219 if ( $this->trxEndCallbacksSuppressed
) {
3223 /** @var Exception $e */
3224 $e = null; // first exception
3226 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3228 $phpCallback( $trigger, $this );
3229 } catch ( Exception
$ex ) {
3230 call_user_func( $this->errorLogger
, $ex );
3235 if ( $e instanceof Exception
) {
3236 throw $e; // re-throw any first exception
3241 * Create a savepoint
3243 * This is used internally to implement atomic sections. It should not be
3247 * @param string $identifier Identifier for the savepoint
3248 * @param string $fname Calling function name
3250 protected function doSavepoint( $identifier, $fname ) {
3251 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3255 * Release a savepoint
3257 * This is used internally to implement atomic sections. It should not be
3261 * @param string $identifier Identifier for the savepoint
3262 * @param string $fname Calling function name
3264 protected function doReleaseSavepoint( $identifier, $fname ) {
3265 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3269 * Rollback to a savepoint
3271 * This is used internally to implement atomic sections. It should not be
3275 * @param string $identifier Identifier for the savepoint
3276 * @param string $fname Calling function name
3278 protected function doRollbackToSavepoint( $identifier, $fname ) {
3279 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3282 final public function startAtomic(
3283 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3285 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3286 if ( !$this->trxLevel
) {
3287 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3288 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3289 // in all changes being in one transaction to keep requests transactional.
3290 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3291 $this->trxAutomaticAtomic
= true;
3293 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3294 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3295 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3296 $this->queryLogger
->warning(
3297 'There have been an excessively large number of atomic sections in a transaction'
3298 . " started by $this->trxFname, reusing IDs (at $fname)",
3299 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3301 $this->trxAtomicCounter
= 0;
3302 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3304 $this->doSavepoint( $savepointId, $fname );
3307 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3310 final public function endAtomic( $fname = __METHOD__
) {
3311 if ( !$this->trxLevel
) {
3312 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3315 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3316 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3317 if ( $savedFname !== $fname ) {
3318 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3321 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3322 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3323 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3324 $this->doReleaseSavepoint( $savepointId, $fname );
3328 final public function cancelAtomic( $fname = __METHOD__
) {
3329 if ( !$this->trxLevel
) {
3330 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3333 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3334 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3335 if ( $savedFname !== $fname ) {
3336 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3338 if ( !$savepointId ) {
3339 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3342 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3343 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3344 } elseif ( $savepointId !== 'n/a' ) {
3345 $this->doRollbackToSavepoint( $savepointId, $fname );
3348 $this->affectedRowCount
= 0; // for the sake of consistency
3351 final public function doAtomicSection( $fname, callable
$callback ) {
3352 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3354 $res = call_user_func_array( $callback, [ $this, $fname ] );
3355 } catch ( Exception
$e ) {
3356 $this->cancelAtomic( $fname );
3359 $this->endAtomic( $fname );
3364 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3365 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3366 if ( $this->trxLevel
) {
3367 if ( $this->trxAtomicLevels
) {
3368 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3369 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3371 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3372 throw new DBUnexpectedError( $this, $msg );
3373 } elseif ( !$this->trxAutomatic
) {
3374 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3375 throw new DBUnexpectedError( $this, $msg );
3377 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3378 throw new DBUnexpectedError( $this, $msg );
3380 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3381 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3382 throw new DBUnexpectedError( $this, $msg );
3385 // Avoid fatals if close() was called
3386 $this->assertOpen();
3388 $this->doBegin( $fname );
3389 $this->trxAtomicCounter
= 0;
3390 $this->trxTimestamp
= microtime( true );
3391 $this->trxFname
= $fname;
3392 $this->trxDoneWrites
= false;
3393 $this->trxAutomaticAtomic
= false;
3394 $this->trxAtomicLevels
= [];
3395 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3396 $this->trxWriteDuration
= 0.0;
3397 $this->trxWriteQueryCount
= 0;
3398 $this->trxWriteAffectedRows
= 0;
3399 $this->trxWriteAdjDuration
= 0.0;
3400 $this->trxWriteAdjQueryCount
= 0;
3401 $this->trxWriteCallers
= [];
3402 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3403 // Get an estimate of the replica DB lag before then, treating estimate staleness
3404 // as lag itself just to be safe
3405 $status = $this->getApproximateLagStatus();
3406 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3407 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3408 // caller will think its OK to muck around with the transaction just because startAtomic()
3409 // has not yet completed (e.g. setting trxAtomicLevels).
3410 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3414 * Issues the BEGIN command to the database server.
3416 * @see Database::begin()
3417 * @param string $fname
3419 protected function doBegin( $fname ) {
3420 $this->query( 'BEGIN', $fname );
3421 $this->trxLevel
= 1;
3424 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3425 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3426 // There are still atomic sections open. This cannot be ignored
3427 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3428 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3430 throw new DBUnexpectedError(
3432 "$fname: Got COMMIT while atomic sections $levels are still open."
3436 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3437 if ( !$this->trxLevel
) {
3438 return; // nothing to do
3439 } elseif ( !$this->trxAutomatic
) {
3440 throw new DBUnexpectedError(
3442 "$fname: Flushing an explicit transaction, getting out of sync."
3446 if ( !$this->trxLevel
) {
3447 $this->queryLogger
->error(
3448 "$fname: No transaction to commit, something got out of sync." );
3449 return; // nothing to do
3450 } elseif ( $this->trxAutomatic
) {
3451 throw new DBUnexpectedError(
3453 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3458 // Avoid fatals if close() was called
3459 $this->assertOpen();
3461 $this->runOnTransactionPreCommitCallbacks();
3462 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3463 $this->doCommit( $fname );
3464 if ( $this->trxDoneWrites
) {
3465 $this->lastWriteTime
= microtime( true );
3466 $this->trxProfiler
->transactionWritingOut(
3471 $this->trxWriteAffectedRows
3475 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3476 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3480 * Issues the COMMIT command to the database server.
3482 * @see Database::commit()
3483 * @param string $fname
3485 protected function doCommit( $fname ) {
3486 if ( $this->trxLevel
) {
3487 $this->query( 'COMMIT', $fname );
3488 $this->trxLevel
= 0;
3492 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3493 $trxActive = $this->trxLevel
;
3495 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3496 if ( $this->getFlag( self
::DBO_TRX
) ) {
3497 throw new DBUnexpectedError(
3499 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3505 // Avoid fatals if close() was called
3506 $this->assertOpen();
3508 $this->doRollback( $fname );
3509 $this->trxAtomicLevels
= [];
3510 if ( $this->trxDoneWrites
) {
3511 $this->trxProfiler
->transactionWritingOut(
3519 // Clear any commit-dependant callbacks. They might even be present
3520 // only due to transaction rounds, with no SQL transaction being active
3521 $this->trxIdleCallbacks
= [];
3522 $this->trxPreCommitCallbacks
= [];
3526 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3527 } catch ( Exception
$e ) {
3528 // already logged; finish and let LoadBalancer move on during mass-rollback
3531 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3532 } catch ( Exception
$e ) {
3533 // already logged; let LoadBalancer move on during mass-rollback
3536 $this->affectedRowCount
= 0; // for the sake of consistency
3541 * Issues the ROLLBACK command to the database server.
3543 * @see Database::rollback()
3544 * @param string $fname
3546 protected function doRollback( $fname ) {
3547 if ( $this->trxLevel
) {
3548 # Disconnects cause rollback anyway, so ignore those errors
3549 $ignoreErrors = true;
3550 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3551 $this->trxLevel
= 0;
3555 public function flushSnapshot( $fname = __METHOD__
) {
3556 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3557 // This only flushes transactions to clear snapshots, not to write data
3558 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3559 throw new DBUnexpectedError(
3561 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3565 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3568 public function explicitTrxActive() {
3569 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3572 public function duplicateTableStructure(
3573 $oldName, $newName, $temporary = false, $fname = __METHOD__
3575 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3578 public function listTables( $prefix = null, $fname = __METHOD__
) {
3579 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3582 public function listViews( $prefix = null, $fname = __METHOD__
) {
3583 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3586 public function timestamp( $ts = 0 ) {
3587 $t = new ConvertibleTimestamp( $ts );
3588 // Let errors bubble up to avoid putting garbage in the DB
3589 return $t->getTimestamp( TS_MW
);
3592 public function timestampOrNull( $ts = null ) {
3593 if ( is_null( $ts ) ) {
3596 return $this->timestamp( $ts );
3600 public function affectedRows() {
3601 return ( $this->affectedRowCount
=== null )
3602 ?
$this->fetchAffectedRowCount() // default to driver value
3603 : $this->affectedRowCount
;
3607 * @return int Number of retrieved rows according to the driver
3609 abstract protected function fetchAffectedRowCount();
3612 * Take the result from a query, and wrap it in a ResultWrapper if
3613 * necessary. Boolean values are passed through as is, to indicate success
3614 * of write queries or failure.
3616 * Once upon a time, Database::query() returned a bare MySQL result
3617 * resource, and it was necessary to call this function to convert it to
3618 * a wrapper. Nowadays, raw database objects are never exposed to external
3619 * callers, so this is unnecessary in external code.
3621 * @param bool|ResultWrapper|resource|object $result
3622 * @return bool|ResultWrapper
3624 protected function resultObject( $result ) {
3627 } elseif ( $result instanceof ResultWrapper
) {
3629 } elseif ( $result === true ) {
3630 // Successful write query
3633 return new ResultWrapper( $this, $result );
3637 public function ping( &$rtt = null ) {
3638 // Avoid hitting the server if it was hit recently
3639 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3640 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3641 $rtt = $this->rttEstimate
;
3642 return true; // don't care about $rtt
3646 // This will reconnect if possible or return false if not
3647 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3648 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3649 $this->restoreFlags( self
::RESTORE_PRIOR
);
3652 $rtt = $this->rttEstimate
;
3659 * Close existing database connection and open a new connection
3661 * @return bool True if new connection is opened successfully, false if error
3663 protected function reconnect() {
3664 $this->closeConnection();
3665 $this->opened
= false;
3666 $this->conn
= false;
3668 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3669 $this->lastPing
= microtime( true );
3671 } catch ( DBConnectionError
$e ) {
3678 public function getSessionLagStatus() {
3679 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3683 * Get the replica DB lag when the current transaction started
3685 * This is useful when transactions might use snapshot isolation
3686 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3687 * is this lag plus transaction duration. If they don't, it is still
3688 * safe to be pessimistic. This returns null if there is no transaction.
3690 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3693 protected function getTransactionLagStatus() {
3694 return $this->trxLevel
3695 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3700 * Get a replica DB lag estimate for this server
3702 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3705 protected function getApproximateLagStatus() {
3707 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3708 'since' => microtime( true )
3713 * Merge the result of getSessionLagStatus() for several DBs
3714 * using the most pessimistic values to estimate the lag of
3715 * any data derived from them in combination
3717 * This is information is useful for caching modules
3719 * @see WANObjectCache::set()
3720 * @see WANObjectCache::getWithSetCallback()
3722 * @param IDatabase $db1
3723 * @param IDatabase $db2 [optional]
3724 * @return array Map of values:
3725 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3726 * - since: oldest UNIX timestamp of any of the DB lag estimates
3727 * - pending: whether any of the DBs have uncommitted changes
3731 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3732 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3733 foreach ( func_get_args() as $db ) {
3734 /** @var IDatabase $db */
3735 $status = $db->getSessionLagStatus();
3736 if ( $status['lag'] === false ) {
3737 $res['lag'] = false;
3738 } elseif ( $res['lag'] !== false ) {
3739 $res['lag'] = max( $res['lag'], $status['lag'] );
3741 $res['since'] = min( $res['since'], $status['since'] );
3742 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3748 public function getLag() {
3752 public function maxListLen() {
3756 public function encodeBlob( $b ) {
3760 public function decodeBlob( $b ) {
3761 if ( $b instanceof Blob
) {
3767 public function setSessionOptions( array $options ) {
3770 public function sourceFile(
3772 callable
$lineCallback = null,
3773 callable
$resultCallback = null,
3775 callable
$inputCallback = null
3777 Wikimedia\
suppressWarnings();
3778 $fp = fopen( $filename, 'r' );
3779 Wikimedia\restoreWarnings
();
3781 if ( false === $fp ) {
3782 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3786 $fname = __METHOD__
. "( $filename )";
3790 $error = $this->sourceStream(
3791 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3792 } catch ( Exception
$e ) {
3802 public function setSchemaVars( $vars ) {
3803 $this->schemaVars
= $vars;
3806 public function sourceStream(
3808 callable
$lineCallback = null,
3809 callable
$resultCallback = null,
3810 $fname = __METHOD__
,
3811 callable
$inputCallback = null
3813 $delimiterReset = new ScopedCallback(
3814 function ( $delimiter ) {
3815 $this->delimiter
= $delimiter;
3817 [ $this->delimiter
]
3821 while ( !feof( $fp ) ) {
3822 if ( $lineCallback ) {
3823 call_user_func( $lineCallback );
3826 $line = trim( fgets( $fp ) );
3828 if ( $line == '' ) {
3832 if ( '-' == $line[0] && '-' == $line[1] ) {
3840 $done = $this->streamStatementEnd( $cmd, $line );
3844 if ( $done ||
feof( $fp ) ) {
3845 $cmd = $this->replaceVars( $cmd );
3847 if ( $inputCallback ) {
3848 $callbackResult = call_user_func( $inputCallback, $cmd );
3850 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3851 $cmd = $callbackResult;
3856 $res = $this->query( $cmd, $fname );
3858 if ( $resultCallback ) {
3859 call_user_func( $resultCallback, $res, $this );
3862 if ( false === $res ) {
3863 $err = $this->lastError();
3865 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3872 ScopedCallback
::consume( $delimiterReset );
3877 * Called by sourceStream() to check if we've reached a statement end
3879 * @param string &$sql SQL assembled so far
3880 * @param string &$newLine New line about to be added to $sql
3881 * @return bool Whether $newLine contains end of the statement
3883 public function streamStatementEnd( &$sql, &$newLine ) {
3884 if ( $this->delimiter
) {
3886 $newLine = preg_replace(
3887 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3888 if ( $newLine != $prev ) {
3897 * Database independent variable replacement. Replaces a set of variables
3898 * in an SQL statement with their contents as given by $this->getSchemaVars().
3900 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3902 * - '{$var}' should be used for text and is passed through the database's
3904 * - `{$var}` should be used for identifiers (e.g. table and database names).
3905 * It is passed through the database's addIdentifierQuotes method which
3906 * can be overridden if the database uses something other than backticks.
3907 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3908 * database's tableName method.
3909 * - / *i* / passes the name that follows through the database's indexName method.
3910 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3911 * its use should be avoided. In 1.24 and older, string encoding was applied.
3913 * @param string $ins SQL statement to replace variables in
3914 * @return string The new SQL statement with variables replaced
3916 protected function replaceVars( $ins ) {
3917 $vars = $this->getSchemaVars();
3918 return preg_replace_callback(
3920 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3921 \'\{\$ (\w+) }\' | # 3. addQuotes
3922 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3923 /\*\$ (\w+) \*/ # 5. leave unencoded
3925 function ( $m ) use ( $vars ) {
3926 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3927 // check for both nonexistent keys *and* the empty string.
3928 if ( isset( $m[1] ) && $m[1] !== '' ) {
3929 if ( $m[1] === 'i' ) {
3930 return $this->indexName( $m[2] );
3932 return $this->tableName( $m[2] );
3934 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3935 return $this->addQuotes( $vars[$m[3]] );
3936 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3937 return $this->addIdentifierQuotes( $vars[$m[4]] );
3938 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3939 return $vars[$m[5]];
3949 * Get schema variables. If none have been set via setSchemaVars(), then
3950 * use some defaults from the current object.
3954 protected function getSchemaVars() {
3955 if ( $this->schemaVars
) {
3956 return $this->schemaVars
;
3958 return $this->getDefaultSchemaVars();
3963 * Get schema variables to use if none have been set via setSchemaVars().
3965 * Override this in derived classes to provide variables for tables.sql
3966 * and SQL patch files.
3970 protected function getDefaultSchemaVars() {
3974 public function lockIsFree( $lockName, $method ) {
3975 // RDBMs methods for checking named locks may or may not count this thread itself.
3976 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3977 // the behavior choosen by the interface for this method.
3978 return !isset( $this->namedLocksHeld
[$lockName] );
3981 public function lock( $lockName, $method, $timeout = 5 ) {
3982 $this->namedLocksHeld
[$lockName] = 1;
3987 public function unlock( $lockName, $method ) {
3988 unset( $this->namedLocksHeld
[$lockName] );
3993 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3994 if ( $this->writesOrCallbacksPending() ) {
3995 // This only flushes transactions to clear snapshots, not to write data
3996 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3997 throw new DBUnexpectedError(
3999 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4003 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4007 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4008 if ( $this->trxLevel() ) {
4009 // There is a good chance an exception was thrown, causing any early return
4010 // from the caller. Let any error handler get a chance to issue rollback().
4011 // If there isn't one, let the error bubble up and trigger server-side rollback.
4012 $this->onTransactionResolution(
4013 function () use ( $lockKey, $fname ) {
4014 $this->unlock( $lockKey, $fname );
4019 $this->unlock( $lockKey, $fname );
4023 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4028 public function namedLocksEnqueue() {
4032 public function tableLocksHaveTransactionScope() {
4036 final public function lockTables( array $read, array $write, $method ) {
4037 if ( $this->writesOrCallbacksPending() ) {
4038 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4041 if ( $this->tableLocksHaveTransactionScope() ) {
4042 $this->startAtomic( $method );
4045 return $this->doLockTables( $read, $write, $method );
4049 * Helper function for lockTables() that handles the actual table locking
4051 * @param array $read Array of tables to lock for read access
4052 * @param array $write Array of tables to lock for write access
4053 * @param string $method Name of caller
4056 protected function doLockTables( array $read, array $write, $method ) {
4060 final public function unlockTables( $method ) {
4061 if ( $this->tableLocksHaveTransactionScope() ) {
4062 $this->endAtomic( $method );
4064 return true; // locks released on COMMIT/ROLLBACK
4067 return $this->doUnlockTables( $method );
4071 * Helper function for unlockTables() that handles the actual table unlocking
4073 * @param string $method Name of caller
4076 protected function doUnlockTables( $method ) {
4082 * @param string $tableName
4083 * @param string $fName
4084 * @return bool|ResultWrapper
4087 public function dropTable( $tableName, $fName = __METHOD__
) {
4088 if ( !$this->tableExists( $tableName, $fName ) ) {
4091 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4093 return $this->query( $sql, $fName );
4096 public function getInfinity() {
4100 public function encodeExpiry( $expiry ) {
4101 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4102 ?
$this->getInfinity()
4103 : $this->timestamp( $expiry );
4106 public function decodeExpiry( $expiry, $format = TS_MW
) {
4107 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4111 return ConvertibleTimestamp
::convert( $format, $expiry );
4114 public function setBigSelects( $value = true ) {
4118 public function isReadOnly() {
4119 return ( $this->getReadOnlyReason() !== false );
4123 * @return string|bool Reason this DB is read-only or false if it is not
4125 protected function getReadOnlyReason() {
4126 $reason = $this->getLBInfo( 'readOnlyReason' );
4128 return is_string( $reason ) ?
$reason : false;
4131 public function setTableAliases( array $aliases ) {
4132 $this->tableAliases
= $aliases;
4135 public function setIndexAliases( array $aliases ) {
4136 $this->indexAliases
= $aliases;
4140 * Get the underlying binding connection handle
4142 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4143 * This catches broken callers than catch and ignore disconnection exceptions.
4144 * Unlike checking isOpen(), this is safe to call inside of open().
4147 * @throws DBUnexpectedError
4150 protected function getBindingHandle() {
4151 if ( !$this->conn
) {
4152 throw new DBUnexpectedError(
4154 'DB connection was already closed or the connection dropped.'
4165 public function __toString() {
4166 return (string)$this->conn
;
4170 * Make sure that copies do not share the same client binding handle
4171 * @throws DBConnectionError
4173 public function __clone() {
4174 $this->connLogger
->warning(
4175 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4176 ( new RuntimeException() )->getTraceAsString()
4179 if ( $this->isOpen() ) {
4180 // Open a new connection resource without messing with the old one
4181 $this->opened
= false;
4182 $this->conn
= false;
4183 $this->trxEndCallbacks
= []; // don't copy
4184 $this->handleSessionLoss(); // no trx or locks anymore
4185 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4186 $this->lastPing
= microtime( true );
4191 * Called by serialize. Throw an exception when DB connection is serialized.
4192 * This causes problems on some database engines because the connection is
4193 * not restored on unserialize.
4195 public function __sleep() {
4196 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4197 'the connection is not restored on wakeup.' );
4201 * Run a few simple sanity checks and close dangling connections
4203 public function __destruct() {
4204 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4205 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4208 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4209 if ( $danglingWriters ) {
4210 $fnames = implode( ', ', $danglingWriters );
4211 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4214 if ( $this->conn
) {
4215 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4216 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4217 Wikimedia\
suppressWarnings();
4218 $this->closeConnection();
4219 Wikimedia\restoreWarnings
();
4220 $this->conn
= false;
4221 $this->opened
= false;
4226 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4227 class_alias( Database
::class, 'Database' ); // b/c global alias