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\ResultWrapper
;
33 use Wikimedia\Rdbms\DBMasterPos
;
34 use Wikimedia\Rdbms\Blob
;
35 use Wikimedia\Timestamp\ConvertibleTimestamp
;
38 * Relational database abstraction object
43 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
44 /** Number of times to re-try an operation in case of deadlock */
45 const DEADLOCK_TRIES
= 4;
46 /** Minimum time to wait before retry, in microseconds */
47 const DEADLOCK_DELAY_MIN
= 500000;
48 /** Maximum time to wait before retry */
49 const DEADLOCK_DELAY_MAX
= 1500000;
51 /** How long before it is worth doing a dummy query to test the connection */
53 const PING_QUERY
= 'SELECT 1 AS ping';
55 const TINY_WRITE_SEC
= .010;
56 const SLOW_WRITE_SEC
= .500;
57 const SMALL_WRITE_ROWS
= 100;
59 /** @var string SQL query */
60 protected $mLastQuery = '';
61 /** @var float|bool UNIX timestamp of last write query */
62 protected $mLastWriteTime = false;
63 /** @var string|bool */
64 protected $mPHPError = false;
73 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
74 protected $tableAliases = [];
75 /** @var bool Whether this PHP instance is for a CLI script */
77 /** @var string Agent name for query profiling */
80 /** @var BagOStuff APC cache */
82 /** @var LoggerInterface */
83 protected $connLogger;
84 /** @var LoggerInterface */
85 protected $queryLogger;
86 /** @var callback Error logging callback */
87 protected $errorLogger;
89 /** @var resource|null Database connection */
90 protected $mConn = null;
92 protected $mOpened = false;
94 /** @var array[] List of (callable, method name) */
95 protected $mTrxIdleCallbacks = [];
96 /** @var array[] List of (callable, method name) */
97 protected $mTrxPreCommitCallbacks = [];
98 /** @var array[] List of (callable, method name) */
99 protected $mTrxEndCallbacks = [];
100 /** @var callable[] Map of (name => callable) */
101 protected $mTrxRecurringCallbacks = [];
102 /** @var bool Whether to suppress triggering of transaction end callbacks */
103 protected $mTrxEndCallbacksSuppressed = false;
106 protected $mTablePrefix = '';
108 protected $mSchema = '';
112 protected $mLBInfo = [];
113 /** @var bool|null */
114 protected $mDefaultBigSelects = null;
115 /** @var array|bool */
116 protected $mSchemaVars = false;
118 protected $mSessionVars = [];
119 /** @var array|null */
120 protected $preparedArgs;
121 /** @var string|bool|null Stashed value of html_errors INI setting */
122 protected $htmlErrors;
124 protected $delimiter = ';';
125 /** @var DatabaseDomain */
126 protected $currentDomain;
129 * Either 1 if a transaction is active or 0 otherwise.
130 * The other Trx fields may not be meaningfull if this is 0.
134 protected $mTrxLevel = 0;
136 * Either a short hexidecimal string if a transaction is active or ""
139 * @see Database::mTrxLevel
141 protected $mTrxShortId = '';
143 * The UNIX time that the transaction started. Callers can assume that if
144 * snapshot isolation is used, then the data is *at least* up to date to that
145 * point (possibly more up-to-date since the first SELECT defines the snapshot).
148 * @see Database::mTrxLevel
150 private $mTrxTimestamp = null;
151 /** @var float Lag estimate at the time of BEGIN */
152 private $mTrxReplicaLag = null;
154 * Remembers the function name given for starting the most recent transaction via begin().
155 * Used to provide additional context for error reporting.
158 * @see Database::mTrxLevel
160 private $mTrxFname = null;
162 * Record if possible write queries were done in the last transaction started
165 * @see Database::mTrxLevel
167 private $mTrxDoneWrites = false;
169 * Record if the current transaction was started implicitly due to DBO_TRX being set.
172 * @see Database::mTrxLevel
174 private $mTrxAutomatic = false;
176 * Array of levels of atomicity within transactions
180 private $mTrxAtomicLevels = [];
182 * Record if the current transaction was started implicitly by Database::startAtomic
186 private $mTrxAutomaticAtomic = false;
188 * Track the write query callers of the current transaction
192 private $mTrxWriteCallers = [];
194 * @var float Seconds spent in write queries for the current transaction
196 private $mTrxWriteDuration = 0.0;
198 * @var integer Number of write queries for the current transaction
200 private $mTrxWriteQueryCount = 0;
202 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
204 private $mTrxWriteAdjDuration = 0.0;
206 * @var integer Number of write queries counted in mTrxWriteAdjDuration
208 private $mTrxWriteAdjQueryCount = 0;
210 * @var float RTT time estimate
212 private $mRTTEstimate = 0.0;
214 /** @var array Map of (name => 1) for locks obtained via lock() */
215 private $mNamedLocksHeld = [];
216 /** @var array Map of (table name => 1) for TEMPORARY tables */
217 protected $mSessionTempTables = [];
219 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
220 private $lazyMasterHandle;
222 /** @var float UNIX timestamp */
223 protected $lastPing = 0.0;
225 /** @var int[] Prior mFlags values */
226 private $priorFlags = [];
228 /** @var object|string Class name or object With profileIn/profileOut methods */
230 /** @var TransactionProfiler */
231 protected $trxProfiler;
234 * Constructor and database handle and attempt to connect to the DB server
236 * IDatabase classes should not be constructed directly in external
237 * code. Database::factory() should be used instead.
239 * @param array $params Parameters passed from Database::factory()
241 function __construct( array $params ) {
242 $server = $params['host'];
243 $user = $params['user'];
244 $password = $params['password'];
245 $dbName = $params['dbname'];
247 $this->mSchema
= $params['schema'];
248 $this->mTablePrefix
= $params['tablePrefix'];
250 $this->cliMode
= $params['cliMode'];
251 // Agent name is added to SQL queries in a comment, so make sure it can't break out
252 $this->agent
= str_replace( '/', '-', $params['agent'] );
254 $this->mFlags
= $params['flags'];
255 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
256 if ( $this->cliMode
) {
257 $this->mFlags
&= ~self
::DBO_TRX
;
259 $this->mFlags |
= self
::DBO_TRX
;
263 $this->mSessionVars
= $params['variables'];
265 $this->srvCache
= isset( $params['srvCache'] )
266 ?
$params['srvCache']
267 : new HashBagOStuff();
269 $this->profiler
= $params['profiler'];
270 $this->trxProfiler
= $params['trxProfiler'];
271 $this->connLogger
= $params['connLogger'];
272 $this->queryLogger
= $params['queryLogger'];
273 $this->errorLogger
= $params['errorLogger'];
275 // Set initial dummy domain until open() sets the final DB/prefix
276 $this->currentDomain
= DatabaseDomain
::newUnspecified();
279 $this->open( $server, $user, $password, $dbName );
280 } elseif ( $this->requiresDatabaseUser() ) {
281 throw new InvalidArgumentException( "No database user provided." );
284 // Set the domain object after open() sets the relevant fields
285 if ( $this->mDBname
!= '' ) {
286 // Domains with server scope but a table prefix are not used by IDatabase classes
287 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
292 * Construct a Database subclass instance given a database type and parameters
294 * This also connects to the database immediately upon object construction
296 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
297 * @param array $p Parameter map with keys:
298 * - host : The hostname of the DB server
299 * - user : The name of the database user the client operates under
300 * - password : The password for the database user
301 * - dbname : The name of the database to use where queries do not specify one.
302 * The database must exist or an error might be thrown. Setting this to the empty string
303 * will avoid any such errors and make the handle have no implicit database scope. This is
304 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
305 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
306 * in which user names and such are defined, e.g. users are database-specific in Postgres.
307 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
308 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
309 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
310 * recognized in queries. This can be used in place of schemas for handle site farms.
311 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
312 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
313 * flag in place UNLESS this this database simply acts as a key/value store.
314 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
315 * 'mysql' driver and the newer 'mysqli' driver.
316 * - variables: Optional map of session variables to set after connecting. This can be
317 * used to adjust lock timeouts or encoding modes and the like.
318 * - connLogger: Optional PSR-3 logger interface instance.
319 * - queryLogger: Optional PSR-3 logger interface instance.
320 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
321 * These will be called in query(), using a simplified version of the SQL that also
322 * includes the agent as a SQL comment.
323 * - trxProfiler: Optional TransactionProfiler instance.
324 * - errorLogger: Optional callback that takes an Exception and logs it.
325 * - cliMode: Whether to consider the execution context that of a CLI script.
326 * - agent: Optional name used to identify the end-user in query profiling/logging.
327 * - srvCache: Optional BagOStuff instance to an APC-style cache.
328 * @return Database|null If the database driver or extension cannot be found
329 * @throws InvalidArgumentException If the database driver or extension cannot be found
332 final public static function factory( $dbType, $p = [] ) {
333 static $canonicalDBTypes = [
334 'mysql' => [ 'mysqli', 'mysql' ],
342 $dbType = strtolower( $dbType );
343 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
344 $possibleDrivers = $canonicalDBTypes[$dbType];
345 if ( !empty( $p['driver'] ) ) {
346 if ( in_array( $p['driver'], $possibleDrivers ) ) {
347 $driver = $p['driver'];
349 throw new InvalidArgumentException( __METHOD__
.
350 " type '$dbType' does not support driver '{$p['driver']}'" );
353 foreach ( $possibleDrivers as $posDriver ) {
354 if ( extension_loaded( $posDriver ) ) {
355 $driver = $posDriver;
363 if ( $driver === false ||
$driver === '' ) {
364 throw new InvalidArgumentException( __METHOD__
.
365 " no viable database extension found for type '$dbType'" );
368 $class = 'Database' . ucfirst( $driver );
369 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
370 // Resolve some defaults for b/c
371 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
372 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
373 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
374 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
375 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
376 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
377 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
378 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
379 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
380 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
381 if ( !isset( $p['connLogger'] ) ) {
382 $p['connLogger'] = new \Psr\Log\
NullLogger();
384 if ( !isset( $p['queryLogger'] ) ) {
385 $p['queryLogger'] = new \Psr\Log\
NullLogger();
387 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
388 if ( !isset( $p['trxProfiler'] ) ) {
389 $p['trxProfiler'] = new TransactionProfiler();
391 if ( !isset( $p['errorLogger'] ) ) {
392 $p['errorLogger'] = function ( Exception
$e ) {
393 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
397 $conn = new $class( $p );
405 public function setLogger( LoggerInterface
$logger ) {
406 $this->queryLogger
= $logger;
409 public function getServerInfo() {
410 return $this->getServerVersion();
413 public function bufferResults( $buffer = null ) {
414 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
415 if ( $buffer !== null ) {
417 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
418 : $this->setFlag( self
::DBO_NOBUFFER
);
425 * Turns on (false) or off (true) the automatic generation and sending
426 * of a "we're sorry, but there has been a database error" page on
427 * database errors. Default is on (false). When turned off, the
428 * code should use lastErrno() and lastError() to handle the
429 * situation as appropriate.
431 * Do not use this function outside of the Database classes.
433 * @param null|bool $ignoreErrors
434 * @return bool The previous value of the flag.
436 protected function ignoreErrors( $ignoreErrors = null ) {
437 $res = $this->getFlag( self
::DBO_IGNORE
);
438 if ( $ignoreErrors !== null ) {
440 ?
$this->setFlag( self
::DBO_IGNORE
)
441 : $this->clearFlag( self
::DBO_IGNORE
);
447 public function trxLevel() {
448 return $this->mTrxLevel
;
451 public function trxTimestamp() {
452 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
455 public function tablePrefix( $prefix = null ) {
456 $old = $this->mTablePrefix
;
457 if ( $prefix !== null ) {
458 $this->mTablePrefix
= $prefix;
459 $this->currentDomain
= ( $this->mDBname
!= '' )
460 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
461 : DatabaseDomain
::newUnspecified();
467 public function dbSchema( $schema = null ) {
468 $old = $this->mSchema
;
469 if ( $schema !== null ) {
470 $this->mSchema
= $schema;
476 public function getLBInfo( $name = null ) {
477 if ( is_null( $name ) ) {
478 return $this->mLBInfo
;
480 if ( array_key_exists( $name, $this->mLBInfo
) ) {
481 return $this->mLBInfo
[$name];
488 public function setLBInfo( $name, $value = null ) {
489 if ( is_null( $value ) ) {
490 $this->mLBInfo
= $name;
492 $this->mLBInfo
[$name] = $value;
496 public function setLazyMasterHandle( IDatabase
$conn ) {
497 $this->lazyMasterHandle
= $conn;
501 * @return IDatabase|null
502 * @see setLazyMasterHandle()
505 protected function getLazyMasterHandle() {
506 return $this->lazyMasterHandle
;
509 public function implicitGroupby() {
513 public function implicitOrderby() {
517 public function lastQuery() {
518 return $this->mLastQuery
;
521 public function doneWrites() {
522 return (bool)$this->mLastWriteTime
;
525 public function lastDoneWrites() {
526 return $this->mLastWriteTime ?
: false;
529 public function writesPending() {
530 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
533 public function writesOrCallbacksPending() {
534 return $this->mTrxLevel
&& (
535 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
539 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
540 if ( !$this->mTrxLevel
) {
542 } elseif ( !$this->mTrxDoneWrites
) {
547 case self
::ESTIMATE_DB_APPLY
:
549 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
550 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
551 // For omitted queries, make them count as something at least
552 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
553 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
556 default: // everything
557 return $this->mTrxWriteDuration
;
561 public function pendingWriteCallers() {
562 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
565 protected function pendingWriteAndCallbackCallers() {
566 if ( !$this->mTrxLevel
) {
570 $fnames = $this->mTrxWriteCallers
;
572 $this->mTrxIdleCallbacks
,
573 $this->mTrxPreCommitCallbacks
,
574 $this->mTrxEndCallbacks
576 foreach ( $callbacks as $callback ) {
577 $fnames[] = $callback[1];
584 public function isOpen() {
585 return $this->mOpened
;
588 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
589 if ( $remember === self
::REMEMBER_PRIOR
) {
590 array_push( $this->priorFlags
, $this->mFlags
);
592 $this->mFlags |
= $flag;
595 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
596 if ( $remember === self
::REMEMBER_PRIOR
) {
597 array_push( $this->priorFlags
, $this->mFlags
);
599 $this->mFlags
&= ~
$flag;
602 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
603 if ( !$this->priorFlags
) {
607 if ( $state === self
::RESTORE_INITIAL
) {
608 $this->mFlags
= reset( $this->priorFlags
);
609 $this->priorFlags
= [];
611 $this->mFlags
= array_pop( $this->priorFlags
);
615 public function getFlag( $flag ) {
616 return !!( $this->mFlags
& $flag );
620 * @param string $name Class field name
622 * @deprecated Since 1.28
624 public function getProperty( $name ) {
628 public function getDomainID() {
629 return $this->currentDomain
->getId();
632 final public function getWikiID() {
633 return $this->getDomainID();
637 * Get information about an index into an object
638 * @param string $table Table name
639 * @param string $index Index name
640 * @param string $fname Calling function name
641 * @return mixed Database-specific index description class or false if the index does not exist
643 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
646 * Wrapper for addslashes()
648 * @param string $s String to be slashed.
649 * @return string Slashed string.
651 abstract function strencode( $s );
653 protected function installErrorHandler() {
654 $this->mPHPError
= false;
655 $this->htmlErrors
= ini_set( 'html_errors', '0' );
656 set_error_handler( [ $this, 'connectionErrorLogger' ] );
660 * @return bool|string
662 protected function restoreErrorHandler() {
663 restore_error_handler();
664 if ( $this->htmlErrors
!== false ) {
665 ini_set( 'html_errors', $this->htmlErrors
);
668 return $this->getLastPHPError();
672 * @return string|bool Last PHP error for this DB (typically connection errors)
674 protected function getLastPHPError() {
675 if ( $this->mPHPError
) {
676 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
677 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
686 * This method should not be used outside of Database classes
689 * @param string $errstr
691 public function connectionErrorLogger( $errno, $errstr ) {
692 $this->mPHPError
= $errstr;
696 * Create a log context to pass to PSR-3 logger functions.
698 * @param array $extras Additional data to add to context
701 protected function getLogContext( array $extras = [] ) {
704 'db_server' => $this->mServer
,
705 'db_name' => $this->mDBname
,
706 'db_user' => $this->mUser
,
712 public function close() {
713 if ( $this->mConn
) {
714 if ( $this->trxLevel() ) {
715 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
718 $closed = $this->closeConnection();
719 $this->mConn
= false;
720 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
721 throw new RuntimeException( "Transaction callbacks still pending." );
725 $this->mOpened
= false;
731 * Make sure isOpen() returns true as a sanity check
733 * @throws DBUnexpectedError
735 protected function assertOpen() {
736 if ( !$this->isOpen() ) {
737 throw new DBUnexpectedError( $this, "DB connection was already closed." );
742 * Closes underlying database connection
744 * @return bool Whether connection was closed successfully
746 abstract protected function closeConnection();
748 public function reportConnectionError( $error = 'Unknown error' ) {
749 $myError = $this->lastError();
755 throw new DBConnectionError( $this, $error );
759 * The DBMS-dependent part of query()
761 * @param string $sql SQL query.
762 * @return ResultWrapper|bool Result object to feed to fetchObject,
763 * fetchRow, ...; or false on failure
765 abstract protected function doQuery( $sql );
768 * Determine whether a query writes to the DB.
769 * Should return true if unsure.
774 protected function isWriteQuery( $sql ) {
776 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
781 * @return string|null
783 protected function getQueryVerb( $sql ) {
784 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
788 * Determine whether a SQL statement is sensitive to isolation level.
789 * A SQL statement is considered transactable if its result could vary
790 * depending on the transaction isolation level. Operational commands
791 * such as 'SET' and 'SHOW' are not considered to be transactable.
796 protected function isTransactableQuery( $sql ) {
798 $this->getQueryVerb( $sql ),
799 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
805 * @param string $sql A SQL query
806 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
808 protected function registerTempTableOperation( $sql ) {
810 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
814 $this->mSessionTempTables
[$matches[1]] = 1;
817 } elseif ( preg_match(
818 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
822 unset( $this->mSessionTempTables
[$matches[1]] );
825 } elseif ( preg_match(
826 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
830 return isset( $this->mSessionTempTables
[$matches[1]] );
836 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
837 $priorWritesPending = $this->writesOrCallbacksPending();
838 $this->mLastQuery
= $sql;
840 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
842 $reason = $this->getReadOnlyReason();
843 if ( $reason !== false ) {
844 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
846 # Set a flag indicating that writes have been done
847 $this->mLastWriteTime
= microtime( true );
850 // Add trace comment to the begin of the sql string, right after the operator.
851 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
852 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
854 # Start implicit transactions that wrap the request if DBO_TRX is enabled
855 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
856 && $this->isTransactableQuery( $sql )
858 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
859 $this->mTrxAutomatic
= true;
862 # Keep track of whether the transaction has write queries pending
863 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
864 $this->mTrxDoneWrites
= true;
865 $this->trxProfiler
->transactionWritingIn(
866 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
869 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
870 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
873 # Avoid fatals if close() was called
876 # Send the query to the server
877 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
879 # Try reconnecting if the connection was lost
880 if ( false === $ret && $this->wasErrorReissuable() ) {
881 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
882 # Stash the last error values before anything might clear them
883 $lastError = $this->lastError();
884 $lastErrno = $this->lastErrno();
885 # Update state tracking to reflect transaction loss due to disconnection
886 $this->handleSessionLoss();
887 if ( $this->reconnect() ) {
888 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
889 $this->connLogger
->warning( $msg );
890 $this->queryLogger
->warning(
891 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
893 if ( !$recoverable ) {
894 # Callers may catch the exception and continue to use the DB
895 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
897 # Should be safe to silently retry the query
898 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
901 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
902 $this->connLogger
->error( $msg );
906 if ( false === $ret ) {
907 # Deadlocks cause the entire transaction to abort, not just the statement.
908 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
909 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
910 if ( $this->wasDeadlock() ) {
911 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
912 $tempIgnore = false; // not recoverable
914 # Update state tracking to reflect transaction loss
915 $this->handleSessionLoss();
918 $this->reportQueryError(
919 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
922 $res = $this->resultObject( $ret );
927 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
928 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
929 # generalizeSQL() will probably cut down the query to reasonable
930 # logging size most of the time. The substr is really just a sanity check.
932 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
934 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
937 # Include query transaction state
938 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
940 $startTime = microtime( true );
941 if ( $this->profiler
) {
942 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
944 $ret = $this->doQuery( $commentedSql );
945 if ( $this->profiler
) {
946 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
948 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
950 unset( $queryProfSection ); // profile out (if set)
952 if ( $ret !== false ) {
953 $this->lastPing
= $startTime;
954 if ( $isWrite && $this->mTrxLevel
) {
955 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
956 $this->mTrxWriteCallers
[] = $fname;
960 if ( $sql === self
::PING_QUERY
) {
961 $this->mRTTEstimate
= $queryRuntime;
964 $this->trxProfiler
->recordQueryCompletion(
965 $queryProf, $startTime, $isWrite, $this->affectedRows()
967 $this->queryLogger
->debug( $sql, [
969 'master' => $isMaster,
970 'runtime' => $queryRuntime,
977 * Update the estimated run-time of a query, not counting large row lock times
979 * LoadBalancer can be set to rollback transactions that will create huge replication
980 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
981 * queries, like inserting a row can take a long time due to row locking. This method
982 * uses some simple heuristics to discount those cases.
984 * @param string $sql A SQL write query
985 * @param float $runtime Total runtime, including RTT
987 private function updateTrxWriteQueryTime( $sql, $runtime ) {
988 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
989 $indicativeOfReplicaRuntime = true;
990 if ( $runtime > self
::SLOW_WRITE_SEC
) {
991 $verb = $this->getQueryVerb( $sql );
992 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
993 if ( $verb === 'INSERT' ) {
994 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
995 } elseif ( $verb === 'REPLACE' ) {
996 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1000 $this->mTrxWriteDuration +
= $runtime;
1001 $this->mTrxWriteQueryCount +
= 1;
1002 if ( $indicativeOfReplicaRuntime ) {
1003 $this->mTrxWriteAdjDuration +
= $runtime;
1004 $this->mTrxWriteAdjQueryCount +
= 1;
1008 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1009 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1010 # Dropped connections also mean that named locks are automatically released.
1011 # Only allow error suppression in autocommit mode or when the lost transaction
1012 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1013 if ( $this->mNamedLocksHeld
) {
1014 return false; // possible critical section violation
1015 } elseif ( $sql === 'COMMIT' ) {
1016 return !$priorWritesPending; // nothing written anyway? (T127428)
1017 } elseif ( $sql === 'ROLLBACK' ) {
1018 return true; // transaction lost...which is also what was requested :)
1019 } elseif ( $this->explicitTrxActive() ) {
1020 return false; // don't drop atomocity
1021 } elseif ( $priorWritesPending ) {
1022 return false; // prior writes lost from implicit transaction
1028 private function handleSessionLoss() {
1029 $this->mTrxLevel
= 0;
1030 $this->mTrxIdleCallbacks
= []; // T67263
1031 $this->mTrxPreCommitCallbacks
= []; // T67263
1032 $this->mSessionTempTables
= [];
1033 $this->mNamedLocksHeld
= [];
1035 // Handle callbacks in mTrxEndCallbacks
1036 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1037 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1039 } catch ( Exception
$e ) {
1040 // Already logged; move on...
1045 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1046 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1047 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1049 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1050 $this->queryLogger
->error(
1051 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1052 $this->getLogContext( [
1053 'method' => __METHOD__
,
1056 'sql1line' => $sql1line,
1060 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1061 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1065 public function freeResult( $res ) {
1068 public function selectField(
1069 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1071 if ( $var === '*' ) { // sanity
1072 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1075 if ( !is_array( $options ) ) {
1076 $options = [ $options ];
1079 $options['LIMIT'] = 1;
1081 $res = $this->select( $table, $var, $cond, $fname, $options );
1082 if ( $res === false ||
!$this->numRows( $res ) ) {
1086 $row = $this->fetchRow( $res );
1088 if ( $row !== false ) {
1089 return reset( $row );
1095 public function selectFieldValues(
1096 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1098 if ( $var === '*' ) { // sanity
1099 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1100 } elseif ( !is_string( $var ) ) { // sanity
1101 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1104 if ( !is_array( $options ) ) {
1105 $options = [ $options ];
1108 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1109 if ( $res === false ) {
1114 foreach ( $res as $row ) {
1115 $values[] = $row->$var;
1122 * Returns an optional USE INDEX clause to go after the table, and a
1123 * string to go at the end of the query.
1125 * @param array $options Associative array of options to be turned into
1126 * an SQL query, valid keys are listed in the function.
1128 * @see Database::select()
1130 protected function makeSelectOptions( $options ) {
1131 $preLimitTail = $postLimitTail = '';
1136 foreach ( $options as $key => $option ) {
1137 if ( is_numeric( $key ) ) {
1138 $noKeyOptions[$option] = true;
1142 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1144 $preLimitTail .= $this->makeOrderBy( $options );
1146 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1147 $postLimitTail .= ' FOR UPDATE';
1150 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1151 $postLimitTail .= ' LOCK IN SHARE MODE';
1154 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1155 $startOpts .= 'DISTINCT';
1158 # Various MySQL extensions
1159 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1160 $startOpts .= ' /*! STRAIGHT_JOIN */';
1163 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1164 $startOpts .= ' HIGH_PRIORITY';
1167 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1168 $startOpts .= ' SQL_BIG_RESULT';
1171 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1172 $startOpts .= ' SQL_BUFFER_RESULT';
1175 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1176 $startOpts .= ' SQL_SMALL_RESULT';
1179 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1180 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1183 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1184 $startOpts .= ' SQL_CACHE';
1187 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1188 $startOpts .= ' SQL_NO_CACHE';
1191 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1192 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1196 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1197 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1202 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1206 * Returns an optional GROUP BY with an optional HAVING
1208 * @param array $options Associative array of options
1210 * @see Database::select()
1213 protected function makeGroupByWithHaving( $options ) {
1215 if ( isset( $options['GROUP BY'] ) ) {
1216 $gb = is_array( $options['GROUP BY'] )
1217 ?
implode( ',', $options['GROUP BY'] )
1218 : $options['GROUP BY'];
1219 $sql .= ' GROUP BY ' . $gb;
1221 if ( isset( $options['HAVING'] ) ) {
1222 $having = is_array( $options['HAVING'] )
1223 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1224 : $options['HAVING'];
1225 $sql .= ' HAVING ' . $having;
1232 * Returns an optional ORDER BY
1234 * @param array $options Associative array of options
1236 * @see Database::select()
1239 protected function makeOrderBy( $options ) {
1240 if ( isset( $options['ORDER BY'] ) ) {
1241 $ob = is_array( $options['ORDER BY'] )
1242 ?
implode( ',', $options['ORDER BY'] )
1243 : $options['ORDER BY'];
1245 return ' ORDER BY ' . $ob;
1251 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1252 $options = [], $join_conds = [] ) {
1253 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1255 return $this->query( $sql, $fname );
1258 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1259 $options = [], $join_conds = []
1261 if ( is_array( $vars ) ) {
1262 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1265 $options = (array)$options;
1266 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1267 ?
$options['USE INDEX']
1270 isset( $options['IGNORE INDEX'] ) &&
1271 is_array( $options['IGNORE INDEX'] )
1273 ?
$options['IGNORE INDEX']
1276 if ( is_array( $table ) ) {
1278 $this->tableNamesWithIndexClauseOrJOIN(
1279 $table, $useIndexes, $ignoreIndexes, $join_conds );
1280 } elseif ( $table != '' ) {
1281 if ( $table[0] == ' ' ) {
1282 $from = ' FROM ' . $table;
1285 $this->tableNamesWithIndexClauseOrJOIN(
1286 [ $table ], $useIndexes, $ignoreIndexes, [] );
1292 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1293 $this->makeSelectOptions( $options );
1295 if ( !empty( $conds ) ) {
1296 if ( is_array( $conds ) ) {
1297 $conds = $this->makeList( $conds, self
::LIST_AND
);
1299 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1300 "WHERE $conds $preLimitTail";
1302 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1305 if ( isset( $options['LIMIT'] ) ) {
1306 $sql = $this->limitResult( $sql, $options['LIMIT'],
1307 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1309 $sql = "$sql $postLimitTail";
1311 if ( isset( $options['EXPLAIN'] ) ) {
1312 $sql = 'EXPLAIN ' . $sql;
1318 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1319 $options = [], $join_conds = []
1321 $options = (array)$options;
1322 $options['LIMIT'] = 1;
1323 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1325 if ( $res === false ) {
1329 if ( !$this->numRows( $res ) ) {
1333 $obj = $this->fetchObject( $res );
1338 public function estimateRowCount(
1339 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1342 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1345 $row = $this->fetchRow( $res );
1346 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1352 public function selectRowCount(
1353 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1356 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1357 // The identifier quotes is primarily for MSSQL.
1358 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1359 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1360 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1363 $row = $this->fetchRow( $res );
1364 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1371 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1372 * It's only slightly flawed. Don't use for anything important.
1374 * @param string $sql A SQL Query
1378 protected static function generalizeSQL( $sql ) {
1379 # This does the same as the regexp below would do, but in such a way
1380 # as to avoid crashing php on some large strings.
1381 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1383 $sql = str_replace( "\\\\", '', $sql );
1384 $sql = str_replace( "\\'", '', $sql );
1385 $sql = str_replace( "\\\"", '', $sql );
1386 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1387 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1389 # All newlines, tabs, etc replaced by single space
1390 $sql = preg_replace( '/\s+/', ' ', $sql );
1393 # except the ones surrounded by characters, e.g. l10n
1394 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1395 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1400 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1401 $info = $this->fieldInfo( $table, $field );
1406 public function indexExists( $table, $index, $fname = __METHOD__
) {
1407 if ( !$this->tableExists( $table ) ) {
1411 $info = $this->indexInfo( $table, $index, $fname );
1412 if ( is_null( $info ) ) {
1415 return $info !== false;
1419 public function tableExists( $table, $fname = __METHOD__
) {
1420 $tableRaw = $this->tableName( $table, 'raw' );
1421 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1422 return true; // already known to exist
1425 $table = $this->tableName( $table );
1426 $ignoreErrors = true;
1427 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1432 public function indexUnique( $table, $index ) {
1433 $indexInfo = $this->indexInfo( $table, $index );
1435 if ( !$indexInfo ) {
1439 return !$indexInfo[0]->Non_unique
;
1443 * Helper for Database::insert().
1445 * @param array $options
1448 protected function makeInsertOptions( $options ) {
1449 return implode( ' ', $options );
1452 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1453 # No rows to insert, easy just return now
1454 if ( !count( $a ) ) {
1458 $table = $this->tableName( $table );
1460 if ( !is_array( $options ) ) {
1461 $options = [ $options ];
1465 if ( isset( $options['fileHandle'] ) ) {
1466 $fh = $options['fileHandle'];
1468 $options = $this->makeInsertOptions( $options );
1470 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1472 $keys = array_keys( $a[0] );
1475 $keys = array_keys( $a );
1478 $sql = 'INSERT ' . $options .
1479 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1483 foreach ( $a as $row ) {
1489 $sql .= '(' . $this->makeList( $row ) . ')';
1492 $sql .= '(' . $this->makeList( $a ) . ')';
1495 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1497 } elseif ( $fh !== null ) {
1501 return (bool)$this->query( $sql, $fname );
1505 * Make UPDATE options array for Database::makeUpdateOptions
1507 * @param array $options
1510 protected function makeUpdateOptionsArray( $options ) {
1511 if ( !is_array( $options ) ) {
1512 $options = [ $options ];
1517 if ( in_array( 'IGNORE', $options ) ) {
1525 * Make UPDATE options for the Database::update function
1527 * @param array $options The options passed to Database::update
1530 protected function makeUpdateOptions( $options ) {
1531 $opts = $this->makeUpdateOptionsArray( $options );
1533 return implode( ' ', $opts );
1536 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1537 $table = $this->tableName( $table );
1538 $opts = $this->makeUpdateOptions( $options );
1539 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1541 if ( $conds !== [] && $conds !== '*' ) {
1542 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1545 return $this->query( $sql, $fname );
1548 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1549 if ( !is_array( $a ) ) {
1550 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1556 foreach ( $a as $field => $value ) {
1558 if ( $mode == self
::LIST_AND
) {
1560 } elseif ( $mode == self
::LIST_OR
) {
1569 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1570 $list .= "($value)";
1571 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1574 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1576 // Remove null from array to be handled separately if found
1577 $includeNull = false;
1578 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1579 $includeNull = true;
1580 unset( $value[$nullKey] );
1582 if ( count( $value ) == 0 && !$includeNull ) {
1583 throw new InvalidArgumentException(
1584 __METHOD__
. ": empty input for field $field" );
1585 } elseif ( count( $value ) == 0 ) {
1586 // only check if $field is null
1587 $list .= "$field IS NULL";
1589 // IN clause contains at least one valid element
1590 if ( $includeNull ) {
1591 // Group subconditions to ensure correct precedence
1594 if ( count( $value ) == 1 ) {
1595 // Special-case single values, as IN isn't terribly efficient
1596 // Don't necessarily assume the single key is 0; we don't
1597 // enforce linear numeric ordering on other arrays here.
1598 $value = array_values( $value )[0];
1599 $list .= $field . " = " . $this->addQuotes( $value );
1601 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1603 // if null present in array, append IS NULL
1604 if ( $includeNull ) {
1605 $list .= " OR $field IS NULL)";
1608 } elseif ( $value === null ) {
1609 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1610 $list .= "$field IS ";
1611 } elseif ( $mode == self
::LIST_SET
) {
1612 $list .= "$field = ";
1617 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1619 $list .= "$field = ";
1621 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1628 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1631 foreach ( $data as $base => $sub ) {
1632 if ( count( $sub ) ) {
1633 $conds[] = $this->makeList(
1634 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1640 return $this->makeList( $conds, self
::LIST_OR
);
1642 // Nothing to search for...
1647 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1651 public function bitNot( $field ) {
1655 public function bitAnd( $fieldLeft, $fieldRight ) {
1656 return "($fieldLeft & $fieldRight)";
1659 public function bitOr( $fieldLeft, $fieldRight ) {
1660 return "($fieldLeft | $fieldRight)";
1663 public function buildConcat( $stringList ) {
1664 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1667 public function buildGroupConcatField(
1668 $delim, $table, $field, $conds = '', $join_conds = []
1670 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1672 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1675 public function buildStringCast( $field ) {
1679 public function selectDB( $db ) {
1680 # Stub. Shouldn't cause serious problems if it's not overridden, but
1681 # if your database engine supports a concept similar to MySQL's
1682 # databases you may as well.
1683 $this->mDBname
= $db;
1688 public function getDBname() {
1689 return $this->mDBname
;
1692 public function getServer() {
1693 return $this->mServer
;
1696 public function tableName( $name, $format = 'quoted' ) {
1697 # Skip the entire process when we have a string quoted on both ends.
1698 # Note that we check the end so that we will still quote any use of
1699 # use of `database`.table. But won't break things if someone wants
1700 # to query a database table with a dot in the name.
1701 if ( $this->isQuotedIdentifier( $name ) ) {
1705 # Lets test for any bits of text that should never show up in a table
1706 # name. Basically anything like JOIN or ON which are actually part of
1707 # SQL queries, but may end up inside of the table value to combine
1708 # sql. Such as how the API is doing.
1709 # Note that we use a whitespace test rather than a \b test to avoid
1710 # any remote case where a word like on may be inside of a table name
1711 # surrounded by symbols which may be considered word breaks.
1712 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1716 # Split database and table into proper variables.
1717 # We reverse the explode so that database.table and table both output
1718 # the correct table.
1719 $dbDetails = explode( '.', $name, 3 );
1720 if ( count( $dbDetails ) == 3 ) {
1721 list( $database, $schema, $table ) = $dbDetails;
1722 # We don't want any prefix added in this case
1724 } elseif ( count( $dbDetails ) == 2 ) {
1725 list( $database, $table ) = $dbDetails;
1726 # We don't want any prefix added in this case
1728 # In dbs that support it, $database may actually be the schema
1729 # but that doesn't affect any of the functionality here
1732 list( $table ) = $dbDetails;
1733 if ( isset( $this->tableAliases
[$table] ) ) {
1734 $database = $this->tableAliases
[$table]['dbname'];
1735 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1736 ?
$this->tableAliases
[$table]['schema']
1738 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1739 ?
$this->tableAliases
[$table]['prefix']
1740 : $this->mTablePrefix
;
1743 $schema = $this->mSchema
; # Default schema
1744 $prefix = $this->mTablePrefix
; # Default prefix
1748 # Quote $table and apply the prefix if not quoted.
1749 # $tableName might be empty if this is called from Database::replaceVars()
1750 $tableName = "{$prefix}{$table}";
1751 if ( $format === 'quoted'
1752 && !$this->isQuotedIdentifier( $tableName )
1753 && $tableName !== ''
1755 $tableName = $this->addIdentifierQuotes( $tableName );
1758 # Quote $schema and $database and merge them with the table name if needed
1759 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1760 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1766 * @param string|null $namespace Database or schema
1767 * @param string $relation Name of table, view, sequence, etc...
1768 * @param string $format One of (raw, quoted)
1769 * @return string Relation name with quoted and merged $namespace as needed
1771 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1772 if ( strlen( $namespace ) ) {
1773 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1774 $namespace = $this->addIdentifierQuotes( $namespace );
1776 $relation = $namespace . '.' . $relation;
1782 public function tableNames() {
1783 $inArray = func_get_args();
1786 foreach ( $inArray as $name ) {
1787 $retVal[$name] = $this->tableName( $name );
1793 public function tableNamesN() {
1794 $inArray = func_get_args();
1797 foreach ( $inArray as $name ) {
1798 $retVal[] = $this->tableName( $name );
1805 * Get an aliased table name
1806 * e.g. tableName AS newTableName
1808 * @param string $name Table name, see tableName()
1809 * @param string|bool $alias Alias (optional)
1810 * @return string SQL name for aliased table. Will not alias a table to its own name
1812 protected function tableNameWithAlias( $name, $alias = false ) {
1813 if ( !$alias ||
$alias == $name ) {
1814 return $this->tableName( $name );
1816 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1821 * Gets an array of aliased table names
1823 * @param array $tables [ [alias] => table ]
1824 * @return string[] See tableNameWithAlias()
1826 protected function tableNamesWithAlias( $tables ) {
1828 foreach ( $tables as $alias => $table ) {
1829 if ( is_numeric( $alias ) ) {
1832 $retval[] = $this->tableNameWithAlias( $table, $alias );
1839 * Get an aliased field name
1840 * e.g. fieldName AS newFieldName
1842 * @param string $name Field name
1843 * @param string|bool $alias Alias (optional)
1844 * @return string SQL name for aliased field. Will not alias a field to its own name
1846 protected function fieldNameWithAlias( $name, $alias = false ) {
1847 if ( !$alias ||
(string)$alias === (string)$name ) {
1850 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1855 * Gets an array of aliased field names
1857 * @param array $fields [ [alias] => field ]
1858 * @return string[] See fieldNameWithAlias()
1860 protected function fieldNamesWithAlias( $fields ) {
1862 foreach ( $fields as $alias => $field ) {
1863 if ( is_numeric( $alias ) ) {
1866 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1873 * Get the aliased table name clause for a FROM clause
1874 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1876 * @param array $tables ( [alias] => table )
1877 * @param array $use_index Same as for select()
1878 * @param array $ignore_index Same as for select()
1879 * @param array $join_conds Same as for select()
1882 protected function tableNamesWithIndexClauseOrJOIN(
1883 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1887 $use_index = (array)$use_index;
1888 $ignore_index = (array)$ignore_index;
1889 $join_conds = (array)$join_conds;
1891 foreach ( $tables as $alias => $table ) {
1892 if ( !is_string( $alias ) ) {
1893 // No alias? Set it equal to the table name
1896 // Is there a JOIN clause for this table?
1897 if ( isset( $join_conds[$alias] ) ) {
1898 list( $joinType, $conds ) = $join_conds[$alias];
1899 $tableClause = $joinType;
1900 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1901 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1902 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1904 $tableClause .= ' ' . $use;
1907 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1908 $ignore = $this->ignoreIndexClause(
1909 implode( ',', (array)$ignore_index[$alias] ) );
1910 if ( $ignore != '' ) {
1911 $tableClause .= ' ' . $ignore;
1914 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1916 $tableClause .= ' ON (' . $on . ')';
1919 $retJOIN[] = $tableClause;
1920 } elseif ( isset( $use_index[$alias] ) ) {
1921 // Is there an INDEX clause for this table?
1922 $tableClause = $this->tableNameWithAlias( $table, $alias );
1923 $tableClause .= ' ' . $this->useIndexClause(
1924 implode( ',', (array)$use_index[$alias] )
1927 $ret[] = $tableClause;
1928 } elseif ( isset( $ignore_index[$alias] ) ) {
1929 // Is there an INDEX clause for this table?
1930 $tableClause = $this->tableNameWithAlias( $table, $alias );
1931 $tableClause .= ' ' . $this->ignoreIndexClause(
1932 implode( ',', (array)$ignore_index[$alias] )
1935 $ret[] = $tableClause;
1937 $tableClause = $this->tableNameWithAlias( $table, $alias );
1939 $ret[] = $tableClause;
1943 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1944 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1945 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1947 // Compile our final table clause
1948 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1952 * Get the name of an index in a given table.
1954 * @param string $index
1957 protected function indexName( $index ) {
1961 public function addQuotes( $s ) {
1962 if ( $s instanceof Blob
) {
1965 if ( $s === null ) {
1967 } elseif ( is_bool( $s ) ) {
1970 # This will also quote numeric values. This should be harmless,
1971 # and protects against weird problems that occur when they really
1972 # _are_ strings such as article titles and string->number->string
1973 # conversion is not 1:1.
1974 return "'" . $this->strencode( $s ) . "'";
1979 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1980 * MySQL uses `backticks` while basically everything else uses double quotes.
1981 * Since MySQL is the odd one out here the double quotes are our generic
1982 * and we implement backticks in DatabaseMysql.
1987 public function addIdentifierQuotes( $s ) {
1988 return '"' . str_replace( '"', '""', $s ) . '"';
1992 * Returns if the given identifier looks quoted or not according to
1993 * the database convention for quoting identifiers .
1995 * @note Do not use this to determine if untrusted input is safe.
1996 * A malicious user can trick this function.
1997 * @param string $name
2000 public function isQuotedIdentifier( $name ) {
2001 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2008 protected function escapeLikeInternal( $s ) {
2009 return addcslashes( $s, '\%_' );
2012 public function buildLike() {
2013 $params = func_get_args();
2015 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2016 $params = $params[0];
2021 foreach ( $params as $value ) {
2022 if ( $value instanceof LikeMatch
) {
2023 $s .= $value->toString();
2025 $s .= $this->escapeLikeInternal( $value );
2029 return " LIKE {$this->addQuotes( $s )} ";
2032 public function anyChar() {
2033 return new LikeMatch( '_' );
2036 public function anyString() {
2037 return new LikeMatch( '%' );
2040 public function nextSequenceValue( $seqName ) {
2045 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2046 * is only needed because a) MySQL must be as efficient as possible due to
2047 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2048 * which index to pick. Anyway, other databases might have different
2049 * indexes on a given table. So don't bother overriding this unless you're
2051 * @param string $index
2054 public function useIndexClause( $index ) {
2059 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2060 * is only needed because a) MySQL must be as efficient as possible due to
2061 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2062 * which index to pick. Anyway, other databases might have different
2063 * indexes on a given table. So don't bother overriding this unless you're
2065 * @param string $index
2068 public function ignoreIndexClause( $index ) {
2072 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2073 $quotedTable = $this->tableName( $table );
2075 if ( count( $rows ) == 0 ) {
2080 if ( !is_array( reset( $rows ) ) ) {
2084 // @FXIME: this is not atomic, but a trx would break affectedRows()
2085 foreach ( $rows as $row ) {
2086 # Delete rows which collide
2087 if ( $uniqueIndexes ) {
2088 $sql = "DELETE FROM $quotedTable WHERE ";
2090 foreach ( $uniqueIndexes as $index ) {
2097 if ( is_array( $index ) ) {
2099 foreach ( $index as $col ) {
2105 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2108 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2112 $this->query( $sql, $fname );
2115 # Now insert the row
2116 $this->insert( $table, $row, $fname );
2121 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2124 * @param string $table Table name
2125 * @param array|string $rows Row(s) to insert
2126 * @param string $fname Caller function name
2128 * @return ResultWrapper
2130 protected function nativeReplace( $table, $rows, $fname ) {
2131 $table = $this->tableName( $table );
2134 if ( !is_array( reset( $rows ) ) ) {
2138 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2141 foreach ( $rows as $row ) {
2148 $sql .= '(' . $this->makeList( $row ) . ')';
2151 return $this->query( $sql, $fname );
2154 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2157 if ( !count( $rows ) ) {
2158 return true; // nothing to do
2161 if ( !is_array( reset( $rows ) ) ) {
2165 if ( count( $uniqueIndexes ) ) {
2166 $clauses = []; // list WHERE clauses that each identify a single row
2167 foreach ( $rows as $row ) {
2168 foreach ( $uniqueIndexes as $index ) {
2169 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2170 $rowKey = []; // unique key to this row
2171 foreach ( $index as $column ) {
2172 $rowKey[$column] = $row[$column];
2174 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2177 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2182 $useTrx = !$this->mTrxLevel
;
2184 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2187 # Update any existing conflicting row(s)
2188 if ( $where !== false ) {
2189 $ok = $this->update( $table, $set, $where, $fname );
2193 # Now insert any non-conflicting row(s)
2194 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2195 } catch ( Exception
$e ) {
2197 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2202 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2208 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2212 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2215 $delTable = $this->tableName( $delTable );
2216 $joinTable = $this->tableName( $joinTable );
2217 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2218 if ( $conds != '*' ) {
2219 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2223 $this->query( $sql, $fname );
2226 public function textFieldSize( $table, $field ) {
2227 $table = $this->tableName( $table );
2228 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2229 $res = $this->query( $sql, __METHOD__
);
2230 $row = $this->fetchObject( $res );
2234 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2243 public function delete( $table, $conds, $fname = __METHOD__
) {
2245 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2248 $table = $this->tableName( $table );
2249 $sql = "DELETE FROM $table";
2251 if ( $conds != '*' ) {
2252 if ( is_array( $conds ) ) {
2253 $conds = $this->makeList( $conds, self
::LIST_AND
);
2255 $sql .= ' WHERE ' . $conds;
2258 return $this->query( $sql, $fname );
2261 public function insertSelect(
2262 $destTable, $srcTable, $varMap, $conds,
2263 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2265 if ( $this->cliMode
) {
2266 // For massive migrations with downtime, we don't want to select everything
2267 // into memory and OOM, so do all this native on the server side if possible.
2268 return $this->nativeInsertSelect(
2279 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2280 // on only the master (without needing row-based-replication). It also makes it easy to
2281 // know how big the INSERT is going to be.
2283 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2284 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2286 $selectOptions[] = 'FOR UPDATE';
2287 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2293 foreach ( $res as $row ) {
2294 $rows[] = (array)$row;
2297 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2300 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2301 $fname = __METHOD__
,
2302 $insertOptions = [], $selectOptions = []
2304 $destTable = $this->tableName( $destTable );
2306 if ( !is_array( $insertOptions ) ) {
2307 $insertOptions = [ $insertOptions ];
2310 $insertOptions = $this->makeInsertOptions( $insertOptions );
2312 if ( !is_array( $selectOptions ) ) {
2313 $selectOptions = [ $selectOptions ];
2316 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2319 if ( is_array( $srcTable ) ) {
2320 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2322 $srcTable = $this->tableName( $srcTable );
2325 $sql = "INSERT $insertOptions" .
2326 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2327 " SELECT $startOpts " . implode( ',', $varMap ) .
2328 " FROM $srcTable $useIndex $ignoreIndex ";
2330 if ( $conds != '*' ) {
2331 if ( is_array( $conds ) ) {
2332 $conds = $this->makeList( $conds, self
::LIST_AND
);
2334 $sql .= " WHERE $conds";
2337 $sql .= " $tailOpts";
2339 return $this->query( $sql, $fname );
2343 * Construct a LIMIT query with optional offset. This is used for query
2344 * pages. The SQL should be adjusted so that only the first $limit rows
2345 * are returned. If $offset is provided as well, then the first $offset
2346 * rows should be discarded, and the next $limit rows should be returned.
2347 * If the result of the query is not ordered, then the rows to be returned
2348 * are theoretically arbitrary.
2350 * $sql is expected to be a SELECT, if that makes a difference.
2352 * The version provided by default works in MySQL and SQLite. It will very
2353 * likely need to be overridden for most other DBMSes.
2355 * @param string $sql SQL query we will append the limit too
2356 * @param int $limit The SQL limit
2357 * @param int|bool $offset The SQL offset (default false)
2358 * @throws DBUnexpectedError
2361 public function limitResult( $sql, $limit, $offset = false ) {
2362 if ( !is_numeric( $limit ) ) {
2363 throw new DBUnexpectedError( $this,
2364 "Invalid non-numeric limit passed to limitResult()\n" );
2367 return "$sql LIMIT "
2368 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2372 public function unionSupportsOrderAndLimit() {
2373 return true; // True for almost every DB supported
2376 public function unionQueries( $sqls, $all ) {
2377 $glue = $all ?
') UNION ALL (' : ') UNION (';
2379 return '(' . implode( $glue, $sqls ) . ')';
2382 public function conditional( $cond, $trueVal, $falseVal ) {
2383 if ( is_array( $cond ) ) {
2384 $cond = $this->makeList( $cond, self
::LIST_AND
);
2387 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2390 public function strreplace( $orig, $old, $new ) {
2391 return "REPLACE({$orig}, {$old}, {$new})";
2394 public function getServerUptime() {
2398 public function wasDeadlock() {
2402 public function wasLockTimeout() {
2406 public function wasErrorReissuable() {
2410 public function wasReadOnlyError() {
2415 * Do not use this method outside of Database/DBError classes
2417 * @param integer|string $errno
2418 * @return bool Whether the given query error was a connection drop
2420 public function wasConnectionError( $errno ) {
2424 public function deadlockLoop() {
2425 $args = func_get_args();
2426 $function = array_shift( $args );
2427 $tries = self
::DEADLOCK_TRIES
;
2429 $this->begin( __METHOD__
);
2432 /** @var Exception $e */
2436 $retVal = call_user_func_array( $function, $args );
2438 } catch ( DBQueryError
$e ) {
2439 if ( $this->wasDeadlock() ) {
2440 // Retry after a randomized delay
2441 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2443 // Throw the error back up
2447 } while ( --$tries > 0 );
2449 if ( $tries <= 0 ) {
2450 // Too many deadlocks; give up
2451 $this->rollback( __METHOD__
);
2454 $this->commit( __METHOD__
);
2460 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2461 # Real waits are implemented in the subclass.
2465 public function getReplicaPos() {
2470 public function getMasterPos() {
2475 public function serverIsReadOnly() {
2479 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2480 if ( !$this->mTrxLevel
) {
2481 throw new DBUnexpectedError( $this, "No transaction is active." );
2483 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2486 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2487 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2488 if ( !$this->mTrxLevel
) {
2489 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2493 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2494 if ( $this->mTrxLevel
) {
2495 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2497 // If no transaction is active, then make one for this callback
2498 $this->startAtomic( __METHOD__
);
2500 call_user_func( $callback );
2501 $this->endAtomic( __METHOD__
);
2502 } catch ( Exception
$e ) {
2503 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2509 final public function setTransactionListener( $name, callable
$callback = null ) {
2511 $this->mTrxRecurringCallbacks
[$name] = $callback;
2513 unset( $this->mTrxRecurringCallbacks
[$name] );
2518 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2520 * This method should not be used outside of Database/LoadBalancer
2522 * @param bool $suppress
2525 final public function setTrxEndCallbackSuppression( $suppress ) {
2526 $this->mTrxEndCallbacksSuppressed
= $suppress;
2530 * Actually run and consume any "on transaction idle/resolution" callbacks.
2532 * This method should not be used outside of Database/LoadBalancer
2534 * @param integer $trigger IDatabase::TRIGGER_* constant
2538 public function runOnTransactionIdleCallbacks( $trigger ) {
2539 if ( $this->mTrxEndCallbacksSuppressed
) {
2543 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2544 /** @var Exception $e */
2545 $e = null; // first exception
2546 do { // callbacks may add callbacks :)
2547 $callbacks = array_merge(
2548 $this->mTrxIdleCallbacks
,
2549 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2551 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2552 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2553 foreach ( $callbacks as $callback ) {
2555 list( $phpCallback ) = $callback;
2556 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2557 call_user_func_array( $phpCallback, [ $trigger ] );
2559 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2561 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2563 } catch ( Exception
$ex ) {
2564 call_user_func( $this->errorLogger
, $ex );
2566 // Some callbacks may use startAtomic/endAtomic, so make sure
2567 // their transactions are ended so other callbacks don't fail
2568 if ( $this->trxLevel() ) {
2569 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2573 } while ( count( $this->mTrxIdleCallbacks
) );
2575 if ( $e instanceof Exception
) {
2576 throw $e; // re-throw any first exception
2581 * Actually run and consume any "on transaction pre-commit" callbacks.
2583 * This method should not be used outside of Database/LoadBalancer
2588 public function runOnTransactionPreCommitCallbacks() {
2589 $e = null; // first exception
2590 do { // callbacks may add callbacks :)
2591 $callbacks = $this->mTrxPreCommitCallbacks
;
2592 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2593 foreach ( $callbacks as $callback ) {
2595 list( $phpCallback ) = $callback;
2596 call_user_func( $phpCallback );
2597 } catch ( Exception
$ex ) {
2598 call_user_func( $this->errorLogger
, $ex );
2602 } while ( count( $this->mTrxPreCommitCallbacks
) );
2604 if ( $e instanceof Exception
) {
2605 throw $e; // re-throw any first exception
2610 * Actually run any "transaction listener" callbacks.
2612 * This method should not be used outside of Database/LoadBalancer
2614 * @param integer $trigger IDatabase::TRIGGER_* constant
2618 public function runTransactionListenerCallbacks( $trigger ) {
2619 if ( $this->mTrxEndCallbacksSuppressed
) {
2623 /** @var Exception $e */
2624 $e = null; // first exception
2626 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2628 $phpCallback( $trigger, $this );
2629 } catch ( Exception
$ex ) {
2630 call_user_func( $this->errorLogger
, $ex );
2635 if ( $e instanceof Exception
) {
2636 throw $e; // re-throw any first exception
2640 final public function startAtomic( $fname = __METHOD__
) {
2641 if ( !$this->mTrxLevel
) {
2642 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2643 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2644 // in all changes being in one transaction to keep requests transactional.
2645 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2646 $this->mTrxAutomaticAtomic
= true;
2650 $this->mTrxAtomicLevels
[] = $fname;
2653 final public function endAtomic( $fname = __METHOD__
) {
2654 if ( !$this->mTrxLevel
) {
2655 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2657 if ( !$this->mTrxAtomicLevels ||
2658 array_pop( $this->mTrxAtomicLevels
) !== $fname
2660 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2663 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2664 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2668 final public function doAtomicSection( $fname, callable
$callback ) {
2669 $this->startAtomic( $fname );
2671 $res = call_user_func_array( $callback, [ $this, $fname ] );
2672 } catch ( Exception
$e ) {
2673 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2676 $this->endAtomic( $fname );
2681 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2682 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2683 if ( $this->mTrxLevel
) {
2684 if ( $this->mTrxAtomicLevels
) {
2685 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2686 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2687 throw new DBUnexpectedError( $this, $msg );
2688 } elseif ( !$this->mTrxAutomatic
) {
2689 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2690 throw new DBUnexpectedError( $this, $msg );
2692 // @TODO: make this an exception at some point
2693 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2694 $this->queryLogger
->error( $msg );
2695 return; // join the main transaction set
2697 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2698 // @TODO: make this an exception at some point
2699 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2700 $this->queryLogger
->error( $msg );
2701 return; // let any writes be in the main transaction
2704 // Avoid fatals if close() was called
2705 $this->assertOpen();
2707 $this->doBegin( $fname );
2708 $this->mTrxTimestamp
= microtime( true );
2709 $this->mTrxFname
= $fname;
2710 $this->mTrxDoneWrites
= false;
2711 $this->mTrxAutomaticAtomic
= false;
2712 $this->mTrxAtomicLevels
= [];
2713 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2714 $this->mTrxWriteDuration
= 0.0;
2715 $this->mTrxWriteQueryCount
= 0;
2716 $this->mTrxWriteAdjDuration
= 0.0;
2717 $this->mTrxWriteAdjQueryCount
= 0;
2718 $this->mTrxWriteCallers
= [];
2719 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2720 // Get an estimate of the replica DB lag before then, treating estimate staleness
2721 // as lag itself just to be safe
2722 $status = $this->getApproximateLagStatus();
2723 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2724 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2725 // caller will think its OK to muck around with the transaction just because startAtomic()
2726 // has not yet completed (e.g. setting mTrxAtomicLevels).
2727 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2731 * Issues the BEGIN command to the database server.
2733 * @see Database::begin()
2734 * @param string $fname
2736 protected function doBegin( $fname ) {
2737 $this->query( 'BEGIN', $fname );
2738 $this->mTrxLevel
= 1;
2741 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2742 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2743 // There are still atomic sections open. This cannot be ignored
2744 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2745 throw new DBUnexpectedError(
2747 "$fname: Got COMMIT while atomic sections $levels are still open."
2751 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2752 if ( !$this->mTrxLevel
) {
2753 return; // nothing to do
2754 } elseif ( !$this->mTrxAutomatic
) {
2755 throw new DBUnexpectedError(
2757 "$fname: Flushing an explicit transaction, getting out of sync."
2761 if ( !$this->mTrxLevel
) {
2762 $this->queryLogger
->error(
2763 "$fname: No transaction to commit, something got out of sync." );
2764 return; // nothing to do
2765 } elseif ( $this->mTrxAutomatic
) {
2766 // @TODO: make this an exception at some point
2767 $msg = "$fname: Explicit commit of implicit transaction.";
2768 $this->queryLogger
->error( $msg );
2769 return; // wait for the main transaction set commit round
2773 // Avoid fatals if close() was called
2774 $this->assertOpen();
2776 $this->runOnTransactionPreCommitCallbacks();
2777 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2778 $this->doCommit( $fname );
2779 if ( $this->mTrxDoneWrites
) {
2780 $this->mLastWriteTime
= microtime( true );
2781 $this->trxProfiler
->transactionWritingOut(
2782 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2785 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2786 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2790 * Issues the COMMIT command to the database server.
2792 * @see Database::commit()
2793 * @param string $fname
2795 protected function doCommit( $fname ) {
2796 if ( $this->mTrxLevel
) {
2797 $this->query( 'COMMIT', $fname );
2798 $this->mTrxLevel
= 0;
2802 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2803 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2804 if ( !$this->mTrxLevel
) {
2805 return; // nothing to do
2808 if ( !$this->mTrxLevel
) {
2809 $this->queryLogger
->error(
2810 "$fname: No transaction to rollback, something got out of sync." );
2811 return; // nothing to do
2812 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2813 throw new DBUnexpectedError(
2815 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2820 // Avoid fatals if close() was called
2821 $this->assertOpen();
2823 $this->doRollback( $fname );
2824 $this->mTrxAtomicLevels
= [];
2825 if ( $this->mTrxDoneWrites
) {
2826 $this->trxProfiler
->transactionWritingOut(
2827 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2830 $this->mTrxIdleCallbacks
= []; // clear
2831 $this->mTrxPreCommitCallbacks
= []; // clear
2832 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2833 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2837 * Issues the ROLLBACK command to the database server.
2839 * @see Database::rollback()
2840 * @param string $fname
2842 protected function doRollback( $fname ) {
2843 if ( $this->mTrxLevel
) {
2844 # Disconnects cause rollback anyway, so ignore those errors
2845 $ignoreErrors = true;
2846 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2847 $this->mTrxLevel
= 0;
2851 public function flushSnapshot( $fname = __METHOD__
) {
2852 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2853 // This only flushes transactions to clear snapshots, not to write data
2854 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2855 throw new DBUnexpectedError(
2857 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2861 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2864 public function explicitTrxActive() {
2865 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2868 public function duplicateTableStructure(
2869 $oldName, $newName, $temporary = false, $fname = __METHOD__
2871 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2874 public function listTables( $prefix = null, $fname = __METHOD__
) {
2875 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2878 public function listViews( $prefix = null, $fname = __METHOD__
) {
2879 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2882 public function timestamp( $ts = 0 ) {
2883 $t = new ConvertibleTimestamp( $ts );
2884 // Let errors bubble up to avoid putting garbage in the DB
2885 return $t->getTimestamp( TS_MW
);
2888 public function timestampOrNull( $ts = null ) {
2889 if ( is_null( $ts ) ) {
2892 return $this->timestamp( $ts );
2897 * Take the result from a query, and wrap it in a ResultWrapper if
2898 * necessary. Boolean values are passed through as is, to indicate success
2899 * of write queries or failure.
2901 * Once upon a time, Database::query() returned a bare MySQL result
2902 * resource, and it was necessary to call this function to convert it to
2903 * a wrapper. Nowadays, raw database objects are never exposed to external
2904 * callers, so this is unnecessary in external code.
2906 * @param bool|ResultWrapper|resource|object $result
2907 * @return bool|ResultWrapper
2909 protected function resultObject( $result ) {
2912 } elseif ( $result instanceof ResultWrapper
) {
2914 } elseif ( $result === true ) {
2915 // Successful write query
2918 return new ResultWrapper( $this, $result );
2922 public function ping( &$rtt = null ) {
2923 // Avoid hitting the server if it was hit recently
2924 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2925 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2926 $rtt = $this->mRTTEstimate
;
2927 return true; // don't care about $rtt
2931 // This will reconnect if possible or return false if not
2932 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
2933 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2934 $this->restoreFlags( self
::RESTORE_PRIOR
);
2937 $rtt = $this->mRTTEstimate
;
2946 protected function reconnect() {
2947 $this->closeConnection();
2948 $this->mOpened
= false;
2949 $this->mConn
= false;
2951 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2952 $this->lastPing
= microtime( true );
2954 } catch ( DBConnectionError
$e ) {
2961 public function getSessionLagStatus() {
2962 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2966 * Get the replica DB lag when the current transaction started
2968 * This is useful when transactions might use snapshot isolation
2969 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2970 * is this lag plus transaction duration. If they don't, it is still
2971 * safe to be pessimistic. This returns null if there is no transaction.
2973 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2976 protected function getTransactionLagStatus() {
2977 return $this->mTrxLevel
2978 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
2983 * Get a replica DB lag estimate for this server
2985 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2988 protected function getApproximateLagStatus() {
2990 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
2991 'since' => microtime( true )
2996 * Merge the result of getSessionLagStatus() for several DBs
2997 * using the most pessimistic values to estimate the lag of
2998 * any data derived from them in combination
3000 * This is information is useful for caching modules
3002 * @see WANObjectCache::set()
3003 * @see WANObjectCache::getWithSetCallback()
3005 * @param IDatabase $db1
3006 * @param IDatabase ...
3007 * @return array Map of values:
3008 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3009 * - since: oldest UNIX timestamp of any of the DB lag estimates
3010 * - pending: whether any of the DBs have uncommitted changes
3013 public static function getCacheSetOptions( IDatabase
$db1 ) {
3014 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3015 foreach ( func_get_args() as $db ) {
3016 /** @var IDatabase $db */
3017 $status = $db->getSessionLagStatus();
3018 if ( $status['lag'] === false ) {
3019 $res['lag'] = false;
3020 } elseif ( $res['lag'] !== false ) {
3021 $res['lag'] = max( $res['lag'], $status['lag'] );
3023 $res['since'] = min( $res['since'], $status['since'] );
3024 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3030 public function getLag() {
3034 public function maxListLen() {
3038 public function encodeBlob( $b ) {
3042 public function decodeBlob( $b ) {
3043 if ( $b instanceof Blob
) {
3049 public function setSessionOptions( array $options ) {
3052 public function sourceFile(
3054 callable
$lineCallback = null,
3055 callable
$resultCallback = null,
3057 callable
$inputCallback = null
3059 MediaWiki\
suppressWarnings();
3060 $fp = fopen( $filename, 'r' );
3061 MediaWiki\restoreWarnings
();
3063 if ( false === $fp ) {
3064 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3068 $fname = __METHOD__
. "( $filename )";
3072 $error = $this->sourceStream(
3073 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3074 } catch ( Exception
$e ) {
3084 public function setSchemaVars( $vars ) {
3085 $this->mSchemaVars
= $vars;
3088 public function sourceStream(
3090 callable
$lineCallback = null,
3091 callable
$resultCallback = null,
3092 $fname = __METHOD__
,
3093 callable
$inputCallback = null
3097 while ( !feof( $fp ) ) {
3098 if ( $lineCallback ) {
3099 call_user_func( $lineCallback );
3102 $line = trim( fgets( $fp ) );
3104 if ( $line == '' ) {
3108 if ( '-' == $line[0] && '-' == $line[1] ) {
3116 $done = $this->streamStatementEnd( $cmd, $line );
3120 if ( $done ||
feof( $fp ) ) {
3121 $cmd = $this->replaceVars( $cmd );
3123 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3124 $res = $this->query( $cmd, $fname );
3126 if ( $resultCallback ) {
3127 call_user_func( $resultCallback, $res, $this );
3130 if ( false === $res ) {
3131 $err = $this->lastError();
3133 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3144 * Called by sourceStream() to check if we've reached a statement end
3146 * @param string &$sql SQL assembled so far
3147 * @param string &$newLine New line about to be added to $sql
3148 * @return bool Whether $newLine contains end of the statement
3150 public function streamStatementEnd( &$sql, &$newLine ) {
3151 if ( $this->delimiter
) {
3153 $newLine = preg_replace(
3154 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3155 if ( $newLine != $prev ) {
3164 * Database independent variable replacement. Replaces a set of variables
3165 * in an SQL statement with their contents as given by $this->getSchemaVars().
3167 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3169 * - '{$var}' should be used for text and is passed through the database's
3171 * - `{$var}` should be used for identifiers (e.g. table and database names).
3172 * It is passed through the database's addIdentifierQuotes method which
3173 * can be overridden if the database uses something other than backticks.
3174 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3175 * database's tableName method.
3176 * - / *i* / passes the name that follows through the database's indexName method.
3177 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3178 * its use should be avoided. In 1.24 and older, string encoding was applied.
3180 * @param string $ins SQL statement to replace variables in
3181 * @return string The new SQL statement with variables replaced
3183 protected function replaceVars( $ins ) {
3184 $vars = $this->getSchemaVars();
3185 return preg_replace_callback(
3187 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3188 \'\{\$ (\w+) }\' | # 3. addQuotes
3189 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3190 /\*\$ (\w+) \*/ # 5. leave unencoded
3192 function ( $m ) use ( $vars ) {
3193 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3194 // check for both nonexistent keys *and* the empty string.
3195 if ( isset( $m[1] ) && $m[1] !== '' ) {
3196 if ( $m[1] === 'i' ) {
3197 return $this->indexName( $m[2] );
3199 return $this->tableName( $m[2] );
3201 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3202 return $this->addQuotes( $vars[$m[3]] );
3203 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3204 return $this->addIdentifierQuotes( $vars[$m[4]] );
3205 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3206 return $vars[$m[5]];
3216 * Get schema variables. If none have been set via setSchemaVars(), then
3217 * use some defaults from the current object.
3221 protected function getSchemaVars() {
3222 if ( $this->mSchemaVars
) {
3223 return $this->mSchemaVars
;
3225 return $this->getDefaultSchemaVars();
3230 * Get schema variables to use if none have been set via setSchemaVars().
3232 * Override this in derived classes to provide variables for tables.sql
3233 * and SQL patch files.
3237 protected function getDefaultSchemaVars() {
3241 public function lockIsFree( $lockName, $method ) {
3245 public function lock( $lockName, $method, $timeout = 5 ) {
3246 $this->mNamedLocksHeld
[$lockName] = 1;
3251 public function unlock( $lockName, $method ) {
3252 unset( $this->mNamedLocksHeld
[$lockName] );
3257 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3258 if ( $this->writesOrCallbacksPending() ) {
3259 // This only flushes transactions to clear snapshots, not to write data
3260 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3261 throw new DBUnexpectedError(
3263 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3267 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3271 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3272 if ( $this->trxLevel() ) {
3273 // There is a good chance an exception was thrown, causing any early return
3274 // from the caller. Let any error handler get a chance to issue rollback().
3275 // If there isn't one, let the error bubble up and trigger server-side rollback.
3276 $this->onTransactionResolution(
3277 function () use ( $lockKey, $fname ) {
3278 $this->unlock( $lockKey, $fname );
3283 $this->unlock( $lockKey, $fname );
3287 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3292 public function namedLocksEnqueue() {
3297 * Lock specific tables
3299 * @param array $read Array of tables to lock for read access
3300 * @param array $write Array of tables to lock for write access
3301 * @param string $method Name of caller
3302 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3305 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3310 * Unlock specific tables
3312 * @param string $method The caller
3315 public function unlockTables( $method ) {
3321 * @param string $tableName
3322 * @param string $fName
3323 * @return bool|ResultWrapper
3326 public function dropTable( $tableName, $fName = __METHOD__
) {
3327 if ( !$this->tableExists( $tableName, $fName ) ) {
3330 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3332 return $this->query( $sql, $fName );
3335 public function getInfinity() {
3339 public function encodeExpiry( $expiry ) {
3340 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3341 ?
$this->getInfinity()
3342 : $this->timestamp( $expiry );
3345 public function decodeExpiry( $expiry, $format = TS_MW
) {
3346 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3350 return ConvertibleTimestamp
::convert( $format, $expiry );
3353 public function setBigSelects( $value = true ) {
3357 public function isReadOnly() {
3358 return ( $this->getReadOnlyReason() !== false );
3362 * @return string|bool Reason this DB is read-only or false if it is not
3364 protected function getReadOnlyReason() {
3365 $reason = $this->getLBInfo( 'readOnlyReason' );
3367 return is_string( $reason ) ?
$reason : false;
3370 public function setTableAliases( array $aliases ) {
3371 $this->tableAliases
= $aliases;
3375 * @return bool Whether a DB user is required to access the DB
3378 protected function requiresDatabaseUser() {
3383 * Get the underlying binding handle, mConn
3385 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3386 * This catches broken callers than catch and ignore disconnection exceptions.
3387 * Unlike checking isOpen(), this is safe to call inside of open().
3389 * @return resource|object
3390 * @throws DBUnexpectedError
3393 protected function getBindingHandle() {
3394 if ( !$this->mConn
) {
3395 throw new DBUnexpectedError(
3397 'DB connection was already closed or the connection dropped.'
3401 return $this->mConn
;
3408 public function __toString() {
3409 return (string)$this->mConn
;
3413 * Make sure that copies do not share the same client binding handle
3414 * @throws DBConnectionError
3416 public function __clone() {
3417 $this->connLogger
->warning(
3418 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3419 ( new RuntimeException() )->getTraceAsString()
3422 if ( $this->isOpen() ) {
3423 // Open a new connection resource without messing with the old one
3424 $this->mOpened
= false;
3425 $this->mConn
= false;
3426 $this->mTrxEndCallbacks
= []; // don't copy
3427 $this->handleSessionLoss(); // no trx or locks anymore
3428 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3429 $this->lastPing
= microtime( true );
3434 * Called by serialize. Throw an exception when DB connection is serialized.
3435 * This causes problems on some database engines because the connection is
3436 * not restored on unserialize.
3438 public function __sleep() {
3439 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3440 'the connection is not restored on wakeup.' );
3444 * Run a few simple sanity checks and close dangling connections
3446 public function __destruct() {
3447 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3448 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3451 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3452 if ( $danglingWriters ) {
3453 $fnames = implode( ', ', $danglingWriters );
3454 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3457 if ( $this->mConn
) {
3458 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3459 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3460 \MediaWiki\
suppressWarnings();
3461 $this->closeConnection();
3462 \MediaWiki\restoreWarnings
();
3463 $this->mConn
= false;
3464 $this->mOpened
= false;
3469 class_alias( Database
::class, 'DatabaseBase' );