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 * Database abstraction object
33 abstract class Database
implements IDatabase
, LoggerAwareInterface
{
34 /** Number of times to re-try an operation in case of deadlock */
35 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
38 /** Maximum time to wait before retry */
39 const DEADLOCK_DELAY_MAX
= 1500000;
41 /** How long before it is worth doing a dummy query to test the connection */
43 const PING_QUERY
= 'SELECT 1 AS ping';
45 const TINY_WRITE_SEC
= .010;
46 const SLOW_WRITE_SEC
= .500;
47 const SMALL_WRITE_ROWS
= 100;
49 /** @var string SQL query */
50 protected $mLastQuery = '';
52 protected $mDoneWrites = false;
53 /** @var string|bool */
54 protected $mPHPError = false;
63 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
64 protected $tableAliases = [];
65 /** @var bool Whether this PHP instance is for a CLI script */
67 /** @var string Agent name for query profiling */
70 /** @var BagOStuff APC cache */
72 /** @var LoggerInterface */
73 protected $connLogger;
74 /** @var LoggerInterface */
75 protected $queryLogger;
76 /** @var callback Error logging callback */
77 protected $errorLogger;
79 /** @var resource Database connection */
80 protected $mConn = null;
82 protected $mOpened = false;
84 /** @var array[] List of (callable, method name) */
85 protected $mTrxIdleCallbacks = [];
86 /** @var array[] List of (callable, method name) */
87 protected $mTrxPreCommitCallbacks = [];
88 /** @var array[] List of (callable, method name) */
89 protected $mTrxEndCallbacks = [];
90 /** @var callable[] Map of (name => callable) */
91 protected $mTrxRecurringCallbacks = [];
92 /** @var bool Whether to suppress triggering of transaction end callbacks */
93 protected $mTrxEndCallbacksSuppressed = false;
96 protected $mTablePrefix = '';
98 protected $mSchema = '';
102 protected $mLBInfo = [];
103 /** @var bool|null */
104 protected $mDefaultBigSelects = null;
105 /** @var array|bool */
106 protected $mSchemaVars = false;
108 protected $mSessionVars = [];
109 /** @var array|null */
110 protected $preparedArgs;
111 /** @var string|bool|null Stashed value of html_errors INI setting */
112 protected $htmlErrors;
114 protected $delimiter = ';';
115 /** @var DatabaseDomain */
116 protected $currentDomain;
119 * Either 1 if a transaction is active or 0 otherwise.
120 * The other Trx fields may not be meaningfull if this is 0.
124 protected $mTrxLevel = 0;
126 * Either a short hexidecimal string if a transaction is active or ""
129 * @see DatabaseBase::mTrxLevel
131 protected $mTrxShortId = '';
133 * The UNIX time that the transaction started. Callers can assume that if
134 * snapshot isolation is used, then the data is *at least* up to date to that
135 * point (possibly more up-to-date since the first SELECT defines the snapshot).
138 * @see DatabaseBase::mTrxLevel
140 private $mTrxTimestamp = null;
141 /** @var float Lag estimate at the time of BEGIN */
142 private $mTrxReplicaLag = null;
144 * Remembers the function name given for starting the most recent transaction via begin().
145 * Used to provide additional context for error reporting.
148 * @see DatabaseBase::mTrxLevel
150 private $mTrxFname = null;
152 * Record if possible write queries were done in the last transaction started
155 * @see DatabaseBase::mTrxLevel
157 private $mTrxDoneWrites = false;
159 * Record if the current transaction was started implicitly due to DBO_TRX being set.
162 * @see DatabaseBase::mTrxLevel
164 private $mTrxAutomatic = false;
166 * Array of levels of atomicity within transactions
170 private $mTrxAtomicLevels = [];
172 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
176 private $mTrxAutomaticAtomic = false;
178 * Track the write query callers of the current transaction
182 private $mTrxWriteCallers = [];
184 * @var float Seconds spent in write queries for the current transaction
186 private $mTrxWriteDuration = 0.0;
188 * @var integer Number of write queries for the current transaction
190 private $mTrxWriteQueryCount = 0;
192 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
194 private $mTrxWriteAdjDuration = 0.0;
196 * @var integer Number of write queries counted in mTrxWriteAdjDuration
198 private $mTrxWriteAdjQueryCount = 0;
200 * @var float RTT time estimate
202 private $mRTTEstimate = 0.0;
204 /** @var array Map of (name => 1) for locks obtained via lock() */
205 private $mNamedLocksHeld = [];
206 /** @var array Map of (table name => 1) for TEMPORARY tables */
207 protected $mSessionTempTables = [];
209 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
210 private $lazyMasterHandle;
214 * @var string[] Process cache of VIEWs names in the database
216 protected $allViews = null;
218 /** @var float UNIX timestamp */
219 protected $lastPing = 0.0;
221 /** @var int[] Prior mFlags values */
222 private $priorFlags = [];
224 /** @var object|string Class name or object With profileIn/profileOut methods */
226 /** @var TransactionProfiler */
227 protected $trxProfiler;
230 * Constructor and database handle and attempt to connect to the DB server
232 * IDatabase classes should not be constructed directly in external
233 * code. Database::factory() should be used instead.
235 * @param array $params Parameters passed from Database::factory()
237 function __construct( array $params ) {
238 $server = $params['host'];
239 $user = $params['user'];
240 $password = $params['password'];
241 $dbName = $params['dbname'];
243 $this->mSchema
= $params['schema'];
244 $this->mTablePrefix
= $params['tablePrefix'];
246 $this->cliMode
= $params['cliMode'];
247 // Agent name is added to SQL queries in a comment, so make sure it can't break out
248 $this->agent
= str_replace( '/', '-', $params['agent'] );
250 $this->mFlags
= $params['flags'];
251 if ( $this->mFlags
& DBO_DEFAULT
) {
252 if ( $this->cliMode
) {
253 $this->mFlags
&= ~DBO_TRX
;
255 $this->mFlags |
= DBO_TRX
;
259 $this->mSessionVars
= $params['variables'];
261 $this->srvCache
= isset( $params['srvCache'] )
262 ?
$params['srvCache']
263 : new HashBagOStuff();
265 $this->profiler
= $params['profiler'];
266 $this->trxProfiler
= $params['trxProfiler'];
267 $this->connLogger
= $params['connLogger'];
268 $this->queryLogger
= $params['queryLogger'];
270 // Set initial dummy domain until open() sets the final DB/prefix
271 $this->currentDomain
= DatabaseDomain
::newUnspecified();
274 $this->open( $server, $user, $password, $dbName );
275 } elseif ( $this->requiresDatabaseUser() ) {
276 throw new InvalidArgumentException( "No database user provided." );
279 // Set the domain object after open() sets the relevant fields
280 if ( $this->mDBname
!= '' ) {
281 // Domains with server scope but a table prefix are not used by IDatabase classes
282 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
287 * Construct a Database subclass instance given a database type and parameters
289 * This also connects to the database immediately upon object construction
291 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
292 * @param array $p Parameter map with keys:
293 * - host : The hostname of the DB server
294 * - user : The name of the database user the client operates under
295 * - password : The password for the database user
296 * - dbname : The name of the database to use where queries do not specify one.
297 * The database must exist or an error might be thrown. Setting this to the empty string
298 * will avoid any such errors and make the handle have no implicit database scope. This is
299 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
300 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
301 * in which user names and such are defined, e.g. users are database-specific in Postgres.
302 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
303 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
304 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
305 * recognized in queries. This can be used in place of schemas for handle site farms.
306 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
307 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
308 * flag in place UNLESS this this database simply acts as a key/value store.
309 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
310 * 'mysql' driver and the newer 'mysqli' driver.
311 * - variables: Optional map of session variables to set after connecting. This can be
312 * used to adjust lock timeouts or encoding modes and the like.
313 * - connLogger: Optional PSR-3 logger interface instance.
314 * - queryLogger: Optional PSR-3 logger interface instance.
315 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
316 * These will be called in query(), using a simplified version of the SQL that also
317 * includes the agent as a SQL comment.
318 * - trxProfiler: Optional TransactionProfiler instance.
319 * - errorLogger: Optional callback that takes an Exception and logs it.
320 * - cliMode: Whether to consider the execution context that of a CLI script.
321 * - agent: Optional name used to identify the end-user in query profiling/logging.
322 * - srvCache: Optional BagOStuff instance to an APC-style cache.
323 * @return Database|null If the database driver or extension cannot be found
324 * @throws InvalidArgumentException If the database driver or extension cannot be found
327 final public static function factory( $dbType, $p = [] ) {
328 static $canonicalDBTypes = [
329 'mysql' => [ 'mysqli', 'mysql' ],
337 $dbType = strtolower( $dbType );
338 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
339 $possibleDrivers = $canonicalDBTypes[$dbType];
340 if ( !empty( $p['driver'] ) ) {
341 if ( in_array( $p['driver'], $possibleDrivers ) ) {
342 $driver = $p['driver'];
344 throw new InvalidArgumentException( __METHOD__
.
345 " type '$dbType' does not support driver '{$p['driver']}'" );
348 foreach ( $possibleDrivers as $posDriver ) {
349 if ( extension_loaded( $posDriver ) ) {
350 $driver = $posDriver;
358 if ( $driver === false ) {
359 throw new InvalidArgumentException( __METHOD__
.
360 " no viable database extension found for type '$dbType'" );
363 $class = 'Database' . ucfirst( $driver );
364 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
365 // Resolve some defaults for b/c
366 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
367 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
368 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
369 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
370 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
371 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
372 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
373 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
374 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
375 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
376 if ( !isset( $p['connLogger'] ) ) {
377 $p['connLogger'] = new \Psr\Log\
NullLogger();
379 if ( !isset( $p['queryLogger'] ) ) {
380 $p['queryLogger'] = new \Psr\Log\
NullLogger();
382 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
383 if ( !isset( $p['trxProfiler'] ) ) {
384 $p['trxProfiler'] = new TransactionProfiler();
386 if ( !isset( $p['errorLogger'] ) ) {
387 $p['errorLogger'] = function ( Exception
$e ) {
388 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
392 $conn = new $class( $p );
400 public function setLogger( LoggerInterface
$logger ) {
401 $this->queryLogger
= $logger;
404 public function getServerInfo() {
405 return $this->getServerVersion();
408 public function bufferResults( $buffer = null ) {
409 $res = !$this->getFlag( DBO_NOBUFFER
);
410 if ( $buffer !== null ) {
411 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
418 * Turns on (false) or off (true) the automatic generation and sending
419 * of a "we're sorry, but there has been a database error" page on
420 * database errors. Default is on (false). When turned off, the
421 * code should use lastErrno() and lastError() to handle the
422 * situation as appropriate.
424 * Do not use this function outside of the Database classes.
426 * @param null|bool $ignoreErrors
427 * @return bool The previous value of the flag.
429 protected function ignoreErrors( $ignoreErrors = null ) {
430 $res = $this->getFlag( DBO_IGNORE
);
431 if ( $ignoreErrors !== null ) {
432 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
438 public function trxLevel() {
439 return $this->mTrxLevel
;
442 public function trxTimestamp() {
443 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
446 public function tablePrefix( $prefix = null ) {
447 $old = $this->mTablePrefix
;
448 if ( $prefix !== null ) {
449 $this->mTablePrefix
= $prefix;
450 $this->currentDomain
= ( $this->mDBname
!= '' )
451 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
452 : DatabaseDomain
::newUnspecified();
458 public function dbSchema( $schema = null ) {
459 $old = $this->mSchema
;
460 if ( $schema !== null ) {
461 $this->mSchema
= $schema;
467 public function getLBInfo( $name = null ) {
468 if ( is_null( $name ) ) {
469 return $this->mLBInfo
;
471 if ( array_key_exists( $name, $this->mLBInfo
) ) {
472 return $this->mLBInfo
[$name];
479 public function setLBInfo( $name, $value = null ) {
480 if ( is_null( $value ) ) {
481 $this->mLBInfo
= $name;
483 $this->mLBInfo
[$name] = $value;
487 public function setLazyMasterHandle( IDatabase
$conn ) {
488 $this->lazyMasterHandle
= $conn;
492 * @return IDatabase|null
493 * @see setLazyMasterHandle()
496 public function getLazyMasterHandle() {
497 return $this->lazyMasterHandle
;
500 public function implicitGroupby() {
504 public function implicitOrderby() {
508 public function lastQuery() {
509 return $this->mLastQuery
;
512 public function doneWrites() {
513 return (bool)$this->mDoneWrites
;
516 public function lastDoneWrites() {
517 return $this->mDoneWrites ?
: false;
520 public function writesPending() {
521 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
524 public function writesOrCallbacksPending() {
525 return $this->mTrxLevel
&& (
526 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
530 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
531 if ( !$this->mTrxLevel
) {
533 } elseif ( !$this->mTrxDoneWrites
) {
538 case self
::ESTIMATE_DB_APPLY
:
540 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
541 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
542 // For omitted queries, make them count as something at least
543 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
544 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
547 default: // everything
548 return $this->mTrxWriteDuration
;
552 public function pendingWriteCallers() {
553 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
556 protected function pendingWriteAndCallbackCallers() {
557 if ( !$this->mTrxLevel
) {
561 $fnames = $this->mTrxWriteCallers
;
563 $this->mTrxIdleCallbacks
,
564 $this->mTrxPreCommitCallbacks
,
565 $this->mTrxEndCallbacks
567 foreach ( $callbacks as $callback ) {
568 $fnames[] = $callback[1];
575 public function isOpen() {
576 return $this->mOpened
;
579 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
580 if ( $remember === self
::REMEMBER_PRIOR
) {
581 array_push( $this->priorFlags
, $this->mFlags
);
583 $this->mFlags |
= $flag;
586 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
587 if ( $remember === self
::REMEMBER_PRIOR
) {
588 array_push( $this->priorFlags
, $this->mFlags
);
590 $this->mFlags
&= ~
$flag;
593 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
594 if ( !$this->priorFlags
) {
598 if ( $state === self
::RESTORE_INITIAL
) {
599 $this->mFlags
= reset( $this->priorFlags
);
600 $this->priorFlags
= [];
602 $this->mFlags
= array_pop( $this->priorFlags
);
606 public function getFlag( $flag ) {
607 return !!( $this->mFlags
& $flag );
610 public function getProperty( $name ) {
614 public function getDomainID() {
615 return $this->currentDomain
->getId();
618 final public function getWikiID() {
619 return $this->getDomainID();
623 * Get information about an index into an object
624 * @param string $table Table name
625 * @param string $index Index name
626 * @param string $fname Calling function name
627 * @return mixed Database-specific index description class or false if the index does not exist
629 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
632 * Wrapper for addslashes()
634 * @param string $s String to be slashed.
635 * @return string Slashed string.
637 abstract function strencode( $s );
639 protected function installErrorHandler() {
640 $this->mPHPError
= false;
641 $this->htmlErrors
= ini_set( 'html_errors', '0' );
642 set_error_handler( [ $this, 'connectionErrorLogger' ] );
646 * @return bool|string
648 protected function restoreErrorHandler() {
649 restore_error_handler();
650 if ( $this->htmlErrors
!== false ) {
651 ini_set( 'html_errors', $this->htmlErrors
);
653 if ( $this->mPHPError
) {
654 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
655 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
664 * This method should not be used outside of Database classes
667 * @param string $errstr
669 public function connectionErrorLogger( $errno, $errstr ) {
670 $this->mPHPError
= $errstr;
674 * Create a log context to pass to PSR-3 logger functions.
676 * @param array $extras Additional data to add to context
679 protected function getLogContext( array $extras = [] ) {
682 'db_server' => $this->mServer
,
683 'db_name' => $this->mDBname
,
684 'db_user' => $this->mUser
,
690 public function close() {
691 if ( $this->mConn
) {
692 if ( $this->trxLevel() ) {
693 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
696 $closed = $this->closeConnection();
697 $this->mConn
= false;
698 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
699 throw new RuntimeException( "Transaction callbacks still pending." );
703 $this->mOpened
= false;
709 * Make sure isOpen() returns true as a sanity check
711 * @throws DBUnexpectedError
713 protected function assertOpen() {
714 if ( !$this->isOpen() ) {
715 throw new DBUnexpectedError( $this, "DB connection was already closed." );
720 * Closes underlying database connection
722 * @return bool Whether connection was closed successfully
724 abstract protected function closeConnection();
726 public function reportConnectionError( $error = 'Unknown error' ) {
727 $myError = $this->lastError();
733 throw new DBConnectionError( $this, $error );
737 * The DBMS-dependent part of query()
739 * @param string $sql SQL query.
740 * @return ResultWrapper|bool Result object to feed to fetchObject,
741 * fetchRow, ...; or false on failure
743 abstract protected function doQuery( $sql );
746 * Determine whether a query writes to the DB.
747 * Should return true if unsure.
752 protected function isWriteQuery( $sql ) {
754 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
759 * @return string|null
761 protected function getQueryVerb( $sql ) {
762 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
766 * Determine whether a SQL statement is sensitive to isolation level.
767 * A SQL statement is considered transactable if its result could vary
768 * depending on the transaction isolation level. Operational commands
769 * such as 'SET' and 'SHOW' are not considered to be transactable.
774 protected function isTransactableQuery( $sql ) {
775 $verb = $this->getQueryVerb( $sql );
776 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
780 * @param string $sql A SQL query
781 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
783 protected function registerTempTableOperation( $sql ) {
785 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
789 $this->mSessionTempTables
[$matches[1]] = 1;
792 } elseif ( preg_match(
793 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
797 unset( $this->mSessionTempTables
[$matches[1]] );
800 } elseif ( preg_match(
801 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
805 return isset( $this->mSessionTempTables
[$matches[1]] );
811 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
812 $priorWritesPending = $this->writesOrCallbacksPending();
813 $this->mLastQuery
= $sql;
815 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
817 $reason = $this->getReadOnlyReason();
818 if ( $reason !== false ) {
819 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
821 # Set a flag indicating that writes have been done
822 $this->mDoneWrites
= microtime( true );
825 // Add trace comment to the begin of the sql string, right after the operator.
826 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
827 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
829 # Start implicit transactions that wrap the request if DBO_TRX is enabled
830 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
831 && $this->isTransactableQuery( $sql )
833 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
834 $this->mTrxAutomatic
= true;
837 # Keep track of whether the transaction has write queries pending
838 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
839 $this->mTrxDoneWrites
= true;
840 $this->trxProfiler
->transactionWritingIn(
841 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
844 if ( $this->getFlag( DBO_DEBUG
) ) {
845 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
848 # Avoid fatals if close() was called
851 # Send the query to the server
852 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
854 # Try reconnecting if the connection was lost
855 if ( false === $ret && $this->wasErrorReissuable() ) {
856 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
857 # Stash the last error values before anything might clear them
858 $lastError = $this->lastError();
859 $lastErrno = $this->lastErrno();
860 # Update state tracking to reflect transaction loss due to disconnection
861 $this->handleSessionLoss();
862 if ( $this->reconnect() ) {
863 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
864 $this->connLogger
->warning( $msg );
865 $this->queryLogger
->warning(
866 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
868 if ( !$recoverable ) {
869 # Callers may catch the exception and continue to use the DB
870 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
872 # Should be safe to silently retry the query
873 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
876 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
877 $this->connLogger
->error( $msg );
881 if ( false === $ret ) {
882 # Deadlocks cause the entire transaction to abort, not just the statement.
883 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
884 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
885 if ( $this->wasDeadlock() ) {
886 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
887 $tempIgnore = false; // not recoverable
889 # Update state tracking to reflect transaction loss
890 $this->handleSessionLoss();
893 $this->reportQueryError(
894 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
897 $res = $this->resultObject( $ret );
902 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
903 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
904 # generalizeSQL() will probably cut down the query to reasonable
905 # logging size most of the time. The substr is really just a sanity check.
907 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
909 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
912 # Include query transaction state
913 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
915 $startTime = microtime( true );
916 if ( $this->profiler
) {
917 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
919 $ret = $this->doQuery( $commentedSql );
920 if ( $this->profiler
) {
921 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
923 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
925 unset( $queryProfSection ); // profile out (if set)
927 if ( $ret !== false ) {
928 $this->lastPing
= $startTime;
929 if ( $isWrite && $this->mTrxLevel
) {
930 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
931 $this->mTrxWriteCallers
[] = $fname;
935 if ( $sql === self
::PING_QUERY
) {
936 $this->mRTTEstimate
= $queryRuntime;
939 $this->trxProfiler
->recordQueryCompletion(
940 $queryProf, $startTime, $isWrite, $this->affectedRows()
942 $this->queryLogger
->debug( $sql, [
944 'master' => $isMaster,
945 'runtime' => $queryRuntime,
952 * Update the estimated run-time of a query, not counting large row lock times
954 * LoadBalancer can be set to rollback transactions that will create huge replication
955 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
956 * queries, like inserting a row can take a long time due to row locking. This method
957 * uses some simple heuristics to discount those cases.
959 * @param string $sql A SQL write query
960 * @param float $runtime Total runtime, including RTT
962 private function updateTrxWriteQueryTime( $sql, $runtime ) {
963 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
964 $indicativeOfReplicaRuntime = true;
965 if ( $runtime > self
::SLOW_WRITE_SEC
) {
966 $verb = $this->getQueryVerb( $sql );
967 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
968 if ( $verb === 'INSERT' ) {
969 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
970 } elseif ( $verb === 'REPLACE' ) {
971 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
975 $this->mTrxWriteDuration +
= $runtime;
976 $this->mTrxWriteQueryCount +
= 1;
977 if ( $indicativeOfReplicaRuntime ) {
978 $this->mTrxWriteAdjDuration +
= $runtime;
979 $this->mTrxWriteAdjQueryCount +
= 1;
983 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
984 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
985 # Dropped connections also mean that named locks are automatically released.
986 # Only allow error suppression in autocommit mode or when the lost transaction
987 # didn't matter anyway (aside from DBO_TRX snapshot loss).
988 if ( $this->mNamedLocksHeld
) {
989 return false; // possible critical section violation
990 } elseif ( $sql === 'COMMIT' ) {
991 return !$priorWritesPending; // nothing written anyway? (T127428)
992 } elseif ( $sql === 'ROLLBACK' ) {
993 return true; // transaction lost...which is also what was requested :)
994 } elseif ( $this->explicitTrxActive() ) {
995 return false; // don't drop atomocity
996 } elseif ( $priorWritesPending ) {
997 return false; // prior writes lost from implicit transaction
1003 private function handleSessionLoss() {
1004 $this->mTrxLevel
= 0;
1005 $this->mTrxIdleCallbacks
= []; // bug 65263
1006 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1007 $this->mSessionTempTables
= [];
1008 $this->mNamedLocksHeld
= [];
1010 // Handle callbacks in mTrxEndCallbacks
1011 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1012 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1014 } catch ( Exception
$e ) {
1015 // Already logged; move on...
1020 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1021 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1022 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1024 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1025 $this->queryLogger
->error(
1026 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1027 $this->getLogContext( [
1028 'method' => __METHOD__
,
1031 'sql1line' => $sql1line,
1035 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1036 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1040 public function freeResult( $res ) {
1043 public function selectField(
1044 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1046 if ( $var === '*' ) { // sanity
1047 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1050 if ( !is_array( $options ) ) {
1051 $options = [ $options ];
1054 $options['LIMIT'] = 1;
1056 $res = $this->select( $table, $var, $cond, $fname, $options );
1057 if ( $res === false ||
!$this->numRows( $res ) ) {
1061 $row = $this->fetchRow( $res );
1063 if ( $row !== false ) {
1064 return reset( $row );
1070 public function selectFieldValues(
1071 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1073 if ( $var === '*' ) { // sanity
1074 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1075 } elseif ( !is_string( $var ) ) { // sanity
1076 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1079 if ( !is_array( $options ) ) {
1080 $options = [ $options ];
1083 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1084 if ( $res === false ) {
1089 foreach ( $res as $row ) {
1090 $values[] = $row->$var;
1097 * Returns an optional USE INDEX clause to go after the table, and a
1098 * string to go at the end of the query.
1100 * @param array $options Associative array of options to be turned into
1101 * an SQL query, valid keys are listed in the function.
1103 * @see DatabaseBase::select()
1105 protected function makeSelectOptions( $options ) {
1106 $preLimitTail = $postLimitTail = '';
1111 foreach ( $options as $key => $option ) {
1112 if ( is_numeric( $key ) ) {
1113 $noKeyOptions[$option] = true;
1117 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1119 $preLimitTail .= $this->makeOrderBy( $options );
1121 // if (isset($options['LIMIT'])) {
1122 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1123 // isset($options['OFFSET']) ? $options['OFFSET']
1127 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1128 $postLimitTail .= ' FOR UPDATE';
1131 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1132 $postLimitTail .= ' LOCK IN SHARE MODE';
1135 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1136 $startOpts .= 'DISTINCT';
1139 # Various MySQL extensions
1140 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1141 $startOpts .= ' /*! STRAIGHT_JOIN */';
1144 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1145 $startOpts .= ' HIGH_PRIORITY';
1148 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1149 $startOpts .= ' SQL_BIG_RESULT';
1152 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1153 $startOpts .= ' SQL_BUFFER_RESULT';
1156 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1157 $startOpts .= ' SQL_SMALL_RESULT';
1160 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1161 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1164 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1165 $startOpts .= ' SQL_CACHE';
1168 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1169 $startOpts .= ' SQL_NO_CACHE';
1172 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1173 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1177 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1178 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1183 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1187 * Returns an optional GROUP BY with an optional HAVING
1189 * @param array $options Associative array of options
1191 * @see DatabaseBase::select()
1194 protected function makeGroupByWithHaving( $options ) {
1196 if ( isset( $options['GROUP BY'] ) ) {
1197 $gb = is_array( $options['GROUP BY'] )
1198 ?
implode( ',', $options['GROUP BY'] )
1199 : $options['GROUP BY'];
1200 $sql .= ' GROUP BY ' . $gb;
1202 if ( isset( $options['HAVING'] ) ) {
1203 $having = is_array( $options['HAVING'] )
1204 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1205 : $options['HAVING'];
1206 $sql .= ' HAVING ' . $having;
1213 * Returns an optional ORDER BY
1215 * @param array $options Associative array of options
1217 * @see DatabaseBase::select()
1220 protected function makeOrderBy( $options ) {
1221 if ( isset( $options['ORDER BY'] ) ) {
1222 $ob = is_array( $options['ORDER BY'] )
1223 ?
implode( ',', $options['ORDER BY'] )
1224 : $options['ORDER BY'];
1226 return ' ORDER BY ' . $ob;
1232 // See IDatabase::select for the docs for this function
1233 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1234 $options = [], $join_conds = [] ) {
1235 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1237 return $this->query( $sql, $fname );
1240 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1241 $options = [], $join_conds = []
1243 if ( is_array( $vars ) ) {
1244 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1247 $options = (array)$options;
1248 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1249 ?
$options['USE INDEX']
1251 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1252 ?
$options['IGNORE INDEX']
1255 if ( is_array( $table ) ) {
1257 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1258 } elseif ( $table != '' ) {
1259 if ( $table[0] == ' ' ) {
1260 $from = ' FROM ' . $table;
1263 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1269 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1270 $this->makeSelectOptions( $options );
1272 if ( !empty( $conds ) ) {
1273 if ( is_array( $conds ) ) {
1274 $conds = $this->makeList( $conds, self
::LIST_AND
);
1276 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1278 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1281 if ( isset( $options['LIMIT'] ) ) {
1282 $sql = $this->limitResult( $sql, $options['LIMIT'],
1283 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1285 $sql = "$sql $postLimitTail";
1287 if ( isset( $options['EXPLAIN'] ) ) {
1288 $sql = 'EXPLAIN ' . $sql;
1294 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1295 $options = [], $join_conds = []
1297 $options = (array)$options;
1298 $options['LIMIT'] = 1;
1299 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1301 if ( $res === false ) {
1305 if ( !$this->numRows( $res ) ) {
1309 $obj = $this->fetchObject( $res );
1314 public function estimateRowCount(
1315 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1318 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1321 $row = $this->fetchRow( $res );
1322 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1328 public function selectRowCount(
1329 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1332 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1333 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1336 $row = $this->fetchRow( $res );
1337 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1344 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1345 * It's only slightly flawed. Don't use for anything important.
1347 * @param string $sql A SQL Query
1351 protected static function generalizeSQL( $sql ) {
1352 # This does the same as the regexp below would do, but in such a way
1353 # as to avoid crashing php on some large strings.
1354 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1356 $sql = str_replace( "\\\\", '', $sql );
1357 $sql = str_replace( "\\'", '', $sql );
1358 $sql = str_replace( "\\\"", '', $sql );
1359 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1360 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1362 # All newlines, tabs, etc replaced by single space
1363 $sql = preg_replace( '/\s+/', ' ', $sql );
1366 # except the ones surrounded by characters, e.g. l10n
1367 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1368 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1373 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1374 $info = $this->fieldInfo( $table, $field );
1379 public function indexExists( $table, $index, $fname = __METHOD__
) {
1380 if ( !$this->tableExists( $table ) ) {
1384 $info = $this->indexInfo( $table, $index, $fname );
1385 if ( is_null( $info ) ) {
1388 return $info !== false;
1392 public function tableExists( $table, $fname = __METHOD__
) {
1393 $tableRaw = $this->tableName( $table, 'raw' );
1394 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1395 return true; // already known to exist
1398 $table = $this->tableName( $table );
1399 $old = $this->ignoreErrors( true );
1400 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1401 $this->ignoreErrors( $old );
1406 public function indexUnique( $table, $index ) {
1407 $indexInfo = $this->indexInfo( $table, $index );
1409 if ( !$indexInfo ) {
1413 return !$indexInfo[0]->Non_unique
;
1417 * Helper for DatabaseBase::insert().
1419 * @param array $options
1422 protected function makeInsertOptions( $options ) {
1423 return implode( ' ', $options );
1426 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1427 # No rows to insert, easy just return now
1428 if ( !count( $a ) ) {
1432 $table = $this->tableName( $table );
1434 if ( !is_array( $options ) ) {
1435 $options = [ $options ];
1439 if ( isset( $options['fileHandle'] ) ) {
1440 $fh = $options['fileHandle'];
1442 $options = $this->makeInsertOptions( $options );
1444 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1446 $keys = array_keys( $a[0] );
1449 $keys = array_keys( $a );
1452 $sql = 'INSERT ' . $options .
1453 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1457 foreach ( $a as $row ) {
1463 $sql .= '(' . $this->makeList( $row ) . ')';
1466 $sql .= '(' . $this->makeList( $a ) . ')';
1469 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1471 } elseif ( $fh !== null ) {
1475 return (bool)$this->query( $sql, $fname );
1479 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1481 * @param array $options
1484 protected function makeUpdateOptionsArray( $options ) {
1485 if ( !is_array( $options ) ) {
1486 $options = [ $options ];
1491 if ( in_array( 'IGNORE', $options ) ) {
1499 * Make UPDATE options for the DatabaseBase::update function
1501 * @param array $options The options passed to DatabaseBase::update
1504 protected function makeUpdateOptions( $options ) {
1505 $opts = $this->makeUpdateOptionsArray( $options );
1507 return implode( ' ', $opts );
1510 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1511 $table = $this->tableName( $table );
1512 $opts = $this->makeUpdateOptions( $options );
1513 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1515 if ( $conds !== [] && $conds !== '*' ) {
1516 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1519 return $this->query( $sql, $fname );
1522 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1523 if ( !is_array( $a ) ) {
1524 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1530 foreach ( $a as $field => $value ) {
1532 if ( $mode == self
::LIST_AND
) {
1534 } elseif ( $mode == self
::LIST_OR
) {
1543 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1544 $list .= "($value)";
1545 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1548 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1550 // Remove null from array to be handled separately if found
1551 $includeNull = false;
1552 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1553 $includeNull = true;
1554 unset( $value[$nullKey] );
1556 if ( count( $value ) == 0 && !$includeNull ) {
1557 throw new InvalidArgumentException(
1558 __METHOD__
. ": empty input for field $field" );
1559 } elseif ( count( $value ) == 0 ) {
1560 // only check if $field is null
1561 $list .= "$field IS NULL";
1563 // IN clause contains at least one valid element
1564 if ( $includeNull ) {
1565 // Group subconditions to ensure correct precedence
1568 if ( count( $value ) == 1 ) {
1569 // Special-case single values, as IN isn't terribly efficient
1570 // Don't necessarily assume the single key is 0; we don't
1571 // enforce linear numeric ordering on other arrays here.
1572 $value = array_values( $value )[0];
1573 $list .= $field . " = " . $this->addQuotes( $value );
1575 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1577 // if null present in array, append IS NULL
1578 if ( $includeNull ) {
1579 $list .= " OR $field IS NULL)";
1582 } elseif ( $value === null ) {
1583 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1584 $list .= "$field IS ";
1585 } elseif ( $mode == self
::LIST_SET
) {
1586 $list .= "$field = ";
1591 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1593 $list .= "$field = ";
1595 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1602 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1605 foreach ( $data as $base => $sub ) {
1606 if ( count( $sub ) ) {
1607 $conds[] = $this->makeList(
1608 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1614 return $this->makeList( $conds, self
::LIST_OR
);
1616 // Nothing to search for...
1621 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1625 public function bitNot( $field ) {
1629 public function bitAnd( $fieldLeft, $fieldRight ) {
1630 return "($fieldLeft & $fieldRight)";
1633 public function bitOr( $fieldLeft, $fieldRight ) {
1634 return "($fieldLeft | $fieldRight)";
1637 public function buildConcat( $stringList ) {
1638 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1641 public function buildGroupConcatField(
1642 $delim, $table, $field, $conds = '', $join_conds = []
1644 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1646 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1649 public function buildStringCast( $field ) {
1653 public function selectDB( $db ) {
1654 # Stub. Shouldn't cause serious problems if it's not overridden, but
1655 # if your database engine supports a concept similar to MySQL's
1656 # databases you may as well.
1657 $this->mDBname
= $db;
1662 public function getDBname() {
1663 return $this->mDBname
;
1666 public function getServer() {
1667 return $this->mServer
;
1671 * Format a table name ready for use in constructing an SQL query
1673 * This does two important things: it quotes the table names to clean them up,
1674 * and it adds a table prefix if only given a table name with no quotes.
1676 * All functions of this object which require a table name call this function
1677 * themselves. Pass the canonical name to such functions. This is only needed
1678 * when calling query() directly.
1680 * @note This function does not sanitize user input. It is not safe to use
1681 * this function to escape user input.
1682 * @param string $name Database table name
1683 * @param string $format One of:
1684 * quoted - Automatically pass the table name through addIdentifierQuotes()
1685 * so that it can be used in a query.
1686 * raw - Do not add identifier quotes to the table name
1687 * @return string Full database name
1689 public function tableName( $name, $format = 'quoted' ) {
1690 # Skip the entire process when we have a string quoted on both ends.
1691 # Note that we check the end so that we will still quote any use of
1692 # use of `database`.table. But won't break things if someone wants
1693 # to query a database table with a dot in the name.
1694 if ( $this->isQuotedIdentifier( $name ) ) {
1698 # Lets test for any bits of text that should never show up in a table
1699 # name. Basically anything like JOIN or ON which are actually part of
1700 # SQL queries, but may end up inside of the table value to combine
1701 # sql. Such as how the API is doing.
1702 # Note that we use a whitespace test rather than a \b test to avoid
1703 # any remote case where a word like on may be inside of a table name
1704 # surrounded by symbols which may be considered word breaks.
1705 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1709 # Split database and table into proper variables.
1710 # We reverse the explode so that database.table and table both output
1711 # the correct table.
1712 $dbDetails = explode( '.', $name, 3 );
1713 if ( count( $dbDetails ) == 3 ) {
1714 list( $database, $schema, $table ) = $dbDetails;
1715 # We don't want any prefix added in this case
1717 } elseif ( count( $dbDetails ) == 2 ) {
1718 list( $database, $table ) = $dbDetails;
1719 # We don't want any prefix added in this case
1720 # In dbs that support it, $database may actually be the schema
1721 # but that doesn't affect any of the functionality here
1725 list( $table ) = $dbDetails;
1726 if ( isset( $this->tableAliases
[$table] ) ) {
1727 $database = $this->tableAliases
[$table]['dbname'];
1728 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1729 ?
$this->tableAliases
[$table]['schema']
1731 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1732 ?
$this->tableAliases
[$table]['prefix']
1733 : $this->mTablePrefix
;
1736 $schema = $this->mSchema
; # Default schema
1737 $prefix = $this->mTablePrefix
; # Default prefix
1741 # Quote $table and apply the prefix if not quoted.
1742 # $tableName might be empty if this is called from Database::replaceVars()
1743 $tableName = "{$prefix}{$table}";
1744 if ( $format == 'quoted'
1745 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1747 $tableName = $this->addIdentifierQuotes( $tableName );
1750 # Quote $schema and merge it with the table name if needed
1751 if ( strlen( $schema ) ) {
1752 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1753 $schema = $this->addIdentifierQuotes( $schema );
1755 $tableName = $schema . '.' . $tableName;
1758 # Quote $database and merge it with the table name if needed
1759 if ( $database !== '' ) {
1760 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1761 $database = $this->addIdentifierQuotes( $database );
1763 $tableName = $database . '.' . $tableName;
1770 * Fetch a number of table names into an array
1771 * This is handy when you need to construct SQL for joins
1774 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1775 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1776 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1780 public function tableNames() {
1781 $inArray = func_get_args();
1784 foreach ( $inArray as $name ) {
1785 $retVal[$name] = $this->tableName( $name );
1792 * Fetch a number of table names into an zero-indexed numerical array
1793 * This is handy when you need to construct SQL for joins
1796 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1797 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1798 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1802 public function tableNamesN() {
1803 $inArray = func_get_args();
1806 foreach ( $inArray as $name ) {
1807 $retVal[] = $this->tableName( $name );
1814 * Get an aliased table name
1815 * e.g. tableName AS newTableName
1817 * @param string $name Table name, see tableName()
1818 * @param string|bool $alias Alias (optional)
1819 * @return string SQL name for aliased table. Will not alias a table to its own name
1821 protected function tableNameWithAlias( $name, $alias = false ) {
1822 if ( !$alias ||
$alias == $name ) {
1823 return $this->tableName( $name );
1825 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1830 * Gets an array of aliased table names
1832 * @param array $tables [ [alias] => table ]
1833 * @return string[] See tableNameWithAlias()
1835 protected function tableNamesWithAlias( $tables ) {
1837 foreach ( $tables as $alias => $table ) {
1838 if ( is_numeric( $alias ) ) {
1841 $retval[] = $this->tableNameWithAlias( $table, $alias );
1848 * Get an aliased field name
1849 * e.g. fieldName AS newFieldName
1851 * @param string $name Field name
1852 * @param string|bool $alias Alias (optional)
1853 * @return string SQL name for aliased field. Will not alias a field to its own name
1855 protected function fieldNameWithAlias( $name, $alias = false ) {
1856 if ( !$alias ||
(string)$alias === (string)$name ) {
1859 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1864 * Gets an array of aliased field names
1866 * @param array $fields [ [alias] => field ]
1867 * @return string[] See fieldNameWithAlias()
1869 protected function fieldNamesWithAlias( $fields ) {
1871 foreach ( $fields as $alias => $field ) {
1872 if ( is_numeric( $alias ) ) {
1875 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1882 * Get the aliased table name clause for a FROM clause
1883 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1885 * @param array $tables ( [alias] => table )
1886 * @param array $use_index Same as for select()
1887 * @param array $ignore_index Same as for select()
1888 * @param array $join_conds Same as for select()
1891 protected function tableNamesWithIndexClauseOrJOIN(
1892 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1896 $use_index = (array)$use_index;
1897 $ignore_index = (array)$ignore_index;
1898 $join_conds = (array)$join_conds;
1900 foreach ( $tables as $alias => $table ) {
1901 if ( !is_string( $alias ) ) {
1902 // No alias? Set it equal to the table name
1905 // Is there a JOIN clause for this table?
1906 if ( isset( $join_conds[$alias] ) ) {
1907 list( $joinType, $conds ) = $join_conds[$alias];
1908 $tableClause = $joinType;
1909 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1910 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1911 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1913 $tableClause .= ' ' . $use;
1916 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1917 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1918 if ( $ignore != '' ) {
1919 $tableClause .= ' ' . $ignore;
1922 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1924 $tableClause .= ' ON (' . $on . ')';
1927 $retJOIN[] = $tableClause;
1928 } elseif ( isset( $use_index[$alias] ) ) {
1929 // Is there an INDEX clause for this table?
1930 $tableClause = $this->tableNameWithAlias( $table, $alias );
1931 $tableClause .= ' ' . $this->useIndexClause(
1932 implode( ',', (array)$use_index[$alias] )
1935 $ret[] = $tableClause;
1936 } elseif ( isset( $ignore_index[$alias] ) ) {
1937 // Is there an INDEX clause for this table?
1938 $tableClause = $this->tableNameWithAlias( $table, $alias );
1939 $tableClause .= ' ' . $this->ignoreIndexClause(
1940 implode( ',', (array)$ignore_index[$alias] )
1943 $ret[] = $tableClause;
1945 $tableClause = $this->tableNameWithAlias( $table, $alias );
1947 $ret[] = $tableClause;
1951 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1952 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1953 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1955 // Compile our final table clause
1956 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1960 * Get the name of an index in a given table.
1962 * @param string $index
1965 protected function indexName( $index ) {
1966 // Backwards-compatibility hack
1968 'ar_usertext_timestamp' => 'usertext_timestamp',
1969 'un_user_id' => 'user_id',
1970 'un_user_ip' => 'user_ip',
1973 if ( isset( $renamed[$index] ) ) {
1974 return $renamed[$index];
1980 public function addQuotes( $s ) {
1981 if ( $s instanceof Blob
) {
1984 if ( $s === null ) {
1986 } elseif ( is_bool( $s ) ) {
1989 # This will also quote numeric values. This should be harmless,
1990 # and protects against weird problems that occur when they really
1991 # _are_ strings such as article titles and string->number->string
1992 # conversion is not 1:1.
1993 return "'" . $this->strencode( $s ) . "'";
1998 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1999 * MySQL uses `backticks` while basically everything else uses double quotes.
2000 * Since MySQL is the odd one out here the double quotes are our generic
2001 * and we implement backticks in DatabaseMysql.
2006 public function addIdentifierQuotes( $s ) {
2007 return '"' . str_replace( '"', '""', $s ) . '"';
2011 * Returns if the given identifier looks quoted or not according to
2012 * the database convention for quoting identifiers .
2014 * @note Do not use this to determine if untrusted input is safe.
2015 * A malicious user can trick this function.
2016 * @param string $name
2019 public function isQuotedIdentifier( $name ) {
2020 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2027 protected function escapeLikeInternal( $s ) {
2028 return addcslashes( $s, '\%_' );
2031 public function buildLike() {
2032 $params = func_get_args();
2034 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2035 $params = $params[0];
2040 foreach ( $params as $value ) {
2041 if ( $value instanceof LikeMatch
) {
2042 $s .= $value->toString();
2044 $s .= $this->escapeLikeInternal( $value );
2048 return " LIKE {$this->addQuotes( $s )} ";
2051 public function anyChar() {
2052 return new LikeMatch( '_' );
2055 public function anyString() {
2056 return new LikeMatch( '%' );
2059 public function nextSequenceValue( $seqName ) {
2064 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2065 * is only needed because a) MySQL must be as efficient as possible due to
2066 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2067 * which index to pick. Anyway, other databases might have different
2068 * indexes on a given table. So don't bother overriding this unless you're
2070 * @param string $index
2073 public function useIndexClause( $index ) {
2078 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2079 * is only needed because a) MySQL must be as efficient as possible due to
2080 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2081 * which index to pick. Anyway, other databases might have different
2082 * indexes on a given table. So don't bother overriding this unless you're
2084 * @param string $index
2087 public function ignoreIndexClause( $index ) {
2091 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2092 $quotedTable = $this->tableName( $table );
2094 if ( count( $rows ) == 0 ) {
2099 if ( !is_array( reset( $rows ) ) ) {
2103 // @FXIME: this is not atomic, but a trx would break affectedRows()
2104 foreach ( $rows as $row ) {
2105 # Delete rows which collide
2106 if ( $uniqueIndexes ) {
2107 $sql = "DELETE FROM $quotedTable WHERE ";
2109 foreach ( $uniqueIndexes as $index ) {
2116 if ( is_array( $index ) ) {
2118 foreach ( $index as $col ) {
2124 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2127 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2131 $this->query( $sql, $fname );
2134 # Now insert the row
2135 $this->insert( $table, $row, $fname );
2140 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2143 * @param string $table Table name
2144 * @param array|string $rows Row(s) to insert
2145 * @param string $fname Caller function name
2147 * @return ResultWrapper
2149 protected function nativeReplace( $table, $rows, $fname ) {
2150 $table = $this->tableName( $table );
2153 if ( !is_array( reset( $rows ) ) ) {
2157 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2160 foreach ( $rows as $row ) {
2167 $sql .= '(' . $this->makeList( $row ) . ')';
2170 return $this->query( $sql, $fname );
2173 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2176 if ( !count( $rows ) ) {
2177 return true; // nothing to do
2180 if ( !is_array( reset( $rows ) ) ) {
2184 if ( count( $uniqueIndexes ) ) {
2185 $clauses = []; // list WHERE clauses that each identify a single row
2186 foreach ( $rows as $row ) {
2187 foreach ( $uniqueIndexes as $index ) {
2188 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2189 $rowKey = []; // unique key to this row
2190 foreach ( $index as $column ) {
2191 $rowKey[$column] = $row[$column];
2193 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2196 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2201 $useTrx = !$this->mTrxLevel
;
2203 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2206 # Update any existing conflicting row(s)
2207 if ( $where !== false ) {
2208 $ok = $this->update( $table, $set, $where, $fname );
2212 # Now insert any non-conflicting row(s)
2213 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2214 } catch ( Exception
$e ) {
2216 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2221 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2227 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2231 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2234 $delTable = $this->tableName( $delTable );
2235 $joinTable = $this->tableName( $joinTable );
2236 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2237 if ( $conds != '*' ) {
2238 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2242 $this->query( $sql, $fname );
2246 * Returns the size of a text field, or -1 for "unlimited"
2248 * @param string $table
2249 * @param string $field
2252 public function textFieldSize( $table, $field ) {
2253 $table = $this->tableName( $table );
2254 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2255 $res = $this->query( $sql, __METHOD__
);
2256 $row = $this->fetchObject( $res );
2260 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2269 public function delete( $table, $conds, $fname = __METHOD__
) {
2271 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2274 $table = $this->tableName( $table );
2275 $sql = "DELETE FROM $table";
2277 if ( $conds != '*' ) {
2278 if ( is_array( $conds ) ) {
2279 $conds = $this->makeList( $conds, self
::LIST_AND
);
2281 $sql .= ' WHERE ' . $conds;
2284 return $this->query( $sql, $fname );
2287 public function insertSelect(
2288 $destTable, $srcTable, $varMap, $conds,
2289 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2291 if ( $this->cliMode
) {
2292 // For massive migrations with downtime, we don't want to select everything
2293 // into memory and OOM, so do all this native on the server side if possible.
2294 return $this->nativeInsertSelect(
2305 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2306 // on only the master (without needing row-based-replication). It also makes it easy to
2307 // know how big the INSERT is going to be.
2309 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2310 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2312 $selectOptions[] = 'FOR UPDATE';
2313 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2319 foreach ( $res as $row ) {
2320 $rows[] = (array)$row;
2323 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2326 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2327 $fname = __METHOD__
,
2328 $insertOptions = [], $selectOptions = []
2330 $destTable = $this->tableName( $destTable );
2332 if ( !is_array( $insertOptions ) ) {
2333 $insertOptions = [ $insertOptions ];
2336 $insertOptions = $this->makeInsertOptions( $insertOptions );
2338 if ( !is_array( $selectOptions ) ) {
2339 $selectOptions = [ $selectOptions ];
2342 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2345 if ( is_array( $srcTable ) ) {
2346 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2348 $srcTable = $this->tableName( $srcTable );
2351 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2352 " SELECT $startOpts " . implode( ',', $varMap ) .
2353 " FROM $srcTable $useIndex $ignoreIndex ";
2355 if ( $conds != '*' ) {
2356 if ( is_array( $conds ) ) {
2357 $conds = $this->makeList( $conds, self
::LIST_AND
);
2359 $sql .= " WHERE $conds";
2362 $sql .= " $tailOpts";
2364 return $this->query( $sql, $fname );
2368 * Construct a LIMIT query with optional offset. This is used for query
2369 * pages. The SQL should be adjusted so that only the first $limit rows
2370 * are returned. If $offset is provided as well, then the first $offset
2371 * rows should be discarded, and the next $limit rows should be returned.
2372 * If the result of the query is not ordered, then the rows to be returned
2373 * are theoretically arbitrary.
2375 * $sql is expected to be a SELECT, if that makes a difference.
2377 * The version provided by default works in MySQL and SQLite. It will very
2378 * likely need to be overridden for most other DBMSes.
2380 * @param string $sql SQL query we will append the limit too
2381 * @param int $limit The SQL limit
2382 * @param int|bool $offset The SQL offset (default false)
2383 * @throws DBUnexpectedError
2386 public function limitResult( $sql, $limit, $offset = false ) {
2387 if ( !is_numeric( $limit ) ) {
2388 throw new DBUnexpectedError( $this,
2389 "Invalid non-numeric limit passed to limitResult()\n" );
2392 return "$sql LIMIT "
2393 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2397 public function unionSupportsOrderAndLimit() {
2398 return true; // True for almost every DB supported
2401 public function unionQueries( $sqls, $all ) {
2402 $glue = $all ?
') UNION ALL (' : ') UNION (';
2404 return '(' . implode( $glue, $sqls ) . ')';
2407 public function conditional( $cond, $trueVal, $falseVal ) {
2408 if ( is_array( $cond ) ) {
2409 $cond = $this->makeList( $cond, self
::LIST_AND
);
2412 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2415 public function strreplace( $orig, $old, $new ) {
2416 return "REPLACE({$orig}, {$old}, {$new})";
2419 public function getServerUptime() {
2423 public function wasDeadlock() {
2427 public function wasLockTimeout() {
2431 public function wasErrorReissuable() {
2435 public function wasReadOnlyError() {
2440 * Do no use the class outside of Database/DBError classes
2442 * @param integer|string $errno
2443 * @return bool Whether the given query error was a connection drop
2445 public function wasConnectionError( $errno ) {
2450 * Perform a deadlock-prone transaction.
2452 * This function invokes a callback function to perform a set of write
2453 * queries. If a deadlock occurs during the processing, the transaction
2454 * will be rolled back and the callback function will be called again.
2456 * Avoid using this method outside of Job or Maintenance classes.
2459 * $dbw->deadlockLoop( callback, ... );
2461 * Extra arguments are passed through to the specified callback function.
2462 * This method requires that no transactions are already active to avoid
2463 * causing premature commits or exceptions.
2465 * Returns whatever the callback function returned on its successful,
2466 * iteration, or false on error, for example if the retry limit was
2470 * @throws DBUnexpectedError
2473 public function deadlockLoop() {
2474 $args = func_get_args();
2475 $function = array_shift( $args );
2476 $tries = self
::DEADLOCK_TRIES
;
2478 $this->begin( __METHOD__
);
2481 /** @var Exception $e */
2485 $retVal = call_user_func_array( $function, $args );
2487 } catch ( DBQueryError
$e ) {
2488 if ( $this->wasDeadlock() ) {
2489 // Retry after a randomized delay
2490 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2492 // Throw the error back up
2496 } while ( --$tries > 0 );
2498 if ( $tries <= 0 ) {
2499 // Too many deadlocks; give up
2500 $this->rollback( __METHOD__
);
2503 $this->commit( __METHOD__
);
2509 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2510 # Real waits are implemented in the subclass.
2514 public function getSlavePos() {
2519 public function getMasterPos() {
2524 public function serverIsReadOnly() {
2528 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2529 if ( !$this->mTrxLevel
) {
2530 throw new DBUnexpectedError( $this, "No transaction is active." );
2532 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2535 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2536 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2537 if ( !$this->mTrxLevel
) {
2538 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2542 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2543 if ( $this->mTrxLevel
) {
2544 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2546 // If no transaction is active, then make one for this callback
2547 $this->startAtomic( __METHOD__
);
2549 call_user_func( $callback );
2550 $this->endAtomic( __METHOD__
);
2551 } catch ( Exception
$e ) {
2552 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2558 final public function setTransactionListener( $name, callable
$callback = null ) {
2560 $this->mTrxRecurringCallbacks
[$name] = $callback;
2562 unset( $this->mTrxRecurringCallbacks
[$name] );
2567 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2569 * This method should not be used outside of Database/LoadBalancer
2571 * @param bool $suppress
2574 final public function setTrxEndCallbackSuppression( $suppress ) {
2575 $this->mTrxEndCallbacksSuppressed
= $suppress;
2579 * Actually run and consume any "on transaction idle/resolution" callbacks.
2581 * This method should not be used outside of Database/LoadBalancer
2583 * @param integer $trigger IDatabase::TRIGGER_* constant
2587 public function runOnTransactionIdleCallbacks( $trigger ) {
2588 if ( $this->mTrxEndCallbacksSuppressed
) {
2592 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2593 /** @var Exception $e */
2594 $e = null; // first exception
2595 do { // callbacks may add callbacks :)
2596 $callbacks = array_merge(
2597 $this->mTrxIdleCallbacks
,
2598 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2600 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2601 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2602 foreach ( $callbacks as $callback ) {
2604 list( $phpCallback ) = $callback;
2605 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2606 call_user_func_array( $phpCallback, [ $trigger ] );
2608 $this->setFlag( DBO_TRX
); // restore automatic begin()
2610 $this->clearFlag( DBO_TRX
); // restore auto-commit
2612 } catch ( Exception
$ex ) {
2613 call_user_func( $this->errorLogger
, $ex );
2615 // Some callbacks may use startAtomic/endAtomic, so make sure
2616 // their transactions are ended so other callbacks don't fail
2617 if ( $this->trxLevel() ) {
2618 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2622 } while ( count( $this->mTrxIdleCallbacks
) );
2624 if ( $e instanceof Exception
) {
2625 throw $e; // re-throw any first exception
2630 * Actually run and consume any "on transaction pre-commit" callbacks.
2632 * This method should not be used outside of Database/LoadBalancer
2637 public function runOnTransactionPreCommitCallbacks() {
2638 $e = null; // first exception
2639 do { // callbacks may add callbacks :)
2640 $callbacks = $this->mTrxPreCommitCallbacks
;
2641 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2642 foreach ( $callbacks as $callback ) {
2644 list( $phpCallback ) = $callback;
2645 call_user_func( $phpCallback );
2646 } catch ( Exception
$ex ) {
2647 call_user_func( $this->errorLogger
, $ex );
2651 } while ( count( $this->mTrxPreCommitCallbacks
) );
2653 if ( $e instanceof Exception
) {
2654 throw $e; // re-throw any first exception
2659 * Actually run any "transaction listener" callbacks.
2661 * This method should not be used outside of Database/LoadBalancer
2663 * @param integer $trigger IDatabase::TRIGGER_* constant
2667 public function runTransactionListenerCallbacks( $trigger ) {
2668 if ( $this->mTrxEndCallbacksSuppressed
) {
2672 /** @var Exception $e */
2673 $e = null; // first exception
2675 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2677 $phpCallback( $trigger, $this );
2678 } catch ( Exception
$ex ) {
2679 call_user_func( $this->errorLogger
, $ex );
2684 if ( $e instanceof Exception
) {
2685 throw $e; // re-throw any first exception
2689 final public function startAtomic( $fname = __METHOD__
) {
2690 if ( !$this->mTrxLevel
) {
2691 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2692 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2693 // in all changes being in one transaction to keep requests transactional.
2694 if ( !$this->getFlag( DBO_TRX
) ) {
2695 $this->mTrxAutomaticAtomic
= true;
2699 $this->mTrxAtomicLevels
[] = $fname;
2702 final public function endAtomic( $fname = __METHOD__
) {
2703 if ( !$this->mTrxLevel
) {
2704 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2706 if ( !$this->mTrxAtomicLevels ||
2707 array_pop( $this->mTrxAtomicLevels
) !== $fname
2709 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2712 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2713 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2717 final public function doAtomicSection( $fname, callable
$callback ) {
2718 $this->startAtomic( $fname );
2720 $res = call_user_func_array( $callback, [ $this, $fname ] );
2721 } catch ( Exception
$e ) {
2722 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2725 $this->endAtomic( $fname );
2730 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2731 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2732 if ( $this->mTrxLevel
) {
2733 if ( $this->mTrxAtomicLevels
) {
2734 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2735 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2736 throw new DBUnexpectedError( $this, $msg );
2737 } elseif ( !$this->mTrxAutomatic
) {
2738 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2739 throw new DBUnexpectedError( $this, $msg );
2741 // @TODO: make this an exception at some point
2742 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2743 $this->queryLogger
->error( $msg );
2744 return; // join the main transaction set
2746 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2747 // @TODO: make this an exception at some point
2748 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2749 $this->queryLogger
->error( $msg );
2750 return; // let any writes be in the main transaction
2753 // Avoid fatals if close() was called
2754 $this->assertOpen();
2756 $this->doBegin( $fname );
2757 $this->mTrxTimestamp
= microtime( true );
2758 $this->mTrxFname
= $fname;
2759 $this->mTrxDoneWrites
= false;
2760 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2761 $this->mTrxAutomaticAtomic
= false;
2762 $this->mTrxAtomicLevels
= [];
2763 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2764 $this->mTrxWriteDuration
= 0.0;
2765 $this->mTrxWriteQueryCount
= 0;
2766 $this->mTrxWriteAdjDuration
= 0.0;
2767 $this->mTrxWriteAdjQueryCount
= 0;
2768 $this->mTrxWriteCallers
= [];
2769 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2770 // Get an estimate of the replica DB lag before then, treating estimate staleness
2771 // as lag itself just to be safe
2772 $status = $this->getApproximateLagStatus();
2773 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2777 * Issues the BEGIN command to the database server.
2779 * @see DatabaseBase::begin()
2780 * @param string $fname
2782 protected function doBegin( $fname ) {
2783 $this->query( 'BEGIN', $fname );
2784 $this->mTrxLevel
= 1;
2787 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2788 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2789 // There are still atomic sections open. This cannot be ignored
2790 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2791 throw new DBUnexpectedError(
2793 "$fname: Got COMMIT while atomic sections $levels are still open."
2797 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2798 if ( !$this->mTrxLevel
) {
2799 return; // nothing to do
2800 } elseif ( !$this->mTrxAutomatic
) {
2801 throw new DBUnexpectedError(
2803 "$fname: Flushing an explicit transaction, getting out of sync."
2807 if ( !$this->mTrxLevel
) {
2808 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2809 return; // nothing to do
2810 } elseif ( $this->mTrxAutomatic
) {
2811 // @TODO: make this an exception at some point
2812 $msg = "$fname: Explicit commit of implicit transaction.";
2813 $this->queryLogger
->error( $msg );
2814 return; // wait for the main transaction set commit round
2818 // Avoid fatals if close() was called
2819 $this->assertOpen();
2821 $this->runOnTransactionPreCommitCallbacks();
2822 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2823 $this->doCommit( $fname );
2824 if ( $this->mTrxDoneWrites
) {
2825 $this->mDoneWrites
= microtime( true );
2826 $this->trxProfiler
->transactionWritingOut(
2827 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2830 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2831 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2835 * Issues the COMMIT command to the database server.
2837 * @see DatabaseBase::commit()
2838 * @param string $fname
2840 protected function doCommit( $fname ) {
2841 if ( $this->mTrxLevel
) {
2842 $this->query( 'COMMIT', $fname );
2843 $this->mTrxLevel
= 0;
2847 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2848 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2849 if ( !$this->mTrxLevel
) {
2850 return; // nothing to do
2853 if ( !$this->mTrxLevel
) {
2854 $this->queryLogger
->error(
2855 "$fname: No transaction to rollback, something got out of sync." );
2856 return; // nothing to do
2857 } elseif ( $this->getFlag( DBO_TRX
) ) {
2858 throw new DBUnexpectedError(
2860 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2865 // Avoid fatals if close() was called
2866 $this->assertOpen();
2868 $this->doRollback( $fname );
2869 $this->mTrxAtomicLevels
= [];
2870 if ( $this->mTrxDoneWrites
) {
2871 $this->trxProfiler
->transactionWritingOut(
2872 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2875 $this->mTrxIdleCallbacks
= []; // clear
2876 $this->mTrxPreCommitCallbacks
= []; // clear
2877 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2878 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2882 * Issues the ROLLBACK command to the database server.
2884 * @see DatabaseBase::rollback()
2885 * @param string $fname
2887 protected function doRollback( $fname ) {
2888 if ( $this->mTrxLevel
) {
2889 # Disconnects cause rollback anyway, so ignore those errors
2890 $ignoreErrors = true;
2891 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2892 $this->mTrxLevel
= 0;
2896 public function flushSnapshot( $fname = __METHOD__
) {
2897 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2898 // This only flushes transactions to clear snapshots, not to write data
2899 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2900 throw new DBUnexpectedError(
2902 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2906 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2909 public function explicitTrxActive() {
2910 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2914 * Creates a new table with structure copied from existing table
2915 * Note that unlike most database abstraction functions, this function does not
2916 * automatically append database prefix, because it works at a lower
2917 * abstraction level.
2918 * The table names passed to this function shall not be quoted (this
2919 * function calls addIdentifierQuotes when needed).
2921 * @param string $oldName Name of table whose structure should be copied
2922 * @param string $newName Name of table to be created
2923 * @param bool $temporary Whether the new table should be temporary
2924 * @param string $fname Calling function name
2925 * @throws RuntimeException
2926 * @return bool True if operation was successful
2928 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2931 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2934 public function listTables( $prefix = null, $fname = __METHOD__
) {
2935 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2939 * Reset the views process cache set by listViews()
2942 final public function clearViewsCache() {
2943 $this->allViews
= null;
2947 * Lists all the VIEWs in the database
2949 * For caching purposes the list of all views should be stored in
2950 * $this->allViews. The process cache can be cleared with clearViewsCache()
2952 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2953 * @param string $fname Name of calling function
2954 * @throws RuntimeException
2958 public function listViews( $prefix = null, $fname = __METHOD__
) {
2959 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2963 * Differentiates between a TABLE and a VIEW
2965 * @param string $name Name of the database-structure to test.
2966 * @throws RuntimeException
2970 public function isView( $name ) {
2971 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2974 public function timestamp( $ts = 0 ) {
2975 $t = new ConvertibleTimestamp( $ts );
2976 // Let errors bubble up to avoid putting garbage in the DB
2977 return $t->getTimestamp( TS_MW
);
2980 public function timestampOrNull( $ts = null ) {
2981 if ( is_null( $ts ) ) {
2984 return $this->timestamp( $ts );
2989 * Take the result from a query, and wrap it in a ResultWrapper if
2990 * necessary. Boolean values are passed through as is, to indicate success
2991 * of write queries or failure.
2993 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2994 * resource, and it was necessary to call this function to convert it to
2995 * a wrapper. Nowadays, raw database objects are never exposed to external
2996 * callers, so this is unnecessary in external code.
2998 * @param bool|ResultWrapper|resource|object $result
2999 * @return bool|ResultWrapper
3001 protected function resultObject( $result ) {
3004 } elseif ( $result instanceof ResultWrapper
) {
3006 } elseif ( $result === true ) {
3007 // Successful write query
3010 return new ResultWrapper( $this, $result );
3014 public function ping( &$rtt = null ) {
3015 // Avoid hitting the server if it was hit recently
3016 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3017 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3018 $rtt = $this->mRTTEstimate
;
3019 return true; // don't care about $rtt
3023 // This will reconnect if possible or return false if not
3024 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3025 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3026 $this->restoreFlags( self
::RESTORE_PRIOR
);
3029 $rtt = $this->mRTTEstimate
;
3038 protected function reconnect() {
3039 $this->closeConnection();
3040 $this->mOpened
= false;
3041 $this->mConn
= false;
3043 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3044 $this->lastPing
= microtime( true );
3046 } catch ( DBConnectionError
$e ) {
3053 public function getSessionLagStatus() {
3054 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3058 * Get the replica DB lag when the current transaction started
3060 * This is useful when transactions might use snapshot isolation
3061 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3062 * is this lag plus transaction duration. If they don't, it is still
3063 * safe to be pessimistic. This returns null if there is no transaction.
3065 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3068 protected function getTransactionLagStatus() {
3069 return $this->mTrxLevel
3070 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3075 * Get a replica DB lag estimate for this server
3077 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3080 protected function getApproximateLagStatus() {
3082 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3083 'since' => microtime( true )
3088 * Merge the result of getSessionLagStatus() for several DBs
3089 * using the most pessimistic values to estimate the lag of
3090 * any data derived from them in combination
3092 * This is information is useful for caching modules
3094 * @see WANObjectCache::set()
3095 * @see WANObjectCache::getWithSetCallback()
3097 * @param IDatabase $db1
3098 * @param IDatabase ...
3099 * @return array Map of values:
3100 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3101 * - since: oldest UNIX timestamp of any of the DB lag estimates
3102 * - pending: whether any of the DBs have uncommitted changes
3105 public static function getCacheSetOptions( IDatabase
$db1 ) {
3106 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3107 foreach ( func_get_args() as $db ) {
3108 /** @var IDatabase $db */
3109 $status = $db->getSessionLagStatus();
3110 if ( $status['lag'] === false ) {
3111 $res['lag'] = false;
3112 } elseif ( $res['lag'] !== false ) {
3113 $res['lag'] = max( $res['lag'], $status['lag'] );
3115 $res['since'] = min( $res['since'], $status['since'] );
3116 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3122 public function getLag() {
3126 public function maxListLen() {
3130 public function encodeBlob( $b ) {
3134 public function decodeBlob( $b ) {
3135 if ( $b instanceof Blob
) {
3141 public function setSessionOptions( array $options ) {
3145 * Read and execute SQL commands from a file.
3147 * Returns true on success, error string or exception on failure (depending
3148 * on object's error ignore settings).
3150 * @param string $filename File name to open
3151 * @param bool|callable $lineCallback Optional function called before reading each line
3152 * @param bool|callable $resultCallback Optional function called for each MySQL result
3153 * @param bool|string $fname Calling function name or false if name should be
3154 * generated dynamically using $filename
3155 * @param bool|callable $inputCallback Optional function called for each
3156 * complete line sent
3157 * @return bool|string
3160 public function sourceFile(
3161 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3163 MediaWiki\
suppressWarnings();
3164 $fp = fopen( $filename, 'r' );
3165 MediaWiki\restoreWarnings
();
3167 if ( false === $fp ) {
3168 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3172 $fname = __METHOD__
. "( $filename )";
3176 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3177 } catch ( Exception
$e ) {
3187 public function setSchemaVars( $vars ) {
3188 $this->mSchemaVars
= $vars;
3192 * Read and execute commands from an open file handle.
3194 * Returns true on success, error string or exception on failure (depending
3195 * on object's error ignore settings).
3197 * @param resource $fp File handle
3198 * @param bool|callable $lineCallback Optional function called before reading each query
3199 * @param bool|callable $resultCallback Optional function called for each MySQL result
3200 * @param string $fname Calling function name
3201 * @param bool|callable $inputCallback Optional function called for each complete query sent
3202 * @return bool|string
3204 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3205 $fname = __METHOD__
, $inputCallback = false
3209 while ( !feof( $fp ) ) {
3210 if ( $lineCallback ) {
3211 call_user_func( $lineCallback );
3214 $line = trim( fgets( $fp ) );
3216 if ( $line == '' ) {
3220 if ( '-' == $line[0] && '-' == $line[1] ) {
3228 $done = $this->streamStatementEnd( $cmd, $line );
3232 if ( $done ||
feof( $fp ) ) {
3233 $cmd = $this->replaceVars( $cmd );
3235 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3236 $res = $this->query( $cmd, $fname );
3238 if ( $resultCallback ) {
3239 call_user_func( $resultCallback, $res, $this );
3242 if ( false === $res ) {
3243 $err = $this->lastError();
3245 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3256 * Called by sourceStream() to check if we've reached a statement end
3258 * @param string $sql SQL assembled so far
3259 * @param string $newLine New line about to be added to $sql
3260 * @return bool Whether $newLine contains end of the statement
3262 public function streamStatementEnd( &$sql, &$newLine ) {
3263 if ( $this->delimiter
) {
3265 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3266 if ( $newLine != $prev ) {
3275 * Database independent variable replacement. Replaces a set of variables
3276 * in an SQL statement with their contents as given by $this->getSchemaVars().
3278 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3280 * - '{$var}' should be used for text and is passed through the database's
3282 * - `{$var}` should be used for identifiers (e.g. table and database names).
3283 * It is passed through the database's addIdentifierQuotes method which
3284 * can be overridden if the database uses something other than backticks.
3285 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3286 * database's tableName method.
3287 * - / *i* / passes the name that follows through the database's indexName method.
3288 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3289 * its use should be avoided. In 1.24 and older, string encoding was applied.
3291 * @param string $ins SQL statement to replace variables in
3292 * @return string The new SQL statement with variables replaced
3294 protected function replaceVars( $ins ) {
3295 $vars = $this->getSchemaVars();
3296 return preg_replace_callback(
3298 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3299 \'\{\$ (\w+) }\' | # 3. addQuotes
3300 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3301 /\*\$ (\w+) \*/ # 5. leave unencoded
3303 function ( $m ) use ( $vars ) {
3304 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3305 // check for both nonexistent keys *and* the empty string.
3306 if ( isset( $m[1] ) && $m[1] !== '' ) {
3307 if ( $m[1] === 'i' ) {
3308 return $this->indexName( $m[2] );
3310 return $this->tableName( $m[2] );
3312 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3313 return $this->addQuotes( $vars[$m[3]] );
3314 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3315 return $this->addIdentifierQuotes( $vars[$m[4]] );
3316 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3317 return $vars[$m[5]];
3327 * Get schema variables. If none have been set via setSchemaVars(), then
3328 * use some defaults from the current object.
3332 protected function getSchemaVars() {
3333 if ( $this->mSchemaVars
) {
3334 return $this->mSchemaVars
;
3336 return $this->getDefaultSchemaVars();
3341 * Get schema variables to use if none have been set via setSchemaVars().
3343 * Override this in derived classes to provide variables for tables.sql
3344 * and SQL patch files.
3348 protected function getDefaultSchemaVars() {
3352 public function lockIsFree( $lockName, $method ) {
3356 public function lock( $lockName, $method, $timeout = 5 ) {
3357 $this->mNamedLocksHeld
[$lockName] = 1;
3362 public function unlock( $lockName, $method ) {
3363 unset( $this->mNamedLocksHeld
[$lockName] );
3368 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3369 if ( $this->writesOrCallbacksPending() ) {
3370 // This only flushes transactions to clear snapshots, not to write data
3371 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3372 throw new DBUnexpectedError(
3374 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3378 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3382 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3383 if ( $this->trxLevel() ) {
3384 // There is a good chance an exception was thrown, causing any early return
3385 // from the caller. Let any error handler get a chance to issue rollback().
3386 // If there isn't one, let the error bubble up and trigger server-side rollback.
3387 $this->onTransactionResolution(
3388 function () use ( $lockKey, $fname ) {
3389 $this->unlock( $lockKey, $fname );
3394 $this->unlock( $lockKey, $fname );
3398 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3403 public function namedLocksEnqueue() {
3408 * Lock specific tables
3410 * @param array $read Array of tables to lock for read access
3411 * @param array $write Array of tables to lock for write access
3412 * @param string $method Name of caller
3413 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3416 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3421 * Unlock specific tables
3423 * @param string $method The caller
3426 public function unlockTables( $method ) {
3432 * @param string $tableName
3433 * @param string $fName
3434 * @return bool|ResultWrapper
3437 public function dropTable( $tableName, $fName = __METHOD__
) {
3438 if ( !$this->tableExists( $tableName, $fName ) ) {
3441 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3443 return $this->query( $sql, $fName );
3446 public function getInfinity() {
3450 public function encodeExpiry( $expiry ) {
3451 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3452 ?
$this->getInfinity()
3453 : $this->timestamp( $expiry );
3456 public function decodeExpiry( $expiry, $format = TS_MW
) {
3457 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3462 $t = new ConvertibleTimestamp( $expiry );
3464 return $t->getTimestamp( $format );
3465 } catch ( TimestampException
$e ) {
3470 public function setBigSelects( $value = true ) {
3474 public function isReadOnly() {
3475 return ( $this->getReadOnlyReason() !== false );
3479 * @return string|bool Reason this DB is read-only or false if it is not
3481 protected function getReadOnlyReason() {
3482 $reason = $this->getLBInfo( 'readOnlyReason' );
3484 return is_string( $reason ) ?
$reason : false;
3487 public function setTableAliases( array $aliases ) {
3488 $this->tableAliases
= $aliases;
3492 * @return bool Whether a DB user is required to access the DB
3495 protected function requiresDatabaseUser() {
3503 public function __toString() {
3504 return (string)$this->mConn
;
3508 * Make sure that copies do not share the same client binding handle
3509 * @throws DBConnectionError
3511 public function __clone() {
3512 $this->connLogger
->warning(
3513 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3514 ( new RuntimeException() )->getTraceAsString()
3517 if ( $this->isOpen() ) {
3518 // Open a new connection resource without messing with the old one
3519 $this->mOpened
= false;
3520 $this->mConn
= false;
3521 $this->mTrxLevel
= 0; // no trx anymore
3522 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3523 $this->lastPing
= microtime( true );
3528 * Called by serialize. Throw an exception when DB connection is serialized.
3529 * This causes problems on some database engines because the connection is
3530 * not restored on unserialize.
3532 public function __sleep() {
3533 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3534 'the connection is not restored on wakeup.' );
3538 * Run a few simple sanity checks and close dangling connections
3540 public function __destruct() {
3541 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3542 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3545 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3546 if ( $danglingWriters ) {
3547 $fnames = implode( ', ', $danglingWriters );
3548 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3551 if ( $this->mConn
) {
3552 // Avoid connection leaks for sanity
3553 $this->closeConnection();
3554 $this->mConn
= false;
3555 $this->mOpened
= false;