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
= .010;
58 const SLOW_WRITE_SEC
= .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;
131 * Either 1 if a transaction is active or 0 otherwise.
132 * The other Trx fields may not be meaningfull if this is 0.
136 protected $mTrxLevel = 0;
138 * Either a short hexidecimal string if a transaction is active or ""
141 * @see Database::mTrxLevel
143 protected $mTrxShortId = '';
145 * The UNIX time that the transaction started. Callers can assume that if
146 * snapshot isolation is used, then the data is *at least* up to date to that
147 * point (possibly more up-to-date since the first SELECT defines the snapshot).
150 * @see Database::mTrxLevel
152 private $mTrxTimestamp = null;
153 /** @var float Lag estimate at the time of BEGIN */
154 private $mTrxReplicaLag = null;
156 * Remembers the function name given for starting the most recent transaction via begin().
157 * Used to provide additional context for error reporting.
160 * @see Database::mTrxLevel
162 private $mTrxFname = null;
164 * Record if possible write queries were done in the last transaction started
167 * @see Database::mTrxLevel
169 private $mTrxDoneWrites = false;
171 * Record if the current transaction was started implicitly due to DBO_TRX being set.
174 * @see Database::mTrxLevel
176 private $mTrxAutomatic = false;
178 * Array of levels of atomicity within transactions
182 private $mTrxAtomicLevels = [];
184 * Record if the current transaction was started implicitly by Database::startAtomic
188 private $mTrxAutomaticAtomic = false;
190 * Track the write query callers of the current transaction
194 private $mTrxWriteCallers = [];
196 * @var float Seconds spent in write queries for the current transaction
198 private $mTrxWriteDuration = 0.0;
200 * @var integer Number of write queries for the current transaction
202 private $mTrxWriteQueryCount = 0;
204 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
206 private $mTrxWriteAdjDuration = 0.0;
208 * @var integer Number of write queries counted in mTrxWriteAdjDuration
210 private $mTrxWriteAdjQueryCount = 0;
212 * @var float RTT time estimate
214 private $mRTTEstimate = 0.0;
216 /** @var array Map of (name => 1) for locks obtained via lock() */
217 private $mNamedLocksHeld = [];
218 /** @var array Map of (table name => 1) for TEMPORARY tables */
219 protected $mSessionTempTables = [];
221 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
222 private $lazyMasterHandle;
224 /** @var float UNIX timestamp */
225 protected $lastPing = 0.0;
227 /** @var int[] Prior mFlags values */
228 private $priorFlags = [];
230 /** @var object|string Class name or object With profileIn/profileOut methods */
232 /** @var TransactionProfiler */
233 protected $trxProfiler;
236 * Constructor and database handle and attempt to connect to the DB server
238 * IDatabase classes should not be constructed directly in external
239 * code. Database::factory() should be used instead.
241 * @param array $params Parameters passed from Database::factory()
243 function __construct( array $params ) {
244 $server = $params['host'];
245 $user = $params['user'];
246 $password = $params['password'];
247 $dbName = $params['dbname'];
249 $this->mSchema
= $params['schema'];
250 $this->mTablePrefix
= $params['tablePrefix'];
252 $this->cliMode
= $params['cliMode'];
253 // Agent name is added to SQL queries in a comment, so make sure it can't break out
254 $this->agent
= str_replace( '/', '-', $params['agent'] );
256 $this->mFlags
= $params['flags'];
257 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
258 if ( $this->cliMode
) {
259 $this->mFlags
&= ~self
::DBO_TRX
;
261 $this->mFlags |
= self
::DBO_TRX
;
265 $this->mSessionVars
= $params['variables'];
267 $this->srvCache
= isset( $params['srvCache'] )
268 ?
$params['srvCache']
269 : new HashBagOStuff();
271 $this->profiler
= $params['profiler'];
272 $this->trxProfiler
= $params['trxProfiler'];
273 $this->connLogger
= $params['connLogger'];
274 $this->queryLogger
= $params['queryLogger'];
275 $this->errorLogger
= $params['errorLogger'];
277 // Set initial dummy domain until open() sets the final DB/prefix
278 $this->currentDomain
= DatabaseDomain
::newUnspecified();
281 $this->open( $server, $user, $password, $dbName );
282 } elseif ( $this->requiresDatabaseUser() ) {
283 throw new InvalidArgumentException( "No database user provided." );
286 // Set the domain object after open() sets the relevant fields
287 if ( $this->mDBname
!= '' ) {
288 // Domains with server scope but a table prefix are not used by IDatabase classes
289 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
294 * Construct a Database subclass instance given a database type and parameters
296 * This also connects to the database immediately upon object construction
298 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
299 * @param array $p Parameter map with keys:
300 * - host : The hostname of the DB server
301 * - user : The name of the database user the client operates under
302 * - password : The password for the database user
303 * - dbname : The name of the database to use where queries do not specify one.
304 * The database must exist or an error might be thrown. Setting this to the empty string
305 * will avoid any such errors and make the handle have no implicit database scope. This is
306 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
307 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
308 * in which user names and such are defined, e.g. users are database-specific in Postgres.
309 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
310 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
311 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
312 * recognized in queries. This can be used in place of schemas for handle site farms.
313 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
314 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
315 * flag in place UNLESS this this database simply acts as a key/value store.
316 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
317 * 'mysql' driver and the newer 'mysqli' driver.
318 * - variables: Optional map of session variables to set after connecting. This can be
319 * used to adjust lock timeouts or encoding modes and the like.
320 * - connLogger: Optional PSR-3 logger interface instance.
321 * - queryLogger: Optional PSR-3 logger interface instance.
322 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
323 * These will be called in query(), using a simplified version of the SQL that also
324 * includes the agent as a SQL comment.
325 * - trxProfiler: Optional TransactionProfiler instance.
326 * - errorLogger: Optional callback that takes an Exception and logs it.
327 * - cliMode: Whether to consider the execution context that of a CLI script.
328 * - agent: Optional name used to identify the end-user in query profiling/logging.
329 * - srvCache: Optional BagOStuff instance to an APC-style cache.
330 * @return Database|null If the database driver or extension cannot be found
331 * @throws InvalidArgumentException If the database driver or extension cannot be found
334 final public static function factory( $dbType, $p = [] ) {
335 static $canonicalDBTypes = [
336 'mysql' => [ 'mysqli', 'mysql' ],
342 static $classAliases = [
343 'DatabaseMssql' => DatabaseMssql
::class,
344 'DatabaseMysql' => DatabaseMysql
::class,
345 'DatabaseMysqli' => DatabaseMysqli
::class,
346 'DatabaseSqlite' => DatabaseSqlite
::class,
347 'DatabasePostgres' => DatabasePostgres
::class
351 $dbType = strtolower( $dbType );
352 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
353 $possibleDrivers = $canonicalDBTypes[$dbType];
354 if ( !empty( $p['driver'] ) ) {
355 if ( in_array( $p['driver'], $possibleDrivers ) ) {
356 $driver = $p['driver'];
358 throw new InvalidArgumentException( __METHOD__
.
359 " type '$dbType' does not support driver '{$p['driver']}'" );
362 foreach ( $possibleDrivers as $posDriver ) {
363 if ( extension_loaded( $posDriver ) ) {
364 $driver = $posDriver;
373 if ( $driver === false ||
$driver === '' ) {
374 throw new InvalidArgumentException( __METHOD__
.
375 " no viable database extension found for type '$dbType'" );
378 $class = 'Database' . ucfirst( $driver );
379 if ( isset( $classAliases[$class] ) ) {
380 $class = $classAliases[$class];
383 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
384 // Resolve some defaults for b/c
385 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
386 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
387 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
388 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
389 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
390 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
391 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
392 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
393 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
394 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
395 if ( !isset( $p['connLogger'] ) ) {
396 $p['connLogger'] = new \Psr\Log\
NullLogger();
398 if ( !isset( $p['queryLogger'] ) ) {
399 $p['queryLogger'] = new \Psr\Log\
NullLogger();
401 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
402 if ( !isset( $p['trxProfiler'] ) ) {
403 $p['trxProfiler'] = new TransactionProfiler();
405 if ( !isset( $p['errorLogger'] ) ) {
406 $p['errorLogger'] = function ( Exception
$e ) {
407 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
411 $conn = new $class( $p );
420 * Set the PSR-3 logger interface to use for query logging. (The logger
421 * interfaces for connection logging and error logging can be set with the
424 * @param LoggerInterface $logger
426 public function setLogger( LoggerInterface
$logger ) {
427 $this->queryLogger
= $logger;
430 public function getServerInfo() {
431 return $this->getServerVersion();
434 public function bufferResults( $buffer = null ) {
435 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
436 if ( $buffer !== null ) {
438 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
439 : $this->setFlag( self
::DBO_NOBUFFER
);
446 * Turns on (false) or off (true) the automatic generation and sending
447 * of a "we're sorry, but there has been a database error" page on
448 * database errors. Default is on (false). When turned off, the
449 * code should use lastErrno() and lastError() to handle the
450 * situation as appropriate.
452 * Do not use this function outside of the Database classes.
454 * @param null|bool $ignoreErrors
455 * @return bool The previous value of the flag.
457 protected function ignoreErrors( $ignoreErrors = null ) {
458 $res = $this->getFlag( self
::DBO_IGNORE
);
459 if ( $ignoreErrors !== null ) {
461 ?
$this->setFlag( self
::DBO_IGNORE
)
462 : $this->clearFlag( self
::DBO_IGNORE
);
468 public function trxLevel() {
469 return $this->mTrxLevel
;
472 public function trxTimestamp() {
473 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
476 public function tablePrefix( $prefix = null ) {
477 $old = $this->mTablePrefix
;
478 if ( $prefix !== null ) {
479 $this->mTablePrefix
= $prefix;
480 $this->currentDomain
= ( $this->mDBname
!= '' )
481 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
482 : DatabaseDomain
::newUnspecified();
488 public function dbSchema( $schema = null ) {
489 $old = $this->mSchema
;
490 if ( $schema !== null ) {
491 $this->mSchema
= $schema;
497 public function getLBInfo( $name = null ) {
498 if ( is_null( $name ) ) {
499 return $this->mLBInfo
;
501 if ( array_key_exists( $name, $this->mLBInfo
) ) {
502 return $this->mLBInfo
[$name];
509 public function setLBInfo( $name, $value = null ) {
510 if ( is_null( $value ) ) {
511 $this->mLBInfo
= $name;
513 $this->mLBInfo
[$name] = $value;
517 public function setLazyMasterHandle( IDatabase
$conn ) {
518 $this->lazyMasterHandle
= $conn;
522 * @return IDatabase|null
523 * @see setLazyMasterHandle()
526 protected function getLazyMasterHandle() {
527 return $this->lazyMasterHandle
;
530 public function implicitGroupby() {
534 public function implicitOrderby() {
538 public function lastQuery() {
539 return $this->mLastQuery
;
542 public function doneWrites() {
543 return (bool)$this->mLastWriteTime
;
546 public function lastDoneWrites() {
547 return $this->mLastWriteTime ?
: false;
550 public function writesPending() {
551 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
554 public function writesOrCallbacksPending() {
555 return $this->mTrxLevel
&& (
556 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
560 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
561 if ( !$this->mTrxLevel
) {
563 } elseif ( !$this->mTrxDoneWrites
) {
568 case self
::ESTIMATE_DB_APPLY
:
570 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
571 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
572 // For omitted queries, make them count as something at least
573 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
574 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
577 default: // everything
578 return $this->mTrxWriteDuration
;
582 public function pendingWriteCallers() {
583 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
587 * Get the list of method names that have pending write queries or callbacks
588 * for this transaction
592 protected function pendingWriteAndCallbackCallers() {
593 if ( !$this->mTrxLevel
) {
597 $fnames = $this->mTrxWriteCallers
;
599 $this->mTrxIdleCallbacks
,
600 $this->mTrxPreCommitCallbacks
,
601 $this->mTrxEndCallbacks
603 foreach ( $callbacks as $callback ) {
604 $fnames[] = $callback[1];
611 public function isOpen() {
612 return $this->mOpened
;
615 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
616 if ( $remember === self
::REMEMBER_PRIOR
) {
617 array_push( $this->priorFlags
, $this->mFlags
);
619 $this->mFlags |
= $flag;
622 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
623 if ( $remember === self
::REMEMBER_PRIOR
) {
624 array_push( $this->priorFlags
, $this->mFlags
);
626 $this->mFlags
&= ~
$flag;
629 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
630 if ( !$this->priorFlags
) {
634 if ( $state === self
::RESTORE_INITIAL
) {
635 $this->mFlags
= reset( $this->priorFlags
);
636 $this->priorFlags
= [];
638 $this->mFlags
= array_pop( $this->priorFlags
);
642 public function getFlag( $flag ) {
643 return !!( $this->mFlags
& $flag );
647 * @param string $name Class field name
649 * @deprecated Since 1.28
651 public function getProperty( $name ) {
655 public function getDomainID() {
656 return $this->currentDomain
->getId();
659 final public function getWikiID() {
660 return $this->getDomainID();
664 * Get information about an index into an object
665 * @param string $table Table name
666 * @param string $index Index name
667 * @param string $fname Calling function name
668 * @return mixed Database-specific index description class or false if the index does not exist
670 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
673 * Wrapper for addslashes()
675 * @param string $s String to be slashed.
676 * @return string Slashed string.
678 abstract function strencode( $s );
681 * Set a custom error handler for logging errors during database connection
683 protected function installErrorHandler() {
684 $this->mPHPError
= false;
685 $this->htmlErrors
= ini_set( 'html_errors', '0' );
686 set_error_handler( [ $this, 'connectionErrorLogger' ] );
690 * Restore the previous error handler and return the last PHP error for this DB
692 * @return bool|string
694 protected function restoreErrorHandler() {
695 restore_error_handler();
696 if ( $this->htmlErrors
!== false ) {
697 ini_set( 'html_errors', $this->htmlErrors
);
700 return $this->getLastPHPError();
704 * @return string|bool Last PHP error for this DB (typically connection errors)
706 protected function getLastPHPError() {
707 if ( $this->mPHPError
) {
708 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
709 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
718 * Error handler for logging errors during database connection
719 * This method should not be used outside of Database classes
722 * @param string $errstr
724 public function connectionErrorLogger( $errno, $errstr ) {
725 $this->mPHPError
= $errstr;
729 * Create a log context to pass to PSR-3 logger functions.
731 * @param array $extras Additional data to add to context
734 protected function getLogContext( array $extras = [] ) {
737 'db_server' => $this->mServer
,
738 'db_name' => $this->mDBname
,
739 'db_user' => $this->mUser
,
745 public function close() {
746 if ( $this->mConn
) {
747 if ( $this->trxLevel() ) {
748 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
751 $closed = $this->closeConnection();
752 $this->mConn
= false;
753 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
754 throw new RuntimeException( "Transaction callbacks still pending." );
758 $this->mOpened
= false;
764 * Make sure isOpen() returns true as a sanity check
766 * @throws DBUnexpectedError
768 protected function assertOpen() {
769 if ( !$this->isOpen() ) {
770 throw new DBUnexpectedError( $this, "DB connection was already closed." );
775 * Closes underlying database connection
777 * @return bool Whether connection was closed successfully
779 abstract protected function closeConnection();
781 public function reportConnectionError( $error = 'Unknown error' ) {
782 $myError = $this->lastError();
788 throw new DBConnectionError( $this, $error );
792 * The DBMS-dependent part of query()
794 * @param string $sql SQL query.
795 * @return ResultWrapper|bool Result object to feed to fetchObject,
796 * fetchRow, ...; or false on failure
798 abstract protected function doQuery( $sql );
801 * Determine whether a query writes to the DB.
802 * Should return true if unsure.
807 protected function isWriteQuery( $sql ) {
809 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
814 * @return string|null
816 protected function getQueryVerb( $sql ) {
817 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
821 * Determine whether a SQL statement is sensitive to isolation level.
822 * A SQL statement is considered transactable if its result could vary
823 * depending on the transaction isolation level. Operational commands
824 * such as 'SET' and 'SHOW' are not considered to be transactable.
829 protected function isTransactableQuery( $sql ) {
831 $this->getQueryVerb( $sql ),
832 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
838 * @param string $sql A SQL query
839 * @return bool Whether $sql is SQL for TEMPORARY table operation
841 protected function registerTempTableOperation( $sql ) {
843 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
847 $this->mSessionTempTables
[$matches[1]] = 1;
850 } elseif ( preg_match(
851 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
855 $isTemp = isset( $this->mSessionTempTables
[$matches[1]] );
856 unset( $this->mSessionTempTables
[$matches[1]] );
859 } elseif ( preg_match(
860 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
864 return isset( $this->mSessionTempTables
[$matches[1]] );
865 } elseif ( preg_match(
866 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
870 return isset( $this->mSessionTempTables
[$matches[1]] );
876 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
877 $priorWritesPending = $this->writesOrCallbacksPending();
878 $this->mLastQuery
= $sql;
880 $isWrite = $this->isWriteQuery( $sql );
882 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
884 $isNonTempWrite = false;
888 # In theory, non-persistent writes are allowed in read-only mode, but due to things
889 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
890 $reason = $this->getReadOnlyReason();
891 if ( $reason !== false ) {
892 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
894 # Set a flag indicating that writes have been done
895 $this->mLastWriteTime
= microtime( true );
898 # Add trace comment to the begin of the sql string, right after the operator.
899 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
900 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
902 # Start implicit transactions that wrap the request if DBO_TRX is enabled
903 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
904 && $this->isTransactableQuery( $sql )
906 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
907 $this->mTrxAutomatic
= true;
910 # Keep track of whether the transaction has write queries pending
911 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
912 $this->mTrxDoneWrites
= true;
913 $this->trxProfiler
->transactionWritingIn(
914 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
917 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
918 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
921 # Avoid fatals if close() was called
924 # Send the query to the server
925 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
927 # Try reconnecting if the connection was lost
928 if ( false === $ret && $this->wasErrorReissuable() ) {
929 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
930 # Stash the last error values before anything might clear them
931 $lastError = $this->lastError();
932 $lastErrno = $this->lastErrno();
933 # Update state tracking to reflect transaction loss due to disconnection
934 $this->handleSessionLoss();
935 if ( $this->reconnect() ) {
936 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
937 $this->connLogger
->warning( $msg );
938 $this->queryLogger
->warning(
939 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
941 if ( !$recoverable ) {
942 # Callers may catch the exception and continue to use the DB
943 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
945 # Should be safe to silently retry the query
946 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
949 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
950 $this->connLogger
->error( $msg );
954 if ( false === $ret ) {
955 # Deadlocks cause the entire transaction to abort, not just the statement.
956 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
957 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
958 if ( $this->wasDeadlock() ) {
959 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
960 $tempIgnore = false; // not recoverable
962 # Update state tracking to reflect transaction loss
963 $this->handleSessionLoss();
966 $this->reportQueryError(
967 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
970 $res = $this->resultObject( $ret );
976 * Helper method for query() that handles profiling and logging and sends
977 * the query to doQuery()
979 * @param string $sql Original SQL query
980 * @param string $commentedSql SQL query with debugging/trace comment
981 * @param bool $isWrite Whether the query is a (non-temporary) write operation
982 * @param string $fname Name of the calling function
983 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
984 * object for a successful read query, or false on failure
986 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
987 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
988 # generalizeSQL() will probably cut down the query to reasonable
989 # logging size most of the time. The substr is really just a sanity check.
991 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
993 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
996 # Include query transaction state
997 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
999 $startTime = microtime( true );
1000 if ( $this->profiler
) {
1001 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1003 $ret = $this->doQuery( $commentedSql );
1004 if ( $this->profiler
) {
1005 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1007 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1009 unset( $queryProfSection ); // profile out (if set)
1011 if ( $ret !== false ) {
1012 $this->lastPing
= $startTime;
1013 if ( $isWrite && $this->mTrxLevel
) {
1014 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
1015 $this->mTrxWriteCallers
[] = $fname;
1019 if ( $sql === self
::PING_QUERY
) {
1020 $this->mRTTEstimate
= $queryRuntime;
1023 $this->trxProfiler
->recordQueryCompletion(
1024 $queryProf, $startTime, $isWrite, $this->affectedRows()
1026 $this->queryLogger
->debug( $sql, [
1028 'master' => $isMaster,
1029 'runtime' => $queryRuntime,
1036 * Update the estimated run-time of a query, not counting large row lock times
1038 * LoadBalancer can be set to rollback transactions that will create huge replication
1039 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1040 * queries, like inserting a row can take a long time due to row locking. This method
1041 * uses some simple heuristics to discount those cases.
1043 * @param string $sql A SQL write query
1044 * @param float $runtime Total runtime, including RTT
1046 private function updateTrxWriteQueryTime( $sql, $runtime ) {
1047 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1048 $indicativeOfReplicaRuntime = true;
1049 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1050 $verb = $this->getQueryVerb( $sql );
1051 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1052 if ( $verb === 'INSERT' ) {
1053 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1054 } elseif ( $verb === 'REPLACE' ) {
1055 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1059 $this->mTrxWriteDuration +
= $runtime;
1060 $this->mTrxWriteQueryCount +
= 1;
1061 if ( $indicativeOfReplicaRuntime ) {
1062 $this->mTrxWriteAdjDuration +
= $runtime;
1063 $this->mTrxWriteAdjQueryCount +
= 1;
1068 * Determine whether or not it is safe to retry queries after a database
1069 * connection is lost
1071 * @param string $sql SQL query
1072 * @param bool $priorWritesPending Whether there is a transaction open with
1073 * possible write queries or transaction pre-commit/idle callbacks
1074 * waiting on it to finish.
1075 * @return bool True if it is safe to retry the query, false otherwise
1077 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1078 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1079 # Dropped connections also mean that named locks are automatically released.
1080 # Only allow error suppression in autocommit mode or when the lost transaction
1081 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1082 if ( $this->mNamedLocksHeld
) {
1083 return false; // possible critical section violation
1084 } elseif ( $sql === 'COMMIT' ) {
1085 return !$priorWritesPending; // nothing written anyway? (T127428)
1086 } elseif ( $sql === 'ROLLBACK' ) {
1087 return true; // transaction lost...which is also what was requested :)
1088 } elseif ( $this->explicitTrxActive() ) {
1089 return false; // don't drop atomocity
1090 } elseif ( $priorWritesPending ) {
1091 return false; // prior writes lost from implicit transaction
1098 * Clean things up after transaction loss due to disconnection
1100 * @return null|Exception
1102 private function handleSessionLoss() {
1103 $this->mTrxLevel
= 0;
1104 $this->mTrxIdleCallbacks
= []; // T67263
1105 $this->mTrxPreCommitCallbacks
= []; // T67263
1106 $this->mSessionTempTables
= [];
1107 $this->mNamedLocksHeld
= [];
1109 // Handle callbacks in mTrxEndCallbacks
1110 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1111 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1113 } catch ( Exception
$e ) {
1114 // Already logged; move on...
1119 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1120 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1121 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1123 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1124 $this->queryLogger
->error(
1125 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1126 $this->getLogContext( [
1127 'method' => __METHOD__
,
1130 'sql1line' => $sql1line,
1134 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1135 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1139 public function freeResult( $res ) {
1142 public function selectField(
1143 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1145 if ( $var === '*' ) { // sanity
1146 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1149 if ( !is_array( $options ) ) {
1150 $options = [ $options ];
1153 $options['LIMIT'] = 1;
1155 $res = $this->select( $table, $var, $cond, $fname, $options );
1156 if ( $res === false ||
!$this->numRows( $res ) ) {
1160 $row = $this->fetchRow( $res );
1162 if ( $row !== false ) {
1163 return reset( $row );
1169 public function selectFieldValues(
1170 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1172 if ( $var === '*' ) { // sanity
1173 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1174 } elseif ( !is_string( $var ) ) { // sanity
1175 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1178 if ( !is_array( $options ) ) {
1179 $options = [ $options ];
1182 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1183 if ( $res === false ) {
1188 foreach ( $res as $row ) {
1189 $values[] = $row->$var;
1196 * Returns an optional USE INDEX clause to go after the table, and a
1197 * string to go at the end of the query.
1199 * @param array $options Associative array of options to be turned into
1200 * an SQL query, valid keys are listed in the function.
1202 * @see Database::select()
1204 protected function makeSelectOptions( $options ) {
1205 $preLimitTail = $postLimitTail = '';
1210 foreach ( $options as $key => $option ) {
1211 if ( is_numeric( $key ) ) {
1212 $noKeyOptions[$option] = true;
1216 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1218 $preLimitTail .= $this->makeOrderBy( $options );
1220 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1221 $postLimitTail .= ' FOR UPDATE';
1224 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1225 $postLimitTail .= ' LOCK IN SHARE MODE';
1228 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1229 $startOpts .= 'DISTINCT';
1232 # Various MySQL extensions
1233 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1234 $startOpts .= ' /*! STRAIGHT_JOIN */';
1237 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1238 $startOpts .= ' HIGH_PRIORITY';
1241 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1242 $startOpts .= ' SQL_BIG_RESULT';
1245 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1246 $startOpts .= ' SQL_BUFFER_RESULT';
1249 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1250 $startOpts .= ' SQL_SMALL_RESULT';
1253 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1254 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1257 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1258 $startOpts .= ' SQL_CACHE';
1261 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1262 $startOpts .= ' SQL_NO_CACHE';
1265 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1266 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1270 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1271 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1276 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1280 * Returns an optional GROUP BY with an optional HAVING
1282 * @param array $options Associative array of options
1284 * @see Database::select()
1287 protected function makeGroupByWithHaving( $options ) {
1289 if ( isset( $options['GROUP BY'] ) ) {
1290 $gb = is_array( $options['GROUP BY'] )
1291 ?
implode( ',', $options['GROUP BY'] )
1292 : $options['GROUP BY'];
1293 $sql .= ' GROUP BY ' . $gb;
1295 if ( isset( $options['HAVING'] ) ) {
1296 $having = is_array( $options['HAVING'] )
1297 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1298 : $options['HAVING'];
1299 $sql .= ' HAVING ' . $having;
1306 * Returns an optional ORDER BY
1308 * @param array $options Associative array of options
1310 * @see Database::select()
1313 protected function makeOrderBy( $options ) {
1314 if ( isset( $options['ORDER BY'] ) ) {
1315 $ob = is_array( $options['ORDER BY'] )
1316 ?
implode( ',', $options['ORDER BY'] )
1317 : $options['ORDER BY'];
1319 return ' ORDER BY ' . $ob;
1325 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1326 $options = [], $join_conds = [] ) {
1327 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1329 return $this->query( $sql, $fname );
1332 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1333 $options = [], $join_conds = []
1335 if ( is_array( $vars ) ) {
1336 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1339 $options = (array)$options;
1340 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1341 ?
$options['USE INDEX']
1344 isset( $options['IGNORE INDEX'] ) &&
1345 is_array( $options['IGNORE INDEX'] )
1347 ?
$options['IGNORE INDEX']
1350 if ( is_array( $table ) ) {
1352 $this->tableNamesWithIndexClauseOrJOIN(
1353 $table, $useIndexes, $ignoreIndexes, $join_conds );
1354 } elseif ( $table != '' ) {
1355 if ( $table[0] == ' ' ) {
1356 $from = ' FROM ' . $table;
1359 $this->tableNamesWithIndexClauseOrJOIN(
1360 [ $table ], $useIndexes, $ignoreIndexes, [] );
1366 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1367 $this->makeSelectOptions( $options );
1369 if ( !empty( $conds ) ) {
1370 if ( is_array( $conds ) ) {
1371 $conds = $this->makeList( $conds, self
::LIST_AND
);
1373 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1374 "WHERE $conds $preLimitTail";
1376 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1379 if ( isset( $options['LIMIT'] ) ) {
1380 $sql = $this->limitResult( $sql, $options['LIMIT'],
1381 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1383 $sql = "$sql $postLimitTail";
1385 if ( isset( $options['EXPLAIN'] ) ) {
1386 $sql = 'EXPLAIN ' . $sql;
1392 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1393 $options = [], $join_conds = []
1395 $options = (array)$options;
1396 $options['LIMIT'] = 1;
1397 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1399 if ( $res === false ) {
1403 if ( !$this->numRows( $res ) ) {
1407 $obj = $this->fetchObject( $res );
1412 public function estimateRowCount(
1413 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1416 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1419 $row = $this->fetchRow( $res );
1420 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1426 public function selectRowCount(
1427 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1430 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1431 // The identifier quotes is primarily for MSSQL.
1432 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1433 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1434 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1437 $row = $this->fetchRow( $res );
1438 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1445 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1446 * It's only slightly flawed. Don't use for anything important.
1448 * @param string $sql A SQL Query
1452 protected static function generalizeSQL( $sql ) {
1453 # This does the same as the regexp below would do, but in such a way
1454 # as to avoid crashing php on some large strings.
1455 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1457 $sql = str_replace( "\\\\", '', $sql );
1458 $sql = str_replace( "\\'", '', $sql );
1459 $sql = str_replace( "\\\"", '', $sql );
1460 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1461 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1463 # All newlines, tabs, etc replaced by single space
1464 $sql = preg_replace( '/\s+/', ' ', $sql );
1467 # except the ones surrounded by characters, e.g. l10n
1468 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1469 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1474 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1475 $info = $this->fieldInfo( $table, $field );
1480 public function indexExists( $table, $index, $fname = __METHOD__
) {
1481 if ( !$this->tableExists( $table ) ) {
1485 $info = $this->indexInfo( $table, $index, $fname );
1486 if ( is_null( $info ) ) {
1489 return $info !== false;
1493 public function tableExists( $table, $fname = __METHOD__
) {
1494 $tableRaw = $this->tableName( $table, 'raw' );
1495 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1496 return true; // already known to exist
1499 $table = $this->tableName( $table );
1500 $ignoreErrors = true;
1501 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1506 public function indexUnique( $table, $index ) {
1507 $indexInfo = $this->indexInfo( $table, $index );
1509 if ( !$indexInfo ) {
1513 return !$indexInfo[0]->Non_unique
;
1517 * Helper for Database::insert().
1519 * @param array $options
1522 protected function makeInsertOptions( $options ) {
1523 return implode( ' ', $options );
1526 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1527 # No rows to insert, easy just return now
1528 if ( !count( $a ) ) {
1532 $table = $this->tableName( $table );
1534 if ( !is_array( $options ) ) {
1535 $options = [ $options ];
1539 if ( isset( $options['fileHandle'] ) ) {
1540 $fh = $options['fileHandle'];
1542 $options = $this->makeInsertOptions( $options );
1544 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1546 $keys = array_keys( $a[0] );
1549 $keys = array_keys( $a );
1552 $sql = 'INSERT ' . $options .
1553 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1557 foreach ( $a as $row ) {
1563 $sql .= '(' . $this->makeList( $row ) . ')';
1566 $sql .= '(' . $this->makeList( $a ) . ')';
1569 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1571 } elseif ( $fh !== null ) {
1575 return (bool)$this->query( $sql, $fname );
1579 * Make UPDATE options array for Database::makeUpdateOptions
1581 * @param array $options
1584 protected function makeUpdateOptionsArray( $options ) {
1585 if ( !is_array( $options ) ) {
1586 $options = [ $options ];
1591 if ( in_array( 'IGNORE', $options ) ) {
1599 * Make UPDATE options for the Database::update function
1601 * @param array $options The options passed to Database::update
1604 protected function makeUpdateOptions( $options ) {
1605 $opts = $this->makeUpdateOptionsArray( $options );
1607 return implode( ' ', $opts );
1610 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1611 $table = $this->tableName( $table );
1612 $opts = $this->makeUpdateOptions( $options );
1613 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1615 if ( $conds !== [] && $conds !== '*' ) {
1616 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1619 return (bool)$this->query( $sql, $fname );
1622 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1623 if ( !is_array( $a ) ) {
1624 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1630 foreach ( $a as $field => $value ) {
1632 if ( $mode == self
::LIST_AND
) {
1634 } elseif ( $mode == self
::LIST_OR
) {
1643 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1644 $list .= "($value)";
1645 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1648 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1650 // Remove null from array to be handled separately if found
1651 $includeNull = false;
1652 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1653 $includeNull = true;
1654 unset( $value[$nullKey] );
1656 if ( count( $value ) == 0 && !$includeNull ) {
1657 throw new InvalidArgumentException(
1658 __METHOD__
. ": empty input for field $field" );
1659 } elseif ( count( $value ) == 0 ) {
1660 // only check if $field is null
1661 $list .= "$field IS NULL";
1663 // IN clause contains at least one valid element
1664 if ( $includeNull ) {
1665 // Group subconditions to ensure correct precedence
1668 if ( count( $value ) == 1 ) {
1669 // Special-case single values, as IN isn't terribly efficient
1670 // Don't necessarily assume the single key is 0; we don't
1671 // enforce linear numeric ordering on other arrays here.
1672 $value = array_values( $value )[0];
1673 $list .= $field . " = " . $this->addQuotes( $value );
1675 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1677 // if null present in array, append IS NULL
1678 if ( $includeNull ) {
1679 $list .= " OR $field IS NULL)";
1682 } elseif ( $value === null ) {
1683 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1684 $list .= "$field IS ";
1685 } elseif ( $mode == self
::LIST_SET
) {
1686 $list .= "$field = ";
1691 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1693 $list .= "$field = ";
1695 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1702 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1705 foreach ( $data as $base => $sub ) {
1706 if ( count( $sub ) ) {
1707 $conds[] = $this->makeList(
1708 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1714 return $this->makeList( $conds, self
::LIST_OR
);
1716 // Nothing to search for...
1721 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1725 public function bitNot( $field ) {
1729 public function bitAnd( $fieldLeft, $fieldRight ) {
1730 return "($fieldLeft & $fieldRight)";
1733 public function bitOr( $fieldLeft, $fieldRight ) {
1734 return "($fieldLeft | $fieldRight)";
1737 public function buildConcat( $stringList ) {
1738 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1741 public function buildGroupConcatField(
1742 $delim, $table, $field, $conds = '', $join_conds = []
1744 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1746 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1749 public function buildStringCast( $field ) {
1753 public function databasesAreIndependent() {
1757 public function selectDB( $db ) {
1758 # Stub. Shouldn't cause serious problems if it's not overridden, but
1759 # if your database engine supports a concept similar to MySQL's
1760 # databases you may as well.
1761 $this->mDBname
= $db;
1766 public function getDBname() {
1767 return $this->mDBname
;
1770 public function getServer() {
1771 return $this->mServer
;
1774 public function tableName( $name, $format = 'quoted' ) {
1775 # Skip the entire process when we have a string quoted on both ends.
1776 # Note that we check the end so that we will still quote any use of
1777 # use of `database`.table. But won't break things if someone wants
1778 # to query a database table with a dot in the name.
1779 if ( $this->isQuotedIdentifier( $name ) ) {
1783 # Lets test for any bits of text that should never show up in a table
1784 # name. Basically anything like JOIN or ON which are actually part of
1785 # SQL queries, but may end up inside of the table value to combine
1786 # sql. Such as how the API is doing.
1787 # Note that we use a whitespace test rather than a \b test to avoid
1788 # any remote case where a word like on may be inside of a table name
1789 # surrounded by symbols which may be considered word breaks.
1790 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1794 # Split database and table into proper variables.
1795 # We reverse the explode so that database.table and table both output
1796 # the correct table.
1797 $dbDetails = explode( '.', $name, 3 );
1798 if ( count( $dbDetails ) == 3 ) {
1799 list( $database, $schema, $table ) = $dbDetails;
1800 # We don't want any prefix added in this case
1802 } elseif ( count( $dbDetails ) == 2 ) {
1803 list( $database, $table ) = $dbDetails;
1804 # We don't want any prefix added in this case
1806 # In dbs that support it, $database may actually be the schema
1807 # but that doesn't affect any of the functionality here
1810 list( $table ) = $dbDetails;
1811 if ( isset( $this->tableAliases
[$table] ) ) {
1812 $database = $this->tableAliases
[$table]['dbname'];
1813 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1814 ?
$this->tableAliases
[$table]['schema']
1816 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1817 ?
$this->tableAliases
[$table]['prefix']
1818 : $this->mTablePrefix
;
1821 $schema = $this->mSchema
; # Default schema
1822 $prefix = $this->mTablePrefix
; # Default prefix
1826 # Quote $table and apply the prefix if not quoted.
1827 # $tableName might be empty if this is called from Database::replaceVars()
1828 $tableName = "{$prefix}{$table}";
1829 if ( $format === 'quoted'
1830 && !$this->isQuotedIdentifier( $tableName )
1831 && $tableName !== ''
1833 $tableName = $this->addIdentifierQuotes( $tableName );
1836 # Quote $schema and $database and merge them with the table name if needed
1837 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1838 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1844 * @param string|null $namespace Database or schema
1845 * @param string $relation Name of table, view, sequence, etc...
1846 * @param string $format One of (raw, quoted)
1847 * @return string Relation name with quoted and merged $namespace as needed
1849 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1850 if ( strlen( $namespace ) ) {
1851 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1852 $namespace = $this->addIdentifierQuotes( $namespace );
1854 $relation = $namespace . '.' . $relation;
1860 public function tableNames() {
1861 $inArray = func_get_args();
1864 foreach ( $inArray as $name ) {
1865 $retVal[$name] = $this->tableName( $name );
1871 public function tableNamesN() {
1872 $inArray = func_get_args();
1875 foreach ( $inArray as $name ) {
1876 $retVal[] = $this->tableName( $name );
1883 * Get an aliased table name
1884 * e.g. tableName AS newTableName
1886 * @param string $name Table name, see tableName()
1887 * @param string|bool $alias Alias (optional)
1888 * @return string SQL name for aliased table. Will not alias a table to its own name
1890 protected function tableNameWithAlias( $name, $alias = false ) {
1891 if ( !$alias ||
$alias == $name ) {
1892 return $this->tableName( $name );
1894 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1899 * Gets an array of aliased table names
1901 * @param array $tables [ [alias] => table ]
1902 * @return string[] See tableNameWithAlias()
1904 protected function tableNamesWithAlias( $tables ) {
1906 foreach ( $tables as $alias => $table ) {
1907 if ( is_numeric( $alias ) ) {
1910 $retval[] = $this->tableNameWithAlias( $table, $alias );
1917 * Get an aliased field name
1918 * e.g. fieldName AS newFieldName
1920 * @param string $name Field name
1921 * @param string|bool $alias Alias (optional)
1922 * @return string SQL name for aliased field. Will not alias a field to its own name
1924 protected function fieldNameWithAlias( $name, $alias = false ) {
1925 if ( !$alias ||
(string)$alias === (string)$name ) {
1928 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1933 * Gets an array of aliased field names
1935 * @param array $fields [ [alias] => field ]
1936 * @return string[] See fieldNameWithAlias()
1938 protected function fieldNamesWithAlias( $fields ) {
1940 foreach ( $fields as $alias => $field ) {
1941 if ( is_numeric( $alias ) ) {
1944 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1951 * Get the aliased table name clause for a FROM clause
1952 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1954 * @param array $tables ( [alias] => table )
1955 * @param array $use_index Same as for select()
1956 * @param array $ignore_index Same as for select()
1957 * @param array $join_conds Same as for select()
1960 protected function tableNamesWithIndexClauseOrJOIN(
1961 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1965 $use_index = (array)$use_index;
1966 $ignore_index = (array)$ignore_index;
1967 $join_conds = (array)$join_conds;
1969 foreach ( $tables as $alias => $table ) {
1970 if ( !is_string( $alias ) ) {
1971 // No alias? Set it equal to the table name
1974 // Is there a JOIN clause for this table?
1975 if ( isset( $join_conds[$alias] ) ) {
1976 list( $joinType, $conds ) = $join_conds[$alias];
1977 $tableClause = $joinType;
1978 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1979 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1980 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1982 $tableClause .= ' ' . $use;
1985 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1986 $ignore = $this->ignoreIndexClause(
1987 implode( ',', (array)$ignore_index[$alias] ) );
1988 if ( $ignore != '' ) {
1989 $tableClause .= ' ' . $ignore;
1992 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1994 $tableClause .= ' ON (' . $on . ')';
1997 $retJOIN[] = $tableClause;
1998 } elseif ( isset( $use_index[$alias] ) ) {
1999 // Is there an INDEX clause for this table?
2000 $tableClause = $this->tableNameWithAlias( $table, $alias );
2001 $tableClause .= ' ' . $this->useIndexClause(
2002 implode( ',', (array)$use_index[$alias] )
2005 $ret[] = $tableClause;
2006 } elseif ( isset( $ignore_index[$alias] ) ) {
2007 // Is there an INDEX clause for this table?
2008 $tableClause = $this->tableNameWithAlias( $table, $alias );
2009 $tableClause .= ' ' . $this->ignoreIndexClause(
2010 implode( ',', (array)$ignore_index[$alias] )
2013 $ret[] = $tableClause;
2015 $tableClause = $this->tableNameWithAlias( $table, $alias );
2017 $ret[] = $tableClause;
2021 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2022 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2023 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2025 // Compile our final table clause
2026 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2030 * Allows for index remapping in queries where this is not consistent across DBMS
2032 * @param string $index
2035 protected function indexName( $index ) {
2039 public function addQuotes( $s ) {
2040 if ( $s instanceof Blob
) {
2043 if ( $s === null ) {
2045 } elseif ( is_bool( $s ) ) {
2048 # This will also quote numeric values. This should be harmless,
2049 # and protects against weird problems that occur when they really
2050 # _are_ strings such as article titles and string->number->string
2051 # conversion is not 1:1.
2052 return "'" . $this->strencode( $s ) . "'";
2057 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2058 * MySQL uses `backticks` while basically everything else uses double quotes.
2059 * Since MySQL is the odd one out here the double quotes are our generic
2060 * and we implement backticks in DatabaseMysql.
2065 public function addIdentifierQuotes( $s ) {
2066 return '"' . str_replace( '"', '""', $s ) . '"';
2070 * Returns if the given identifier looks quoted or not according to
2071 * the database convention for quoting identifiers .
2073 * @note Do not use this to determine if untrusted input is safe.
2074 * A malicious user can trick this function.
2075 * @param string $name
2078 public function isQuotedIdentifier( $name ) {
2079 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2086 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2087 return str_replace( [ $escapeChar, '%', '_' ],
2088 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2092 public function buildLike() {
2093 $params = func_get_args();
2095 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2096 $params = $params[0];
2101 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2102 // may escape backslashes, creating problems of double escaping. The `
2103 // character has good cross-DBMS compatibility, avoiding special operators
2104 // in MS SQL like ^ and %
2107 foreach ( $params as $value ) {
2108 if ( $value instanceof LikeMatch
) {
2109 $s .= $value->toString();
2111 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2115 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2118 public function anyChar() {
2119 return new LikeMatch( '_' );
2122 public function anyString() {
2123 return new LikeMatch( '%' );
2126 public function nextSequenceValue( $seqName ) {
2131 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2132 * is only needed because a) MySQL must be as efficient as possible due to
2133 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2134 * which index to pick. Anyway, other databases might have different
2135 * indexes on a given table. So don't bother overriding this unless you're
2137 * @param string $index
2140 public function useIndexClause( $index ) {
2145 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2146 * is only needed because a) MySQL must be as efficient as possible due to
2147 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2148 * which index to pick. Anyway, other databases might have different
2149 * indexes on a given table. So don't bother overriding this unless you're
2151 * @param string $index
2154 public function ignoreIndexClause( $index ) {
2158 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2159 $quotedTable = $this->tableName( $table );
2161 if ( count( $rows ) == 0 ) {
2166 if ( !is_array( reset( $rows ) ) ) {
2170 // @FXIME: this is not atomic, but a trx would break affectedRows()
2171 foreach ( $rows as $row ) {
2172 # Delete rows which collide
2173 if ( $uniqueIndexes ) {
2174 $sql = "DELETE FROM $quotedTable WHERE ";
2176 foreach ( $uniqueIndexes as $index ) {
2183 if ( is_array( $index ) ) {
2185 foreach ( $index as $col ) {
2191 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2194 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2198 $this->query( $sql, $fname );
2201 # Now insert the row
2202 $this->insert( $table, $row, $fname );
2207 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2210 * @param string $table Table name
2211 * @param array|string $rows Row(s) to insert
2212 * @param string $fname Caller function name
2214 * @return ResultWrapper
2216 protected function nativeReplace( $table, $rows, $fname ) {
2217 $table = $this->tableName( $table );
2220 if ( !is_array( reset( $rows ) ) ) {
2224 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2227 foreach ( $rows as $row ) {
2234 $sql .= '(' . $this->makeList( $row ) . ')';
2237 return $this->query( $sql, $fname );
2240 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2243 if ( !count( $rows ) ) {
2244 return true; // nothing to do
2247 if ( !is_array( reset( $rows ) ) ) {
2251 if ( count( $uniqueIndexes ) ) {
2252 $clauses = []; // list WHERE clauses that each identify a single row
2253 foreach ( $rows as $row ) {
2254 foreach ( $uniqueIndexes as $index ) {
2255 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2256 $rowKey = []; // unique key to this row
2257 foreach ( $index as $column ) {
2258 $rowKey[$column] = $row[$column];
2260 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2263 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2268 $useTrx = !$this->mTrxLevel
;
2270 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2273 # Update any existing conflicting row(s)
2274 if ( $where !== false ) {
2275 $ok = $this->update( $table, $set, $where, $fname );
2279 # Now insert any non-conflicting row(s)
2280 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2281 } catch ( Exception
$e ) {
2283 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2288 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2294 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2298 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2301 $delTable = $this->tableName( $delTable );
2302 $joinTable = $this->tableName( $joinTable );
2303 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2304 if ( $conds != '*' ) {
2305 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2309 $this->query( $sql, $fname );
2312 public function textFieldSize( $table, $field ) {
2313 $table = $this->tableName( $table );
2314 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2315 $res = $this->query( $sql, __METHOD__
);
2316 $row = $this->fetchObject( $res );
2320 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2329 public function delete( $table, $conds, $fname = __METHOD__
) {
2331 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2334 $table = $this->tableName( $table );
2335 $sql = "DELETE FROM $table";
2337 if ( $conds != '*' ) {
2338 if ( is_array( $conds ) ) {
2339 $conds = $this->makeList( $conds, self
::LIST_AND
);
2341 $sql .= ' WHERE ' . $conds;
2344 return $this->query( $sql, $fname );
2347 public function insertSelect(
2348 $destTable, $srcTable, $varMap, $conds,
2349 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2351 if ( $this->cliMode
) {
2352 // For massive migrations with downtime, we don't want to select everything
2353 // into memory and OOM, so do all this native on the server side if possible.
2354 return $this->nativeInsertSelect(
2365 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2366 // on only the master (without needing row-based-replication). It also makes it easy to
2367 // know how big the INSERT is going to be.
2369 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2370 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2372 $selectOptions[] = 'FOR UPDATE';
2373 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2379 foreach ( $res as $row ) {
2380 $rows[] = (array)$row;
2383 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2387 * Native server-side implementation of insertSelect() for situations where
2388 * we don't want to select everything into memory
2390 * @see IDatabase::insertSelect()
2392 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2393 $fname = __METHOD__
,
2394 $insertOptions = [], $selectOptions = []
2396 $destTable = $this->tableName( $destTable );
2398 if ( !is_array( $insertOptions ) ) {
2399 $insertOptions = [ $insertOptions ];
2402 $insertOptions = $this->makeInsertOptions( $insertOptions );
2404 if ( !is_array( $selectOptions ) ) {
2405 $selectOptions = [ $selectOptions ];
2408 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2411 if ( is_array( $srcTable ) ) {
2412 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2414 $srcTable = $this->tableName( $srcTable );
2417 $sql = "INSERT $insertOptions" .
2418 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2419 " SELECT $startOpts " . implode( ',', $varMap ) .
2420 " FROM $srcTable $useIndex $ignoreIndex ";
2422 if ( $conds != '*' ) {
2423 if ( is_array( $conds ) ) {
2424 $conds = $this->makeList( $conds, self
::LIST_AND
);
2426 $sql .= " WHERE $conds";
2429 $sql .= " $tailOpts";
2431 return $this->query( $sql, $fname );
2435 * Construct a LIMIT query with optional offset. This is used for query
2436 * pages. The SQL should be adjusted so that only the first $limit rows
2437 * are returned. If $offset is provided as well, then the first $offset
2438 * rows should be discarded, and the next $limit rows should be returned.
2439 * If the result of the query is not ordered, then the rows to be returned
2440 * are theoretically arbitrary.
2442 * $sql is expected to be a SELECT, if that makes a difference.
2444 * The version provided by default works in MySQL and SQLite. It will very
2445 * likely need to be overridden for most other DBMSes.
2447 * @param string $sql SQL query we will append the limit too
2448 * @param int $limit The SQL limit
2449 * @param int|bool $offset The SQL offset (default false)
2450 * @throws DBUnexpectedError
2453 public function limitResult( $sql, $limit, $offset = false ) {
2454 if ( !is_numeric( $limit ) ) {
2455 throw new DBUnexpectedError( $this,
2456 "Invalid non-numeric limit passed to limitResult()\n" );
2459 return "$sql LIMIT "
2460 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2464 public function unionSupportsOrderAndLimit() {
2465 return true; // True for almost every DB supported
2468 public function unionQueries( $sqls, $all ) {
2469 $glue = $all ?
') UNION ALL (' : ') UNION (';
2471 return '(' . implode( $glue, $sqls ) . ')';
2474 public function conditional( $cond, $trueVal, $falseVal ) {
2475 if ( is_array( $cond ) ) {
2476 $cond = $this->makeList( $cond, self
::LIST_AND
);
2479 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2482 public function strreplace( $orig, $old, $new ) {
2483 return "REPLACE({$orig}, {$old}, {$new})";
2486 public function getServerUptime() {
2490 public function wasDeadlock() {
2494 public function wasLockTimeout() {
2498 public function wasErrorReissuable() {
2502 public function wasReadOnlyError() {
2507 * Do not use this method outside of Database/DBError classes
2509 * @param integer|string $errno
2510 * @return bool Whether the given query error was a connection drop
2512 public function wasConnectionError( $errno ) {
2516 public function deadlockLoop() {
2517 $args = func_get_args();
2518 $function = array_shift( $args );
2519 $tries = self
::DEADLOCK_TRIES
;
2521 $this->begin( __METHOD__
);
2524 /** @var Exception $e */
2528 $retVal = call_user_func_array( $function, $args );
2530 } catch ( DBQueryError
$e ) {
2531 if ( $this->wasDeadlock() ) {
2532 // Retry after a randomized delay
2533 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2535 // Throw the error back up
2539 } while ( --$tries > 0 );
2541 if ( $tries <= 0 ) {
2542 // Too many deadlocks; give up
2543 $this->rollback( __METHOD__
);
2546 $this->commit( __METHOD__
);
2552 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2553 # Real waits are implemented in the subclass.
2557 public function getReplicaPos() {
2562 public function getMasterPos() {
2567 public function serverIsReadOnly() {
2571 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2572 if ( !$this->mTrxLevel
) {
2573 throw new DBUnexpectedError( $this, "No transaction is active." );
2575 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2578 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2579 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2580 if ( !$this->mTrxLevel
) {
2581 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2585 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2586 if ( $this->mTrxLevel
) {
2587 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2589 // If no transaction is active, then make one for this callback
2590 $this->startAtomic( __METHOD__
);
2592 call_user_func( $callback );
2593 $this->endAtomic( __METHOD__
);
2594 } catch ( Exception
$e ) {
2595 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2601 final public function setTransactionListener( $name, callable
$callback = null ) {
2603 $this->mTrxRecurringCallbacks
[$name] = $callback;
2605 unset( $this->mTrxRecurringCallbacks
[$name] );
2610 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2612 * This method should not be used outside of Database/LoadBalancer
2614 * @param bool $suppress
2617 final public function setTrxEndCallbackSuppression( $suppress ) {
2618 $this->mTrxEndCallbacksSuppressed
= $suppress;
2622 * Actually run and consume any "on transaction idle/resolution" callbacks.
2624 * This method should not be used outside of Database/LoadBalancer
2626 * @param integer $trigger IDatabase::TRIGGER_* constant
2630 public function runOnTransactionIdleCallbacks( $trigger ) {
2631 if ( $this->mTrxEndCallbacksSuppressed
) {
2635 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2636 /** @var Exception $e */
2637 $e = null; // first exception
2638 do { // callbacks may add callbacks :)
2639 $callbacks = array_merge(
2640 $this->mTrxIdleCallbacks
,
2641 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2643 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2644 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2645 foreach ( $callbacks as $callback ) {
2647 list( $phpCallback ) = $callback;
2648 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2649 call_user_func_array( $phpCallback, [ $trigger ] );
2651 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2653 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2655 } catch ( Exception
$ex ) {
2656 call_user_func( $this->errorLogger
, $ex );
2658 // Some callbacks may use startAtomic/endAtomic, so make sure
2659 // their transactions are ended so other callbacks don't fail
2660 if ( $this->trxLevel() ) {
2661 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2665 } while ( count( $this->mTrxIdleCallbacks
) );
2667 if ( $e instanceof Exception
) {
2668 throw $e; // re-throw any first exception
2673 * Actually run and consume any "on transaction pre-commit" callbacks.
2675 * This method should not be used outside of Database/LoadBalancer
2680 public function runOnTransactionPreCommitCallbacks() {
2681 $e = null; // first exception
2682 do { // callbacks may add callbacks :)
2683 $callbacks = $this->mTrxPreCommitCallbacks
;
2684 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2685 foreach ( $callbacks as $callback ) {
2687 list( $phpCallback ) = $callback;
2688 call_user_func( $phpCallback );
2689 } catch ( Exception
$ex ) {
2690 call_user_func( $this->errorLogger
, $ex );
2694 } while ( count( $this->mTrxPreCommitCallbacks
) );
2696 if ( $e instanceof Exception
) {
2697 throw $e; // re-throw any first exception
2702 * Actually run any "transaction listener" callbacks.
2704 * This method should not be used outside of Database/LoadBalancer
2706 * @param integer $trigger IDatabase::TRIGGER_* constant
2710 public function runTransactionListenerCallbacks( $trigger ) {
2711 if ( $this->mTrxEndCallbacksSuppressed
) {
2715 /** @var Exception $e */
2716 $e = null; // first exception
2718 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2720 $phpCallback( $trigger, $this );
2721 } catch ( Exception
$ex ) {
2722 call_user_func( $this->errorLogger
, $ex );
2727 if ( $e instanceof Exception
) {
2728 throw $e; // re-throw any first exception
2732 final public function startAtomic( $fname = __METHOD__
) {
2733 if ( !$this->mTrxLevel
) {
2734 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2735 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2736 // in all changes being in one transaction to keep requests transactional.
2737 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2738 $this->mTrxAutomaticAtomic
= true;
2742 $this->mTrxAtomicLevels
[] = $fname;
2745 final public function endAtomic( $fname = __METHOD__
) {
2746 if ( !$this->mTrxLevel
) {
2747 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2749 if ( !$this->mTrxAtomicLevels ||
2750 array_pop( $this->mTrxAtomicLevels
) !== $fname
2752 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2755 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2756 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2760 final public function doAtomicSection( $fname, callable
$callback ) {
2761 $this->startAtomic( $fname );
2763 $res = call_user_func_array( $callback, [ $this, $fname ] );
2764 } catch ( Exception
$e ) {
2765 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2768 $this->endAtomic( $fname );
2773 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2774 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2775 if ( $this->mTrxLevel
) {
2776 if ( $this->mTrxAtomicLevels
) {
2777 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2778 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2779 throw new DBUnexpectedError( $this, $msg );
2780 } elseif ( !$this->mTrxAutomatic
) {
2781 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2782 throw new DBUnexpectedError( $this, $msg );
2784 // @TODO: make this an exception at some point
2785 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2786 $this->queryLogger
->error( $msg );
2787 return; // join the main transaction set
2789 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2790 // @TODO: make this an exception at some point
2791 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2792 $this->queryLogger
->error( $msg );
2793 return; // let any writes be in the main transaction
2796 // Avoid fatals if close() was called
2797 $this->assertOpen();
2799 $this->doBegin( $fname );
2800 $this->mTrxTimestamp
= microtime( true );
2801 $this->mTrxFname
= $fname;
2802 $this->mTrxDoneWrites
= false;
2803 $this->mTrxAutomaticAtomic
= false;
2804 $this->mTrxAtomicLevels
= [];
2805 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2806 $this->mTrxWriteDuration
= 0.0;
2807 $this->mTrxWriteQueryCount
= 0;
2808 $this->mTrxWriteAdjDuration
= 0.0;
2809 $this->mTrxWriteAdjQueryCount
= 0;
2810 $this->mTrxWriteCallers
= [];
2811 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2812 // Get an estimate of the replica DB lag before then, treating estimate staleness
2813 // as lag itself just to be safe
2814 $status = $this->getApproximateLagStatus();
2815 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2816 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2817 // caller will think its OK to muck around with the transaction just because startAtomic()
2818 // has not yet completed (e.g. setting mTrxAtomicLevels).
2819 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2823 * Issues the BEGIN command to the database server.
2825 * @see Database::begin()
2826 * @param string $fname
2828 protected function doBegin( $fname ) {
2829 $this->query( 'BEGIN', $fname );
2830 $this->mTrxLevel
= 1;
2833 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2834 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2835 // There are still atomic sections open. This cannot be ignored
2836 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2837 throw new DBUnexpectedError(
2839 "$fname: Got COMMIT while atomic sections $levels are still open."
2843 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2844 if ( !$this->mTrxLevel
) {
2845 return; // nothing to do
2846 } elseif ( !$this->mTrxAutomatic
) {
2847 throw new DBUnexpectedError(
2849 "$fname: Flushing an explicit transaction, getting out of sync."
2853 if ( !$this->mTrxLevel
) {
2854 $this->queryLogger
->error(
2855 "$fname: No transaction to commit, something got out of sync." );
2856 return; // nothing to do
2857 } elseif ( $this->mTrxAutomatic
) {
2858 // @TODO: make this an exception at some point
2859 $msg = "$fname: Explicit commit of implicit transaction.";
2860 $this->queryLogger
->error( $msg );
2861 return; // wait for the main transaction set commit round
2865 // Avoid fatals if close() was called
2866 $this->assertOpen();
2868 $this->runOnTransactionPreCommitCallbacks();
2869 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2870 $this->doCommit( $fname );
2871 if ( $this->mTrxDoneWrites
) {
2872 $this->mLastWriteTime
= microtime( true );
2873 $this->trxProfiler
->transactionWritingOut(
2874 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2877 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2878 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2882 * Issues the COMMIT command to the database server.
2884 * @see Database::commit()
2885 * @param string $fname
2887 protected function doCommit( $fname ) {
2888 if ( $this->mTrxLevel
) {
2889 $this->query( 'COMMIT', $fname );
2890 $this->mTrxLevel
= 0;
2894 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2895 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2896 if ( !$this->mTrxLevel
) {
2897 return; // nothing to do
2900 if ( !$this->mTrxLevel
) {
2901 $this->queryLogger
->error(
2902 "$fname: No transaction to rollback, something got out of sync." );
2903 return; // nothing to do
2904 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2905 throw new DBUnexpectedError(
2907 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2912 // Avoid fatals if close() was called
2913 $this->assertOpen();
2915 $this->doRollback( $fname );
2916 $this->mTrxAtomicLevels
= [];
2917 if ( $this->mTrxDoneWrites
) {
2918 $this->trxProfiler
->transactionWritingOut(
2919 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2922 $this->mTrxIdleCallbacks
= []; // clear
2923 $this->mTrxPreCommitCallbacks
= []; // clear
2924 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2925 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2929 * Issues the ROLLBACK command to the database server.
2931 * @see Database::rollback()
2932 * @param string $fname
2934 protected function doRollback( $fname ) {
2935 if ( $this->mTrxLevel
) {
2936 # Disconnects cause rollback anyway, so ignore those errors
2937 $ignoreErrors = true;
2938 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2939 $this->mTrxLevel
= 0;
2943 public function flushSnapshot( $fname = __METHOD__
) {
2944 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2945 // This only flushes transactions to clear snapshots, not to write data
2946 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2947 throw new DBUnexpectedError(
2949 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2953 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2956 public function explicitTrxActive() {
2957 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2960 public function duplicateTableStructure(
2961 $oldName, $newName, $temporary = false, $fname = __METHOD__
2963 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2966 public function listTables( $prefix = null, $fname = __METHOD__
) {
2967 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2970 public function listViews( $prefix = null, $fname = __METHOD__
) {
2971 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2974 public function timestamp( $ts = 0 ) {
2975 $t = new ConvertibleTimestamp( $ts );
2976 // Let errors bubble up to avoid putting garbage in the DB
2977 return $t->getTimestamp( TS_MW
);
2980 public function timestampOrNull( $ts = null ) {
2981 if ( is_null( $ts ) ) {
2984 return $this->timestamp( $ts );
2989 * Take the result from a query, and wrap it in a ResultWrapper if
2990 * necessary. Boolean values are passed through as is, to indicate success
2991 * of write queries or failure.
2993 * Once upon a time, Database::query() returned a bare MySQL result
2994 * resource, and it was necessary to call this function to convert it to
2995 * a wrapper. Nowadays, raw database objects are never exposed to external
2996 * callers, so this is unnecessary in external code.
2998 * @param bool|ResultWrapper|resource|object $result
2999 * @return bool|ResultWrapper
3001 protected function resultObject( $result ) {
3004 } elseif ( $result instanceof ResultWrapper
) {
3006 } elseif ( $result === true ) {
3007 // Successful write query
3010 return new ResultWrapper( $this, $result );
3014 public function ping( &$rtt = null ) {
3015 // Avoid hitting the server if it was hit recently
3016 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3017 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3018 $rtt = $this->mRTTEstimate
;
3019 return true; // don't care about $rtt
3023 // This will reconnect if possible or return false if not
3024 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3025 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3026 $this->restoreFlags( self
::RESTORE_PRIOR
);
3029 $rtt = $this->mRTTEstimate
;
3036 * Close existing database connection and open a new connection
3038 * @return bool True if new connection is opened successfully, false if error
3040 protected function reconnect() {
3041 $this->closeConnection();
3042 $this->mOpened
= false;
3043 $this->mConn
= false;
3045 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3046 $this->lastPing
= microtime( true );
3048 } catch ( DBConnectionError
$e ) {
3055 public function getSessionLagStatus() {
3056 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3060 * Get the replica DB lag when the current transaction started
3062 * This is useful when transactions might use snapshot isolation
3063 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3064 * is this lag plus transaction duration. If they don't, it is still
3065 * safe to be pessimistic. This returns null if there is no transaction.
3067 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3070 protected function getTransactionLagStatus() {
3071 return $this->mTrxLevel
3072 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3077 * Get a replica DB lag estimate for this server
3079 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3082 protected function getApproximateLagStatus() {
3084 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3085 'since' => microtime( true )
3090 * Merge the result of getSessionLagStatus() for several DBs
3091 * using the most pessimistic values to estimate the lag of
3092 * any data derived from them in combination
3094 * This is information is useful for caching modules
3096 * @see WANObjectCache::set()
3097 * @see WANObjectCache::getWithSetCallback()
3099 * @param IDatabase $db1
3100 * @param IDatabase ...
3101 * @return array Map of values:
3102 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3103 * - since: oldest UNIX timestamp of any of the DB lag estimates
3104 * - pending: whether any of the DBs have uncommitted changes
3107 public static function getCacheSetOptions( IDatabase
$db1 ) {
3108 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3109 foreach ( func_get_args() as $db ) {
3110 /** @var IDatabase $db */
3111 $status = $db->getSessionLagStatus();
3112 if ( $status['lag'] === false ) {
3113 $res['lag'] = false;
3114 } elseif ( $res['lag'] !== false ) {
3115 $res['lag'] = max( $res['lag'], $status['lag'] );
3117 $res['since'] = min( $res['since'], $status['since'] );
3118 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3124 public function getLag() {
3128 public function maxListLen() {
3132 public function encodeBlob( $b ) {
3136 public function decodeBlob( $b ) {
3137 if ( $b instanceof Blob
) {
3143 public function setSessionOptions( array $options ) {
3146 public function sourceFile(
3148 callable
$lineCallback = null,
3149 callable
$resultCallback = null,
3151 callable
$inputCallback = null
3153 MediaWiki\
suppressWarnings();
3154 $fp = fopen( $filename, 'r' );
3155 MediaWiki\restoreWarnings
();
3157 if ( false === $fp ) {
3158 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3162 $fname = __METHOD__
. "( $filename )";
3166 $error = $this->sourceStream(
3167 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3168 } catch ( Exception
$e ) {
3178 public function setSchemaVars( $vars ) {
3179 $this->mSchemaVars
= $vars;
3182 public function sourceStream(
3184 callable
$lineCallback = null,
3185 callable
$resultCallback = null,
3186 $fname = __METHOD__
,
3187 callable
$inputCallback = null
3191 while ( !feof( $fp ) ) {
3192 if ( $lineCallback ) {
3193 call_user_func( $lineCallback );
3196 $line = trim( fgets( $fp ) );
3198 if ( $line == '' ) {
3202 if ( '-' == $line[0] && '-' == $line[1] ) {
3210 $done = $this->streamStatementEnd( $cmd, $line );
3214 if ( $done ||
feof( $fp ) ) {
3215 $cmd = $this->replaceVars( $cmd );
3217 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3218 $res = $this->query( $cmd, $fname );
3220 if ( $resultCallback ) {
3221 call_user_func( $resultCallback, $res, $this );
3224 if ( false === $res ) {
3225 $err = $this->lastError();
3227 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3238 * Called by sourceStream() to check if we've reached a statement end
3240 * @param string &$sql SQL assembled so far
3241 * @param string &$newLine New line about to be added to $sql
3242 * @return bool Whether $newLine contains end of the statement
3244 public function streamStatementEnd( &$sql, &$newLine ) {
3245 if ( $this->delimiter
) {
3247 $newLine = preg_replace(
3248 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3249 if ( $newLine != $prev ) {
3258 * Database independent variable replacement. Replaces a set of variables
3259 * in an SQL statement with their contents as given by $this->getSchemaVars().
3261 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3263 * - '{$var}' should be used for text and is passed through the database's
3265 * - `{$var}` should be used for identifiers (e.g. table and database names).
3266 * It is passed through the database's addIdentifierQuotes method which
3267 * can be overridden if the database uses something other than backticks.
3268 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3269 * database's tableName method.
3270 * - / *i* / passes the name that follows through the database's indexName method.
3271 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3272 * its use should be avoided. In 1.24 and older, string encoding was applied.
3274 * @param string $ins SQL statement to replace variables in
3275 * @return string The new SQL statement with variables replaced
3277 protected function replaceVars( $ins ) {
3278 $vars = $this->getSchemaVars();
3279 return preg_replace_callback(
3281 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3282 \'\{\$ (\w+) }\' | # 3. addQuotes
3283 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3284 /\*\$ (\w+) \*/ # 5. leave unencoded
3286 function ( $m ) use ( $vars ) {
3287 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3288 // check for both nonexistent keys *and* the empty string.
3289 if ( isset( $m[1] ) && $m[1] !== '' ) {
3290 if ( $m[1] === 'i' ) {
3291 return $this->indexName( $m[2] );
3293 return $this->tableName( $m[2] );
3295 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3296 return $this->addQuotes( $vars[$m[3]] );
3297 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3298 return $this->addIdentifierQuotes( $vars[$m[4]] );
3299 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3300 return $vars[$m[5]];
3310 * Get schema variables. If none have been set via setSchemaVars(), then
3311 * use some defaults from the current object.
3315 protected function getSchemaVars() {
3316 if ( $this->mSchemaVars
) {
3317 return $this->mSchemaVars
;
3319 return $this->getDefaultSchemaVars();
3324 * Get schema variables to use if none have been set via setSchemaVars().
3326 * Override this in derived classes to provide variables for tables.sql
3327 * and SQL patch files.
3331 protected function getDefaultSchemaVars() {
3335 public function lockIsFree( $lockName, $method ) {
3339 public function lock( $lockName, $method, $timeout = 5 ) {
3340 $this->mNamedLocksHeld
[$lockName] = 1;
3345 public function unlock( $lockName, $method ) {
3346 unset( $this->mNamedLocksHeld
[$lockName] );
3351 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3352 if ( $this->writesOrCallbacksPending() ) {
3353 // This only flushes transactions to clear snapshots, not to write data
3354 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3355 throw new DBUnexpectedError(
3357 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3361 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3365 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3366 if ( $this->trxLevel() ) {
3367 // There is a good chance an exception was thrown, causing any early return
3368 // from the caller. Let any error handler get a chance to issue rollback().
3369 // If there isn't one, let the error bubble up and trigger server-side rollback.
3370 $this->onTransactionResolution(
3371 function () use ( $lockKey, $fname ) {
3372 $this->unlock( $lockKey, $fname );
3377 $this->unlock( $lockKey, $fname );
3381 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3386 public function namedLocksEnqueue() {
3390 public function tableLocksHaveTransactionScope() {
3394 final public function lockTables( array $read, array $write, $method ) {
3395 if ( $this->writesOrCallbacksPending() ) {
3396 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3399 if ( $this->tableLocksHaveTransactionScope() ) {
3400 $this->startAtomic( $method );
3403 return $this->doLockTables( $read, $write, $method );
3407 * Helper function for lockTables() that handles the actual table locking
3409 * @param array $read Array of tables to lock for read access
3410 * @param array $write Array of tables to lock for write access
3411 * @param string $method Name of caller
3414 protected function doLockTables( array $read, array $write, $method ) {
3418 final public function unlockTables( $method ) {
3419 if ( $this->tableLocksHaveTransactionScope() ) {
3420 $this->endAtomic( $method );
3422 return true; // locks released on COMMIT/ROLLBACK
3425 return $this->doUnlockTables( $method );
3429 * Helper function for unlockTables() that handles the actual table unlocking
3431 * @param string $method Name of caller
3434 protected function doUnlockTables( $method ) {
3440 * @param string $tableName
3441 * @param string $fName
3442 * @return bool|ResultWrapper
3445 public function dropTable( $tableName, $fName = __METHOD__
) {
3446 if ( !$this->tableExists( $tableName, $fName ) ) {
3449 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3451 return $this->query( $sql, $fName );
3454 public function getInfinity() {
3458 public function encodeExpiry( $expiry ) {
3459 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3460 ?
$this->getInfinity()
3461 : $this->timestamp( $expiry );
3464 public function decodeExpiry( $expiry, $format = TS_MW
) {
3465 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3469 return ConvertibleTimestamp
::convert( $format, $expiry );
3472 public function setBigSelects( $value = true ) {
3476 public function isReadOnly() {
3477 return ( $this->getReadOnlyReason() !== false );
3481 * @return string|bool Reason this DB is read-only or false if it is not
3483 protected function getReadOnlyReason() {
3484 $reason = $this->getLBInfo( 'readOnlyReason' );
3486 return is_string( $reason ) ?
$reason : false;
3489 public function setTableAliases( array $aliases ) {
3490 $this->tableAliases
= $aliases;
3494 * @return bool Whether a DB user is required to access the DB
3497 protected function requiresDatabaseUser() {
3502 * Get the underlying binding handle, mConn
3504 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3505 * This catches broken callers than catch and ignore disconnection exceptions.
3506 * Unlike checking isOpen(), this is safe to call inside of open().
3508 * @return resource|object
3509 * @throws DBUnexpectedError
3512 protected function getBindingHandle() {
3513 if ( !$this->mConn
) {
3514 throw new DBUnexpectedError(
3516 'DB connection was already closed or the connection dropped.'
3520 return $this->mConn
;
3527 public function __toString() {
3528 return (string)$this->mConn
;
3532 * Make sure that copies do not share the same client binding handle
3533 * @throws DBConnectionError
3535 public function __clone() {
3536 $this->connLogger
->warning(
3537 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3538 ( new RuntimeException() )->getTraceAsString()
3541 if ( $this->isOpen() ) {
3542 // Open a new connection resource without messing with the old one
3543 $this->mOpened
= false;
3544 $this->mConn
= false;
3545 $this->mTrxEndCallbacks
= []; // don't copy
3546 $this->handleSessionLoss(); // no trx or locks anymore
3547 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3548 $this->lastPing
= microtime( true );
3553 * Called by serialize. Throw an exception when DB connection is serialized.
3554 * This causes problems on some database engines because the connection is
3555 * not restored on unserialize.
3557 public function __sleep() {
3558 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3559 'the connection is not restored on wakeup.' );
3563 * Run a few simple sanity checks and close dangling connections
3565 public function __destruct() {
3566 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3567 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3570 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3571 if ( $danglingWriters ) {
3572 $fnames = implode( ', ', $danglingWriters );
3573 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3576 if ( $this->mConn
) {
3577 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3578 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3579 \MediaWiki\
suppressWarnings();
3580 $this->closeConnection();
3581 \MediaWiki\restoreWarnings
();
3582 $this->mConn
= false;
3583 $this->mOpened
= false;
3588 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3589 class_alias( Database
::class, 'Database' ); // b/c global alias