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 use Psr\Log\LoggerAwareInterface
;
27 use Psr\Log\LoggerInterface
;
28 use Wikimedia\ScopedCallback
;
29 use Wikimedia\Rdbms\TransactionProfiler
;
30 use Wikimedia\Rdbms\LikeMatch
;
31 use Wikimedia\Rdbms\DatabaseDomain
;
32 use Wikimedia\Rdbms\DBMasterPos
;
33 use Wikimedia\Rdbms\Blob
;
36 * Relational database abstraction object
41 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
42 /** Number of times to re-try an operation in case of deadlock */
43 const DEADLOCK_TRIES
= 4;
44 /** Minimum time to wait before retry, in microseconds */
45 const DEADLOCK_DELAY_MIN
= 500000;
46 /** Maximum time to wait before retry */
47 const DEADLOCK_DELAY_MAX
= 1500000;
49 /** How long before it is worth doing a dummy query to test the connection */
51 const PING_QUERY
= 'SELECT 1 AS ping';
53 const TINY_WRITE_SEC
= .010;
54 const SLOW_WRITE_SEC
= .500;
55 const SMALL_WRITE_ROWS
= 100;
57 /** @var string SQL query */
58 protected $mLastQuery = '';
59 /** @var float|bool UNIX timestamp of last write query */
60 protected $mLastWriteTime = false;
61 /** @var string|bool */
62 protected $mPHPError = false;
71 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
72 protected $tableAliases = [];
73 /** @var bool Whether this PHP instance is for a CLI script */
75 /** @var string Agent name for query profiling */
78 /** @var BagOStuff APC cache */
80 /** @var LoggerInterface */
81 protected $connLogger;
82 /** @var LoggerInterface */
83 protected $queryLogger;
84 /** @var callback Error logging callback */
85 protected $errorLogger;
87 /** @var resource|null Database connection */
88 protected $mConn = null;
90 protected $mOpened = false;
92 /** @var array[] List of (callable, method name) */
93 protected $mTrxIdleCallbacks = [];
94 /** @var array[] List of (callable, method name) */
95 protected $mTrxPreCommitCallbacks = [];
96 /** @var array[] List of (callable, method name) */
97 protected $mTrxEndCallbacks = [];
98 /** @var callable[] Map of (name => callable) */
99 protected $mTrxRecurringCallbacks = [];
100 /** @var bool Whether to suppress triggering of transaction end callbacks */
101 protected $mTrxEndCallbacksSuppressed = false;
104 protected $mTablePrefix = '';
106 protected $mSchema = '';
110 protected $mLBInfo = [];
111 /** @var bool|null */
112 protected $mDefaultBigSelects = null;
113 /** @var array|bool */
114 protected $mSchemaVars = false;
116 protected $mSessionVars = [];
117 /** @var array|null */
118 protected $preparedArgs;
119 /** @var string|bool|null Stashed value of html_errors INI setting */
120 protected $htmlErrors;
122 protected $delimiter = ';';
123 /** @var DatabaseDomain */
124 protected $currentDomain;
127 * Either 1 if a transaction is active or 0 otherwise.
128 * The other Trx fields may not be meaningfull if this is 0.
132 protected $mTrxLevel = 0;
134 * Either a short hexidecimal string if a transaction is active or ""
137 * @see Database::mTrxLevel
139 protected $mTrxShortId = '';
141 * The UNIX time that the transaction started. Callers can assume that if
142 * snapshot isolation is used, then the data is *at least* up to date to that
143 * point (possibly more up-to-date since the first SELECT defines the snapshot).
146 * @see Database::mTrxLevel
148 private $mTrxTimestamp = null;
149 /** @var float Lag estimate at the time of BEGIN */
150 private $mTrxReplicaLag = null;
152 * Remembers the function name given for starting the most recent transaction via begin().
153 * Used to provide additional context for error reporting.
156 * @see Database::mTrxLevel
158 private $mTrxFname = null;
160 * Record if possible write queries were done in the last transaction started
163 * @see Database::mTrxLevel
165 private $mTrxDoneWrites = false;
167 * Record if the current transaction was started implicitly due to DBO_TRX being set.
170 * @see Database::mTrxLevel
172 private $mTrxAutomatic = false;
174 * Array of levels of atomicity within transactions
178 private $mTrxAtomicLevels = [];
180 * Record if the current transaction was started implicitly by Database::startAtomic
184 private $mTrxAutomaticAtomic = false;
186 * Track the write query callers of the current transaction
190 private $mTrxWriteCallers = [];
192 * @var float Seconds spent in write queries for the current transaction
194 private $mTrxWriteDuration = 0.0;
196 * @var integer Number of write queries for the current transaction
198 private $mTrxWriteQueryCount = 0;
200 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
202 private $mTrxWriteAdjDuration = 0.0;
204 * @var integer Number of write queries counted in mTrxWriteAdjDuration
206 private $mTrxWriteAdjQueryCount = 0;
208 * @var float RTT time estimate
210 private $mRTTEstimate = 0.0;
212 /** @var array Map of (name => 1) for locks obtained via lock() */
213 private $mNamedLocksHeld = [];
214 /** @var array Map of (table name => 1) for TEMPORARY tables */
215 protected $mSessionTempTables = [];
217 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
218 private $lazyMasterHandle;
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
226 /** @var object|string Class name or object With profileIn/profileOut methods */
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
232 * Constructor and database handle and attempt to connect to the DB server
234 * IDatabase classes should not be constructed directly in external
235 * code. Database::factory() should be used instead.
237 * @param array $params Parameters passed from Database::factory()
239 function __construct( array $params ) {
240 $server = $params['host'];
241 $user = $params['user'];
242 $password = $params['password'];
243 $dbName = $params['dbname'];
245 $this->mSchema
= $params['schema'];
246 $this->mTablePrefix
= $params['tablePrefix'];
248 $this->cliMode
= $params['cliMode'];
249 // Agent name is added to SQL queries in a comment, so make sure it can't break out
250 $this->agent
= str_replace( '/', '-', $params['agent'] );
252 $this->mFlags
= $params['flags'];
253 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
254 if ( $this->cliMode
) {
255 $this->mFlags
&= ~self
::DBO_TRX
;
257 $this->mFlags |
= self
::DBO_TRX
;
261 $this->mSessionVars
= $params['variables'];
263 $this->srvCache
= isset( $params['srvCache'] )
264 ?
$params['srvCache']
265 : new HashBagOStuff();
267 $this->profiler
= $params['profiler'];
268 $this->trxProfiler
= $params['trxProfiler'];
269 $this->connLogger
= $params['connLogger'];
270 $this->queryLogger
= $params['queryLogger'];
271 $this->errorLogger
= $params['errorLogger'];
273 // Set initial dummy domain until open() sets the final DB/prefix
274 $this->currentDomain
= DatabaseDomain
::newUnspecified();
277 $this->open( $server, $user, $password, $dbName );
278 } elseif ( $this->requiresDatabaseUser() ) {
279 throw new InvalidArgumentException( "No database user provided." );
282 // Set the domain object after open() sets the relevant fields
283 if ( $this->mDBname
!= '' ) {
284 // Domains with server scope but a table prefix are not used by IDatabase classes
285 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
290 * Construct a Database subclass instance given a database type and parameters
292 * This also connects to the database immediately upon object construction
294 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
295 * @param array $p Parameter map with keys:
296 * - host : The hostname of the DB server
297 * - user : The name of the database user the client operates under
298 * - password : The password for the database user
299 * - dbname : The name of the database to use where queries do not specify one.
300 * The database must exist or an error might be thrown. Setting this to the empty string
301 * will avoid any such errors and make the handle have no implicit database scope. This is
302 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
303 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
304 * in which user names and such are defined, e.g. users are database-specific in Postgres.
305 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
306 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
307 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
308 * recognized in queries. This can be used in place of schemas for handle site farms.
309 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
310 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
311 * flag in place UNLESS this this database simply acts as a key/value store.
312 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
313 * 'mysql' driver and the newer 'mysqli' driver.
314 * - variables: Optional map of session variables to set after connecting. This can be
315 * used to adjust lock timeouts or encoding modes and the like.
316 * - connLogger: Optional PSR-3 logger interface instance.
317 * - queryLogger: Optional PSR-3 logger interface instance.
318 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
319 * These will be called in query(), using a simplified version of the SQL that also
320 * includes the agent as a SQL comment.
321 * - trxProfiler: Optional TransactionProfiler instance.
322 * - errorLogger: Optional callback that takes an Exception and logs it.
323 * - cliMode: Whether to consider the execution context that of a CLI script.
324 * - agent: Optional name used to identify the end-user in query profiling/logging.
325 * - srvCache: Optional BagOStuff instance to an APC-style cache.
326 * @return Database|null If the database driver or extension cannot be found
327 * @throws InvalidArgumentException If the database driver or extension cannot be found
330 final public static function factory( $dbType, $p = [] ) {
331 static $canonicalDBTypes = [
332 'mysql' => [ 'mysqli', 'mysql' ],
340 $dbType = strtolower( $dbType );
341 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
342 $possibleDrivers = $canonicalDBTypes[$dbType];
343 if ( !empty( $p['driver'] ) ) {
344 if ( in_array( $p['driver'], $possibleDrivers ) ) {
345 $driver = $p['driver'];
347 throw new InvalidArgumentException( __METHOD__
.
348 " type '$dbType' does not support driver '{$p['driver']}'" );
351 foreach ( $possibleDrivers as $posDriver ) {
352 if ( extension_loaded( $posDriver ) ) {
353 $driver = $posDriver;
361 if ( $driver === false ||
$driver === '' ) {
362 throw new InvalidArgumentException( __METHOD__
.
363 " no viable database extension found for type '$dbType'" );
366 $class = 'Database' . ucfirst( $driver );
367 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
368 // Resolve some defaults for b/c
369 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
370 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
371 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
372 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
373 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
374 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
375 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
376 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
377 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
378 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
379 if ( !isset( $p['connLogger'] ) ) {
380 $p['connLogger'] = new \Psr\Log\
NullLogger();
382 if ( !isset( $p['queryLogger'] ) ) {
383 $p['queryLogger'] = new \Psr\Log\
NullLogger();
385 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
386 if ( !isset( $p['trxProfiler'] ) ) {
387 $p['trxProfiler'] = new TransactionProfiler();
389 if ( !isset( $p['errorLogger'] ) ) {
390 $p['errorLogger'] = function ( Exception
$e ) {
391 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
395 $conn = new $class( $p );
403 public function setLogger( LoggerInterface
$logger ) {
404 $this->queryLogger
= $logger;
407 public function getServerInfo() {
408 return $this->getServerVersion();
411 public function bufferResults( $buffer = null ) {
412 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
413 if ( $buffer !== null ) {
415 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
416 : $this->setFlag( self
::DBO_NOBUFFER
);
423 * Turns on (false) or off (true) the automatic generation and sending
424 * of a "we're sorry, but there has been a database error" page on
425 * database errors. Default is on (false). When turned off, the
426 * code should use lastErrno() and lastError() to handle the
427 * situation as appropriate.
429 * Do not use this function outside of the Database classes.
431 * @param null|bool $ignoreErrors
432 * @return bool The previous value of the flag.
434 protected function ignoreErrors( $ignoreErrors = null ) {
435 $res = $this->getFlag( self
::DBO_IGNORE
);
436 if ( $ignoreErrors !== null ) {
438 ?
$this->setFlag( self
::DBO_IGNORE
)
439 : $this->clearFlag( self
::DBO_IGNORE
);
445 public function trxLevel() {
446 return $this->mTrxLevel
;
449 public function trxTimestamp() {
450 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
453 public function tablePrefix( $prefix = null ) {
454 $old = $this->mTablePrefix
;
455 if ( $prefix !== null ) {
456 $this->mTablePrefix
= $prefix;
457 $this->currentDomain
= ( $this->mDBname
!= '' )
458 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
459 : DatabaseDomain
::newUnspecified();
465 public function dbSchema( $schema = null ) {
466 $old = $this->mSchema
;
467 if ( $schema !== null ) {
468 $this->mSchema
= $schema;
474 public function getLBInfo( $name = null ) {
475 if ( is_null( $name ) ) {
476 return $this->mLBInfo
;
478 if ( array_key_exists( $name, $this->mLBInfo
) ) {
479 return $this->mLBInfo
[$name];
486 public function setLBInfo( $name, $value = null ) {
487 if ( is_null( $value ) ) {
488 $this->mLBInfo
= $name;
490 $this->mLBInfo
[$name] = $value;
494 public function setLazyMasterHandle( IDatabase
$conn ) {
495 $this->lazyMasterHandle
= $conn;
499 * @return IDatabase|null
500 * @see setLazyMasterHandle()
503 protected function getLazyMasterHandle() {
504 return $this->lazyMasterHandle
;
507 public function implicitGroupby() {
511 public function implicitOrderby() {
515 public function lastQuery() {
516 return $this->mLastQuery
;
519 public function doneWrites() {
520 return (bool)$this->mLastWriteTime
;
523 public function lastDoneWrites() {
524 return $this->mLastWriteTime ?
: false;
527 public function writesPending() {
528 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
531 public function writesOrCallbacksPending() {
532 return $this->mTrxLevel
&& (
533 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
537 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
538 if ( !$this->mTrxLevel
) {
540 } elseif ( !$this->mTrxDoneWrites
) {
545 case self
::ESTIMATE_DB_APPLY
:
547 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
548 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
549 // For omitted queries, make them count as something at least
550 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
551 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
554 default: // everything
555 return $this->mTrxWriteDuration
;
559 public function pendingWriteCallers() {
560 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
563 protected function pendingWriteAndCallbackCallers() {
564 if ( !$this->mTrxLevel
) {
568 $fnames = $this->mTrxWriteCallers
;
570 $this->mTrxIdleCallbacks
,
571 $this->mTrxPreCommitCallbacks
,
572 $this->mTrxEndCallbacks
574 foreach ( $callbacks as $callback ) {
575 $fnames[] = $callback[1];
582 public function isOpen() {
583 return $this->mOpened
;
586 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
587 if ( $remember === self
::REMEMBER_PRIOR
) {
588 array_push( $this->priorFlags
, $this->mFlags
);
590 $this->mFlags |
= $flag;
593 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
594 if ( $remember === self
::REMEMBER_PRIOR
) {
595 array_push( $this->priorFlags
, $this->mFlags
);
597 $this->mFlags
&= ~
$flag;
600 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
601 if ( !$this->priorFlags
) {
605 if ( $state === self
::RESTORE_INITIAL
) {
606 $this->mFlags
= reset( $this->priorFlags
);
607 $this->priorFlags
= [];
609 $this->mFlags
= array_pop( $this->priorFlags
);
613 public function getFlag( $flag ) {
614 return !!( $this->mFlags
& $flag );
618 * @param string $name Class field name
620 * @deprecated Since 1.28
622 public function getProperty( $name ) {
626 public function getDomainID() {
627 return $this->currentDomain
->getId();
630 final public function getWikiID() {
631 return $this->getDomainID();
635 * Get information about an index into an object
636 * @param string $table Table name
637 * @param string $index Index name
638 * @param string $fname Calling function name
639 * @return mixed Database-specific index description class or false if the index does not exist
641 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
644 * Wrapper for addslashes()
646 * @param string $s String to be slashed.
647 * @return string Slashed string.
649 abstract function strencode( $s );
651 protected function installErrorHandler() {
652 $this->mPHPError
= false;
653 $this->htmlErrors
= ini_set( 'html_errors', '0' );
654 set_error_handler( [ $this, 'connectionErrorLogger' ] );
658 * @return bool|string
660 protected function restoreErrorHandler() {
661 restore_error_handler();
662 if ( $this->htmlErrors
!== false ) {
663 ini_set( 'html_errors', $this->htmlErrors
);
666 return $this->getLastPHPError();
670 * @return string|bool Last PHP error for this DB (typically connection errors)
672 protected function getLastPHPError() {
673 if ( $this->mPHPError
) {
674 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
675 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
684 * This method should not be used outside of Database classes
687 * @param string $errstr
689 public function connectionErrorLogger( $errno, $errstr ) {
690 $this->mPHPError
= $errstr;
694 * Create a log context to pass to PSR-3 logger functions.
696 * @param array $extras Additional data to add to context
699 protected function getLogContext( array $extras = [] ) {
702 'db_server' => $this->mServer
,
703 'db_name' => $this->mDBname
,
704 'db_user' => $this->mUser
,
710 public function close() {
711 if ( $this->mConn
) {
712 if ( $this->trxLevel() ) {
713 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
716 $closed = $this->closeConnection();
717 $this->mConn
= false;
718 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
719 throw new RuntimeException( "Transaction callbacks still pending." );
723 $this->mOpened
= false;
729 * Make sure isOpen() returns true as a sanity check
731 * @throws DBUnexpectedError
733 protected function assertOpen() {
734 if ( !$this->isOpen() ) {
735 throw new DBUnexpectedError( $this, "DB connection was already closed." );
740 * Closes underlying database connection
742 * @return bool Whether connection was closed successfully
744 abstract protected function closeConnection();
746 public function reportConnectionError( $error = 'Unknown error' ) {
747 $myError = $this->lastError();
753 throw new DBConnectionError( $this, $error );
757 * The DBMS-dependent part of query()
759 * @param string $sql SQL query.
760 * @return ResultWrapper|bool Result object to feed to fetchObject,
761 * fetchRow, ...; or false on failure
763 abstract protected function doQuery( $sql );
766 * Determine whether a query writes to the DB.
767 * Should return true if unsure.
772 protected function isWriteQuery( $sql ) {
774 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
779 * @return string|null
781 protected function getQueryVerb( $sql ) {
782 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
786 * Determine whether a SQL statement is sensitive to isolation level.
787 * A SQL statement is considered transactable if its result could vary
788 * depending on the transaction isolation level. Operational commands
789 * such as 'SET' and 'SHOW' are not considered to be transactable.
794 protected function isTransactableQuery( $sql ) {
796 $this->getQueryVerb( $sql ),
797 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
803 * @param string $sql A SQL query
804 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
806 protected function registerTempTableOperation( $sql ) {
808 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
812 $this->mSessionTempTables
[$matches[1]] = 1;
815 } elseif ( preg_match(
816 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
820 unset( $this->mSessionTempTables
[$matches[1]] );
823 } elseif ( preg_match(
824 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
828 return isset( $this->mSessionTempTables
[$matches[1]] );
834 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
835 $priorWritesPending = $this->writesOrCallbacksPending();
836 $this->mLastQuery
= $sql;
838 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
840 $reason = $this->getReadOnlyReason();
841 if ( $reason !== false ) {
842 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
844 # Set a flag indicating that writes have been done
845 $this->mLastWriteTime
= microtime( true );
848 // Add trace comment to the begin of the sql string, right after the operator.
849 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
850 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
852 # Start implicit transactions that wrap the request if DBO_TRX is enabled
853 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
854 && $this->isTransactableQuery( $sql )
856 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
857 $this->mTrxAutomatic
= true;
860 # Keep track of whether the transaction has write queries pending
861 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
862 $this->mTrxDoneWrites
= true;
863 $this->trxProfiler
->transactionWritingIn(
864 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
867 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
868 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
871 # Avoid fatals if close() was called
874 # Send the query to the server
875 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
877 # Try reconnecting if the connection was lost
878 if ( false === $ret && $this->wasErrorReissuable() ) {
879 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
880 # Stash the last error values before anything might clear them
881 $lastError = $this->lastError();
882 $lastErrno = $this->lastErrno();
883 # Update state tracking to reflect transaction loss due to disconnection
884 $this->handleSessionLoss();
885 if ( $this->reconnect() ) {
886 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
887 $this->connLogger
->warning( $msg );
888 $this->queryLogger
->warning(
889 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
891 if ( !$recoverable ) {
892 # Callers may catch the exception and continue to use the DB
893 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
895 # Should be safe to silently retry the query
896 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
899 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
900 $this->connLogger
->error( $msg );
904 if ( false === $ret ) {
905 # Deadlocks cause the entire transaction to abort, not just the statement.
906 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
907 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
908 if ( $this->wasDeadlock() ) {
909 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
910 $tempIgnore = false; // not recoverable
912 # Update state tracking to reflect transaction loss
913 $this->handleSessionLoss();
916 $this->reportQueryError(
917 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
920 $res = $this->resultObject( $ret );
925 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
926 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
927 # generalizeSQL() will probably cut down the query to reasonable
928 # logging size most of the time. The substr is really just a sanity check.
930 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
932 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
935 # Include query transaction state
936 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
938 $startTime = microtime( true );
939 if ( $this->profiler
) {
940 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
942 $ret = $this->doQuery( $commentedSql );
943 if ( $this->profiler
) {
944 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
946 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
948 unset( $queryProfSection ); // profile out (if set)
950 if ( $ret !== false ) {
951 $this->lastPing
= $startTime;
952 if ( $isWrite && $this->mTrxLevel
) {
953 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
954 $this->mTrxWriteCallers
[] = $fname;
958 if ( $sql === self
::PING_QUERY
) {
959 $this->mRTTEstimate
= $queryRuntime;
962 $this->trxProfiler
->recordQueryCompletion(
963 $queryProf, $startTime, $isWrite, $this->affectedRows()
965 $this->queryLogger
->debug( $sql, [
967 'master' => $isMaster,
968 'runtime' => $queryRuntime,
975 * Update the estimated run-time of a query, not counting large row lock times
977 * LoadBalancer can be set to rollback transactions that will create huge replication
978 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
979 * queries, like inserting a row can take a long time due to row locking. This method
980 * uses some simple heuristics to discount those cases.
982 * @param string $sql A SQL write query
983 * @param float $runtime Total runtime, including RTT
985 private function updateTrxWriteQueryTime( $sql, $runtime ) {
986 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
987 $indicativeOfReplicaRuntime = true;
988 if ( $runtime > self
::SLOW_WRITE_SEC
) {
989 $verb = $this->getQueryVerb( $sql );
990 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
991 if ( $verb === 'INSERT' ) {
992 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
993 } elseif ( $verb === 'REPLACE' ) {
994 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
998 $this->mTrxWriteDuration +
= $runtime;
999 $this->mTrxWriteQueryCount +
= 1;
1000 if ( $indicativeOfReplicaRuntime ) {
1001 $this->mTrxWriteAdjDuration +
= $runtime;
1002 $this->mTrxWriteAdjQueryCount +
= 1;
1006 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1007 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1008 # Dropped connections also mean that named locks are automatically released.
1009 # Only allow error suppression in autocommit mode or when the lost transaction
1010 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1011 if ( $this->mNamedLocksHeld
) {
1012 return false; // possible critical section violation
1013 } elseif ( $sql === 'COMMIT' ) {
1014 return !$priorWritesPending; // nothing written anyway? (T127428)
1015 } elseif ( $sql === 'ROLLBACK' ) {
1016 return true; // transaction lost...which is also what was requested :)
1017 } elseif ( $this->explicitTrxActive() ) {
1018 return false; // don't drop atomocity
1019 } elseif ( $priorWritesPending ) {
1020 return false; // prior writes lost from implicit transaction
1026 private function handleSessionLoss() {
1027 $this->mTrxLevel
= 0;
1028 $this->mTrxIdleCallbacks
= []; // T67263
1029 $this->mTrxPreCommitCallbacks
= []; // T67263
1030 $this->mSessionTempTables
= [];
1031 $this->mNamedLocksHeld
= [];
1033 // Handle callbacks in mTrxEndCallbacks
1034 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1035 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1037 } catch ( Exception
$e ) {
1038 // Already logged; move on...
1043 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1044 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1045 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1047 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1048 $this->queryLogger
->error(
1049 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1050 $this->getLogContext( [
1051 'method' => __METHOD__
,
1054 'sql1line' => $sql1line,
1058 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1059 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1063 public function freeResult( $res ) {
1066 public function selectField(
1067 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1069 if ( $var === '*' ) { // sanity
1070 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1073 if ( !is_array( $options ) ) {
1074 $options = [ $options ];
1077 $options['LIMIT'] = 1;
1079 $res = $this->select( $table, $var, $cond, $fname, $options );
1080 if ( $res === false ||
!$this->numRows( $res ) ) {
1084 $row = $this->fetchRow( $res );
1086 if ( $row !== false ) {
1087 return reset( $row );
1093 public function selectFieldValues(
1094 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1096 if ( $var === '*' ) { // sanity
1097 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1098 } elseif ( !is_string( $var ) ) { // sanity
1099 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1102 if ( !is_array( $options ) ) {
1103 $options = [ $options ];
1106 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1107 if ( $res === false ) {
1112 foreach ( $res as $row ) {
1113 $values[] = $row->$var;
1120 * Returns an optional USE INDEX clause to go after the table, and a
1121 * string to go at the end of the query.
1123 * @param array $options Associative array of options to be turned into
1124 * an SQL query, valid keys are listed in the function.
1126 * @see Database::select()
1128 protected function makeSelectOptions( $options ) {
1129 $preLimitTail = $postLimitTail = '';
1134 foreach ( $options as $key => $option ) {
1135 if ( is_numeric( $key ) ) {
1136 $noKeyOptions[$option] = true;
1140 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1142 $preLimitTail .= $this->makeOrderBy( $options );
1144 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1145 $postLimitTail .= ' FOR UPDATE';
1148 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1149 $postLimitTail .= ' LOCK IN SHARE MODE';
1152 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1153 $startOpts .= 'DISTINCT';
1156 # Various MySQL extensions
1157 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1158 $startOpts .= ' /*! STRAIGHT_JOIN */';
1161 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1162 $startOpts .= ' HIGH_PRIORITY';
1165 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1166 $startOpts .= ' SQL_BIG_RESULT';
1169 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1170 $startOpts .= ' SQL_BUFFER_RESULT';
1173 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1174 $startOpts .= ' SQL_SMALL_RESULT';
1177 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1178 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1181 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1182 $startOpts .= ' SQL_CACHE';
1185 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1186 $startOpts .= ' SQL_NO_CACHE';
1189 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1190 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1194 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1195 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1200 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1204 * Returns an optional GROUP BY with an optional HAVING
1206 * @param array $options Associative array of options
1208 * @see Database::select()
1211 protected function makeGroupByWithHaving( $options ) {
1213 if ( isset( $options['GROUP BY'] ) ) {
1214 $gb = is_array( $options['GROUP BY'] )
1215 ?
implode( ',', $options['GROUP BY'] )
1216 : $options['GROUP BY'];
1217 $sql .= ' GROUP BY ' . $gb;
1219 if ( isset( $options['HAVING'] ) ) {
1220 $having = is_array( $options['HAVING'] )
1221 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1222 : $options['HAVING'];
1223 $sql .= ' HAVING ' . $having;
1230 * Returns an optional ORDER BY
1232 * @param array $options Associative array of options
1234 * @see Database::select()
1237 protected function makeOrderBy( $options ) {
1238 if ( isset( $options['ORDER BY'] ) ) {
1239 $ob = is_array( $options['ORDER BY'] )
1240 ?
implode( ',', $options['ORDER BY'] )
1241 : $options['ORDER BY'];
1243 return ' ORDER BY ' . $ob;
1249 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1250 $options = [], $join_conds = [] ) {
1251 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1253 return $this->query( $sql, $fname );
1256 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1257 $options = [], $join_conds = []
1259 if ( is_array( $vars ) ) {
1260 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1263 $options = (array)$options;
1264 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1265 ?
$options['USE INDEX']
1268 isset( $options['IGNORE INDEX'] ) &&
1269 is_array( $options['IGNORE INDEX'] )
1271 ?
$options['IGNORE INDEX']
1274 if ( is_array( $table ) ) {
1276 $this->tableNamesWithIndexClauseOrJOIN(
1277 $table, $useIndexes, $ignoreIndexes, $join_conds );
1278 } elseif ( $table != '' ) {
1279 if ( $table[0] == ' ' ) {
1280 $from = ' FROM ' . $table;
1283 $this->tableNamesWithIndexClauseOrJOIN(
1284 [ $table ], $useIndexes, $ignoreIndexes, [] );
1290 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1291 $this->makeSelectOptions( $options );
1293 if ( !empty( $conds ) ) {
1294 if ( is_array( $conds ) ) {
1295 $conds = $this->makeList( $conds, self
::LIST_AND
);
1297 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1298 "WHERE $conds $preLimitTail";
1300 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1303 if ( isset( $options['LIMIT'] ) ) {
1304 $sql = $this->limitResult( $sql, $options['LIMIT'],
1305 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1307 $sql = "$sql $postLimitTail";
1309 if ( isset( $options['EXPLAIN'] ) ) {
1310 $sql = 'EXPLAIN ' . $sql;
1316 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1317 $options = [], $join_conds = []
1319 $options = (array)$options;
1320 $options['LIMIT'] = 1;
1321 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1323 if ( $res === false ) {
1327 if ( !$this->numRows( $res ) ) {
1331 $obj = $this->fetchObject( $res );
1336 public function estimateRowCount(
1337 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1340 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1343 $row = $this->fetchRow( $res );
1344 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1350 public function selectRowCount(
1351 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1354 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1355 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1358 $row = $this->fetchRow( $res );
1359 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1366 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1367 * It's only slightly flawed. Don't use for anything important.
1369 * @param string $sql A SQL Query
1373 protected static function generalizeSQL( $sql ) {
1374 # This does the same as the regexp below would do, but in such a way
1375 # as to avoid crashing php on some large strings.
1376 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1378 $sql = str_replace( "\\\\", '', $sql );
1379 $sql = str_replace( "\\'", '', $sql );
1380 $sql = str_replace( "\\\"", '', $sql );
1381 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1382 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1384 # All newlines, tabs, etc replaced by single space
1385 $sql = preg_replace( '/\s+/', ' ', $sql );
1388 # except the ones surrounded by characters, e.g. l10n
1389 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1390 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1395 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1396 $info = $this->fieldInfo( $table, $field );
1401 public function indexExists( $table, $index, $fname = __METHOD__
) {
1402 if ( !$this->tableExists( $table ) ) {
1406 $info = $this->indexInfo( $table, $index, $fname );
1407 if ( is_null( $info ) ) {
1410 return $info !== false;
1414 public function tableExists( $table, $fname = __METHOD__
) {
1415 $tableRaw = $this->tableName( $table, 'raw' );
1416 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1417 return true; // already known to exist
1420 $table = $this->tableName( $table );
1421 $ignoreErrors = true;
1422 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1427 public function indexUnique( $table, $index ) {
1428 $indexInfo = $this->indexInfo( $table, $index );
1430 if ( !$indexInfo ) {
1434 return !$indexInfo[0]->Non_unique
;
1438 * Helper for Database::insert().
1440 * @param array $options
1443 protected function makeInsertOptions( $options ) {
1444 return implode( ' ', $options );
1447 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1448 # No rows to insert, easy just return now
1449 if ( !count( $a ) ) {
1453 $table = $this->tableName( $table );
1455 if ( !is_array( $options ) ) {
1456 $options = [ $options ];
1460 if ( isset( $options['fileHandle'] ) ) {
1461 $fh = $options['fileHandle'];
1463 $options = $this->makeInsertOptions( $options );
1465 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1467 $keys = array_keys( $a[0] );
1470 $keys = array_keys( $a );
1473 $sql = 'INSERT ' . $options .
1474 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1478 foreach ( $a as $row ) {
1484 $sql .= '(' . $this->makeList( $row ) . ')';
1487 $sql .= '(' . $this->makeList( $a ) . ')';
1490 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1492 } elseif ( $fh !== null ) {
1496 return (bool)$this->query( $sql, $fname );
1500 * Make UPDATE options array for Database::makeUpdateOptions
1502 * @param array $options
1505 protected function makeUpdateOptionsArray( $options ) {
1506 if ( !is_array( $options ) ) {
1507 $options = [ $options ];
1512 if ( in_array( 'IGNORE', $options ) ) {
1520 * Make UPDATE options for the Database::update function
1522 * @param array $options The options passed to Database::update
1525 protected function makeUpdateOptions( $options ) {
1526 $opts = $this->makeUpdateOptionsArray( $options );
1528 return implode( ' ', $opts );
1531 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1532 $table = $this->tableName( $table );
1533 $opts = $this->makeUpdateOptions( $options );
1534 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1536 if ( $conds !== [] && $conds !== '*' ) {
1537 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1540 return $this->query( $sql, $fname );
1543 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1544 if ( !is_array( $a ) ) {
1545 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1551 foreach ( $a as $field => $value ) {
1553 if ( $mode == self
::LIST_AND
) {
1555 } elseif ( $mode == self
::LIST_OR
) {
1564 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1565 $list .= "($value)";
1566 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1569 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1571 // Remove null from array to be handled separately if found
1572 $includeNull = false;
1573 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1574 $includeNull = true;
1575 unset( $value[$nullKey] );
1577 if ( count( $value ) == 0 && !$includeNull ) {
1578 throw new InvalidArgumentException(
1579 __METHOD__
. ": empty input for field $field" );
1580 } elseif ( count( $value ) == 0 ) {
1581 // only check if $field is null
1582 $list .= "$field IS NULL";
1584 // IN clause contains at least one valid element
1585 if ( $includeNull ) {
1586 // Group subconditions to ensure correct precedence
1589 if ( count( $value ) == 1 ) {
1590 // Special-case single values, as IN isn't terribly efficient
1591 // Don't necessarily assume the single key is 0; we don't
1592 // enforce linear numeric ordering on other arrays here.
1593 $value = array_values( $value )[0];
1594 $list .= $field . " = " . $this->addQuotes( $value );
1596 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1598 // if null present in array, append IS NULL
1599 if ( $includeNull ) {
1600 $list .= " OR $field IS NULL)";
1603 } elseif ( $value === null ) {
1604 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1605 $list .= "$field IS ";
1606 } elseif ( $mode == self
::LIST_SET
) {
1607 $list .= "$field = ";
1612 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1614 $list .= "$field = ";
1616 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1623 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1626 foreach ( $data as $base => $sub ) {
1627 if ( count( $sub ) ) {
1628 $conds[] = $this->makeList(
1629 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1635 return $this->makeList( $conds, self
::LIST_OR
);
1637 // Nothing to search for...
1642 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1646 public function bitNot( $field ) {
1650 public function bitAnd( $fieldLeft, $fieldRight ) {
1651 return "($fieldLeft & $fieldRight)";
1654 public function bitOr( $fieldLeft, $fieldRight ) {
1655 return "($fieldLeft | $fieldRight)";
1658 public function buildConcat( $stringList ) {
1659 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1662 public function buildGroupConcatField(
1663 $delim, $table, $field, $conds = '', $join_conds = []
1665 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1667 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1670 public function buildStringCast( $field ) {
1674 public function selectDB( $db ) {
1675 # Stub. Shouldn't cause serious problems if it's not overridden, but
1676 # if your database engine supports a concept similar to MySQL's
1677 # databases you may as well.
1678 $this->mDBname
= $db;
1683 public function getDBname() {
1684 return $this->mDBname
;
1687 public function getServer() {
1688 return $this->mServer
;
1691 public function tableName( $name, $format = 'quoted' ) {
1692 # Skip the entire process when we have a string quoted on both ends.
1693 # Note that we check the end so that we will still quote any use of
1694 # use of `database`.table. But won't break things if someone wants
1695 # to query a database table with a dot in the name.
1696 if ( $this->isQuotedIdentifier( $name ) ) {
1700 # Lets test for any bits of text that should never show up in a table
1701 # name. Basically anything like JOIN or ON which are actually part of
1702 # SQL queries, but may end up inside of the table value to combine
1703 # sql. Such as how the API is doing.
1704 # Note that we use a whitespace test rather than a \b test to avoid
1705 # any remote case where a word like on may be inside of a table name
1706 # surrounded by symbols which may be considered word breaks.
1707 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1711 # Split database and table into proper variables.
1712 # We reverse the explode so that database.table and table both output
1713 # the correct table.
1714 $dbDetails = explode( '.', $name, 3 );
1715 if ( count( $dbDetails ) == 3 ) {
1716 list( $database, $schema, $table ) = $dbDetails;
1717 # We don't want any prefix added in this case
1719 } elseif ( count( $dbDetails ) == 2 ) {
1720 list( $database, $table ) = $dbDetails;
1721 # We don't want any prefix added in this case
1723 # In dbs that support it, $database may actually be the schema
1724 # but that doesn't affect any of the functionality here
1727 list( $table ) = $dbDetails;
1728 if ( isset( $this->tableAliases
[$table] ) ) {
1729 $database = $this->tableAliases
[$table]['dbname'];
1730 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1731 ?
$this->tableAliases
[$table]['schema']
1733 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1734 ?
$this->tableAliases
[$table]['prefix']
1735 : $this->mTablePrefix
;
1738 $schema = $this->mSchema
; # Default schema
1739 $prefix = $this->mTablePrefix
; # Default prefix
1743 # Quote $table and apply the prefix if not quoted.
1744 # $tableName might be empty if this is called from Database::replaceVars()
1745 $tableName = "{$prefix}{$table}";
1746 if ( $format === 'quoted'
1747 && !$this->isQuotedIdentifier( $tableName )
1748 && $tableName !== ''
1750 $tableName = $this->addIdentifierQuotes( $tableName );
1753 # Quote $schema and $database and merge them with the table name if needed
1754 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1755 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1761 * @param string|null $namespace Database or schema
1762 * @param string $relation Name of table, view, sequence, etc...
1763 * @param string $format One of (raw, quoted)
1764 * @return string Relation name with quoted and merged $namespace as needed
1766 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1767 if ( strlen( $namespace ) ) {
1768 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1769 $namespace = $this->addIdentifierQuotes( $namespace );
1771 $relation = $namespace . '.' . $relation;
1777 public function tableNames() {
1778 $inArray = func_get_args();
1781 foreach ( $inArray as $name ) {
1782 $retVal[$name] = $this->tableName( $name );
1788 public function tableNamesN() {
1789 $inArray = func_get_args();
1792 foreach ( $inArray as $name ) {
1793 $retVal[] = $this->tableName( $name );
1800 * Get an aliased table name
1801 * e.g. tableName AS newTableName
1803 * @param string $name Table name, see tableName()
1804 * @param string|bool $alias Alias (optional)
1805 * @return string SQL name for aliased table. Will not alias a table to its own name
1807 protected function tableNameWithAlias( $name, $alias = false ) {
1808 if ( !$alias ||
$alias == $name ) {
1809 return $this->tableName( $name );
1811 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1816 * Gets an array of aliased table names
1818 * @param array $tables [ [alias] => table ]
1819 * @return string[] See tableNameWithAlias()
1821 protected function tableNamesWithAlias( $tables ) {
1823 foreach ( $tables as $alias => $table ) {
1824 if ( is_numeric( $alias ) ) {
1827 $retval[] = $this->tableNameWithAlias( $table, $alias );
1834 * Get an aliased field name
1835 * e.g. fieldName AS newFieldName
1837 * @param string $name Field name
1838 * @param string|bool $alias Alias (optional)
1839 * @return string SQL name for aliased field. Will not alias a field to its own name
1841 protected function fieldNameWithAlias( $name, $alias = false ) {
1842 if ( !$alias ||
(string)$alias === (string)$name ) {
1845 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1850 * Gets an array of aliased field names
1852 * @param array $fields [ [alias] => field ]
1853 * @return string[] See fieldNameWithAlias()
1855 protected function fieldNamesWithAlias( $fields ) {
1857 foreach ( $fields as $alias => $field ) {
1858 if ( is_numeric( $alias ) ) {
1861 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1868 * Get the aliased table name clause for a FROM clause
1869 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1871 * @param array $tables ( [alias] => table )
1872 * @param array $use_index Same as for select()
1873 * @param array $ignore_index Same as for select()
1874 * @param array $join_conds Same as for select()
1877 protected function tableNamesWithIndexClauseOrJOIN(
1878 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1882 $use_index = (array)$use_index;
1883 $ignore_index = (array)$ignore_index;
1884 $join_conds = (array)$join_conds;
1886 foreach ( $tables as $alias => $table ) {
1887 if ( !is_string( $alias ) ) {
1888 // No alias? Set it equal to the table name
1891 // Is there a JOIN clause for this table?
1892 if ( isset( $join_conds[$alias] ) ) {
1893 list( $joinType, $conds ) = $join_conds[$alias];
1894 $tableClause = $joinType;
1895 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1896 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1897 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1899 $tableClause .= ' ' . $use;
1902 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1903 $ignore = $this->ignoreIndexClause(
1904 implode( ',', (array)$ignore_index[$alias] ) );
1905 if ( $ignore != '' ) {
1906 $tableClause .= ' ' . $ignore;
1909 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1911 $tableClause .= ' ON (' . $on . ')';
1914 $retJOIN[] = $tableClause;
1915 } elseif ( isset( $use_index[$alias] ) ) {
1916 // Is there an INDEX clause for this table?
1917 $tableClause = $this->tableNameWithAlias( $table, $alias );
1918 $tableClause .= ' ' . $this->useIndexClause(
1919 implode( ',', (array)$use_index[$alias] )
1922 $ret[] = $tableClause;
1923 } elseif ( isset( $ignore_index[$alias] ) ) {
1924 // Is there an INDEX clause for this table?
1925 $tableClause = $this->tableNameWithAlias( $table, $alias );
1926 $tableClause .= ' ' . $this->ignoreIndexClause(
1927 implode( ',', (array)$ignore_index[$alias] )
1930 $ret[] = $tableClause;
1932 $tableClause = $this->tableNameWithAlias( $table, $alias );
1934 $ret[] = $tableClause;
1938 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1939 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1940 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1942 // Compile our final table clause
1943 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1947 * Get the name of an index in a given table.
1949 * @param string $index
1952 protected function indexName( $index ) {
1956 public function addQuotes( $s ) {
1957 if ( $s instanceof Blob
) {
1960 if ( $s === null ) {
1962 } elseif ( is_bool( $s ) ) {
1965 # This will also quote numeric values. This should be harmless,
1966 # and protects against weird problems that occur when they really
1967 # _are_ strings such as article titles and string->number->string
1968 # conversion is not 1:1.
1969 return "'" . $this->strencode( $s ) . "'";
1974 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1975 * MySQL uses `backticks` while basically everything else uses double quotes.
1976 * Since MySQL is the odd one out here the double quotes are our generic
1977 * and we implement backticks in DatabaseMysql.
1982 public function addIdentifierQuotes( $s ) {
1983 return '"' . str_replace( '"', '""', $s ) . '"';
1987 * Returns if the given identifier looks quoted or not according to
1988 * the database convention for quoting identifiers .
1990 * @note Do not use this to determine if untrusted input is safe.
1991 * A malicious user can trick this function.
1992 * @param string $name
1995 public function isQuotedIdentifier( $name ) {
1996 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2003 protected function escapeLikeInternal( $s ) {
2004 return addcslashes( $s, '\%_' );
2007 public function buildLike() {
2008 $params = func_get_args();
2010 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2011 $params = $params[0];
2016 foreach ( $params as $value ) {
2017 if ( $value instanceof LikeMatch
) {
2018 $s .= $value->toString();
2020 $s .= $this->escapeLikeInternal( $value );
2024 return " LIKE {$this->addQuotes( $s )} ";
2027 public function anyChar() {
2028 return new LikeMatch( '_' );
2031 public function anyString() {
2032 return new LikeMatch( '%' );
2035 public function nextSequenceValue( $seqName ) {
2040 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2041 * is only needed because a) MySQL must be as efficient as possible due to
2042 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2043 * which index to pick. Anyway, other databases might have different
2044 * indexes on a given table. So don't bother overriding this unless you're
2046 * @param string $index
2049 public function useIndexClause( $index ) {
2054 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2055 * is only needed because a) MySQL must be as efficient as possible due to
2056 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2057 * which index to pick. Anyway, other databases might have different
2058 * indexes on a given table. So don't bother overriding this unless you're
2060 * @param string $index
2063 public function ignoreIndexClause( $index ) {
2067 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2068 $quotedTable = $this->tableName( $table );
2070 if ( count( $rows ) == 0 ) {
2075 if ( !is_array( reset( $rows ) ) ) {
2079 // @FXIME: this is not atomic, but a trx would break affectedRows()
2080 foreach ( $rows as $row ) {
2081 # Delete rows which collide
2082 if ( $uniqueIndexes ) {
2083 $sql = "DELETE FROM $quotedTable WHERE ";
2085 foreach ( $uniqueIndexes as $index ) {
2092 if ( is_array( $index ) ) {
2094 foreach ( $index as $col ) {
2100 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2103 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2107 $this->query( $sql, $fname );
2110 # Now insert the row
2111 $this->insert( $table, $row, $fname );
2116 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2119 * @param string $table Table name
2120 * @param array|string $rows Row(s) to insert
2121 * @param string $fname Caller function name
2123 * @return ResultWrapper
2125 protected function nativeReplace( $table, $rows, $fname ) {
2126 $table = $this->tableName( $table );
2129 if ( !is_array( reset( $rows ) ) ) {
2133 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2136 foreach ( $rows as $row ) {
2143 $sql .= '(' . $this->makeList( $row ) . ')';
2146 return $this->query( $sql, $fname );
2149 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2152 if ( !count( $rows ) ) {
2153 return true; // nothing to do
2156 if ( !is_array( reset( $rows ) ) ) {
2160 if ( count( $uniqueIndexes ) ) {
2161 $clauses = []; // list WHERE clauses that each identify a single row
2162 foreach ( $rows as $row ) {
2163 foreach ( $uniqueIndexes as $index ) {
2164 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2165 $rowKey = []; // unique key to this row
2166 foreach ( $index as $column ) {
2167 $rowKey[$column] = $row[$column];
2169 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2172 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2177 $useTrx = !$this->mTrxLevel
;
2179 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2182 # Update any existing conflicting row(s)
2183 if ( $where !== false ) {
2184 $ok = $this->update( $table, $set, $where, $fname );
2188 # Now insert any non-conflicting row(s)
2189 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2190 } catch ( Exception
$e ) {
2192 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2197 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2203 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2207 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2210 $delTable = $this->tableName( $delTable );
2211 $joinTable = $this->tableName( $joinTable );
2212 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2213 if ( $conds != '*' ) {
2214 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2218 $this->query( $sql, $fname );
2221 public function textFieldSize( $table, $field ) {
2222 $table = $this->tableName( $table );
2223 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2224 $res = $this->query( $sql, __METHOD__
);
2225 $row = $this->fetchObject( $res );
2229 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2238 public function delete( $table, $conds, $fname = __METHOD__
) {
2240 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2243 $table = $this->tableName( $table );
2244 $sql = "DELETE FROM $table";
2246 if ( $conds != '*' ) {
2247 if ( is_array( $conds ) ) {
2248 $conds = $this->makeList( $conds, self
::LIST_AND
);
2250 $sql .= ' WHERE ' . $conds;
2253 return $this->query( $sql, $fname );
2256 public function insertSelect(
2257 $destTable, $srcTable, $varMap, $conds,
2258 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2260 if ( $this->cliMode
) {
2261 // For massive migrations with downtime, we don't want to select everything
2262 // into memory and OOM, so do all this native on the server side if possible.
2263 return $this->nativeInsertSelect(
2274 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2275 // on only the master (without needing row-based-replication). It also makes it easy to
2276 // know how big the INSERT is going to be.
2278 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2279 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2281 $selectOptions[] = 'FOR UPDATE';
2282 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2288 foreach ( $res as $row ) {
2289 $rows[] = (array)$row;
2292 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2295 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2296 $fname = __METHOD__
,
2297 $insertOptions = [], $selectOptions = []
2299 $destTable = $this->tableName( $destTable );
2301 if ( !is_array( $insertOptions ) ) {
2302 $insertOptions = [ $insertOptions ];
2305 $insertOptions = $this->makeInsertOptions( $insertOptions );
2307 if ( !is_array( $selectOptions ) ) {
2308 $selectOptions = [ $selectOptions ];
2311 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2314 if ( is_array( $srcTable ) ) {
2315 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2317 $srcTable = $this->tableName( $srcTable );
2320 $sql = "INSERT $insertOptions" .
2321 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2322 " SELECT $startOpts " . implode( ',', $varMap ) .
2323 " FROM $srcTable $useIndex $ignoreIndex ";
2325 if ( $conds != '*' ) {
2326 if ( is_array( $conds ) ) {
2327 $conds = $this->makeList( $conds, self
::LIST_AND
);
2329 $sql .= " WHERE $conds";
2332 $sql .= " $tailOpts";
2334 return $this->query( $sql, $fname );
2338 * Construct a LIMIT query with optional offset. This is used for query
2339 * pages. The SQL should be adjusted so that only the first $limit rows
2340 * are returned. If $offset is provided as well, then the first $offset
2341 * rows should be discarded, and the next $limit rows should be returned.
2342 * If the result of the query is not ordered, then the rows to be returned
2343 * are theoretically arbitrary.
2345 * $sql is expected to be a SELECT, if that makes a difference.
2347 * The version provided by default works in MySQL and SQLite. It will very
2348 * likely need to be overridden for most other DBMSes.
2350 * @param string $sql SQL query we will append the limit too
2351 * @param int $limit The SQL limit
2352 * @param int|bool $offset The SQL offset (default false)
2353 * @throws DBUnexpectedError
2356 public function limitResult( $sql, $limit, $offset = false ) {
2357 if ( !is_numeric( $limit ) ) {
2358 throw new DBUnexpectedError( $this,
2359 "Invalid non-numeric limit passed to limitResult()\n" );
2362 return "$sql LIMIT "
2363 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2367 public function unionSupportsOrderAndLimit() {
2368 return true; // True for almost every DB supported
2371 public function unionQueries( $sqls, $all ) {
2372 $glue = $all ?
') UNION ALL (' : ') UNION (';
2374 return '(' . implode( $glue, $sqls ) . ')';
2377 public function conditional( $cond, $trueVal, $falseVal ) {
2378 if ( is_array( $cond ) ) {
2379 $cond = $this->makeList( $cond, self
::LIST_AND
);
2382 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2385 public function strreplace( $orig, $old, $new ) {
2386 return "REPLACE({$orig}, {$old}, {$new})";
2389 public function getServerUptime() {
2393 public function wasDeadlock() {
2397 public function wasLockTimeout() {
2401 public function wasErrorReissuable() {
2405 public function wasReadOnlyError() {
2410 * Do not use this method outside of Database/DBError classes
2412 * @param integer|string $errno
2413 * @return bool Whether the given query error was a connection drop
2415 public function wasConnectionError( $errno ) {
2419 public function deadlockLoop() {
2420 $args = func_get_args();
2421 $function = array_shift( $args );
2422 $tries = self
::DEADLOCK_TRIES
;
2424 $this->begin( __METHOD__
);
2427 /** @var Exception $e */
2431 $retVal = call_user_func_array( $function, $args );
2433 } catch ( DBQueryError
$e ) {
2434 if ( $this->wasDeadlock() ) {
2435 // Retry after a randomized delay
2436 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2438 // Throw the error back up
2442 } while ( --$tries > 0 );
2444 if ( $tries <= 0 ) {
2445 // Too many deadlocks; give up
2446 $this->rollback( __METHOD__
);
2449 $this->commit( __METHOD__
);
2455 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2456 # Real waits are implemented in the subclass.
2460 public function getReplicaPos() {
2465 public function getMasterPos() {
2470 public function serverIsReadOnly() {
2474 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2475 if ( !$this->mTrxLevel
) {
2476 throw new DBUnexpectedError( $this, "No transaction is active." );
2478 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2481 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2482 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2483 if ( !$this->mTrxLevel
) {
2484 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2488 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2489 if ( $this->mTrxLevel
) {
2490 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2492 // If no transaction is active, then make one for this callback
2493 $this->startAtomic( __METHOD__
);
2495 call_user_func( $callback );
2496 $this->endAtomic( __METHOD__
);
2497 } catch ( Exception
$e ) {
2498 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2504 final public function setTransactionListener( $name, callable
$callback = null ) {
2506 $this->mTrxRecurringCallbacks
[$name] = $callback;
2508 unset( $this->mTrxRecurringCallbacks
[$name] );
2513 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2515 * This method should not be used outside of Database/LoadBalancer
2517 * @param bool $suppress
2520 final public function setTrxEndCallbackSuppression( $suppress ) {
2521 $this->mTrxEndCallbacksSuppressed
= $suppress;
2525 * Actually run and consume any "on transaction idle/resolution" callbacks.
2527 * This method should not be used outside of Database/LoadBalancer
2529 * @param integer $trigger IDatabase::TRIGGER_* constant
2533 public function runOnTransactionIdleCallbacks( $trigger ) {
2534 if ( $this->mTrxEndCallbacksSuppressed
) {
2538 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2539 /** @var Exception $e */
2540 $e = null; // first exception
2541 do { // callbacks may add callbacks :)
2542 $callbacks = array_merge(
2543 $this->mTrxIdleCallbacks
,
2544 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2546 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2547 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2548 foreach ( $callbacks as $callback ) {
2550 list( $phpCallback ) = $callback;
2551 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2552 call_user_func_array( $phpCallback, [ $trigger ] );
2554 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2556 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2558 } catch ( Exception
$ex ) {
2559 call_user_func( $this->errorLogger
, $ex );
2561 // Some callbacks may use startAtomic/endAtomic, so make sure
2562 // their transactions are ended so other callbacks don't fail
2563 if ( $this->trxLevel() ) {
2564 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2568 } while ( count( $this->mTrxIdleCallbacks
) );
2570 if ( $e instanceof Exception
) {
2571 throw $e; // re-throw any first exception
2576 * Actually run and consume any "on transaction pre-commit" callbacks.
2578 * This method should not be used outside of Database/LoadBalancer
2583 public function runOnTransactionPreCommitCallbacks() {
2584 $e = null; // first exception
2585 do { // callbacks may add callbacks :)
2586 $callbacks = $this->mTrxPreCommitCallbacks
;
2587 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2588 foreach ( $callbacks as $callback ) {
2590 list( $phpCallback ) = $callback;
2591 call_user_func( $phpCallback );
2592 } catch ( Exception
$ex ) {
2593 call_user_func( $this->errorLogger
, $ex );
2597 } while ( count( $this->mTrxPreCommitCallbacks
) );
2599 if ( $e instanceof Exception
) {
2600 throw $e; // re-throw any first exception
2605 * Actually run any "transaction listener" callbacks.
2607 * This method should not be used outside of Database/LoadBalancer
2609 * @param integer $trigger IDatabase::TRIGGER_* constant
2613 public function runTransactionListenerCallbacks( $trigger ) {
2614 if ( $this->mTrxEndCallbacksSuppressed
) {
2618 /** @var Exception $e */
2619 $e = null; // first exception
2621 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2623 $phpCallback( $trigger, $this );
2624 } catch ( Exception
$ex ) {
2625 call_user_func( $this->errorLogger
, $ex );
2630 if ( $e instanceof Exception
) {
2631 throw $e; // re-throw any first exception
2635 final public function startAtomic( $fname = __METHOD__
) {
2636 if ( !$this->mTrxLevel
) {
2637 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2638 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2639 // in all changes being in one transaction to keep requests transactional.
2640 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2641 $this->mTrxAutomaticAtomic
= true;
2645 $this->mTrxAtomicLevels
[] = $fname;
2648 final public function endAtomic( $fname = __METHOD__
) {
2649 if ( !$this->mTrxLevel
) {
2650 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2652 if ( !$this->mTrxAtomicLevels ||
2653 array_pop( $this->mTrxAtomicLevels
) !== $fname
2655 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2658 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2659 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2663 final public function doAtomicSection( $fname, callable
$callback ) {
2664 $this->startAtomic( $fname );
2666 $res = call_user_func_array( $callback, [ $this, $fname ] );
2667 } catch ( Exception
$e ) {
2668 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2671 $this->endAtomic( $fname );
2676 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2677 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2678 if ( $this->mTrxLevel
) {
2679 if ( $this->mTrxAtomicLevels
) {
2680 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2681 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2682 throw new DBUnexpectedError( $this, $msg );
2683 } elseif ( !$this->mTrxAutomatic
) {
2684 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2685 throw new DBUnexpectedError( $this, $msg );
2687 // @TODO: make this an exception at some point
2688 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2689 $this->queryLogger
->error( $msg );
2690 return; // join the main transaction set
2692 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2693 // @TODO: make this an exception at some point
2694 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2695 $this->queryLogger
->error( $msg );
2696 return; // let any writes be in the main transaction
2699 // Avoid fatals if close() was called
2700 $this->assertOpen();
2702 $this->doBegin( $fname );
2703 $this->mTrxTimestamp
= microtime( true );
2704 $this->mTrxFname
= $fname;
2705 $this->mTrxDoneWrites
= false;
2706 $this->mTrxAutomaticAtomic
= false;
2707 $this->mTrxAtomicLevels
= [];
2708 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2709 $this->mTrxWriteDuration
= 0.0;
2710 $this->mTrxWriteQueryCount
= 0;
2711 $this->mTrxWriteAdjDuration
= 0.0;
2712 $this->mTrxWriteAdjQueryCount
= 0;
2713 $this->mTrxWriteCallers
= [];
2714 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2715 // Get an estimate of the replica DB lag before then, treating estimate staleness
2716 // as lag itself just to be safe
2717 $status = $this->getApproximateLagStatus();
2718 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2719 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2720 // caller will think its OK to muck around with the transaction just because startAtomic()
2721 // has not yet completed (e.g. setting mTrxAtomicLevels).
2722 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2726 * Issues the BEGIN command to the database server.
2728 * @see Database::begin()
2729 * @param string $fname
2731 protected function doBegin( $fname ) {
2732 $this->query( 'BEGIN', $fname );
2733 $this->mTrxLevel
= 1;
2736 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2737 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2738 // There are still atomic sections open. This cannot be ignored
2739 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2740 throw new DBUnexpectedError(
2742 "$fname: Got COMMIT while atomic sections $levels are still open."
2746 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2747 if ( !$this->mTrxLevel
) {
2748 return; // nothing to do
2749 } elseif ( !$this->mTrxAutomatic
) {
2750 throw new DBUnexpectedError(
2752 "$fname: Flushing an explicit transaction, getting out of sync."
2756 if ( !$this->mTrxLevel
) {
2757 $this->queryLogger
->error(
2758 "$fname: No transaction to commit, something got out of sync." );
2759 return; // nothing to do
2760 } elseif ( $this->mTrxAutomatic
) {
2761 // @TODO: make this an exception at some point
2762 $msg = "$fname: Explicit commit of implicit transaction.";
2763 $this->queryLogger
->error( $msg );
2764 return; // wait for the main transaction set commit round
2768 // Avoid fatals if close() was called
2769 $this->assertOpen();
2771 $this->runOnTransactionPreCommitCallbacks();
2772 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2773 $this->doCommit( $fname );
2774 if ( $this->mTrxDoneWrites
) {
2775 $this->mLastWriteTime
= microtime( true );
2776 $this->trxProfiler
->transactionWritingOut(
2777 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2780 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2781 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2785 * Issues the COMMIT command to the database server.
2787 * @see Database::commit()
2788 * @param string $fname
2790 protected function doCommit( $fname ) {
2791 if ( $this->mTrxLevel
) {
2792 $this->query( 'COMMIT', $fname );
2793 $this->mTrxLevel
= 0;
2797 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2798 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2799 if ( !$this->mTrxLevel
) {
2800 return; // nothing to do
2803 if ( !$this->mTrxLevel
) {
2804 $this->queryLogger
->error(
2805 "$fname: No transaction to rollback, something got out of sync." );
2806 return; // nothing to do
2807 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2808 throw new DBUnexpectedError(
2810 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2815 // Avoid fatals if close() was called
2816 $this->assertOpen();
2818 $this->doRollback( $fname );
2819 $this->mTrxAtomicLevels
= [];
2820 if ( $this->mTrxDoneWrites
) {
2821 $this->trxProfiler
->transactionWritingOut(
2822 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2825 $this->mTrxIdleCallbacks
= []; // clear
2826 $this->mTrxPreCommitCallbacks
= []; // clear
2827 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2828 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2832 * Issues the ROLLBACK command to the database server.
2834 * @see Database::rollback()
2835 * @param string $fname
2837 protected function doRollback( $fname ) {
2838 if ( $this->mTrxLevel
) {
2839 # Disconnects cause rollback anyway, so ignore those errors
2840 $ignoreErrors = true;
2841 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2842 $this->mTrxLevel
= 0;
2846 public function flushSnapshot( $fname = __METHOD__
) {
2847 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2848 // This only flushes transactions to clear snapshots, not to write data
2849 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2850 throw new DBUnexpectedError(
2852 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2856 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2859 public function explicitTrxActive() {
2860 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2863 public function duplicateTableStructure(
2864 $oldName, $newName, $temporary = false, $fname = __METHOD__
2866 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2869 public function listTables( $prefix = null, $fname = __METHOD__
) {
2870 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2873 public function listViews( $prefix = null, $fname = __METHOD__
) {
2874 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2877 public function timestamp( $ts = 0 ) {
2878 $t = new ConvertibleTimestamp( $ts );
2879 // Let errors bubble up to avoid putting garbage in the DB
2880 return $t->getTimestamp( TS_MW
);
2883 public function timestampOrNull( $ts = null ) {
2884 if ( is_null( $ts ) ) {
2887 return $this->timestamp( $ts );
2892 * Take the result from a query, and wrap it in a ResultWrapper if
2893 * necessary. Boolean values are passed through as is, to indicate success
2894 * of write queries or failure.
2896 * Once upon a time, Database::query() returned a bare MySQL result
2897 * resource, and it was necessary to call this function to convert it to
2898 * a wrapper. Nowadays, raw database objects are never exposed to external
2899 * callers, so this is unnecessary in external code.
2901 * @param bool|ResultWrapper|resource|object $result
2902 * @return bool|ResultWrapper
2904 protected function resultObject( $result ) {
2907 } elseif ( $result instanceof ResultWrapper
) {
2909 } elseif ( $result === true ) {
2910 // Successful write query
2913 return new ResultWrapper( $this, $result );
2917 public function ping( &$rtt = null ) {
2918 // Avoid hitting the server if it was hit recently
2919 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2920 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2921 $rtt = $this->mRTTEstimate
;
2922 return true; // don't care about $rtt
2926 // This will reconnect if possible or return false if not
2927 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
2928 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2929 $this->restoreFlags( self
::RESTORE_PRIOR
);
2932 $rtt = $this->mRTTEstimate
;
2941 protected function reconnect() {
2942 $this->closeConnection();
2943 $this->mOpened
= false;
2944 $this->mConn
= false;
2946 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2947 $this->lastPing
= microtime( true );
2949 } catch ( DBConnectionError
$e ) {
2956 public function getSessionLagStatus() {
2957 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2961 * Get the replica DB lag when the current transaction started
2963 * This is useful when transactions might use snapshot isolation
2964 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2965 * is this lag plus transaction duration. If they don't, it is still
2966 * safe to be pessimistic. This returns null if there is no transaction.
2968 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2971 protected function getTransactionLagStatus() {
2972 return $this->mTrxLevel
2973 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
2978 * Get a replica DB lag estimate for this server
2980 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2983 protected function getApproximateLagStatus() {
2985 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
2986 'since' => microtime( true )
2991 * Merge the result of getSessionLagStatus() for several DBs
2992 * using the most pessimistic values to estimate the lag of
2993 * any data derived from them in combination
2995 * This is information is useful for caching modules
2997 * @see WANObjectCache::set()
2998 * @see WANObjectCache::getWithSetCallback()
3000 * @param IDatabase $db1
3001 * @param IDatabase ...
3002 * @return array Map of values:
3003 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3004 * - since: oldest UNIX timestamp of any of the DB lag estimates
3005 * - pending: whether any of the DBs have uncommitted changes
3008 public static function getCacheSetOptions( IDatabase
$db1 ) {
3009 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3010 foreach ( func_get_args() as $db ) {
3011 /** @var IDatabase $db */
3012 $status = $db->getSessionLagStatus();
3013 if ( $status['lag'] === false ) {
3014 $res['lag'] = false;
3015 } elseif ( $res['lag'] !== false ) {
3016 $res['lag'] = max( $res['lag'], $status['lag'] );
3018 $res['since'] = min( $res['since'], $status['since'] );
3019 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3025 public function getLag() {
3029 public function maxListLen() {
3033 public function encodeBlob( $b ) {
3037 public function decodeBlob( $b ) {
3038 if ( $b instanceof Blob
) {
3044 public function setSessionOptions( array $options ) {
3047 public function sourceFile(
3049 callable
$lineCallback = null,
3050 callable
$resultCallback = null,
3052 callable
$inputCallback = null
3054 MediaWiki\
suppressWarnings();
3055 $fp = fopen( $filename, 'r' );
3056 MediaWiki\restoreWarnings
();
3058 if ( false === $fp ) {
3059 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3063 $fname = __METHOD__
. "( $filename )";
3067 $error = $this->sourceStream(
3068 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3069 } catch ( Exception
$e ) {
3079 public function setSchemaVars( $vars ) {
3080 $this->mSchemaVars
= $vars;
3083 public function sourceStream(
3085 callable
$lineCallback = null,
3086 callable
$resultCallback = null,
3087 $fname = __METHOD__
,
3088 callable
$inputCallback = null
3092 while ( !feof( $fp ) ) {
3093 if ( $lineCallback ) {
3094 call_user_func( $lineCallback );
3097 $line = trim( fgets( $fp ) );
3099 if ( $line == '' ) {
3103 if ( '-' == $line[0] && '-' == $line[1] ) {
3111 $done = $this->streamStatementEnd( $cmd, $line );
3115 if ( $done ||
feof( $fp ) ) {
3116 $cmd = $this->replaceVars( $cmd );
3118 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3119 $res = $this->query( $cmd, $fname );
3121 if ( $resultCallback ) {
3122 call_user_func( $resultCallback, $res, $this );
3125 if ( false === $res ) {
3126 $err = $this->lastError();
3128 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3139 * Called by sourceStream() to check if we've reached a statement end
3141 * @param string &$sql SQL assembled so far
3142 * @param string &$newLine New line about to be added to $sql
3143 * @return bool Whether $newLine contains end of the statement
3145 public function streamStatementEnd( &$sql, &$newLine ) {
3146 if ( $this->delimiter
) {
3148 $newLine = preg_replace(
3149 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3150 if ( $newLine != $prev ) {
3159 * Database independent variable replacement. Replaces a set of variables
3160 * in an SQL statement with their contents as given by $this->getSchemaVars().
3162 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3164 * - '{$var}' should be used for text and is passed through the database's
3166 * - `{$var}` should be used for identifiers (e.g. table and database names).
3167 * It is passed through the database's addIdentifierQuotes method which
3168 * can be overridden if the database uses something other than backticks.
3169 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3170 * database's tableName method.
3171 * - / *i* / passes the name that follows through the database's indexName method.
3172 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3173 * its use should be avoided. In 1.24 and older, string encoding was applied.
3175 * @param string $ins SQL statement to replace variables in
3176 * @return string The new SQL statement with variables replaced
3178 protected function replaceVars( $ins ) {
3179 $vars = $this->getSchemaVars();
3180 return preg_replace_callback(
3182 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3183 \'\{\$ (\w+) }\' | # 3. addQuotes
3184 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3185 /\*\$ (\w+) \*/ # 5. leave unencoded
3187 function ( $m ) use ( $vars ) {
3188 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3189 // check for both nonexistent keys *and* the empty string.
3190 if ( isset( $m[1] ) && $m[1] !== '' ) {
3191 if ( $m[1] === 'i' ) {
3192 return $this->indexName( $m[2] );
3194 return $this->tableName( $m[2] );
3196 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3197 return $this->addQuotes( $vars[$m[3]] );
3198 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3199 return $this->addIdentifierQuotes( $vars[$m[4]] );
3200 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3201 return $vars[$m[5]];
3211 * Get schema variables. If none have been set via setSchemaVars(), then
3212 * use some defaults from the current object.
3216 protected function getSchemaVars() {
3217 if ( $this->mSchemaVars
) {
3218 return $this->mSchemaVars
;
3220 return $this->getDefaultSchemaVars();
3225 * Get schema variables to use if none have been set via setSchemaVars().
3227 * Override this in derived classes to provide variables for tables.sql
3228 * and SQL patch files.
3232 protected function getDefaultSchemaVars() {
3236 public function lockIsFree( $lockName, $method ) {
3240 public function lock( $lockName, $method, $timeout = 5 ) {
3241 $this->mNamedLocksHeld
[$lockName] = 1;
3246 public function unlock( $lockName, $method ) {
3247 unset( $this->mNamedLocksHeld
[$lockName] );
3252 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3253 if ( $this->writesOrCallbacksPending() ) {
3254 // This only flushes transactions to clear snapshots, not to write data
3255 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3256 throw new DBUnexpectedError(
3258 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3262 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3266 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3267 if ( $this->trxLevel() ) {
3268 // There is a good chance an exception was thrown, causing any early return
3269 // from the caller. Let any error handler get a chance to issue rollback().
3270 // If there isn't one, let the error bubble up and trigger server-side rollback.
3271 $this->onTransactionResolution(
3272 function () use ( $lockKey, $fname ) {
3273 $this->unlock( $lockKey, $fname );
3278 $this->unlock( $lockKey, $fname );
3282 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3287 public function namedLocksEnqueue() {
3292 * Lock specific tables
3294 * @param array $read Array of tables to lock for read access
3295 * @param array $write Array of tables to lock for write access
3296 * @param string $method Name of caller
3297 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3300 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3305 * Unlock specific tables
3307 * @param string $method The caller
3310 public function unlockTables( $method ) {
3316 * @param string $tableName
3317 * @param string $fName
3318 * @return bool|ResultWrapper
3321 public function dropTable( $tableName, $fName = __METHOD__
) {
3322 if ( !$this->tableExists( $tableName, $fName ) ) {
3325 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3327 return $this->query( $sql, $fName );
3330 public function getInfinity() {
3334 public function encodeExpiry( $expiry ) {
3335 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3336 ?
$this->getInfinity()
3337 : $this->timestamp( $expiry );
3340 public function decodeExpiry( $expiry, $format = TS_MW
) {
3341 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3345 return ConvertibleTimestamp
::convert( $format, $expiry );
3348 public function setBigSelects( $value = true ) {
3352 public function isReadOnly() {
3353 return ( $this->getReadOnlyReason() !== false );
3357 * @return string|bool Reason this DB is read-only or false if it is not
3359 protected function getReadOnlyReason() {
3360 $reason = $this->getLBInfo( 'readOnlyReason' );
3362 return is_string( $reason ) ?
$reason : false;
3365 public function setTableAliases( array $aliases ) {
3366 $this->tableAliases
= $aliases;
3370 * @return bool Whether a DB user is required to access the DB
3373 protected function requiresDatabaseUser() {
3378 * Get the underlying binding handle, mConn
3380 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3381 * This catches broken callers than catch and ignore disconnection exceptions.
3382 * Unlike checking isOpen(), this is safe to call inside of open().
3384 * @return resource|object
3385 * @throws DBUnexpectedError
3388 protected function getBindingHandle() {
3389 if ( !$this->mConn
) {
3390 throw new DBUnexpectedError(
3392 'DB connection was already closed or the connection dropped.'
3396 return $this->mConn
;
3403 public function __toString() {
3404 return (string)$this->mConn
;
3408 * Make sure that copies do not share the same client binding handle
3409 * @throws DBConnectionError
3411 public function __clone() {
3412 $this->connLogger
->warning(
3413 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3414 ( new RuntimeException() )->getTraceAsString()
3417 if ( $this->isOpen() ) {
3418 // Open a new connection resource without messing with the old one
3419 $this->mOpened
= false;
3420 $this->mConn
= false;
3421 $this->mTrxEndCallbacks
= []; // don't copy
3422 $this->handleSessionLoss(); // no trx or locks anymore
3423 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3424 $this->lastPing
= microtime( true );
3429 * Called by serialize. Throw an exception when DB connection is serialized.
3430 * This causes problems on some database engines because the connection is
3431 * not restored on unserialize.
3433 public function __sleep() {
3434 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3435 'the connection is not restored on wakeup.' );
3439 * Run a few simple sanity checks and close dangling connections
3441 public function __destruct() {
3442 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3443 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3446 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3447 if ( $danglingWriters ) {
3448 $fnames = implode( ', ', $danglingWriters );
3449 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3452 if ( $this->mConn
) {
3453 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3454 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3455 \MediaWiki\
suppressWarnings();
3456 $this->closeConnection();
3457 \MediaWiki\restoreWarnings
();
3458 $this->mConn
= false;
3459 $this->mOpened
= false;
3464 class_alias( Database
::class, 'DatabaseBase' );