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
;
36 use InvalidArgumentException
;
41 * Relational database abstraction object
46 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
47 /** Number of times to re-try an operation in case of deadlock */
48 const DEADLOCK_TRIES
= 4;
49 /** Minimum time to wait before retry, in microseconds */
50 const DEADLOCK_DELAY_MIN
= 500000;
51 /** Maximum time to wait before retry */
52 const DEADLOCK_DELAY_MAX
= 1500000;
54 /** How long before it is worth doing a dummy query to test the connection */
56 const PING_QUERY
= 'SELECT 1 AS ping';
58 const TINY_WRITE_SEC
= 0.010;
59 const SLOW_WRITE_SEC
= 0.500;
60 const SMALL_WRITE_ROWS
= 100;
62 /** @var string Whether lock granularity is on the level of the entire database */
63 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
65 /** @var string SQL query */
66 protected $lastQuery = '';
67 /** @var float|bool UNIX timestamp of last write query */
68 protected $lastWriteTime = false;
69 /** @var string|bool */
70 protected $phpError = false;
79 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
80 protected $tableAliases = [];
81 /** @var bool Whether this PHP instance is for a CLI script */
83 /** @var string Agent name for query profiling */
86 /** @var BagOStuff APC cache */
88 /** @var LoggerInterface */
89 protected $connLogger;
90 /** @var LoggerInterface */
91 protected $queryLogger;
92 /** @var callback Error logging callback */
93 protected $errorLogger;
95 /** @var resource|null Database connection */
96 protected $conn = null;
98 protected $opened = false;
100 /** @var array[] List of (callable, method name) */
101 protected $trxIdleCallbacks = [];
102 /** @var array[] List of (callable, method name) */
103 protected $trxPreCommitCallbacks = [];
104 /** @var array[] List of (callable, method name) */
105 protected $trxEndCallbacks = [];
106 /** @var callable[] Map of (name => callable) */
107 protected $trxRecurringCallbacks = [];
108 /** @var bool Whether to suppress triggering of transaction end callbacks */
109 protected $trxEndCallbacksSuppressed = false;
112 protected $tablePrefix = '';
114 protected $schema = '';
118 protected $lbInfo = [];
119 /** @var array|bool */
120 protected $schemaVars = false;
122 protected $sessionVars = [];
123 /** @var array|null */
124 protected $preparedArgs;
125 /** @var string|bool|null Stashed value of html_errors INI setting */
126 protected $htmlErrors;
128 protected $delimiter = ';';
129 /** @var DatabaseDomain */
130 protected $currentDomain;
131 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
132 protected $affectedRowCount;
135 * Either 1 if a transaction is active or 0 otherwise.
136 * The other Trx fields may not be meaningfull if this is 0.
140 protected $trxLevel = 0;
142 * Either a short hexidecimal string if a transaction is active or ""
145 * @see Database::trxLevel
147 protected $trxShortId = '';
149 * The UNIX time that the transaction started. Callers can assume that if
150 * snapshot isolation is used, then the data is *at least* up to date to that
151 * point (possibly more up-to-date since the first SELECT defines the snapshot).
154 * @see Database::trxLevel
156 private $trxTimestamp = null;
157 /** @var float Lag estimate at the time of BEGIN */
158 private $trxReplicaLag = null;
160 * Remembers the function name given for starting the most recent transaction via begin().
161 * Used to provide additional context for error reporting.
164 * @see Database::trxLevel
166 private $trxFname = null;
168 * Record if possible write queries were done in the last transaction started
171 * @see Database::trxLevel
173 private $trxDoneWrites = false;
175 * Record if the current transaction was started implicitly due to DBO_TRX being set.
178 * @see Database::trxLevel
180 private $trxAutomatic = false;
182 * Array of levels of atomicity within transactions
186 private $trxAtomicLevels = [];
188 * Record if the current transaction was started implicitly by Database::startAtomic
192 private $trxAutomaticAtomic = false;
194 * Track the write query callers of the current transaction
198 private $trxWriteCallers = [];
200 * @var float Seconds spent in write queries for the current transaction
202 private $trxWriteDuration = 0.0;
204 * @var int Number of write queries for the current transaction
206 private $trxWriteQueryCount = 0;
208 * @var int Number of rows affected by write queries for the current transaction
210 private $trxWriteAffectedRows = 0;
212 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
214 private $trxWriteAdjDuration = 0.0;
216 * @var int Number of write queries counted in trxWriteAdjDuration
218 private $trxWriteAdjQueryCount = 0;
220 * @var float RTT time estimate
222 private $rttEstimate = 0.0;
224 /** @var array Map of (name => 1) for locks obtained via lock() */
225 private $namedLocksHeld = [];
226 /** @var array Map of (table name => 1) for TEMPORARY tables */
227 protected $sessionTempTables = [];
229 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
230 private $lazyMasterHandle;
232 /** @var float UNIX timestamp */
233 protected $lastPing = 0.0;
235 /** @var int[] Prior flags member variable values */
236 private $priorFlags = [];
238 /** @var object|string Class name or object With profileIn/profileOut methods */
240 /** @var TransactionProfiler */
241 protected $trxProfiler;
244 protected $nonNativeInsertSelectBatchSize = 10000;
247 * Constructor and database handle and attempt to connect to the DB server
249 * IDatabase classes should not be constructed directly in external
250 * code. Database::factory() should be used instead.
252 * @param array $params Parameters passed from Database::factory()
254 function __construct( array $params ) {
255 $server = $params['host'];
256 $user = $params['user'];
257 $password = $params['password'];
258 $dbName = $params['dbname'];
260 $this->schema
= $params['schema'];
261 $this->tablePrefix
= $params['tablePrefix'];
263 $this->cliMode
= $params['cliMode'];
264 // Agent name is added to SQL queries in a comment, so make sure it can't break out
265 $this->agent
= str_replace( '/', '-', $params['agent'] );
267 $this->flags
= $params['flags'];
268 if ( $this->flags
& self
::DBO_DEFAULT
) {
269 if ( $this->cliMode
) {
270 $this->flags
&= ~self
::DBO_TRX
;
272 $this->flags |
= self
::DBO_TRX
;
276 $this->sessionVars
= $params['variables'];
278 $this->srvCache
= isset( $params['srvCache'] )
279 ?
$params['srvCache']
280 : new HashBagOStuff();
282 $this->profiler
= $params['profiler'];
283 $this->trxProfiler
= $params['trxProfiler'];
284 $this->connLogger
= $params['connLogger'];
285 $this->queryLogger
= $params['queryLogger'];
286 $this->errorLogger
= $params['errorLogger'];
288 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
289 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
292 // Set initial dummy domain until open() sets the final DB/prefix
293 $this->currentDomain
= DatabaseDomain
::newUnspecified();
296 $this->open( $server, $user, $password, $dbName );
297 } elseif ( $this->requiresDatabaseUser() ) {
298 throw new InvalidArgumentException( "No database user provided." );
301 // Set the domain object after open() sets the relevant fields
302 if ( $this->dbName
!= '' ) {
303 // Domains with server scope but a table prefix are not used by IDatabase classes
304 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
309 * Construct a Database subclass instance given a database type and parameters
311 * This also connects to the database immediately upon object construction
313 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
314 * @param array $p Parameter map with keys:
315 * - host : The hostname of the DB server
316 * - user : The name of the database user the client operates under
317 * - password : The password for the database user
318 * - dbname : The name of the database to use where queries do not specify one.
319 * The database must exist or an error might be thrown. Setting this to the empty string
320 * will avoid any such errors and make the handle have no implicit database scope. This is
321 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
322 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
323 * in which user names and such are defined, e.g. users are database-specific in Postgres.
324 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
325 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
326 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
327 * recognized in queries. This can be used in place of schemas for handle site farms.
328 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
329 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
330 * flag in place UNLESS this this database simply acts as a key/value store.
331 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
332 * 'mysqli' driver; the old one 'mysql' has been removed.
333 * - variables: Optional map of session variables to set after connecting. This can be
334 * used to adjust lock timeouts or encoding modes and the like.
335 * - connLogger: Optional PSR-3 logger interface instance.
336 * - queryLogger: Optional PSR-3 logger interface instance.
337 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
338 * These will be called in query(), using a simplified version of the SQL that also
339 * includes the agent as a SQL comment.
340 * - trxProfiler: Optional TransactionProfiler instance.
341 * - errorLogger: Optional callback that takes an Exception and logs it.
342 * - cliMode: Whether to consider the execution context that of a CLI script.
343 * - agent: Optional name used to identify the end-user in query profiling/logging.
344 * - srvCache: Optional BagOStuff instance to an APC-style cache.
345 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
346 * @return Database|null If the database driver or extension cannot be found
347 * @throws InvalidArgumentException If the database driver or extension cannot be found
350 final public static function factory( $dbType, $p = [] ) {
351 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
353 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
354 // Resolve some defaults for b/c
355 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
356 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
357 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
358 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
359 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
360 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
361 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
362 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
363 $p['cliMode'] = isset( $p['cliMode'] )
365 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
366 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
367 if ( !isset( $p['connLogger'] ) ) {
368 $p['connLogger'] = new NullLogger();
370 if ( !isset( $p['queryLogger'] ) ) {
371 $p['queryLogger'] = new NullLogger();
373 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
374 if ( !isset( $p['trxProfiler'] ) ) {
375 $p['trxProfiler'] = new TransactionProfiler();
377 if ( !isset( $p['errorLogger'] ) ) {
378 $p['errorLogger'] = function ( Exception
$e ) {
379 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
383 $conn = new $class( $p );
392 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
393 * @param string|null $driver Optional name of a specific DB client driver
394 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
395 * @throws InvalidArgumentException
398 final public static function attributesFromType( $dbType, $driver = null ) {
399 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
401 $class = self
::getClass( $dbType, $driver );
403 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
407 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
408 * @param string|null $driver Optional name of a specific DB client driver
409 * @return string Database subclass name to use
410 * @throws InvalidArgumentException
412 private static function getClass( $dbType, $driver = null ) {
413 // For database types with built-in support, the below maps type to IDatabase
414 // implementations. For types with multipe driver implementations (PHP extensions),
415 // an array can be used, keyed by extension name. In case of an array, the
416 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
417 // we auto-detect the first available driver. For types without built-in support,
418 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
419 static $builtinTypes = [
420 'mssql' => DatabaseMssql
::class,
421 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
422 'sqlite' => DatabaseSqlite
::class,
423 'postgres' => DatabasePostgres
::class,
426 $dbType = strtolower( $dbType );
429 if ( isset( $builtinTypes[$dbType] ) ) {
430 $possibleDrivers = $builtinTypes[$dbType];
431 if ( is_string( $possibleDrivers ) ) {
432 $class = $possibleDrivers;
434 if ( (string)$driver !== '' ) {
435 if ( !isset( $possibleDrivers[$driver] ) ) {
436 throw new InvalidArgumentException( __METHOD__
.
437 " type '$dbType' does not support driver '{$driver}'" );
439 $class = $possibleDrivers[$driver];
442 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
443 if ( extension_loaded( $posDriver ) ) {
444 $class = $possibleClass;
451 $class = 'Database' . ucfirst( $dbType );
454 if ( $class === false ) {
455 throw new InvalidArgumentException( __METHOD__
.
456 " no viable database extension found for type '$dbType'" );
463 * @return array Map of (Database::ATTRIBUTE_* constant => value
466 protected static function getAttributes() {
471 * Set the PSR-3 logger interface to use for query logging. (The logger
472 * interfaces for connection logging and error logging can be set with the
475 * @param LoggerInterface $logger
477 public function setLogger( LoggerInterface
$logger ) {
478 $this->queryLogger
= $logger;
481 public function getServerInfo() {
482 return $this->getServerVersion();
485 public function bufferResults( $buffer = null ) {
486 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
487 if ( $buffer !== null ) {
489 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
490 : $this->setFlag( self
::DBO_NOBUFFER
);
497 * Turns on (false) or off (true) the automatic generation and sending
498 * of a "we're sorry, but there has been a database error" page on
499 * database errors. Default is on (false). When turned off, the
500 * code should use lastErrno() and lastError() to handle the
501 * situation as appropriate.
503 * Do not use this function outside of the Database classes.
505 * @param null|bool $ignoreErrors
506 * @return bool The previous value of the flag.
508 protected function ignoreErrors( $ignoreErrors = null ) {
509 $res = $this->getFlag( self
::DBO_IGNORE
);
510 if ( $ignoreErrors !== null ) {
511 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
512 if ( $ignoreErrors ) {
513 $this->flags |
= self
::DBO_IGNORE
;
515 $this->flags
&= ~self
::DBO_IGNORE
;
522 public function trxLevel() {
523 return $this->trxLevel
;
526 public function trxTimestamp() {
527 return $this->trxLevel ?
$this->trxTimestamp
: null;
530 public function tablePrefix( $prefix = null ) {
531 $old = $this->tablePrefix
;
532 if ( $prefix !== null ) {
533 $this->tablePrefix
= $prefix;
534 $this->currentDomain
= ( $this->dbName
!= '' )
535 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
536 : DatabaseDomain
::newUnspecified();
542 public function dbSchema( $schema = null ) {
543 $old = $this->schema
;
544 if ( $schema !== null ) {
545 $this->schema
= $schema;
551 public function getLBInfo( $name = null ) {
552 if ( is_null( $name ) ) {
553 return $this->lbInfo
;
555 if ( array_key_exists( $name, $this->lbInfo
) ) {
556 return $this->lbInfo
[$name];
563 public function setLBInfo( $name, $value = null ) {
564 if ( is_null( $value ) ) {
565 $this->lbInfo
= $name;
567 $this->lbInfo
[$name] = $value;
571 public function setLazyMasterHandle( IDatabase
$conn ) {
572 $this->lazyMasterHandle
= $conn;
576 * @return IDatabase|null
577 * @see setLazyMasterHandle()
580 protected function getLazyMasterHandle() {
581 return $this->lazyMasterHandle
;
584 public function implicitGroupby() {
588 public function implicitOrderby() {
592 public function lastQuery() {
593 return $this->lastQuery
;
596 public function doneWrites() {
597 return (bool)$this->lastWriteTime
;
600 public function lastDoneWrites() {
601 return $this->lastWriteTime ?
: false;
604 public function writesPending() {
605 return $this->trxLevel
&& $this->trxDoneWrites
;
608 public function writesOrCallbacksPending() {
609 return $this->trxLevel
&& (
610 $this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks
614 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
615 if ( !$this->trxLevel
) {
617 } elseif ( !$this->trxDoneWrites
) {
622 case self
::ESTIMATE_DB_APPLY
:
624 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
625 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
626 // For omitted queries, make them count as something at least
627 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
628 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
631 default: // everything
632 return $this->trxWriteDuration
;
636 public function pendingWriteCallers() {
637 return $this->trxLevel ?
$this->trxWriteCallers
: [];
640 public function pendingWriteRowsAffected() {
641 return $this->trxWriteAffectedRows
;
645 * Get the list of method names that have pending write queries or callbacks
646 * for this transaction
650 protected function pendingWriteAndCallbackCallers() {
651 if ( !$this->trxLevel
) {
655 $fnames = $this->trxWriteCallers
;
657 $this->trxIdleCallbacks
,
658 $this->trxPreCommitCallbacks
,
659 $this->trxEndCallbacks
661 foreach ( $callbacks as $callback ) {
662 $fnames[] = $callback[1];
669 public function isOpen() {
670 return $this->opened
;
673 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
674 if ( ( $flag & self
::DBO_IGNORE
) ) {
675 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
678 if ( $remember === self
::REMEMBER_PRIOR
) {
679 array_push( $this->priorFlags
, $this->flags
);
681 $this->flags |
= $flag;
684 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
685 if ( ( $flag & self
::DBO_IGNORE
) ) {
686 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
689 if ( $remember === self
::REMEMBER_PRIOR
) {
690 array_push( $this->priorFlags
, $this->flags
);
692 $this->flags
&= ~
$flag;
695 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
696 if ( !$this->priorFlags
) {
700 if ( $state === self
::RESTORE_INITIAL
) {
701 $this->flags
= reset( $this->priorFlags
);
702 $this->priorFlags
= [];
704 $this->flags
= array_pop( $this->priorFlags
);
708 public function getFlag( $flag ) {
709 return !!( $this->flags
& $flag );
713 * @param string $name Class field name
715 * @deprecated Since 1.28
717 public function getProperty( $name ) {
721 public function getDomainID() {
722 return $this->currentDomain
->getId();
725 final public function getWikiID() {
726 return $this->getDomainID();
730 * Get information about an index into an object
731 * @param string $table Table name
732 * @param string $index Index name
733 * @param string $fname Calling function name
734 * @return mixed Database-specific index description class or false if the index does not exist
736 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
739 * Wrapper for addslashes()
741 * @param string $s String to be slashed.
742 * @return string Slashed string.
744 abstract function strencode( $s );
747 * Set a custom error handler for logging errors during database connection
749 protected function installErrorHandler() {
750 $this->phpError
= false;
751 $this->htmlErrors
= ini_set( 'html_errors', '0' );
752 set_error_handler( [ $this, 'connectionErrorLogger' ] );
756 * Restore the previous error handler and return the last PHP error for this DB
758 * @return bool|string
760 protected function restoreErrorHandler() {
761 restore_error_handler();
762 if ( $this->htmlErrors
!== false ) {
763 ini_set( 'html_errors', $this->htmlErrors
);
766 return $this->getLastPHPError();
770 * @return string|bool Last PHP error for this DB (typically connection errors)
772 protected function getLastPHPError() {
773 if ( $this->phpError
) {
774 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
775 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
784 * Error handler for logging errors during database connection
785 * This method should not be used outside of Database classes
788 * @param string $errstr
790 public function connectionErrorLogger( $errno, $errstr ) {
791 $this->phpError
= $errstr;
795 * Create a log context to pass to PSR-3 logger functions.
797 * @param array $extras Additional data to add to context
800 protected function getLogContext( array $extras = [] ) {
803 'db_server' => $this->server
,
804 'db_name' => $this->dbName
,
805 'db_user' => $this->user
,
811 public function close() {
813 if ( $this->trxLevel() ) {
814 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
817 $closed = $this->closeConnection();
820 $this->trxIdleCallbacks ||
821 $this->trxPreCommitCallbacks ||
822 $this->trxEndCallbacks
824 throw new RuntimeException( "Transaction callbacks still pending." );
828 $this->opened
= false;
834 * Make sure isOpen() returns true as a sanity check
836 * @throws DBUnexpectedError
838 protected function assertOpen() {
839 if ( !$this->isOpen() ) {
840 throw new DBUnexpectedError( $this, "DB connection was already closed." );
845 * Closes underlying database connection
847 * @return bool Whether connection was closed successfully
849 abstract protected function closeConnection();
851 public function reportConnectionError( $error = 'Unknown error' ) {
852 $myError = $this->lastError();
858 throw new DBConnectionError( $this, $error );
862 * The DBMS-dependent part of query()
864 * @param string $sql SQL query.
865 * @return ResultWrapper|bool Result object to feed to fetchObject,
866 * fetchRow, ...; or false on failure
868 abstract protected function doQuery( $sql );
871 * Determine whether a query writes to the DB.
872 * Should return true if unsure.
877 protected function isWriteQuery( $sql ) {
879 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
884 * @return string|null
886 protected function getQueryVerb( $sql ) {
887 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
891 * Determine whether a SQL statement is sensitive to isolation level.
892 * A SQL statement is considered transactable if its result could vary
893 * depending on the transaction isolation level. Operational commands
894 * such as 'SET' and 'SHOW' are not considered to be transactable.
899 protected function isTransactableQuery( $sql ) {
901 $this->getQueryVerb( $sql ),
902 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
908 * @param string $sql A SQL query
909 * @return bool Whether $sql is SQL for TEMPORARY table operation
911 protected function registerTempTableOperation( $sql ) {
913 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
917 $this->sessionTempTables
[$matches[1]] = 1;
920 } elseif ( preg_match(
921 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
925 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
926 unset( $this->sessionTempTables
[$matches[1]] );
929 } elseif ( preg_match(
930 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
934 return isset( $this->sessionTempTables
[$matches[1]] );
935 } elseif ( preg_match(
936 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
940 return isset( $this->sessionTempTables
[$matches[1]] );
946 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
947 $priorWritesPending = $this->writesOrCallbacksPending();
948 $this->lastQuery
= $sql;
950 $isWrite = $this->isWriteQuery( $sql );
952 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
954 $isNonTempWrite = false;
958 if ( $this->getLBInfo( 'replica' ) === true ) {
961 'Write operations are not allowed on replica database connections.'
964 # In theory, non-persistent writes are allowed in read-only mode, but due to things
965 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
966 $reason = $this->getReadOnlyReason();
967 if ( $reason !== false ) {
968 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
970 # Set a flag indicating that writes have been done
971 $this->lastWriteTime
= microtime( true );
974 # Add trace comment to the begin of the sql string, right after the operator.
975 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
976 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
978 # Start implicit transactions that wrap the request if DBO_TRX is enabled
979 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
980 && $this->isTransactableQuery( $sql )
982 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
983 $this->trxAutomatic
= true;
986 # Keep track of whether the transaction has write queries pending
987 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
988 $this->trxDoneWrites
= true;
989 $this->trxProfiler
->transactionWritingIn(
990 $this->server
, $this->dbName
, $this->trxShortId
);
993 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
994 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
997 # Avoid fatals if close() was called
1000 # Send the query to the server
1001 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1003 # Try reconnecting if the connection was lost
1004 if ( false === $ret && $this->wasErrorReissuable() ) {
1005 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1006 # Stash the last error values before anything might clear them
1007 $lastError = $this->lastError();
1008 $lastErrno = $this->lastErrno();
1009 # Update state tracking to reflect transaction loss due to disconnection
1010 $this->handleSessionLoss();
1011 if ( $this->reconnect() ) {
1012 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1013 $params = [ 'dbserver' => $this->getServer() ];
1014 $this->connLogger
->warning( $msg, $params );
1015 $this->queryLogger
->warning( $msg, $params +
1016 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1018 if ( !$recoverable ) {
1019 # Callers may catch the exception and continue to use the DB
1020 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1022 # Should be safe to silently retry the query
1023 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1026 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1027 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1031 if ( false === $ret ) {
1032 # Deadlocks cause the entire transaction to abort, not just the statement.
1033 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1034 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1035 if ( $this->wasDeadlock() ) {
1036 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1037 $tempIgnore = false; // not recoverable
1039 # Update state tracking to reflect transaction loss
1040 $this->handleSessionLoss();
1043 $this->reportQueryError(
1044 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1047 $res = $this->resultObject( $ret );
1053 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1055 * @param string $sql Original SQL query
1056 * @param string $commentedSql SQL query with debugging/trace comment
1057 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1058 * @param string $fname Name of the calling function
1059 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1060 * object for a successful read query, or false on failure
1062 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1063 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1064 # generalizeSQL() will probably cut down the query to reasonable
1065 # logging size most of the time. The substr is really just a sanity check.
1067 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1069 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1072 # Include query transaction state
1073 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1075 $startTime = microtime( true );
1076 if ( $this->profiler
) {
1077 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1079 $this->affectedRowCount
= null;
1080 $ret = $this->doQuery( $commentedSql );
1081 $this->affectedRowCount
= $this->affectedRows();
1082 if ( $this->profiler
) {
1083 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1085 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1087 unset( $queryProfSection ); // profile out (if set)
1089 if ( $ret !== false ) {
1090 $this->lastPing
= $startTime;
1091 if ( $isWrite && $this->trxLevel
) {
1092 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1093 $this->trxWriteCallers
[] = $fname;
1097 if ( $sql === self
::PING_QUERY
) {
1098 $this->rttEstimate
= $queryRuntime;
1101 $this->trxProfiler
->recordQueryCompletion(
1102 $queryProf, $startTime, $isWrite, $this->affectedRows()
1104 $this->queryLogger
->debug( $sql, [
1106 'master' => $isMaster,
1107 'runtime' => $queryRuntime,
1114 * Update the estimated run-time of a query, not counting large row lock times
1116 * LoadBalancer can be set to rollback transactions that will create huge replication
1117 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1118 * queries, like inserting a row can take a long time due to row locking. This method
1119 * uses some simple heuristics to discount those cases.
1121 * @param string $sql A SQL write query
1122 * @param float $runtime Total runtime, including RTT
1123 * @param int $affected Affected row count
1125 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1126 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1127 $indicativeOfReplicaRuntime = true;
1128 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1129 $verb = $this->getQueryVerb( $sql );
1130 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1131 if ( $verb === 'INSERT' ) {
1132 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1133 } elseif ( $verb === 'REPLACE' ) {
1134 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1138 $this->trxWriteDuration +
= $runtime;
1139 $this->trxWriteQueryCount +
= 1;
1140 $this->trxWriteAffectedRows +
= $affected;
1141 if ( $indicativeOfReplicaRuntime ) {
1142 $this->trxWriteAdjDuration +
= $runtime;
1143 $this->trxWriteAdjQueryCount +
= 1;
1148 * Determine whether or not it is safe to retry queries after a database
1149 * connection is lost
1151 * @param string $sql SQL query
1152 * @param bool $priorWritesPending Whether there is a transaction open with
1153 * possible write queries or transaction pre-commit/idle callbacks
1154 * waiting on it to finish.
1155 * @return bool True if it is safe to retry the query, false otherwise
1157 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1158 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1159 # Dropped connections also mean that named locks are automatically released.
1160 # Only allow error suppression in autocommit mode or when the lost transaction
1161 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1162 if ( $this->namedLocksHeld
) {
1163 return false; // possible critical section violation
1164 } elseif ( $sql === 'COMMIT' ) {
1165 return !$priorWritesPending; // nothing written anyway? (T127428)
1166 } elseif ( $sql === 'ROLLBACK' ) {
1167 return true; // transaction lost...which is also what was requested :)
1168 } elseif ( $this->explicitTrxActive() ) {
1169 return false; // don't drop atomocity
1170 } elseif ( $priorWritesPending ) {
1171 return false; // prior writes lost from implicit transaction
1178 * Clean things up after transaction loss due to disconnection
1180 * @return null|Exception
1182 private function handleSessionLoss() {
1183 $this->trxLevel
= 0;
1184 $this->trxIdleCallbacks
= []; // T67263
1185 $this->trxPreCommitCallbacks
= []; // T67263
1186 $this->sessionTempTables
= [];
1187 $this->namedLocksHeld
= [];
1189 // Handle callbacks in trxEndCallbacks
1190 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1191 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1193 } catch ( Exception
$e ) {
1194 // Already logged; move on...
1200 * Checks whether the cause of the error is detected to be a timeout.
1202 * It returns false by default, and not all engines support detecting this yet.
1203 * If this returns false, it will be treated as a generic query error.
1205 * @param string $error Error text
1206 * @param int $errno Error number
1209 protected function wasQueryTimeout( $error, $errno ) {
1213 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1214 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1215 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1217 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1218 $this->queryLogger
->error(
1219 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1220 $this->getLogContext( [
1221 'method' => __METHOD__
,
1224 'sql1line' => $sql1line,
1228 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1229 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1230 if ( $wasQueryTimeout ) {
1231 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1233 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1238 public function freeResult( $res ) {
1241 public function selectField(
1242 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1244 if ( $var === '*' ) { // sanity
1245 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1248 if ( !is_array( $options ) ) {
1249 $options = [ $options ];
1252 $options['LIMIT'] = 1;
1254 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1255 if ( $res === false ||
!$this->numRows( $res ) ) {
1259 $row = $this->fetchRow( $res );
1261 if ( $row !== false ) {
1262 return reset( $row );
1268 public function selectFieldValues(
1269 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1271 if ( $var === '*' ) { // sanity
1272 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1273 } elseif ( !is_string( $var ) ) { // sanity
1274 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1277 if ( !is_array( $options ) ) {
1278 $options = [ $options ];
1281 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1282 if ( $res === false ) {
1287 foreach ( $res as $row ) {
1288 $values[] = $row->$var;
1295 * Returns an optional USE INDEX clause to go after the table, and a
1296 * string to go at the end of the query.
1298 * @param array $options Associative array of options to be turned into
1299 * an SQL query, valid keys are listed in the function.
1301 * @see Database::select()
1303 protected function makeSelectOptions( $options ) {
1304 $preLimitTail = $postLimitTail = '';
1309 foreach ( $options as $key => $option ) {
1310 if ( is_numeric( $key ) ) {
1311 $noKeyOptions[$option] = true;
1315 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1317 $preLimitTail .= $this->makeOrderBy( $options );
1319 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1320 $postLimitTail .= ' FOR UPDATE';
1323 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1324 $postLimitTail .= ' LOCK IN SHARE MODE';
1327 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1328 $startOpts .= 'DISTINCT';
1331 # Various MySQL extensions
1332 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1333 $startOpts .= ' /*! STRAIGHT_JOIN */';
1336 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1337 $startOpts .= ' HIGH_PRIORITY';
1340 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1341 $startOpts .= ' SQL_BIG_RESULT';
1344 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1345 $startOpts .= ' SQL_BUFFER_RESULT';
1348 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1349 $startOpts .= ' SQL_SMALL_RESULT';
1352 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1353 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1356 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1357 $startOpts .= ' SQL_CACHE';
1360 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1361 $startOpts .= ' SQL_NO_CACHE';
1364 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1365 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1369 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1370 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1375 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1379 * Returns an optional GROUP BY with an optional HAVING
1381 * @param array $options Associative array of options
1383 * @see Database::select()
1386 protected function makeGroupByWithHaving( $options ) {
1388 if ( isset( $options['GROUP BY'] ) ) {
1389 $gb = is_array( $options['GROUP BY'] )
1390 ?
implode( ',', $options['GROUP BY'] )
1391 : $options['GROUP BY'];
1392 $sql .= ' GROUP BY ' . $gb;
1394 if ( isset( $options['HAVING'] ) ) {
1395 $having = is_array( $options['HAVING'] )
1396 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1397 : $options['HAVING'];
1398 $sql .= ' HAVING ' . $having;
1405 * Returns an optional ORDER BY
1407 * @param array $options Associative array of options
1409 * @see Database::select()
1412 protected function makeOrderBy( $options ) {
1413 if ( isset( $options['ORDER BY'] ) ) {
1414 $ob = is_array( $options['ORDER BY'] )
1415 ?
implode( ',', $options['ORDER BY'] )
1416 : $options['ORDER BY'];
1418 return ' ORDER BY ' . $ob;
1424 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1425 $options = [], $join_conds = [] ) {
1426 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1428 return $this->query( $sql, $fname );
1431 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1432 $options = [], $join_conds = []
1434 if ( is_array( $vars ) ) {
1435 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1438 $options = (array)$options;
1439 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1440 ?
$options['USE INDEX']
1443 isset( $options['IGNORE INDEX'] ) &&
1444 is_array( $options['IGNORE INDEX'] )
1446 ?
$options['IGNORE INDEX']
1449 if ( is_array( $table ) ) {
1451 $this->tableNamesWithIndexClauseOrJOIN(
1452 $table, $useIndexes, $ignoreIndexes, $join_conds );
1453 } elseif ( $table != '' ) {
1455 $this->tableNamesWithIndexClauseOrJOIN(
1456 [ $table ], $useIndexes, $ignoreIndexes, [] );
1461 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1462 $this->makeSelectOptions( $options );
1464 if ( is_array( $conds ) ) {
1465 $conds = $this->makeList( $conds, self
::LIST_AND
);
1468 if ( $conds === null ||
$conds === false ) {
1469 $this->queryLogger
->warning(
1473 . ' with incorrect parameters: $conds must be a string or an array'
1478 if ( $conds === '' ) {
1479 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1480 } elseif ( is_string( $conds ) ) {
1481 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1482 "WHERE $conds $preLimitTail";
1484 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1487 if ( isset( $options['LIMIT'] ) ) {
1488 $sql = $this->limitResult( $sql, $options['LIMIT'],
1489 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1491 $sql = "$sql $postLimitTail";
1493 if ( isset( $options['EXPLAIN'] ) ) {
1494 $sql = 'EXPLAIN ' . $sql;
1500 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1501 $options = [], $join_conds = []
1503 $options = (array)$options;
1504 $options['LIMIT'] = 1;
1505 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1507 if ( $res === false ) {
1511 if ( !$this->numRows( $res ) ) {
1515 $obj = $this->fetchObject( $res );
1520 public function estimateRowCount(
1521 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1524 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1527 $row = $this->fetchRow( $res );
1528 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1534 public function selectRowCount(
1535 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1538 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1539 // The identifier quotes is primarily for MSSQL.
1540 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1541 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1542 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1545 $row = $this->fetchRow( $res );
1546 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1553 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1554 * It's only slightly flawed. Don't use for anything important.
1556 * @param string $sql A SQL Query
1560 protected static function generalizeSQL( $sql ) {
1561 # This does the same as the regexp below would do, but in such a way
1562 # as to avoid crashing php on some large strings.
1563 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1565 $sql = str_replace( "\\\\", '', $sql );
1566 $sql = str_replace( "\\'", '', $sql );
1567 $sql = str_replace( "\\\"", '', $sql );
1568 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1569 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1571 # All newlines, tabs, etc replaced by single space
1572 $sql = preg_replace( '/\s+/', ' ', $sql );
1575 # except the ones surrounded by characters, e.g. l10n
1576 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1577 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1582 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1583 $info = $this->fieldInfo( $table, $field );
1588 public function indexExists( $table, $index, $fname = __METHOD__
) {
1589 if ( !$this->tableExists( $table ) ) {
1593 $info = $this->indexInfo( $table, $index, $fname );
1594 if ( is_null( $info ) ) {
1597 return $info !== false;
1601 public function tableExists( $table, $fname = __METHOD__
) {
1602 $tableRaw = $this->tableName( $table, 'raw' );
1603 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1604 return true; // already known to exist
1607 $table = $this->tableName( $table );
1608 $ignoreErrors = true;
1609 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1614 public function indexUnique( $table, $index ) {
1615 $indexInfo = $this->indexInfo( $table, $index );
1617 if ( !$indexInfo ) {
1621 return !$indexInfo[0]->Non_unique
;
1625 * Helper for Database::insert().
1627 * @param array $options
1630 protected function makeInsertOptions( $options ) {
1631 return implode( ' ', $options );
1634 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1635 # No rows to insert, easy just return now
1636 if ( !count( $a ) ) {
1640 $table = $this->tableName( $table );
1642 if ( !is_array( $options ) ) {
1643 $options = [ $options ];
1647 if ( isset( $options['fileHandle'] ) ) {
1648 $fh = $options['fileHandle'];
1650 $options = $this->makeInsertOptions( $options );
1652 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1654 $keys = array_keys( $a[0] );
1657 $keys = array_keys( $a );
1660 $sql = 'INSERT ' . $options .
1661 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1665 foreach ( $a as $row ) {
1671 $sql .= '(' . $this->makeList( $row ) . ')';
1674 $sql .= '(' . $this->makeList( $a ) . ')';
1677 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1679 } elseif ( $fh !== null ) {
1683 return (bool)$this->query( $sql, $fname );
1687 * Make UPDATE options array for Database::makeUpdateOptions
1689 * @param array $options
1692 protected function makeUpdateOptionsArray( $options ) {
1693 if ( !is_array( $options ) ) {
1694 $options = [ $options ];
1699 if ( in_array( 'IGNORE', $options ) ) {
1707 * Make UPDATE options for the Database::update function
1709 * @param array $options The options passed to Database::update
1712 protected function makeUpdateOptions( $options ) {
1713 $opts = $this->makeUpdateOptionsArray( $options );
1715 return implode( ' ', $opts );
1718 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1719 $table = $this->tableName( $table );
1720 $opts = $this->makeUpdateOptions( $options );
1721 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1723 if ( $conds !== [] && $conds !== '*' ) {
1724 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1727 return (bool)$this->query( $sql, $fname );
1730 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1731 if ( !is_array( $a ) ) {
1732 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1738 foreach ( $a as $field => $value ) {
1740 if ( $mode == self
::LIST_AND
) {
1742 } elseif ( $mode == self
::LIST_OR
) {
1751 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1752 $list .= "($value)";
1753 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1756 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1758 // Remove null from array to be handled separately if found
1759 $includeNull = false;
1760 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1761 $includeNull = true;
1762 unset( $value[$nullKey] );
1764 if ( count( $value ) == 0 && !$includeNull ) {
1765 throw new InvalidArgumentException(
1766 __METHOD__
. ": empty input for field $field" );
1767 } elseif ( count( $value ) == 0 ) {
1768 // only check if $field is null
1769 $list .= "$field IS NULL";
1771 // IN clause contains at least one valid element
1772 if ( $includeNull ) {
1773 // Group subconditions to ensure correct precedence
1776 if ( count( $value ) == 1 ) {
1777 // Special-case single values, as IN isn't terribly efficient
1778 // Don't necessarily assume the single key is 0; we don't
1779 // enforce linear numeric ordering on other arrays here.
1780 $value = array_values( $value )[0];
1781 $list .= $field . " = " . $this->addQuotes( $value );
1783 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1785 // if null present in array, append IS NULL
1786 if ( $includeNull ) {
1787 $list .= " OR $field IS NULL)";
1790 } elseif ( $value === null ) {
1791 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1792 $list .= "$field IS ";
1793 } elseif ( $mode == self
::LIST_SET
) {
1794 $list .= "$field = ";
1799 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1801 $list .= "$field = ";
1803 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1810 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1813 foreach ( $data as $base => $sub ) {
1814 if ( count( $sub ) ) {
1815 $conds[] = $this->makeList(
1816 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1822 return $this->makeList( $conds, self
::LIST_OR
);
1824 // Nothing to search for...
1829 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1833 public function bitNot( $field ) {
1837 public function bitAnd( $fieldLeft, $fieldRight ) {
1838 return "($fieldLeft & $fieldRight)";
1841 public function bitOr( $fieldLeft, $fieldRight ) {
1842 return "($fieldLeft | $fieldRight)";
1845 public function buildConcat( $stringList ) {
1846 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1849 public function buildGroupConcatField(
1850 $delim, $table, $field, $conds = '', $join_conds = []
1852 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1854 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1857 public function buildStringCast( $field ) {
1861 public function databasesAreIndependent() {
1865 public function selectDB( $db ) {
1866 # Stub. Shouldn't cause serious problems if it's not overridden, but
1867 # if your database engine supports a concept similar to MySQL's
1868 # databases you may as well.
1869 $this->dbName
= $db;
1874 public function getDBname() {
1875 return $this->dbName
;
1878 public function getServer() {
1879 return $this->server
;
1882 public function tableName( $name, $format = 'quoted' ) {
1883 # Skip the entire process when we have a string quoted on both ends.
1884 # Note that we check the end so that we will still quote any use of
1885 # use of `database`.table. But won't break things if someone wants
1886 # to query a database table with a dot in the name.
1887 if ( $this->isQuotedIdentifier( $name ) ) {
1891 # Lets test for any bits of text that should never show up in a table
1892 # name. Basically anything like JOIN or ON which are actually part of
1893 # SQL queries, but may end up inside of the table value to combine
1894 # sql. Such as how the API is doing.
1895 # Note that we use a whitespace test rather than a \b test to avoid
1896 # any remote case where a word like on may be inside of a table name
1897 # surrounded by symbols which may be considered word breaks.
1898 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1902 # Split database and table into proper variables.
1903 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1905 # Quote $table and apply the prefix if not quoted.
1906 # $tableName might be empty if this is called from Database::replaceVars()
1907 $tableName = "{$prefix}{$table}";
1908 if ( $format === 'quoted'
1909 && !$this->isQuotedIdentifier( $tableName )
1910 && $tableName !== ''
1912 $tableName = $this->addIdentifierQuotes( $tableName );
1915 # Quote $schema and $database and merge them with the table name if needed
1916 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1917 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1923 * Get the table components needed for a query given the currently selected database
1925 * @param string $name Table name in the form of db.schema.table, db.table, or table
1926 * @return array (DB name or "" for default, schema name, table prefix, table name)
1928 protected function qualifiedTableComponents( $name ) {
1929 # We reverse the explode so that database.table and table both output the correct table.
1930 $dbDetails = explode( '.', $name, 3 );
1931 if ( count( $dbDetails ) == 3 ) {
1932 list( $database, $schema, $table ) = $dbDetails;
1933 # We don't want any prefix added in this case
1935 } elseif ( count( $dbDetails ) == 2 ) {
1936 list( $database, $table ) = $dbDetails;
1937 # We don't want any prefix added in this case
1939 # In dbs that support it, $database may actually be the schema
1940 # but that doesn't affect any of the functionality here
1943 list( $table ) = $dbDetails;
1944 if ( isset( $this->tableAliases
[$table] ) ) {
1945 $database = $this->tableAliases
[$table]['dbname'];
1946 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1947 ?
$this->tableAliases
[$table]['schema']
1949 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1950 ?
$this->tableAliases
[$table]['prefix']
1951 : $this->tablePrefix
;
1954 $schema = $this->schema
; # Default schema
1955 $prefix = $this->tablePrefix
; # Default prefix
1959 return [ $database, $schema, $prefix, $table ];
1963 * @param string|null $namespace Database or schema
1964 * @param string $relation Name of table, view, sequence, etc...
1965 * @param string $format One of (raw, quoted)
1966 * @return string Relation name with quoted and merged $namespace as needed
1968 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1969 if ( strlen( $namespace ) ) {
1970 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1971 $namespace = $this->addIdentifierQuotes( $namespace );
1973 $relation = $namespace . '.' . $relation;
1979 public function tableNames() {
1980 $inArray = func_get_args();
1983 foreach ( $inArray as $name ) {
1984 $retVal[$name] = $this->tableName( $name );
1990 public function tableNamesN() {
1991 $inArray = func_get_args();
1994 foreach ( $inArray as $name ) {
1995 $retVal[] = $this->tableName( $name );
2002 * Get an aliased table name
2003 * e.g. tableName AS newTableName
2005 * @param string $name Table name, see tableName()
2006 * @param string|bool $alias Alias (optional)
2007 * @return string SQL name for aliased table. Will not alias a table to its own name
2009 protected function tableNameWithAlias( $name, $alias = false ) {
2010 if ( !$alias ||
$alias == $name ) {
2011 return $this->tableName( $name );
2013 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2018 * Gets an array of aliased table names
2020 * @param array $tables [ [alias] => table ]
2021 * @return string[] See tableNameWithAlias()
2023 protected function tableNamesWithAlias( $tables ) {
2025 foreach ( $tables as $alias => $table ) {
2026 if ( is_numeric( $alias ) ) {
2029 $retval[] = $this->tableNameWithAlias( $table, $alias );
2036 * Get an aliased field name
2037 * e.g. fieldName AS newFieldName
2039 * @param string $name Field name
2040 * @param string|bool $alias Alias (optional)
2041 * @return string SQL name for aliased field. Will not alias a field to its own name
2043 protected function fieldNameWithAlias( $name, $alias = false ) {
2044 if ( !$alias ||
(string)$alias === (string)$name ) {
2047 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2052 * Gets an array of aliased field names
2054 * @param array $fields [ [alias] => field ]
2055 * @return string[] See fieldNameWithAlias()
2057 protected function fieldNamesWithAlias( $fields ) {
2059 foreach ( $fields as $alias => $field ) {
2060 if ( is_numeric( $alias ) ) {
2063 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2070 * Get the aliased table name clause for a FROM clause
2071 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2073 * @param array $tables ( [alias] => table )
2074 * @param array $use_index Same as for select()
2075 * @param array $ignore_index Same as for select()
2076 * @param array $join_conds Same as for select()
2079 protected function tableNamesWithIndexClauseOrJOIN(
2080 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2084 $use_index = (array)$use_index;
2085 $ignore_index = (array)$ignore_index;
2086 $join_conds = (array)$join_conds;
2088 foreach ( $tables as $alias => $table ) {
2089 if ( !is_string( $alias ) ) {
2090 // No alias? Set it equal to the table name
2094 if ( is_array( $table ) ) {
2095 // A parenthesized group
2096 if ( count( $table ) > 1 ) {
2098 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2102 $innerTable = reset( $table );
2103 $innerAlias = key( $table );
2104 $joinedTable = $this->tableNameWithAlias(
2106 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2110 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2113 // Is there a JOIN clause for this table?
2114 if ( isset( $join_conds[$alias] ) ) {
2115 list( $joinType, $conds ) = $join_conds[$alias];
2116 $tableClause = $joinType;
2117 $tableClause .= ' ' . $joinedTable;
2118 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2119 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2121 $tableClause .= ' ' . $use;
2124 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2125 $ignore = $this->ignoreIndexClause(
2126 implode( ',', (array)$ignore_index[$alias] ) );
2127 if ( $ignore != '' ) {
2128 $tableClause .= ' ' . $ignore;
2131 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2133 $tableClause .= ' ON (' . $on . ')';
2136 $retJOIN[] = $tableClause;
2137 } elseif ( isset( $use_index[$alias] ) ) {
2138 // Is there an INDEX clause for this table?
2139 $tableClause = $joinedTable;
2140 $tableClause .= ' ' . $this->useIndexClause(
2141 implode( ',', (array)$use_index[$alias] )
2144 $ret[] = $tableClause;
2145 } elseif ( isset( $ignore_index[$alias] ) ) {
2146 // Is there an INDEX clause for this table?
2147 $tableClause = $joinedTable;
2148 $tableClause .= ' ' . $this->ignoreIndexClause(
2149 implode( ',', (array)$ignore_index[$alias] )
2152 $ret[] = $tableClause;
2154 $tableClause = $joinedTable;
2156 $ret[] = $tableClause;
2160 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2161 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2162 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2164 // Compile our final table clause
2165 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2169 * Allows for index remapping in queries where this is not consistent across DBMS
2171 * @param string $index
2174 protected function indexName( $index ) {
2178 public function addQuotes( $s ) {
2179 if ( $s instanceof Blob
) {
2182 if ( $s === null ) {
2184 } elseif ( is_bool( $s ) ) {
2187 # This will also quote numeric values. This should be harmless,
2188 # and protects against weird problems that occur when they really
2189 # _are_ strings such as article titles and string->number->string
2190 # conversion is not 1:1.
2191 return "'" . $this->strencode( $s ) . "'";
2196 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2197 * MySQL uses `backticks` while basically everything else uses double quotes.
2198 * Since MySQL is the odd one out here the double quotes are our generic
2199 * and we implement backticks in DatabaseMysqlBase.
2204 public function addIdentifierQuotes( $s ) {
2205 return '"' . str_replace( '"', '""', $s ) . '"';
2209 * Returns if the given identifier looks quoted or not according to
2210 * the database convention for quoting identifiers .
2212 * @note Do not use this to determine if untrusted input is safe.
2213 * A malicious user can trick this function.
2214 * @param string $name
2217 public function isQuotedIdentifier( $name ) {
2218 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2223 * @param string $escapeChar
2226 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2227 return str_replace( [ $escapeChar, '%', '_' ],
2228 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2232 public function buildLike() {
2233 $params = func_get_args();
2235 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2236 $params = $params[0];
2241 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2242 // may escape backslashes, creating problems of double escaping. The `
2243 // character has good cross-DBMS compatibility, avoiding special operators
2244 // in MS SQL like ^ and %
2247 foreach ( $params as $value ) {
2248 if ( $value instanceof LikeMatch
) {
2249 $s .= $value->toString();
2251 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2255 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2258 public function anyChar() {
2259 return new LikeMatch( '_' );
2262 public function anyString() {
2263 return new LikeMatch( '%' );
2266 public function nextSequenceValue( $seqName ) {
2271 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2272 * is only needed because a) MySQL must be as efficient as possible due to
2273 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2274 * which index to pick. Anyway, other databases might have different
2275 * indexes on a given table. So don't bother overriding this unless you're
2277 * @param string $index
2280 public function useIndexClause( $index ) {
2285 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2286 * is only needed because a) MySQL must be as efficient as possible due to
2287 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2288 * which index to pick. Anyway, other databases might have different
2289 * indexes on a given table. So don't bother overriding this unless you're
2291 * @param string $index
2294 public function ignoreIndexClause( $index ) {
2298 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2299 if ( count( $rows ) == 0 ) {
2304 if ( !is_array( reset( $rows ) ) ) {
2309 $this->startAtomic( $fname );
2310 $affectedRowCount = 0;
2311 foreach ( $rows as $row ) {
2312 // Delete rows which collide with this one
2313 $indexWhereClauses = [];
2314 foreach ( $uniqueIndexes as $index ) {
2315 $indexColumns = (array)$index;
2316 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2317 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2318 throw new DBUnexpectedError(
2320 'New record does not provide all values for unique key (' .
2321 implode( ', ', $indexColumns ) . ')'
2323 } elseif ( in_array( null, $indexRowValues, true ) ) {
2324 throw new DBUnexpectedError(
2326 'New record has a null value for unique key (' .
2327 implode( ', ', $indexColumns ) . ')'
2330 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2333 if ( $indexWhereClauses ) {
2334 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2335 $affectedRowCount +
= $this->affectedRows();
2338 // Now insert the row
2339 $this->insert( $table, $row, $fname );
2340 $affectedRowCount +
= $this->affectedRows();
2342 $this->endAtomic( $fname );
2343 $this->affectedRowCount
= $affectedRowCount;
2344 } catch ( Exception
$e ) {
2345 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2351 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2354 * @param string $table Table name
2355 * @param array|string $rows Row(s) to insert
2356 * @param string $fname Caller function name
2358 * @return ResultWrapper
2360 protected function nativeReplace( $table, $rows, $fname ) {
2361 $table = $this->tableName( $table );
2364 if ( !is_array( reset( $rows ) ) ) {
2368 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2371 foreach ( $rows as $row ) {
2378 $sql .= '(' . $this->makeList( $row ) . ')';
2381 return $this->query( $sql, $fname );
2384 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2387 if ( !count( $rows ) ) {
2388 return true; // nothing to do
2391 if ( !is_array( reset( $rows ) ) ) {
2395 if ( count( $uniqueIndexes ) ) {
2396 $clauses = []; // list WHERE clauses that each identify a single row
2397 foreach ( $rows as $row ) {
2398 foreach ( $uniqueIndexes as $index ) {
2399 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2400 $rowKey = []; // unique key to this row
2401 foreach ( $index as $column ) {
2402 $rowKey[$column] = $row[$column];
2404 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2407 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2412 $affectedRowCount = 0;
2414 $this->startAtomic( $fname );
2415 # Update any existing conflicting row(s)
2416 if ( $where !== false ) {
2417 $ok = $this->update( $table, $set, $where, $fname );
2418 $affectedRowCount +
= $this->affectedRows();
2422 # Now insert any non-conflicting row(s)
2423 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2424 $affectedRowCount +
= $this->affectedRows();
2425 $this->endAtomic( $fname );
2426 $this->affectedRowCount
= $affectedRowCount;
2427 } catch ( Exception
$e ) {
2428 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2435 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2439 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2442 $delTable = $this->tableName( $delTable );
2443 $joinTable = $this->tableName( $joinTable );
2444 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2445 if ( $conds != '*' ) {
2446 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2450 $this->query( $sql, $fname );
2453 public function textFieldSize( $table, $field ) {
2454 $table = $this->tableName( $table );
2455 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2456 $res = $this->query( $sql, __METHOD__
);
2457 $row = $this->fetchObject( $res );
2461 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2470 public function delete( $table, $conds, $fname = __METHOD__
) {
2472 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2475 $table = $this->tableName( $table );
2476 $sql = "DELETE FROM $table";
2478 if ( $conds != '*' ) {
2479 if ( is_array( $conds ) ) {
2480 $conds = $this->makeList( $conds, self
::LIST_AND
);
2482 $sql .= ' WHERE ' . $conds;
2485 return $this->query( $sql, $fname );
2488 final public function insertSelect(
2489 $destTable, $srcTable, $varMap, $conds,
2490 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2492 static $hints = [ 'NO_AUTO_COLUMNS' ];
2494 $insertOptions = (array)$insertOptions;
2495 $selectOptions = (array)$selectOptions;
2497 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2498 // For massive migrations with downtime, we don't want to select everything
2499 // into memory and OOM, so do all this native on the server side if possible.
2500 return $this->nativeInsertSelect(
2506 array_diff( $insertOptions, $hints ),
2512 return $this->nonNativeInsertSelect(
2518 array_diff( $insertOptions, $hints ),
2525 * @param array $insertOptions INSERT options
2526 * @param array $selectOptions SELECT options
2527 * @return bool Whether an INSERT SELECT with these options will be replication safe
2530 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2535 * Implementation of insertSelect() based on select() and insert()
2537 * @see IDatabase::insertSelect()
2539 * @param string $destTable
2540 * @param string|array $srcTable
2541 * @param array $varMap
2542 * @param array $conds
2543 * @param string $fname
2544 * @param array $insertOptions
2545 * @param array $selectOptions
2546 * @param array $selectJoinConds
2549 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2550 $fname = __METHOD__
,
2551 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2553 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2554 // on only the master (without needing row-based-replication). It also makes it easy to
2555 // know how big the INSERT is going to be.
2557 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2558 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2560 $selectOptions[] = 'FOR UPDATE';
2561 $res = $this->select(
2562 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2569 $affectedRowCount = 0;
2570 $this->startAtomic( $fname );
2573 foreach ( $res as $row ) {
2574 $rows[] = (array)$row;
2576 // Avoid inserts that are too huge
2577 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2578 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2582 $affectedRowCount +
= $this->affectedRows();
2586 if ( $rows && $ok ) {
2587 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2589 $affectedRowCount +
= $this->affectedRows();
2593 $this->endAtomic( $fname );
2594 $this->affectedRowCount
= $affectedRowCount;
2596 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2599 } catch ( Exception
$e ) {
2600 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2606 * Native server-side implementation of insertSelect() for situations where
2607 * we don't want to select everything into memory
2609 * @see IDatabase::insertSelect()
2610 * @param string $destTable
2611 * @param string|array $srcTable
2612 * @param array $varMap
2613 * @param array $conds
2614 * @param string $fname
2615 * @param array $insertOptions
2616 * @param array $selectOptions
2617 * @param array $selectJoinConds
2620 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2621 $fname = __METHOD__
,
2622 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2624 $destTable = $this->tableName( $destTable );
2626 if ( !is_array( $insertOptions ) ) {
2627 $insertOptions = [ $insertOptions ];
2630 $insertOptions = $this->makeInsertOptions( $insertOptions );
2632 $selectSql = $this->selectSQLText(
2634 array_values( $varMap ),
2641 $sql = "INSERT $insertOptions" .
2642 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2645 return $this->query( $sql, $fname );
2649 * Construct a LIMIT query with optional offset. This is used for query
2650 * pages. The SQL should be adjusted so that only the first $limit rows
2651 * are returned. If $offset is provided as well, then the first $offset
2652 * rows should be discarded, and the next $limit rows should be returned.
2653 * If the result of the query is not ordered, then the rows to be returned
2654 * are theoretically arbitrary.
2656 * $sql is expected to be a SELECT, if that makes a difference.
2658 * The version provided by default works in MySQL and SQLite. It will very
2659 * likely need to be overridden for most other DBMSes.
2661 * @param string $sql SQL query we will append the limit too
2662 * @param int $limit The SQL limit
2663 * @param int|bool $offset The SQL offset (default false)
2664 * @throws DBUnexpectedError
2667 public function limitResult( $sql, $limit, $offset = false ) {
2668 if ( !is_numeric( $limit ) ) {
2669 throw new DBUnexpectedError( $this,
2670 "Invalid non-numeric limit passed to limitResult()\n" );
2673 return "$sql LIMIT "
2674 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2678 public function unionSupportsOrderAndLimit() {
2679 return true; // True for almost every DB supported
2682 public function unionQueries( $sqls, $all ) {
2683 $glue = $all ?
') UNION ALL (' : ') UNION (';
2685 return '(' . implode( $glue, $sqls ) . ')';
2688 public function unionConditionPermutations(
2689 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2690 $options = [], $join_conds = []
2692 // First, build the Cartesian product of $permute_conds
2694 foreach ( $permute_conds as $field => $values ) {
2696 // Skip empty $values
2699 $values = array_unique( $values ); // For sanity
2701 foreach ( $conds as $cond ) {
2702 foreach ( $values as $value ) {
2703 $cond[$field] = $value;
2704 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2710 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2712 // If there's just one condition and no subordering, hand off to
2713 // selectSQLText directly.
2714 if ( count( $conds ) === 1 &&
2715 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2717 return $this->selectSQLText(
2718 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2722 // Otherwise, we need to pull out the order and limit to apply after
2723 // the union. Then build the SQL queries for each set of conditions in
2724 // $conds. Then union them together (using UNION ALL, because the
2725 // product *should* already be distinct).
2726 $orderBy = $this->makeOrderBy( $options );
2727 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2728 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2729 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2730 if ( !$this->unionSupportsOrderAndLimit() ) {
2731 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2733 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2734 $options['ORDER BY'] = $options['INNER ORDER BY'];
2736 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2737 // We need to increase the limit by the offset rather than
2738 // using the offset directly, otherwise it'll skip incorrectly
2739 // in the subqueries.
2740 $options['LIMIT'] = $limit +
$offset;
2741 unset( $options['OFFSET'] );
2746 foreach ( $conds as $cond ) {
2747 $sqls[] = $this->selectSQLText(
2748 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2751 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2752 if ( $limit !== null ) {
2753 $sql = $this->limitResult( $sql, $limit, $offset );
2759 public function conditional( $cond, $trueVal, $falseVal ) {
2760 if ( is_array( $cond ) ) {
2761 $cond = $this->makeList( $cond, self
::LIST_AND
);
2764 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2767 public function strreplace( $orig, $old, $new ) {
2768 return "REPLACE({$orig}, {$old}, {$new})";
2771 public function getServerUptime() {
2775 public function wasDeadlock() {
2779 public function wasLockTimeout() {
2783 public function wasErrorReissuable() {
2787 public function wasReadOnlyError() {
2792 * Do not use this method outside of Database/DBError classes
2794 * @param int|string $errno
2795 * @return bool Whether the given query error was a connection drop
2797 public function wasConnectionError( $errno ) {
2801 public function deadlockLoop() {
2802 $args = func_get_args();
2803 $function = array_shift( $args );
2804 $tries = self
::DEADLOCK_TRIES
;
2806 $this->begin( __METHOD__
);
2809 /** @var Exception $e */
2813 $retVal = call_user_func_array( $function, $args );
2815 } catch ( DBQueryError
$e ) {
2816 if ( $this->wasDeadlock() ) {
2817 // Retry after a randomized delay
2818 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2820 // Throw the error back up
2824 } while ( --$tries > 0 );
2826 if ( $tries <= 0 ) {
2827 // Too many deadlocks; give up
2828 $this->rollback( __METHOD__
);
2831 $this->commit( __METHOD__
);
2837 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2838 # Real waits are implemented in the subclass.
2842 public function getReplicaPos() {
2847 public function getMasterPos() {
2852 public function serverIsReadOnly() {
2856 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2857 if ( !$this->trxLevel
) {
2858 throw new DBUnexpectedError( $this, "No transaction is active." );
2860 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2863 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2864 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2865 if ( !$this->trxLevel
) {
2866 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2870 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2871 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2872 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2873 // an implicit commit of all peer databases. This is true even if a transaction has
2874 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2875 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2877 // No transaction is active nor will start implicitly, so make one for this callback
2878 $this->startAtomic( __METHOD__
);
2880 call_user_func( $callback );
2881 $this->endAtomic( __METHOD__
);
2882 } catch ( Exception
$e ) {
2883 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2889 final public function setTransactionListener( $name, callable
$callback = null ) {
2891 $this->trxRecurringCallbacks
[$name] = $callback;
2893 unset( $this->trxRecurringCallbacks
[$name] );
2898 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2900 * This method should not be used outside of Database/LoadBalancer
2902 * @param bool $suppress
2905 final public function setTrxEndCallbackSuppression( $suppress ) {
2906 $this->trxEndCallbacksSuppressed
= $suppress;
2910 * Actually run and consume any "on transaction idle/resolution" callbacks.
2912 * This method should not be used outside of Database/LoadBalancer
2914 * @param int $trigger IDatabase::TRIGGER_* constant
2918 public function runOnTransactionIdleCallbacks( $trigger ) {
2919 if ( $this->trxEndCallbacksSuppressed
) {
2923 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2924 /** @var Exception $e */
2925 $e = null; // first exception
2926 do { // callbacks may add callbacks :)
2927 $callbacks = array_merge(
2928 $this->trxIdleCallbacks
,
2929 $this->trxEndCallbacks
// include "transaction resolution" callbacks
2931 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
2932 $this->trxEndCallbacks
= []; // consumed (recursion guard)
2933 foreach ( $callbacks as $callback ) {
2935 list( $phpCallback ) = $callback;
2936 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2937 call_user_func_array( $phpCallback, [ $trigger ] );
2939 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2941 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2943 } catch ( Exception
$ex ) {
2944 call_user_func( $this->errorLogger
, $ex );
2946 // Some callbacks may use startAtomic/endAtomic, so make sure
2947 // their transactions are ended so other callbacks don't fail
2948 if ( $this->trxLevel() ) {
2949 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2953 } while ( count( $this->trxIdleCallbacks
) );
2955 if ( $e instanceof Exception
) {
2956 throw $e; // re-throw any first exception
2961 * Actually run and consume any "on transaction pre-commit" callbacks.
2963 * This method should not be used outside of Database/LoadBalancer
2968 public function runOnTransactionPreCommitCallbacks() {
2969 $e = null; // first exception
2970 do { // callbacks may add callbacks :)
2971 $callbacks = $this->trxPreCommitCallbacks
;
2972 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
2973 foreach ( $callbacks as $callback ) {
2975 list( $phpCallback ) = $callback;
2976 call_user_func( $phpCallback );
2977 } catch ( Exception
$ex ) {
2978 call_user_func( $this->errorLogger
, $ex );
2982 } while ( count( $this->trxPreCommitCallbacks
) );
2984 if ( $e instanceof Exception
) {
2985 throw $e; // re-throw any first exception
2990 * Actually run any "transaction listener" callbacks.
2992 * This method should not be used outside of Database/LoadBalancer
2994 * @param int $trigger IDatabase::TRIGGER_* constant
2998 public function runTransactionListenerCallbacks( $trigger ) {
2999 if ( $this->trxEndCallbacksSuppressed
) {
3003 /** @var Exception $e */
3004 $e = null; // first exception
3006 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3008 $phpCallback( $trigger, $this );
3009 } catch ( Exception
$ex ) {
3010 call_user_func( $this->errorLogger
, $ex );
3015 if ( $e instanceof Exception
) {
3016 throw $e; // re-throw any first exception
3020 final public function startAtomic( $fname = __METHOD__
) {
3021 if ( !$this->trxLevel
) {
3022 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3023 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3024 // in all changes being in one transaction to keep requests transactional.
3025 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3026 $this->trxAutomaticAtomic
= true;
3030 $this->trxAtomicLevels
[] = $fname;
3033 final public function endAtomic( $fname = __METHOD__
) {
3034 if ( !$this->trxLevel
) {
3035 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3037 if ( !$this->trxAtomicLevels ||
3038 array_pop( $this->trxAtomicLevels
) !== $fname
3040 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3043 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3044 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3048 final public function doAtomicSection( $fname, callable
$callback ) {
3049 $this->startAtomic( $fname );
3051 $res = call_user_func_array( $callback, [ $this, $fname ] );
3052 } catch ( Exception
$e ) {
3053 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3056 $this->endAtomic( $fname );
3061 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3062 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3063 if ( $this->trxLevel
) {
3064 if ( $this->trxAtomicLevels
) {
3065 $levels = implode( ', ', $this->trxAtomicLevels
);
3066 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3067 throw new DBUnexpectedError( $this, $msg );
3068 } elseif ( !$this->trxAutomatic
) {
3069 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3070 throw new DBUnexpectedError( $this, $msg );
3072 // @TODO: make this an exception at some point
3073 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3074 $this->queryLogger
->error( $msg );
3075 return; // join the main transaction set
3077 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3078 // @TODO: make this an exception at some point
3079 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3080 $this->queryLogger
->error( $msg );
3081 return; // let any writes be in the main transaction
3084 // Avoid fatals if close() was called
3085 $this->assertOpen();
3087 $this->doBegin( $fname );
3088 $this->trxTimestamp
= microtime( true );
3089 $this->trxFname
= $fname;
3090 $this->trxDoneWrites
= false;
3091 $this->trxAutomaticAtomic
= false;
3092 $this->trxAtomicLevels
= [];
3093 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3094 $this->trxWriteDuration
= 0.0;
3095 $this->trxWriteQueryCount
= 0;
3096 $this->trxWriteAffectedRows
= 0;
3097 $this->trxWriteAdjDuration
= 0.0;
3098 $this->trxWriteAdjQueryCount
= 0;
3099 $this->trxWriteCallers
= [];
3100 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3101 // Get an estimate of the replica DB lag before then, treating estimate staleness
3102 // as lag itself just to be safe
3103 $status = $this->getApproximateLagStatus();
3104 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3105 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3106 // caller will think its OK to muck around with the transaction just because startAtomic()
3107 // has not yet completed (e.g. setting trxAtomicLevels).
3108 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3112 * Issues the BEGIN command to the database server.
3114 * @see Database::begin()
3115 * @param string $fname
3117 protected function doBegin( $fname ) {
3118 $this->query( 'BEGIN', $fname );
3119 $this->trxLevel
= 1;
3122 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3123 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3124 // There are still atomic sections open. This cannot be ignored
3125 $levels = implode( ', ', $this->trxAtomicLevels
);
3126 throw new DBUnexpectedError(
3128 "$fname: Got COMMIT while atomic sections $levels are still open."
3132 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3133 if ( !$this->trxLevel
) {
3134 return; // nothing to do
3135 } elseif ( !$this->trxAutomatic
) {
3136 throw new DBUnexpectedError(
3138 "$fname: Flushing an explicit transaction, getting out of sync."
3142 if ( !$this->trxLevel
) {
3143 $this->queryLogger
->error(
3144 "$fname: No transaction to commit, something got out of sync." );
3145 return; // nothing to do
3146 } elseif ( $this->trxAutomatic
) {
3147 // @TODO: make this an exception at some point
3148 $msg = "$fname: Explicit commit of implicit transaction.";
3149 $this->queryLogger
->error( $msg );
3150 return; // wait for the main transaction set commit round
3154 // Avoid fatals if close() was called
3155 $this->assertOpen();
3157 $this->runOnTransactionPreCommitCallbacks();
3158 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3159 $this->doCommit( $fname );
3160 if ( $this->trxDoneWrites
) {
3161 $this->lastWriteTime
= microtime( true );
3162 $this->trxProfiler
->transactionWritingOut(
3167 $this->trxWriteAffectedRows
3171 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3172 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3176 * Issues the COMMIT command to the database server.
3178 * @see Database::commit()
3179 * @param string $fname
3181 protected function doCommit( $fname ) {
3182 if ( $this->trxLevel
) {
3183 $this->query( 'COMMIT', $fname );
3184 $this->trxLevel
= 0;
3188 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3189 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3190 if ( !$this->trxLevel
) {
3191 return; // nothing to do
3194 if ( !$this->trxLevel
) {
3195 $this->queryLogger
->error(
3196 "$fname: No transaction to rollback, something got out of sync." );
3197 return; // nothing to do
3198 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3199 throw new DBUnexpectedError(
3201 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3206 // Avoid fatals if close() was called
3207 $this->assertOpen();
3209 $this->doRollback( $fname );
3210 $this->trxAtomicLevels
= [];
3211 if ( $this->trxDoneWrites
) {
3212 $this->trxProfiler
->transactionWritingOut(
3219 $this->trxIdleCallbacks
= []; // clear
3220 $this->trxPreCommitCallbacks
= []; // clear
3222 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3223 } catch ( Exception
$e ) {
3224 // already logged; finish and let LoadBalancer move on during mass-rollback
3227 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3228 } catch ( Exception
$e ) {
3229 // already logged; let LoadBalancer move on during mass-rollback
3232 $this->affectedRowCount
= 0; // for the sake of consistency
3236 * Issues the ROLLBACK command to the database server.
3238 * @see Database::rollback()
3239 * @param string $fname
3241 protected function doRollback( $fname ) {
3242 if ( $this->trxLevel
) {
3243 # Disconnects cause rollback anyway, so ignore those errors
3244 $ignoreErrors = true;
3245 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3246 $this->trxLevel
= 0;
3250 public function flushSnapshot( $fname = __METHOD__
) {
3251 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3252 // This only flushes transactions to clear snapshots, not to write data
3253 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3254 throw new DBUnexpectedError(
3256 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3260 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3263 public function explicitTrxActive() {
3264 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3267 public function duplicateTableStructure(
3268 $oldName, $newName, $temporary = false, $fname = __METHOD__
3270 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3273 public function listTables( $prefix = null, $fname = __METHOD__
) {
3274 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3277 public function listViews( $prefix = null, $fname = __METHOD__
) {
3278 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3281 public function timestamp( $ts = 0 ) {
3282 $t = new ConvertibleTimestamp( $ts );
3283 // Let errors bubble up to avoid putting garbage in the DB
3284 return $t->getTimestamp( TS_MW
);
3287 public function timestampOrNull( $ts = null ) {
3288 if ( is_null( $ts ) ) {
3291 return $this->timestamp( $ts );
3295 public function affectedRows() {
3296 return ( $this->affectedRowCount
=== null )
3297 ?
$this->fetchAffectedRowCount() // default to driver value
3298 : $this->affectedRowCount
;
3302 * @return int Number of retrieved rows according to the driver
3304 abstract protected function fetchAffectedRowCount();
3307 * Take the result from a query, and wrap it in a ResultWrapper if
3308 * necessary. Boolean values are passed through as is, to indicate success
3309 * of write queries or failure.
3311 * Once upon a time, Database::query() returned a bare MySQL result
3312 * resource, and it was necessary to call this function to convert it to
3313 * a wrapper. Nowadays, raw database objects are never exposed to external
3314 * callers, so this is unnecessary in external code.
3316 * @param bool|ResultWrapper|resource|object $result
3317 * @return bool|ResultWrapper
3319 protected function resultObject( $result ) {
3322 } elseif ( $result instanceof ResultWrapper
) {
3324 } elseif ( $result === true ) {
3325 // Successful write query
3328 return new ResultWrapper( $this, $result );
3332 public function ping( &$rtt = null ) {
3333 // Avoid hitting the server if it was hit recently
3334 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3335 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3336 $rtt = $this->rttEstimate
;
3337 return true; // don't care about $rtt
3341 // This will reconnect if possible or return false if not
3342 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3343 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3344 $this->restoreFlags( self
::RESTORE_PRIOR
);
3347 $rtt = $this->rttEstimate
;
3354 * Close existing database connection and open a new connection
3356 * @return bool True if new connection is opened successfully, false if error
3358 protected function reconnect() {
3359 $this->closeConnection();
3360 $this->opened
= false;
3361 $this->conn
= false;
3363 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3364 $this->lastPing
= microtime( true );
3366 } catch ( DBConnectionError
$e ) {
3373 public function getSessionLagStatus() {
3374 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3378 * Get the replica DB lag when the current transaction started
3380 * This is useful when transactions might use snapshot isolation
3381 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3382 * is this lag plus transaction duration. If they don't, it is still
3383 * safe to be pessimistic. This returns null if there is no transaction.
3385 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3388 protected function getTransactionLagStatus() {
3389 return $this->trxLevel
3390 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3395 * Get a replica DB lag estimate for this server
3397 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3400 protected function getApproximateLagStatus() {
3402 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3403 'since' => microtime( true )
3408 * Merge the result of getSessionLagStatus() for several DBs
3409 * using the most pessimistic values to estimate the lag of
3410 * any data derived from them in combination
3412 * This is information is useful for caching modules
3414 * @see WANObjectCache::set()
3415 * @see WANObjectCache::getWithSetCallback()
3417 * @param IDatabase $db1
3418 * @param IDatabase $db2 [optional]
3419 * @return array Map of values:
3420 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3421 * - since: oldest UNIX timestamp of any of the DB lag estimates
3422 * - pending: whether any of the DBs have uncommitted changes
3426 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3427 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3428 foreach ( func_get_args() as $db ) {
3429 /** @var IDatabase $db */
3430 $status = $db->getSessionLagStatus();
3431 if ( $status['lag'] === false ) {
3432 $res['lag'] = false;
3433 } elseif ( $res['lag'] !== false ) {
3434 $res['lag'] = max( $res['lag'], $status['lag'] );
3436 $res['since'] = min( $res['since'], $status['since'] );
3437 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3443 public function getLag() {
3447 public function maxListLen() {
3451 public function encodeBlob( $b ) {
3455 public function decodeBlob( $b ) {
3456 if ( $b instanceof Blob
) {
3462 public function setSessionOptions( array $options ) {
3465 public function sourceFile(
3467 callable
$lineCallback = null,
3468 callable
$resultCallback = null,
3470 callable
$inputCallback = null
3472 Wikimedia\
suppressWarnings();
3473 $fp = fopen( $filename, 'r' );
3474 Wikimedia\restoreWarnings
();
3476 if ( false === $fp ) {
3477 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3481 $fname = __METHOD__
. "( $filename )";
3485 $error = $this->sourceStream(
3486 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3487 } catch ( Exception
$e ) {
3497 public function setSchemaVars( $vars ) {
3498 $this->schemaVars
= $vars;
3501 public function sourceStream(
3503 callable
$lineCallback = null,
3504 callable
$resultCallback = null,
3505 $fname = __METHOD__
,
3506 callable
$inputCallback = null
3508 $delimiterReset = new ScopedCallback(
3509 function ( $delimiter ) {
3510 $this->delimiter
= $delimiter;
3512 [ $this->delimiter
]
3516 while ( !feof( $fp ) ) {
3517 if ( $lineCallback ) {
3518 call_user_func( $lineCallback );
3521 $line = trim( fgets( $fp ) );
3523 if ( $line == '' ) {
3527 if ( '-' == $line[0] && '-' == $line[1] ) {
3535 $done = $this->streamStatementEnd( $cmd, $line );
3539 if ( $done ||
feof( $fp ) ) {
3540 $cmd = $this->replaceVars( $cmd );
3542 if ( $inputCallback ) {
3543 $callbackResult = call_user_func( $inputCallback, $cmd );
3545 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3546 $cmd = $callbackResult;
3551 $res = $this->query( $cmd, $fname );
3553 if ( $resultCallback ) {
3554 call_user_func( $resultCallback, $res, $this );
3557 if ( false === $res ) {
3558 $err = $this->lastError();
3560 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3567 ScopedCallback
::consume( $delimiterReset );
3572 * Called by sourceStream() to check if we've reached a statement end
3574 * @param string &$sql SQL assembled so far
3575 * @param string &$newLine New line about to be added to $sql
3576 * @return bool Whether $newLine contains end of the statement
3578 public function streamStatementEnd( &$sql, &$newLine ) {
3579 if ( $this->delimiter
) {
3581 $newLine = preg_replace(
3582 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3583 if ( $newLine != $prev ) {
3592 * Database independent variable replacement. Replaces a set of variables
3593 * in an SQL statement with their contents as given by $this->getSchemaVars().
3595 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3597 * - '{$var}' should be used for text and is passed through the database's
3599 * - `{$var}` should be used for identifiers (e.g. table and database names).
3600 * It is passed through the database's addIdentifierQuotes method which
3601 * can be overridden if the database uses something other than backticks.
3602 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3603 * database's tableName method.
3604 * - / *i* / passes the name that follows through the database's indexName method.
3605 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3606 * its use should be avoided. In 1.24 and older, string encoding was applied.
3608 * @param string $ins SQL statement to replace variables in
3609 * @return string The new SQL statement with variables replaced
3611 protected function replaceVars( $ins ) {
3612 $vars = $this->getSchemaVars();
3613 return preg_replace_callback(
3615 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3616 \'\{\$ (\w+) }\' | # 3. addQuotes
3617 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3618 /\*\$ (\w+) \*/ # 5. leave unencoded
3620 function ( $m ) use ( $vars ) {
3621 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3622 // check for both nonexistent keys *and* the empty string.
3623 if ( isset( $m[1] ) && $m[1] !== '' ) {
3624 if ( $m[1] === 'i' ) {
3625 return $this->indexName( $m[2] );
3627 return $this->tableName( $m[2] );
3629 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3630 return $this->addQuotes( $vars[$m[3]] );
3631 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3632 return $this->addIdentifierQuotes( $vars[$m[4]] );
3633 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3634 return $vars[$m[5]];
3644 * Get schema variables. If none have been set via setSchemaVars(), then
3645 * use some defaults from the current object.
3649 protected function getSchemaVars() {
3650 if ( $this->schemaVars
) {
3651 return $this->schemaVars
;
3653 return $this->getDefaultSchemaVars();
3658 * Get schema variables to use if none have been set via setSchemaVars().
3660 * Override this in derived classes to provide variables for tables.sql
3661 * and SQL patch files.
3665 protected function getDefaultSchemaVars() {
3669 public function lockIsFree( $lockName, $method ) {
3670 // RDBMs methods for checking named locks may or may not count this thread itself.
3671 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3672 // the behavior choosen by the interface for this method.
3673 return !isset( $this->namedLocksHeld
[$lockName] );
3676 public function lock( $lockName, $method, $timeout = 5 ) {
3677 $this->namedLocksHeld
[$lockName] = 1;
3682 public function unlock( $lockName, $method ) {
3683 unset( $this->namedLocksHeld
[$lockName] );
3688 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3689 if ( $this->writesOrCallbacksPending() ) {
3690 // This only flushes transactions to clear snapshots, not to write data
3691 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3692 throw new DBUnexpectedError(
3694 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3698 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3702 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3703 if ( $this->trxLevel() ) {
3704 // There is a good chance an exception was thrown, causing any early return
3705 // from the caller. Let any error handler get a chance to issue rollback().
3706 // If there isn't one, let the error bubble up and trigger server-side rollback.
3707 $this->onTransactionResolution(
3708 function () use ( $lockKey, $fname ) {
3709 $this->unlock( $lockKey, $fname );
3714 $this->unlock( $lockKey, $fname );
3718 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3723 public function namedLocksEnqueue() {
3727 public function tableLocksHaveTransactionScope() {
3731 final public function lockTables( array $read, array $write, $method ) {
3732 if ( $this->writesOrCallbacksPending() ) {
3733 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3736 if ( $this->tableLocksHaveTransactionScope() ) {
3737 $this->startAtomic( $method );
3740 return $this->doLockTables( $read, $write, $method );
3744 * Helper function for lockTables() that handles the actual table locking
3746 * @param array $read Array of tables to lock for read access
3747 * @param array $write Array of tables to lock for write access
3748 * @param string $method Name of caller
3751 protected function doLockTables( array $read, array $write, $method ) {
3755 final public function unlockTables( $method ) {
3756 if ( $this->tableLocksHaveTransactionScope() ) {
3757 $this->endAtomic( $method );
3759 return true; // locks released on COMMIT/ROLLBACK
3762 return $this->doUnlockTables( $method );
3766 * Helper function for unlockTables() that handles the actual table unlocking
3768 * @param string $method Name of caller
3771 protected function doUnlockTables( $method ) {
3777 * @param string $tableName
3778 * @param string $fName
3779 * @return bool|ResultWrapper
3782 public function dropTable( $tableName, $fName = __METHOD__
) {
3783 if ( !$this->tableExists( $tableName, $fName ) ) {
3786 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3788 return $this->query( $sql, $fName );
3791 public function getInfinity() {
3795 public function encodeExpiry( $expiry ) {
3796 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3797 ?
$this->getInfinity()
3798 : $this->timestamp( $expiry );
3801 public function decodeExpiry( $expiry, $format = TS_MW
) {
3802 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3806 return ConvertibleTimestamp
::convert( $format, $expiry );
3809 public function setBigSelects( $value = true ) {
3813 public function isReadOnly() {
3814 return ( $this->getReadOnlyReason() !== false );
3818 * @return string|bool Reason this DB is read-only or false if it is not
3820 protected function getReadOnlyReason() {
3821 $reason = $this->getLBInfo( 'readOnlyReason' );
3823 return is_string( $reason ) ?
$reason : false;
3826 public function setTableAliases( array $aliases ) {
3827 $this->tableAliases
= $aliases;
3831 * @return bool Whether a DB user is required to access the DB
3834 protected function requiresDatabaseUser() {
3839 * Get the underlying binding connection handle
3841 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3842 * This catches broken callers than catch and ignore disconnection exceptions.
3843 * Unlike checking isOpen(), this is safe to call inside of open().
3845 * @return resource|object
3846 * @throws DBUnexpectedError
3849 protected function getBindingHandle() {
3850 if ( !$this->conn
) {
3851 throw new DBUnexpectedError(
3853 'DB connection was already closed or the connection dropped.'
3864 public function __toString() {
3865 return (string)$this->conn
;
3869 * Make sure that copies do not share the same client binding handle
3870 * @throws DBConnectionError
3872 public function __clone() {
3873 $this->connLogger
->warning(
3874 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3875 ( new RuntimeException() )->getTraceAsString()
3878 if ( $this->isOpen() ) {
3879 // Open a new connection resource without messing with the old one
3880 $this->opened
= false;
3881 $this->conn
= false;
3882 $this->trxEndCallbacks
= []; // don't copy
3883 $this->handleSessionLoss(); // no trx or locks anymore
3884 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3885 $this->lastPing
= microtime( true );
3890 * Called by serialize. Throw an exception when DB connection is serialized.
3891 * This causes problems on some database engines because the connection is
3892 * not restored on unserialize.
3894 public function __sleep() {
3895 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3896 'the connection is not restored on wakeup.' );
3900 * Run a few simple sanity checks and close dangling connections
3902 public function __destruct() {
3903 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3904 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3907 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3908 if ( $danglingWriters ) {
3909 $fnames = implode( ', ', $danglingWriters );
3910 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3913 if ( $this->conn
) {
3914 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3915 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3916 Wikimedia\
suppressWarnings();
3917 $this->closeConnection();
3918 Wikimedia\restoreWarnings
();
3919 $this->conn
= false;
3920 $this->opened
= false;
3925 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3926 class_alias( Database
::class, 'Database' ); // b/c global alias