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[] Map of (table => (dbname, schema, prefix) map) */
80 protected $tableAliases = [];
81 /** @var string[] Map of (index alias => index) */
82 protected $indexAliases = [];
83 /** @var bool Whether this PHP instance is for a CLI script */
85 /** @var string Agent name for query profiling */
88 /** @var BagOStuff APC cache */
90 /** @var LoggerInterface */
91 protected $connLogger;
92 /** @var LoggerInterface */
93 protected $queryLogger;
94 /** @var callback Error logging callback */
95 protected $errorLogger;
97 /** @var resource|null Database connection */
98 protected $conn = null;
100 protected $opened = false;
102 /** @var array[] List of (callable, method name) */
103 protected $trxIdleCallbacks = [];
104 /** @var array[] List of (callable, method name) */
105 protected $trxPreCommitCallbacks = [];
106 /** @var array[] List of (callable, method name) */
107 protected $trxEndCallbacks = [];
108 /** @var callable[] Map of (name => callable) */
109 protected $trxRecurringCallbacks = [];
110 /** @var bool Whether to suppress triggering of transaction end callbacks */
111 protected $trxEndCallbacksSuppressed = false;
114 protected $tablePrefix = '';
116 protected $schema = '';
120 protected $lbInfo = [];
121 /** @var array|bool */
122 protected $schemaVars = false;
124 protected $sessionVars = [];
125 /** @var array|null */
126 protected $preparedArgs;
127 /** @var string|bool|null Stashed value of html_errors INI setting */
128 protected $htmlErrors;
130 protected $delimiter = ';';
131 /** @var DatabaseDomain */
132 protected $currentDomain;
133 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
134 protected $affectedRowCount;
137 * Either 1 if a transaction is active or 0 otherwise.
138 * The other Trx fields may not be meaningfull if this is 0.
142 protected $trxLevel = 0;
144 * Either a short hexidecimal string if a transaction is active or ""
147 * @see Database::trxLevel
149 protected $trxShortId = '';
151 * The UNIX time that the transaction started. Callers can assume that if
152 * snapshot isolation is used, then the data is *at least* up to date to that
153 * point (possibly more up-to-date since the first SELECT defines the snapshot).
156 * @see Database::trxLevel
158 private $trxTimestamp = null;
159 /** @var float Lag estimate at the time of BEGIN */
160 private $trxReplicaLag = null;
162 * Remembers the function name given for starting the most recent transaction via begin().
163 * Used to provide additional context for error reporting.
166 * @see Database::trxLevel
168 private $trxFname = null;
170 * Record if possible write queries were done in the last transaction started
173 * @see Database::trxLevel
175 private $trxDoneWrites = false;
177 * Record if the current transaction was started implicitly due to DBO_TRX being set.
180 * @see Database::trxLevel
182 private $trxAutomatic = false;
184 * Array of levels of atomicity within transactions
188 private $trxAtomicLevels = [];
190 * Record if the current transaction was started implicitly by Database::startAtomic
194 private $trxAutomaticAtomic = false;
196 * Track the write query callers of the current transaction
200 private $trxWriteCallers = [];
202 * @var float Seconds spent in write queries for the current transaction
204 private $trxWriteDuration = 0.0;
206 * @var int Number of write queries for the current transaction
208 private $trxWriteQueryCount = 0;
210 * @var int Number of rows affected by write queries for the current transaction
212 private $trxWriteAffectedRows = 0;
214 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
216 private $trxWriteAdjDuration = 0.0;
218 * @var int Number of write queries counted in trxWriteAdjDuration
220 private $trxWriteAdjQueryCount = 0;
222 * @var float RTT time estimate
224 private $rttEstimate = 0.0;
226 /** @var array Map of (name => 1) for locks obtained via lock() */
227 private $namedLocksHeld = [];
228 /** @var array Map of (table name => 1) for TEMPORARY tables */
229 protected $sessionTempTables = [];
231 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
232 private $lazyMasterHandle;
234 /** @var float UNIX timestamp */
235 protected $lastPing = 0.0;
237 /** @var int[] Prior flags member variable values */
238 private $priorFlags = [];
240 /** @var object|string Class name or object With profileIn/profileOut methods */
242 /** @var TransactionProfiler */
243 protected $trxProfiler;
246 protected $nonNativeInsertSelectBatchSize = 10000;
249 * Constructor and database handle and attempt to connect to the DB server
251 * IDatabase classes should not be constructed directly in external
252 * code. Database::factory() should be used instead.
254 * @param array $params Parameters passed from Database::factory()
256 function __construct( array $params ) {
257 $server = $params['host'];
258 $user = $params['user'];
259 $password = $params['password'];
260 $dbName = $params['dbname'];
262 $this->schema
= $params['schema'];
263 $this->tablePrefix
= $params['tablePrefix'];
265 $this->cliMode
= $params['cliMode'];
266 // Agent name is added to SQL queries in a comment, so make sure it can't break out
267 $this->agent
= str_replace( '/', '-', $params['agent'] );
269 $this->flags
= $params['flags'];
270 if ( $this->flags
& self
::DBO_DEFAULT
) {
271 if ( $this->cliMode
) {
272 $this->flags
&= ~self
::DBO_TRX
;
274 $this->flags |
= self
::DBO_TRX
;
278 $this->sessionVars
= $params['variables'];
280 $this->srvCache
= isset( $params['srvCache'] )
281 ?
$params['srvCache']
282 : new HashBagOStuff();
284 $this->profiler
= $params['profiler'];
285 $this->trxProfiler
= $params['trxProfiler'];
286 $this->connLogger
= $params['connLogger'];
287 $this->queryLogger
= $params['queryLogger'];
288 $this->errorLogger
= $params['errorLogger'];
290 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
291 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
294 // Set initial dummy domain until open() sets the final DB/prefix
295 $this->currentDomain
= DatabaseDomain
::newUnspecified();
298 $this->open( $server, $user, $password, $dbName );
299 } elseif ( $this->requiresDatabaseUser() ) {
300 throw new InvalidArgumentException( "No database user provided." );
303 // Set the domain object after open() sets the relevant fields
304 if ( $this->dbName
!= '' ) {
305 // Domains with server scope but a table prefix are not used by IDatabase classes
306 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
311 * Construct a Database subclass instance given a database type and parameters
313 * This also connects to the database immediately upon object construction
315 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
316 * @param array $p Parameter map with keys:
317 * - host : The hostname of the DB server
318 * - user : The name of the database user the client operates under
319 * - password : The password for the database user
320 * - dbname : The name of the database to use where queries do not specify one.
321 * The database must exist or an error might be thrown. Setting this to the empty string
322 * will avoid any such errors and make the handle have no implicit database scope. This is
323 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
324 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
325 * in which user names and such are defined, e.g. users are database-specific in Postgres.
326 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
327 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
328 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
329 * recognized in queries. This can be used in place of schemas for handle site farms.
330 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
331 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
332 * flag in place UNLESS this this database simply acts as a key/value store.
333 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
334 * 'mysqli' driver; the old one 'mysql' has been removed.
335 * - variables: Optional map of session variables to set after connecting. This can be
336 * used to adjust lock timeouts or encoding modes and the like.
337 * - connLogger: Optional PSR-3 logger interface instance.
338 * - queryLogger: Optional PSR-3 logger interface instance.
339 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
340 * These will be called in query(), using a simplified version of the SQL that also
341 * includes the agent as a SQL comment.
342 * - trxProfiler: Optional TransactionProfiler instance.
343 * - errorLogger: Optional callback that takes an Exception and logs it.
344 * - cliMode: Whether to consider the execution context that of a CLI script.
345 * - agent: Optional name used to identify the end-user in query profiling/logging.
346 * - srvCache: Optional BagOStuff instance to an APC-style cache.
347 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
348 * @return Database|null If the database driver or extension cannot be found
349 * @throws InvalidArgumentException If the database driver or extension cannot be found
352 final public static function factory( $dbType, $p = [] ) {
353 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
355 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
356 // Resolve some defaults for b/c
357 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
358 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
359 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
360 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
361 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
362 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
363 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
364 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
365 $p['cliMode'] = isset( $p['cliMode'] )
367 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
368 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
369 if ( !isset( $p['connLogger'] ) ) {
370 $p['connLogger'] = new NullLogger();
372 if ( !isset( $p['queryLogger'] ) ) {
373 $p['queryLogger'] = new NullLogger();
375 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
376 if ( !isset( $p['trxProfiler'] ) ) {
377 $p['trxProfiler'] = new TransactionProfiler();
379 if ( !isset( $p['errorLogger'] ) ) {
380 $p['errorLogger'] = function ( Exception
$e ) {
381 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
385 $conn = new $class( $p );
394 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
395 * @param string|null $driver Optional name of a specific DB client driver
396 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
397 * @throws InvalidArgumentException
400 final public static function attributesFromType( $dbType, $driver = null ) {
401 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
403 $class = self
::getClass( $dbType, $driver );
405 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
409 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
410 * @param string|null $driver Optional name of a specific DB client driver
411 * @return string Database subclass name to use
412 * @throws InvalidArgumentException
414 private static function getClass( $dbType, $driver = null ) {
415 // For database types with built-in support, the below maps type to IDatabase
416 // implementations. For types with multipe driver implementations (PHP extensions),
417 // an array can be used, keyed by extension name. In case of an array, the
418 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
419 // we auto-detect the first available driver. For types without built-in support,
420 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
421 static $builtinTypes = [
422 'mssql' => DatabaseMssql
::class,
423 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
424 'sqlite' => DatabaseSqlite
::class,
425 'postgres' => DatabasePostgres
::class,
428 $dbType = strtolower( $dbType );
431 if ( isset( $builtinTypes[$dbType] ) ) {
432 $possibleDrivers = $builtinTypes[$dbType];
433 if ( is_string( $possibleDrivers ) ) {
434 $class = $possibleDrivers;
436 if ( (string)$driver !== '' ) {
437 if ( !isset( $possibleDrivers[$driver] ) ) {
438 throw new InvalidArgumentException( __METHOD__
.
439 " type '$dbType' does not support driver '{$driver}'" );
441 $class = $possibleDrivers[$driver];
444 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
445 if ( extension_loaded( $posDriver ) ) {
446 $class = $possibleClass;
453 $class = 'Database' . ucfirst( $dbType );
456 if ( $class === false ) {
457 throw new InvalidArgumentException( __METHOD__
.
458 " no viable database extension found for type '$dbType'" );
465 * @return array Map of (Database::ATTRIBUTE_* constant => value
468 protected static function getAttributes() {
473 * Set the PSR-3 logger interface to use for query logging. (The logger
474 * interfaces for connection logging and error logging can be set with the
477 * @param LoggerInterface $logger
479 public function setLogger( LoggerInterface
$logger ) {
480 $this->queryLogger
= $logger;
483 public function getServerInfo() {
484 return $this->getServerVersion();
487 public function bufferResults( $buffer = null ) {
488 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
489 if ( $buffer !== null ) {
491 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
492 : $this->setFlag( self
::DBO_NOBUFFER
);
499 * Turns on (false) or off (true) the automatic generation and sending
500 * of a "we're sorry, but there has been a database error" page on
501 * database errors. Default is on (false). When turned off, the
502 * code should use lastErrno() and lastError() to handle the
503 * situation as appropriate.
505 * Do not use this function outside of the Database classes.
507 * @param null|bool $ignoreErrors
508 * @return bool The previous value of the flag.
510 protected function ignoreErrors( $ignoreErrors = null ) {
511 $res = $this->getFlag( self
::DBO_IGNORE
);
512 if ( $ignoreErrors !== null ) {
513 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
514 if ( $ignoreErrors ) {
515 $this->flags |
= self
::DBO_IGNORE
;
517 $this->flags
&= ~self
::DBO_IGNORE
;
524 public function trxLevel() {
525 return $this->trxLevel
;
528 public function trxTimestamp() {
529 return $this->trxLevel ?
$this->trxTimestamp
: null;
532 public function tablePrefix( $prefix = null ) {
533 $old = $this->tablePrefix
;
534 if ( $prefix !== null ) {
535 $this->tablePrefix
= $prefix;
536 $this->currentDomain
= ( $this->dbName
!= '' )
537 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
538 : DatabaseDomain
::newUnspecified();
544 public function dbSchema( $schema = null ) {
545 $old = $this->schema
;
546 if ( $schema !== null ) {
547 $this->schema
= $schema;
553 public function getLBInfo( $name = null ) {
554 if ( is_null( $name ) ) {
555 return $this->lbInfo
;
557 if ( array_key_exists( $name, $this->lbInfo
) ) {
558 return $this->lbInfo
[$name];
565 public function setLBInfo( $name, $value = null ) {
566 if ( is_null( $value ) ) {
567 $this->lbInfo
= $name;
569 $this->lbInfo
[$name] = $value;
573 public function setLazyMasterHandle( IDatabase
$conn ) {
574 $this->lazyMasterHandle
= $conn;
578 * @return IDatabase|null
579 * @see setLazyMasterHandle()
582 protected function getLazyMasterHandle() {
583 return $this->lazyMasterHandle
;
586 public function implicitGroupby() {
590 public function implicitOrderby() {
594 public function lastQuery() {
595 return $this->lastQuery
;
598 public function doneWrites() {
599 return (bool)$this->lastWriteTime
;
602 public function lastDoneWrites() {
603 return $this->lastWriteTime ?
: false;
606 public function writesPending() {
607 return $this->trxLevel
&& $this->trxDoneWrites
;
610 public function writesOrCallbacksPending() {
611 return $this->trxLevel
&& (
612 $this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks
616 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
617 if ( !$this->trxLevel
) {
619 } elseif ( !$this->trxDoneWrites
) {
624 case self
::ESTIMATE_DB_APPLY
:
626 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
627 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
628 // For omitted queries, make them count as something at least
629 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
630 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
633 default: // everything
634 return $this->trxWriteDuration
;
638 public function pendingWriteCallers() {
639 return $this->trxLevel ?
$this->trxWriteCallers
: [];
642 public function pendingWriteRowsAffected() {
643 return $this->trxWriteAffectedRows
;
647 * Get the list of method names that have pending write queries or callbacks
648 * for this transaction
652 protected function pendingWriteAndCallbackCallers() {
653 if ( !$this->trxLevel
) {
657 $fnames = $this->trxWriteCallers
;
659 $this->trxIdleCallbacks
,
660 $this->trxPreCommitCallbacks
,
661 $this->trxEndCallbacks
663 foreach ( $callbacks as $callback ) {
664 $fnames[] = $callback[1];
671 public function isOpen() {
672 return $this->opened
;
675 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
676 if ( ( $flag & self
::DBO_IGNORE
) ) {
677 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
680 if ( $remember === self
::REMEMBER_PRIOR
) {
681 array_push( $this->priorFlags
, $this->flags
);
683 $this->flags |
= $flag;
686 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
687 if ( ( $flag & self
::DBO_IGNORE
) ) {
688 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
691 if ( $remember === self
::REMEMBER_PRIOR
) {
692 array_push( $this->priorFlags
, $this->flags
);
694 $this->flags
&= ~
$flag;
697 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
698 if ( !$this->priorFlags
) {
702 if ( $state === self
::RESTORE_INITIAL
) {
703 $this->flags
= reset( $this->priorFlags
);
704 $this->priorFlags
= [];
706 $this->flags
= array_pop( $this->priorFlags
);
710 public function getFlag( $flag ) {
711 return !!( $this->flags
& $flag );
715 * @param string $name Class field name
717 * @deprecated Since 1.28
719 public function getProperty( $name ) {
723 public function getDomainID() {
724 return $this->currentDomain
->getId();
727 final public function getWikiID() {
728 return $this->getDomainID();
732 * Get information about an index into an object
733 * @param string $table Table name
734 * @param string $index Index name
735 * @param string $fname Calling function name
736 * @return mixed Database-specific index description class or false if the index does not exist
738 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
741 * Wrapper for addslashes()
743 * @param string $s String to be slashed.
744 * @return string Slashed string.
746 abstract function strencode( $s );
749 * Set a custom error handler for logging errors during database connection
751 protected function installErrorHandler() {
752 $this->phpError
= false;
753 $this->htmlErrors
= ini_set( 'html_errors', '0' );
754 set_error_handler( [ $this, 'connectionErrorLogger' ] );
758 * Restore the previous error handler and return the last PHP error for this DB
760 * @return bool|string
762 protected function restoreErrorHandler() {
763 restore_error_handler();
764 if ( $this->htmlErrors
!== false ) {
765 ini_set( 'html_errors', $this->htmlErrors
);
768 return $this->getLastPHPError();
772 * @return string|bool Last PHP error for this DB (typically connection errors)
774 protected function getLastPHPError() {
775 if ( $this->phpError
) {
776 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
777 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
786 * Error handler for logging errors during database connection
787 * This method should not be used outside of Database classes
790 * @param string $errstr
792 public function connectionErrorLogger( $errno, $errstr ) {
793 $this->phpError
= $errstr;
797 * Create a log context to pass to PSR-3 logger functions.
799 * @param array $extras Additional data to add to context
802 protected function getLogContext( array $extras = [] ) {
805 'db_server' => $this->server
,
806 'db_name' => $this->dbName
,
807 'db_user' => $this->user
,
813 public function close() {
815 if ( $this->trxLevel() ) {
816 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
819 $closed = $this->closeConnection();
822 $this->trxIdleCallbacks ||
823 $this->trxPreCommitCallbacks ||
824 $this->trxEndCallbacks
826 throw new RuntimeException( "Transaction callbacks still pending." );
830 $this->opened
= false;
836 * Make sure isOpen() returns true as a sanity check
838 * @throws DBUnexpectedError
840 protected function assertOpen() {
841 if ( !$this->isOpen() ) {
842 throw new DBUnexpectedError( $this, "DB connection was already closed." );
847 * Closes underlying database connection
849 * @return bool Whether connection was closed successfully
851 abstract protected function closeConnection();
853 public function reportConnectionError( $error = 'Unknown error' ) {
854 $myError = $this->lastError();
860 throw new DBConnectionError( $this, $error );
864 * The DBMS-dependent part of query()
866 * @param string $sql SQL query.
867 * @return ResultWrapper|bool Result object to feed to fetchObject,
868 * fetchRow, ...; or false on failure
870 abstract protected function doQuery( $sql );
873 * Determine whether a query writes to the DB.
874 * Should return true if unsure.
879 protected function isWriteQuery( $sql ) {
881 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
886 * @return string|null
888 protected function getQueryVerb( $sql ) {
889 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
893 * Determine whether a SQL statement is sensitive to isolation level.
894 * A SQL statement is considered transactable if its result could vary
895 * depending on the transaction isolation level. Operational commands
896 * such as 'SET' and 'SHOW' are not considered to be transactable.
901 protected function isTransactableQuery( $sql ) {
903 $this->getQueryVerb( $sql ),
904 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
910 * @param string $sql A SQL query
911 * @return bool Whether $sql is SQL for TEMPORARY table operation
913 protected function registerTempTableOperation( $sql ) {
915 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
919 $this->sessionTempTables
[$matches[1]] = 1;
922 } elseif ( preg_match(
923 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
927 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
928 unset( $this->sessionTempTables
[$matches[1]] );
931 } elseif ( preg_match(
932 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
936 return isset( $this->sessionTempTables
[$matches[1]] );
937 } elseif ( preg_match(
938 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
942 return isset( $this->sessionTempTables
[$matches[1]] );
948 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
949 $priorWritesPending = $this->writesOrCallbacksPending();
950 $this->lastQuery
= $sql;
952 $isWrite = $this->isWriteQuery( $sql );
954 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
956 $isNonTempWrite = false;
960 if ( $this->getLBInfo( 'replica' ) === true ) {
963 'Write operations are not allowed on replica database connections.'
966 # In theory, non-persistent writes are allowed in read-only mode, but due to things
967 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
968 $reason = $this->getReadOnlyReason();
969 if ( $reason !== false ) {
970 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
972 # Set a flag indicating that writes have been done
973 $this->lastWriteTime
= microtime( true );
976 # Add trace comment to the begin of the sql string, right after the operator.
977 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
978 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
980 # Start implicit transactions that wrap the request if DBO_TRX is enabled
981 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
982 && $this->isTransactableQuery( $sql )
984 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
985 $this->trxAutomatic
= true;
988 # Keep track of whether the transaction has write queries pending
989 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
990 $this->trxDoneWrites
= true;
991 $this->trxProfiler
->transactionWritingIn(
992 $this->server
, $this->dbName
, $this->trxShortId
);
995 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
996 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
999 # Avoid fatals if close() was called
1000 $this->assertOpen();
1002 # Send the query to the server
1003 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1005 # Try reconnecting if the connection was lost
1006 if ( false === $ret && $this->wasErrorReissuable() ) {
1007 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1008 # Stash the last error values before anything might clear them
1009 $lastError = $this->lastError();
1010 $lastErrno = $this->lastErrno();
1011 # Update state tracking to reflect transaction loss due to disconnection
1012 $this->handleSessionLoss();
1013 if ( $this->reconnect() ) {
1014 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1015 $params = [ 'dbserver' => $this->getServer() ];
1016 $this->connLogger
->warning( $msg, $params );
1017 $this->queryLogger
->warning( $msg, $params +
1018 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1020 if ( $recoverable ) {
1021 # Should be safe to silently retry the query
1022 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1024 # Callers may catch the exception and continue to use the DB
1025 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1028 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1029 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1033 if ( false === $ret ) {
1034 # Deadlocks cause the entire transaction to abort, not just the statement.
1035 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1036 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1037 if ( $this->wasDeadlock() ) {
1038 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1039 $tempIgnore = false; // not recoverable
1041 # Update state tracking to reflect transaction loss
1042 $this->handleSessionLoss();
1045 $this->reportQueryError(
1046 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1049 $res = $this->resultObject( $ret );
1055 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1057 * @param string $sql Original SQL query
1058 * @param string $commentedSql SQL query with debugging/trace comment
1059 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1060 * @param string $fname Name of the calling function
1061 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1062 * object for a successful read query, or false on failure
1064 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1065 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1066 # generalizeSQL() will probably cut down the query to reasonable
1067 # logging size most of the time. The substr is really just a sanity check.
1069 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1071 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1074 # Include query transaction state
1075 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1077 $startTime = microtime( true );
1078 if ( $this->profiler
) {
1079 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1081 $this->affectedRowCount
= null;
1082 $ret = $this->doQuery( $commentedSql );
1083 $this->affectedRowCount
= $this->affectedRows();
1084 if ( $this->profiler
) {
1085 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1087 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1089 unset( $queryProfSection ); // profile out (if set)
1091 if ( $ret !== false ) {
1092 $this->lastPing
= $startTime;
1093 if ( $isWrite && $this->trxLevel
) {
1094 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1095 $this->trxWriteCallers
[] = $fname;
1099 if ( $sql === self
::PING_QUERY
) {
1100 $this->rttEstimate
= $queryRuntime;
1103 $this->trxProfiler
->recordQueryCompletion(
1104 $queryProf, $startTime, $isWrite, $this->affectedRows()
1106 $this->queryLogger
->debug( $sql, [
1108 'master' => $isMaster,
1109 'runtime' => $queryRuntime,
1116 * Update the estimated run-time of a query, not counting large row lock times
1118 * LoadBalancer can be set to rollback transactions that will create huge replication
1119 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1120 * queries, like inserting a row can take a long time due to row locking. This method
1121 * uses some simple heuristics to discount those cases.
1123 * @param string $sql A SQL write query
1124 * @param float $runtime Total runtime, including RTT
1125 * @param int $affected Affected row count
1127 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1128 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1129 $indicativeOfReplicaRuntime = true;
1130 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1131 $verb = $this->getQueryVerb( $sql );
1132 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1133 if ( $verb === 'INSERT' ) {
1134 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1135 } elseif ( $verb === 'REPLACE' ) {
1136 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1140 $this->trxWriteDuration +
= $runtime;
1141 $this->trxWriteQueryCount +
= 1;
1142 $this->trxWriteAffectedRows +
= $affected;
1143 if ( $indicativeOfReplicaRuntime ) {
1144 $this->trxWriteAdjDuration +
= $runtime;
1145 $this->trxWriteAdjQueryCount +
= 1;
1150 * Determine whether or not it is safe to retry queries after a database
1151 * connection is lost
1153 * @param string $sql SQL query
1154 * @param bool $priorWritesPending Whether there is a transaction open with
1155 * possible write queries or transaction pre-commit/idle callbacks
1156 * waiting on it to finish.
1157 * @return bool True if it is safe to retry the query, false otherwise
1159 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1160 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1161 # Dropped connections also mean that named locks are automatically released.
1162 # Only allow error suppression in autocommit mode or when the lost transaction
1163 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1164 if ( $this->namedLocksHeld
) {
1165 return false; // possible critical section violation
1166 } elseif ( $sql === 'COMMIT' ) {
1167 return !$priorWritesPending; // nothing written anyway? (T127428)
1168 } elseif ( $sql === 'ROLLBACK' ) {
1169 return true; // transaction lost...which is also what was requested :)
1170 } elseif ( $this->explicitTrxActive() ) {
1171 return false; // don't drop atomocity
1172 } elseif ( $priorWritesPending ) {
1173 return false; // prior writes lost from implicit transaction
1180 * Clean things up after transaction loss due to disconnection
1182 * @return null|Exception
1184 private function handleSessionLoss() {
1185 $this->trxLevel
= 0;
1186 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1187 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1188 $this->sessionTempTables
= [];
1189 $this->namedLocksHeld
= [];
1191 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1194 // Handle callbacks in trxEndCallbacks
1195 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1196 } catch ( Exception
$ex ) {
1197 // Already logged; move on...
1201 // Handle callbacks in trxRecurringCallbacks
1202 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1203 } catch ( Exception
$ex ) {
1204 // Already logged; move on...
1212 * Checks whether the cause of the error is detected to be a timeout.
1214 * It returns false by default, and not all engines support detecting this yet.
1215 * If this returns false, it will be treated as a generic query error.
1217 * @param string $error Error text
1218 * @param int $errno Error number
1221 protected function wasQueryTimeout( $error, $errno ) {
1225 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1226 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1227 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1229 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1230 $this->queryLogger
->error(
1231 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1232 $this->getLogContext( [
1233 'method' => __METHOD__
,
1236 'sql1line' => $sql1line,
1240 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1241 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1242 if ( $wasQueryTimeout ) {
1243 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1245 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1250 public function freeResult( $res ) {
1253 public function selectField(
1254 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1256 if ( $var === '*' ) { // sanity
1257 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1260 if ( !is_array( $options ) ) {
1261 $options = [ $options ];
1264 $options['LIMIT'] = 1;
1266 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1267 if ( $res === false ||
!$this->numRows( $res ) ) {
1271 $row = $this->fetchRow( $res );
1273 if ( $row !== false ) {
1274 return reset( $row );
1280 public function selectFieldValues(
1281 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1283 if ( $var === '*' ) { // sanity
1284 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1285 } elseif ( !is_string( $var ) ) { // sanity
1286 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1289 if ( !is_array( $options ) ) {
1290 $options = [ $options ];
1293 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1294 if ( $res === false ) {
1299 foreach ( $res as $row ) {
1300 $values[] = $row->$var;
1307 * Returns an optional USE INDEX clause to go after the table, and a
1308 * string to go at the end of the query.
1310 * @param array $options Associative array of options to be turned into
1311 * an SQL query, valid keys are listed in the function.
1313 * @see Database::select()
1315 protected function makeSelectOptions( $options ) {
1316 $preLimitTail = $postLimitTail = '';
1321 foreach ( $options as $key => $option ) {
1322 if ( is_numeric( $key ) ) {
1323 $noKeyOptions[$option] = true;
1327 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1329 $preLimitTail .= $this->makeOrderBy( $options );
1331 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1332 $postLimitTail .= ' FOR UPDATE';
1335 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1336 $postLimitTail .= ' LOCK IN SHARE MODE';
1339 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1340 $startOpts .= 'DISTINCT';
1343 # Various MySQL extensions
1344 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1345 $startOpts .= ' /*! STRAIGHT_JOIN */';
1348 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1349 $startOpts .= ' HIGH_PRIORITY';
1352 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1353 $startOpts .= ' SQL_BIG_RESULT';
1356 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1357 $startOpts .= ' SQL_BUFFER_RESULT';
1360 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1361 $startOpts .= ' SQL_SMALL_RESULT';
1364 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1365 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1368 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1369 $startOpts .= ' SQL_CACHE';
1372 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1373 $startOpts .= ' SQL_NO_CACHE';
1376 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1377 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1381 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1382 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1387 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1391 * Returns an optional GROUP BY with an optional HAVING
1393 * @param array $options Associative array of options
1395 * @see Database::select()
1398 protected function makeGroupByWithHaving( $options ) {
1400 if ( isset( $options['GROUP BY'] ) ) {
1401 $gb = is_array( $options['GROUP BY'] )
1402 ?
implode( ',', $options['GROUP BY'] )
1403 : $options['GROUP BY'];
1404 $sql .= ' GROUP BY ' . $gb;
1406 if ( isset( $options['HAVING'] ) ) {
1407 $having = is_array( $options['HAVING'] )
1408 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1409 : $options['HAVING'];
1410 $sql .= ' HAVING ' . $having;
1417 * Returns an optional ORDER BY
1419 * @param array $options Associative array of options
1421 * @see Database::select()
1424 protected function makeOrderBy( $options ) {
1425 if ( isset( $options['ORDER BY'] ) ) {
1426 $ob = is_array( $options['ORDER BY'] )
1427 ?
implode( ',', $options['ORDER BY'] )
1428 : $options['ORDER BY'];
1430 return ' ORDER BY ' . $ob;
1436 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1437 $options = [], $join_conds = [] ) {
1438 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1440 return $this->query( $sql, $fname );
1443 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1444 $options = [], $join_conds = []
1446 if ( is_array( $vars ) ) {
1447 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1450 $options = (array)$options;
1451 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1452 ?
$options['USE INDEX']
1455 isset( $options['IGNORE INDEX'] ) &&
1456 is_array( $options['IGNORE INDEX'] )
1458 ?
$options['IGNORE INDEX']
1461 if ( is_array( $table ) ) {
1463 $this->tableNamesWithIndexClauseOrJOIN(
1464 $table, $useIndexes, $ignoreIndexes, $join_conds );
1465 } elseif ( $table != '' ) {
1467 $this->tableNamesWithIndexClauseOrJOIN(
1468 [ $table ], $useIndexes, $ignoreIndexes, [] );
1473 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1474 $this->makeSelectOptions( $options );
1476 if ( is_array( $conds ) ) {
1477 $conds = $this->makeList( $conds, self
::LIST_AND
);
1480 if ( $conds === null ||
$conds === false ) {
1481 $this->queryLogger
->warning(
1485 . ' with incorrect parameters: $conds must be a string or an array'
1490 if ( $conds === '' ) {
1491 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1492 } elseif ( is_string( $conds ) ) {
1493 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1494 "WHERE $conds $preLimitTail";
1496 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1499 if ( isset( $options['LIMIT'] ) ) {
1500 $sql = $this->limitResult( $sql, $options['LIMIT'],
1501 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1503 $sql = "$sql $postLimitTail";
1505 if ( isset( $options['EXPLAIN'] ) ) {
1506 $sql = 'EXPLAIN ' . $sql;
1512 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1513 $options = [], $join_conds = []
1515 $options = (array)$options;
1516 $options['LIMIT'] = 1;
1517 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1519 if ( $res === false ) {
1523 if ( !$this->numRows( $res ) ) {
1527 $obj = $this->fetchObject( $res );
1532 public function estimateRowCount(
1533 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1536 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1539 $row = $this->fetchRow( $res );
1540 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1546 public function selectRowCount(
1547 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1550 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1551 // The identifier quotes is primarily for MSSQL.
1552 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1553 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1554 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1557 $row = $this->fetchRow( $res );
1558 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1565 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1566 * It's only slightly flawed. Don't use for anything important.
1568 * @param string $sql A SQL Query
1572 protected static function generalizeSQL( $sql ) {
1573 # This does the same as the regexp below would do, but in such a way
1574 # as to avoid crashing php on some large strings.
1575 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1577 $sql = str_replace( "\\\\", '', $sql );
1578 $sql = str_replace( "\\'", '', $sql );
1579 $sql = str_replace( "\\\"", '', $sql );
1580 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1581 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1583 # All newlines, tabs, etc replaced by single space
1584 $sql = preg_replace( '/\s+/', ' ', $sql );
1587 # except the ones surrounded by characters, e.g. l10n
1588 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1589 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1594 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1595 $info = $this->fieldInfo( $table, $field );
1600 public function indexExists( $table, $index, $fname = __METHOD__
) {
1601 if ( !$this->tableExists( $table ) ) {
1605 $info = $this->indexInfo( $table, $index, $fname );
1606 if ( is_null( $info ) ) {
1609 return $info !== false;
1613 public function tableExists( $table, $fname = __METHOD__
) {
1614 $tableRaw = $this->tableName( $table, 'raw' );
1615 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1616 return true; // already known to exist
1619 $table = $this->tableName( $table );
1620 $ignoreErrors = true;
1621 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1626 public function indexUnique( $table, $index ) {
1627 $indexInfo = $this->indexInfo( $table, $index );
1629 if ( !$indexInfo ) {
1633 return !$indexInfo[0]->Non_unique
;
1637 * Helper for Database::insert().
1639 * @param array $options
1642 protected function makeInsertOptions( $options ) {
1643 return implode( ' ', $options );
1646 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1647 # No rows to insert, easy just return now
1648 if ( !count( $a ) ) {
1652 $table = $this->tableName( $table );
1654 if ( !is_array( $options ) ) {
1655 $options = [ $options ];
1659 if ( isset( $options['fileHandle'] ) ) {
1660 $fh = $options['fileHandle'];
1662 $options = $this->makeInsertOptions( $options );
1664 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1666 $keys = array_keys( $a[0] );
1669 $keys = array_keys( $a );
1672 $sql = 'INSERT ' . $options .
1673 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1677 foreach ( $a as $row ) {
1683 $sql .= '(' . $this->makeList( $row ) . ')';
1686 $sql .= '(' . $this->makeList( $a ) . ')';
1689 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1691 } elseif ( $fh !== null ) {
1695 return (bool)$this->query( $sql, $fname );
1699 * Make UPDATE options array for Database::makeUpdateOptions
1701 * @param array $options
1704 protected function makeUpdateOptionsArray( $options ) {
1705 if ( !is_array( $options ) ) {
1706 $options = [ $options ];
1711 if ( in_array( 'IGNORE', $options ) ) {
1719 * Make UPDATE options for the Database::update function
1721 * @param array $options The options passed to Database::update
1724 protected function makeUpdateOptions( $options ) {
1725 $opts = $this->makeUpdateOptionsArray( $options );
1727 return implode( ' ', $opts );
1730 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1731 $table = $this->tableName( $table );
1732 $opts = $this->makeUpdateOptions( $options );
1733 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1735 if ( $conds !== [] && $conds !== '*' ) {
1736 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1739 return (bool)$this->query( $sql, $fname );
1742 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1743 if ( !is_array( $a ) ) {
1744 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1750 foreach ( $a as $field => $value ) {
1752 if ( $mode == self
::LIST_AND
) {
1754 } elseif ( $mode == self
::LIST_OR
) {
1763 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1764 $list .= "($value)";
1765 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1768 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1770 // Remove null from array to be handled separately if found
1771 $includeNull = false;
1772 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1773 $includeNull = true;
1774 unset( $value[$nullKey] );
1776 if ( count( $value ) == 0 && !$includeNull ) {
1777 throw new InvalidArgumentException(
1778 __METHOD__
. ": empty input for field $field" );
1779 } elseif ( count( $value ) == 0 ) {
1780 // only check if $field is null
1781 $list .= "$field IS NULL";
1783 // IN clause contains at least one valid element
1784 if ( $includeNull ) {
1785 // Group subconditions to ensure correct precedence
1788 if ( count( $value ) == 1 ) {
1789 // Special-case single values, as IN isn't terribly efficient
1790 // Don't necessarily assume the single key is 0; we don't
1791 // enforce linear numeric ordering on other arrays here.
1792 $value = array_values( $value )[0];
1793 $list .= $field . " = " . $this->addQuotes( $value );
1795 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1797 // if null present in array, append IS NULL
1798 if ( $includeNull ) {
1799 $list .= " OR $field IS NULL)";
1802 } elseif ( $value === null ) {
1803 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1804 $list .= "$field IS ";
1805 } elseif ( $mode == self
::LIST_SET
) {
1806 $list .= "$field = ";
1811 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1813 $list .= "$field = ";
1815 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1822 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1825 foreach ( $data as $base => $sub ) {
1826 if ( count( $sub ) ) {
1827 $conds[] = $this->makeList(
1828 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1834 return $this->makeList( $conds, self
::LIST_OR
);
1836 // Nothing to search for...
1841 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1845 public function bitNot( $field ) {
1849 public function bitAnd( $fieldLeft, $fieldRight ) {
1850 return "($fieldLeft & $fieldRight)";
1853 public function bitOr( $fieldLeft, $fieldRight ) {
1854 return "($fieldLeft | $fieldRight)";
1857 public function buildConcat( $stringList ) {
1858 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1861 public function buildGroupConcatField(
1862 $delim, $table, $field, $conds = '', $join_conds = []
1864 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1866 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1869 public function buildSubstring( $input, $startPosition, $length = null ) {
1870 $this->assertBuildSubstringParams( $startPosition, $length );
1871 $functionBody = "$input FROM $startPosition";
1872 if ( $length !== null ) {
1873 $functionBody .= " FOR $length";
1875 return 'SUBSTRING(' . $functionBody . ')';
1879 * Check type and bounds for parameters to self::buildSubstring()
1881 * All supported databases have substring functions that behave the same for
1882 * positive $startPosition and non-negative $length, but behaviors differ when
1883 * given 0 or negative $startPosition or negative $length. The simplest
1884 * solution to that is to just forbid those values.
1886 * @param int $startPosition
1887 * @param int|null $length
1890 protected function assertBuildSubstringParams( $startPosition, $length ) {
1891 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
1892 throw new InvalidArgumentException(
1893 '$startPosition must be a positive integer'
1896 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
1897 throw new InvalidArgumentException(
1898 '$length must be null or an integer greater than or equal to 0'
1903 public function buildStringCast( $field ) {
1907 public function buildIntegerCast( $field ) {
1908 return 'CAST( ' . $field . ' AS INTEGER )';
1911 public function databasesAreIndependent() {
1915 public function selectDB( $db ) {
1916 # Stub. Shouldn't cause serious problems if it's not overridden, but
1917 # if your database engine supports a concept similar to MySQL's
1918 # databases you may as well.
1919 $this->dbName
= $db;
1924 public function getDBname() {
1925 return $this->dbName
;
1928 public function getServer() {
1929 return $this->server
;
1932 public function tableName( $name, $format = 'quoted' ) {
1933 # Skip the entire process when we have a string quoted on both ends.
1934 # Note that we check the end so that we will still quote any use of
1935 # use of `database`.table. But won't break things if someone wants
1936 # to query a database table with a dot in the name.
1937 if ( $this->isQuotedIdentifier( $name ) ) {
1941 # Lets test for any bits of text that should never show up in a table
1942 # name. Basically anything like JOIN or ON which are actually part of
1943 # SQL queries, but may end up inside of the table value to combine
1944 # sql. Such as how the API is doing.
1945 # Note that we use a whitespace test rather than a \b test to avoid
1946 # any remote case where a word like on may be inside of a table name
1947 # surrounded by symbols which may be considered word breaks.
1948 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1952 # Split database and table into proper variables.
1953 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1955 # Quote $table and apply the prefix if not quoted.
1956 # $tableName might be empty if this is called from Database::replaceVars()
1957 $tableName = "{$prefix}{$table}";
1958 if ( $format === 'quoted'
1959 && !$this->isQuotedIdentifier( $tableName )
1960 && $tableName !== ''
1962 $tableName = $this->addIdentifierQuotes( $tableName );
1965 # Quote $schema and $database and merge them with the table name if needed
1966 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1967 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1973 * Get the table components needed for a query given the currently selected database
1975 * @param string $name Table name in the form of db.schema.table, db.table, or table
1976 * @return array (DB name or "" for default, schema name, table prefix, table name)
1978 protected function qualifiedTableComponents( $name ) {
1979 # We reverse the explode so that database.table and table both output the correct table.
1980 $dbDetails = explode( '.', $name, 3 );
1981 if ( count( $dbDetails ) == 3 ) {
1982 list( $database, $schema, $table ) = $dbDetails;
1983 # We don't want any prefix added in this case
1985 } elseif ( count( $dbDetails ) == 2 ) {
1986 list( $database, $table ) = $dbDetails;
1987 # We don't want any prefix added in this case
1989 # In dbs that support it, $database may actually be the schema
1990 # but that doesn't affect any of the functionality here
1993 list( $table ) = $dbDetails;
1994 if ( isset( $this->tableAliases
[$table] ) ) {
1995 $database = $this->tableAliases
[$table]['dbname'];
1996 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1997 ?
$this->tableAliases
[$table]['schema']
1999 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2000 ?
$this->tableAliases
[$table]['prefix']
2001 : $this->tablePrefix
;
2004 $schema = $this->schema
; # Default schema
2005 $prefix = $this->tablePrefix
; # Default prefix
2009 return [ $database, $schema, $prefix, $table ];
2013 * @param string|null $namespace Database or schema
2014 * @param string $relation Name of table, view, sequence, etc...
2015 * @param string $format One of (raw, quoted)
2016 * @return string Relation name with quoted and merged $namespace as needed
2018 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2019 if ( strlen( $namespace ) ) {
2020 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2021 $namespace = $this->addIdentifierQuotes( $namespace );
2023 $relation = $namespace . '.' . $relation;
2029 public function tableNames() {
2030 $inArray = func_get_args();
2033 foreach ( $inArray as $name ) {
2034 $retVal[$name] = $this->tableName( $name );
2040 public function tableNamesN() {
2041 $inArray = func_get_args();
2044 foreach ( $inArray as $name ) {
2045 $retVal[] = $this->tableName( $name );
2052 * Get an aliased table name
2053 * e.g. tableName AS newTableName
2055 * @param string $name Table name, see tableName()
2056 * @param string|bool $alias Alias (optional)
2057 * @return string SQL name for aliased table. Will not alias a table to its own name
2059 protected function tableNameWithAlias( $name, $alias = false ) {
2060 if ( !$alias ||
$alias == $name ) {
2061 return $this->tableName( $name );
2063 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2068 * Gets an array of aliased table names
2070 * @param array $tables [ [alias] => table ]
2071 * @return string[] See tableNameWithAlias()
2073 protected function tableNamesWithAlias( $tables ) {
2075 foreach ( $tables as $alias => $table ) {
2076 if ( is_numeric( $alias ) ) {
2079 $retval[] = $this->tableNameWithAlias( $table, $alias );
2086 * Get an aliased field name
2087 * e.g. fieldName AS newFieldName
2089 * @param string $name Field name
2090 * @param string|bool $alias Alias (optional)
2091 * @return string SQL name for aliased field. Will not alias a field to its own name
2093 protected function fieldNameWithAlias( $name, $alias = false ) {
2094 if ( !$alias ||
(string)$alias === (string)$name ) {
2097 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2102 * Gets an array of aliased field names
2104 * @param array $fields [ [alias] => field ]
2105 * @return string[] See fieldNameWithAlias()
2107 protected function fieldNamesWithAlias( $fields ) {
2109 foreach ( $fields as $alias => $field ) {
2110 if ( is_numeric( $alias ) ) {
2113 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2120 * Get the aliased table name clause for a FROM clause
2121 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2123 * @param array $tables ( [alias] => table )
2124 * @param array $use_index Same as for select()
2125 * @param array $ignore_index Same as for select()
2126 * @param array $join_conds Same as for select()
2129 protected function tableNamesWithIndexClauseOrJOIN(
2130 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2134 $use_index = (array)$use_index;
2135 $ignore_index = (array)$ignore_index;
2136 $join_conds = (array)$join_conds;
2138 foreach ( $tables as $alias => $table ) {
2139 if ( !is_string( $alias ) ) {
2140 // No alias? Set it equal to the table name
2144 if ( is_array( $table ) ) {
2145 // A parenthesized group
2146 if ( count( $table ) > 1 ) {
2148 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2152 $innerTable = reset( $table );
2153 $innerAlias = key( $table );
2154 $joinedTable = $this->tableNameWithAlias(
2156 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2160 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2163 // Is there a JOIN clause for this table?
2164 if ( isset( $join_conds[$alias] ) ) {
2165 list( $joinType, $conds ) = $join_conds[$alias];
2166 $tableClause = $joinType;
2167 $tableClause .= ' ' . $joinedTable;
2168 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2169 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2171 $tableClause .= ' ' . $use;
2174 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2175 $ignore = $this->ignoreIndexClause(
2176 implode( ',', (array)$ignore_index[$alias] ) );
2177 if ( $ignore != '' ) {
2178 $tableClause .= ' ' . $ignore;
2181 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2183 $tableClause .= ' ON (' . $on . ')';
2186 $retJOIN[] = $tableClause;
2187 } elseif ( isset( $use_index[$alias] ) ) {
2188 // Is there an INDEX clause for this table?
2189 $tableClause = $joinedTable;
2190 $tableClause .= ' ' . $this->useIndexClause(
2191 implode( ',', (array)$use_index[$alias] )
2194 $ret[] = $tableClause;
2195 } elseif ( isset( $ignore_index[$alias] ) ) {
2196 // Is there an INDEX clause for this table?
2197 $tableClause = $joinedTable;
2198 $tableClause .= ' ' . $this->ignoreIndexClause(
2199 implode( ',', (array)$ignore_index[$alias] )
2202 $ret[] = $tableClause;
2204 $tableClause = $joinedTable;
2206 $ret[] = $tableClause;
2210 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2211 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2212 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2214 // Compile our final table clause
2215 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2219 * Allows for index remapping in queries where this is not consistent across DBMS
2221 * @param string $index
2224 protected function indexName( $index ) {
2225 return isset( $this->indexAliases
[$index] )
2226 ?
$this->indexAliases
[$index]
2230 public function addQuotes( $s ) {
2231 if ( $s instanceof Blob
) {
2234 if ( $s === null ) {
2236 } elseif ( is_bool( $s ) ) {
2239 # This will also quote numeric values. This should be harmless,
2240 # and protects against weird problems that occur when they really
2241 # _are_ strings such as article titles and string->number->string
2242 # conversion is not 1:1.
2243 return "'" . $this->strencode( $s ) . "'";
2248 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2249 * MySQL uses `backticks` while basically everything else uses double quotes.
2250 * Since MySQL is the odd one out here the double quotes are our generic
2251 * and we implement backticks in DatabaseMysqlBase.
2256 public function addIdentifierQuotes( $s ) {
2257 return '"' . str_replace( '"', '""', $s ) . '"';
2261 * Returns if the given identifier looks quoted or not according to
2262 * the database convention for quoting identifiers .
2264 * @note Do not use this to determine if untrusted input is safe.
2265 * A malicious user can trick this function.
2266 * @param string $name
2269 public function isQuotedIdentifier( $name ) {
2270 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2275 * @param string $escapeChar
2278 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2279 return str_replace( [ $escapeChar, '%', '_' ],
2280 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2284 public function buildLike() {
2285 $params = func_get_args();
2287 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2288 $params = $params[0];
2293 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2294 // may escape backslashes, creating problems of double escaping. The `
2295 // character has good cross-DBMS compatibility, avoiding special operators
2296 // in MS SQL like ^ and %
2299 foreach ( $params as $value ) {
2300 if ( $value instanceof LikeMatch
) {
2301 $s .= $value->toString();
2303 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2307 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2310 public function anyChar() {
2311 return new LikeMatch( '_' );
2314 public function anyString() {
2315 return new LikeMatch( '%' );
2318 public function nextSequenceValue( $seqName ) {
2323 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2324 * is only needed because a) MySQL must be as efficient as possible due to
2325 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2326 * which index to pick. Anyway, other databases might have different
2327 * indexes on a given table. So don't bother overriding this unless you're
2329 * @param string $index
2332 public function useIndexClause( $index ) {
2337 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2338 * is only needed because a) MySQL must be as efficient as possible due to
2339 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2340 * which index to pick. Anyway, other databases might have different
2341 * indexes on a given table. So don't bother overriding this unless you're
2343 * @param string $index
2346 public function ignoreIndexClause( $index ) {
2350 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2351 if ( count( $rows ) == 0 ) {
2356 if ( !is_array( reset( $rows ) ) ) {
2361 $this->startAtomic( $fname );
2362 $affectedRowCount = 0;
2363 foreach ( $rows as $row ) {
2364 // Delete rows which collide with this one
2365 $indexWhereClauses = [];
2366 foreach ( $uniqueIndexes as $index ) {
2367 $indexColumns = (array)$index;
2368 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2369 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2370 throw new DBUnexpectedError(
2372 'New record does not provide all values for unique key (' .
2373 implode( ', ', $indexColumns ) . ')'
2375 } elseif ( in_array( null, $indexRowValues, true ) ) {
2376 throw new DBUnexpectedError(
2378 'New record has a null value for unique key (' .
2379 implode( ', ', $indexColumns ) . ')'
2382 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2385 if ( $indexWhereClauses ) {
2386 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2387 $affectedRowCount +
= $this->affectedRows();
2390 // Now insert the row
2391 $this->insert( $table, $row, $fname );
2392 $affectedRowCount +
= $this->affectedRows();
2394 $this->endAtomic( $fname );
2395 $this->affectedRowCount
= $affectedRowCount;
2396 } catch ( Exception
$e ) {
2397 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2403 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2406 * @param string $table Table name
2407 * @param array|string $rows Row(s) to insert
2408 * @param string $fname Caller function name
2410 * @return ResultWrapper
2412 protected function nativeReplace( $table, $rows, $fname ) {
2413 $table = $this->tableName( $table );
2416 if ( !is_array( reset( $rows ) ) ) {
2420 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2423 foreach ( $rows as $row ) {
2430 $sql .= '(' . $this->makeList( $row ) . ')';
2433 return $this->query( $sql, $fname );
2436 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2439 if ( !count( $rows ) ) {
2440 return true; // nothing to do
2443 if ( !is_array( reset( $rows ) ) ) {
2447 if ( count( $uniqueIndexes ) ) {
2448 $clauses = []; // list WHERE clauses that each identify a single row
2449 foreach ( $rows as $row ) {
2450 foreach ( $uniqueIndexes as $index ) {
2451 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2452 $rowKey = []; // unique key to this row
2453 foreach ( $index as $column ) {
2454 $rowKey[$column] = $row[$column];
2456 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2459 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2464 $affectedRowCount = 0;
2466 $this->startAtomic( $fname );
2467 # Update any existing conflicting row(s)
2468 if ( $where !== false ) {
2469 $ok = $this->update( $table, $set, $where, $fname );
2470 $affectedRowCount +
= $this->affectedRows();
2474 # Now insert any non-conflicting row(s)
2475 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2476 $affectedRowCount +
= $this->affectedRows();
2477 $this->endAtomic( $fname );
2478 $this->affectedRowCount
= $affectedRowCount;
2479 } catch ( Exception
$e ) {
2480 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2487 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2491 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2494 $delTable = $this->tableName( $delTable );
2495 $joinTable = $this->tableName( $joinTable );
2496 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2497 if ( $conds != '*' ) {
2498 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2502 $this->query( $sql, $fname );
2505 public function textFieldSize( $table, $field ) {
2506 $table = $this->tableName( $table );
2507 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2508 $res = $this->query( $sql, __METHOD__
);
2509 $row = $this->fetchObject( $res );
2513 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2522 public function delete( $table, $conds, $fname = __METHOD__
) {
2524 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2527 $table = $this->tableName( $table );
2528 $sql = "DELETE FROM $table";
2530 if ( $conds != '*' ) {
2531 if ( is_array( $conds ) ) {
2532 $conds = $this->makeList( $conds, self
::LIST_AND
);
2534 $sql .= ' WHERE ' . $conds;
2537 return $this->query( $sql, $fname );
2540 final public function insertSelect(
2541 $destTable, $srcTable, $varMap, $conds,
2542 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2544 static $hints = [ 'NO_AUTO_COLUMNS' ];
2546 $insertOptions = (array)$insertOptions;
2547 $selectOptions = (array)$selectOptions;
2549 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2550 // For massive migrations with downtime, we don't want to select everything
2551 // into memory and OOM, so do all this native on the server side if possible.
2552 return $this->nativeInsertSelect(
2558 array_diff( $insertOptions, $hints ),
2564 return $this->nonNativeInsertSelect(
2570 array_diff( $insertOptions, $hints ),
2577 * @param array $insertOptions INSERT options
2578 * @param array $selectOptions SELECT options
2579 * @return bool Whether an INSERT SELECT with these options will be replication safe
2582 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2587 * Implementation of insertSelect() based on select() and insert()
2589 * @see IDatabase::insertSelect()
2591 * @param string $destTable
2592 * @param string|array $srcTable
2593 * @param array $varMap
2594 * @param array $conds
2595 * @param string $fname
2596 * @param array $insertOptions
2597 * @param array $selectOptions
2598 * @param array $selectJoinConds
2601 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2602 $fname = __METHOD__
,
2603 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2605 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2606 // on only the master (without needing row-based-replication). It also makes it easy to
2607 // know how big the INSERT is going to be.
2609 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2610 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2612 $selectOptions[] = 'FOR UPDATE';
2613 $res = $this->select(
2614 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2621 $affectedRowCount = 0;
2622 $this->startAtomic( $fname );
2625 foreach ( $res as $row ) {
2626 $rows[] = (array)$row;
2628 // Avoid inserts that are too huge
2629 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2630 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2634 $affectedRowCount +
= $this->affectedRows();
2638 if ( $rows && $ok ) {
2639 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2641 $affectedRowCount +
= $this->affectedRows();
2645 $this->endAtomic( $fname );
2646 $this->affectedRowCount
= $affectedRowCount;
2648 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2651 } catch ( Exception
$e ) {
2652 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2658 * Native server-side implementation of insertSelect() for situations where
2659 * we don't want to select everything into memory
2661 * @see IDatabase::insertSelect()
2662 * @param string $destTable
2663 * @param string|array $srcTable
2664 * @param array $varMap
2665 * @param array $conds
2666 * @param string $fname
2667 * @param array $insertOptions
2668 * @param array $selectOptions
2669 * @param array $selectJoinConds
2672 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2673 $fname = __METHOD__
,
2674 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2676 $destTable = $this->tableName( $destTable );
2678 if ( !is_array( $insertOptions ) ) {
2679 $insertOptions = [ $insertOptions ];
2682 $insertOptions = $this->makeInsertOptions( $insertOptions );
2684 $selectSql = $this->selectSQLText(
2686 array_values( $varMap ),
2693 $sql = "INSERT $insertOptions" .
2694 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2697 return $this->query( $sql, $fname );
2701 * Construct a LIMIT query with optional offset. This is used for query
2702 * pages. The SQL should be adjusted so that only the first $limit rows
2703 * are returned. If $offset is provided as well, then the first $offset
2704 * rows should be discarded, and the next $limit rows should be returned.
2705 * If the result of the query is not ordered, then the rows to be returned
2706 * are theoretically arbitrary.
2708 * $sql is expected to be a SELECT, if that makes a difference.
2710 * The version provided by default works in MySQL and SQLite. It will very
2711 * likely need to be overridden for most other DBMSes.
2713 * @param string $sql SQL query we will append the limit too
2714 * @param int $limit The SQL limit
2715 * @param int|bool $offset The SQL offset (default false)
2716 * @throws DBUnexpectedError
2719 public function limitResult( $sql, $limit, $offset = false ) {
2720 if ( !is_numeric( $limit ) ) {
2721 throw new DBUnexpectedError( $this,
2722 "Invalid non-numeric limit passed to limitResult()\n" );
2725 return "$sql LIMIT "
2726 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2730 public function unionSupportsOrderAndLimit() {
2731 return true; // True for almost every DB supported
2734 public function unionQueries( $sqls, $all ) {
2735 $glue = $all ?
') UNION ALL (' : ') UNION (';
2737 return '(' . implode( $glue, $sqls ) . ')';
2740 public function unionConditionPermutations(
2741 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2742 $options = [], $join_conds = []
2744 // First, build the Cartesian product of $permute_conds
2746 foreach ( $permute_conds as $field => $values ) {
2748 // Skip empty $values
2751 $values = array_unique( $values ); // For sanity
2753 foreach ( $conds as $cond ) {
2754 foreach ( $values as $value ) {
2755 $cond[$field] = $value;
2756 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2762 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2764 // If there's just one condition and no subordering, hand off to
2765 // selectSQLText directly.
2766 if ( count( $conds ) === 1 &&
2767 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2769 return $this->selectSQLText(
2770 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2774 // Otherwise, we need to pull out the order and limit to apply after
2775 // the union. Then build the SQL queries for each set of conditions in
2776 // $conds. Then union them together (using UNION ALL, because the
2777 // product *should* already be distinct).
2778 $orderBy = $this->makeOrderBy( $options );
2779 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2780 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2781 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2782 if ( !$this->unionSupportsOrderAndLimit() ) {
2783 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2785 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2786 $options['ORDER BY'] = $options['INNER ORDER BY'];
2788 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2789 // We need to increase the limit by the offset rather than
2790 // using the offset directly, otherwise it'll skip incorrectly
2791 // in the subqueries.
2792 $options['LIMIT'] = $limit +
$offset;
2793 unset( $options['OFFSET'] );
2798 foreach ( $conds as $cond ) {
2799 $sqls[] = $this->selectSQLText(
2800 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2803 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2804 if ( $limit !== null ) {
2805 $sql = $this->limitResult( $sql, $limit, $offset );
2811 public function conditional( $cond, $trueVal, $falseVal ) {
2812 if ( is_array( $cond ) ) {
2813 $cond = $this->makeList( $cond, self
::LIST_AND
);
2816 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2819 public function strreplace( $orig, $old, $new ) {
2820 return "REPLACE({$orig}, {$old}, {$new})";
2823 public function getServerUptime() {
2827 public function wasDeadlock() {
2831 public function wasLockTimeout() {
2835 public function wasErrorReissuable() {
2839 public function wasReadOnlyError() {
2844 * Do not use this method outside of Database/DBError classes
2846 * @param int|string $errno
2847 * @return bool Whether the given query error was a connection drop
2849 public function wasConnectionError( $errno ) {
2853 public function deadlockLoop() {
2854 $args = func_get_args();
2855 $function = array_shift( $args );
2856 $tries = self
::DEADLOCK_TRIES
;
2858 $this->begin( __METHOD__
);
2861 /** @var Exception $e */
2865 $retVal = call_user_func_array( $function, $args );
2867 } catch ( DBQueryError
$e ) {
2868 if ( $this->wasDeadlock() ) {
2869 // Retry after a randomized delay
2870 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2872 // Throw the error back up
2876 } while ( --$tries > 0 );
2878 if ( $tries <= 0 ) {
2879 // Too many deadlocks; give up
2880 $this->rollback( __METHOD__
);
2883 $this->commit( __METHOD__
);
2889 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2890 # Real waits are implemented in the subclass.
2894 public function getReplicaPos() {
2899 public function getMasterPos() {
2904 public function serverIsReadOnly() {
2908 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2909 if ( !$this->trxLevel
) {
2910 throw new DBUnexpectedError( $this, "No transaction is active." );
2912 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2915 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2916 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2917 if ( !$this->trxLevel
) {
2918 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2922 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2923 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2924 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2925 // an implicit commit of all peer databases. This is true even if a transaction has
2926 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2927 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2929 // No transaction is active nor will start implicitly, so make one for this callback
2930 $this->startAtomic( __METHOD__
);
2932 call_user_func( $callback );
2933 $this->endAtomic( __METHOD__
);
2934 } catch ( Exception
$e ) {
2935 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2941 final public function setTransactionListener( $name, callable
$callback = null ) {
2943 $this->trxRecurringCallbacks
[$name] = $callback;
2945 unset( $this->trxRecurringCallbacks
[$name] );
2950 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2952 * This method should not be used outside of Database/LoadBalancer
2954 * @param bool $suppress
2957 final public function setTrxEndCallbackSuppression( $suppress ) {
2958 $this->trxEndCallbacksSuppressed
= $suppress;
2962 * Actually run and consume any "on transaction idle/resolution" callbacks.
2964 * This method should not be used outside of Database/LoadBalancer
2966 * @param int $trigger IDatabase::TRIGGER_* constant
2970 public function runOnTransactionIdleCallbacks( $trigger ) {
2971 if ( $this->trxEndCallbacksSuppressed
) {
2975 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2976 /** @var Exception $e */
2977 $e = null; // first exception
2978 do { // callbacks may add callbacks :)
2979 $callbacks = array_merge(
2980 $this->trxIdleCallbacks
,
2981 $this->trxEndCallbacks
// include "transaction resolution" callbacks
2983 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
2984 $this->trxEndCallbacks
= []; // consumed (recursion guard)
2985 foreach ( $callbacks as $callback ) {
2987 list( $phpCallback ) = $callback;
2988 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2989 call_user_func_array( $phpCallback, [ $trigger ] );
2991 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2993 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2995 } catch ( Exception
$ex ) {
2996 call_user_func( $this->errorLogger
, $ex );
2998 // Some callbacks may use startAtomic/endAtomic, so make sure
2999 // their transactions are ended so other callbacks don't fail
3000 if ( $this->trxLevel() ) {
3001 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3005 } while ( count( $this->trxIdleCallbacks
) );
3007 if ( $e instanceof Exception
) {
3008 throw $e; // re-throw any first exception
3013 * Actually run and consume any "on transaction pre-commit" callbacks.
3015 * This method should not be used outside of Database/LoadBalancer
3020 public function runOnTransactionPreCommitCallbacks() {
3021 $e = null; // first exception
3022 do { // callbacks may add callbacks :)
3023 $callbacks = $this->trxPreCommitCallbacks
;
3024 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3025 foreach ( $callbacks as $callback ) {
3027 list( $phpCallback ) = $callback;
3028 call_user_func( $phpCallback );
3029 } catch ( Exception
$ex ) {
3030 call_user_func( $this->errorLogger
, $ex );
3034 } while ( count( $this->trxPreCommitCallbacks
) );
3036 if ( $e instanceof Exception
) {
3037 throw $e; // re-throw any first exception
3042 * Actually run any "transaction listener" callbacks.
3044 * This method should not be used outside of Database/LoadBalancer
3046 * @param int $trigger IDatabase::TRIGGER_* constant
3050 public function runTransactionListenerCallbacks( $trigger ) {
3051 if ( $this->trxEndCallbacksSuppressed
) {
3055 /** @var Exception $e */
3056 $e = null; // first exception
3058 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3060 $phpCallback( $trigger, $this );
3061 } catch ( Exception
$ex ) {
3062 call_user_func( $this->errorLogger
, $ex );
3067 if ( $e instanceof Exception
) {
3068 throw $e; // re-throw any first exception
3072 final public function startAtomic( $fname = __METHOD__
) {
3073 if ( !$this->trxLevel
) {
3074 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3075 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3076 // in all changes being in one transaction to keep requests transactional.
3077 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3078 $this->trxAutomaticAtomic
= true;
3082 $this->trxAtomicLevels
[] = $fname;
3085 final public function endAtomic( $fname = __METHOD__
) {
3086 if ( !$this->trxLevel
) {
3087 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3089 if ( !$this->trxAtomicLevels ||
3090 array_pop( $this->trxAtomicLevels
) !== $fname
3092 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3095 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3096 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3100 final public function doAtomicSection( $fname, callable
$callback ) {
3101 $this->startAtomic( $fname );
3103 $res = call_user_func_array( $callback, [ $this, $fname ] );
3104 } catch ( Exception
$e ) {
3105 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3108 $this->endAtomic( $fname );
3113 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3114 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3115 if ( $this->trxLevel
) {
3116 if ( $this->trxAtomicLevels
) {
3117 $levels = implode( ', ', $this->trxAtomicLevels
);
3118 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3119 throw new DBUnexpectedError( $this, $msg );
3120 } elseif ( !$this->trxAutomatic
) {
3121 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3122 throw new DBUnexpectedError( $this, $msg );
3124 // @TODO: make this an exception at some point
3125 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3126 $this->queryLogger
->error( $msg );
3127 return; // join the main transaction set
3129 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3130 // @TODO: make this an exception at some point
3131 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3132 $this->queryLogger
->error( $msg );
3133 return; // let any writes be in the main transaction
3136 // Avoid fatals if close() was called
3137 $this->assertOpen();
3139 $this->doBegin( $fname );
3140 $this->trxTimestamp
= microtime( true );
3141 $this->trxFname
= $fname;
3142 $this->trxDoneWrites
= false;
3143 $this->trxAutomaticAtomic
= false;
3144 $this->trxAtomicLevels
= [];
3145 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3146 $this->trxWriteDuration
= 0.0;
3147 $this->trxWriteQueryCount
= 0;
3148 $this->trxWriteAffectedRows
= 0;
3149 $this->trxWriteAdjDuration
= 0.0;
3150 $this->trxWriteAdjQueryCount
= 0;
3151 $this->trxWriteCallers
= [];
3152 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3153 // Get an estimate of the replica DB lag before then, treating estimate staleness
3154 // as lag itself just to be safe
3155 $status = $this->getApproximateLagStatus();
3156 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3157 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3158 // caller will think its OK to muck around with the transaction just because startAtomic()
3159 // has not yet completed (e.g. setting trxAtomicLevels).
3160 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3164 * Issues the BEGIN command to the database server.
3166 * @see Database::begin()
3167 * @param string $fname
3169 protected function doBegin( $fname ) {
3170 $this->query( 'BEGIN', $fname );
3171 $this->trxLevel
= 1;
3174 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3175 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3176 // There are still atomic sections open. This cannot be ignored
3177 $levels = implode( ', ', $this->trxAtomicLevels
);
3178 throw new DBUnexpectedError(
3180 "$fname: Got COMMIT while atomic sections $levels are still open."
3184 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3185 if ( !$this->trxLevel
) {
3186 return; // nothing to do
3187 } elseif ( !$this->trxAutomatic
) {
3188 throw new DBUnexpectedError(
3190 "$fname: Flushing an explicit transaction, getting out of sync."
3194 if ( !$this->trxLevel
) {
3195 $this->queryLogger
->error(
3196 "$fname: No transaction to commit, something got out of sync." );
3197 return; // nothing to do
3198 } elseif ( $this->trxAutomatic
) {
3199 // @TODO: make this an exception at some point
3200 $msg = "$fname: Explicit commit of implicit transaction.";
3201 $this->queryLogger
->error( $msg );
3202 return; // wait for the main transaction set commit round
3206 // Avoid fatals if close() was called
3207 $this->assertOpen();
3209 $this->runOnTransactionPreCommitCallbacks();
3210 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3211 $this->doCommit( $fname );
3212 if ( $this->trxDoneWrites
) {
3213 $this->lastWriteTime
= microtime( true );
3214 $this->trxProfiler
->transactionWritingOut(
3219 $this->trxWriteAffectedRows
3223 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3224 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3228 * Issues the COMMIT command to the database server.
3230 * @see Database::commit()
3231 * @param string $fname
3233 protected function doCommit( $fname ) {
3234 if ( $this->trxLevel
) {
3235 $this->query( 'COMMIT', $fname );
3236 $this->trxLevel
= 0;
3240 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3241 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3242 if ( !$this->trxLevel
) {
3243 return; // nothing to do
3246 if ( !$this->trxLevel
) {
3247 $this->queryLogger
->error(
3248 "$fname: No transaction to rollback, something got out of sync." );
3249 return; // nothing to do
3250 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3251 throw new DBUnexpectedError(
3253 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3258 // Avoid fatals if close() was called
3259 $this->assertOpen();
3261 $this->doRollback( $fname );
3262 $this->trxAtomicLevels
= [];
3263 if ( $this->trxDoneWrites
) {
3264 $this->trxProfiler
->transactionWritingOut(
3271 $this->trxIdleCallbacks
= []; // clear
3272 $this->trxPreCommitCallbacks
= []; // clear
3274 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3275 } catch ( Exception
$e ) {
3276 // already logged; finish and let LoadBalancer move on during mass-rollback
3279 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3280 } catch ( Exception
$e ) {
3281 // already logged; let LoadBalancer move on during mass-rollback
3284 $this->affectedRowCount
= 0; // for the sake of consistency
3288 * Issues the ROLLBACK command to the database server.
3290 * @see Database::rollback()
3291 * @param string $fname
3293 protected function doRollback( $fname ) {
3294 if ( $this->trxLevel
) {
3295 # Disconnects cause rollback anyway, so ignore those errors
3296 $ignoreErrors = true;
3297 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3298 $this->trxLevel
= 0;
3302 public function flushSnapshot( $fname = __METHOD__
) {
3303 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3304 // This only flushes transactions to clear snapshots, not to write data
3305 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3306 throw new DBUnexpectedError(
3308 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3312 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3315 public function explicitTrxActive() {
3316 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3319 public function duplicateTableStructure(
3320 $oldName, $newName, $temporary = false, $fname = __METHOD__
3322 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3325 public function listTables( $prefix = null, $fname = __METHOD__
) {
3326 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3329 public function listViews( $prefix = null, $fname = __METHOD__
) {
3330 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3333 public function timestamp( $ts = 0 ) {
3334 $t = new ConvertibleTimestamp( $ts );
3335 // Let errors bubble up to avoid putting garbage in the DB
3336 return $t->getTimestamp( TS_MW
);
3339 public function timestampOrNull( $ts = null ) {
3340 if ( is_null( $ts ) ) {
3343 return $this->timestamp( $ts );
3347 public function affectedRows() {
3348 return ( $this->affectedRowCount
=== null )
3349 ?
$this->fetchAffectedRowCount() // default to driver value
3350 : $this->affectedRowCount
;
3354 * @return int Number of retrieved rows according to the driver
3356 abstract protected function fetchAffectedRowCount();
3359 * Take the result from a query, and wrap it in a ResultWrapper if
3360 * necessary. Boolean values are passed through as is, to indicate success
3361 * of write queries or failure.
3363 * Once upon a time, Database::query() returned a bare MySQL result
3364 * resource, and it was necessary to call this function to convert it to
3365 * a wrapper. Nowadays, raw database objects are never exposed to external
3366 * callers, so this is unnecessary in external code.
3368 * @param bool|ResultWrapper|resource|object $result
3369 * @return bool|ResultWrapper
3371 protected function resultObject( $result ) {
3374 } elseif ( $result instanceof ResultWrapper
) {
3376 } elseif ( $result === true ) {
3377 // Successful write query
3380 return new ResultWrapper( $this, $result );
3384 public function ping( &$rtt = null ) {
3385 // Avoid hitting the server if it was hit recently
3386 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3387 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3388 $rtt = $this->rttEstimate
;
3389 return true; // don't care about $rtt
3393 // This will reconnect if possible or return false if not
3394 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3395 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3396 $this->restoreFlags( self
::RESTORE_PRIOR
);
3399 $rtt = $this->rttEstimate
;
3406 * Close existing database connection and open a new connection
3408 * @return bool True if new connection is opened successfully, false if error
3410 protected function reconnect() {
3411 $this->closeConnection();
3412 $this->opened
= false;
3413 $this->conn
= false;
3415 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3416 $this->lastPing
= microtime( true );
3418 } catch ( DBConnectionError
$e ) {
3425 public function getSessionLagStatus() {
3426 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3430 * Get the replica DB lag when the current transaction started
3432 * This is useful when transactions might use snapshot isolation
3433 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3434 * is this lag plus transaction duration. If they don't, it is still
3435 * safe to be pessimistic. This returns null if there is no transaction.
3437 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3440 protected function getTransactionLagStatus() {
3441 return $this->trxLevel
3442 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3447 * Get a replica DB lag estimate for this server
3449 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3452 protected function getApproximateLagStatus() {
3454 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3455 'since' => microtime( true )
3460 * Merge the result of getSessionLagStatus() for several DBs
3461 * using the most pessimistic values to estimate the lag of
3462 * any data derived from them in combination
3464 * This is information is useful for caching modules
3466 * @see WANObjectCache::set()
3467 * @see WANObjectCache::getWithSetCallback()
3469 * @param IDatabase $db1
3470 * @param IDatabase $db2 [optional]
3471 * @return array Map of values:
3472 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3473 * - since: oldest UNIX timestamp of any of the DB lag estimates
3474 * - pending: whether any of the DBs have uncommitted changes
3478 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3479 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3480 foreach ( func_get_args() as $db ) {
3481 /** @var IDatabase $db */
3482 $status = $db->getSessionLagStatus();
3483 if ( $status['lag'] === false ) {
3484 $res['lag'] = false;
3485 } elseif ( $res['lag'] !== false ) {
3486 $res['lag'] = max( $res['lag'], $status['lag'] );
3488 $res['since'] = min( $res['since'], $status['since'] );
3489 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3495 public function getLag() {
3499 public function maxListLen() {
3503 public function encodeBlob( $b ) {
3507 public function decodeBlob( $b ) {
3508 if ( $b instanceof Blob
) {
3514 public function setSessionOptions( array $options ) {
3517 public function sourceFile(
3519 callable
$lineCallback = null,
3520 callable
$resultCallback = null,
3522 callable
$inputCallback = null
3524 Wikimedia\
suppressWarnings();
3525 $fp = fopen( $filename, 'r' );
3526 Wikimedia\restoreWarnings
();
3528 if ( false === $fp ) {
3529 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3533 $fname = __METHOD__
. "( $filename )";
3537 $error = $this->sourceStream(
3538 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3539 } catch ( Exception
$e ) {
3549 public function setSchemaVars( $vars ) {
3550 $this->schemaVars
= $vars;
3553 public function sourceStream(
3555 callable
$lineCallback = null,
3556 callable
$resultCallback = null,
3557 $fname = __METHOD__
,
3558 callable
$inputCallback = null
3560 $delimiterReset = new ScopedCallback(
3561 function ( $delimiter ) {
3562 $this->delimiter
= $delimiter;
3564 [ $this->delimiter
]
3568 while ( !feof( $fp ) ) {
3569 if ( $lineCallback ) {
3570 call_user_func( $lineCallback );
3573 $line = trim( fgets( $fp ) );
3575 if ( $line == '' ) {
3579 if ( '-' == $line[0] && '-' == $line[1] ) {
3587 $done = $this->streamStatementEnd( $cmd, $line );
3591 if ( $done ||
feof( $fp ) ) {
3592 $cmd = $this->replaceVars( $cmd );
3594 if ( $inputCallback ) {
3595 $callbackResult = call_user_func( $inputCallback, $cmd );
3597 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3598 $cmd = $callbackResult;
3603 $res = $this->query( $cmd, $fname );
3605 if ( $resultCallback ) {
3606 call_user_func( $resultCallback, $res, $this );
3609 if ( false === $res ) {
3610 $err = $this->lastError();
3612 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3619 ScopedCallback
::consume( $delimiterReset );
3624 * Called by sourceStream() to check if we've reached a statement end
3626 * @param string &$sql SQL assembled so far
3627 * @param string &$newLine New line about to be added to $sql
3628 * @return bool Whether $newLine contains end of the statement
3630 public function streamStatementEnd( &$sql, &$newLine ) {
3631 if ( $this->delimiter
) {
3633 $newLine = preg_replace(
3634 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3635 if ( $newLine != $prev ) {
3644 * Database independent variable replacement. Replaces a set of variables
3645 * in an SQL statement with their contents as given by $this->getSchemaVars().
3647 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3649 * - '{$var}' should be used for text and is passed through the database's
3651 * - `{$var}` should be used for identifiers (e.g. table and database names).
3652 * It is passed through the database's addIdentifierQuotes method which
3653 * can be overridden if the database uses something other than backticks.
3654 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3655 * database's tableName method.
3656 * - / *i* / passes the name that follows through the database's indexName method.
3657 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3658 * its use should be avoided. In 1.24 and older, string encoding was applied.
3660 * @param string $ins SQL statement to replace variables in
3661 * @return string The new SQL statement with variables replaced
3663 protected function replaceVars( $ins ) {
3664 $vars = $this->getSchemaVars();
3665 return preg_replace_callback(
3667 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3668 \'\{\$ (\w+) }\' | # 3. addQuotes
3669 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3670 /\*\$ (\w+) \*/ # 5. leave unencoded
3672 function ( $m ) use ( $vars ) {
3673 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3674 // check for both nonexistent keys *and* the empty string.
3675 if ( isset( $m[1] ) && $m[1] !== '' ) {
3676 if ( $m[1] === 'i' ) {
3677 return $this->indexName( $m[2] );
3679 return $this->tableName( $m[2] );
3681 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3682 return $this->addQuotes( $vars[$m[3]] );
3683 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3684 return $this->addIdentifierQuotes( $vars[$m[4]] );
3685 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3686 return $vars[$m[5]];
3696 * Get schema variables. If none have been set via setSchemaVars(), then
3697 * use some defaults from the current object.
3701 protected function getSchemaVars() {
3702 if ( $this->schemaVars
) {
3703 return $this->schemaVars
;
3705 return $this->getDefaultSchemaVars();
3710 * Get schema variables to use if none have been set via setSchemaVars().
3712 * Override this in derived classes to provide variables for tables.sql
3713 * and SQL patch files.
3717 protected function getDefaultSchemaVars() {
3721 public function lockIsFree( $lockName, $method ) {
3722 // RDBMs methods for checking named locks may or may not count this thread itself.
3723 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3724 // the behavior choosen by the interface for this method.
3725 return !isset( $this->namedLocksHeld
[$lockName] );
3728 public function lock( $lockName, $method, $timeout = 5 ) {
3729 $this->namedLocksHeld
[$lockName] = 1;
3734 public function unlock( $lockName, $method ) {
3735 unset( $this->namedLocksHeld
[$lockName] );
3740 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3741 if ( $this->writesOrCallbacksPending() ) {
3742 // This only flushes transactions to clear snapshots, not to write data
3743 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3744 throw new DBUnexpectedError(
3746 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3750 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3754 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3755 if ( $this->trxLevel() ) {
3756 // There is a good chance an exception was thrown, causing any early return
3757 // from the caller. Let any error handler get a chance to issue rollback().
3758 // If there isn't one, let the error bubble up and trigger server-side rollback.
3759 $this->onTransactionResolution(
3760 function () use ( $lockKey, $fname ) {
3761 $this->unlock( $lockKey, $fname );
3766 $this->unlock( $lockKey, $fname );
3770 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3775 public function namedLocksEnqueue() {
3779 public function tableLocksHaveTransactionScope() {
3783 final public function lockTables( array $read, array $write, $method ) {
3784 if ( $this->writesOrCallbacksPending() ) {
3785 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3788 if ( $this->tableLocksHaveTransactionScope() ) {
3789 $this->startAtomic( $method );
3792 return $this->doLockTables( $read, $write, $method );
3796 * Helper function for lockTables() that handles the actual table locking
3798 * @param array $read Array of tables to lock for read access
3799 * @param array $write Array of tables to lock for write access
3800 * @param string $method Name of caller
3803 protected function doLockTables( array $read, array $write, $method ) {
3807 final public function unlockTables( $method ) {
3808 if ( $this->tableLocksHaveTransactionScope() ) {
3809 $this->endAtomic( $method );
3811 return true; // locks released on COMMIT/ROLLBACK
3814 return $this->doUnlockTables( $method );
3818 * Helper function for unlockTables() that handles the actual table unlocking
3820 * @param string $method Name of caller
3823 protected function doUnlockTables( $method ) {
3829 * @param string $tableName
3830 * @param string $fName
3831 * @return bool|ResultWrapper
3834 public function dropTable( $tableName, $fName = __METHOD__
) {
3835 if ( !$this->tableExists( $tableName, $fName ) ) {
3838 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3840 return $this->query( $sql, $fName );
3843 public function getInfinity() {
3847 public function encodeExpiry( $expiry ) {
3848 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3849 ?
$this->getInfinity()
3850 : $this->timestamp( $expiry );
3853 public function decodeExpiry( $expiry, $format = TS_MW
) {
3854 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3858 return ConvertibleTimestamp
::convert( $format, $expiry );
3861 public function setBigSelects( $value = true ) {
3865 public function isReadOnly() {
3866 return ( $this->getReadOnlyReason() !== false );
3870 * @return string|bool Reason this DB is read-only or false if it is not
3872 protected function getReadOnlyReason() {
3873 $reason = $this->getLBInfo( 'readOnlyReason' );
3875 return is_string( $reason ) ?
$reason : false;
3878 public function setTableAliases( array $aliases ) {
3879 $this->tableAliases
= $aliases;
3882 public function setIndexAliases( array $aliases ) {
3883 $this->indexAliases
= $aliases;
3887 * @return bool Whether a DB user is required to access the DB
3890 protected function requiresDatabaseUser() {
3895 * Get the underlying binding connection handle
3897 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3898 * This catches broken callers than catch and ignore disconnection exceptions.
3899 * Unlike checking isOpen(), this is safe to call inside of open().
3901 * @return resource|object
3902 * @throws DBUnexpectedError
3905 protected function getBindingHandle() {
3906 if ( !$this->conn
) {
3907 throw new DBUnexpectedError(
3909 'DB connection was already closed or the connection dropped.'
3920 public function __toString() {
3921 return (string)$this->conn
;
3925 * Make sure that copies do not share the same client binding handle
3926 * @throws DBConnectionError
3928 public function __clone() {
3929 $this->connLogger
->warning(
3930 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3931 ( new RuntimeException() )->getTraceAsString()
3934 if ( $this->isOpen() ) {
3935 // Open a new connection resource without messing with the old one
3936 $this->opened
= false;
3937 $this->conn
= false;
3938 $this->trxEndCallbacks
= []; // don't copy
3939 $this->handleSessionLoss(); // no trx or locks anymore
3940 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3941 $this->lastPing
= microtime( true );
3946 * Called by serialize. Throw an exception when DB connection is serialized.
3947 * This causes problems on some database engines because the connection is
3948 * not restored on unserialize.
3950 public function __sleep() {
3951 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3952 'the connection is not restored on wakeup.' );
3956 * Run a few simple sanity checks and close dangling connections
3958 public function __destruct() {
3959 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3960 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3963 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3964 if ( $danglingWriters ) {
3965 $fnames = implode( ', ', $danglingWriters );
3966 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3969 if ( $this->conn
) {
3970 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3971 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3972 Wikimedia\
suppressWarnings();
3973 $this->closeConnection();
3974 Wikimedia\restoreWarnings
();
3975 $this->conn
= false;
3976 $this->opened
= false;
3981 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3982 class_alias( Database
::class, 'Database' ); // b/c global alias