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();
916 * @param string $error Fallback error message, used if none is given by DB
917 * @throws DBConnectionError
919 public function reportConnectionError( $error = 'Unknown error' ) {
920 $myError = $this->lastError();
926 throw new DBConnectionError( $this, $error );
930 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
932 * This might return things, such as mysqli_result, that do not formally implement
933 * IResultWrapper, but nonetheless implement all of its methods correctly
935 * @param string $sql SQL query.
936 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
938 abstract protected function doQuery( $sql );
941 * Determine whether a query writes to the DB.
942 * Should return true if unsure.
947 protected function isWriteQuery( $sql ) {
949 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
954 * @return string|null
956 protected function getQueryVerb( $sql ) {
957 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
961 * Determine whether a SQL statement is sensitive to isolation level.
962 * A SQL statement is considered transactable if its result could vary
963 * depending on the transaction isolation level. Operational commands
964 * such as 'SET' and 'SHOW' are not considered to be transactable.
969 protected function isTransactableQuery( $sql ) {
971 $this->getQueryVerb( $sql ),
972 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
978 * @param string $sql A SQL query
979 * @return bool Whether $sql is SQL for TEMPORARY table operation
981 protected function registerTempTableOperation( $sql ) {
983 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
987 $this->sessionTempTables
[$matches[1]] = 1;
990 } elseif ( preg_match(
991 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
995 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
996 unset( $this->sessionTempTables
[$matches[1]] );
999 } elseif ( preg_match(
1000 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1004 return isset( $this->sessionTempTables
[$matches[1]] );
1005 } elseif ( preg_match(
1006 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1010 return isset( $this->sessionTempTables
[$matches[1]] );
1016 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1017 $priorWritesPending = $this->writesOrCallbacksPending();
1018 $this->lastQuery
= $sql;
1020 $isWrite = $this->isWriteQuery( $sql );
1022 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1024 $isNonTempWrite = false;
1028 if ( $this->getLBInfo( 'replica' ) === true ) {
1031 'Write operations are not allowed on replica database connections.'
1034 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1035 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1036 $reason = $this->getReadOnlyReason();
1037 if ( $reason !== false ) {
1038 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1040 # Set a flag indicating that writes have been done
1041 $this->lastWriteTime
= microtime( true );
1044 # Add trace comment to the begin of the sql string, right after the operator.
1045 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1046 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1048 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1049 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1050 && $this->isTransactableQuery( $sql )
1052 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1053 $this->trxAutomatic
= true;
1056 # Keep track of whether the transaction has write queries pending
1057 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1058 $this->trxDoneWrites
= true;
1059 $this->trxProfiler
->transactionWritingIn(
1060 $this->server
, $this->dbName
, $this->trxShortId
);
1063 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1064 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1067 # Avoid fatals if close() was called
1068 $this->assertOpen();
1070 # Send the query to the server and fetch any corresponding errors
1071 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1072 $lastError = $this->lastError();
1073 $lastErrno = $this->lastErrno();
1075 # Try reconnecting if the connection was lost
1076 if ( $ret === false && $this->wasConnectionLoss() ) {
1077 # Check if any meaningful session state was lost
1078 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1079 # Update session state tracking and try to restore the connection
1080 $reconnected = $this->replaceLostConnection( __METHOD__
);
1081 # Silently resend the query to the server if it is safe and possible
1082 if ( $reconnected && $recoverable ) {
1083 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1084 $lastError = $this->lastError();
1085 $lastErrno = $this->lastErrno();
1087 if ( $ret === false && $this->wasConnectionLoss() ) {
1088 # Query probably causes disconnects; reconnect and do not re-run it
1089 $this->replaceLostConnection( __METHOD__
);
1094 if ( $ret === false ) {
1095 # Deadlocks cause the entire transaction to abort, not just the statement.
1096 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1097 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1098 if ( $this->wasDeadlock() ) {
1099 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1100 $tempIgnore = false; // not recoverable
1102 # Usually the transaction is rolled back to BEGIN, leaving an empty transaction.
1103 # Destroy any such transaction so the rollback callbacks run in AUTO-COMMIT mode
1104 # as normal. Also, if DBO_TRX is set and an explicit transaction rolled back here,
1105 # further queries should be back in AUTO-COMMIT mode, not stuck in a transaction.
1106 $this->doRollback( __METHOD__
);
1107 # Update state tracking to reflect transaction loss
1108 $this->handleTransactionLoss();
1111 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1114 return $this->resultObject( $ret );
1118 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1120 * @param string $sql Original SQL query
1121 * @param string $commentedSql SQL query with debugging/trace comment
1122 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1123 * @param string $fname Name of the calling function
1124 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1125 * object for a successful read query, or false on failure
1127 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1128 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1129 # generalizeSQL() will probably cut down the query to reasonable
1130 # logging size most of the time. The substr is really just a sanity check.
1132 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1134 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1137 # Include query transaction state
1138 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1140 $startTime = microtime( true );
1141 if ( $this->profiler
) {
1142 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1144 $this->affectedRowCount
= null;
1145 $ret = $this->doQuery( $commentedSql );
1146 $this->affectedRowCount
= $this->affectedRows();
1147 if ( $this->profiler
) {
1148 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1150 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1152 unset( $queryProfSection ); // profile out (if set)
1154 if ( $ret !== false ) {
1155 $this->lastPing
= $startTime;
1156 if ( $isWrite && $this->trxLevel
) {
1157 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1158 $this->trxWriteCallers
[] = $fname;
1162 if ( $sql === self
::PING_QUERY
) {
1163 $this->rttEstimate
= $queryRuntime;
1166 $this->trxProfiler
->recordQueryCompletion(
1167 $queryProf, $startTime, $isWrite, $this->affectedRows()
1169 $this->queryLogger
->debug( $sql, [
1171 'master' => $isMaster,
1172 'runtime' => $queryRuntime,
1179 * Update the estimated run-time of a query, not counting large row lock times
1181 * LoadBalancer can be set to rollback transactions that will create huge replication
1182 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1183 * queries, like inserting a row can take a long time due to row locking. This method
1184 * uses some simple heuristics to discount those cases.
1186 * @param string $sql A SQL write query
1187 * @param float $runtime Total runtime, including RTT
1188 * @param int $affected Affected row count
1190 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1191 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1192 $indicativeOfReplicaRuntime = true;
1193 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1194 $verb = $this->getQueryVerb( $sql );
1195 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1196 if ( $verb === 'INSERT' ) {
1197 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1198 } elseif ( $verb === 'REPLACE' ) {
1199 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1203 $this->trxWriteDuration +
= $runtime;
1204 $this->trxWriteQueryCount +
= 1;
1205 $this->trxWriteAffectedRows +
= $affected;
1206 if ( $indicativeOfReplicaRuntime ) {
1207 $this->trxWriteAdjDuration +
= $runtime;
1208 $this->trxWriteAdjQueryCount +
= 1;
1213 * Determine whether or not it is safe to retry queries after a database
1214 * connection is lost
1216 * @param string $sql SQL query
1217 * @param bool $priorWritesPending Whether there is a transaction open with
1218 * possible write queries or transaction pre-commit/idle callbacks
1219 * waiting on it to finish.
1220 * @return bool True if it is safe to retry the query, false otherwise
1222 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1223 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1224 # Dropped connections also mean that named locks are automatically released.
1225 # Only allow error suppression in autocommit mode or when the lost transaction
1226 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1227 if ( $this->namedLocksHeld
) {
1228 return false; // possible critical section violation
1229 } elseif ( $this->sessionTempTables
) {
1230 return false; // tables might be queried latter
1231 } elseif ( $sql === 'COMMIT' ) {
1232 return !$priorWritesPending; // nothing written anyway? (T127428)
1233 } elseif ( $sql === 'ROLLBACK' ) {
1234 return true; // transaction lost...which is also what was requested :)
1235 } elseif ( $this->explicitTrxActive() ) {
1236 return false; // don't drop atomocity
1237 } elseif ( $priorWritesPending ) {
1238 return false; // prior writes lost from implicit transaction
1245 * Clean things up after session (and thus transaction) loss
1247 private function handleSessionLoss() {
1248 // Clean up tracking of session-level things...
1249 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1250 // https://www.postgresql.org/docs/9.1/static/sql-createtable.html (ignoring ON COMMIT)
1251 $this->sessionTempTables
= [];
1252 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1253 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1254 $this->namedLocksHeld
= [];
1255 // Session loss implies transaction loss
1256 $this->handleTransactionLoss();
1260 * Clean things up after transaction loss
1262 private function handleTransactionLoss() {
1263 $this->trxLevel
= 0;
1264 $this->trxAtomicCounter
= 0;
1265 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1266 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1268 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1269 // If callback suppression is set then the array will remain unhandled.
1270 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1271 } catch ( Exception
$ex ) {
1272 // Already logged; move on...
1275 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1276 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1277 } catch ( Exception
$ex ) {
1278 // Already logged; move on...
1283 * Checks whether the cause of the error is detected to be a timeout.
1285 * It returns false by default, and not all engines support detecting this yet.
1286 * If this returns false, it will be treated as a generic query error.
1288 * @param string $error Error text
1289 * @param int $errno Error number
1292 protected function wasQueryTimeout( $error, $errno ) {
1297 * Report a query error. Log the error, and if neither the object ignore
1298 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1300 * @param string $error
1302 * @param string $sql
1303 * @param string $fname
1304 * @param bool $tempIgnore
1305 * @throws DBQueryError
1307 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1308 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1309 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1311 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1312 $this->queryLogger
->error(
1313 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1314 $this->getLogContext( [
1315 'method' => __METHOD__
,
1318 'sql1line' => $sql1line,
1322 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1323 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1324 if ( $wasQueryTimeout ) {
1325 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1327 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1332 public function freeResult( $res ) {
1335 public function selectField(
1336 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1338 if ( $var === '*' ) { // sanity
1339 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1342 if ( !is_array( $options ) ) {
1343 $options = [ $options ];
1346 $options['LIMIT'] = 1;
1348 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1349 if ( $res === false ||
!$this->numRows( $res ) ) {
1353 $row = $this->fetchRow( $res );
1355 if ( $row !== false ) {
1356 return reset( $row );
1362 public function selectFieldValues(
1363 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1365 if ( $var === '*' ) { // sanity
1366 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1367 } elseif ( !is_string( $var ) ) { // sanity
1368 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1371 if ( !is_array( $options ) ) {
1372 $options = [ $options ];
1375 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1376 if ( $res === false ) {
1381 foreach ( $res as $row ) {
1382 $values[] = $row->$var;
1389 * Returns an optional USE INDEX clause to go after the table, and a
1390 * string to go at the end of the query.
1392 * @param array $options Associative array of options to be turned into
1393 * an SQL query, valid keys are listed in the function.
1395 * @see Database::select()
1397 protected function makeSelectOptions( $options ) {
1398 $preLimitTail = $postLimitTail = '';
1403 foreach ( $options as $key => $option ) {
1404 if ( is_numeric( $key ) ) {
1405 $noKeyOptions[$option] = true;
1409 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1411 $preLimitTail .= $this->makeOrderBy( $options );
1413 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1414 $postLimitTail .= ' FOR UPDATE';
1417 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1418 $postLimitTail .= ' LOCK IN SHARE MODE';
1421 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1422 $startOpts .= 'DISTINCT';
1425 # Various MySQL extensions
1426 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1427 $startOpts .= ' /*! STRAIGHT_JOIN */';
1430 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1431 $startOpts .= ' HIGH_PRIORITY';
1434 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1435 $startOpts .= ' SQL_BIG_RESULT';
1438 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1439 $startOpts .= ' SQL_BUFFER_RESULT';
1442 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1443 $startOpts .= ' SQL_SMALL_RESULT';
1446 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1447 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1450 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1451 $startOpts .= ' SQL_CACHE';
1454 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1455 $startOpts .= ' SQL_NO_CACHE';
1458 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1459 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1463 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1464 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1469 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1473 * Returns an optional GROUP BY with an optional HAVING
1475 * @param array $options Associative array of options
1477 * @see Database::select()
1480 protected function makeGroupByWithHaving( $options ) {
1482 if ( isset( $options['GROUP BY'] ) ) {
1483 $gb = is_array( $options['GROUP BY'] )
1484 ?
implode( ',', $options['GROUP BY'] )
1485 : $options['GROUP BY'];
1486 $sql .= ' GROUP BY ' . $gb;
1488 if ( isset( $options['HAVING'] ) ) {
1489 $having = is_array( $options['HAVING'] )
1490 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1491 : $options['HAVING'];
1492 $sql .= ' HAVING ' . $having;
1499 * Returns an optional ORDER BY
1501 * @param array $options Associative array of options
1503 * @see Database::select()
1506 protected function makeOrderBy( $options ) {
1507 if ( isset( $options['ORDER BY'] ) ) {
1508 $ob = is_array( $options['ORDER BY'] )
1509 ?
implode( ',', $options['ORDER BY'] )
1510 : $options['ORDER BY'];
1512 return ' ORDER BY ' . $ob;
1518 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1519 $options = [], $join_conds = [] ) {
1520 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1522 return $this->query( $sql, $fname );
1525 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1526 $options = [], $join_conds = []
1528 if ( is_array( $vars ) ) {
1529 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1532 $options = (array)$options;
1533 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1534 ?
$options['USE INDEX']
1537 isset( $options['IGNORE INDEX'] ) &&
1538 is_array( $options['IGNORE INDEX'] )
1540 ?
$options['IGNORE INDEX']
1543 if ( is_array( $table ) ) {
1545 $this->tableNamesWithIndexClauseOrJOIN(
1546 $table, $useIndexes, $ignoreIndexes, $join_conds );
1547 } elseif ( $table != '' ) {
1549 $this->tableNamesWithIndexClauseOrJOIN(
1550 [ $table ], $useIndexes, $ignoreIndexes, [] );
1555 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1556 $this->makeSelectOptions( $options );
1558 if ( is_array( $conds ) ) {
1559 $conds = $this->makeList( $conds, self
::LIST_AND
);
1562 if ( $conds === null ||
$conds === false ) {
1563 $this->queryLogger
->warning(
1567 . ' with incorrect parameters: $conds must be a string or an array'
1572 if ( $conds === '' ) {
1573 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1574 } elseif ( is_string( $conds ) ) {
1575 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1576 "WHERE $conds $preLimitTail";
1578 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1581 if ( isset( $options['LIMIT'] ) ) {
1582 $sql = $this->limitResult( $sql, $options['LIMIT'],
1583 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1585 $sql = "$sql $postLimitTail";
1587 if ( isset( $options['EXPLAIN'] ) ) {
1588 $sql = 'EXPLAIN ' . $sql;
1594 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1595 $options = [], $join_conds = []
1597 $options = (array)$options;
1598 $options['LIMIT'] = 1;
1599 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1601 if ( $res === false ) {
1605 if ( !$this->numRows( $res ) ) {
1609 $obj = $this->fetchObject( $res );
1614 public function estimateRowCount(
1615 $table, $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(
1624 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1626 $row = $res ?
$this->fetchRow( $res ) : [];
1628 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1631 public function selectRowCount(
1632 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1634 $conds = $this->normalizeConditions( $conds, $fname );
1635 $column = $this->extractSingleFieldFromList( $var );
1636 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1637 $conds[] = "$column IS NOT NULL";
1640 $res = $this->select(
1642 'tmp_count' => $this->buildSelectSubquery(
1651 [ 'rowcount' => 'COUNT(*)' ],
1655 $row = $res ?
$this->fetchRow( $res ) : [];
1657 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1661 * @param array|string $conds
1662 * @param string $fname
1665 final protected function normalizeConditions( $conds, $fname ) {
1666 if ( $conds === null ||
$conds === false ) {
1667 $this->queryLogger
->warning(
1671 . ' with incorrect parameters: $conds must be a string or an array'
1676 if ( !is_array( $conds ) ) {
1677 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1684 * @param array|string $var Field parameter in the style of select()
1685 * @return string|null Column name or null; ignores aliases
1686 * @throws DBUnexpectedError Errors out if multiple columns are given
1688 final protected function extractSingleFieldFromList( $var ) {
1689 if ( is_array( $var ) ) {
1692 } elseif ( count( $var ) == 1 ) {
1693 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1695 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1705 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1706 * It's only slightly flawed. Don't use for anything important.
1708 * @param string $sql A SQL Query
1712 protected static function generalizeSQL( $sql ) {
1713 # This does the same as the regexp below would do, but in such a way
1714 # as to avoid crashing php on some large strings.
1715 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1717 $sql = str_replace( "\\\\", '', $sql );
1718 $sql = str_replace( "\\'", '', $sql );
1719 $sql = str_replace( "\\\"", '', $sql );
1720 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1721 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1723 # All newlines, tabs, etc replaced by single space
1724 $sql = preg_replace( '/\s+/', ' ', $sql );
1727 # except the ones surrounded by characters, e.g. l10n
1728 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1729 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1734 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1735 $info = $this->fieldInfo( $table, $field );
1740 public function indexExists( $table, $index, $fname = __METHOD__
) {
1741 if ( !$this->tableExists( $table ) ) {
1745 $info = $this->indexInfo( $table, $index, $fname );
1746 if ( is_null( $info ) ) {
1749 return $info !== false;
1753 public function tableExists( $table, $fname = __METHOD__
) {
1754 $tableRaw = $this->tableName( $table, 'raw' );
1755 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1756 return true; // already known to exist
1759 $table = $this->tableName( $table );
1760 $ignoreErrors = true;
1761 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1766 public function indexUnique( $table, $index ) {
1767 $indexInfo = $this->indexInfo( $table, $index );
1769 if ( !$indexInfo ) {
1773 return !$indexInfo[0]->Non_unique
;
1777 * Helper for Database::insert().
1779 * @param array $options
1782 protected function makeInsertOptions( $options ) {
1783 return implode( ' ', $options );
1786 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1787 # No rows to insert, easy just return now
1788 if ( !count( $a ) ) {
1792 $table = $this->tableName( $table );
1794 if ( !is_array( $options ) ) {
1795 $options = [ $options ];
1799 if ( isset( $options['fileHandle'] ) ) {
1800 $fh = $options['fileHandle'];
1802 $options = $this->makeInsertOptions( $options );
1804 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1806 $keys = array_keys( $a[0] );
1809 $keys = array_keys( $a );
1812 $sql = 'INSERT ' . $options .
1813 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1817 foreach ( $a as $row ) {
1823 $sql .= '(' . $this->makeList( $row ) . ')';
1826 $sql .= '(' . $this->makeList( $a ) . ')';
1829 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1831 } elseif ( $fh !== null ) {
1835 return (bool)$this->query( $sql, $fname );
1839 * Make UPDATE options array for Database::makeUpdateOptions
1841 * @param array $options
1844 protected function makeUpdateOptionsArray( $options ) {
1845 if ( !is_array( $options ) ) {
1846 $options = [ $options ];
1851 if ( in_array( 'IGNORE', $options ) ) {
1859 * Make UPDATE options for the Database::update function
1861 * @param array $options The options passed to Database::update
1864 protected function makeUpdateOptions( $options ) {
1865 $opts = $this->makeUpdateOptionsArray( $options );
1867 return implode( ' ', $opts );
1870 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1871 $table = $this->tableName( $table );
1872 $opts = $this->makeUpdateOptions( $options );
1873 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1875 if ( $conds !== [] && $conds !== '*' ) {
1876 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1879 return (bool)$this->query( $sql, $fname );
1882 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1883 if ( !is_array( $a ) ) {
1884 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1890 foreach ( $a as $field => $value ) {
1892 if ( $mode == self
::LIST_AND
) {
1894 } elseif ( $mode == self
::LIST_OR
) {
1903 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1904 $list .= "($value)";
1905 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1908 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1910 // Remove null from array to be handled separately if found
1911 $includeNull = false;
1912 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1913 $includeNull = true;
1914 unset( $value[$nullKey] );
1916 if ( count( $value ) == 0 && !$includeNull ) {
1917 throw new InvalidArgumentException(
1918 __METHOD__
. ": empty input for field $field" );
1919 } elseif ( count( $value ) == 0 ) {
1920 // only check if $field is null
1921 $list .= "$field IS NULL";
1923 // IN clause contains at least one valid element
1924 if ( $includeNull ) {
1925 // Group subconditions to ensure correct precedence
1928 if ( count( $value ) == 1 ) {
1929 // Special-case single values, as IN isn't terribly efficient
1930 // Don't necessarily assume the single key is 0; we don't
1931 // enforce linear numeric ordering on other arrays here.
1932 $value = array_values( $value )[0];
1933 $list .= $field . " = " . $this->addQuotes( $value );
1935 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1937 // if null present in array, append IS NULL
1938 if ( $includeNull ) {
1939 $list .= " OR $field IS NULL)";
1942 } elseif ( $value === null ) {
1943 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1944 $list .= "$field IS ";
1945 } elseif ( $mode == self
::LIST_SET
) {
1946 $list .= "$field = ";
1951 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1953 $list .= "$field = ";
1955 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1962 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1965 foreach ( $data as $base => $sub ) {
1966 if ( count( $sub ) ) {
1967 $conds[] = $this->makeList(
1968 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1974 return $this->makeList( $conds, self
::LIST_OR
);
1976 // Nothing to search for...
1981 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1985 public function bitNot( $field ) {
1989 public function bitAnd( $fieldLeft, $fieldRight ) {
1990 return "($fieldLeft & $fieldRight)";
1993 public function bitOr( $fieldLeft, $fieldRight ) {
1994 return "($fieldLeft | $fieldRight)";
1997 public function buildConcat( $stringList ) {
1998 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2001 public function buildGroupConcatField(
2002 $delim, $table, $field, $conds = '', $join_conds = []
2004 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2006 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2009 public function buildSubstring( $input, $startPosition, $length = null ) {
2010 $this->assertBuildSubstringParams( $startPosition, $length );
2011 $functionBody = "$input FROM $startPosition";
2012 if ( $length !== null ) {
2013 $functionBody .= " FOR $length";
2015 return 'SUBSTRING(' . $functionBody . ')';
2019 * Check type and bounds for parameters to self::buildSubstring()
2021 * All supported databases have substring functions that behave the same for
2022 * positive $startPosition and non-negative $length, but behaviors differ when
2023 * given 0 or negative $startPosition or negative $length. The simplest
2024 * solution to that is to just forbid those values.
2026 * @param int $startPosition
2027 * @param int|null $length
2030 protected function assertBuildSubstringParams( $startPosition, $length ) {
2031 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2032 throw new InvalidArgumentException(
2033 '$startPosition must be a positive integer'
2036 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2037 throw new InvalidArgumentException(
2038 '$length must be null or an integer greater than or equal to 0'
2043 public function buildStringCast( $field ) {
2047 public function buildIntegerCast( $field ) {
2048 return 'CAST( ' . $field . ' AS INTEGER )';
2051 public function buildSelectSubquery(
2052 $table, $vars, $conds = '', $fname = __METHOD__
,
2053 $options = [], $join_conds = []
2055 return new Subquery(
2056 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2060 public function databasesAreIndependent() {
2064 public function selectDB( $db ) {
2065 # Stub. Shouldn't cause serious problems if it's not overridden, but
2066 # if your database engine supports a concept similar to MySQL's
2067 # databases you may as well.
2068 $this->dbName
= $db;
2073 public function getDBname() {
2074 return $this->dbName
;
2077 public function getServer() {
2078 return $this->server
;
2081 public function tableName( $name, $format = 'quoted' ) {
2082 if ( $name instanceof Subquery
) {
2083 throw new DBUnexpectedError(
2085 __METHOD__
. ': got Subquery instance when expecting a string.'
2089 # Skip the entire process when we have a string quoted on both ends.
2090 # Note that we check the end so that we will still quote any use of
2091 # use of `database`.table. But won't break things if someone wants
2092 # to query a database table with a dot in the name.
2093 if ( $this->isQuotedIdentifier( $name ) ) {
2097 # Lets test for any bits of text that should never show up in a table
2098 # name. Basically anything like JOIN or ON which are actually part of
2099 # SQL queries, but may end up inside of the table value to combine
2100 # sql. Such as how the API is doing.
2101 # Note that we use a whitespace test rather than a \b test to avoid
2102 # any remote case where a word like on may be inside of a table name
2103 # surrounded by symbols which may be considered word breaks.
2104 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2105 $this->queryLogger
->warning(
2106 __METHOD__
. ": use of subqueries is not supported this way.",
2107 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2113 # Split database and table into proper variables.
2114 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2116 # Quote $table and apply the prefix if not quoted.
2117 # $tableName might be empty if this is called from Database::replaceVars()
2118 $tableName = "{$prefix}{$table}";
2119 if ( $format === 'quoted'
2120 && !$this->isQuotedIdentifier( $tableName )
2121 && $tableName !== ''
2123 $tableName = $this->addIdentifierQuotes( $tableName );
2126 # Quote $schema and $database and merge them with the table name if needed
2127 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2128 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2134 * Get the table components needed for a query given the currently selected database
2136 * @param string $name Table name in the form of db.schema.table, db.table, or table
2137 * @return array (DB name or "" for default, schema name, table prefix, table name)
2139 protected function qualifiedTableComponents( $name ) {
2140 # We reverse the explode so that database.table and table both output the correct table.
2141 $dbDetails = explode( '.', $name, 3 );
2142 if ( count( $dbDetails ) == 3 ) {
2143 list( $database, $schema, $table ) = $dbDetails;
2144 # We don't want any prefix added in this case
2146 } elseif ( count( $dbDetails ) == 2 ) {
2147 list( $database, $table ) = $dbDetails;
2148 # We don't want any prefix added in this case
2150 # In dbs that support it, $database may actually be the schema
2151 # but that doesn't affect any of the functionality here
2154 list( $table ) = $dbDetails;
2155 if ( isset( $this->tableAliases
[$table] ) ) {
2156 $database = $this->tableAliases
[$table]['dbname'];
2157 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2158 ?
$this->tableAliases
[$table]['schema']
2160 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2161 ?
$this->tableAliases
[$table]['prefix']
2162 : $this->tablePrefix
;
2165 $schema = $this->schema
; # Default schema
2166 $prefix = $this->tablePrefix
; # Default prefix
2170 return [ $database, $schema, $prefix, $table ];
2174 * @param string|null $namespace Database or schema
2175 * @param string $relation Name of table, view, sequence, etc...
2176 * @param string $format One of (raw, quoted)
2177 * @return string Relation name with quoted and merged $namespace as needed
2179 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2180 if ( strlen( $namespace ) ) {
2181 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2182 $namespace = $this->addIdentifierQuotes( $namespace );
2184 $relation = $namespace . '.' . $relation;
2190 public function tableNames() {
2191 $inArray = func_get_args();
2194 foreach ( $inArray as $name ) {
2195 $retVal[$name] = $this->tableName( $name );
2201 public function tableNamesN() {
2202 $inArray = func_get_args();
2205 foreach ( $inArray as $name ) {
2206 $retVal[] = $this->tableName( $name );
2213 * Get an aliased table name
2215 * This returns strings like "tableName AS newTableName" for aliased tables
2216 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2218 * @see Database::tableName()
2219 * @param string|Subquery $table Table name or object with a 'sql' field
2220 * @param string|bool $alias Table alias (optional)
2221 * @return string SQL name for aliased table. Will not alias a table to its own name
2223 protected function tableNameWithAlias( $table, $alias = false ) {
2224 if ( is_string( $table ) ) {
2225 $quotedTable = $this->tableName( $table );
2226 } elseif ( $table instanceof Subquery
) {
2227 $quotedTable = (string)$table;
2229 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2232 if ( !strlen( $alias ) ||
$alias === $table ) {
2233 if ( $table instanceof Subquery
) {
2234 throw new InvalidArgumentException( "Subquery table missing alias." );
2237 return $quotedTable;
2239 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2244 * Gets an array of aliased table names
2246 * @param array $tables [ [alias] => table ]
2247 * @return string[] See tableNameWithAlias()
2249 protected function tableNamesWithAlias( $tables ) {
2251 foreach ( $tables as $alias => $table ) {
2252 if ( is_numeric( $alias ) ) {
2255 $retval[] = $this->tableNameWithAlias( $table, $alias );
2262 * Get an aliased field name
2263 * e.g. fieldName AS newFieldName
2265 * @param string $name Field name
2266 * @param string|bool $alias Alias (optional)
2267 * @return string SQL name for aliased field. Will not alias a field to its own name
2269 protected function fieldNameWithAlias( $name, $alias = false ) {
2270 if ( !$alias ||
(string)$alias === (string)$name ) {
2273 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2278 * Gets an array of aliased field names
2280 * @param array $fields [ [alias] => field ]
2281 * @return string[] See fieldNameWithAlias()
2283 protected function fieldNamesWithAlias( $fields ) {
2285 foreach ( $fields as $alias => $field ) {
2286 if ( is_numeric( $alias ) ) {
2289 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2296 * Get the aliased table name clause for a FROM clause
2297 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2299 * @param array $tables ( [alias] => table )
2300 * @param array $use_index Same as for select()
2301 * @param array $ignore_index Same as for select()
2302 * @param array $join_conds Same as for select()
2305 protected function tableNamesWithIndexClauseOrJOIN(
2306 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2310 $use_index = (array)$use_index;
2311 $ignore_index = (array)$ignore_index;
2312 $join_conds = (array)$join_conds;
2314 foreach ( $tables as $alias => $table ) {
2315 if ( !is_string( $alias ) ) {
2316 // No alias? Set it equal to the table name
2320 if ( is_array( $table ) ) {
2321 // A parenthesized group
2322 if ( count( $table ) > 1 ) {
2323 $joinedTable = '(' .
2324 $this->tableNamesWithIndexClauseOrJOIN(
2325 $table, $use_index, $ignore_index, $join_conds ) . ')';
2328 $innerTable = reset( $table );
2329 $innerAlias = key( $table );
2330 $joinedTable = $this->tableNameWithAlias(
2332 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2336 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2339 // Is there a JOIN clause for this table?
2340 if ( isset( $join_conds[$alias] ) ) {
2341 list( $joinType, $conds ) = $join_conds[$alias];
2342 $tableClause = $joinType;
2343 $tableClause .= ' ' . $joinedTable;
2344 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2345 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2347 $tableClause .= ' ' . $use;
2350 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2351 $ignore = $this->ignoreIndexClause(
2352 implode( ',', (array)$ignore_index[$alias] ) );
2353 if ( $ignore != '' ) {
2354 $tableClause .= ' ' . $ignore;
2357 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2359 $tableClause .= ' ON (' . $on . ')';
2362 $retJOIN[] = $tableClause;
2363 } elseif ( isset( $use_index[$alias] ) ) {
2364 // Is there an INDEX clause for this table?
2365 $tableClause = $joinedTable;
2366 $tableClause .= ' ' . $this->useIndexClause(
2367 implode( ',', (array)$use_index[$alias] )
2370 $ret[] = $tableClause;
2371 } elseif ( isset( $ignore_index[$alias] ) ) {
2372 // Is there an INDEX clause for this table?
2373 $tableClause = $joinedTable;
2374 $tableClause .= ' ' . $this->ignoreIndexClause(
2375 implode( ',', (array)$ignore_index[$alias] )
2378 $ret[] = $tableClause;
2380 $tableClause = $joinedTable;
2382 $ret[] = $tableClause;
2386 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2387 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2388 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2390 // Compile our final table clause
2391 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2395 * Allows for index remapping in queries where this is not consistent across DBMS
2397 * @param string $index
2400 protected function indexName( $index ) {
2401 return isset( $this->indexAliases
[$index] )
2402 ?
$this->indexAliases
[$index]
2406 public function addQuotes( $s ) {
2407 if ( $s instanceof Blob
) {
2410 if ( $s === null ) {
2412 } elseif ( is_bool( $s ) ) {
2415 # This will also quote numeric values. This should be harmless,
2416 # and protects against weird problems that occur when they really
2417 # _are_ strings such as article titles and string->number->string
2418 # conversion is not 1:1.
2419 return "'" . $this->strencode( $s ) . "'";
2424 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2425 * MySQL uses `backticks` while basically everything else uses double quotes.
2426 * Since MySQL is the odd one out here the double quotes are our generic
2427 * and we implement backticks in DatabaseMysqlBase.
2432 public function addIdentifierQuotes( $s ) {
2433 return '"' . str_replace( '"', '""', $s ) . '"';
2437 * Returns if the given identifier looks quoted or not according to
2438 * the database convention for quoting identifiers .
2440 * @note Do not use this to determine if untrusted input is safe.
2441 * A malicious user can trick this function.
2442 * @param string $name
2445 public function isQuotedIdentifier( $name ) {
2446 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2451 * @param string $escapeChar
2454 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2455 return str_replace( [ $escapeChar, '%', '_' ],
2456 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2460 public function buildLike() {
2461 $params = func_get_args();
2463 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2464 $params = $params[0];
2469 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2470 // may escape backslashes, creating problems of double escaping. The `
2471 // character has good cross-DBMS compatibility, avoiding special operators
2472 // in MS SQL like ^ and %
2475 foreach ( $params as $value ) {
2476 if ( $value instanceof LikeMatch
) {
2477 $s .= $value->toString();
2479 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2484 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2487 public function anyChar() {
2488 return new LikeMatch( '_' );
2491 public function anyString() {
2492 return new LikeMatch( '%' );
2495 public function nextSequenceValue( $seqName ) {
2500 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2501 * is only needed because a) MySQL must be as efficient as possible due to
2502 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2503 * which index to pick. Anyway, other databases might have different
2504 * indexes on a given table. So don't bother overriding this unless you're
2506 * @param string $index
2509 public function useIndexClause( $index ) {
2514 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2515 * is only needed because a) MySQL must be as efficient as possible due to
2516 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2517 * which index to pick. Anyway, other databases might have different
2518 * indexes on a given table. So don't bother overriding this unless you're
2520 * @param string $index
2523 public function ignoreIndexClause( $index ) {
2527 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2528 if ( count( $rows ) == 0 ) {
2533 if ( !is_array( reset( $rows ) ) ) {
2538 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2539 $affectedRowCount = 0;
2540 foreach ( $rows as $row ) {
2541 // Delete rows which collide with this one
2542 $indexWhereClauses = [];
2543 foreach ( $uniqueIndexes as $index ) {
2544 $indexColumns = (array)$index;
2545 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2546 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2547 throw new DBUnexpectedError(
2549 'New record does not provide all values for unique key (' .
2550 implode( ', ', $indexColumns ) . ')'
2552 } elseif ( in_array( null, $indexRowValues, true ) ) {
2553 throw new DBUnexpectedError(
2555 'New record has a null value for unique key (' .
2556 implode( ', ', $indexColumns ) . ')'
2559 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2562 if ( $indexWhereClauses ) {
2563 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2564 $affectedRowCount +
= $this->affectedRows();
2567 // Now insert the row
2568 $this->insert( $table, $row, $fname );
2569 $affectedRowCount +
= $this->affectedRows();
2571 $this->endAtomic( $fname );
2572 $this->affectedRowCount
= $affectedRowCount;
2573 } catch ( Exception
$e ) {
2574 $this->cancelAtomic( $fname );
2580 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2583 * @param string $table Table name
2584 * @param array|string $rows Row(s) to insert
2585 * @param string $fname Caller function name
2587 * @return ResultWrapper
2589 protected function nativeReplace( $table, $rows, $fname ) {
2590 $table = $this->tableName( $table );
2593 if ( !is_array( reset( $rows ) ) ) {
2597 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2600 foreach ( $rows as $row ) {
2607 $sql .= '(' . $this->makeList( $row ) . ')';
2610 return $this->query( $sql, $fname );
2613 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2616 if ( !count( $rows ) ) {
2617 return true; // nothing to do
2620 if ( !is_array( reset( $rows ) ) ) {
2624 if ( count( $uniqueIndexes ) ) {
2625 $clauses = []; // list WHERE clauses that each identify a single row
2626 foreach ( $rows as $row ) {
2627 foreach ( $uniqueIndexes as $index ) {
2628 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2629 $rowKey = []; // unique key to this row
2630 foreach ( $index as $column ) {
2631 $rowKey[$column] = $row[$column];
2633 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2636 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2641 $affectedRowCount = 0;
2643 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2644 # Update any existing conflicting row(s)
2645 if ( $where !== false ) {
2646 $ok = $this->update( $table, $set, $where, $fname );
2647 $affectedRowCount +
= $this->affectedRows();
2651 # Now insert any non-conflicting row(s)
2652 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2653 $affectedRowCount +
= $this->affectedRows();
2654 $this->endAtomic( $fname );
2655 $this->affectedRowCount
= $affectedRowCount;
2656 } catch ( Exception
$e ) {
2657 $this->cancelAtomic( $fname );
2664 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2668 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2671 $delTable = $this->tableName( $delTable );
2672 $joinTable = $this->tableName( $joinTable );
2673 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2674 if ( $conds != '*' ) {
2675 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2679 $this->query( $sql, $fname );
2682 public function textFieldSize( $table, $field ) {
2683 $table = $this->tableName( $table );
2684 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2685 $res = $this->query( $sql, __METHOD__
);
2686 $row = $this->fetchObject( $res );
2690 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2699 public function delete( $table, $conds, $fname = __METHOD__
) {
2701 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2704 $table = $this->tableName( $table );
2705 $sql = "DELETE FROM $table";
2707 if ( $conds != '*' ) {
2708 if ( is_array( $conds ) ) {
2709 $conds = $this->makeList( $conds, self
::LIST_AND
);
2711 $sql .= ' WHERE ' . $conds;
2714 return $this->query( $sql, $fname );
2717 final public function insertSelect(
2718 $destTable, $srcTable, $varMap, $conds,
2719 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2721 static $hints = [ 'NO_AUTO_COLUMNS' ];
2723 $insertOptions = (array)$insertOptions;
2724 $selectOptions = (array)$selectOptions;
2726 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2727 // For massive migrations with downtime, we don't want to select everything
2728 // into memory and OOM, so do all this native on the server side if possible.
2729 return $this->nativeInsertSelect(
2735 array_diff( $insertOptions, $hints ),
2741 return $this->nonNativeInsertSelect(
2747 array_diff( $insertOptions, $hints ),
2754 * @param array $insertOptions INSERT options
2755 * @param array $selectOptions SELECT options
2756 * @return bool Whether an INSERT SELECT with these options will be replication safe
2759 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2764 * Implementation of insertSelect() based on select() and insert()
2766 * @see IDatabase::insertSelect()
2768 * @param string $destTable
2769 * @param string|array $srcTable
2770 * @param array $varMap
2771 * @param array $conds
2772 * @param string $fname
2773 * @param array $insertOptions
2774 * @param array $selectOptions
2775 * @param array $selectJoinConds
2778 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2779 $fname = __METHOD__
,
2780 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2782 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2783 // on only the master (without needing row-based-replication). It also makes it easy to
2784 // know how big the INSERT is going to be.
2786 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2787 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2789 $selectOptions[] = 'FOR UPDATE';
2790 $res = $this->select(
2791 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2798 $affectedRowCount = 0;
2799 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2802 foreach ( $res as $row ) {
2803 $rows[] = (array)$row;
2805 // Avoid inserts that are too huge
2806 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2807 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2811 $affectedRowCount +
= $this->affectedRows();
2815 if ( $rows && $ok ) {
2816 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2818 $affectedRowCount +
= $this->affectedRows();
2822 $this->endAtomic( $fname );
2823 $this->affectedRowCount
= $affectedRowCount;
2825 $this->cancelAtomic( $fname );
2828 } catch ( Exception
$e ) {
2829 $this->cancelAtomic( $fname );
2835 * Native server-side implementation of insertSelect() for situations where
2836 * we don't want to select everything into memory
2838 * @see IDatabase::insertSelect()
2839 * @param string $destTable
2840 * @param string|array $srcTable
2841 * @param array $varMap
2842 * @param array $conds
2843 * @param string $fname
2844 * @param array $insertOptions
2845 * @param array $selectOptions
2846 * @param array $selectJoinConds
2849 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2850 $fname = __METHOD__
,
2851 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2853 $destTable = $this->tableName( $destTable );
2855 if ( !is_array( $insertOptions ) ) {
2856 $insertOptions = [ $insertOptions ];
2859 $insertOptions = $this->makeInsertOptions( $insertOptions );
2861 $selectSql = $this->selectSQLText(
2863 array_values( $varMap ),
2870 $sql = "INSERT $insertOptions" .
2871 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2874 return $this->query( $sql, $fname );
2878 * Construct a LIMIT query with optional offset. This is used for query
2879 * pages. The SQL should be adjusted so that only the first $limit rows
2880 * are returned. If $offset is provided as well, then the first $offset
2881 * rows should be discarded, and the next $limit rows should be returned.
2882 * If the result of the query is not ordered, then the rows to be returned
2883 * are theoretically arbitrary.
2885 * $sql is expected to be a SELECT, if that makes a difference.
2887 * The version provided by default works in MySQL and SQLite. It will very
2888 * likely need to be overridden for most other DBMSes.
2890 * @param string $sql SQL query we will append the limit too
2891 * @param int $limit The SQL limit
2892 * @param int|bool $offset The SQL offset (default false)
2893 * @throws DBUnexpectedError
2896 public function limitResult( $sql, $limit, $offset = false ) {
2897 if ( !is_numeric( $limit ) ) {
2898 throw new DBUnexpectedError( $this,
2899 "Invalid non-numeric limit passed to limitResult()\n" );
2902 return "$sql LIMIT "
2903 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2907 public function unionSupportsOrderAndLimit() {
2908 return true; // True for almost every DB supported
2911 public function unionQueries( $sqls, $all ) {
2912 $glue = $all ?
') UNION ALL (' : ') UNION (';
2914 return '(' . implode( $glue, $sqls ) . ')';
2917 public function unionConditionPermutations(
2918 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2919 $options = [], $join_conds = []
2921 // First, build the Cartesian product of $permute_conds
2923 foreach ( $permute_conds as $field => $values ) {
2925 // Skip empty $values
2928 $values = array_unique( $values ); // For sanity
2930 foreach ( $conds as $cond ) {
2931 foreach ( $values as $value ) {
2932 $cond[$field] = $value;
2933 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2939 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2941 // If there's just one condition and no subordering, hand off to
2942 // selectSQLText directly.
2943 if ( count( $conds ) === 1 &&
2944 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2946 return $this->selectSQLText(
2947 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2951 // Otherwise, we need to pull out the order and limit to apply after
2952 // the union. Then build the SQL queries for each set of conditions in
2953 // $conds. Then union them together (using UNION ALL, because the
2954 // product *should* already be distinct).
2955 $orderBy = $this->makeOrderBy( $options );
2956 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2957 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2958 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2959 if ( !$this->unionSupportsOrderAndLimit() ) {
2960 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2962 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2963 $options['ORDER BY'] = $options['INNER ORDER BY'];
2965 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2966 // We need to increase the limit by the offset rather than
2967 // using the offset directly, otherwise it'll skip incorrectly
2968 // in the subqueries.
2969 $options['LIMIT'] = $limit +
$offset;
2970 unset( $options['OFFSET'] );
2975 foreach ( $conds as $cond ) {
2976 $sqls[] = $this->selectSQLText(
2977 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2980 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2981 if ( $limit !== null ) {
2982 $sql = $this->limitResult( $sql, $limit, $offset );
2988 public function conditional( $cond, $trueVal, $falseVal ) {
2989 if ( is_array( $cond ) ) {
2990 $cond = $this->makeList( $cond, self
::LIST_AND
);
2993 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2996 public function strreplace( $orig, $old, $new ) {
2997 return "REPLACE({$orig}, {$old}, {$new})";
3000 public function getServerUptime() {
3004 public function wasDeadlock() {
3008 public function wasLockTimeout() {
3012 public function wasConnectionLoss() {
3013 return $this->wasConnectionError( $this->lastErrno() );
3016 public function wasReadOnlyError() {
3020 public function wasErrorReissuable() {
3022 $this->wasDeadlock() ||
3023 $this->wasLockTimeout() ||
3024 $this->wasConnectionLoss()
3029 * Do not use this method outside of Database/DBError classes
3031 * @param int|string $errno
3032 * @return bool Whether the given query error was a connection drop
3034 public function wasConnectionError( $errno ) {
3038 public function deadlockLoop() {
3039 $args = func_get_args();
3040 $function = array_shift( $args );
3041 $tries = self
::DEADLOCK_TRIES
;
3043 $this->begin( __METHOD__
);
3046 /** @var Exception $e */
3050 $retVal = call_user_func_array( $function, $args );
3052 } catch ( DBQueryError
$e ) {
3053 if ( $this->wasDeadlock() ) {
3054 // Retry after a randomized delay
3055 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3057 // Throw the error back up
3061 } while ( --$tries > 0 );
3063 if ( $tries <= 0 ) {
3064 // Too many deadlocks; give up
3065 $this->rollback( __METHOD__
);
3068 $this->commit( __METHOD__
);
3074 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3075 # Real waits are implemented in the subclass.
3079 public function getReplicaPos() {
3084 public function getMasterPos() {
3089 public function serverIsReadOnly() {
3093 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3094 if ( !$this->trxLevel
) {
3095 throw new DBUnexpectedError( $this, "No transaction is active." );
3097 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3100 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3101 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3102 if ( !$this->trxLevel
) {
3103 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3107 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3108 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
3109 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3110 // an implicit commit of all peer databases. This is true even if a transaction has
3111 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3112 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3114 // No transaction is active nor will start implicitly, so make one for this callback
3115 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3117 call_user_func( $callback );
3118 $this->endAtomic( __METHOD__
);
3119 } catch ( Exception
$e ) {
3120 $this->cancelAtomic( __METHOD__
);
3126 final public function setTransactionListener( $name, callable
$callback = null ) {
3128 $this->trxRecurringCallbacks
[$name] = $callback;
3130 unset( $this->trxRecurringCallbacks
[$name] );
3135 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3137 * This method should not be used outside of Database/LoadBalancer
3139 * @param bool $suppress
3142 final public function setTrxEndCallbackSuppression( $suppress ) {
3143 $this->trxEndCallbacksSuppressed
= $suppress;
3147 * Actually run and consume any "on transaction idle/resolution" callbacks.
3149 * This method should not be used outside of Database/LoadBalancer
3151 * @param int $trigger IDatabase::TRIGGER_* constant
3155 public function runOnTransactionIdleCallbacks( $trigger ) {
3156 if ( $this->trxEndCallbacksSuppressed
) {
3160 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3161 /** @var Exception $e */
3162 $e = null; // first exception
3163 do { // callbacks may add callbacks :)
3164 $callbacks = array_merge(
3165 $this->trxIdleCallbacks
,
3166 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3168 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3169 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3170 foreach ( $callbacks as $callback ) {
3172 list( $phpCallback ) = $callback;
3173 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3174 call_user_func_array( $phpCallback, [ $trigger ] );
3176 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3178 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3180 } catch ( Exception
$ex ) {
3181 call_user_func( $this->errorLogger
, $ex );
3183 // Some callbacks may use startAtomic/endAtomic, so make sure
3184 // their transactions are ended so other callbacks don't fail
3185 if ( $this->trxLevel() ) {
3186 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3190 } while ( count( $this->trxIdleCallbacks
) );
3192 if ( $e instanceof Exception
) {
3193 throw $e; // re-throw any first exception
3198 * Actually run and consume any "on transaction pre-commit" callbacks.
3200 * This method should not be used outside of Database/LoadBalancer
3205 public function runOnTransactionPreCommitCallbacks() {
3206 $e = null; // first exception
3207 do { // callbacks may add callbacks :)
3208 $callbacks = $this->trxPreCommitCallbacks
;
3209 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3210 foreach ( $callbacks as $callback ) {
3212 list( $phpCallback ) = $callback;
3213 call_user_func( $phpCallback );
3214 } catch ( Exception
$ex ) {
3215 call_user_func( $this->errorLogger
, $ex );
3219 } while ( count( $this->trxPreCommitCallbacks
) );
3221 if ( $e instanceof Exception
) {
3222 throw $e; // re-throw any first exception
3227 * Actually run any "transaction listener" callbacks.
3229 * This method should not be used outside of Database/LoadBalancer
3231 * @param int $trigger IDatabase::TRIGGER_* constant
3235 public function runTransactionListenerCallbacks( $trigger ) {
3236 if ( $this->trxEndCallbacksSuppressed
) {
3240 /** @var Exception $e */
3241 $e = null; // first exception
3243 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3245 $phpCallback( $trigger, $this );
3246 } catch ( Exception
$ex ) {
3247 call_user_func( $this->errorLogger
, $ex );
3252 if ( $e instanceof Exception
) {
3253 throw $e; // re-throw any first exception
3258 * Create a savepoint
3260 * This is used internally to implement atomic sections. It should not be
3264 * @param string $identifier Identifier for the savepoint
3265 * @param string $fname Calling function name
3267 protected function doSavepoint( $identifier, $fname ) {
3268 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3272 * Release a savepoint
3274 * This is used internally to implement atomic sections. It should not be
3278 * @param string $identifier Identifier for the savepoint
3279 * @param string $fname Calling function name
3281 protected function doReleaseSavepoint( $identifier, $fname ) {
3282 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3286 * Rollback to a savepoint
3288 * This is used internally to implement atomic sections. It should not be
3292 * @param string $identifier Identifier for the savepoint
3293 * @param string $fname Calling function name
3295 protected function doRollbackToSavepoint( $identifier, $fname ) {
3296 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3299 final public function startAtomic(
3300 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3302 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3303 if ( !$this->trxLevel
) {
3304 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3305 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3306 // in all changes being in one transaction to keep requests transactional.
3307 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3308 $this->trxAutomaticAtomic
= true;
3310 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3311 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3312 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3313 $this->queryLogger
->warning(
3314 'There have been an excessively large number of atomic sections in a transaction'
3315 . " started by $this->trxFname, reusing IDs (at $fname)",
3316 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3318 $this->trxAtomicCounter
= 0;
3319 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3321 $this->doSavepoint( $savepointId, $fname );
3324 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3327 final public function endAtomic( $fname = __METHOD__
) {
3328 if ( !$this->trxLevel
) {
3329 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3332 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3333 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3334 if ( $savedFname !== $fname ) {
3335 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3338 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3339 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3340 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3341 $this->doReleaseSavepoint( $savepointId, $fname );
3345 final public function cancelAtomic( $fname = __METHOD__
) {
3346 if ( !$this->trxLevel
) {
3347 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3350 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3351 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3352 if ( $savedFname !== $fname ) {
3353 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3355 if ( !$savepointId ) {
3356 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3359 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3360 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3361 } elseif ( $savepointId !== 'n/a' ) {
3362 $this->doRollbackToSavepoint( $savepointId, $fname );
3365 $this->affectedRowCount
= 0; // for the sake of consistency
3368 final public function doAtomicSection( $fname, callable
$callback ) {
3369 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3371 $res = call_user_func_array( $callback, [ $this, $fname ] );
3372 } catch ( Exception
$e ) {
3373 $this->cancelAtomic( $fname );
3376 $this->endAtomic( $fname );
3381 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3382 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3383 if ( $this->trxLevel
) {
3384 if ( $this->trxAtomicLevels
) {
3385 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3386 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3388 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3389 throw new DBUnexpectedError( $this, $msg );
3390 } elseif ( !$this->trxAutomatic
) {
3391 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3392 throw new DBUnexpectedError( $this, $msg );
3394 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3395 throw new DBUnexpectedError( $this, $msg );
3397 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3398 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3399 throw new DBUnexpectedError( $this, $msg );
3402 // Avoid fatals if close() was called
3403 $this->assertOpen();
3405 $this->doBegin( $fname );
3406 $this->trxAtomicCounter
= 0;
3407 $this->trxTimestamp
= microtime( true );
3408 $this->trxFname
= $fname;
3409 $this->trxDoneWrites
= false;
3410 $this->trxAutomaticAtomic
= false;
3411 $this->trxAtomicLevels
= [];
3412 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3413 $this->trxWriteDuration
= 0.0;
3414 $this->trxWriteQueryCount
= 0;
3415 $this->trxWriteAffectedRows
= 0;
3416 $this->trxWriteAdjDuration
= 0.0;
3417 $this->trxWriteAdjQueryCount
= 0;
3418 $this->trxWriteCallers
= [];
3419 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3420 // Get an estimate of the replica DB lag before then, treating estimate staleness
3421 // as lag itself just to be safe
3422 $status = $this->getApproximateLagStatus();
3423 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3424 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3425 // caller will think its OK to muck around with the transaction just because startAtomic()
3426 // has not yet completed (e.g. setting trxAtomicLevels).
3427 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3431 * Issues the BEGIN command to the database server.
3433 * @see Database::begin()
3434 * @param string $fname
3436 protected function doBegin( $fname ) {
3437 $this->query( 'BEGIN', $fname );
3438 $this->trxLevel
= 1;
3441 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3442 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3443 // There are still atomic sections open. This cannot be ignored
3444 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3445 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3447 throw new DBUnexpectedError(
3449 "$fname: Got COMMIT while atomic sections $levels are still open."
3453 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3454 if ( !$this->trxLevel
) {
3455 return; // nothing to do
3456 } elseif ( !$this->trxAutomatic
) {
3457 throw new DBUnexpectedError(
3459 "$fname: Flushing an explicit transaction, getting out of sync."
3463 if ( !$this->trxLevel
) {
3464 $this->queryLogger
->error(
3465 "$fname: No transaction to commit, something got out of sync." );
3466 return; // nothing to do
3467 } elseif ( $this->trxAutomatic
) {
3468 throw new DBUnexpectedError(
3470 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3475 // Avoid fatals if close() was called
3476 $this->assertOpen();
3478 $this->runOnTransactionPreCommitCallbacks();
3479 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3480 $this->doCommit( $fname );
3481 if ( $this->trxDoneWrites
) {
3482 $this->lastWriteTime
= microtime( true );
3483 $this->trxProfiler
->transactionWritingOut(
3488 $this->trxWriteAffectedRows
3492 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3493 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3497 * Issues the COMMIT command to the database server.
3499 * @see Database::commit()
3500 * @param string $fname
3502 protected function doCommit( $fname ) {
3503 if ( $this->trxLevel
) {
3504 $this->query( 'COMMIT', $fname );
3505 $this->trxLevel
= 0;
3509 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3510 $trxActive = $this->trxLevel
;
3512 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3513 if ( $this->getFlag( self
::DBO_TRX
) ) {
3514 throw new DBUnexpectedError(
3516 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3522 // Avoid fatals if close() was called
3523 $this->assertOpen();
3525 $this->doRollback( $fname );
3526 $this->trxAtomicLevels
= [];
3527 if ( $this->trxDoneWrites
) {
3528 $this->trxProfiler
->transactionWritingOut(
3536 // Clear any commit-dependant callbacks. They might even be present
3537 // only due to transaction rounds, with no SQL transaction being active
3538 $this->trxIdleCallbacks
= [];
3539 $this->trxPreCommitCallbacks
= [];
3543 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3544 } catch ( Exception
$e ) {
3545 // already logged; finish and let LoadBalancer move on during mass-rollback
3548 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3549 } catch ( Exception
$e ) {
3550 // already logged; let LoadBalancer move on during mass-rollback
3553 $this->affectedRowCount
= 0; // for the sake of consistency
3558 * Issues the ROLLBACK command to the database server.
3560 * @see Database::rollback()
3561 * @param string $fname
3563 protected function doRollback( $fname ) {
3564 if ( $this->trxLevel
) {
3565 # Disconnects cause rollback anyway, so ignore those errors
3566 $ignoreErrors = true;
3567 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3568 $this->trxLevel
= 0;
3572 public function flushSnapshot( $fname = __METHOD__
) {
3573 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3574 // This only flushes transactions to clear snapshots, not to write data
3575 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3576 throw new DBUnexpectedError(
3578 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3582 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3585 public function explicitTrxActive() {
3586 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3589 public function duplicateTableStructure(
3590 $oldName, $newName, $temporary = false, $fname = __METHOD__
3592 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3595 public function listTables( $prefix = null, $fname = __METHOD__
) {
3596 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3599 public function listViews( $prefix = null, $fname = __METHOD__
) {
3600 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3603 public function timestamp( $ts = 0 ) {
3604 $t = new ConvertibleTimestamp( $ts );
3605 // Let errors bubble up to avoid putting garbage in the DB
3606 return $t->getTimestamp( TS_MW
);
3609 public function timestampOrNull( $ts = null ) {
3610 if ( is_null( $ts ) ) {
3613 return $this->timestamp( $ts );
3617 public function affectedRows() {
3618 return ( $this->affectedRowCount
=== null )
3619 ?
$this->fetchAffectedRowCount() // default to driver value
3620 : $this->affectedRowCount
;
3624 * @return int Number of retrieved rows according to the driver
3626 abstract protected function fetchAffectedRowCount();
3629 * Take the result from a query, and wrap it in a ResultWrapper if
3630 * necessary. Boolean values are passed through as is, to indicate success
3631 * of write queries or failure.
3633 * Once upon a time, Database::query() returned a bare MySQL result
3634 * resource, and it was necessary to call this function to convert it to
3635 * a wrapper. Nowadays, raw database objects are never exposed to external
3636 * callers, so this is unnecessary in external code.
3638 * @param bool|ResultWrapper|resource|object $result
3639 * @return bool|ResultWrapper
3641 protected function resultObject( $result ) {
3644 } elseif ( $result instanceof ResultWrapper
) {
3646 } elseif ( $result === true ) {
3647 // Successful write query
3650 return new ResultWrapper( $this, $result );
3654 public function ping( &$rtt = null ) {
3655 // Avoid hitting the server if it was hit recently
3656 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3657 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3658 $rtt = $this->rttEstimate
;
3659 return true; // don't care about $rtt
3663 // This will reconnect if possible or return false if not
3664 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3665 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3666 $this->restoreFlags( self
::RESTORE_PRIOR
);
3669 $rtt = $this->rttEstimate
;
3676 * Close any existing (dead) database connection and open a new connection
3678 * @param string $fname
3679 * @return bool True if new connection is opened successfully, false if error
3681 protected function replaceLostConnection( $fname ) {
3682 $this->closeConnection();
3683 $this->opened
= false;
3684 $this->conn
= false;
3686 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3687 $this->lastPing
= microtime( true );
3690 $this->connLogger
->warning(
3691 $fname . ': lost connection to {dbserver}; reconnected',
3693 'dbserver' => $this->getServer(),
3694 'trace' => ( new RuntimeException() )->getTraceAsString()
3697 } catch ( DBConnectionError
$e ) {
3700 $this->connLogger
->error(
3701 $fname . ': lost connection to {dbserver} permanently',
3702 [ 'dbserver' => $this->getServer() ]
3706 $this->handleSessionLoss();
3711 public function getSessionLagStatus() {
3712 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3716 * Get the replica DB lag when the current transaction started
3718 * This is useful when transactions might use snapshot isolation
3719 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3720 * is this lag plus transaction duration. If they don't, it is still
3721 * safe to be pessimistic. This returns null if there is no transaction.
3723 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3726 protected function getTransactionLagStatus() {
3727 return $this->trxLevel
3728 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3733 * Get a replica DB lag estimate for this server
3735 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3738 protected function getApproximateLagStatus() {
3740 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3741 'since' => microtime( true )
3746 * Merge the result of getSessionLagStatus() for several DBs
3747 * using the most pessimistic values to estimate the lag of
3748 * any data derived from them in combination
3750 * This is information is useful for caching modules
3752 * @see WANObjectCache::set()
3753 * @see WANObjectCache::getWithSetCallback()
3755 * @param IDatabase $db1
3756 * @param IDatabase $db2 [optional]
3757 * @return array Map of values:
3758 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3759 * - since: oldest UNIX timestamp of any of the DB lag estimates
3760 * - pending: whether any of the DBs have uncommitted changes
3764 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3765 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3766 foreach ( func_get_args() as $db ) {
3767 /** @var IDatabase $db */
3768 $status = $db->getSessionLagStatus();
3769 if ( $status['lag'] === false ) {
3770 $res['lag'] = false;
3771 } elseif ( $res['lag'] !== false ) {
3772 $res['lag'] = max( $res['lag'], $status['lag'] );
3774 $res['since'] = min( $res['since'], $status['since'] );
3775 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3781 public function getLag() {
3785 public function maxListLen() {
3789 public function encodeBlob( $b ) {
3793 public function decodeBlob( $b ) {
3794 if ( $b instanceof Blob
) {
3800 public function setSessionOptions( array $options ) {
3803 public function sourceFile(
3805 callable
$lineCallback = null,
3806 callable
$resultCallback = null,
3808 callable
$inputCallback = null
3810 Wikimedia\
suppressWarnings();
3811 $fp = fopen( $filename, 'r' );
3812 Wikimedia\restoreWarnings
();
3814 if ( false === $fp ) {
3815 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3819 $fname = __METHOD__
. "( $filename )";
3823 $error = $this->sourceStream(
3824 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3825 } catch ( Exception
$e ) {
3835 public function setSchemaVars( $vars ) {
3836 $this->schemaVars
= $vars;
3839 public function sourceStream(
3841 callable
$lineCallback = null,
3842 callable
$resultCallback = null,
3843 $fname = __METHOD__
,
3844 callable
$inputCallback = null
3846 $delimiterReset = new ScopedCallback(
3847 function ( $delimiter ) {
3848 $this->delimiter
= $delimiter;
3850 [ $this->delimiter
]
3854 while ( !feof( $fp ) ) {
3855 if ( $lineCallback ) {
3856 call_user_func( $lineCallback );
3859 $line = trim( fgets( $fp ) );
3861 if ( $line == '' ) {
3865 if ( '-' == $line[0] && '-' == $line[1] ) {
3873 $done = $this->streamStatementEnd( $cmd, $line );
3877 if ( $done ||
feof( $fp ) ) {
3878 $cmd = $this->replaceVars( $cmd );
3880 if ( $inputCallback ) {
3881 $callbackResult = call_user_func( $inputCallback, $cmd );
3883 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3884 $cmd = $callbackResult;
3889 $res = $this->query( $cmd, $fname );
3891 if ( $resultCallback ) {
3892 call_user_func( $resultCallback, $res, $this );
3895 if ( false === $res ) {
3896 $err = $this->lastError();
3898 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3905 ScopedCallback
::consume( $delimiterReset );
3910 * Called by sourceStream() to check if we've reached a statement end
3912 * @param string &$sql SQL assembled so far
3913 * @param string &$newLine New line about to be added to $sql
3914 * @return bool Whether $newLine contains end of the statement
3916 public function streamStatementEnd( &$sql, &$newLine ) {
3917 if ( $this->delimiter
) {
3919 $newLine = preg_replace(
3920 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3921 if ( $newLine != $prev ) {
3930 * Database independent variable replacement. Replaces a set of variables
3931 * in an SQL statement with their contents as given by $this->getSchemaVars().
3933 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3935 * - '{$var}' should be used for text and is passed through the database's
3937 * - `{$var}` should be used for identifiers (e.g. table and database names).
3938 * It is passed through the database's addIdentifierQuotes method which
3939 * can be overridden if the database uses something other than backticks.
3940 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3941 * database's tableName method.
3942 * - / *i* / passes the name that follows through the database's indexName method.
3943 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3944 * its use should be avoided. In 1.24 and older, string encoding was applied.
3946 * @param string $ins SQL statement to replace variables in
3947 * @return string The new SQL statement with variables replaced
3949 protected function replaceVars( $ins ) {
3950 $vars = $this->getSchemaVars();
3951 return preg_replace_callback(
3953 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3954 \'\{\$ (\w+) }\' | # 3. addQuotes
3955 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3956 /\*\$ (\w+) \*/ # 5. leave unencoded
3958 function ( $m ) use ( $vars ) {
3959 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3960 // check for both nonexistent keys *and* the empty string.
3961 if ( isset( $m[1] ) && $m[1] !== '' ) {
3962 if ( $m[1] === 'i' ) {
3963 return $this->indexName( $m[2] );
3965 return $this->tableName( $m[2] );
3967 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3968 return $this->addQuotes( $vars[$m[3]] );
3969 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3970 return $this->addIdentifierQuotes( $vars[$m[4]] );
3971 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3972 return $vars[$m[5]];
3982 * Get schema variables. If none have been set via setSchemaVars(), then
3983 * use some defaults from the current object.
3987 protected function getSchemaVars() {
3988 if ( $this->schemaVars
) {
3989 return $this->schemaVars
;
3991 return $this->getDefaultSchemaVars();
3996 * Get schema variables to use if none have been set via setSchemaVars().
3998 * Override this in derived classes to provide variables for tables.sql
3999 * and SQL patch files.
4003 protected function getDefaultSchemaVars() {
4007 public function lockIsFree( $lockName, $method ) {
4008 // RDBMs methods for checking named locks may or may not count this thread itself.
4009 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4010 // the behavior choosen by the interface for this method.
4011 return !isset( $this->namedLocksHeld
[$lockName] );
4014 public function lock( $lockName, $method, $timeout = 5 ) {
4015 $this->namedLocksHeld
[$lockName] = 1;
4020 public function unlock( $lockName, $method ) {
4021 unset( $this->namedLocksHeld
[$lockName] );
4026 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4027 if ( $this->writesOrCallbacksPending() ) {
4028 // This only flushes transactions to clear snapshots, not to write data
4029 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4030 throw new DBUnexpectedError(
4032 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4036 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4040 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4041 if ( $this->trxLevel() ) {
4042 // There is a good chance an exception was thrown, causing any early return
4043 // from the caller. Let any error handler get a chance to issue rollback().
4044 // If there isn't one, let the error bubble up and trigger server-side rollback.
4045 $this->onTransactionResolution(
4046 function () use ( $lockKey, $fname ) {
4047 $this->unlock( $lockKey, $fname );
4052 $this->unlock( $lockKey, $fname );
4056 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4061 public function namedLocksEnqueue() {
4065 public function tableLocksHaveTransactionScope() {
4069 final public function lockTables( array $read, array $write, $method ) {
4070 if ( $this->writesOrCallbacksPending() ) {
4071 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4074 if ( $this->tableLocksHaveTransactionScope() ) {
4075 $this->startAtomic( $method );
4078 return $this->doLockTables( $read, $write, $method );
4082 * Helper function for lockTables() that handles the actual table locking
4084 * @param array $read Array of tables to lock for read access
4085 * @param array $write Array of tables to lock for write access
4086 * @param string $method Name of caller
4089 protected function doLockTables( array $read, array $write, $method ) {
4093 final public function unlockTables( $method ) {
4094 if ( $this->tableLocksHaveTransactionScope() ) {
4095 $this->endAtomic( $method );
4097 return true; // locks released on COMMIT/ROLLBACK
4100 return $this->doUnlockTables( $method );
4104 * Helper function for unlockTables() that handles the actual table unlocking
4106 * @param string $method Name of caller
4109 protected function doUnlockTables( $method ) {
4115 * @param string $tableName
4116 * @param string $fName
4117 * @return bool|ResultWrapper
4120 public function dropTable( $tableName, $fName = __METHOD__
) {
4121 if ( !$this->tableExists( $tableName, $fName ) ) {
4124 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4126 return $this->query( $sql, $fName );
4129 public function getInfinity() {
4133 public function encodeExpiry( $expiry ) {
4134 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4135 ?
$this->getInfinity()
4136 : $this->timestamp( $expiry );
4139 public function decodeExpiry( $expiry, $format = TS_MW
) {
4140 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4144 return ConvertibleTimestamp
::convert( $format, $expiry );
4147 public function setBigSelects( $value = true ) {
4151 public function isReadOnly() {
4152 return ( $this->getReadOnlyReason() !== false );
4156 * @return string|bool Reason this DB is read-only or false if it is not
4158 protected function getReadOnlyReason() {
4159 $reason = $this->getLBInfo( 'readOnlyReason' );
4161 return is_string( $reason ) ?
$reason : false;
4164 public function setTableAliases( array $aliases ) {
4165 $this->tableAliases
= $aliases;
4168 public function setIndexAliases( array $aliases ) {
4169 $this->indexAliases
= $aliases;
4173 * Get the underlying binding connection handle
4175 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4176 * This catches broken callers than catch and ignore disconnection exceptions.
4177 * Unlike checking isOpen(), this is safe to call inside of open().
4180 * @throws DBUnexpectedError
4183 protected function getBindingHandle() {
4184 if ( !$this->conn
) {
4185 throw new DBUnexpectedError(
4187 'DB connection was already closed or the connection dropped.'
4198 public function __toString() {
4199 return (string)$this->conn
;
4203 * Make sure that copies do not share the same client binding handle
4204 * @throws DBConnectionError
4206 public function __clone() {
4207 $this->connLogger
->warning(
4208 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4209 ( new RuntimeException() )->getTraceAsString()
4212 if ( $this->isOpen() ) {
4213 // Open a new connection resource without messing with the old one
4214 $this->opened
= false;
4215 $this->conn
= false;
4216 $this->trxEndCallbacks
= []; // don't copy
4217 $this->handleSessionLoss(); // no trx or locks anymore
4218 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4219 $this->lastPing
= microtime( true );
4224 * Called by serialize. Throw an exception when DB connection is serialized.
4225 * This causes problems on some database engines because the connection is
4226 * not restored on unserialize.
4228 public function __sleep() {
4229 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4230 'the connection is not restored on wakeup.' );
4234 * Run a few simple sanity checks and close dangling connections
4236 public function __destruct() {
4237 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4238 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4241 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4242 if ( $danglingWriters ) {
4243 $fnames = implode( ', ', $danglingWriters );
4244 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4247 if ( $this->conn
) {
4248 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4249 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4250 Wikimedia\
suppressWarnings();
4251 $this->closeConnection();
4252 Wikimedia\restoreWarnings
();
4253 $this->conn
= false;
4254 $this->opened
= false;
4259 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4260 class_alias( Database
::class, 'Database' ); // b/c global alias