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
;
30 * Relational database abstraction object
35 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
36 /** Number of times to re-try an operation in case of deadlock */
37 const DEADLOCK_TRIES
= 4;
38 /** Minimum time to wait before retry, in microseconds */
39 const DEADLOCK_DELAY_MIN
= 500000;
40 /** Maximum time to wait before retry */
41 const DEADLOCK_DELAY_MAX
= 1500000;
43 /** How long before it is worth doing a dummy query to test the connection */
45 const PING_QUERY
= 'SELECT 1 AS ping';
47 const TINY_WRITE_SEC
= .010;
48 const SLOW_WRITE_SEC
= .500;
49 const SMALL_WRITE_ROWS
= 100;
51 /** @var string SQL query */
52 protected $mLastQuery = '';
54 protected $mDoneWrites = false;
55 /** @var string|bool */
56 protected $mPHPError = false;
65 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
66 protected $tableAliases = [];
67 /** @var bool Whether this PHP instance is for a CLI script */
69 /** @var string Agent name for query profiling */
72 /** @var BagOStuff APC cache */
74 /** @var LoggerInterface */
75 protected $connLogger;
76 /** @var LoggerInterface */
77 protected $queryLogger;
78 /** @var callback Error logging callback */
79 protected $errorLogger;
81 /** @var resource Database connection */
82 protected $mConn = null;
84 protected $mOpened = false;
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxIdleCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxPreCommitCallbacks = [];
90 /** @var array[] List of (callable, method name) */
91 protected $mTrxEndCallbacks = [];
92 /** @var callable[] Map of (name => callable) */
93 protected $mTrxRecurringCallbacks = [];
94 /** @var bool Whether to suppress triggering of transaction end callbacks */
95 protected $mTrxEndCallbacksSuppressed = false;
98 protected $mTablePrefix = '';
100 protected $mSchema = '';
104 protected $mLBInfo = [];
105 /** @var bool|null */
106 protected $mDefaultBigSelects = null;
107 /** @var array|bool */
108 protected $mSchemaVars = false;
110 protected $mSessionVars = [];
111 /** @var array|null */
112 protected $preparedArgs;
113 /** @var string|bool|null Stashed value of html_errors INI setting */
114 protected $htmlErrors;
116 protected $delimiter = ';';
117 /** @var DatabaseDomain */
118 protected $currentDomain;
121 * Either 1 if a transaction is active or 0 otherwise.
122 * The other Trx fields may not be meaningfull if this is 0.
126 protected $mTrxLevel = 0;
128 * Either a short hexidecimal string if a transaction is active or ""
131 * @see DatabaseBase::mTrxLevel
133 protected $mTrxShortId = '';
135 * The UNIX time that the transaction started. Callers can assume that if
136 * snapshot isolation is used, then the data is *at least* up to date to that
137 * point (possibly more up-to-date since the first SELECT defines the snapshot).
140 * @see DatabaseBase::mTrxLevel
142 private $mTrxTimestamp = null;
143 /** @var float Lag estimate at the time of BEGIN */
144 private $mTrxReplicaLag = null;
146 * Remembers the function name given for starting the most recent transaction via begin().
147 * Used to provide additional context for error reporting.
150 * @see DatabaseBase::mTrxLevel
152 private $mTrxFname = null;
154 * Record if possible write queries were done in the last transaction started
157 * @see DatabaseBase::mTrxLevel
159 private $mTrxDoneWrites = false;
161 * Record if the current transaction was started implicitly due to DBO_TRX being set.
164 * @see DatabaseBase::mTrxLevel
166 private $mTrxAutomatic = false;
168 * Array of levels of atomicity within transactions
172 private $mTrxAtomicLevels = [];
174 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
178 private $mTrxAutomaticAtomic = false;
180 * Track the write query callers of the current transaction
184 private $mTrxWriteCallers = [];
186 * @var float Seconds spent in write queries for the current transaction
188 private $mTrxWriteDuration = 0.0;
190 * @var integer Number of write queries for the current transaction
192 private $mTrxWriteQueryCount = 0;
194 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
196 private $mTrxWriteAdjDuration = 0.0;
198 * @var integer Number of write queries counted in mTrxWriteAdjDuration
200 private $mTrxWriteAdjQueryCount = 0;
202 * @var float RTT time estimate
204 private $mRTTEstimate = 0.0;
206 /** @var array Map of (name => 1) for locks obtained via lock() */
207 private $mNamedLocksHeld = [];
208 /** @var array Map of (table name => 1) for TEMPORARY tables */
209 protected $mSessionTempTables = [];
211 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
212 private $lazyMasterHandle;
216 * @var string[] Process cache of VIEWs names in the database
218 protected $allViews = null;
220 /** @var float UNIX timestamp */
221 protected $lastPing = 0.0;
223 /** @var int[] Prior mFlags values */
224 private $priorFlags = [];
226 /** @var object|string Class name or object With profileIn/profileOut methods */
228 /** @var TransactionProfiler */
229 protected $trxProfiler;
232 * Constructor and database handle and attempt to connect to the DB server
234 * IDatabase classes should not be constructed directly in external
235 * code. Database::factory() should be used instead.
237 * @param array $params Parameters passed from Database::factory()
239 function __construct( array $params ) {
240 $server = $params['host'];
241 $user = $params['user'];
242 $password = $params['password'];
243 $dbName = $params['dbname'];
245 $this->mSchema
= $params['schema'];
246 $this->mTablePrefix
= $params['tablePrefix'];
248 $this->cliMode
= $params['cliMode'];
249 // Agent name is added to SQL queries in a comment, so make sure it can't break out
250 $this->agent
= str_replace( '/', '-', $params['agent'] );
252 $this->mFlags
= $params['flags'];
253 if ( $this->mFlags
& DBO_DEFAULT
) {
254 if ( $this->cliMode
) {
255 $this->mFlags
&= ~DBO_TRX
;
257 $this->mFlags |
= DBO_TRX
;
261 $this->mSessionVars
= $params['variables'];
263 $this->srvCache
= isset( $params['srvCache'] )
264 ?
$params['srvCache']
265 : new HashBagOStuff();
267 $this->profiler
= $params['profiler'];
268 $this->trxProfiler
= $params['trxProfiler'];
269 $this->connLogger
= $params['connLogger'];
270 $this->queryLogger
= $params['queryLogger'];
271 $this->errorLogger
= $params['errorLogger'];
273 // Set initial dummy domain until open() sets the final DB/prefix
274 $this->currentDomain
= DatabaseDomain
::newUnspecified();
277 $this->open( $server, $user, $password, $dbName );
278 } elseif ( $this->requiresDatabaseUser() ) {
279 throw new InvalidArgumentException( "No database user provided." );
282 // Set the domain object after open() sets the relevant fields
283 if ( $this->mDBname
!= '' ) {
284 // Domains with server scope but a table prefix are not used by IDatabase classes
285 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
290 * Construct a Database subclass instance given a database type and parameters
292 * This also connects to the database immediately upon object construction
294 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
295 * @param array $p Parameter map with keys:
296 * - host : The hostname of the DB server
297 * - user : The name of the database user the client operates under
298 * - password : The password for the database user
299 * - dbname : The name of the database to use where queries do not specify one.
300 * The database must exist or an error might be thrown. Setting this to the empty string
301 * will avoid any such errors and make the handle have no implicit database scope. This is
302 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
303 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
304 * in which user names and such are defined, e.g. users are database-specific in Postgres.
305 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
306 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
307 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
308 * recognized in queries. This can be used in place of schemas for handle site farms.
309 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
310 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
311 * flag in place UNLESS this this database simply acts as a key/value store.
312 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
313 * 'mysql' driver and the newer 'mysqli' driver.
314 * - variables: Optional map of session variables to set after connecting. This can be
315 * used to adjust lock timeouts or encoding modes and the like.
316 * - connLogger: Optional PSR-3 logger interface instance.
317 * - queryLogger: Optional PSR-3 logger interface instance.
318 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
319 * These will be called in query(), using a simplified version of the SQL that also
320 * includes the agent as a SQL comment.
321 * - trxProfiler: Optional TransactionProfiler instance.
322 * - errorLogger: Optional callback that takes an Exception and logs it.
323 * - cliMode: Whether to consider the execution context that of a CLI script.
324 * - agent: Optional name used to identify the end-user in query profiling/logging.
325 * - srvCache: Optional BagOStuff instance to an APC-style cache.
326 * @return Database|null If the database driver or extension cannot be found
327 * @throws InvalidArgumentException If the database driver or extension cannot be found
330 final public static function factory( $dbType, $p = [] ) {
331 static $canonicalDBTypes = [
332 'mysql' => [ 'mysqli', 'mysql' ],
340 $dbType = strtolower( $dbType );
341 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
342 $possibleDrivers = $canonicalDBTypes[$dbType];
343 if ( !empty( $p['driver'] ) ) {
344 if ( in_array( $p['driver'], $possibleDrivers ) ) {
345 $driver = $p['driver'];
347 throw new InvalidArgumentException( __METHOD__
.
348 " type '$dbType' does not support driver '{$p['driver']}'" );
351 foreach ( $possibleDrivers as $posDriver ) {
352 if ( extension_loaded( $posDriver ) ) {
353 $driver = $posDriver;
361 if ( $driver === false ) {
362 throw new InvalidArgumentException( __METHOD__
.
363 " no viable database extension found for type '$dbType'" );
366 $class = 'Database' . ucfirst( $driver );
367 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
368 // Resolve some defaults for b/c
369 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
370 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
371 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
372 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
373 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
374 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
375 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
376 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
377 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
378 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
379 if ( !isset( $p['connLogger'] ) ) {
380 $p['connLogger'] = new \Psr\Log\
NullLogger();
382 if ( !isset( $p['queryLogger'] ) ) {
383 $p['queryLogger'] = new \Psr\Log\
NullLogger();
385 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
386 if ( !isset( $p['trxProfiler'] ) ) {
387 $p['trxProfiler'] = new TransactionProfiler();
389 if ( !isset( $p['errorLogger'] ) ) {
390 $p['errorLogger'] = function ( Exception
$e ) {
391 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
395 $conn = new $class( $p );
403 public function setLogger( LoggerInterface
$logger ) {
404 $this->queryLogger
= $logger;
407 public function getServerInfo() {
408 return $this->getServerVersion();
411 public function bufferResults( $buffer = null ) {
412 $res = !$this->getFlag( DBO_NOBUFFER
);
413 if ( $buffer !== null ) {
414 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
421 * Turns on (false) or off (true) the automatic generation and sending
422 * of a "we're sorry, but there has been a database error" page on
423 * database errors. Default is on (false). When turned off, the
424 * code should use lastErrno() and lastError() to handle the
425 * situation as appropriate.
427 * Do not use this function outside of the Database classes.
429 * @param null|bool $ignoreErrors
430 * @return bool The previous value of the flag.
432 protected function ignoreErrors( $ignoreErrors = null ) {
433 $res = $this->getFlag( DBO_IGNORE
);
434 if ( $ignoreErrors !== null ) {
435 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
441 public function trxLevel() {
442 return $this->mTrxLevel
;
445 public function trxTimestamp() {
446 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
449 public function tablePrefix( $prefix = null ) {
450 $old = $this->mTablePrefix
;
451 if ( $prefix !== null ) {
452 $this->mTablePrefix
= $prefix;
453 $this->currentDomain
= ( $this->mDBname
!= '' )
454 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
455 : DatabaseDomain
::newUnspecified();
461 public function dbSchema( $schema = null ) {
462 $old = $this->mSchema
;
463 if ( $schema !== null ) {
464 $this->mSchema
= $schema;
470 public function getLBInfo( $name = null ) {
471 if ( is_null( $name ) ) {
472 return $this->mLBInfo
;
474 if ( array_key_exists( $name, $this->mLBInfo
) ) {
475 return $this->mLBInfo
[$name];
482 public function setLBInfo( $name, $value = null ) {
483 if ( is_null( $value ) ) {
484 $this->mLBInfo
= $name;
486 $this->mLBInfo
[$name] = $value;
490 public function setLazyMasterHandle( IDatabase
$conn ) {
491 $this->lazyMasterHandle
= $conn;
495 * @return IDatabase|null
496 * @see setLazyMasterHandle()
499 public function getLazyMasterHandle() {
500 return $this->lazyMasterHandle
;
503 public function implicitGroupby() {
507 public function implicitOrderby() {
511 public function lastQuery() {
512 return $this->mLastQuery
;
515 public function doneWrites() {
516 return (bool)$this->mDoneWrites
;
519 public function lastDoneWrites() {
520 return $this->mDoneWrites ?
: false;
523 public function writesPending() {
524 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
527 public function writesOrCallbacksPending() {
528 return $this->mTrxLevel
&& (
529 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
533 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
534 if ( !$this->mTrxLevel
) {
536 } elseif ( !$this->mTrxDoneWrites
) {
541 case self
::ESTIMATE_DB_APPLY
:
543 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
544 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
545 // For omitted queries, make them count as something at least
546 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
547 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
550 default: // everything
551 return $this->mTrxWriteDuration
;
555 public function pendingWriteCallers() {
556 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
559 protected function pendingWriteAndCallbackCallers() {
560 if ( !$this->mTrxLevel
) {
564 $fnames = $this->mTrxWriteCallers
;
566 $this->mTrxIdleCallbacks
,
567 $this->mTrxPreCommitCallbacks
,
568 $this->mTrxEndCallbacks
570 foreach ( $callbacks as $callback ) {
571 $fnames[] = $callback[1];
578 public function isOpen() {
579 return $this->mOpened
;
582 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
583 if ( $remember === self
::REMEMBER_PRIOR
) {
584 array_push( $this->priorFlags
, $this->mFlags
);
586 $this->mFlags |
= $flag;
589 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
590 if ( $remember === self
::REMEMBER_PRIOR
) {
591 array_push( $this->priorFlags
, $this->mFlags
);
593 $this->mFlags
&= ~
$flag;
596 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
597 if ( !$this->priorFlags
) {
601 if ( $state === self
::RESTORE_INITIAL
) {
602 $this->mFlags
= reset( $this->priorFlags
);
603 $this->priorFlags
= [];
605 $this->mFlags
= array_pop( $this->priorFlags
);
609 public function getFlag( $flag ) {
610 return !!( $this->mFlags
& $flag );
613 public function getProperty( $name ) {
617 public function getDomainID() {
618 return $this->currentDomain
->getId();
621 final public function getWikiID() {
622 return $this->getDomainID();
626 * Get information about an index into an object
627 * @param string $table Table name
628 * @param string $index Index name
629 * @param string $fname Calling function name
630 * @return mixed Database-specific index description class or false if the index does not exist
632 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
635 * Wrapper for addslashes()
637 * @param string $s String to be slashed.
638 * @return string Slashed string.
640 abstract function strencode( $s );
642 protected function installErrorHandler() {
643 $this->mPHPError
= false;
644 $this->htmlErrors
= ini_set( 'html_errors', '0' );
645 set_error_handler( [ $this, 'connectionErrorLogger' ] );
649 * @return bool|string
651 protected function restoreErrorHandler() {
652 restore_error_handler();
653 if ( $this->htmlErrors
!== false ) {
654 ini_set( 'html_errors', $this->htmlErrors
);
656 if ( $this->mPHPError
) {
657 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
658 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
667 * This method should not be used outside of Database classes
670 * @param string $errstr
672 public function connectionErrorLogger( $errno, $errstr ) {
673 $this->mPHPError
= $errstr;
677 * Create a log context to pass to PSR-3 logger functions.
679 * @param array $extras Additional data to add to context
682 protected function getLogContext( array $extras = [] ) {
685 'db_server' => $this->mServer
,
686 'db_name' => $this->mDBname
,
687 'db_user' => $this->mUser
,
693 public function close() {
694 if ( $this->mConn
) {
695 if ( $this->trxLevel() ) {
696 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
699 $closed = $this->closeConnection();
700 $this->mConn
= false;
701 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
702 throw new RuntimeException( "Transaction callbacks still pending." );
706 $this->mOpened
= false;
712 * Make sure isOpen() returns true as a sanity check
714 * @throws DBUnexpectedError
716 protected function assertOpen() {
717 if ( !$this->isOpen() ) {
718 throw new DBUnexpectedError( $this, "DB connection was already closed." );
723 * Closes underlying database connection
725 * @return bool Whether connection was closed successfully
727 abstract protected function closeConnection();
729 public function reportConnectionError( $error = 'Unknown error' ) {
730 $myError = $this->lastError();
736 throw new DBConnectionError( $this, $error );
740 * The DBMS-dependent part of query()
742 * @param string $sql SQL query.
743 * @return ResultWrapper|bool Result object to feed to fetchObject,
744 * fetchRow, ...; or false on failure
746 abstract protected function doQuery( $sql );
749 * Determine whether a query writes to the DB.
750 * Should return true if unsure.
755 protected function isWriteQuery( $sql ) {
757 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
762 * @return string|null
764 protected function getQueryVerb( $sql ) {
765 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
769 * Determine whether a SQL statement is sensitive to isolation level.
770 * A SQL statement is considered transactable if its result could vary
771 * depending on the transaction isolation level. Operational commands
772 * such as 'SET' and 'SHOW' are not considered to be transactable.
777 protected function isTransactableQuery( $sql ) {
778 $verb = $this->getQueryVerb( $sql );
779 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
783 * @param string $sql A SQL query
784 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
786 protected function registerTempTableOperation( $sql ) {
788 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
792 $this->mSessionTempTables
[$matches[1]] = 1;
795 } elseif ( preg_match(
796 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
800 unset( $this->mSessionTempTables
[$matches[1]] );
803 } elseif ( preg_match(
804 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
808 return isset( $this->mSessionTempTables
[$matches[1]] );
814 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
815 $priorWritesPending = $this->writesOrCallbacksPending();
816 $this->mLastQuery
= $sql;
818 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
820 $reason = $this->getReadOnlyReason();
821 if ( $reason !== false ) {
822 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
824 # Set a flag indicating that writes have been done
825 $this->mDoneWrites
= microtime( true );
828 // Add trace comment to the begin of the sql string, right after the operator.
829 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
830 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
832 # Start implicit transactions that wrap the request if DBO_TRX is enabled
833 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
834 && $this->isTransactableQuery( $sql )
836 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
837 $this->mTrxAutomatic
= true;
840 # Keep track of whether the transaction has write queries pending
841 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
842 $this->mTrxDoneWrites
= true;
843 $this->trxProfiler
->transactionWritingIn(
844 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
847 if ( $this->getFlag( DBO_DEBUG
) ) {
848 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
851 # Avoid fatals if close() was called
854 # Send the query to the server
855 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
857 # Try reconnecting if the connection was lost
858 if ( false === $ret && $this->wasErrorReissuable() ) {
859 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
860 # Stash the last error values before anything might clear them
861 $lastError = $this->lastError();
862 $lastErrno = $this->lastErrno();
863 # Update state tracking to reflect transaction loss due to disconnection
864 $this->handleSessionLoss();
865 if ( $this->reconnect() ) {
866 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
867 $this->connLogger
->warning( $msg );
868 $this->queryLogger
->warning(
869 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
871 if ( !$recoverable ) {
872 # Callers may catch the exception and continue to use the DB
873 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
875 # Should be safe to silently retry the query
876 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
879 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
880 $this->connLogger
->error( $msg );
884 if ( false === $ret ) {
885 # Deadlocks cause the entire transaction to abort, not just the statement.
886 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
887 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
888 if ( $this->wasDeadlock() ) {
889 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
890 $tempIgnore = false; // not recoverable
892 # Update state tracking to reflect transaction loss
893 $this->handleSessionLoss();
896 $this->reportQueryError(
897 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
900 $res = $this->resultObject( $ret );
905 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
906 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
907 # generalizeSQL() will probably cut down the query to reasonable
908 # logging size most of the time. The substr is really just a sanity check.
910 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
912 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
915 # Include query transaction state
916 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
918 $startTime = microtime( true );
919 if ( $this->profiler
) {
920 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
922 $ret = $this->doQuery( $commentedSql );
923 if ( $this->profiler
) {
924 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
926 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
928 unset( $queryProfSection ); // profile out (if set)
930 if ( $ret !== false ) {
931 $this->lastPing
= $startTime;
932 if ( $isWrite && $this->mTrxLevel
) {
933 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
934 $this->mTrxWriteCallers
[] = $fname;
938 if ( $sql === self
::PING_QUERY
) {
939 $this->mRTTEstimate
= $queryRuntime;
942 $this->trxProfiler
->recordQueryCompletion(
943 $queryProf, $startTime, $isWrite, $this->affectedRows()
945 $this->queryLogger
->debug( $sql, [
947 'master' => $isMaster,
948 'runtime' => $queryRuntime,
955 * Update the estimated run-time of a query, not counting large row lock times
957 * LoadBalancer can be set to rollback transactions that will create huge replication
958 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
959 * queries, like inserting a row can take a long time due to row locking. This method
960 * uses some simple heuristics to discount those cases.
962 * @param string $sql A SQL write query
963 * @param float $runtime Total runtime, including RTT
965 private function updateTrxWriteQueryTime( $sql, $runtime ) {
966 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
967 $indicativeOfReplicaRuntime = true;
968 if ( $runtime > self
::SLOW_WRITE_SEC
) {
969 $verb = $this->getQueryVerb( $sql );
970 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
971 if ( $verb === 'INSERT' ) {
972 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
973 } elseif ( $verb === 'REPLACE' ) {
974 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
978 $this->mTrxWriteDuration +
= $runtime;
979 $this->mTrxWriteQueryCount +
= 1;
980 if ( $indicativeOfReplicaRuntime ) {
981 $this->mTrxWriteAdjDuration +
= $runtime;
982 $this->mTrxWriteAdjQueryCount +
= 1;
986 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
987 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
988 # Dropped connections also mean that named locks are automatically released.
989 # Only allow error suppression in autocommit mode or when the lost transaction
990 # didn't matter anyway (aside from DBO_TRX snapshot loss).
991 if ( $this->mNamedLocksHeld
) {
992 return false; // possible critical section violation
993 } elseif ( $sql === 'COMMIT' ) {
994 return !$priorWritesPending; // nothing written anyway? (T127428)
995 } elseif ( $sql === 'ROLLBACK' ) {
996 return true; // transaction lost...which is also what was requested :)
997 } elseif ( $this->explicitTrxActive() ) {
998 return false; // don't drop atomocity
999 } elseif ( $priorWritesPending ) {
1000 return false; // prior writes lost from implicit transaction
1006 private function handleSessionLoss() {
1007 $this->mTrxLevel
= 0;
1008 $this->mTrxIdleCallbacks
= []; // bug 65263
1009 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1010 $this->mSessionTempTables
= [];
1011 $this->mNamedLocksHeld
= [];
1013 // Handle callbacks in mTrxEndCallbacks
1014 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1015 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1017 } catch ( Exception
$e ) {
1018 // Already logged; move on...
1023 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1024 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1025 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1027 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1028 $this->queryLogger
->error(
1029 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1030 $this->getLogContext( [
1031 'method' => __METHOD__
,
1034 'sql1line' => $sql1line,
1038 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1039 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1043 public function freeResult( $res ) {
1046 public function selectField(
1047 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1049 if ( $var === '*' ) { // sanity
1050 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1053 if ( !is_array( $options ) ) {
1054 $options = [ $options ];
1057 $options['LIMIT'] = 1;
1059 $res = $this->select( $table, $var, $cond, $fname, $options );
1060 if ( $res === false ||
!$this->numRows( $res ) ) {
1064 $row = $this->fetchRow( $res );
1066 if ( $row !== false ) {
1067 return reset( $row );
1073 public function selectFieldValues(
1074 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1076 if ( $var === '*' ) { // sanity
1077 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1078 } elseif ( !is_string( $var ) ) { // sanity
1079 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1082 if ( !is_array( $options ) ) {
1083 $options = [ $options ];
1086 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1087 if ( $res === false ) {
1092 foreach ( $res as $row ) {
1093 $values[] = $row->$var;
1100 * Returns an optional USE INDEX clause to go after the table, and a
1101 * string to go at the end of the query.
1103 * @param array $options Associative array of options to be turned into
1104 * an SQL query, valid keys are listed in the function.
1106 * @see DatabaseBase::select()
1108 protected function makeSelectOptions( $options ) {
1109 $preLimitTail = $postLimitTail = '';
1114 foreach ( $options as $key => $option ) {
1115 if ( is_numeric( $key ) ) {
1116 $noKeyOptions[$option] = true;
1120 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1122 $preLimitTail .= $this->makeOrderBy( $options );
1124 // if (isset($options['LIMIT'])) {
1125 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1126 // isset($options['OFFSET']) ? $options['OFFSET']
1130 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1131 $postLimitTail .= ' FOR UPDATE';
1134 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1135 $postLimitTail .= ' LOCK IN SHARE MODE';
1138 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1139 $startOpts .= 'DISTINCT';
1142 # Various MySQL extensions
1143 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1144 $startOpts .= ' /*! STRAIGHT_JOIN */';
1147 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1148 $startOpts .= ' HIGH_PRIORITY';
1151 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1152 $startOpts .= ' SQL_BIG_RESULT';
1155 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1156 $startOpts .= ' SQL_BUFFER_RESULT';
1159 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1160 $startOpts .= ' SQL_SMALL_RESULT';
1163 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1164 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1167 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1168 $startOpts .= ' SQL_CACHE';
1171 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1172 $startOpts .= ' SQL_NO_CACHE';
1175 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1176 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1180 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1181 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1186 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1190 * Returns an optional GROUP BY with an optional HAVING
1192 * @param array $options Associative array of options
1194 * @see DatabaseBase::select()
1197 protected function makeGroupByWithHaving( $options ) {
1199 if ( isset( $options['GROUP BY'] ) ) {
1200 $gb = is_array( $options['GROUP BY'] )
1201 ?
implode( ',', $options['GROUP BY'] )
1202 : $options['GROUP BY'];
1203 $sql .= ' GROUP BY ' . $gb;
1205 if ( isset( $options['HAVING'] ) ) {
1206 $having = is_array( $options['HAVING'] )
1207 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1208 : $options['HAVING'];
1209 $sql .= ' HAVING ' . $having;
1216 * Returns an optional ORDER BY
1218 * @param array $options Associative array of options
1220 * @see DatabaseBase::select()
1223 protected function makeOrderBy( $options ) {
1224 if ( isset( $options['ORDER BY'] ) ) {
1225 $ob = is_array( $options['ORDER BY'] )
1226 ?
implode( ',', $options['ORDER BY'] )
1227 : $options['ORDER BY'];
1229 return ' ORDER BY ' . $ob;
1235 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1236 $options = [], $join_conds = [] ) {
1237 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1239 return $this->query( $sql, $fname );
1242 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1243 $options = [], $join_conds = []
1245 if ( is_array( $vars ) ) {
1246 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1249 $options = (array)$options;
1250 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1251 ?
$options['USE INDEX']
1254 isset( $options['IGNORE INDEX'] ) &&
1255 is_array( $options['IGNORE INDEX'] )
1257 ?
$options['IGNORE INDEX']
1260 if ( is_array( $table ) ) {
1262 $this->tableNamesWithIndexClauseOrJOIN(
1263 $table, $useIndexes, $ignoreIndexes, $join_conds );
1264 } elseif ( $table != '' ) {
1265 if ( $table[0] == ' ' ) {
1266 $from = ' FROM ' . $table;
1269 $this->tableNamesWithIndexClauseOrJOIN(
1270 [ $table ], $useIndexes, $ignoreIndexes, [] );
1276 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1277 $this->makeSelectOptions( $options );
1279 if ( !empty( $conds ) ) {
1280 if ( is_array( $conds ) ) {
1281 $conds = $this->makeList( $conds, self
::LIST_AND
);
1283 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1284 "WHERE $conds $preLimitTail";
1286 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1289 if ( isset( $options['LIMIT'] ) ) {
1290 $sql = $this->limitResult( $sql, $options['LIMIT'],
1291 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1293 $sql = "$sql $postLimitTail";
1295 if ( isset( $options['EXPLAIN'] ) ) {
1296 $sql = 'EXPLAIN ' . $sql;
1302 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1303 $options = [], $join_conds = []
1305 $options = (array)$options;
1306 $options['LIMIT'] = 1;
1307 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1309 if ( $res === false ) {
1313 if ( !$this->numRows( $res ) ) {
1317 $obj = $this->fetchObject( $res );
1322 public function estimateRowCount(
1323 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1326 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1329 $row = $this->fetchRow( $res );
1330 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1336 public function selectRowCount(
1337 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1340 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1341 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1344 $row = $this->fetchRow( $res );
1345 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1352 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1353 * It's only slightly flawed. Don't use for anything important.
1355 * @param string $sql A SQL Query
1359 protected static function generalizeSQL( $sql ) {
1360 # This does the same as the regexp below would do, but in such a way
1361 # as to avoid crashing php on some large strings.
1362 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1364 $sql = str_replace( "\\\\", '', $sql );
1365 $sql = str_replace( "\\'", '', $sql );
1366 $sql = str_replace( "\\\"", '', $sql );
1367 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1368 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1370 # All newlines, tabs, etc replaced by single space
1371 $sql = preg_replace( '/\s+/', ' ', $sql );
1374 # except the ones surrounded by characters, e.g. l10n
1375 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1376 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1381 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1382 $info = $this->fieldInfo( $table, $field );
1387 public function indexExists( $table, $index, $fname = __METHOD__
) {
1388 if ( !$this->tableExists( $table ) ) {
1392 $info = $this->indexInfo( $table, $index, $fname );
1393 if ( is_null( $info ) ) {
1396 return $info !== false;
1400 public function tableExists( $table, $fname = __METHOD__
) {
1401 $tableRaw = $this->tableName( $table, 'raw' );
1402 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1403 return true; // already known to exist
1406 $table = $this->tableName( $table );
1407 $old = $this->ignoreErrors( true );
1408 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1409 $this->ignoreErrors( $old );
1414 public function indexUnique( $table, $index ) {
1415 $indexInfo = $this->indexInfo( $table, $index );
1417 if ( !$indexInfo ) {
1421 return !$indexInfo[0]->Non_unique
;
1425 * Helper for DatabaseBase::insert().
1427 * @param array $options
1430 protected function makeInsertOptions( $options ) {
1431 return implode( ' ', $options );
1434 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1435 # No rows to insert, easy just return now
1436 if ( !count( $a ) ) {
1440 $table = $this->tableName( $table );
1442 if ( !is_array( $options ) ) {
1443 $options = [ $options ];
1447 if ( isset( $options['fileHandle'] ) ) {
1448 $fh = $options['fileHandle'];
1450 $options = $this->makeInsertOptions( $options );
1452 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1454 $keys = array_keys( $a[0] );
1457 $keys = array_keys( $a );
1460 $sql = 'INSERT ' . $options .
1461 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1465 foreach ( $a as $row ) {
1471 $sql .= '(' . $this->makeList( $row ) . ')';
1474 $sql .= '(' . $this->makeList( $a ) . ')';
1477 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1479 } elseif ( $fh !== null ) {
1483 return (bool)$this->query( $sql, $fname );
1487 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1489 * @param array $options
1492 protected function makeUpdateOptionsArray( $options ) {
1493 if ( !is_array( $options ) ) {
1494 $options = [ $options ];
1499 if ( in_array( 'IGNORE', $options ) ) {
1507 * Make UPDATE options for the DatabaseBase::update function
1509 * @param array $options The options passed to DatabaseBase::update
1512 protected function makeUpdateOptions( $options ) {
1513 $opts = $this->makeUpdateOptionsArray( $options );
1515 return implode( ' ', $opts );
1518 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1519 $table = $this->tableName( $table );
1520 $opts = $this->makeUpdateOptions( $options );
1521 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1523 if ( $conds !== [] && $conds !== '*' ) {
1524 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1527 return $this->query( $sql, $fname );
1530 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1531 if ( !is_array( $a ) ) {
1532 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1538 foreach ( $a as $field => $value ) {
1540 if ( $mode == self
::LIST_AND
) {
1542 } elseif ( $mode == self
::LIST_OR
) {
1551 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1552 $list .= "($value)";
1553 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1556 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1558 // Remove null from array to be handled separately if found
1559 $includeNull = false;
1560 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1561 $includeNull = true;
1562 unset( $value[$nullKey] );
1564 if ( count( $value ) == 0 && !$includeNull ) {
1565 throw new InvalidArgumentException(
1566 __METHOD__
. ": empty input for field $field" );
1567 } elseif ( count( $value ) == 0 ) {
1568 // only check if $field is null
1569 $list .= "$field IS NULL";
1571 // IN clause contains at least one valid element
1572 if ( $includeNull ) {
1573 // Group subconditions to ensure correct precedence
1576 if ( count( $value ) == 1 ) {
1577 // Special-case single values, as IN isn't terribly efficient
1578 // Don't necessarily assume the single key is 0; we don't
1579 // enforce linear numeric ordering on other arrays here.
1580 $value = array_values( $value )[0];
1581 $list .= $field . " = " . $this->addQuotes( $value );
1583 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1585 // if null present in array, append IS NULL
1586 if ( $includeNull ) {
1587 $list .= " OR $field IS NULL)";
1590 } elseif ( $value === null ) {
1591 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1592 $list .= "$field IS ";
1593 } elseif ( $mode == self
::LIST_SET
) {
1594 $list .= "$field = ";
1599 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1601 $list .= "$field = ";
1603 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1610 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1613 foreach ( $data as $base => $sub ) {
1614 if ( count( $sub ) ) {
1615 $conds[] = $this->makeList(
1616 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1622 return $this->makeList( $conds, self
::LIST_OR
);
1624 // Nothing to search for...
1629 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1633 public function bitNot( $field ) {
1637 public function bitAnd( $fieldLeft, $fieldRight ) {
1638 return "($fieldLeft & $fieldRight)";
1641 public function bitOr( $fieldLeft, $fieldRight ) {
1642 return "($fieldLeft | $fieldRight)";
1645 public function buildConcat( $stringList ) {
1646 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1649 public function buildGroupConcatField(
1650 $delim, $table, $field, $conds = '', $join_conds = []
1652 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1654 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1657 public function buildStringCast( $field ) {
1661 public function selectDB( $db ) {
1662 # Stub. Shouldn't cause serious problems if it's not overridden, but
1663 # if your database engine supports a concept similar to MySQL's
1664 # databases you may as well.
1665 $this->mDBname
= $db;
1670 public function getDBname() {
1671 return $this->mDBname
;
1674 public function getServer() {
1675 return $this->mServer
;
1678 public function tableName( $name, $format = 'quoted' ) {
1679 # Skip the entire process when we have a string quoted on both ends.
1680 # Note that we check the end so that we will still quote any use of
1681 # use of `database`.table. But won't break things if someone wants
1682 # to query a database table with a dot in the name.
1683 if ( $this->isQuotedIdentifier( $name ) ) {
1687 # Lets test for any bits of text that should never show up in a table
1688 # name. Basically anything like JOIN or ON which are actually part of
1689 # SQL queries, but may end up inside of the table value to combine
1690 # sql. Such as how the API is doing.
1691 # Note that we use a whitespace test rather than a \b test to avoid
1692 # any remote case where a word like on may be inside of a table name
1693 # surrounded by symbols which may be considered word breaks.
1694 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1698 # Split database and table into proper variables.
1699 # We reverse the explode so that database.table and table both output
1700 # the correct table.
1701 $dbDetails = explode( '.', $name, 3 );
1702 if ( count( $dbDetails ) == 3 ) {
1703 list( $database, $schema, $table ) = $dbDetails;
1704 # We don't want any prefix added in this case
1706 } elseif ( count( $dbDetails ) == 2 ) {
1707 list( $database, $table ) = $dbDetails;
1708 # We don't want any prefix added in this case
1709 # In dbs that support it, $database may actually be the schema
1710 # but that doesn't affect any of the functionality here
1714 list( $table ) = $dbDetails;
1715 if ( isset( $this->tableAliases
[$table] ) ) {
1716 $database = $this->tableAliases
[$table]['dbname'];
1717 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1718 ?
$this->tableAliases
[$table]['schema']
1720 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1721 ?
$this->tableAliases
[$table]['prefix']
1722 : $this->mTablePrefix
;
1725 $schema = $this->mSchema
; # Default schema
1726 $prefix = $this->mTablePrefix
; # Default prefix
1730 # Quote $table and apply the prefix if not quoted.
1731 # $tableName might be empty if this is called from Database::replaceVars()
1732 $tableName = "{$prefix}{$table}";
1733 if ( $format == 'quoted'
1734 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1736 $tableName = $this->addIdentifierQuotes( $tableName );
1739 # Quote $schema and merge it with the table name if needed
1740 if ( strlen( $schema ) ) {
1741 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1742 $schema = $this->addIdentifierQuotes( $schema );
1744 $tableName = $schema . '.' . $tableName;
1747 # Quote $database and merge it with the table name if needed
1748 if ( $database !== '' ) {
1749 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1750 $database = $this->addIdentifierQuotes( $database );
1752 $tableName = $database . '.' . $tableName;
1758 public function tableNames() {
1759 $inArray = func_get_args();
1762 foreach ( $inArray as $name ) {
1763 $retVal[$name] = $this->tableName( $name );
1769 public function tableNamesN() {
1770 $inArray = func_get_args();
1773 foreach ( $inArray as $name ) {
1774 $retVal[] = $this->tableName( $name );
1781 * Get an aliased table name
1782 * e.g. tableName AS newTableName
1784 * @param string $name Table name, see tableName()
1785 * @param string|bool $alias Alias (optional)
1786 * @return string SQL name for aliased table. Will not alias a table to its own name
1788 protected function tableNameWithAlias( $name, $alias = false ) {
1789 if ( !$alias ||
$alias == $name ) {
1790 return $this->tableName( $name );
1792 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1797 * Gets an array of aliased table names
1799 * @param array $tables [ [alias] => table ]
1800 * @return string[] See tableNameWithAlias()
1802 protected function tableNamesWithAlias( $tables ) {
1804 foreach ( $tables as $alias => $table ) {
1805 if ( is_numeric( $alias ) ) {
1808 $retval[] = $this->tableNameWithAlias( $table, $alias );
1815 * Get an aliased field name
1816 * e.g. fieldName AS newFieldName
1818 * @param string $name Field name
1819 * @param string|bool $alias Alias (optional)
1820 * @return string SQL name for aliased field. Will not alias a field to its own name
1822 protected function fieldNameWithAlias( $name, $alias = false ) {
1823 if ( !$alias ||
(string)$alias === (string)$name ) {
1826 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1831 * Gets an array of aliased field names
1833 * @param array $fields [ [alias] => field ]
1834 * @return string[] See fieldNameWithAlias()
1836 protected function fieldNamesWithAlias( $fields ) {
1838 foreach ( $fields as $alias => $field ) {
1839 if ( is_numeric( $alias ) ) {
1842 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1849 * Get the aliased table name clause for a FROM clause
1850 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1852 * @param array $tables ( [alias] => table )
1853 * @param array $use_index Same as for select()
1854 * @param array $ignore_index Same as for select()
1855 * @param array $join_conds Same as for select()
1858 protected function tableNamesWithIndexClauseOrJOIN(
1859 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1863 $use_index = (array)$use_index;
1864 $ignore_index = (array)$ignore_index;
1865 $join_conds = (array)$join_conds;
1867 foreach ( $tables as $alias => $table ) {
1868 if ( !is_string( $alias ) ) {
1869 // No alias? Set it equal to the table name
1872 // Is there a JOIN clause for this table?
1873 if ( isset( $join_conds[$alias] ) ) {
1874 list( $joinType, $conds ) = $join_conds[$alias];
1875 $tableClause = $joinType;
1876 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1877 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1878 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1880 $tableClause .= ' ' . $use;
1883 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1884 $ignore = $this->ignoreIndexClause(
1885 implode( ',', (array)$ignore_index[$alias] ) );
1886 if ( $ignore != '' ) {
1887 $tableClause .= ' ' . $ignore;
1890 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1892 $tableClause .= ' ON (' . $on . ')';
1895 $retJOIN[] = $tableClause;
1896 } elseif ( isset( $use_index[$alias] ) ) {
1897 // Is there an INDEX clause for this table?
1898 $tableClause = $this->tableNameWithAlias( $table, $alias );
1899 $tableClause .= ' ' . $this->useIndexClause(
1900 implode( ',', (array)$use_index[$alias] )
1903 $ret[] = $tableClause;
1904 } elseif ( isset( $ignore_index[$alias] ) ) {
1905 // Is there an INDEX clause for this table?
1906 $tableClause = $this->tableNameWithAlias( $table, $alias );
1907 $tableClause .= ' ' . $this->ignoreIndexClause(
1908 implode( ',', (array)$ignore_index[$alias] )
1911 $ret[] = $tableClause;
1913 $tableClause = $this->tableNameWithAlias( $table, $alias );
1915 $ret[] = $tableClause;
1919 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1920 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1921 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1923 // Compile our final table clause
1924 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1928 * Get the name of an index in a given table.
1930 * @param string $index
1933 protected function indexName( $index ) {
1937 public function addQuotes( $s ) {
1938 if ( $s instanceof Blob
) {
1941 if ( $s === null ) {
1943 } elseif ( is_bool( $s ) ) {
1946 # This will also quote numeric values. This should be harmless,
1947 # and protects against weird problems that occur when they really
1948 # _are_ strings such as article titles and string->number->string
1949 # conversion is not 1:1.
1950 return "'" . $this->strencode( $s ) . "'";
1955 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1956 * MySQL uses `backticks` while basically everything else uses double quotes.
1957 * Since MySQL is the odd one out here the double quotes are our generic
1958 * and we implement backticks in DatabaseMysql.
1963 public function addIdentifierQuotes( $s ) {
1964 return '"' . str_replace( '"', '""', $s ) . '"';
1968 * Returns if the given identifier looks quoted or not according to
1969 * the database convention for quoting identifiers .
1971 * @note Do not use this to determine if untrusted input is safe.
1972 * A malicious user can trick this function.
1973 * @param string $name
1976 public function isQuotedIdentifier( $name ) {
1977 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1984 protected function escapeLikeInternal( $s ) {
1985 return addcslashes( $s, '\%_' );
1988 public function buildLike() {
1989 $params = func_get_args();
1991 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1992 $params = $params[0];
1997 foreach ( $params as $value ) {
1998 if ( $value instanceof LikeMatch
) {
1999 $s .= $value->toString();
2001 $s .= $this->escapeLikeInternal( $value );
2005 return " LIKE {$this->addQuotes( $s )} ";
2008 public function anyChar() {
2009 return new LikeMatch( '_' );
2012 public function anyString() {
2013 return new LikeMatch( '%' );
2016 public function nextSequenceValue( $seqName ) {
2021 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2022 * is only needed because a) MySQL must be as efficient as possible due to
2023 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2024 * which index to pick. Anyway, other databases might have different
2025 * indexes on a given table. So don't bother overriding this unless you're
2027 * @param string $index
2030 public function useIndexClause( $index ) {
2035 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2036 * is only needed because a) MySQL must be as efficient as possible due to
2037 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2038 * which index to pick. Anyway, other databases might have different
2039 * indexes on a given table. So don't bother overriding this unless you're
2041 * @param string $index
2044 public function ignoreIndexClause( $index ) {
2048 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2049 $quotedTable = $this->tableName( $table );
2051 if ( count( $rows ) == 0 ) {
2056 if ( !is_array( reset( $rows ) ) ) {
2060 // @FXIME: this is not atomic, but a trx would break affectedRows()
2061 foreach ( $rows as $row ) {
2062 # Delete rows which collide
2063 if ( $uniqueIndexes ) {
2064 $sql = "DELETE FROM $quotedTable WHERE ";
2066 foreach ( $uniqueIndexes as $index ) {
2073 if ( is_array( $index ) ) {
2075 foreach ( $index as $col ) {
2081 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2084 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2088 $this->query( $sql, $fname );
2091 # Now insert the row
2092 $this->insert( $table, $row, $fname );
2097 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2100 * @param string $table Table name
2101 * @param array|string $rows Row(s) to insert
2102 * @param string $fname Caller function name
2104 * @return ResultWrapper
2106 protected function nativeReplace( $table, $rows, $fname ) {
2107 $table = $this->tableName( $table );
2110 if ( !is_array( reset( $rows ) ) ) {
2114 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2117 foreach ( $rows as $row ) {
2124 $sql .= '(' . $this->makeList( $row ) . ')';
2127 return $this->query( $sql, $fname );
2130 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2133 if ( !count( $rows ) ) {
2134 return true; // nothing to do
2137 if ( !is_array( reset( $rows ) ) ) {
2141 if ( count( $uniqueIndexes ) ) {
2142 $clauses = []; // list WHERE clauses that each identify a single row
2143 foreach ( $rows as $row ) {
2144 foreach ( $uniqueIndexes as $index ) {
2145 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2146 $rowKey = []; // unique key to this row
2147 foreach ( $index as $column ) {
2148 $rowKey[$column] = $row[$column];
2150 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2153 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2158 $useTrx = !$this->mTrxLevel
;
2160 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2163 # Update any existing conflicting row(s)
2164 if ( $where !== false ) {
2165 $ok = $this->update( $table, $set, $where, $fname );
2169 # Now insert any non-conflicting row(s)
2170 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2171 } catch ( Exception
$e ) {
2173 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2178 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2184 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2188 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2191 $delTable = $this->tableName( $delTable );
2192 $joinTable = $this->tableName( $joinTable );
2193 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2194 if ( $conds != '*' ) {
2195 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2199 $this->query( $sql, $fname );
2202 public function textFieldSize( $table, $field ) {
2203 $table = $this->tableName( $table );
2204 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2205 $res = $this->query( $sql, __METHOD__
);
2206 $row = $this->fetchObject( $res );
2210 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2219 public function delete( $table, $conds, $fname = __METHOD__
) {
2221 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2224 $table = $this->tableName( $table );
2225 $sql = "DELETE FROM $table";
2227 if ( $conds != '*' ) {
2228 if ( is_array( $conds ) ) {
2229 $conds = $this->makeList( $conds, self
::LIST_AND
);
2231 $sql .= ' WHERE ' . $conds;
2234 return $this->query( $sql, $fname );
2237 public function insertSelect(
2238 $destTable, $srcTable, $varMap, $conds,
2239 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2241 if ( $this->cliMode
) {
2242 // For massive migrations with downtime, we don't want to select everything
2243 // into memory and OOM, so do all this native on the server side if possible.
2244 return $this->nativeInsertSelect(
2255 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2256 // on only the master (without needing row-based-replication). It also makes it easy to
2257 // know how big the INSERT is going to be.
2259 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2260 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2262 $selectOptions[] = 'FOR UPDATE';
2263 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2269 foreach ( $res as $row ) {
2270 $rows[] = (array)$row;
2273 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2276 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2277 $fname = __METHOD__
,
2278 $insertOptions = [], $selectOptions = []
2280 $destTable = $this->tableName( $destTable );
2282 if ( !is_array( $insertOptions ) ) {
2283 $insertOptions = [ $insertOptions ];
2286 $insertOptions = $this->makeInsertOptions( $insertOptions );
2288 if ( !is_array( $selectOptions ) ) {
2289 $selectOptions = [ $selectOptions ];
2292 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2295 if ( is_array( $srcTable ) ) {
2296 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2298 $srcTable = $this->tableName( $srcTable );
2301 $sql = "INSERT $insertOptions" .
2302 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2303 " SELECT $startOpts " . implode( ',', $varMap ) .
2304 " FROM $srcTable $useIndex $ignoreIndex ";
2306 if ( $conds != '*' ) {
2307 if ( is_array( $conds ) ) {
2308 $conds = $this->makeList( $conds, self
::LIST_AND
);
2310 $sql .= " WHERE $conds";
2313 $sql .= " $tailOpts";
2315 return $this->query( $sql, $fname );
2319 * Construct a LIMIT query with optional offset. This is used for query
2320 * pages. The SQL should be adjusted so that only the first $limit rows
2321 * are returned. If $offset is provided as well, then the first $offset
2322 * rows should be discarded, and the next $limit rows should be returned.
2323 * If the result of the query is not ordered, then the rows to be returned
2324 * are theoretically arbitrary.
2326 * $sql is expected to be a SELECT, if that makes a difference.
2328 * The version provided by default works in MySQL and SQLite. It will very
2329 * likely need to be overridden for most other DBMSes.
2331 * @param string $sql SQL query we will append the limit too
2332 * @param int $limit The SQL limit
2333 * @param int|bool $offset The SQL offset (default false)
2334 * @throws DBUnexpectedError
2337 public function limitResult( $sql, $limit, $offset = false ) {
2338 if ( !is_numeric( $limit ) ) {
2339 throw new DBUnexpectedError( $this,
2340 "Invalid non-numeric limit passed to limitResult()\n" );
2343 return "$sql LIMIT "
2344 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2348 public function unionSupportsOrderAndLimit() {
2349 return true; // True for almost every DB supported
2352 public function unionQueries( $sqls, $all ) {
2353 $glue = $all ?
') UNION ALL (' : ') UNION (';
2355 return '(' . implode( $glue, $sqls ) . ')';
2358 public function conditional( $cond, $trueVal, $falseVal ) {
2359 if ( is_array( $cond ) ) {
2360 $cond = $this->makeList( $cond, self
::LIST_AND
);
2363 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2366 public function strreplace( $orig, $old, $new ) {
2367 return "REPLACE({$orig}, {$old}, {$new})";
2370 public function getServerUptime() {
2374 public function wasDeadlock() {
2378 public function wasLockTimeout() {
2382 public function wasErrorReissuable() {
2386 public function wasReadOnlyError() {
2391 * Do not use this method outside of Database/DBError classes
2393 * @param integer|string $errno
2394 * @return bool Whether the given query error was a connection drop
2396 public function wasConnectionError( $errno ) {
2400 public function deadlockLoop() {
2401 $args = func_get_args();
2402 $function = array_shift( $args );
2403 $tries = self
::DEADLOCK_TRIES
;
2405 $this->begin( __METHOD__
);
2408 /** @var Exception $e */
2412 $retVal = call_user_func_array( $function, $args );
2414 } catch ( DBQueryError
$e ) {
2415 if ( $this->wasDeadlock() ) {
2416 // Retry after a randomized delay
2417 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2419 // Throw the error back up
2423 } while ( --$tries > 0 );
2425 if ( $tries <= 0 ) {
2426 // Too many deadlocks; give up
2427 $this->rollback( __METHOD__
);
2430 $this->commit( __METHOD__
);
2436 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2437 # Real waits are implemented in the subclass.
2441 public function getSlavePos() {
2446 public function getMasterPos() {
2451 public function serverIsReadOnly() {
2455 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2456 if ( !$this->mTrxLevel
) {
2457 throw new DBUnexpectedError( $this, "No transaction is active." );
2459 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2462 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2463 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2464 if ( !$this->mTrxLevel
) {
2465 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2469 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2470 if ( $this->mTrxLevel
) {
2471 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2473 // If no transaction is active, then make one for this callback
2474 $this->startAtomic( __METHOD__
);
2476 call_user_func( $callback );
2477 $this->endAtomic( __METHOD__
);
2478 } catch ( Exception
$e ) {
2479 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2485 final public function setTransactionListener( $name, callable
$callback = null ) {
2487 $this->mTrxRecurringCallbacks
[$name] = $callback;
2489 unset( $this->mTrxRecurringCallbacks
[$name] );
2494 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2496 * This method should not be used outside of Database/LoadBalancer
2498 * @param bool $suppress
2501 final public function setTrxEndCallbackSuppression( $suppress ) {
2502 $this->mTrxEndCallbacksSuppressed
= $suppress;
2506 * Actually run and consume any "on transaction idle/resolution" callbacks.
2508 * This method should not be used outside of Database/LoadBalancer
2510 * @param integer $trigger IDatabase::TRIGGER_* constant
2514 public function runOnTransactionIdleCallbacks( $trigger ) {
2515 if ( $this->mTrxEndCallbacksSuppressed
) {
2519 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2520 /** @var Exception $e */
2521 $e = null; // first exception
2522 do { // callbacks may add callbacks :)
2523 $callbacks = array_merge(
2524 $this->mTrxIdleCallbacks
,
2525 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2527 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2528 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2529 foreach ( $callbacks as $callback ) {
2531 list( $phpCallback ) = $callback;
2532 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2533 call_user_func_array( $phpCallback, [ $trigger ] );
2535 $this->setFlag( DBO_TRX
); // restore automatic begin()
2537 $this->clearFlag( DBO_TRX
); // restore auto-commit
2539 } catch ( Exception
$ex ) {
2540 call_user_func( $this->errorLogger
, $ex );
2542 // Some callbacks may use startAtomic/endAtomic, so make sure
2543 // their transactions are ended so other callbacks don't fail
2544 if ( $this->trxLevel() ) {
2545 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2549 } while ( count( $this->mTrxIdleCallbacks
) );
2551 if ( $e instanceof Exception
) {
2552 throw $e; // re-throw any first exception
2557 * Actually run and consume any "on transaction pre-commit" callbacks.
2559 * This method should not be used outside of Database/LoadBalancer
2564 public function runOnTransactionPreCommitCallbacks() {
2565 $e = null; // first exception
2566 do { // callbacks may add callbacks :)
2567 $callbacks = $this->mTrxPreCommitCallbacks
;
2568 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2569 foreach ( $callbacks as $callback ) {
2571 list( $phpCallback ) = $callback;
2572 call_user_func( $phpCallback );
2573 } catch ( Exception
$ex ) {
2574 call_user_func( $this->errorLogger
, $ex );
2578 } while ( count( $this->mTrxPreCommitCallbacks
) );
2580 if ( $e instanceof Exception
) {
2581 throw $e; // re-throw any first exception
2586 * Actually run any "transaction listener" callbacks.
2588 * This method should not be used outside of Database/LoadBalancer
2590 * @param integer $trigger IDatabase::TRIGGER_* constant
2594 public function runTransactionListenerCallbacks( $trigger ) {
2595 if ( $this->mTrxEndCallbacksSuppressed
) {
2599 /** @var Exception $e */
2600 $e = null; // first exception
2602 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2604 $phpCallback( $trigger, $this );
2605 } catch ( Exception
$ex ) {
2606 call_user_func( $this->errorLogger
, $ex );
2611 if ( $e instanceof Exception
) {
2612 throw $e; // re-throw any first exception
2616 final public function startAtomic( $fname = __METHOD__
) {
2617 if ( !$this->mTrxLevel
) {
2618 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2619 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2620 // in all changes being in one transaction to keep requests transactional.
2621 if ( !$this->getFlag( DBO_TRX
) ) {
2622 $this->mTrxAutomaticAtomic
= true;
2626 $this->mTrxAtomicLevels
[] = $fname;
2629 final public function endAtomic( $fname = __METHOD__
) {
2630 if ( !$this->mTrxLevel
) {
2631 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2633 if ( !$this->mTrxAtomicLevels ||
2634 array_pop( $this->mTrxAtomicLevels
) !== $fname
2636 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2639 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2640 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2644 final public function doAtomicSection( $fname, callable
$callback ) {
2645 $this->startAtomic( $fname );
2647 $res = call_user_func_array( $callback, [ $this, $fname ] );
2648 } catch ( Exception
$e ) {
2649 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2652 $this->endAtomic( $fname );
2657 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2658 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2659 if ( $this->mTrxLevel
) {
2660 if ( $this->mTrxAtomicLevels
) {
2661 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2662 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2663 throw new DBUnexpectedError( $this, $msg );
2664 } elseif ( !$this->mTrxAutomatic
) {
2665 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2666 throw new DBUnexpectedError( $this, $msg );
2668 // @TODO: make this an exception at some point
2669 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2670 $this->queryLogger
->error( $msg );
2671 return; // join the main transaction set
2673 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2674 // @TODO: make this an exception at some point
2675 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2676 $this->queryLogger
->error( $msg );
2677 return; // let any writes be in the main transaction
2680 // Avoid fatals if close() was called
2681 $this->assertOpen();
2683 $this->doBegin( $fname );
2684 $this->mTrxTimestamp
= microtime( true );
2685 $this->mTrxFname
= $fname;
2686 $this->mTrxDoneWrites
= false;
2687 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2688 $this->mTrxAutomaticAtomic
= false;
2689 $this->mTrxAtomicLevels
= [];
2690 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2691 $this->mTrxWriteDuration
= 0.0;
2692 $this->mTrxWriteQueryCount
= 0;
2693 $this->mTrxWriteAdjDuration
= 0.0;
2694 $this->mTrxWriteAdjQueryCount
= 0;
2695 $this->mTrxWriteCallers
= [];
2696 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2697 // Get an estimate of the replica DB lag before then, treating estimate staleness
2698 // as lag itself just to be safe
2699 $status = $this->getApproximateLagStatus();
2700 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2704 * Issues the BEGIN command to the database server.
2706 * @see DatabaseBase::begin()
2707 * @param string $fname
2709 protected function doBegin( $fname ) {
2710 $this->query( 'BEGIN', $fname );
2711 $this->mTrxLevel
= 1;
2714 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2715 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2716 // There are still atomic sections open. This cannot be ignored
2717 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2718 throw new DBUnexpectedError(
2720 "$fname: Got COMMIT while atomic sections $levels are still open."
2724 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2725 if ( !$this->mTrxLevel
) {
2726 return; // nothing to do
2727 } elseif ( !$this->mTrxAutomatic
) {
2728 throw new DBUnexpectedError(
2730 "$fname: Flushing an explicit transaction, getting out of sync."
2734 if ( !$this->mTrxLevel
) {
2735 $this->queryLogger
->error(
2736 "$fname: No transaction to commit, something got out of sync." );
2737 return; // nothing to do
2738 } elseif ( $this->mTrxAutomatic
) {
2739 // @TODO: make this an exception at some point
2740 $msg = "$fname: Explicit commit of implicit transaction.";
2741 $this->queryLogger
->error( $msg );
2742 return; // wait for the main transaction set commit round
2746 // Avoid fatals if close() was called
2747 $this->assertOpen();
2749 $this->runOnTransactionPreCommitCallbacks();
2750 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2751 $this->doCommit( $fname );
2752 if ( $this->mTrxDoneWrites
) {
2753 $this->mDoneWrites
= microtime( true );
2754 $this->trxProfiler
->transactionWritingOut(
2755 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2758 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2759 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2763 * Issues the COMMIT command to the database server.
2765 * @see DatabaseBase::commit()
2766 * @param string $fname
2768 protected function doCommit( $fname ) {
2769 if ( $this->mTrxLevel
) {
2770 $this->query( 'COMMIT', $fname );
2771 $this->mTrxLevel
= 0;
2775 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2776 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2777 if ( !$this->mTrxLevel
) {
2778 return; // nothing to do
2781 if ( !$this->mTrxLevel
) {
2782 $this->queryLogger
->error(
2783 "$fname: No transaction to rollback, something got out of sync." );
2784 return; // nothing to do
2785 } elseif ( $this->getFlag( DBO_TRX
) ) {
2786 throw new DBUnexpectedError(
2788 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2793 // Avoid fatals if close() was called
2794 $this->assertOpen();
2796 $this->doRollback( $fname );
2797 $this->mTrxAtomicLevels
= [];
2798 if ( $this->mTrxDoneWrites
) {
2799 $this->trxProfiler
->transactionWritingOut(
2800 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2803 $this->mTrxIdleCallbacks
= []; // clear
2804 $this->mTrxPreCommitCallbacks
= []; // clear
2805 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2806 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2810 * Issues the ROLLBACK command to the database server.
2812 * @see DatabaseBase::rollback()
2813 * @param string $fname
2815 protected function doRollback( $fname ) {
2816 if ( $this->mTrxLevel
) {
2817 # Disconnects cause rollback anyway, so ignore those errors
2818 $ignoreErrors = true;
2819 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2820 $this->mTrxLevel
= 0;
2824 public function flushSnapshot( $fname = __METHOD__
) {
2825 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2826 // This only flushes transactions to clear snapshots, not to write data
2827 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2828 throw new DBUnexpectedError(
2830 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2834 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2837 public function explicitTrxActive() {
2838 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2842 * Creates a new table with structure copied from existing table
2843 * Note that unlike most database abstraction functions, this function does not
2844 * automatically append database prefix, because it works at a lower
2845 * abstraction level.
2846 * The table names passed to this function shall not be quoted (this
2847 * function calls addIdentifierQuotes when needed).
2849 * @param string $oldName Name of table whose structure should be copied
2850 * @param string $newName Name of table to be created
2851 * @param bool $temporary Whether the new table should be temporary
2852 * @param string $fname Calling function name
2853 * @throws RuntimeException
2854 * @return bool True if operation was successful
2856 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2859 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2862 public function listTables( $prefix = null, $fname = __METHOD__
) {
2863 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2867 * Reset the views process cache set by listViews()
2870 final public function clearViewsCache() {
2871 $this->allViews
= null;
2874 public function listViews( $prefix = null, $fname = __METHOD__
) {
2875 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2879 * Differentiates between a TABLE and a VIEW
2881 * @param string $name Name of the database-structure to test.
2882 * @throws RuntimeException
2886 public function isView( $name ) {
2887 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2890 public function timestamp( $ts = 0 ) {
2891 $t = new ConvertibleTimestamp( $ts );
2892 // Let errors bubble up to avoid putting garbage in the DB
2893 return $t->getTimestamp( TS_MW
);
2896 public function timestampOrNull( $ts = null ) {
2897 if ( is_null( $ts ) ) {
2900 return $this->timestamp( $ts );
2905 * Take the result from a query, and wrap it in a ResultWrapper if
2906 * necessary. Boolean values are passed through as is, to indicate success
2907 * of write queries or failure.
2909 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2910 * resource, and it was necessary to call this function to convert it to
2911 * a wrapper. Nowadays, raw database objects are never exposed to external
2912 * callers, so this is unnecessary in external code.
2914 * @param bool|ResultWrapper|resource|object $result
2915 * @return bool|ResultWrapper
2917 protected function resultObject( $result ) {
2920 } elseif ( $result instanceof ResultWrapper
) {
2922 } elseif ( $result === true ) {
2923 // Successful write query
2926 return new ResultWrapper( $this, $result );
2930 public function ping( &$rtt = null ) {
2931 // Avoid hitting the server if it was hit recently
2932 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
2933 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
2934 $rtt = $this->mRTTEstimate
;
2935 return true; // don't care about $rtt
2939 // This will reconnect if possible or return false if not
2940 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
2941 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
2942 $this->restoreFlags( self
::RESTORE_PRIOR
);
2945 $rtt = $this->mRTTEstimate
;
2954 protected function reconnect() {
2955 $this->closeConnection();
2956 $this->mOpened
= false;
2957 $this->mConn
= false;
2959 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2960 $this->lastPing
= microtime( true );
2962 } catch ( DBConnectionError
$e ) {
2969 public function getSessionLagStatus() {
2970 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2974 * Get the replica DB lag when the current transaction started
2976 * This is useful when transactions might use snapshot isolation
2977 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2978 * is this lag plus transaction duration. If they don't, it is still
2979 * safe to be pessimistic. This returns null if there is no transaction.
2981 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2984 protected function getTransactionLagStatus() {
2985 return $this->mTrxLevel
2986 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
2991 * Get a replica DB lag estimate for this server
2993 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2996 protected function getApproximateLagStatus() {
2998 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
2999 'since' => microtime( true )
3004 * Merge the result of getSessionLagStatus() for several DBs
3005 * using the most pessimistic values to estimate the lag of
3006 * any data derived from them in combination
3008 * This is information is useful for caching modules
3010 * @see WANObjectCache::set()
3011 * @see WANObjectCache::getWithSetCallback()
3013 * @param IDatabase $db1
3014 * @param IDatabase ...
3015 * @return array Map of values:
3016 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3017 * - since: oldest UNIX timestamp of any of the DB lag estimates
3018 * - pending: whether any of the DBs have uncommitted changes
3021 public static function getCacheSetOptions( IDatabase
$db1 ) {
3022 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3023 foreach ( func_get_args() as $db ) {
3024 /** @var IDatabase $db */
3025 $status = $db->getSessionLagStatus();
3026 if ( $status['lag'] === false ) {
3027 $res['lag'] = false;
3028 } elseif ( $res['lag'] !== false ) {
3029 $res['lag'] = max( $res['lag'], $status['lag'] );
3031 $res['since'] = min( $res['since'], $status['since'] );
3032 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3038 public function getLag() {
3042 public function maxListLen() {
3046 public function encodeBlob( $b ) {
3050 public function decodeBlob( $b ) {
3051 if ( $b instanceof Blob
) {
3057 public function setSessionOptions( array $options ) {
3060 public function sourceFile(
3062 $lineCallback = false,
3063 $resultCallback = false,
3065 $inputCallback = false
3067 MediaWiki\
suppressWarnings();
3068 $fp = fopen( $filename, 'r' );
3069 MediaWiki\restoreWarnings
();
3071 if ( false === $fp ) {
3072 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3076 $fname = __METHOD__
. "( $filename )";
3080 $error = $this->sourceStream(
3081 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3082 } catch ( Exception
$e ) {
3092 public function setSchemaVars( $vars ) {
3093 $this->mSchemaVars
= $vars;
3096 public function sourceStream(
3098 $lineCallback = false,
3099 $resultCallback = false,
3100 $fname = __METHOD__
,
3101 $inputCallback = false
3105 while ( !feof( $fp ) ) {
3106 if ( $lineCallback ) {
3107 call_user_func( $lineCallback );
3110 $line = trim( fgets( $fp ) );
3112 if ( $line == '' ) {
3116 if ( '-' == $line[0] && '-' == $line[1] ) {
3124 $done = $this->streamStatementEnd( $cmd, $line );
3128 if ( $done ||
feof( $fp ) ) {
3129 $cmd = $this->replaceVars( $cmd );
3131 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3132 $res = $this->query( $cmd, $fname );
3134 if ( $resultCallback ) {
3135 call_user_func( $resultCallback, $res, $this );
3138 if ( false === $res ) {
3139 $err = $this->lastError();
3141 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3152 * Called by sourceStream() to check if we've reached a statement end
3154 * @param string &$sql SQL assembled so far
3155 * @param string &$newLine New line about to be added to $sql
3156 * @return bool Whether $newLine contains end of the statement
3158 public function streamStatementEnd( &$sql, &$newLine ) {
3159 if ( $this->delimiter
) {
3161 $newLine = preg_replace(
3162 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3163 if ( $newLine != $prev ) {
3172 * Database independent variable replacement. Replaces a set of variables
3173 * in an SQL statement with their contents as given by $this->getSchemaVars().
3175 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3177 * - '{$var}' should be used for text and is passed through the database's
3179 * - `{$var}` should be used for identifiers (e.g. table and database names).
3180 * It is passed through the database's addIdentifierQuotes method which
3181 * can be overridden if the database uses something other than backticks.
3182 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3183 * database's tableName method.
3184 * - / *i* / passes the name that follows through the database's indexName method.
3185 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3186 * its use should be avoided. In 1.24 and older, string encoding was applied.
3188 * @param string $ins SQL statement to replace variables in
3189 * @return string The new SQL statement with variables replaced
3191 protected function replaceVars( $ins ) {
3192 $vars = $this->getSchemaVars();
3193 return preg_replace_callback(
3195 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3196 \'\{\$ (\w+) }\' | # 3. addQuotes
3197 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3198 /\*\$ (\w+) \*/ # 5. leave unencoded
3200 function ( $m ) use ( $vars ) {
3201 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3202 // check for both nonexistent keys *and* the empty string.
3203 if ( isset( $m[1] ) && $m[1] !== '' ) {
3204 if ( $m[1] === 'i' ) {
3205 return $this->indexName( $m[2] );
3207 return $this->tableName( $m[2] );
3209 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3210 return $this->addQuotes( $vars[$m[3]] );
3211 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3212 return $this->addIdentifierQuotes( $vars[$m[4]] );
3213 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3214 return $vars[$m[5]];
3224 * Get schema variables. If none have been set via setSchemaVars(), then
3225 * use some defaults from the current object.
3229 protected function getSchemaVars() {
3230 if ( $this->mSchemaVars
) {
3231 return $this->mSchemaVars
;
3233 return $this->getDefaultSchemaVars();
3238 * Get schema variables to use if none have been set via setSchemaVars().
3240 * Override this in derived classes to provide variables for tables.sql
3241 * and SQL patch files.
3245 protected function getDefaultSchemaVars() {
3249 public function lockIsFree( $lockName, $method ) {
3253 public function lock( $lockName, $method, $timeout = 5 ) {
3254 $this->mNamedLocksHeld
[$lockName] = 1;
3259 public function unlock( $lockName, $method ) {
3260 unset( $this->mNamedLocksHeld
[$lockName] );
3265 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3266 if ( $this->writesOrCallbacksPending() ) {
3267 // This only flushes transactions to clear snapshots, not to write data
3268 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3269 throw new DBUnexpectedError(
3271 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3275 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3279 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3280 if ( $this->trxLevel() ) {
3281 // There is a good chance an exception was thrown, causing any early return
3282 // from the caller. Let any error handler get a chance to issue rollback().
3283 // If there isn't one, let the error bubble up and trigger server-side rollback.
3284 $this->onTransactionResolution(
3285 function () use ( $lockKey, $fname ) {
3286 $this->unlock( $lockKey, $fname );
3291 $this->unlock( $lockKey, $fname );
3295 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3300 public function namedLocksEnqueue() {
3305 * Lock specific tables
3307 * @param array $read Array of tables to lock for read access
3308 * @param array $write Array of tables to lock for write access
3309 * @param string $method Name of caller
3310 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3313 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3318 * Unlock specific tables
3320 * @param string $method The caller
3323 public function unlockTables( $method ) {
3329 * @param string $tableName
3330 * @param string $fName
3331 * @return bool|ResultWrapper
3334 public function dropTable( $tableName, $fName = __METHOD__
) {
3335 if ( !$this->tableExists( $tableName, $fName ) ) {
3338 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3340 return $this->query( $sql, $fName );
3343 public function getInfinity() {
3347 public function encodeExpiry( $expiry ) {
3348 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3349 ?
$this->getInfinity()
3350 : $this->timestamp( $expiry );
3353 public function decodeExpiry( $expiry, $format = TS_MW
) {
3354 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3358 return ConvertibleTimestamp
::convert( $format, $expiry );
3361 public function setBigSelects( $value = true ) {
3365 public function isReadOnly() {
3366 return ( $this->getReadOnlyReason() !== false );
3370 * @return string|bool Reason this DB is read-only or false if it is not
3372 protected function getReadOnlyReason() {
3373 $reason = $this->getLBInfo( 'readOnlyReason' );
3375 return is_string( $reason ) ?
$reason : false;
3378 public function setTableAliases( array $aliases ) {
3379 $this->tableAliases
= $aliases;
3383 * @return bool Whether a DB user is required to access the DB
3386 protected function requiresDatabaseUser() {
3394 public function __toString() {
3395 return (string)$this->mConn
;
3399 * Make sure that copies do not share the same client binding handle
3400 * @throws DBConnectionError
3402 public function __clone() {
3403 $this->connLogger
->warning(
3404 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3405 ( new RuntimeException() )->getTraceAsString()
3408 if ( $this->isOpen() ) {
3409 // Open a new connection resource without messing with the old one
3410 $this->mOpened
= false;
3411 $this->mConn
= false;
3412 $this->mTrxEndCallbacks
= []; // don't copy
3413 $this->handleSessionLoss(); // no trx or locks anymore
3414 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3415 $this->lastPing
= microtime( true );
3420 * Called by serialize. Throw an exception when DB connection is serialized.
3421 * This causes problems on some database engines because the connection is
3422 * not restored on unserialize.
3424 public function __sleep() {
3425 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3426 'the connection is not restored on wakeup.' );
3430 * Run a few simple sanity checks and close dangling connections
3432 public function __destruct() {
3433 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3434 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3437 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3438 if ( $danglingWriters ) {
3439 $fnames = implode( ', ', $danglingWriters );
3440 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3443 if ( $this->mConn
) {
3444 // Avoid connection leaks for sanity
3445 $this->closeConnection();
3446 $this->mConn
= false;
3447 $this->mOpened
= false;