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 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1360 $row = $this->fetchRow( $res );
1361 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1368 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1369 * It's only slightly flawed. Don't use for anything important.
1371 * @param string $sql A SQL Query
1375 protected static function generalizeSQL( $sql ) {
1376 # This does the same as the regexp below would do, but in such a way
1377 # as to avoid crashing php on some large strings.
1378 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1380 $sql = str_replace( "\\\\", '', $sql );
1381 $sql = str_replace( "\\'", '', $sql );
1382 $sql = str_replace( "\\\"", '', $sql );
1383 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1384 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1386 # All newlines, tabs, etc replaced by single space
1387 $sql = preg_replace( '/\s+/', ' ', $sql );
1390 # except the ones surrounded by characters, e.g. l10n
1391 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1392 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1397 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1398 $info = $this->fieldInfo( $table, $field );
1403 public function indexExists( $table, $index, $fname = __METHOD__
) {
1404 if ( !$this->tableExists( $table ) ) {
1408 $info = $this->indexInfo( $table, $index, $fname );
1409 if ( is_null( $info ) ) {
1412 return $info !== false;
1416 public function tableExists( $table, $fname = __METHOD__
) {
1417 $tableRaw = $this->tableName( $table, 'raw' );
1418 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1419 return true; // already known to exist
1422 $table = $this->tableName( $table );
1423 $ignoreErrors = true;
1424 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1429 public function indexUnique( $table, $index ) {
1430 $indexInfo = $this->indexInfo( $table, $index );
1432 if ( !$indexInfo ) {
1436 return !$indexInfo[0]->Non_unique
;
1440 * Helper for Database::insert().
1442 * @param array $options
1445 protected function makeInsertOptions( $options ) {
1446 return implode( ' ', $options );
1449 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1450 # No rows to insert, easy just return now
1451 if ( !count( $a ) ) {
1455 $table = $this->tableName( $table );
1457 if ( !is_array( $options ) ) {
1458 $options = [ $options ];
1462 if ( isset( $options['fileHandle'] ) ) {
1463 $fh = $options['fileHandle'];
1465 $options = $this->makeInsertOptions( $options );
1467 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1469 $keys = array_keys( $a[0] );
1472 $keys = array_keys( $a );
1475 $sql = 'INSERT ' . $options .
1476 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1480 foreach ( $a as $row ) {
1486 $sql .= '(' . $this->makeList( $row ) . ')';
1489 $sql .= '(' . $this->makeList( $a ) . ')';
1492 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1494 } elseif ( $fh !== null ) {
1498 return (bool)$this->query( $sql, $fname );
1502 * Make UPDATE options array for Database::makeUpdateOptions
1504 * @param array $options
1507 protected function makeUpdateOptionsArray( $options ) {
1508 if ( !is_array( $options ) ) {
1509 $options = [ $options ];
1514 if ( in_array( 'IGNORE', $options ) ) {
1522 * Make UPDATE options for the Database::update function
1524 * @param array $options The options passed to Database::update
1527 protected function makeUpdateOptions( $options ) {
1528 $opts = $this->makeUpdateOptionsArray( $options );
1530 return implode( ' ', $opts );
1533 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1534 $table = $this->tableName( $table );
1535 $opts = $this->makeUpdateOptions( $options );
1536 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1538 if ( $conds !== [] && $conds !== '*' ) {
1539 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1542 return $this->query( $sql, $fname );
1545 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1546 if ( !is_array( $a ) ) {
1547 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1553 foreach ( $a as $field => $value ) {
1555 if ( $mode == self
::LIST_AND
) {
1557 } elseif ( $mode == self
::LIST_OR
) {
1566 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1567 $list .= "($value)";
1568 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1571 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1573 // Remove null from array to be handled separately if found
1574 $includeNull = false;
1575 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1576 $includeNull = true;
1577 unset( $value[$nullKey] );
1579 if ( count( $value ) == 0 && !$includeNull ) {
1580 throw new InvalidArgumentException(
1581 __METHOD__
. ": empty input for field $field" );
1582 } elseif ( count( $value ) == 0 ) {
1583 // only check if $field is null
1584 $list .= "$field IS NULL";
1586 // IN clause contains at least one valid element
1587 if ( $includeNull ) {
1588 // Group subconditions to ensure correct precedence
1591 if ( count( $value ) == 1 ) {
1592 // Special-case single values, as IN isn't terribly efficient
1593 // Don't necessarily assume the single key is 0; we don't
1594 // enforce linear numeric ordering on other arrays here.
1595 $value = array_values( $value )[0];
1596 $list .= $field . " = " . $this->addQuotes( $value );
1598 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1600 // if null present in array, append IS NULL
1601 if ( $includeNull ) {
1602 $list .= " OR $field IS NULL)";
1605 } elseif ( $value === null ) {
1606 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1607 $list .= "$field IS ";
1608 } elseif ( $mode == self
::LIST_SET
) {
1609 $list .= "$field = ";
1614 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1616 $list .= "$field = ";
1618 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1625 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1628 foreach ( $data as $base => $sub ) {
1629 if ( count( $sub ) ) {
1630 $conds[] = $this->makeList(
1631 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1637 return $this->makeList( $conds, self
::LIST_OR
);
1639 // Nothing to search for...
1644 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1648 public function bitNot( $field ) {
1652 public function bitAnd( $fieldLeft, $fieldRight ) {
1653 return "($fieldLeft & $fieldRight)";
1656 public function bitOr( $fieldLeft, $fieldRight ) {
1657 return "($fieldLeft | $fieldRight)";
1660 public function buildConcat( $stringList ) {
1661 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1664 public function buildGroupConcatField(
1665 $delim, $table, $field, $conds = '', $join_conds = []
1667 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1669 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1672 public function buildStringCast( $field ) {
1676 public function selectDB( $db ) {
1677 # Stub. Shouldn't cause serious problems if it's not overridden, but
1678 # if your database engine supports a concept similar to MySQL's
1679 # databases you may as well.
1680 $this->mDBname
= $db;
1685 public function getDBname() {
1686 return $this->mDBname
;
1689 public function getServer() {
1690 return $this->mServer
;
1693 public function tableName( $name, $format = 'quoted' ) {
1694 # Skip the entire process when we have a string quoted on both ends.
1695 # Note that we check the end so that we will still quote any use of
1696 # use of `database`.table. But won't break things if someone wants
1697 # to query a database table with a dot in the name.
1698 if ( $this->isQuotedIdentifier( $name ) ) {
1702 # Lets test for any bits of text that should never show up in a table
1703 # name. Basically anything like JOIN or ON which are actually part of
1704 # SQL queries, but may end up inside of the table value to combine
1705 # sql. Such as how the API is doing.
1706 # Note that we use a whitespace test rather than a \b test to avoid
1707 # any remote case where a word like on may be inside of a table name
1708 # surrounded by symbols which may be considered word breaks.
1709 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1713 # Split database and table into proper variables.
1714 # We reverse the explode so that database.table and table both output
1715 # the correct table.
1716 $dbDetails = explode( '.', $name, 3 );
1717 if ( count( $dbDetails ) == 3 ) {
1718 list( $database, $schema, $table ) = $dbDetails;
1719 # We don't want any prefix added in this case
1721 } elseif ( count( $dbDetails ) == 2 ) {
1722 list( $database, $table ) = $dbDetails;
1723 # We don't want any prefix added in this case
1725 # In dbs that support it, $database may actually be the schema
1726 # but that doesn't affect any of the functionality here
1729 list( $table ) = $dbDetails;
1730 if ( isset( $this->tableAliases
[$table] ) ) {
1731 $database = $this->tableAliases
[$table]['dbname'];
1732 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1733 ?
$this->tableAliases
[$table]['schema']
1735 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1736 ?
$this->tableAliases
[$table]['prefix']
1737 : $this->mTablePrefix
;
1740 $schema = $this->mSchema
; # Default schema
1741 $prefix = $this->mTablePrefix
; # Default prefix
1745 # Quote $table and apply the prefix if not quoted.
1746 # $tableName might be empty if this is called from Database::replaceVars()
1747 $tableName = "{$prefix}{$table}";
1748 if ( $format === 'quoted'
1749 && !$this->isQuotedIdentifier( $tableName )
1750 && $tableName !== ''
1752 $tableName = $this->addIdentifierQuotes( $tableName );
1755 # Quote $schema and $database and merge them with the table name if needed
1756 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1757 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1763 * @param string|null $namespace Database or schema
1764 * @param string $relation Name of table, view, sequence, etc...
1765 * @param string $format One of (raw, quoted)
1766 * @return string Relation name with quoted and merged $namespace as needed
1768 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1769 if ( strlen( $namespace ) ) {
1770 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1771 $namespace = $this->addIdentifierQuotes( $namespace );
1773 $relation = $namespace . '.' . $relation;
1779 public function tableNames() {
1780 $inArray = func_get_args();
1783 foreach ( $inArray as $name ) {
1784 $retVal[$name] = $this->tableName( $name );
1790 public function tableNamesN() {
1791 $inArray = func_get_args();
1794 foreach ( $inArray as $name ) {
1795 $retVal[] = $this->tableName( $name );
1802 * Get an aliased table name
1803 * e.g. tableName AS newTableName
1805 * @param string $name Table name, see tableName()
1806 * @param string|bool $alias Alias (optional)
1807 * @return string SQL name for aliased table. Will not alias a table to its own name
1809 protected function tableNameWithAlias( $name, $alias = false ) {
1810 if ( !$alias ||
$alias == $name ) {
1811 return $this->tableName( $name );
1813 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1818 * Gets an array of aliased table names
1820 * @param array $tables [ [alias] => table ]
1821 * @return string[] See tableNameWithAlias()
1823 protected function tableNamesWithAlias( $tables ) {
1825 foreach ( $tables as $alias => $table ) {
1826 if ( is_numeric( $alias ) ) {
1829 $retval[] = $this->tableNameWithAlias( $table, $alias );
1836 * Get an aliased field name
1837 * e.g. fieldName AS newFieldName
1839 * @param string $name Field name
1840 * @param string|bool $alias Alias (optional)
1841 * @return string SQL name for aliased field. Will not alias a field to its own name
1843 protected function fieldNameWithAlias( $name, $alias = false ) {
1844 if ( !$alias ||
(string)$alias === (string)$name ) {
1847 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1852 * Gets an array of aliased field names
1854 * @param array $fields [ [alias] => field ]
1855 * @return string[] See fieldNameWithAlias()
1857 protected function fieldNamesWithAlias( $fields ) {
1859 foreach ( $fields as $alias => $field ) {
1860 if ( is_numeric( $alias ) ) {
1863 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1870 * Get the aliased table name clause for a FROM clause
1871 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1873 * @param array $tables ( [alias] => table )
1874 * @param array $use_index Same as for select()
1875 * @param array $ignore_index Same as for select()
1876 * @param array $join_conds Same as for select()
1879 protected function tableNamesWithIndexClauseOrJOIN(
1880 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1884 $use_index = (array)$use_index;
1885 $ignore_index = (array)$ignore_index;
1886 $join_conds = (array)$join_conds;
1888 foreach ( $tables as $alias => $table ) {
1889 if ( !is_string( $alias ) ) {
1890 // No alias? Set it equal to the table name
1893 // Is there a JOIN clause for this table?
1894 if ( isset( $join_conds[$alias] ) ) {
1895 list( $joinType, $conds ) = $join_conds[$alias];
1896 $tableClause = $joinType;
1897 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1898 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1899 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1901 $tableClause .= ' ' . $use;
1904 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1905 $ignore = $this->ignoreIndexClause(
1906 implode( ',', (array)$ignore_index[$alias] ) );
1907 if ( $ignore != '' ) {
1908 $tableClause .= ' ' . $ignore;
1911 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1913 $tableClause .= ' ON (' . $on . ')';
1916 $retJOIN[] = $tableClause;
1917 } elseif ( isset( $use_index[$alias] ) ) {
1918 // Is there an INDEX clause for this table?
1919 $tableClause = $this->tableNameWithAlias( $table, $alias );
1920 $tableClause .= ' ' . $this->useIndexClause(
1921 implode( ',', (array)$use_index[$alias] )
1924 $ret[] = $tableClause;
1925 } elseif ( isset( $ignore_index[$alias] ) ) {
1926 // Is there an INDEX clause for this table?
1927 $tableClause = $this->tableNameWithAlias( $table, $alias );
1928 $tableClause .= ' ' . $this->ignoreIndexClause(
1929 implode( ',', (array)$ignore_index[$alias] )
1932 $ret[] = $tableClause;
1934 $tableClause = $this->tableNameWithAlias( $table, $alias );
1936 $ret[] = $tableClause;
1940 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1941 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1942 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1944 // Compile our final table clause
1945 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1949 * Get the name of an index in a given table.
1951 * @param string $index
1954 protected function indexName( $index ) {
1958 public function addQuotes( $s ) {
1959 if ( $s instanceof Blob
) {
1962 if ( $s === null ) {
1964 } elseif ( is_bool( $s ) ) {
1967 # This will also quote numeric values. This should be harmless,
1968 # and protects against weird problems that occur when they really
1969 # _are_ strings such as article titles and string->number->string
1970 # conversion is not 1:1.
1971 return "'" . $this->strencode( $s ) . "'";
1976 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1977 * MySQL uses `backticks` while basically everything else uses double quotes.
1978 * Since MySQL is the odd one out here the double quotes are our generic
1979 * and we implement backticks in DatabaseMysql.
1984 public function addIdentifierQuotes( $s ) {
1985 return '"' . str_replace( '"', '""', $s ) . '"';
1989 * Returns if the given identifier looks quoted or not according to
1990 * the database convention for quoting identifiers .
1992 * @note Do not use this to determine if untrusted input is safe.
1993 * A malicious user can trick this function.
1994 * @param string $name
1997 public function isQuotedIdentifier( $name ) {
1998 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2005 protected function escapeLikeInternal( $s ) {
2006 return addcslashes( $s, '\%_' );
2009 public function buildLike() {
2010 $params = func_get_args();
2012 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2013 $params = $params[0];
2018 foreach ( $params as $value ) {
2019 if ( $value instanceof LikeMatch
) {
2020 $s .= $value->toString();
2022 $s .= $this->escapeLikeInternal( $value );
2026 return " LIKE {$this->addQuotes( $s )} ";
2029 public function anyChar() {
2030 return new LikeMatch( '_' );
2033 public function anyString() {
2034 return new LikeMatch( '%' );
2037 public function nextSequenceValue( $seqName ) {
2042 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2043 * is only needed because a) MySQL must be as efficient as possible due to
2044 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2045 * which index to pick. Anyway, other databases might have different
2046 * indexes on a given table. So don't bother overriding this unless you're
2048 * @param string $index
2051 public function useIndexClause( $index ) {
2056 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2057 * is only needed because a) MySQL must be as efficient as possible due to
2058 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2059 * which index to pick. Anyway, other databases might have different
2060 * indexes on a given table. So don't bother overriding this unless you're
2062 * @param string $index
2065 public function ignoreIndexClause( $index ) {
2069 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2070 $quotedTable = $this->tableName( $table );
2072 if ( count( $rows ) == 0 ) {
2077 if ( !is_array( reset( $rows ) ) ) {
2081 // @FXIME: this is not atomic, but a trx would break affectedRows()
2082 foreach ( $rows as $row ) {
2083 # Delete rows which collide
2084 if ( $uniqueIndexes ) {
2085 $sql = "DELETE FROM $quotedTable WHERE ";
2087 foreach ( $uniqueIndexes as $index ) {
2094 if ( is_array( $index ) ) {
2096 foreach ( $index as $col ) {
2102 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2105 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2109 $this->query( $sql, $fname );
2112 # Now insert the row
2113 $this->insert( $table, $row, $fname );
2118 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2121 * @param string $table Table name
2122 * @param array|string $rows Row(s) to insert
2123 * @param string $fname Caller function name
2125 * @return ResultWrapper
2127 protected function nativeReplace( $table, $rows, $fname ) {
2128 $table = $this->tableName( $table );
2131 if ( !is_array( reset( $rows ) ) ) {
2135 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2138 foreach ( $rows as $row ) {
2145 $sql .= '(' . $this->makeList( $row ) . ')';
2148 return $this->query( $sql, $fname );
2151 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2154 if ( !count( $rows ) ) {
2155 return true; // nothing to do
2158 if ( !is_array( reset( $rows ) ) ) {
2162 if ( count( $uniqueIndexes ) ) {
2163 $clauses = []; // list WHERE clauses that each identify a single row
2164 foreach ( $rows as $row ) {
2165 foreach ( $uniqueIndexes as $index ) {
2166 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2167 $rowKey = []; // unique key to this row
2168 foreach ( $index as $column ) {
2169 $rowKey[$column] = $row[$column];
2171 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2174 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2179 $useTrx = !$this->mTrxLevel
;
2181 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2184 # Update any existing conflicting row(s)
2185 if ( $where !== false ) {
2186 $ok = $this->update( $table, $set, $where, $fname );
2190 # Now insert any non-conflicting row(s)
2191 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2192 } catch ( Exception
$e ) {
2194 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2199 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2205 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2209 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2212 $delTable = $this->tableName( $delTable );
2213 $joinTable = $this->tableName( $joinTable );
2214 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2215 if ( $conds != '*' ) {
2216 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2220 $this->query( $sql, $fname );
2223 public function textFieldSize( $table, $field ) {
2224 $table = $this->tableName( $table );
2225 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2226 $res = $this->query( $sql, __METHOD__
);
2227 $row = $this->fetchObject( $res );
2231 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2240 public function delete( $table, $conds, $fname = __METHOD__
) {
2242 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2245 $table = $this->tableName( $table );
2246 $sql = "DELETE FROM $table";
2248 if ( $conds != '*' ) {
2249 if ( is_array( $conds ) ) {
2250 $conds = $this->makeList( $conds, self
::LIST_AND
);
2252 $sql .= ' WHERE ' . $conds;
2255 return $this->query( $sql, $fname );
2258 public function insertSelect(
2259 $destTable, $srcTable, $varMap, $conds,
2260 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2262 if ( $this->cliMode
) {
2263 // For massive migrations with downtime, we don't want to select everything
2264 // into memory and OOM, so do all this native on the server side if possible.
2265 return $this->nativeInsertSelect(
2276 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2277 // on only the master (without needing row-based-replication). It also makes it easy to
2278 // know how big the INSERT is going to be.
2280 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2281 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2283 $selectOptions[] = 'FOR UPDATE';
2284 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2290 foreach ( $res as $row ) {
2291 $rows[] = (array)$row;
2294 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2297 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2298 $fname = __METHOD__
,
2299 $insertOptions = [], $selectOptions = []
2301 $destTable = $this->tableName( $destTable );
2303 if ( !is_array( $insertOptions ) ) {
2304 $insertOptions = [ $insertOptions ];
2307 $insertOptions = $this->makeInsertOptions( $insertOptions );
2309 if ( !is_array( $selectOptions ) ) {
2310 $selectOptions = [ $selectOptions ];
2313 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2316 if ( is_array( $srcTable ) ) {
2317 $srcTable = implode( ',', array_map( [ $this, 'tableName' ], $srcTable ) );
2319 $srcTable = $this->tableName( $srcTable );
2322 $sql = "INSERT $insertOptions" .
2323 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2324 " SELECT $startOpts " . implode( ',', $varMap ) .
2325 " FROM $srcTable $useIndex $ignoreIndex ";
2327 if ( $conds != '*' ) {
2328 if ( is_array( $conds ) ) {
2329 $conds = $this->makeList( $conds, self
::LIST_AND
);
2331 $sql .= " WHERE $conds";
2334 $sql .= " $tailOpts";
2336 return $this->query( $sql, $fname );
2340 * Construct a LIMIT query with optional offset. This is used for query
2341 * pages. The SQL should be adjusted so that only the first $limit rows
2342 * are returned. If $offset is provided as well, then the first $offset
2343 * rows should be discarded, and the next $limit rows should be returned.
2344 * If the result of the query is not ordered, then the rows to be returned
2345 * are theoretically arbitrary.
2347 * $sql is expected to be a SELECT, if that makes a difference.
2349 * The version provided by default works in MySQL and SQLite. It will very
2350 * likely need to be overridden for most other DBMSes.
2352 * @param string $sql SQL query we will append the limit too
2353 * @param int $limit The SQL limit
2354 * @param int|bool $offset The SQL offset (default false)
2355 * @throws DBUnexpectedError
2358 public function limitResult( $sql, $limit, $offset = false ) {
2359 if ( !is_numeric( $limit ) ) {
2360 throw new DBUnexpectedError( $this,
2361 "Invalid non-numeric limit passed to limitResult()\n" );
2364 return "$sql LIMIT "
2365 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2369 public function unionSupportsOrderAndLimit() {
2370 return true; // True for almost every DB supported
2373 public function unionQueries( $sqls, $all ) {
2374 $glue = $all ?
') UNION ALL (' : ') UNION (';
2376 return '(' . implode( $glue, $sqls ) . ')';
2379 public function conditional( $cond, $trueVal, $falseVal ) {
2380 if ( is_array( $cond ) ) {
2381 $cond = $this->makeList( $cond, self
::LIST_AND
);
2384 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2387 public function strreplace( $orig, $old, $new ) {
2388 return "REPLACE({$orig}, {$old}, {$new})";
2391 public function getServerUptime() {
2395 public function wasDeadlock() {
2399 public function wasLockTimeout() {
2403 public function wasErrorReissuable() {
2407 public function wasReadOnlyError() {
2412 * Do not use this method outside of Database/DBError classes
2414 * @param integer|string $errno
2415 * @return bool Whether the given query error was a connection drop
2417 public function wasConnectionError( $errno ) {
2421 public function deadlockLoop() {
2422 $args = func_get_args();
2423 $function = array_shift( $args );
2424 $tries = self
::DEADLOCK_TRIES
;
2426 $this->begin( __METHOD__
);
2429 /** @var Exception $e */
2433 $retVal = call_user_func_array( $function, $args );
2435 } catch ( DBQueryError
$e ) {
2436 if ( $this->wasDeadlock() ) {
2437 // Retry after a randomized delay
2438 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2440 // Throw the error back up
2444 } while ( --$tries > 0 );
2446 if ( $tries <= 0 ) {
2447 // Too many deadlocks; give up
2448 $this->rollback( __METHOD__
);
2451 $this->commit( __METHOD__
);
2457 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2458 # Real waits are implemented in the subclass.
2462 public function getReplicaPos() {
2467 public function getMasterPos() {
2472 public function serverIsReadOnly() {
2476 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2477 if ( !$this->mTrxLevel
) {
2478 throw new DBUnexpectedError( $this, "No transaction is active." );
2480 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2483 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2484 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2485 if ( !$this->mTrxLevel
) {
2486 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2490 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2491 if ( $this->mTrxLevel
) {
2492 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2494 // If no transaction is active, then make one for this callback
2495 $this->startAtomic( __METHOD__
);
2497 call_user_func( $callback );
2498 $this->endAtomic( __METHOD__
);
2499 } catch ( Exception
$e ) {
2500 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2506 final public function setTransactionListener( $name, callable
$callback = null ) {
2508 $this->mTrxRecurringCallbacks
[$name] = $callback;
2510 unset( $this->mTrxRecurringCallbacks
[$name] );
2515 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2517 * This method should not be used outside of Database/LoadBalancer
2519 * @param bool $suppress
2522 final public function setTrxEndCallbackSuppression( $suppress ) {
2523 $this->mTrxEndCallbacksSuppressed
= $suppress;
2527 * Actually run and consume any "on transaction idle/resolution" callbacks.
2529 * This method should not be used outside of Database/LoadBalancer
2531 * @param integer $trigger IDatabase::TRIGGER_* constant
2535 public function runOnTransactionIdleCallbacks( $trigger ) {
2536 if ( $this->mTrxEndCallbacksSuppressed
) {
2540 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2541 /** @var Exception $e */
2542 $e = null; // first exception
2543 do { // callbacks may add callbacks :)
2544 $callbacks = array_merge(
2545 $this->mTrxIdleCallbacks
,
2546 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2548 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2549 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2550 foreach ( $callbacks as $callback ) {
2552 list( $phpCallback ) = $callback;
2553 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2554 call_user_func_array( $phpCallback, [ $trigger ] );
2556 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2558 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2560 } catch ( Exception
$ex ) {
2561 call_user_func( $this->errorLogger
, $ex );
2563 // Some callbacks may use startAtomic/endAtomic, so make sure
2564 // their transactions are ended so other callbacks don't fail
2565 if ( $this->trxLevel() ) {
2566 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2570 } while ( count( $this->mTrxIdleCallbacks
) );
2572 if ( $e instanceof Exception
) {
2573 throw $e; // re-throw any first exception
2578 * Actually run and consume any "on transaction pre-commit" callbacks.
2580 * This method should not be used outside of Database/LoadBalancer
2585 public function runOnTransactionPreCommitCallbacks() {
2586 $e = null; // first exception
2587 do { // callbacks may add callbacks :)
2588 $callbacks = $this->mTrxPreCommitCallbacks
;
2589 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2590 foreach ( $callbacks as $callback ) {
2592 list( $phpCallback ) = $callback;
2593 call_user_func( $phpCallback );
2594 } catch ( Exception
$ex ) {
2595 call_user_func( $this->errorLogger
, $ex );
2599 } while ( count( $this->mTrxPreCommitCallbacks
) );
2601 if ( $e instanceof Exception
) {
2602 throw $e; // re-throw any first exception
2607 * Actually run any "transaction listener" callbacks.
2609 * This method should not be used outside of Database/LoadBalancer
2611 * @param integer $trigger IDatabase::TRIGGER_* constant
2615 public function runTransactionListenerCallbacks( $trigger ) {
2616 if ( $this->mTrxEndCallbacksSuppressed
) {
2620 /** @var Exception $e */
2621 $e = null; // first exception
2623 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2625 $phpCallback( $trigger, $this );
2626 } catch ( Exception
$ex ) {
2627 call_user_func( $this->errorLogger
, $ex );
2632 if ( $e instanceof Exception
) {
2633 throw $e; // re-throw any first exception
2637 final public function startAtomic( $fname = __METHOD__
) {
2638 if ( !$this->mTrxLevel
) {
2639 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2640 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2641 // in all changes being in one transaction to keep requests transactional.
2642 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2643 $this->mTrxAutomaticAtomic
= true;
2647 $this->mTrxAtomicLevels
[] = $fname;
2650 final public function endAtomic( $fname = __METHOD__
) {
2651 if ( !$this->mTrxLevel
) {
2652 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2654 if ( !$this->mTrxAtomicLevels ||
2655 array_pop( $this->mTrxAtomicLevels
) !== $fname
2657 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2660 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2661 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2665 final public function doAtomicSection( $fname, callable
$callback ) {
2666 $this->startAtomic( $fname );
2668 $res = call_user_func_array( $callback, [ $this, $fname ] );
2669 } catch ( Exception
$e ) {
2670 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2673 $this->endAtomic( $fname );
2678 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2679 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2680 if ( $this->mTrxLevel
) {
2681 if ( $this->mTrxAtomicLevels
) {
2682 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2683 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2684 throw new DBUnexpectedError( $this, $msg );
2685 } elseif ( !$this->mTrxAutomatic
) {
2686 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2687 throw new DBUnexpectedError( $this, $msg );
2689 // @TODO: make this an exception at some point
2690 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2691 $this->queryLogger
->error( $msg );
2692 return; // join the main transaction set
2694 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2695 // @TODO: make this an exception at some point
2696 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2697 $this->queryLogger
->error( $msg );
2698 return; // let any writes be in the main transaction
2701 // Avoid fatals if close() was called
2702 $this->assertOpen();
2704 $this->doBegin( $fname );
2705 $this->mTrxTimestamp
= microtime( true );
2706 $this->mTrxFname
= $fname;
2707 $this->mTrxDoneWrites
= false;
2708 $this->mTrxAutomaticAtomic
= false;
2709 $this->mTrxAtomicLevels
= [];
2710 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2711 $this->mTrxWriteDuration
= 0.0;
2712 $this->mTrxWriteQueryCount
= 0;
2713 $this->mTrxWriteAdjDuration
= 0.0;
2714 $this->mTrxWriteAdjQueryCount
= 0;
2715 $this->mTrxWriteCallers
= [];
2716 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2717 // Get an estimate of the replica DB lag before then, treating estimate staleness
2718 // as lag itself just to be safe
2719 $status = $this->getApproximateLagStatus();
2720 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2721 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2722 // caller will think its OK to muck around with the transaction just because startAtomic()
2723 // has not yet completed (e.g. setting mTrxAtomicLevels).
2724 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2728 * Issues the BEGIN command to the database server.
2730 * @see Database::begin()
2731 * @param string $fname
2733 protected function doBegin( $fname ) {
2734 $this->query( 'BEGIN', $fname );
2735 $this->mTrxLevel
= 1;
2738 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2739 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2740 // There are still atomic sections open. This cannot be ignored
2741 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2742 throw new DBUnexpectedError(
2744 "$fname: Got COMMIT while atomic sections $levels are still open."
2748 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2749 if ( !$this->mTrxLevel
) {
2750 return; // nothing to do
2751 } elseif ( !$this->mTrxAutomatic
) {
2752 throw new DBUnexpectedError(
2754 "$fname: Flushing an explicit transaction, getting out of sync."
2758 if ( !$this->mTrxLevel
) {
2759 $this->queryLogger
->error(
2760 "$fname: No transaction to commit, something got out of sync." );
2761 return; // nothing to do
2762 } elseif ( $this->mTrxAutomatic
) {
2763 // @TODO: make this an exception at some point
2764 $msg = "$fname: Explicit commit of implicit transaction.";
2765 $this->queryLogger
->error( $msg );
2766 return; // wait for the main transaction set commit round
2770 // Avoid fatals if close() was called
2771 $this->assertOpen();
2773 $this->runOnTransactionPreCommitCallbacks();
2774 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2775 $this->doCommit( $fname );
2776 if ( $this->mTrxDoneWrites
) {
2777 $this->mLastWriteTime
= microtime( true );
2778 $this->trxProfiler
->transactionWritingOut(
2779 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2782 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2783 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2787 * Issues the COMMIT command to the database server.
2789 * @see Database::commit()
2790 * @param string $fname
2792 protected function doCommit( $fname ) {
2793 if ( $this->mTrxLevel
) {
2794 $this->query( 'COMMIT', $fname );
2795 $this->mTrxLevel
= 0;
2799 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2800 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2801 if ( !$this->mTrxLevel
) {
2802 return; // nothing to do
2805 if ( !$this->mTrxLevel
) {
2806 $this->queryLogger
->error(
2807 "$fname: No transaction to rollback, something got out of sync." );
2808 return; // nothing to do
2809 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2810 throw new DBUnexpectedError(
2812 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2817 // Avoid fatals if close() was called
2818 $this->assertOpen();
2820 $this->doRollback( $fname );
2821 $this->mTrxAtomicLevels
= [];
2822 if ( $this->mTrxDoneWrites
) {
2823 $this->trxProfiler
->transactionWritingOut(
2824 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2827 $this->mTrxIdleCallbacks
= []; // clear
2828 $this->mTrxPreCommitCallbacks
= []; // clear
2829 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2830 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2834 * Issues the ROLLBACK command to the database server.
2836 * @see Database::rollback()
2837 * @param string $fname
2839 protected function doRollback( $fname ) {
2840 if ( $this->mTrxLevel
) {
2841 # Disconnects cause rollback anyway, so ignore those errors
2842 $ignoreErrors = true;
2843 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2844 $this->mTrxLevel
= 0;
2848 public function flushSnapshot( $fname = __METHOD__
) {
2849 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2850 // This only flushes transactions to clear snapshots, not to write data
2851 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2852 throw new DBUnexpectedError(
2854 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
2858 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2861 public function explicitTrxActive() {
2862 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2865 public function duplicateTableStructure(
2866 $oldName, $newName, $temporary = false, $fname = __METHOD__
2868 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2871 public function listTables( $prefix = null, $fname = __METHOD__
) {
2872 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2875 public function listViews( $prefix = null, $fname = __METHOD__
) {
2876 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2879 public function timestamp( $ts = 0 ) {
2880 $t = new ConvertibleTimestamp( $ts );
2881 // Let errors bubble up to avoid putting garbage in the DB
2882 return $t->getTimestamp( TS_MW
);
2885 public function timestampOrNull( $ts = null ) {
2886 if ( is_null( $ts ) ) {
2889 return $this->timestamp( $ts );
2894 * Take the result from a query, and wrap it in a ResultWrapper if
2895 * necessary. Boolean values are passed through as is, to indicate success
2896 * of write queries or failure.
2898 * Once upon a time, Database::query() returned a bare MySQL result
2899 * resource, and it was necessary to call this function to convert it to
2900 * a wrapper. Nowadays, raw database objects are never exposed to external
2901 * callers, so this is unnecessary in external code.
2903 * @param bool|ResultWrapper|resource|object $result
2904 * @return bool|ResultWrapper
2906 protected function resultObject( $result ) {
2909 } elseif ( $result instanceof ResultWrapper
) {
2911 } elseif ( $result === true ) {
2912 // Successful write query
2915 return new ResultWrapper( $this, $result );
2919 public function ping( &$rtt = null ) {
2920 // Avoid hitting the server if it was hit recently
2921 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2922 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2923 $rtt = $this->mRTTEstimate
;
2924 return true; // don't care about $rtt
2928 // This will reconnect if possible or return false if not
2929 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
2930 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2931 $this->restoreFlags( self
::RESTORE_PRIOR
);
2934 $rtt = $this->mRTTEstimate
;
2943 protected function reconnect() {
2944 $this->closeConnection();
2945 $this->mOpened
= false;
2946 $this->mConn
= false;
2948 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2949 $this->lastPing
= microtime( true );
2951 } catch ( DBConnectionError
$e ) {
2958 public function getSessionLagStatus() {
2959 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2963 * Get the replica DB lag when the current transaction started
2965 * This is useful when transactions might use snapshot isolation
2966 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2967 * is this lag plus transaction duration. If they don't, it is still
2968 * safe to be pessimistic. This returns null if there is no transaction.
2970 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2973 protected function getTransactionLagStatus() {
2974 return $this->mTrxLevel
2975 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
2980 * Get a replica DB lag estimate for this server
2982 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2985 protected function getApproximateLagStatus() {
2987 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
2988 'since' => microtime( true )
2993 * Merge the result of getSessionLagStatus() for several DBs
2994 * using the most pessimistic values to estimate the lag of
2995 * any data derived from them in combination
2997 * This is information is useful for caching modules
2999 * @see WANObjectCache::set()
3000 * @see WANObjectCache::getWithSetCallback()
3002 * @param IDatabase $db1
3003 * @param IDatabase ...
3004 * @return array Map of values:
3005 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3006 * - since: oldest UNIX timestamp of any of the DB lag estimates
3007 * - pending: whether any of the DBs have uncommitted changes
3010 public static function getCacheSetOptions( IDatabase
$db1 ) {
3011 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3012 foreach ( func_get_args() as $db ) {
3013 /** @var IDatabase $db */
3014 $status = $db->getSessionLagStatus();
3015 if ( $status['lag'] === false ) {
3016 $res['lag'] = false;
3017 } elseif ( $res['lag'] !== false ) {
3018 $res['lag'] = max( $res['lag'], $status['lag'] );
3020 $res['since'] = min( $res['since'], $status['since'] );
3021 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3027 public function getLag() {
3031 public function maxListLen() {
3035 public function encodeBlob( $b ) {
3039 public function decodeBlob( $b ) {
3040 if ( $b instanceof Blob
) {
3046 public function setSessionOptions( array $options ) {
3049 public function sourceFile(
3051 callable
$lineCallback = null,
3052 callable
$resultCallback = null,
3054 callable
$inputCallback = null
3056 MediaWiki\
suppressWarnings();
3057 $fp = fopen( $filename, 'r' );
3058 MediaWiki\restoreWarnings
();
3060 if ( false === $fp ) {
3061 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3065 $fname = __METHOD__
. "( $filename )";
3069 $error = $this->sourceStream(
3070 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3071 } catch ( Exception
$e ) {
3081 public function setSchemaVars( $vars ) {
3082 $this->mSchemaVars
= $vars;
3085 public function sourceStream(
3087 callable
$lineCallback = null,
3088 callable
$resultCallback = null,
3089 $fname = __METHOD__
,
3090 callable
$inputCallback = null
3094 while ( !feof( $fp ) ) {
3095 if ( $lineCallback ) {
3096 call_user_func( $lineCallback );
3099 $line = trim( fgets( $fp ) );
3101 if ( $line == '' ) {
3105 if ( '-' == $line[0] && '-' == $line[1] ) {
3113 $done = $this->streamStatementEnd( $cmd, $line );
3117 if ( $done ||
feof( $fp ) ) {
3118 $cmd = $this->replaceVars( $cmd );
3120 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3121 $res = $this->query( $cmd, $fname );
3123 if ( $resultCallback ) {
3124 call_user_func( $resultCallback, $res, $this );
3127 if ( false === $res ) {
3128 $err = $this->lastError();
3130 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3141 * Called by sourceStream() to check if we've reached a statement end
3143 * @param string &$sql SQL assembled so far
3144 * @param string &$newLine New line about to be added to $sql
3145 * @return bool Whether $newLine contains end of the statement
3147 public function streamStatementEnd( &$sql, &$newLine ) {
3148 if ( $this->delimiter
) {
3150 $newLine = preg_replace(
3151 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3152 if ( $newLine != $prev ) {
3161 * Database independent variable replacement. Replaces a set of variables
3162 * in an SQL statement with their contents as given by $this->getSchemaVars().
3164 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3166 * - '{$var}' should be used for text and is passed through the database's
3168 * - `{$var}` should be used for identifiers (e.g. table and database names).
3169 * It is passed through the database's addIdentifierQuotes method which
3170 * can be overridden if the database uses something other than backticks.
3171 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3172 * database's tableName method.
3173 * - / *i* / passes the name that follows through the database's indexName method.
3174 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3175 * its use should be avoided. In 1.24 and older, string encoding was applied.
3177 * @param string $ins SQL statement to replace variables in
3178 * @return string The new SQL statement with variables replaced
3180 protected function replaceVars( $ins ) {
3181 $vars = $this->getSchemaVars();
3182 return preg_replace_callback(
3184 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3185 \'\{\$ (\w+) }\' | # 3. addQuotes
3186 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3187 /\*\$ (\w+) \*/ # 5. leave unencoded
3189 function ( $m ) use ( $vars ) {
3190 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3191 // check for both nonexistent keys *and* the empty string.
3192 if ( isset( $m[1] ) && $m[1] !== '' ) {
3193 if ( $m[1] === 'i' ) {
3194 return $this->indexName( $m[2] );
3196 return $this->tableName( $m[2] );
3198 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3199 return $this->addQuotes( $vars[$m[3]] );
3200 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3201 return $this->addIdentifierQuotes( $vars[$m[4]] );
3202 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3203 return $vars[$m[5]];
3213 * Get schema variables. If none have been set via setSchemaVars(), then
3214 * use some defaults from the current object.
3218 protected function getSchemaVars() {
3219 if ( $this->mSchemaVars
) {
3220 return $this->mSchemaVars
;
3222 return $this->getDefaultSchemaVars();
3227 * Get schema variables to use if none have been set via setSchemaVars().
3229 * Override this in derived classes to provide variables for tables.sql
3230 * and SQL patch files.
3234 protected function getDefaultSchemaVars() {
3238 public function lockIsFree( $lockName, $method ) {
3242 public function lock( $lockName, $method, $timeout = 5 ) {
3243 $this->mNamedLocksHeld
[$lockName] = 1;
3248 public function unlock( $lockName, $method ) {
3249 unset( $this->mNamedLocksHeld
[$lockName] );
3254 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3255 if ( $this->writesOrCallbacksPending() ) {
3256 // This only flushes transactions to clear snapshots, not to write data
3257 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3258 throw new DBUnexpectedError(
3260 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3264 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3268 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3269 if ( $this->trxLevel() ) {
3270 // There is a good chance an exception was thrown, causing any early return
3271 // from the caller. Let any error handler get a chance to issue rollback().
3272 // If there isn't one, let the error bubble up and trigger server-side rollback.
3273 $this->onTransactionResolution(
3274 function () use ( $lockKey, $fname ) {
3275 $this->unlock( $lockKey, $fname );
3280 $this->unlock( $lockKey, $fname );
3284 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3289 public function namedLocksEnqueue() {
3294 * Lock specific tables
3296 * @param array $read Array of tables to lock for read access
3297 * @param array $write Array of tables to lock for write access
3298 * @param string $method Name of caller
3299 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3302 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3307 * Unlock specific tables
3309 * @param string $method The caller
3312 public function unlockTables( $method ) {
3318 * @param string $tableName
3319 * @param string $fName
3320 * @return bool|ResultWrapper
3323 public function dropTable( $tableName, $fName = __METHOD__
) {
3324 if ( !$this->tableExists( $tableName, $fName ) ) {
3327 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3329 return $this->query( $sql, $fName );
3332 public function getInfinity() {
3336 public function encodeExpiry( $expiry ) {
3337 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3338 ?
$this->getInfinity()
3339 : $this->timestamp( $expiry );
3342 public function decodeExpiry( $expiry, $format = TS_MW
) {
3343 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3347 return ConvertibleTimestamp
::convert( $format, $expiry );
3350 public function setBigSelects( $value = true ) {
3354 public function isReadOnly() {
3355 return ( $this->getReadOnlyReason() !== false );
3359 * @return string|bool Reason this DB is read-only or false if it is not
3361 protected function getReadOnlyReason() {
3362 $reason = $this->getLBInfo( 'readOnlyReason' );
3364 return is_string( $reason ) ?
$reason : false;
3367 public function setTableAliases( array $aliases ) {
3368 $this->tableAliases
= $aliases;
3372 * @return bool Whether a DB user is required to access the DB
3375 protected function requiresDatabaseUser() {
3380 * Get the underlying binding handle, mConn
3382 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3383 * This catches broken callers than catch and ignore disconnection exceptions.
3384 * Unlike checking isOpen(), this is safe to call inside of open().
3386 * @return resource|object
3387 * @throws DBUnexpectedError
3390 protected function getBindingHandle() {
3391 if ( !$this->mConn
) {
3392 throw new DBUnexpectedError(
3394 'DB connection was already closed or the connection dropped.'
3398 return $this->mConn
;
3405 public function __toString() {
3406 return (string)$this->mConn
;
3410 * Make sure that copies do not share the same client binding handle
3411 * @throws DBConnectionError
3413 public function __clone() {
3414 $this->connLogger
->warning(
3415 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3416 ( new RuntimeException() )->getTraceAsString()
3419 if ( $this->isOpen() ) {
3420 // Open a new connection resource without messing with the old one
3421 $this->mOpened
= false;
3422 $this->mConn
= false;
3423 $this->mTrxEndCallbacks
= []; // don't copy
3424 $this->handleSessionLoss(); // no trx or locks anymore
3425 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3426 $this->lastPing
= microtime( true );
3431 * Called by serialize. Throw an exception when DB connection is serialized.
3432 * This causes problems on some database engines because the connection is
3433 * not restored on unserialize.
3435 public function __sleep() {
3436 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3437 'the connection is not restored on wakeup.' );
3441 * Run a few simple sanity checks and close dangling connections
3443 public function __destruct() {
3444 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3445 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3448 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3449 if ( $danglingWriters ) {
3450 $fnames = implode( ', ', $danglingWriters );
3451 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3454 if ( $this->mConn
) {
3455 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3456 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3457 \MediaWiki\
suppressWarnings();
3458 $this->closeConnection();
3459 \MediaWiki\restoreWarnings
();
3460 $this->mConn
= false;
3461 $this->mOpened
= false;
3466 class_alias( Database
::class, 'DatabaseBase' );