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 Wikimedia\ScopedCallback
;
31 use Wikimedia\Timestamp\ConvertibleTimestamp
;
35 use InvalidArgumentException
;
40 * Relational database abstraction object
45 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
46 /** Number of times to re-try an operation in case of deadlock */
47 const DEADLOCK_TRIES
= 4;
48 /** Minimum time to wait before retry, in microseconds */
49 const DEADLOCK_DELAY_MIN
= 500000;
50 /** Maximum time to wait before retry */
51 const DEADLOCK_DELAY_MAX
= 1500000;
53 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_QUERY
= 'SELECT 1 AS ping';
57 const TINY_WRITE_SEC
= 0.010;
58 const SLOW_WRITE_SEC
= 0.500;
59 const SMALL_WRITE_ROWS
= 100;
61 /** @var string SQL query */
62 protected $mLastQuery = '';
63 /** @var float|bool UNIX timestamp of last write query */
64 protected $mLastWriteTime = false;
65 /** @var string|bool */
66 protected $mPHPError = false;
75 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
76 protected $tableAliases = [];
77 /** @var bool Whether this PHP instance is for a CLI script */
79 /** @var string Agent name for query profiling */
82 /** @var BagOStuff APC cache */
84 /** @var LoggerInterface */
85 protected $connLogger;
86 /** @var LoggerInterface */
87 protected $queryLogger;
88 /** @var callback Error logging callback */
89 protected $errorLogger;
91 /** @var resource|null Database connection */
92 protected $mConn = null;
94 protected $mOpened = false;
96 /** @var array[] List of (callable, method name) */
97 protected $mTrxIdleCallbacks = [];
98 /** @var array[] List of (callable, method name) */
99 protected $mTrxPreCommitCallbacks = [];
100 /** @var array[] List of (callable, method name) */
101 protected $mTrxEndCallbacks = [];
102 /** @var callable[] Map of (name => callable) */
103 protected $mTrxRecurringCallbacks = [];
104 /** @var bool Whether to suppress triggering of transaction end callbacks */
105 protected $mTrxEndCallbacksSuppressed = false;
108 protected $mTablePrefix = '';
110 protected $mSchema = '';
114 protected $mLBInfo = [];
115 /** @var bool|null */
116 protected $mDefaultBigSelects = null;
117 /** @var array|bool */
118 protected $mSchemaVars = false;
120 protected $mSessionVars = [];
121 /** @var array|null */
122 protected $preparedArgs;
123 /** @var string|bool|null Stashed value of html_errors INI setting */
124 protected $htmlErrors;
126 protected $delimiter = ';';
127 /** @var DatabaseDomain */
128 protected $currentDomain;
129 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
130 protected $affectedRowCount;
133 * Either 1 if a transaction is active or 0 otherwise.
134 * The other Trx fields may not be meaningfull if this is 0.
138 protected $mTrxLevel = 0;
140 * Either a short hexidecimal string if a transaction is active or ""
143 * @see Database::mTrxLevel
145 protected $mTrxShortId = '';
147 * The UNIX time that the transaction started. Callers can assume that if
148 * snapshot isolation is used, then the data is *at least* up to date to that
149 * point (possibly more up-to-date since the first SELECT defines the snapshot).
152 * @see Database::mTrxLevel
154 private $mTrxTimestamp = null;
155 /** @var float Lag estimate at the time of BEGIN */
156 private $mTrxReplicaLag = null;
158 * Remembers the function name given for starting the most recent transaction via begin().
159 * Used to provide additional context for error reporting.
162 * @see Database::mTrxLevel
164 private $mTrxFname = null;
166 * Record if possible write queries were done in the last transaction started
169 * @see Database::mTrxLevel
171 private $mTrxDoneWrites = false;
173 * Record if the current transaction was started implicitly due to DBO_TRX being set.
176 * @see Database::mTrxLevel
178 private $mTrxAutomatic = false;
180 * Array of levels of atomicity within transactions
184 private $mTrxAtomicLevels = [];
186 * Record if the current transaction was started implicitly by Database::startAtomic
190 private $mTrxAutomaticAtomic = false;
192 * Track the write query callers of the current transaction
196 private $mTrxWriteCallers = [];
198 * @var float Seconds spent in write queries for the current transaction
200 private $mTrxWriteDuration = 0.0;
202 * @var int Number of write queries for the current transaction
204 private $mTrxWriteQueryCount = 0;
206 * @var int Number of rows affected by write queries for the current transaction
208 private $mTrxWriteAffectedRows = 0;
210 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
212 private $mTrxWriteAdjDuration = 0.0;
214 * @var int Number of write queries counted in mTrxWriteAdjDuration
216 private $mTrxWriteAdjQueryCount = 0;
218 * @var float RTT time estimate
220 private $mRTTEstimate = 0.0;
222 /** @var array Map of (name => 1) for locks obtained via lock() */
223 private $mNamedLocksHeld = [];
224 /** @var array Map of (table name => 1) for TEMPORARY tables */
225 protected $mSessionTempTables = [];
227 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
228 private $lazyMasterHandle;
230 /** @var float UNIX timestamp */
231 protected $lastPing = 0.0;
233 /** @var int[] Prior mFlags values */
234 private $priorFlags = [];
236 /** @var object|string Class name or object With profileIn/profileOut methods */
238 /** @var TransactionProfiler */
239 protected $trxProfiler;
242 * Constructor and database handle and attempt to connect to the DB server
244 * IDatabase classes should not be constructed directly in external
245 * code. Database::factory() should be used instead.
247 * @param array $params Parameters passed from Database::factory()
249 function __construct( array $params ) {
250 $server = $params['host'];
251 $user = $params['user'];
252 $password = $params['password'];
253 $dbName = $params['dbname'];
255 $this->mSchema
= $params['schema'];
256 $this->mTablePrefix
= $params['tablePrefix'];
258 $this->cliMode
= $params['cliMode'];
259 // Agent name is added to SQL queries in a comment, so make sure it can't break out
260 $this->agent
= str_replace( '/', '-', $params['agent'] );
262 $this->mFlags
= $params['flags'];
263 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
264 if ( $this->cliMode
) {
265 $this->mFlags
&= ~self
::DBO_TRX
;
267 $this->mFlags |
= self
::DBO_TRX
;
271 $this->mSessionVars
= $params['variables'];
273 $this->srvCache
= isset( $params['srvCache'] )
274 ?
$params['srvCache']
275 : new HashBagOStuff();
277 $this->profiler
= $params['profiler'];
278 $this->trxProfiler
= $params['trxProfiler'];
279 $this->connLogger
= $params['connLogger'];
280 $this->queryLogger
= $params['queryLogger'];
281 $this->errorLogger
= $params['errorLogger'];
283 // Set initial dummy domain until open() sets the final DB/prefix
284 $this->currentDomain
= DatabaseDomain
::newUnspecified();
287 $this->open( $server, $user, $password, $dbName );
288 } elseif ( $this->requiresDatabaseUser() ) {
289 throw new InvalidArgumentException( "No database user provided." );
292 // Set the domain object after open() sets the relevant fields
293 if ( $this->mDBname
!= '' ) {
294 // Domains with server scope but a table prefix are not used by IDatabase classes
295 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
300 * Construct a Database subclass instance given a database type and parameters
302 * This also connects to the database immediately upon object construction
304 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
305 * @param array $p Parameter map with keys:
306 * - host : The hostname of the DB server
307 * - user : The name of the database user the client operates under
308 * - password : The password for the database user
309 * - dbname : The name of the database to use where queries do not specify one.
310 * The database must exist or an error might be thrown. Setting this to the empty string
311 * will avoid any such errors and make the handle have no implicit database scope. This is
312 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
313 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
314 * in which user names and such are defined, e.g. users are database-specific in Postgres.
315 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
316 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
317 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
318 * recognized in queries. This can be used in place of schemas for handle site farms.
319 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
320 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
321 * flag in place UNLESS this this database simply acts as a key/value store.
322 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
323 * 'mysqli' driver; the old one 'mysql' has been removed.
324 * - variables: Optional map of session variables to set after connecting. This can be
325 * used to adjust lock timeouts or encoding modes and the like.
326 * - connLogger: Optional PSR-3 logger interface instance.
327 * - queryLogger: Optional PSR-3 logger interface instance.
328 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
329 * These will be called in query(), using a simplified version of the SQL that also
330 * includes the agent as a SQL comment.
331 * - trxProfiler: Optional TransactionProfiler instance.
332 * - errorLogger: Optional callback that takes an Exception and logs it.
333 * - cliMode: Whether to consider the execution context that of a CLI script.
334 * - agent: Optional name used to identify the end-user in query profiling/logging.
335 * - srvCache: Optional BagOStuff instance to an APC-style cache.
336 * @return Database|null If the database driver or extension cannot be found
337 * @throws InvalidArgumentException If the database driver or extension cannot be found
340 final public static function factory( $dbType, $p = [] ) {
341 // For database types with built-in support, the below maps type to IDatabase
342 // implementations. For types with multipe driver implementations (PHP extensions),
343 // an array can be used, keyed by extension name. In case of an array, the
344 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
345 // we auto-detect the first available driver. For types without built-in support,
346 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
347 static $builtinTypes = [
348 'mssql' => DatabaseMssql
::class,
349 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
350 'sqlite' => DatabaseSqlite
::class,
351 'postgres' => DatabasePostgres
::class,
354 $dbType = strtolower( $dbType );
356 if ( isset( $builtinTypes[$dbType] ) ) {
357 $possibleDrivers = $builtinTypes[$dbType];
358 if ( is_string( $possibleDrivers ) ) {
359 $class = $possibleDrivers;
361 if ( !empty( $p['driver'] ) ) {
362 if ( !isset( $possibleDrivers[$p['driver']] ) ) {
363 throw new InvalidArgumentException( __METHOD__
.
364 " type '$dbType' does not support driver '{$p['driver']}'" );
366 $class = $possibleDrivers[$p['driver']];
369 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
370 if ( extension_loaded( $posDriver ) ) {
371 $class = $possibleClass;
378 $class = 'Database' . ucfirst( $dbType );
381 if ( $class === false ) {
382 throw new InvalidArgumentException( __METHOD__
.
383 " no viable database extension found for type '$dbType'" );
386 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
387 // Resolve some defaults for b/c
388 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
389 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
390 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
391 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
392 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
393 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
394 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
395 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
396 $p['cliMode'] = isset( $p['cliMode'] )
398 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
399 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
400 if ( !isset( $p['connLogger'] ) ) {
401 $p['connLogger'] = new \Psr\Log\
NullLogger();
403 if ( !isset( $p['queryLogger'] ) ) {
404 $p['queryLogger'] = new \Psr\Log\
NullLogger();
406 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
407 if ( !isset( $p['trxProfiler'] ) ) {
408 $p['trxProfiler'] = new TransactionProfiler();
410 if ( !isset( $p['errorLogger'] ) ) {
411 $p['errorLogger'] = function ( Exception
$e ) {
412 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
416 $conn = new $class( $p );
425 * Set the PSR-3 logger interface to use for query logging. (The logger
426 * interfaces for connection logging and error logging can be set with the
429 * @param LoggerInterface $logger
431 public function setLogger( LoggerInterface
$logger ) {
432 $this->queryLogger
= $logger;
435 public function getServerInfo() {
436 return $this->getServerVersion();
439 public function bufferResults( $buffer = null ) {
440 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
441 if ( $buffer !== null ) {
443 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
444 : $this->setFlag( self
::DBO_NOBUFFER
);
451 * Turns on (false) or off (true) the automatic generation and sending
452 * of a "we're sorry, but there has been a database error" page on
453 * database errors. Default is on (false). When turned off, the
454 * code should use lastErrno() and lastError() to handle the
455 * situation as appropriate.
457 * Do not use this function outside of the Database classes.
459 * @param null|bool $ignoreErrors
460 * @return bool The previous value of the flag.
462 protected function ignoreErrors( $ignoreErrors = null ) {
463 $res = $this->getFlag( self
::DBO_IGNORE
);
464 if ( $ignoreErrors !== null ) {
465 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
466 if ( $ignoreErrors ) {
467 $this->mFlags |
= self
::DBO_IGNORE
;
469 $this->mFlags
&= ~self
::DBO_IGNORE
;
476 public function trxLevel() {
477 return $this->mTrxLevel
;
480 public function trxTimestamp() {
481 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
484 public function tablePrefix( $prefix = null ) {
485 $old = $this->mTablePrefix
;
486 if ( $prefix !== null ) {
487 $this->mTablePrefix
= $prefix;
488 $this->currentDomain
= ( $this->mDBname
!= '' )
489 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
490 : DatabaseDomain
::newUnspecified();
496 public function dbSchema( $schema = null ) {
497 $old = $this->mSchema
;
498 if ( $schema !== null ) {
499 $this->mSchema
= $schema;
505 public function getLBInfo( $name = null ) {
506 if ( is_null( $name ) ) {
507 return $this->mLBInfo
;
509 if ( array_key_exists( $name, $this->mLBInfo
) ) {
510 return $this->mLBInfo
[$name];
517 public function setLBInfo( $name, $value = null ) {
518 if ( is_null( $value ) ) {
519 $this->mLBInfo
= $name;
521 $this->mLBInfo
[$name] = $value;
525 public function setLazyMasterHandle( IDatabase
$conn ) {
526 $this->lazyMasterHandle
= $conn;
530 * @return IDatabase|null
531 * @see setLazyMasterHandle()
534 protected function getLazyMasterHandle() {
535 return $this->lazyMasterHandle
;
538 public function implicitGroupby() {
542 public function implicitOrderby() {
546 public function lastQuery() {
547 return $this->mLastQuery
;
550 public function doneWrites() {
551 return (bool)$this->mLastWriteTime
;
554 public function lastDoneWrites() {
555 return $this->mLastWriteTime ?
: false;
558 public function writesPending() {
559 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
562 public function writesOrCallbacksPending() {
563 return $this->mTrxLevel
&& (
564 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
568 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
569 if ( !$this->mTrxLevel
) {
571 } elseif ( !$this->mTrxDoneWrites
) {
576 case self
::ESTIMATE_DB_APPLY
:
578 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
579 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
580 // For omitted queries, make them count as something at least
581 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
582 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
585 default: // everything
586 return $this->mTrxWriteDuration
;
590 public function pendingWriteCallers() {
591 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
594 public function pendingWriteRowsAffected() {
595 return $this->mTrxWriteAffectedRows
;
599 * Get the list of method names that have pending write queries or callbacks
600 * for this transaction
604 protected function pendingWriteAndCallbackCallers() {
605 if ( !$this->mTrxLevel
) {
609 $fnames = $this->mTrxWriteCallers
;
611 $this->mTrxIdleCallbacks
,
612 $this->mTrxPreCommitCallbacks
,
613 $this->mTrxEndCallbacks
615 foreach ( $callbacks as $callback ) {
616 $fnames[] = $callback[1];
623 public function isOpen() {
624 return $this->mOpened
;
627 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
628 if ( ( $flag & self
::DBO_IGNORE
) ) {
629 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
632 if ( $remember === self
::REMEMBER_PRIOR
) {
633 array_push( $this->priorFlags
, $this->mFlags
);
635 $this->mFlags |
= $flag;
638 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
639 if ( ( $flag & self
::DBO_IGNORE
) ) {
640 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
643 if ( $remember === self
::REMEMBER_PRIOR
) {
644 array_push( $this->priorFlags
, $this->mFlags
);
646 $this->mFlags
&= ~
$flag;
649 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
650 if ( !$this->priorFlags
) {
654 if ( $state === self
::RESTORE_INITIAL
) {
655 $this->mFlags
= reset( $this->priorFlags
);
656 $this->priorFlags
= [];
658 $this->mFlags
= array_pop( $this->priorFlags
);
662 public function getFlag( $flag ) {
663 return !!( $this->mFlags
& $flag );
667 * @param string $name Class field name
669 * @deprecated Since 1.28
671 public function getProperty( $name ) {
675 public function getDomainID() {
676 return $this->currentDomain
->getId();
679 final public function getWikiID() {
680 return $this->getDomainID();
684 * Get information about an index into an object
685 * @param string $table Table name
686 * @param string $index Index name
687 * @param string $fname Calling function name
688 * @return mixed Database-specific index description class or false if the index does not exist
690 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
693 * Wrapper for addslashes()
695 * @param string $s String to be slashed.
696 * @return string Slashed string.
698 abstract function strencode( $s );
701 * Set a custom error handler for logging errors during database connection
703 protected function installErrorHandler() {
704 $this->mPHPError
= false;
705 $this->htmlErrors
= ini_set( 'html_errors', '0' );
706 set_error_handler( [ $this, 'connectionErrorLogger' ] );
710 * Restore the previous error handler and return the last PHP error for this DB
712 * @return bool|string
714 protected function restoreErrorHandler() {
715 restore_error_handler();
716 if ( $this->htmlErrors
!== false ) {
717 ini_set( 'html_errors', $this->htmlErrors
);
720 return $this->getLastPHPError();
724 * @return string|bool Last PHP error for this DB (typically connection errors)
726 protected function getLastPHPError() {
727 if ( $this->mPHPError
) {
728 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
729 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
738 * Error handler for logging errors during database connection
739 * This method should not be used outside of Database classes
742 * @param string $errstr
744 public function connectionErrorLogger( $errno, $errstr ) {
745 $this->mPHPError
= $errstr;
749 * Create a log context to pass to PSR-3 logger functions.
751 * @param array $extras Additional data to add to context
754 protected function getLogContext( array $extras = [] ) {
757 'db_server' => $this->mServer
,
758 'db_name' => $this->mDBname
,
759 'db_user' => $this->mUser
,
765 public function close() {
766 if ( $this->mConn
) {
767 if ( $this->trxLevel() ) {
768 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
771 $closed = $this->closeConnection();
772 $this->mConn
= false;
774 $this->mTrxIdleCallbacks ||
775 $this->mTrxPreCommitCallbacks ||
776 $this->mTrxEndCallbacks
778 throw new RuntimeException( "Transaction callbacks still pending." );
782 $this->mOpened
= false;
788 * Make sure isOpen() returns true as a sanity check
790 * @throws DBUnexpectedError
792 protected function assertOpen() {
793 if ( !$this->isOpen() ) {
794 throw new DBUnexpectedError( $this, "DB connection was already closed." );
799 * Closes underlying database connection
801 * @return bool Whether connection was closed successfully
803 abstract protected function closeConnection();
805 public function reportConnectionError( $error = 'Unknown error' ) {
806 $myError = $this->lastError();
812 throw new DBConnectionError( $this, $error );
816 * The DBMS-dependent part of query()
818 * @param string $sql SQL query.
819 * @return ResultWrapper|bool Result object to feed to fetchObject,
820 * fetchRow, ...; or false on failure
822 abstract protected function doQuery( $sql );
825 * Determine whether a query writes to the DB.
826 * Should return true if unsure.
831 protected function isWriteQuery( $sql ) {
833 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
838 * @return string|null
840 protected function getQueryVerb( $sql ) {
841 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
845 * Determine whether a SQL statement is sensitive to isolation level.
846 * A SQL statement is considered transactable if its result could vary
847 * depending on the transaction isolation level. Operational commands
848 * such as 'SET' and 'SHOW' are not considered to be transactable.
853 protected function isTransactableQuery( $sql ) {
855 $this->getQueryVerb( $sql ),
856 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
862 * @param string $sql A SQL query
863 * @return bool Whether $sql is SQL for TEMPORARY table operation
865 protected function registerTempTableOperation( $sql ) {
867 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
871 $this->mSessionTempTables
[$matches[1]] = 1;
874 } elseif ( preg_match(
875 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
879 $isTemp = isset( $this->mSessionTempTables
[$matches[1]] );
880 unset( $this->mSessionTempTables
[$matches[1]] );
883 } elseif ( preg_match(
884 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
888 return isset( $this->mSessionTempTables
[$matches[1]] );
889 } elseif ( preg_match(
890 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
894 return isset( $this->mSessionTempTables
[$matches[1]] );
900 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
901 $priorWritesPending = $this->writesOrCallbacksPending();
902 $this->mLastQuery
= $sql;
904 $isWrite = $this->isWriteQuery( $sql );
906 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
908 $isNonTempWrite = false;
912 if ( $this->getLBInfo( 'replica' ) === true ) {
915 'Write operations are not allowed on replica database connections.'
918 # In theory, non-persistent writes are allowed in read-only mode, but due to things
919 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
920 $reason = $this->getReadOnlyReason();
921 if ( $reason !== false ) {
922 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
924 # Set a flag indicating that writes have been done
925 $this->mLastWriteTime
= microtime( true );
928 # Add trace comment to the begin of the sql string, right after the operator.
929 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
930 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
932 # Start implicit transactions that wrap the request if DBO_TRX is enabled
933 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
934 && $this->isTransactableQuery( $sql )
936 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
937 $this->mTrxAutomatic
= true;
940 # Keep track of whether the transaction has write queries pending
941 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
942 $this->mTrxDoneWrites
= true;
943 $this->trxProfiler
->transactionWritingIn(
944 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
947 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
948 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
951 # Avoid fatals if close() was called
954 # Send the query to the server
955 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
957 # Try reconnecting if the connection was lost
958 if ( false === $ret && $this->wasErrorReissuable() ) {
959 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
960 # Stash the last error values before anything might clear them
961 $lastError = $this->lastError();
962 $lastErrno = $this->lastErrno();
963 # Update state tracking to reflect transaction loss due to disconnection
964 $this->handleSessionLoss();
965 if ( $this->reconnect() ) {
966 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
967 $params = [ 'dbserver' => $this->getServer() ];
968 $this->connLogger
->warning( $msg, $params );
969 $this->queryLogger
->warning( $msg, $params +
970 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
972 if ( !$recoverable ) {
973 # Callers may catch the exception and continue to use the DB
974 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
976 # Should be safe to silently retry the query
977 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
980 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
981 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
985 if ( false === $ret ) {
986 # Deadlocks cause the entire transaction to abort, not just the statement.
987 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
988 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
989 if ( $this->wasDeadlock() ) {
990 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
991 $tempIgnore = false; // not recoverable
993 # Update state tracking to reflect transaction loss
994 $this->handleSessionLoss();
997 $this->reportQueryError(
998 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1001 $res = $this->resultObject( $ret );
1007 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1009 * @param string $sql Original SQL query
1010 * @param string $commentedSql SQL query with debugging/trace comment
1011 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1012 * @param string $fname Name of the calling function
1013 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1014 * object for a successful read query, or false on failure
1016 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1017 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1018 # generalizeSQL() will probably cut down the query to reasonable
1019 # logging size most of the time. The substr is really just a sanity check.
1021 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1023 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1026 # Include query transaction state
1027 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1029 $startTime = microtime( true );
1030 if ( $this->profiler
) {
1031 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1033 $this->affectedRowCount
= null;
1034 $ret = $this->doQuery( $commentedSql );
1035 $this->affectedRowCount
= $this->affectedRows();
1036 if ( $this->profiler
) {
1037 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1039 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1041 unset( $queryProfSection ); // profile out (if set)
1043 if ( $ret !== false ) {
1044 $this->lastPing
= $startTime;
1045 if ( $isWrite && $this->mTrxLevel
) {
1046 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1047 $this->mTrxWriteCallers
[] = $fname;
1051 if ( $sql === self
::PING_QUERY
) {
1052 $this->mRTTEstimate
= $queryRuntime;
1055 $this->trxProfiler
->recordQueryCompletion(
1056 $queryProf, $startTime, $isWrite, $this->affectedRows()
1058 $this->queryLogger
->debug( $sql, [
1060 'master' => $isMaster,
1061 'runtime' => $queryRuntime,
1068 * Update the estimated run-time of a query, not counting large row lock times
1070 * LoadBalancer can be set to rollback transactions that will create huge replication
1071 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1072 * queries, like inserting a row can take a long time due to row locking. This method
1073 * uses some simple heuristics to discount those cases.
1075 * @param string $sql A SQL write query
1076 * @param float $runtime Total runtime, including RTT
1077 * @param int $affected Affected row count
1079 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1080 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1081 $indicativeOfReplicaRuntime = true;
1082 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1083 $verb = $this->getQueryVerb( $sql );
1084 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1085 if ( $verb === 'INSERT' ) {
1086 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1087 } elseif ( $verb === 'REPLACE' ) {
1088 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1092 $this->mTrxWriteDuration +
= $runtime;
1093 $this->mTrxWriteQueryCount +
= 1;
1094 $this->mTrxWriteAffectedRows +
= $affected;
1095 if ( $indicativeOfReplicaRuntime ) {
1096 $this->mTrxWriteAdjDuration +
= $runtime;
1097 $this->mTrxWriteAdjQueryCount +
= 1;
1102 * Determine whether or not it is safe to retry queries after a database
1103 * connection is lost
1105 * @param string $sql SQL query
1106 * @param bool $priorWritesPending Whether there is a transaction open with
1107 * possible write queries or transaction pre-commit/idle callbacks
1108 * waiting on it to finish.
1109 * @return bool True if it is safe to retry the query, false otherwise
1111 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1112 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1113 # Dropped connections also mean that named locks are automatically released.
1114 # Only allow error suppression in autocommit mode or when the lost transaction
1115 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1116 if ( $this->mNamedLocksHeld
) {
1117 return false; // possible critical section violation
1118 } elseif ( $sql === 'COMMIT' ) {
1119 return !$priorWritesPending; // nothing written anyway? (T127428)
1120 } elseif ( $sql === 'ROLLBACK' ) {
1121 return true; // transaction lost...which is also what was requested :)
1122 } elseif ( $this->explicitTrxActive() ) {
1123 return false; // don't drop atomocity
1124 } elseif ( $priorWritesPending ) {
1125 return false; // prior writes lost from implicit transaction
1132 * Clean things up after transaction loss due to disconnection
1134 * @return null|Exception
1136 private function handleSessionLoss() {
1137 $this->mTrxLevel
= 0;
1138 $this->mTrxIdleCallbacks
= []; // T67263
1139 $this->mTrxPreCommitCallbacks
= []; // T67263
1140 $this->mSessionTempTables
= [];
1141 $this->mNamedLocksHeld
= [];
1143 // Handle callbacks in mTrxEndCallbacks
1144 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1145 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1147 } catch ( Exception
$e ) {
1148 // Already logged; move on...
1154 * Checks whether the cause of the error is detected to be a timeout.
1156 * It returns false by default, and not all engines support detecting this yet.
1157 * If this returns false, it will be treated as a generic query error.
1159 * @param string $error Error text
1160 * @param int $errno Error number
1163 protected function wasQueryTimeout( $error, $errno ) {
1167 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1168 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1169 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1171 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1172 $this->queryLogger
->error(
1173 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1174 $this->getLogContext( [
1175 'method' => __METHOD__
,
1178 'sql1line' => $sql1line,
1182 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1183 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1184 if ( $wasQueryTimeout ) {
1185 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1187 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1192 public function freeResult( $res ) {
1195 public function selectField(
1196 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1198 if ( $var === '*' ) { // sanity
1199 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1202 if ( !is_array( $options ) ) {
1203 $options = [ $options ];
1206 $options['LIMIT'] = 1;
1208 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1209 if ( $res === false ||
!$this->numRows( $res ) ) {
1213 $row = $this->fetchRow( $res );
1215 if ( $row !== false ) {
1216 return reset( $row );
1222 public function selectFieldValues(
1223 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1225 if ( $var === '*' ) { // sanity
1226 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1227 } elseif ( !is_string( $var ) ) { // sanity
1228 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1231 if ( !is_array( $options ) ) {
1232 $options = [ $options ];
1235 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1236 if ( $res === false ) {
1241 foreach ( $res as $row ) {
1242 $values[] = $row->$var;
1249 * Returns an optional USE INDEX clause to go after the table, and a
1250 * string to go at the end of the query.
1252 * @param array $options Associative array of options to be turned into
1253 * an SQL query, valid keys are listed in the function.
1255 * @see Database::select()
1257 protected function makeSelectOptions( $options ) {
1258 $preLimitTail = $postLimitTail = '';
1263 foreach ( $options as $key => $option ) {
1264 if ( is_numeric( $key ) ) {
1265 $noKeyOptions[$option] = true;
1269 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1271 $preLimitTail .= $this->makeOrderBy( $options );
1273 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1274 $postLimitTail .= ' FOR UPDATE';
1277 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1278 $postLimitTail .= ' LOCK IN SHARE MODE';
1281 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1282 $startOpts .= 'DISTINCT';
1285 # Various MySQL extensions
1286 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1287 $startOpts .= ' /*! STRAIGHT_JOIN */';
1290 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1291 $startOpts .= ' HIGH_PRIORITY';
1294 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1295 $startOpts .= ' SQL_BIG_RESULT';
1298 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1299 $startOpts .= ' SQL_BUFFER_RESULT';
1302 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1303 $startOpts .= ' SQL_SMALL_RESULT';
1306 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1307 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1310 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1311 $startOpts .= ' SQL_CACHE';
1314 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1315 $startOpts .= ' SQL_NO_CACHE';
1318 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1319 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1323 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1324 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1329 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1333 * Returns an optional GROUP BY with an optional HAVING
1335 * @param array $options Associative array of options
1337 * @see Database::select()
1340 protected function makeGroupByWithHaving( $options ) {
1342 if ( isset( $options['GROUP BY'] ) ) {
1343 $gb = is_array( $options['GROUP BY'] )
1344 ?
implode( ',', $options['GROUP BY'] )
1345 : $options['GROUP BY'];
1346 $sql .= ' GROUP BY ' . $gb;
1348 if ( isset( $options['HAVING'] ) ) {
1349 $having = is_array( $options['HAVING'] )
1350 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1351 : $options['HAVING'];
1352 $sql .= ' HAVING ' . $having;
1359 * Returns an optional ORDER BY
1361 * @param array $options Associative array of options
1363 * @see Database::select()
1366 protected function makeOrderBy( $options ) {
1367 if ( isset( $options['ORDER BY'] ) ) {
1368 $ob = is_array( $options['ORDER BY'] )
1369 ?
implode( ',', $options['ORDER BY'] )
1370 : $options['ORDER BY'];
1372 return ' ORDER BY ' . $ob;
1378 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1379 $options = [], $join_conds = [] ) {
1380 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1382 return $this->query( $sql, $fname );
1385 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1386 $options = [], $join_conds = []
1388 if ( is_array( $vars ) ) {
1389 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1392 $options = (array)$options;
1393 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1394 ?
$options['USE INDEX']
1397 isset( $options['IGNORE INDEX'] ) &&
1398 is_array( $options['IGNORE INDEX'] )
1400 ?
$options['IGNORE INDEX']
1403 if ( is_array( $table ) ) {
1405 $this->tableNamesWithIndexClauseOrJOIN(
1406 $table, $useIndexes, $ignoreIndexes, $join_conds );
1407 } elseif ( $table != '' ) {
1408 if ( $table[0] == ' ' ) {
1409 $from = ' FROM ' . $table;
1412 $this->tableNamesWithIndexClauseOrJOIN(
1413 [ $table ], $useIndexes, $ignoreIndexes, [] );
1419 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1420 $this->makeSelectOptions( $options );
1422 if ( !empty( $conds ) ) {
1423 if ( is_array( $conds ) ) {
1424 $conds = $this->makeList( $conds, self
::LIST_AND
);
1426 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1427 "WHERE $conds $preLimitTail";
1429 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1432 if ( isset( $options['LIMIT'] ) ) {
1433 $sql = $this->limitResult( $sql, $options['LIMIT'],
1434 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1436 $sql = "$sql $postLimitTail";
1438 if ( isset( $options['EXPLAIN'] ) ) {
1439 $sql = 'EXPLAIN ' . $sql;
1445 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1446 $options = [], $join_conds = []
1448 $options = (array)$options;
1449 $options['LIMIT'] = 1;
1450 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1452 if ( $res === false ) {
1456 if ( !$this->numRows( $res ) ) {
1460 $obj = $this->fetchObject( $res );
1465 public function estimateRowCount(
1466 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1469 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1472 $row = $this->fetchRow( $res );
1473 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1479 public function selectRowCount(
1480 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1483 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1484 // The identifier quotes is primarily for MSSQL.
1485 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1486 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1487 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1490 $row = $this->fetchRow( $res );
1491 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1498 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1499 * It's only slightly flawed. Don't use for anything important.
1501 * @param string $sql A SQL Query
1505 protected static function generalizeSQL( $sql ) {
1506 # This does the same as the regexp below would do, but in such a way
1507 # as to avoid crashing php on some large strings.
1508 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1510 $sql = str_replace( "\\\\", '', $sql );
1511 $sql = str_replace( "\\'", '', $sql );
1512 $sql = str_replace( "\\\"", '', $sql );
1513 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1514 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1516 # All newlines, tabs, etc replaced by single space
1517 $sql = preg_replace( '/\s+/', ' ', $sql );
1520 # except the ones surrounded by characters, e.g. l10n
1521 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1522 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1527 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1528 $info = $this->fieldInfo( $table, $field );
1533 public function indexExists( $table, $index, $fname = __METHOD__
) {
1534 if ( !$this->tableExists( $table ) ) {
1538 $info = $this->indexInfo( $table, $index, $fname );
1539 if ( is_null( $info ) ) {
1542 return $info !== false;
1546 public function tableExists( $table, $fname = __METHOD__
) {
1547 $tableRaw = $this->tableName( $table, 'raw' );
1548 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1549 return true; // already known to exist
1552 $table = $this->tableName( $table );
1553 $ignoreErrors = true;
1554 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1559 public function indexUnique( $table, $index ) {
1560 $indexInfo = $this->indexInfo( $table, $index );
1562 if ( !$indexInfo ) {
1566 return !$indexInfo[0]->Non_unique
;
1570 * Helper for Database::insert().
1572 * @param array $options
1575 protected function makeInsertOptions( $options ) {
1576 return implode( ' ', $options );
1579 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1580 # No rows to insert, easy just return now
1581 if ( !count( $a ) ) {
1585 $table = $this->tableName( $table );
1587 if ( !is_array( $options ) ) {
1588 $options = [ $options ];
1592 if ( isset( $options['fileHandle'] ) ) {
1593 $fh = $options['fileHandle'];
1595 $options = $this->makeInsertOptions( $options );
1597 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1599 $keys = array_keys( $a[0] );
1602 $keys = array_keys( $a );
1605 $sql = 'INSERT ' . $options .
1606 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1610 foreach ( $a as $row ) {
1616 $sql .= '(' . $this->makeList( $row ) . ')';
1619 $sql .= '(' . $this->makeList( $a ) . ')';
1622 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1624 } elseif ( $fh !== null ) {
1628 return (bool)$this->query( $sql, $fname );
1632 * Make UPDATE options array for Database::makeUpdateOptions
1634 * @param array $options
1637 protected function makeUpdateOptionsArray( $options ) {
1638 if ( !is_array( $options ) ) {
1639 $options = [ $options ];
1644 if ( in_array( 'IGNORE', $options ) ) {
1652 * Make UPDATE options for the Database::update function
1654 * @param array $options The options passed to Database::update
1657 protected function makeUpdateOptions( $options ) {
1658 $opts = $this->makeUpdateOptionsArray( $options );
1660 return implode( ' ', $opts );
1663 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1664 $table = $this->tableName( $table );
1665 $opts = $this->makeUpdateOptions( $options );
1666 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1668 if ( $conds !== [] && $conds !== '*' ) {
1669 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1672 return (bool)$this->query( $sql, $fname );
1675 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1676 if ( !is_array( $a ) ) {
1677 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1683 foreach ( $a as $field => $value ) {
1685 if ( $mode == self
::LIST_AND
) {
1687 } elseif ( $mode == self
::LIST_OR
) {
1696 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1697 $list .= "($value)";
1698 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1701 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1703 // Remove null from array to be handled separately if found
1704 $includeNull = false;
1705 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1706 $includeNull = true;
1707 unset( $value[$nullKey] );
1709 if ( count( $value ) == 0 && !$includeNull ) {
1710 throw new InvalidArgumentException(
1711 __METHOD__
. ": empty input for field $field" );
1712 } elseif ( count( $value ) == 0 ) {
1713 // only check if $field is null
1714 $list .= "$field IS NULL";
1716 // IN clause contains at least one valid element
1717 if ( $includeNull ) {
1718 // Group subconditions to ensure correct precedence
1721 if ( count( $value ) == 1 ) {
1722 // Special-case single values, as IN isn't terribly efficient
1723 // Don't necessarily assume the single key is 0; we don't
1724 // enforce linear numeric ordering on other arrays here.
1725 $value = array_values( $value )[0];
1726 $list .= $field . " = " . $this->addQuotes( $value );
1728 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1730 // if null present in array, append IS NULL
1731 if ( $includeNull ) {
1732 $list .= " OR $field IS NULL)";
1735 } elseif ( $value === null ) {
1736 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1737 $list .= "$field IS ";
1738 } elseif ( $mode == self
::LIST_SET
) {
1739 $list .= "$field = ";
1744 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1746 $list .= "$field = ";
1748 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1755 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1758 foreach ( $data as $base => $sub ) {
1759 if ( count( $sub ) ) {
1760 $conds[] = $this->makeList(
1761 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1767 return $this->makeList( $conds, self
::LIST_OR
);
1769 // Nothing to search for...
1774 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1778 public function bitNot( $field ) {
1782 public function bitAnd( $fieldLeft, $fieldRight ) {
1783 return "($fieldLeft & $fieldRight)";
1786 public function bitOr( $fieldLeft, $fieldRight ) {
1787 return "($fieldLeft | $fieldRight)";
1790 public function buildConcat( $stringList ) {
1791 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1794 public function buildGroupConcatField(
1795 $delim, $table, $field, $conds = '', $join_conds = []
1797 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1799 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1802 public function buildStringCast( $field ) {
1806 public function databasesAreIndependent() {
1810 public function selectDB( $db ) {
1811 # Stub. Shouldn't cause serious problems if it's not overridden, but
1812 # if your database engine supports a concept similar to MySQL's
1813 # databases you may as well.
1814 $this->mDBname
= $db;
1819 public function getDBname() {
1820 return $this->mDBname
;
1823 public function getServer() {
1824 return $this->mServer
;
1827 public function tableName( $name, $format = 'quoted' ) {
1828 # Skip the entire process when we have a string quoted on both ends.
1829 # Note that we check the end so that we will still quote any use of
1830 # use of `database`.table. But won't break things if someone wants
1831 # to query a database table with a dot in the name.
1832 if ( $this->isQuotedIdentifier( $name ) ) {
1836 # Lets test for any bits of text that should never show up in a table
1837 # name. Basically anything like JOIN or ON which are actually part of
1838 # SQL queries, but may end up inside of the table value to combine
1839 # sql. Such as how the API is doing.
1840 # Note that we use a whitespace test rather than a \b test to avoid
1841 # any remote case where a word like on may be inside of a table name
1842 # surrounded by symbols which may be considered word breaks.
1843 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1847 # Split database and table into proper variables.
1848 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1850 # Quote $table and apply the prefix if not quoted.
1851 # $tableName might be empty if this is called from Database::replaceVars()
1852 $tableName = "{$prefix}{$table}";
1853 if ( $format === 'quoted'
1854 && !$this->isQuotedIdentifier( $tableName )
1855 && $tableName !== ''
1857 $tableName = $this->addIdentifierQuotes( $tableName );
1860 # Quote $schema and $database and merge them with the table name if needed
1861 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1862 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1868 * Get the table components needed for a query given the currently selected database
1870 * @param string $name Table name in the form of db.schema.table, db.table, or table
1871 * @return array (DB name or "" for default, schema name, table prefix, table name)
1873 protected function qualifiedTableComponents( $name ) {
1874 # We reverse the explode so that database.table and table both output the correct table.
1875 $dbDetails = explode( '.', $name, 3 );
1876 if ( count( $dbDetails ) == 3 ) {
1877 list( $database, $schema, $table ) = $dbDetails;
1878 # We don't want any prefix added in this case
1880 } elseif ( count( $dbDetails ) == 2 ) {
1881 list( $database, $table ) = $dbDetails;
1882 # We don't want any prefix added in this case
1884 # In dbs that support it, $database may actually be the schema
1885 # but that doesn't affect any of the functionality here
1888 list( $table ) = $dbDetails;
1889 if ( isset( $this->tableAliases
[$table] ) ) {
1890 $database = $this->tableAliases
[$table]['dbname'];
1891 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1892 ?
$this->tableAliases
[$table]['schema']
1894 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1895 ?
$this->tableAliases
[$table]['prefix']
1896 : $this->mTablePrefix
;
1899 $schema = $this->mSchema
; # Default schema
1900 $prefix = $this->mTablePrefix
; # Default prefix
1904 return [ $database, $schema, $prefix, $table ];
1908 * @param string|null $namespace Database or schema
1909 * @param string $relation Name of table, view, sequence, etc...
1910 * @param string $format One of (raw, quoted)
1911 * @return string Relation name with quoted and merged $namespace as needed
1913 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1914 if ( strlen( $namespace ) ) {
1915 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1916 $namespace = $this->addIdentifierQuotes( $namespace );
1918 $relation = $namespace . '.' . $relation;
1924 public function tableNames() {
1925 $inArray = func_get_args();
1928 foreach ( $inArray as $name ) {
1929 $retVal[$name] = $this->tableName( $name );
1935 public function tableNamesN() {
1936 $inArray = func_get_args();
1939 foreach ( $inArray as $name ) {
1940 $retVal[] = $this->tableName( $name );
1947 * Get an aliased table name
1948 * e.g. tableName AS newTableName
1950 * @param string $name Table name, see tableName()
1951 * @param string|bool $alias Alias (optional)
1952 * @return string SQL name for aliased table. Will not alias a table to its own name
1954 protected function tableNameWithAlias( $name, $alias = false ) {
1955 if ( !$alias ||
$alias == $name ) {
1956 return $this->tableName( $name );
1958 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1963 * Gets an array of aliased table names
1965 * @param array $tables [ [alias] => table ]
1966 * @return string[] See tableNameWithAlias()
1968 protected function tableNamesWithAlias( $tables ) {
1970 foreach ( $tables as $alias => $table ) {
1971 if ( is_numeric( $alias ) ) {
1974 $retval[] = $this->tableNameWithAlias( $table, $alias );
1981 * Get an aliased field name
1982 * e.g. fieldName AS newFieldName
1984 * @param string $name Field name
1985 * @param string|bool $alias Alias (optional)
1986 * @return string SQL name for aliased field. Will not alias a field to its own name
1988 protected function fieldNameWithAlias( $name, $alias = false ) {
1989 if ( !$alias ||
(string)$alias === (string)$name ) {
1992 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1997 * Gets an array of aliased field names
1999 * @param array $fields [ [alias] => field ]
2000 * @return string[] See fieldNameWithAlias()
2002 protected function fieldNamesWithAlias( $fields ) {
2004 foreach ( $fields as $alias => $field ) {
2005 if ( is_numeric( $alias ) ) {
2008 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2015 * Get the aliased table name clause for a FROM clause
2016 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2018 * @param array $tables ( [alias] => table )
2019 * @param array $use_index Same as for select()
2020 * @param array $ignore_index Same as for select()
2021 * @param array $join_conds Same as for select()
2024 protected function tableNamesWithIndexClauseOrJOIN(
2025 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2029 $use_index = (array)$use_index;
2030 $ignore_index = (array)$ignore_index;
2031 $join_conds = (array)$join_conds;
2033 foreach ( $tables as $alias => $table ) {
2034 if ( !is_string( $alias ) ) {
2035 // No alias? Set it equal to the table name
2039 if ( is_array( $table ) ) {
2040 // A parenthesized group
2041 if ( count( $table ) > 1 ) {
2043 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2047 $innerTable = reset( $table );
2048 $innerAlias = key( $table );
2049 $joinedTable = $this->tableNameWithAlias(
2051 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2055 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2058 // Is there a JOIN clause for this table?
2059 if ( isset( $join_conds[$alias] ) ) {
2060 list( $joinType, $conds ) = $join_conds[$alias];
2061 $tableClause = $joinType;
2062 $tableClause .= ' ' . $joinedTable;
2063 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2064 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2066 $tableClause .= ' ' . $use;
2069 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2070 $ignore = $this->ignoreIndexClause(
2071 implode( ',', (array)$ignore_index[$alias] ) );
2072 if ( $ignore != '' ) {
2073 $tableClause .= ' ' . $ignore;
2076 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2078 $tableClause .= ' ON (' . $on . ')';
2081 $retJOIN[] = $tableClause;
2082 } elseif ( isset( $use_index[$alias] ) ) {
2083 // Is there an INDEX clause for this table?
2084 $tableClause = $joinedTable;
2085 $tableClause .= ' ' . $this->useIndexClause(
2086 implode( ',', (array)$use_index[$alias] )
2089 $ret[] = $tableClause;
2090 } elseif ( isset( $ignore_index[$alias] ) ) {
2091 // Is there an INDEX clause for this table?
2092 $tableClause = $joinedTable;
2093 $tableClause .= ' ' . $this->ignoreIndexClause(
2094 implode( ',', (array)$ignore_index[$alias] )
2097 $ret[] = $tableClause;
2099 $tableClause = $joinedTable;
2101 $ret[] = $tableClause;
2105 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2106 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2107 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2109 // Compile our final table clause
2110 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2114 * Allows for index remapping in queries where this is not consistent across DBMS
2116 * @param string $index
2119 protected function indexName( $index ) {
2123 public function addQuotes( $s ) {
2124 if ( $s instanceof Blob
) {
2127 if ( $s === null ) {
2129 } elseif ( is_bool( $s ) ) {
2132 # This will also quote numeric values. This should be harmless,
2133 # and protects against weird problems that occur when they really
2134 # _are_ strings such as article titles and string->number->string
2135 # conversion is not 1:1.
2136 return "'" . $this->strencode( $s ) . "'";
2141 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2142 * MySQL uses `backticks` while basically everything else uses double quotes.
2143 * Since MySQL is the odd one out here the double quotes are our generic
2144 * and we implement backticks in DatabaseMysqlBase.
2149 public function addIdentifierQuotes( $s ) {
2150 return '"' . str_replace( '"', '""', $s ) . '"';
2154 * Returns if the given identifier looks quoted or not according to
2155 * the database convention for quoting identifiers .
2157 * @note Do not use this to determine if untrusted input is safe.
2158 * A malicious user can trick this function.
2159 * @param string $name
2162 public function isQuotedIdentifier( $name ) {
2163 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2168 * @param string $escapeChar
2171 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2172 return str_replace( [ $escapeChar, '%', '_' ],
2173 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2177 public function buildLike() {
2178 $params = func_get_args();
2180 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2181 $params = $params[0];
2186 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2187 // may escape backslashes, creating problems of double escaping. The `
2188 // character has good cross-DBMS compatibility, avoiding special operators
2189 // in MS SQL like ^ and %
2192 foreach ( $params as $value ) {
2193 if ( $value instanceof LikeMatch
) {
2194 $s .= $value->toString();
2196 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2200 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2203 public function anyChar() {
2204 return new LikeMatch( '_' );
2207 public function anyString() {
2208 return new LikeMatch( '%' );
2211 public function nextSequenceValue( $seqName ) {
2216 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2217 * is only needed because a) MySQL must be as efficient as possible due to
2218 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2219 * which index to pick. Anyway, other databases might have different
2220 * indexes on a given table. So don't bother overriding this unless you're
2222 * @param string $index
2225 public function useIndexClause( $index ) {
2230 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2231 * is only needed because a) MySQL must be as efficient as possible due to
2232 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2233 * which index to pick. Anyway, other databases might have different
2234 * indexes on a given table. So don't bother overriding this unless you're
2236 * @param string $index
2239 public function ignoreIndexClause( $index ) {
2243 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2244 if ( count( $rows ) == 0 ) {
2249 if ( !is_array( reset( $rows ) ) ) {
2253 $affectedRowCount = 0;
2254 foreach ( $rows as $row ) {
2255 // Delete rows which collide with this one
2256 $indexWhereClauses = [];
2257 foreach ( $uniqueIndexes as $index ) {
2258 $indexColumns = (array)$index;
2259 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2260 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2261 throw new DBUnexpectedError(
2263 'New record does not provide all values for unique key (' .
2264 implode( ', ', $indexColumns ) . ')'
2266 } elseif ( in_array( null, $indexRowValues, true ) ) {
2267 throw new DBUnexpectedError(
2269 'New record has a null value for unique key (' .
2270 implode( ', ', $indexColumns ) . ')'
2273 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2276 if ( $indexWhereClauses ) {
2277 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2278 $affectedRowCount +
= $this->affectedRows();
2281 // Now insert the row
2282 $this->insert( $table, $row, $fname );
2283 $affectedRowCount +
= $this->affectedRows();
2286 $this->affectedRowCount
= $affectedRowCount;
2290 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2293 * @param string $table Table name
2294 * @param array|string $rows Row(s) to insert
2295 * @param string $fname Caller function name
2297 * @return ResultWrapper
2299 protected function nativeReplace( $table, $rows, $fname ) {
2300 $table = $this->tableName( $table );
2303 if ( !is_array( reset( $rows ) ) ) {
2307 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2310 foreach ( $rows as $row ) {
2317 $sql .= '(' . $this->makeList( $row ) . ')';
2320 return $this->query( $sql, $fname );
2323 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2326 if ( !count( $rows ) ) {
2327 return true; // nothing to do
2330 if ( !is_array( reset( $rows ) ) ) {
2334 if ( count( $uniqueIndexes ) ) {
2335 $clauses = []; // list WHERE clauses that each identify a single row
2336 foreach ( $rows as $row ) {
2337 foreach ( $uniqueIndexes as $index ) {
2338 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2339 $rowKey = []; // unique key to this row
2340 foreach ( $index as $column ) {
2341 $rowKey[$column] = $row[$column];
2343 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2346 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2351 $affectedRowCount = 0;
2352 $useTrx = !$this->mTrxLevel
;
2354 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2357 # Update any existing conflicting row(s)
2358 if ( $where !== false ) {
2359 $ok = $this->update( $table, $set, $where, $fname );
2360 $affectedRowCount +
= $this->affectedRows();
2364 # Now insert any non-conflicting row(s)
2365 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2366 $affectedRowCount +
= $this->affectedRows();
2367 } catch ( Exception
$e ) {
2369 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2374 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2376 $this->affectedRowCount
= $affectedRowCount;
2381 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2385 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2388 $delTable = $this->tableName( $delTable );
2389 $joinTable = $this->tableName( $joinTable );
2390 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2391 if ( $conds != '*' ) {
2392 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2396 $this->query( $sql, $fname );
2399 public function textFieldSize( $table, $field ) {
2400 $table = $this->tableName( $table );
2401 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2402 $res = $this->query( $sql, __METHOD__
);
2403 $row = $this->fetchObject( $res );
2407 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2416 public function delete( $table, $conds, $fname = __METHOD__
) {
2418 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2421 $table = $this->tableName( $table );
2422 $sql = "DELETE FROM $table";
2424 if ( $conds != '*' ) {
2425 if ( is_array( $conds ) ) {
2426 $conds = $this->makeList( $conds, self
::LIST_AND
);
2428 $sql .= ' WHERE ' . $conds;
2431 return $this->query( $sql, $fname );
2434 public function insertSelect(
2435 $destTable, $srcTable, $varMap, $conds,
2436 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2438 if ( $this->cliMode
) {
2439 // For massive migrations with downtime, we don't want to select everything
2440 // into memory and OOM, so do all this native on the server side if possible.
2441 return $this->nativeInsertSelect(
2453 return $this->nonNativeInsertSelect(
2466 * Implementation of insertSelect() based on select() and insert()
2468 * @see IDatabase::insertSelect()
2470 * @param string $destTable
2471 * @param string|array $srcTable
2472 * @param array $varMap
2473 * @param array $conds
2474 * @param string $fname
2475 * @param array $insertOptions
2476 * @param array $selectOptions
2477 * @param array $selectJoinConds
2480 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2481 $fname = __METHOD__
,
2482 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2484 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2485 // on only the master (without needing row-based-replication). It also makes it easy to
2486 // know how big the INSERT is going to be.
2488 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2489 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2491 $selectOptions[] = 'FOR UPDATE';
2492 $res = $this->select(
2493 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2500 foreach ( $res as $row ) {
2501 $rows[] = (array)$row;
2504 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2508 * Native server-side implementation of insertSelect() for situations where
2509 * we don't want to select everything into memory
2511 * @see IDatabase::insertSelect()
2512 * @param string $destTable
2513 * @param string|array $srcTable
2514 * @param array $varMap
2515 * @param array $conds
2516 * @param string $fname
2517 * @param array $insertOptions
2518 * @param array $selectOptions
2519 * @param array $selectJoinConds
2522 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2523 $fname = __METHOD__
,
2524 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2526 $destTable = $this->tableName( $destTable );
2528 if ( !is_array( $insertOptions ) ) {
2529 $insertOptions = [ $insertOptions ];
2532 $insertOptions = $this->makeInsertOptions( $insertOptions );
2534 $selectSql = $this->selectSQLText(
2536 array_values( $varMap ),
2543 $sql = "INSERT $insertOptions" .
2544 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2547 return $this->query( $sql, $fname );
2551 * Construct a LIMIT query with optional offset. This is used for query
2552 * pages. The SQL should be adjusted so that only the first $limit rows
2553 * are returned. If $offset is provided as well, then the first $offset
2554 * rows should be discarded, and the next $limit rows should be returned.
2555 * If the result of the query is not ordered, then the rows to be returned
2556 * are theoretically arbitrary.
2558 * $sql is expected to be a SELECT, if that makes a difference.
2560 * The version provided by default works in MySQL and SQLite. It will very
2561 * likely need to be overridden for most other DBMSes.
2563 * @param string $sql SQL query we will append the limit too
2564 * @param int $limit The SQL limit
2565 * @param int|bool $offset The SQL offset (default false)
2566 * @throws DBUnexpectedError
2569 public function limitResult( $sql, $limit, $offset = false ) {
2570 if ( !is_numeric( $limit ) ) {
2571 throw new DBUnexpectedError( $this,
2572 "Invalid non-numeric limit passed to limitResult()\n" );
2575 return "$sql LIMIT "
2576 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2580 public function unionSupportsOrderAndLimit() {
2581 return true; // True for almost every DB supported
2584 public function unionQueries( $sqls, $all ) {
2585 $glue = $all ?
') UNION ALL (' : ') UNION (';
2587 return '(' . implode( $glue, $sqls ) . ')';
2590 public function unionConditionPermutations(
2591 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2592 $options = [], $join_conds = []
2594 // First, build the Cartesian product of $permute_conds
2596 foreach ( $permute_conds as $field => $values ) {
2598 // Skip empty $values
2601 $values = array_unique( $values ); // For sanity
2603 foreach ( $conds as $cond ) {
2604 foreach ( $values as $value ) {
2605 $cond[$field] = $value;
2606 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2612 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2614 // If there's just one condition and no subordering, hand off to
2615 // selectSQLText directly.
2616 if ( count( $conds ) === 1 &&
2617 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2619 return $this->selectSQLText(
2620 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2624 // Otherwise, we need to pull out the order and limit to apply after
2625 // the union. Then build the SQL queries for each set of conditions in
2626 // $conds. Then union them together (using UNION ALL, because the
2627 // product *should* already be distinct).
2628 $orderBy = $this->makeOrderBy( $options );
2629 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2630 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2631 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2632 if ( !$this->unionSupportsOrderAndLimit() ) {
2633 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2635 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2636 $options['ORDER BY'] = $options['INNER ORDER BY'];
2638 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2639 // We need to increase the limit by the offset rather than
2640 // using the offset directly, otherwise it'll skip incorrectly
2641 // in the subqueries.
2642 $options['LIMIT'] = $limit +
$offset;
2643 unset( $options['OFFSET'] );
2648 foreach ( $conds as $cond ) {
2649 $sqls[] = $this->selectSQLText(
2650 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2653 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2654 if ( $limit !== null ) {
2655 $sql = $this->limitResult( $sql, $limit, $offset );
2661 public function conditional( $cond, $trueVal, $falseVal ) {
2662 if ( is_array( $cond ) ) {
2663 $cond = $this->makeList( $cond, self
::LIST_AND
);
2666 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2669 public function strreplace( $orig, $old, $new ) {
2670 return "REPLACE({$orig}, {$old}, {$new})";
2673 public function getServerUptime() {
2677 public function wasDeadlock() {
2681 public function wasLockTimeout() {
2685 public function wasErrorReissuable() {
2689 public function wasReadOnlyError() {
2694 * Do not use this method outside of Database/DBError classes
2696 * @param int|string $errno
2697 * @return bool Whether the given query error was a connection drop
2699 public function wasConnectionError( $errno ) {
2703 public function deadlockLoop() {
2704 $args = func_get_args();
2705 $function = array_shift( $args );
2706 $tries = self
::DEADLOCK_TRIES
;
2708 $this->begin( __METHOD__
);
2711 /** @var Exception $e */
2715 $retVal = call_user_func_array( $function, $args );
2717 } catch ( DBQueryError
$e ) {
2718 if ( $this->wasDeadlock() ) {
2719 // Retry after a randomized delay
2720 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2722 // Throw the error back up
2726 } while ( --$tries > 0 );
2728 if ( $tries <= 0 ) {
2729 // Too many deadlocks; give up
2730 $this->rollback( __METHOD__
);
2733 $this->commit( __METHOD__
);
2739 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2740 # Real waits are implemented in the subclass.
2744 public function getReplicaPos() {
2749 public function getMasterPos() {
2754 public function serverIsReadOnly() {
2758 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2759 if ( !$this->mTrxLevel
) {
2760 throw new DBUnexpectedError( $this, "No transaction is active." );
2762 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2765 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2766 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2767 if ( !$this->mTrxLevel
) {
2768 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2772 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2773 if ( $this->mTrxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2774 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2775 // an implicit commit of all peer databases. This is true even if a transaction has
2776 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2777 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2779 // No transaction is active nor will start implicitly, so make one for this callback
2780 $this->startAtomic( __METHOD__
);
2782 call_user_func( $callback );
2783 $this->endAtomic( __METHOD__
);
2784 } catch ( Exception
$e ) {
2785 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2791 final public function setTransactionListener( $name, callable
$callback = null ) {
2793 $this->mTrxRecurringCallbacks
[$name] = $callback;
2795 unset( $this->mTrxRecurringCallbacks
[$name] );
2800 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2802 * This method should not be used outside of Database/LoadBalancer
2804 * @param bool $suppress
2807 final public function setTrxEndCallbackSuppression( $suppress ) {
2808 $this->mTrxEndCallbacksSuppressed
= $suppress;
2812 * Actually run and consume any "on transaction idle/resolution" callbacks.
2814 * This method should not be used outside of Database/LoadBalancer
2816 * @param int $trigger IDatabase::TRIGGER_* constant
2820 public function runOnTransactionIdleCallbacks( $trigger ) {
2821 if ( $this->mTrxEndCallbacksSuppressed
) {
2825 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2826 /** @var Exception $e */
2827 $e = null; // first exception
2828 do { // callbacks may add callbacks :)
2829 $callbacks = array_merge(
2830 $this->mTrxIdleCallbacks
,
2831 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2833 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2834 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2835 foreach ( $callbacks as $callback ) {
2837 list( $phpCallback ) = $callback;
2838 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2839 call_user_func_array( $phpCallback, [ $trigger ] );
2841 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2843 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2845 } catch ( Exception
$ex ) {
2846 call_user_func( $this->errorLogger
, $ex );
2848 // Some callbacks may use startAtomic/endAtomic, so make sure
2849 // their transactions are ended so other callbacks don't fail
2850 if ( $this->trxLevel() ) {
2851 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2855 } while ( count( $this->mTrxIdleCallbacks
) );
2857 if ( $e instanceof Exception
) {
2858 throw $e; // re-throw any first exception
2863 * Actually run and consume any "on transaction pre-commit" callbacks.
2865 * This method should not be used outside of Database/LoadBalancer
2870 public function runOnTransactionPreCommitCallbacks() {
2871 $e = null; // first exception
2872 do { // callbacks may add callbacks :)
2873 $callbacks = $this->mTrxPreCommitCallbacks
;
2874 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2875 foreach ( $callbacks as $callback ) {
2877 list( $phpCallback ) = $callback;
2878 call_user_func( $phpCallback );
2879 } catch ( Exception
$ex ) {
2880 call_user_func( $this->errorLogger
, $ex );
2884 } while ( count( $this->mTrxPreCommitCallbacks
) );
2886 if ( $e instanceof Exception
) {
2887 throw $e; // re-throw any first exception
2892 * Actually run any "transaction listener" callbacks.
2894 * This method should not be used outside of Database/LoadBalancer
2896 * @param int $trigger IDatabase::TRIGGER_* constant
2900 public function runTransactionListenerCallbacks( $trigger ) {
2901 if ( $this->mTrxEndCallbacksSuppressed
) {
2905 /** @var Exception $e */
2906 $e = null; // first exception
2908 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2910 $phpCallback( $trigger, $this );
2911 } catch ( Exception
$ex ) {
2912 call_user_func( $this->errorLogger
, $ex );
2917 if ( $e instanceof Exception
) {
2918 throw $e; // re-throw any first exception
2922 final public function startAtomic( $fname = __METHOD__
) {
2923 if ( !$this->mTrxLevel
) {
2924 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2925 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2926 // in all changes being in one transaction to keep requests transactional.
2927 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2928 $this->mTrxAutomaticAtomic
= true;
2932 $this->mTrxAtomicLevels
[] = $fname;
2935 final public function endAtomic( $fname = __METHOD__
) {
2936 if ( !$this->mTrxLevel
) {
2937 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2939 if ( !$this->mTrxAtomicLevels ||
2940 array_pop( $this->mTrxAtomicLevels
) !== $fname
2942 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2945 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2946 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2950 final public function doAtomicSection( $fname, callable
$callback ) {
2951 $this->startAtomic( $fname );
2953 $res = call_user_func_array( $callback, [ $this, $fname ] );
2954 } catch ( Exception
$e ) {
2955 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2958 $this->endAtomic( $fname );
2963 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2964 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2965 if ( $this->mTrxLevel
) {
2966 if ( $this->mTrxAtomicLevels
) {
2967 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2968 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2969 throw new DBUnexpectedError( $this, $msg );
2970 } elseif ( !$this->mTrxAutomatic
) {
2971 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2972 throw new DBUnexpectedError( $this, $msg );
2974 // @TODO: make this an exception at some point
2975 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2976 $this->queryLogger
->error( $msg );
2977 return; // join the main transaction set
2979 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2980 // @TODO: make this an exception at some point
2981 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2982 $this->queryLogger
->error( $msg );
2983 return; // let any writes be in the main transaction
2986 // Avoid fatals if close() was called
2987 $this->assertOpen();
2989 $this->doBegin( $fname );
2990 $this->mTrxTimestamp
= microtime( true );
2991 $this->mTrxFname
= $fname;
2992 $this->mTrxDoneWrites
= false;
2993 $this->mTrxAutomaticAtomic
= false;
2994 $this->mTrxAtomicLevels
= [];
2995 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2996 $this->mTrxWriteDuration
= 0.0;
2997 $this->mTrxWriteQueryCount
= 0;
2998 $this->mTrxWriteAffectedRows
= 0;
2999 $this->mTrxWriteAdjDuration
= 0.0;
3000 $this->mTrxWriteAdjQueryCount
= 0;
3001 $this->mTrxWriteCallers
= [];
3002 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3003 // Get an estimate of the replica DB lag before then, treating estimate staleness
3004 // as lag itself just to be safe
3005 $status = $this->getApproximateLagStatus();
3006 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3007 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3008 // caller will think its OK to muck around with the transaction just because startAtomic()
3009 // has not yet completed (e.g. setting mTrxAtomicLevels).
3010 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3014 * Issues the BEGIN command to the database server.
3016 * @see Database::begin()
3017 * @param string $fname
3019 protected function doBegin( $fname ) {
3020 $this->query( 'BEGIN', $fname );
3021 $this->mTrxLevel
= 1;
3024 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3025 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3026 // There are still atomic sections open. This cannot be ignored
3027 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3028 throw new DBUnexpectedError(
3030 "$fname: Got COMMIT while atomic sections $levels are still open."
3034 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3035 if ( !$this->mTrxLevel
) {
3036 return; // nothing to do
3037 } elseif ( !$this->mTrxAutomatic
) {
3038 throw new DBUnexpectedError(
3040 "$fname: Flushing an explicit transaction, getting out of sync."
3044 if ( !$this->mTrxLevel
) {
3045 $this->queryLogger
->error(
3046 "$fname: No transaction to commit, something got out of sync." );
3047 return; // nothing to do
3048 } elseif ( $this->mTrxAutomatic
) {
3049 // @TODO: make this an exception at some point
3050 $msg = "$fname: Explicit commit of implicit transaction.";
3051 $this->queryLogger
->error( $msg );
3052 return; // wait for the main transaction set commit round
3056 // Avoid fatals if close() was called
3057 $this->assertOpen();
3059 $this->runOnTransactionPreCommitCallbacks();
3060 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3061 $this->doCommit( $fname );
3062 if ( $this->mTrxDoneWrites
) {
3063 $this->mLastWriteTime
= microtime( true );
3064 $this->trxProfiler
->transactionWritingOut(
3069 $this->mTrxWriteAffectedRows
3073 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3074 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3078 * Issues the COMMIT command to the database server.
3080 * @see Database::commit()
3081 * @param string $fname
3083 protected function doCommit( $fname ) {
3084 if ( $this->mTrxLevel
) {
3085 $this->query( 'COMMIT', $fname );
3086 $this->mTrxLevel
= 0;
3090 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3091 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3092 if ( !$this->mTrxLevel
) {
3093 return; // nothing to do
3096 if ( !$this->mTrxLevel
) {
3097 $this->queryLogger
->error(
3098 "$fname: No transaction to rollback, something got out of sync." );
3099 return; // nothing to do
3100 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3101 throw new DBUnexpectedError(
3103 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3108 // Avoid fatals if close() was called
3109 $this->assertOpen();
3111 $this->doRollback( $fname );
3112 $this->mTrxAtomicLevels
= [];
3113 if ( $this->mTrxDoneWrites
) {
3114 $this->trxProfiler
->transactionWritingOut(
3121 $this->mTrxIdleCallbacks
= []; // clear
3122 $this->mTrxPreCommitCallbacks
= []; // clear
3124 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3125 } catch ( Exception
$e ) {
3126 // already logged; finish and let LoadBalancer move on during mass-rollback
3129 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3130 } catch ( Exception
$e ) {
3131 // already logged; let LoadBalancer move on during mass-rollback
3136 * Issues the ROLLBACK command to the database server.
3138 * @see Database::rollback()
3139 * @param string $fname
3141 protected function doRollback( $fname ) {
3142 if ( $this->mTrxLevel
) {
3143 # Disconnects cause rollback anyway, so ignore those errors
3144 $ignoreErrors = true;
3145 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3146 $this->mTrxLevel
= 0;
3150 public function flushSnapshot( $fname = __METHOD__
) {
3151 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3152 // This only flushes transactions to clear snapshots, not to write data
3153 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3154 throw new DBUnexpectedError(
3156 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3160 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3163 public function explicitTrxActive() {
3164 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3167 public function duplicateTableStructure(
3168 $oldName, $newName, $temporary = false, $fname = __METHOD__
3170 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3173 public function listTables( $prefix = null, $fname = __METHOD__
) {
3174 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3177 public function listViews( $prefix = null, $fname = __METHOD__
) {
3178 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3181 public function timestamp( $ts = 0 ) {
3182 $t = new ConvertibleTimestamp( $ts );
3183 // Let errors bubble up to avoid putting garbage in the DB
3184 return $t->getTimestamp( TS_MW
);
3187 public function timestampOrNull( $ts = null ) {
3188 if ( is_null( $ts ) ) {
3191 return $this->timestamp( $ts );
3195 public function affectedRows() {
3196 return ( $this->affectedRowCount
=== null )
3197 ?
$this->fetchAffectedRowCount() // default to driver value
3198 : $this->affectedRowCount
;
3202 * @return int Number of retrieved rows according to the driver
3204 abstract protected function fetchAffectedRowCount();
3207 * Take the result from a query, and wrap it in a ResultWrapper if
3208 * necessary. Boolean values are passed through as is, to indicate success
3209 * of write queries or failure.
3211 * Once upon a time, Database::query() returned a bare MySQL result
3212 * resource, and it was necessary to call this function to convert it to
3213 * a wrapper. Nowadays, raw database objects are never exposed to external
3214 * callers, so this is unnecessary in external code.
3216 * @param bool|ResultWrapper|resource|object $result
3217 * @return bool|ResultWrapper
3219 protected function resultObject( $result ) {
3222 } elseif ( $result instanceof ResultWrapper
) {
3224 } elseif ( $result === true ) {
3225 // Successful write query
3228 return new ResultWrapper( $this, $result );
3232 public function ping( &$rtt = null ) {
3233 // Avoid hitting the server if it was hit recently
3234 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3235 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3236 $rtt = $this->mRTTEstimate
;
3237 return true; // don't care about $rtt
3241 // This will reconnect if possible or return false if not
3242 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3243 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3244 $this->restoreFlags( self
::RESTORE_PRIOR
);
3247 $rtt = $this->mRTTEstimate
;
3254 * Close existing database connection and open a new connection
3256 * @return bool True if new connection is opened successfully, false if error
3258 protected function reconnect() {
3259 $this->closeConnection();
3260 $this->mOpened
= false;
3261 $this->mConn
= false;
3263 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3264 $this->lastPing
= microtime( true );
3266 } catch ( DBConnectionError
$e ) {
3273 public function getSessionLagStatus() {
3274 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3278 * Get the replica DB lag when the current transaction started
3280 * This is useful when transactions might use snapshot isolation
3281 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3282 * is this lag plus transaction duration. If they don't, it is still
3283 * safe to be pessimistic. This returns null if there is no transaction.
3285 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3288 protected function getTransactionLagStatus() {
3289 return $this->mTrxLevel
3290 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3295 * Get a replica DB lag estimate for this server
3297 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3300 protected function getApproximateLagStatus() {
3302 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3303 'since' => microtime( true )
3308 * Merge the result of getSessionLagStatus() for several DBs
3309 * using the most pessimistic values to estimate the lag of
3310 * any data derived from them in combination
3312 * This is information is useful for caching modules
3314 * @see WANObjectCache::set()
3315 * @see WANObjectCache::getWithSetCallback()
3317 * @param IDatabase $db1
3318 * @param IDatabase $db2 [optional]
3319 * @return array Map of values:
3320 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3321 * - since: oldest UNIX timestamp of any of the DB lag estimates
3322 * - pending: whether any of the DBs have uncommitted changes
3326 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3327 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3328 foreach ( func_get_args() as $db ) {
3329 /** @var IDatabase $db */
3330 $status = $db->getSessionLagStatus();
3331 if ( $status['lag'] === false ) {
3332 $res['lag'] = false;
3333 } elseif ( $res['lag'] !== false ) {
3334 $res['lag'] = max( $res['lag'], $status['lag'] );
3336 $res['since'] = min( $res['since'], $status['since'] );
3337 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3343 public function getLag() {
3347 public function maxListLen() {
3351 public function encodeBlob( $b ) {
3355 public function decodeBlob( $b ) {
3356 if ( $b instanceof Blob
) {
3362 public function setSessionOptions( array $options ) {
3365 public function sourceFile(
3367 callable
$lineCallback = null,
3368 callable
$resultCallback = null,
3370 callable
$inputCallback = null
3372 Wikimedia\
suppressWarnings();
3373 $fp = fopen( $filename, 'r' );
3374 Wikimedia\restoreWarnings
();
3376 if ( false === $fp ) {
3377 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3381 $fname = __METHOD__
. "( $filename )";
3385 $error = $this->sourceStream(
3386 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3387 } catch ( Exception
$e ) {
3397 public function setSchemaVars( $vars ) {
3398 $this->mSchemaVars
= $vars;
3401 public function sourceStream(
3403 callable
$lineCallback = null,
3404 callable
$resultCallback = null,
3405 $fname = __METHOD__
,
3406 callable
$inputCallback = null
3408 $delimiterReset = new ScopedCallback(
3409 function ( $delimiter ) {
3410 $this->delimiter
= $delimiter;
3412 [ $this->delimiter
]
3416 while ( !feof( $fp ) ) {
3417 if ( $lineCallback ) {
3418 call_user_func( $lineCallback );
3421 $line = trim( fgets( $fp ) );
3423 if ( $line == '' ) {
3427 if ( '-' == $line[0] && '-' == $line[1] ) {
3435 $done = $this->streamStatementEnd( $cmd, $line );
3439 if ( $done ||
feof( $fp ) ) {
3440 $cmd = $this->replaceVars( $cmd );
3442 if ( $inputCallback ) {
3443 $callbackResult = call_user_func( $inputCallback, $cmd );
3445 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3446 $cmd = $callbackResult;
3451 $res = $this->query( $cmd, $fname );
3453 if ( $resultCallback ) {
3454 call_user_func( $resultCallback, $res, $this );
3457 if ( false === $res ) {
3458 $err = $this->lastError();
3460 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3467 ScopedCallback
::consume( $delimiterReset );
3472 * Called by sourceStream() to check if we've reached a statement end
3474 * @param string &$sql SQL assembled so far
3475 * @param string &$newLine New line about to be added to $sql
3476 * @return bool Whether $newLine contains end of the statement
3478 public function streamStatementEnd( &$sql, &$newLine ) {
3479 if ( $this->delimiter
) {
3481 $newLine = preg_replace(
3482 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3483 if ( $newLine != $prev ) {
3492 * Database independent variable replacement. Replaces a set of variables
3493 * in an SQL statement with their contents as given by $this->getSchemaVars().
3495 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3497 * - '{$var}' should be used for text and is passed through the database's
3499 * - `{$var}` should be used for identifiers (e.g. table and database names).
3500 * It is passed through the database's addIdentifierQuotes method which
3501 * can be overridden if the database uses something other than backticks.
3502 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3503 * database's tableName method.
3504 * - / *i* / passes the name that follows through the database's indexName method.
3505 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3506 * its use should be avoided. In 1.24 and older, string encoding was applied.
3508 * @param string $ins SQL statement to replace variables in
3509 * @return string The new SQL statement with variables replaced
3511 protected function replaceVars( $ins ) {
3512 $vars = $this->getSchemaVars();
3513 return preg_replace_callback(
3515 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3516 \'\{\$ (\w+) }\' | # 3. addQuotes
3517 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3518 /\*\$ (\w+) \*/ # 5. leave unencoded
3520 function ( $m ) use ( $vars ) {
3521 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3522 // check for both nonexistent keys *and* the empty string.
3523 if ( isset( $m[1] ) && $m[1] !== '' ) {
3524 if ( $m[1] === 'i' ) {
3525 return $this->indexName( $m[2] );
3527 return $this->tableName( $m[2] );
3529 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3530 return $this->addQuotes( $vars[$m[3]] );
3531 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3532 return $this->addIdentifierQuotes( $vars[$m[4]] );
3533 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3534 return $vars[$m[5]];
3544 * Get schema variables. If none have been set via setSchemaVars(), then
3545 * use some defaults from the current object.
3549 protected function getSchemaVars() {
3550 if ( $this->mSchemaVars
) {
3551 return $this->mSchemaVars
;
3553 return $this->getDefaultSchemaVars();
3558 * Get schema variables to use if none have been set via setSchemaVars().
3560 * Override this in derived classes to provide variables for tables.sql
3561 * and SQL patch files.
3565 protected function getDefaultSchemaVars() {
3569 public function lockIsFree( $lockName, $method ) {
3573 public function lock( $lockName, $method, $timeout = 5 ) {
3574 $this->mNamedLocksHeld
[$lockName] = 1;
3579 public function unlock( $lockName, $method ) {
3580 unset( $this->mNamedLocksHeld
[$lockName] );
3585 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3586 if ( $this->writesOrCallbacksPending() ) {
3587 // This only flushes transactions to clear snapshots, not to write data
3588 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3589 throw new DBUnexpectedError(
3591 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3595 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3599 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3600 if ( $this->trxLevel() ) {
3601 // There is a good chance an exception was thrown, causing any early return
3602 // from the caller. Let any error handler get a chance to issue rollback().
3603 // If there isn't one, let the error bubble up and trigger server-side rollback.
3604 $this->onTransactionResolution(
3605 function () use ( $lockKey, $fname ) {
3606 $this->unlock( $lockKey, $fname );
3611 $this->unlock( $lockKey, $fname );
3615 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3620 public function namedLocksEnqueue() {
3624 public function tableLocksHaveTransactionScope() {
3628 final public function lockTables( array $read, array $write, $method ) {
3629 if ( $this->writesOrCallbacksPending() ) {
3630 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3633 if ( $this->tableLocksHaveTransactionScope() ) {
3634 $this->startAtomic( $method );
3637 return $this->doLockTables( $read, $write, $method );
3641 * Helper function for lockTables() that handles the actual table locking
3643 * @param array $read Array of tables to lock for read access
3644 * @param array $write Array of tables to lock for write access
3645 * @param string $method Name of caller
3648 protected function doLockTables( array $read, array $write, $method ) {
3652 final public function unlockTables( $method ) {
3653 if ( $this->tableLocksHaveTransactionScope() ) {
3654 $this->endAtomic( $method );
3656 return true; // locks released on COMMIT/ROLLBACK
3659 return $this->doUnlockTables( $method );
3663 * Helper function for unlockTables() that handles the actual table unlocking
3665 * @param string $method Name of caller
3668 protected function doUnlockTables( $method ) {
3674 * @param string $tableName
3675 * @param string $fName
3676 * @return bool|ResultWrapper
3679 public function dropTable( $tableName, $fName = __METHOD__
) {
3680 if ( !$this->tableExists( $tableName, $fName ) ) {
3683 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3685 return $this->query( $sql, $fName );
3688 public function getInfinity() {
3692 public function encodeExpiry( $expiry ) {
3693 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3694 ?
$this->getInfinity()
3695 : $this->timestamp( $expiry );
3698 public function decodeExpiry( $expiry, $format = TS_MW
) {
3699 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3703 return ConvertibleTimestamp
::convert( $format, $expiry );
3706 public function setBigSelects( $value = true ) {
3710 public function isReadOnly() {
3711 return ( $this->getReadOnlyReason() !== false );
3715 * @return string|bool Reason this DB is read-only or false if it is not
3717 protected function getReadOnlyReason() {
3718 $reason = $this->getLBInfo( 'readOnlyReason' );
3720 return is_string( $reason ) ?
$reason : false;
3723 public function setTableAliases( array $aliases ) {
3724 $this->tableAliases
= $aliases;
3728 * @return bool Whether a DB user is required to access the DB
3731 protected function requiresDatabaseUser() {
3736 * Get the underlying binding handle, mConn
3738 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3739 * This catches broken callers than catch and ignore disconnection exceptions.
3740 * Unlike checking isOpen(), this is safe to call inside of open().
3742 * @return resource|object
3743 * @throws DBUnexpectedError
3746 protected function getBindingHandle() {
3747 if ( !$this->mConn
) {
3748 throw new DBUnexpectedError(
3750 'DB connection was already closed or the connection dropped.'
3754 return $this->mConn
;
3761 public function __toString() {
3762 return (string)$this->mConn
;
3766 * Make sure that copies do not share the same client binding handle
3767 * @throws DBConnectionError
3769 public function __clone() {
3770 $this->connLogger
->warning(
3771 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3772 ( new RuntimeException() )->getTraceAsString()
3775 if ( $this->isOpen() ) {
3776 // Open a new connection resource without messing with the old one
3777 $this->mOpened
= false;
3778 $this->mConn
= false;
3779 $this->mTrxEndCallbacks
= []; // don't copy
3780 $this->handleSessionLoss(); // no trx or locks anymore
3781 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3782 $this->lastPing
= microtime( true );
3787 * Called by serialize. Throw an exception when DB connection is serialized.
3788 * This causes problems on some database engines because the connection is
3789 * not restored on unserialize.
3791 public function __sleep() {
3792 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3793 'the connection is not restored on wakeup.' );
3797 * Run a few simple sanity checks and close dangling connections
3799 public function __destruct() {
3800 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3801 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3804 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3805 if ( $danglingWriters ) {
3806 $fnames = implode( ', ', $danglingWriters );
3807 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3810 if ( $this->mConn
) {
3811 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3812 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3813 Wikimedia\
suppressWarnings();
3814 $this->closeConnection();
3815 Wikimedia\restoreWarnings
();
3816 $this->mConn
= false;
3817 $this->mOpened
= false;
3822 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3823 class_alias( Database
::class, 'Database' ); // b/c global alias