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'];
269 $this->errorLogger
= $params['errorLogger'];
271 // Set initial dummy domain until open() sets the final DB/prefix
272 $this->currentDomain
= DatabaseDomain
::newUnspecified();
275 $this->open( $server, $user, $password, $dbName );
276 } elseif ( $this->requiresDatabaseUser() ) {
277 throw new InvalidArgumentException( "No database user provided." );
280 // Set the domain object after open() sets the relevant fields
281 if ( $this->mDBname
!= '' ) {
282 // Domains with server scope but a table prefix are not used by IDatabase classes
283 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
288 * Construct a Database subclass instance given a database type and parameters
290 * This also connects to the database immediately upon object construction
292 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
293 * @param array $p Parameter map with keys:
294 * - host : The hostname of the DB server
295 * - user : The name of the database user the client operates under
296 * - password : The password for the database user
297 * - dbname : The name of the database to use where queries do not specify one.
298 * The database must exist or an error might be thrown. Setting this to the empty string
299 * will avoid any such errors and make the handle have no implicit database scope. This is
300 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
301 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
302 * in which user names and such are defined, e.g. users are database-specific in Postgres.
303 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
304 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
305 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
306 * recognized in queries. This can be used in place of schemas for handle site farms.
307 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
308 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
309 * flag in place UNLESS this this database simply acts as a key/value store.
310 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
311 * 'mysql' driver and the newer 'mysqli' driver.
312 * - variables: Optional map of session variables to set after connecting. This can be
313 * used to adjust lock timeouts or encoding modes and the like.
314 * - connLogger: Optional PSR-3 logger interface instance.
315 * - queryLogger: Optional PSR-3 logger interface instance.
316 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
317 * These will be called in query(), using a simplified version of the SQL that also
318 * includes the agent as a SQL comment.
319 * - trxProfiler: Optional TransactionProfiler instance.
320 * - errorLogger: Optional callback that takes an Exception and logs it.
321 * - cliMode: Whether to consider the execution context that of a CLI script.
322 * - agent: Optional name used to identify the end-user in query profiling/logging.
323 * - srvCache: Optional BagOStuff instance to an APC-style cache.
324 * @return Database|null If the database driver or extension cannot be found
325 * @throws InvalidArgumentException If the database driver or extension cannot be found
328 final public static function factory( $dbType, $p = [] ) {
329 static $canonicalDBTypes = [
330 'mysql' => [ 'mysqli', 'mysql' ],
338 $dbType = strtolower( $dbType );
339 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
340 $possibleDrivers = $canonicalDBTypes[$dbType];
341 if ( !empty( $p['driver'] ) ) {
342 if ( in_array( $p['driver'], $possibleDrivers ) ) {
343 $driver = $p['driver'];
345 throw new InvalidArgumentException( __METHOD__
.
346 " type '$dbType' does not support driver '{$p['driver']}'" );
349 foreach ( $possibleDrivers as $posDriver ) {
350 if ( extension_loaded( $posDriver ) ) {
351 $driver = $posDriver;
359 if ( $driver === false ) {
360 throw new InvalidArgumentException( __METHOD__
.
361 " no viable database extension found for type '$dbType'" );
364 $class = 'Database' . ucfirst( $driver );
365 if ( class_exists( $class ) && is_subclass_of( $class, 'IDatabase' ) ) {
366 // Resolve some defaults for b/c
367 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
368 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
369 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
370 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
371 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
372 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
373 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
374 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
375 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
376 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
377 if ( !isset( $p['connLogger'] ) ) {
378 $p['connLogger'] = new \Psr\Log\
NullLogger();
380 if ( !isset( $p['queryLogger'] ) ) {
381 $p['queryLogger'] = new \Psr\Log\
NullLogger();
383 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
384 if ( !isset( $p['trxProfiler'] ) ) {
385 $p['trxProfiler'] = new TransactionProfiler();
387 if ( !isset( $p['errorLogger'] ) ) {
388 $p['errorLogger'] = function ( Exception
$e ) {
389 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_WARNING
);
393 $conn = new $class( $p );
401 public function setLogger( LoggerInterface
$logger ) {
402 $this->queryLogger
= $logger;
405 public function getServerInfo() {
406 return $this->getServerVersion();
409 public function bufferResults( $buffer = null ) {
410 $res = !$this->getFlag( DBO_NOBUFFER
);
411 if ( $buffer !== null ) {
412 $buffer ?
$this->clearFlag( DBO_NOBUFFER
) : $this->setFlag( DBO_NOBUFFER
);
419 * Turns on (false) or off (true) the automatic generation and sending
420 * of a "we're sorry, but there has been a database error" page on
421 * database errors. Default is on (false). When turned off, the
422 * code should use lastErrno() and lastError() to handle the
423 * situation as appropriate.
425 * Do not use this function outside of the Database classes.
427 * @param null|bool $ignoreErrors
428 * @return bool The previous value of the flag.
430 protected function ignoreErrors( $ignoreErrors = null ) {
431 $res = $this->getFlag( DBO_IGNORE
);
432 if ( $ignoreErrors !== null ) {
433 $ignoreErrors ?
$this->setFlag( DBO_IGNORE
) : $this->clearFlag( DBO_IGNORE
);
439 public function trxLevel() {
440 return $this->mTrxLevel
;
443 public function trxTimestamp() {
444 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
447 public function tablePrefix( $prefix = null ) {
448 $old = $this->mTablePrefix
;
449 if ( $prefix !== null ) {
450 $this->mTablePrefix
= $prefix;
451 $this->currentDomain
= ( $this->mDBname
!= '' )
452 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
453 : DatabaseDomain
::newUnspecified();
459 public function dbSchema( $schema = null ) {
460 $old = $this->mSchema
;
461 if ( $schema !== null ) {
462 $this->mSchema
= $schema;
468 public function getLBInfo( $name = null ) {
469 if ( is_null( $name ) ) {
470 return $this->mLBInfo
;
472 if ( array_key_exists( $name, $this->mLBInfo
) ) {
473 return $this->mLBInfo
[$name];
480 public function setLBInfo( $name, $value = null ) {
481 if ( is_null( $value ) ) {
482 $this->mLBInfo
= $name;
484 $this->mLBInfo
[$name] = $value;
488 public function setLazyMasterHandle( IDatabase
$conn ) {
489 $this->lazyMasterHandle
= $conn;
493 * @return IDatabase|null
494 * @see setLazyMasterHandle()
497 public function getLazyMasterHandle() {
498 return $this->lazyMasterHandle
;
501 public function implicitGroupby() {
505 public function implicitOrderby() {
509 public function lastQuery() {
510 return $this->mLastQuery
;
513 public function doneWrites() {
514 return (bool)$this->mDoneWrites
;
517 public function lastDoneWrites() {
518 return $this->mDoneWrites ?
: false;
521 public function writesPending() {
522 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
525 public function writesOrCallbacksPending() {
526 return $this->mTrxLevel
&& (
527 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
531 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
532 if ( !$this->mTrxLevel
) {
534 } elseif ( !$this->mTrxDoneWrites
) {
539 case self
::ESTIMATE_DB_APPLY
:
541 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
542 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
543 // For omitted queries, make them count as something at least
544 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
545 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
548 default: // everything
549 return $this->mTrxWriteDuration
;
553 public function pendingWriteCallers() {
554 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
557 protected function pendingWriteAndCallbackCallers() {
558 if ( !$this->mTrxLevel
) {
562 $fnames = $this->mTrxWriteCallers
;
564 $this->mTrxIdleCallbacks
,
565 $this->mTrxPreCommitCallbacks
,
566 $this->mTrxEndCallbacks
568 foreach ( $callbacks as $callback ) {
569 $fnames[] = $callback[1];
576 public function isOpen() {
577 return $this->mOpened
;
580 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
581 if ( $remember === self
::REMEMBER_PRIOR
) {
582 array_push( $this->priorFlags
, $this->mFlags
);
584 $this->mFlags |
= $flag;
587 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
588 if ( $remember === self
::REMEMBER_PRIOR
) {
589 array_push( $this->priorFlags
, $this->mFlags
);
591 $this->mFlags
&= ~
$flag;
594 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
595 if ( !$this->priorFlags
) {
599 if ( $state === self
::RESTORE_INITIAL
) {
600 $this->mFlags
= reset( $this->priorFlags
);
601 $this->priorFlags
= [];
603 $this->mFlags
= array_pop( $this->priorFlags
);
607 public function getFlag( $flag ) {
608 return !!( $this->mFlags
& $flag );
611 public function getProperty( $name ) {
615 public function getDomainID() {
616 return $this->currentDomain
->getId();
619 final public function getWikiID() {
620 return $this->getDomainID();
624 * Get information about an index into an object
625 * @param string $table Table name
626 * @param string $index Index name
627 * @param string $fname Calling function name
628 * @return mixed Database-specific index description class or false if the index does not exist
630 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
633 * Wrapper for addslashes()
635 * @param string $s String to be slashed.
636 * @return string Slashed string.
638 abstract function strencode( $s );
640 protected function installErrorHandler() {
641 $this->mPHPError
= false;
642 $this->htmlErrors
= ini_set( 'html_errors', '0' );
643 set_error_handler( [ $this, 'connectionErrorLogger' ] );
647 * @return bool|string
649 protected function restoreErrorHandler() {
650 restore_error_handler();
651 if ( $this->htmlErrors
!== false ) {
652 ini_set( 'html_errors', $this->htmlErrors
);
654 if ( $this->mPHPError
) {
655 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
656 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
665 * This method should not be used outside of Database classes
668 * @param string $errstr
670 public function connectionErrorLogger( $errno, $errstr ) {
671 $this->mPHPError
= $errstr;
675 * Create a log context to pass to PSR-3 logger functions.
677 * @param array $extras Additional data to add to context
680 protected function getLogContext( array $extras = [] ) {
683 'db_server' => $this->mServer
,
684 'db_name' => $this->mDBname
,
685 'db_user' => $this->mUser
,
691 public function close() {
692 if ( $this->mConn
) {
693 if ( $this->trxLevel() ) {
694 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
697 $closed = $this->closeConnection();
698 $this->mConn
= false;
699 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
700 throw new RuntimeException( "Transaction callbacks still pending." );
704 $this->mOpened
= false;
710 * Make sure isOpen() returns true as a sanity check
712 * @throws DBUnexpectedError
714 protected function assertOpen() {
715 if ( !$this->isOpen() ) {
716 throw new DBUnexpectedError( $this, "DB connection was already closed." );
721 * Closes underlying database connection
723 * @return bool Whether connection was closed successfully
725 abstract protected function closeConnection();
727 public function reportConnectionError( $error = 'Unknown error' ) {
728 $myError = $this->lastError();
734 throw new DBConnectionError( $this, $error );
738 * The DBMS-dependent part of query()
740 * @param string $sql SQL query.
741 * @return ResultWrapper|bool Result object to feed to fetchObject,
742 * fetchRow, ...; or false on failure
744 abstract protected function doQuery( $sql );
747 * Determine whether a query writes to the DB.
748 * Should return true if unsure.
753 protected function isWriteQuery( $sql ) {
755 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
760 * @return string|null
762 protected function getQueryVerb( $sql ) {
763 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
767 * Determine whether a SQL statement is sensitive to isolation level.
768 * A SQL statement is considered transactable if its result could vary
769 * depending on the transaction isolation level. Operational commands
770 * such as 'SET' and 'SHOW' are not considered to be transactable.
775 protected function isTransactableQuery( $sql ) {
776 $verb = $this->getQueryVerb( $sql );
777 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ], true );
781 * @param string $sql A SQL query
782 * @return bool Whether $sql is SQL for creating/dropping a new TEMPORARY table
784 protected function registerTempTableOperation( $sql ) {
786 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
790 $this->mSessionTempTables
[$matches[1]] = 1;
793 } elseif ( preg_match(
794 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
798 unset( $this->mSessionTempTables
[$matches[1]] );
801 } elseif ( preg_match(
802 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
806 return isset( $this->mSessionTempTables
[$matches[1]] );
812 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
813 $priorWritesPending = $this->writesOrCallbacksPending();
814 $this->mLastQuery
= $sql;
816 $isWrite = $this->isWriteQuery( $sql ) && !$this->registerTempTableOperation( $sql );
818 $reason = $this->getReadOnlyReason();
819 if ( $reason !== false ) {
820 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
822 # Set a flag indicating that writes have been done
823 $this->mDoneWrites
= microtime( true );
826 // Add trace comment to the begin of the sql string, right after the operator.
827 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
828 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
830 # Start implicit transactions that wrap the request if DBO_TRX is enabled
831 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
)
832 && $this->isTransactableQuery( $sql )
834 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
835 $this->mTrxAutomatic
= true;
838 # Keep track of whether the transaction has write queries pending
839 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
840 $this->mTrxDoneWrites
= true;
841 $this->trxProfiler
->transactionWritingIn(
842 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
845 if ( $this->getFlag( DBO_DEBUG
) ) {
846 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
849 # Avoid fatals if close() was called
852 # Send the query to the server
853 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
855 # Try reconnecting if the connection was lost
856 if ( false === $ret && $this->wasErrorReissuable() ) {
857 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
858 # Stash the last error values before anything might clear them
859 $lastError = $this->lastError();
860 $lastErrno = $this->lastErrno();
861 # Update state tracking to reflect transaction loss due to disconnection
862 $this->handleSessionLoss();
863 if ( $this->reconnect() ) {
864 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
865 $this->connLogger
->warning( $msg );
866 $this->queryLogger
->warning(
867 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
869 if ( !$recoverable ) {
870 # Callers may catch the exception and continue to use the DB
871 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
873 # Should be safe to silently retry the query
874 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isWrite, $fname );
877 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
878 $this->connLogger
->error( $msg );
882 if ( false === $ret ) {
883 # Deadlocks cause the entire transaction to abort, not just the statement.
884 # http://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
885 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
886 if ( $this->wasDeadlock() ) {
887 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
888 $tempIgnore = false; // not recoverable
890 # Update state tracking to reflect transaction loss
891 $this->handleSessionLoss();
894 $this->reportQueryError(
895 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
898 $res = $this->resultObject( $ret );
903 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
904 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
905 # generalizeSQL() will probably cut down the query to reasonable
906 # logging size most of the time. The substr is really just a sanity check.
908 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
910 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
913 # Include query transaction state
914 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
916 $startTime = microtime( true );
917 if ( $this->profiler
) {
918 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
920 $ret = $this->doQuery( $commentedSql );
921 if ( $this->profiler
) {
922 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
924 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
926 unset( $queryProfSection ); // profile out (if set)
928 if ( $ret !== false ) {
929 $this->lastPing
= $startTime;
930 if ( $isWrite && $this->mTrxLevel
) {
931 $this->updateTrxWriteQueryTime( $sql, $queryRuntime );
932 $this->mTrxWriteCallers
[] = $fname;
936 if ( $sql === self
::PING_QUERY
) {
937 $this->mRTTEstimate
= $queryRuntime;
940 $this->trxProfiler
->recordQueryCompletion(
941 $queryProf, $startTime, $isWrite, $this->affectedRows()
943 $this->queryLogger
->debug( $sql, [
945 'master' => $isMaster,
946 'runtime' => $queryRuntime,
953 * Update the estimated run-time of a query, not counting large row lock times
955 * LoadBalancer can be set to rollback transactions that will create huge replication
956 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
957 * queries, like inserting a row can take a long time due to row locking. This method
958 * uses some simple heuristics to discount those cases.
960 * @param string $sql A SQL write query
961 * @param float $runtime Total runtime, including RTT
963 private function updateTrxWriteQueryTime( $sql, $runtime ) {
964 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
965 $indicativeOfReplicaRuntime = true;
966 if ( $runtime > self
::SLOW_WRITE_SEC
) {
967 $verb = $this->getQueryVerb( $sql );
968 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
969 if ( $verb === 'INSERT' ) {
970 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
971 } elseif ( $verb === 'REPLACE' ) {
972 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
976 $this->mTrxWriteDuration +
= $runtime;
977 $this->mTrxWriteQueryCount +
= 1;
978 if ( $indicativeOfReplicaRuntime ) {
979 $this->mTrxWriteAdjDuration +
= $runtime;
980 $this->mTrxWriteAdjQueryCount +
= 1;
984 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
985 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
986 # Dropped connections also mean that named locks are automatically released.
987 # Only allow error suppression in autocommit mode or when the lost transaction
988 # didn't matter anyway (aside from DBO_TRX snapshot loss).
989 if ( $this->mNamedLocksHeld
) {
990 return false; // possible critical section violation
991 } elseif ( $sql === 'COMMIT' ) {
992 return !$priorWritesPending; // nothing written anyway? (T127428)
993 } elseif ( $sql === 'ROLLBACK' ) {
994 return true; // transaction lost...which is also what was requested :)
995 } elseif ( $this->explicitTrxActive() ) {
996 return false; // don't drop atomocity
997 } elseif ( $priorWritesPending ) {
998 return false; // prior writes lost from implicit transaction
1004 private function handleSessionLoss() {
1005 $this->mTrxLevel
= 0;
1006 $this->mTrxIdleCallbacks
= []; // bug 65263
1007 $this->mTrxPreCommitCallbacks
= []; // bug 65263
1008 $this->mSessionTempTables
= [];
1009 $this->mNamedLocksHeld
= [];
1011 // Handle callbacks in mTrxEndCallbacks
1012 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1013 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1015 } catch ( Exception
$e ) {
1016 // Already logged; move on...
1021 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1022 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1023 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1025 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1026 $this->queryLogger
->error(
1027 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1028 $this->getLogContext( [
1029 'method' => __METHOD__
,
1032 'sql1line' => $sql1line,
1036 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1037 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1041 public function freeResult( $res ) {
1044 public function selectField(
1045 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1047 if ( $var === '*' ) { // sanity
1048 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1051 if ( !is_array( $options ) ) {
1052 $options = [ $options ];
1055 $options['LIMIT'] = 1;
1057 $res = $this->select( $table, $var, $cond, $fname, $options );
1058 if ( $res === false ||
!$this->numRows( $res ) ) {
1062 $row = $this->fetchRow( $res );
1064 if ( $row !== false ) {
1065 return reset( $row );
1071 public function selectFieldValues(
1072 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1074 if ( $var === '*' ) { // sanity
1075 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1076 } elseif ( !is_string( $var ) ) { // sanity
1077 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1080 if ( !is_array( $options ) ) {
1081 $options = [ $options ];
1084 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1085 if ( $res === false ) {
1090 foreach ( $res as $row ) {
1091 $values[] = $row->$var;
1098 * Returns an optional USE INDEX clause to go after the table, and a
1099 * string to go at the end of the query.
1101 * @param array $options Associative array of options to be turned into
1102 * an SQL query, valid keys are listed in the function.
1104 * @see DatabaseBase::select()
1106 protected function makeSelectOptions( $options ) {
1107 $preLimitTail = $postLimitTail = '';
1112 foreach ( $options as $key => $option ) {
1113 if ( is_numeric( $key ) ) {
1114 $noKeyOptions[$option] = true;
1118 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1120 $preLimitTail .= $this->makeOrderBy( $options );
1122 // if (isset($options['LIMIT'])) {
1123 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1124 // isset($options['OFFSET']) ? $options['OFFSET']
1128 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1129 $postLimitTail .= ' FOR UPDATE';
1132 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1133 $postLimitTail .= ' LOCK IN SHARE MODE';
1136 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1137 $startOpts .= 'DISTINCT';
1140 # Various MySQL extensions
1141 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1142 $startOpts .= ' /*! STRAIGHT_JOIN */';
1145 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1146 $startOpts .= ' HIGH_PRIORITY';
1149 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1150 $startOpts .= ' SQL_BIG_RESULT';
1153 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1154 $startOpts .= ' SQL_BUFFER_RESULT';
1157 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1158 $startOpts .= ' SQL_SMALL_RESULT';
1161 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1162 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1165 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1166 $startOpts .= ' SQL_CACHE';
1169 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1170 $startOpts .= ' SQL_NO_CACHE';
1173 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1174 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1178 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1179 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1184 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1188 * Returns an optional GROUP BY with an optional HAVING
1190 * @param array $options Associative array of options
1192 * @see DatabaseBase::select()
1195 protected function makeGroupByWithHaving( $options ) {
1197 if ( isset( $options['GROUP BY'] ) ) {
1198 $gb = is_array( $options['GROUP BY'] )
1199 ?
implode( ',', $options['GROUP BY'] )
1200 : $options['GROUP BY'];
1201 $sql .= ' GROUP BY ' . $gb;
1203 if ( isset( $options['HAVING'] ) ) {
1204 $having = is_array( $options['HAVING'] )
1205 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1206 : $options['HAVING'];
1207 $sql .= ' HAVING ' . $having;
1214 * Returns an optional ORDER BY
1216 * @param array $options Associative array of options
1218 * @see DatabaseBase::select()
1221 protected function makeOrderBy( $options ) {
1222 if ( isset( $options['ORDER BY'] ) ) {
1223 $ob = is_array( $options['ORDER BY'] )
1224 ?
implode( ',', $options['ORDER BY'] )
1225 : $options['ORDER BY'];
1227 return ' ORDER BY ' . $ob;
1233 // See IDatabase::select for the docs for this function
1234 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1235 $options = [], $join_conds = [] ) {
1236 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1238 return $this->query( $sql, $fname );
1241 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1242 $options = [], $join_conds = []
1244 if ( is_array( $vars ) ) {
1245 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1248 $options = (array)$options;
1249 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1250 ?
$options['USE INDEX']
1252 $ignoreIndexes = ( isset( $options['IGNORE INDEX'] ) && is_array( $options['IGNORE INDEX'] ) )
1253 ?
$options['IGNORE INDEX']
1256 if ( is_array( $table ) ) {
1258 $this->tableNamesWithIndexClauseOrJOIN( $table, $useIndexes, $ignoreIndexes, $join_conds );
1259 } elseif ( $table != '' ) {
1260 if ( $table[0] == ' ' ) {
1261 $from = ' FROM ' . $table;
1264 $this->tableNamesWithIndexClauseOrJOIN( [ $table ], $useIndexes, $ignoreIndexes, [] );
1270 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1271 $this->makeSelectOptions( $options );
1273 if ( !empty( $conds ) ) {
1274 if ( is_array( $conds ) ) {
1275 $conds = $this->makeList( $conds, self
::LIST_AND
);
1277 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex WHERE $conds $preLimitTail";
1279 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1282 if ( isset( $options['LIMIT'] ) ) {
1283 $sql = $this->limitResult( $sql, $options['LIMIT'],
1284 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1286 $sql = "$sql $postLimitTail";
1288 if ( isset( $options['EXPLAIN'] ) ) {
1289 $sql = 'EXPLAIN ' . $sql;
1295 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1296 $options = [], $join_conds = []
1298 $options = (array)$options;
1299 $options['LIMIT'] = 1;
1300 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1302 if ( $res === false ) {
1306 if ( !$this->numRows( $res ) ) {
1310 $obj = $this->fetchObject( $res );
1315 public function estimateRowCount(
1316 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1319 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1322 $row = $this->fetchRow( $res );
1323 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1329 public function selectRowCount(
1330 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1333 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1334 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1337 $row = $this->fetchRow( $res );
1338 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1345 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1346 * It's only slightly flawed. Don't use for anything important.
1348 * @param string $sql A SQL Query
1352 protected static function generalizeSQL( $sql ) {
1353 # This does the same as the regexp below would do, but in such a way
1354 # as to avoid crashing php on some large strings.
1355 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1357 $sql = str_replace( "\\\\", '', $sql );
1358 $sql = str_replace( "\\'", '', $sql );
1359 $sql = str_replace( "\\\"", '', $sql );
1360 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1361 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1363 # All newlines, tabs, etc replaced by single space
1364 $sql = preg_replace( '/\s+/', ' ', $sql );
1367 # except the ones surrounded by characters, e.g. l10n
1368 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1369 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1374 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1375 $info = $this->fieldInfo( $table, $field );
1380 public function indexExists( $table, $index, $fname = __METHOD__
) {
1381 if ( !$this->tableExists( $table ) ) {
1385 $info = $this->indexInfo( $table, $index, $fname );
1386 if ( is_null( $info ) ) {
1389 return $info !== false;
1393 public function tableExists( $table, $fname = __METHOD__
) {
1394 $tableRaw = $this->tableName( $table, 'raw' );
1395 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1396 return true; // already known to exist
1399 $table = $this->tableName( $table );
1400 $old = $this->ignoreErrors( true );
1401 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1402 $this->ignoreErrors( $old );
1407 public function indexUnique( $table, $index ) {
1408 $indexInfo = $this->indexInfo( $table, $index );
1410 if ( !$indexInfo ) {
1414 return !$indexInfo[0]->Non_unique
;
1418 * Helper for DatabaseBase::insert().
1420 * @param array $options
1423 protected function makeInsertOptions( $options ) {
1424 return implode( ' ', $options );
1427 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1428 # No rows to insert, easy just return now
1429 if ( !count( $a ) ) {
1433 $table = $this->tableName( $table );
1435 if ( !is_array( $options ) ) {
1436 $options = [ $options ];
1440 if ( isset( $options['fileHandle'] ) ) {
1441 $fh = $options['fileHandle'];
1443 $options = $this->makeInsertOptions( $options );
1445 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1447 $keys = array_keys( $a[0] );
1450 $keys = array_keys( $a );
1453 $sql = 'INSERT ' . $options .
1454 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1458 foreach ( $a as $row ) {
1464 $sql .= '(' . $this->makeList( $row ) . ')';
1467 $sql .= '(' . $this->makeList( $a ) . ')';
1470 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1472 } elseif ( $fh !== null ) {
1476 return (bool)$this->query( $sql, $fname );
1480 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1482 * @param array $options
1485 protected function makeUpdateOptionsArray( $options ) {
1486 if ( !is_array( $options ) ) {
1487 $options = [ $options ];
1492 if ( in_array( 'IGNORE', $options ) ) {
1500 * Make UPDATE options for the DatabaseBase::update function
1502 * @param array $options The options passed to DatabaseBase::update
1505 protected function makeUpdateOptions( $options ) {
1506 $opts = $this->makeUpdateOptionsArray( $options );
1508 return implode( ' ', $opts );
1511 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1512 $table = $this->tableName( $table );
1513 $opts = $this->makeUpdateOptions( $options );
1514 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1516 if ( $conds !== [] && $conds !== '*' ) {
1517 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1520 return $this->query( $sql, $fname );
1523 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1524 if ( !is_array( $a ) ) {
1525 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1531 foreach ( $a as $field => $value ) {
1533 if ( $mode == self
::LIST_AND
) {
1535 } elseif ( $mode == self
::LIST_OR
) {
1544 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1545 $list .= "($value)";
1546 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1549 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1551 // Remove null from array to be handled separately if found
1552 $includeNull = false;
1553 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1554 $includeNull = true;
1555 unset( $value[$nullKey] );
1557 if ( count( $value ) == 0 && !$includeNull ) {
1558 throw new InvalidArgumentException(
1559 __METHOD__
. ": empty input for field $field" );
1560 } elseif ( count( $value ) == 0 ) {
1561 // only check if $field is null
1562 $list .= "$field IS NULL";
1564 // IN clause contains at least one valid element
1565 if ( $includeNull ) {
1566 // Group subconditions to ensure correct precedence
1569 if ( count( $value ) == 1 ) {
1570 // Special-case single values, as IN isn't terribly efficient
1571 // Don't necessarily assume the single key is 0; we don't
1572 // enforce linear numeric ordering on other arrays here.
1573 $value = array_values( $value )[0];
1574 $list .= $field . " = " . $this->addQuotes( $value );
1576 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1578 // if null present in array, append IS NULL
1579 if ( $includeNull ) {
1580 $list .= " OR $field IS NULL)";
1583 } elseif ( $value === null ) {
1584 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1585 $list .= "$field IS ";
1586 } elseif ( $mode == self
::LIST_SET
) {
1587 $list .= "$field = ";
1592 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1594 $list .= "$field = ";
1596 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1603 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1606 foreach ( $data as $base => $sub ) {
1607 if ( count( $sub ) ) {
1608 $conds[] = $this->makeList(
1609 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1615 return $this->makeList( $conds, self
::LIST_OR
);
1617 // Nothing to search for...
1622 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1626 public function bitNot( $field ) {
1630 public function bitAnd( $fieldLeft, $fieldRight ) {
1631 return "($fieldLeft & $fieldRight)";
1634 public function bitOr( $fieldLeft, $fieldRight ) {
1635 return "($fieldLeft | $fieldRight)";
1638 public function buildConcat( $stringList ) {
1639 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1642 public function buildGroupConcatField(
1643 $delim, $table, $field, $conds = '', $join_conds = []
1645 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1647 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1650 public function buildStringCast( $field ) {
1654 public function selectDB( $db ) {
1655 # Stub. Shouldn't cause serious problems if it's not overridden, but
1656 # if your database engine supports a concept similar to MySQL's
1657 # databases you may as well.
1658 $this->mDBname
= $db;
1663 public function getDBname() {
1664 return $this->mDBname
;
1667 public function getServer() {
1668 return $this->mServer
;
1672 * Format a table name ready for use in constructing an SQL query
1674 * This does two important things: it quotes the table names to clean them up,
1675 * and it adds a table prefix if only given a table name with no quotes.
1677 * All functions of this object which require a table name call this function
1678 * themselves. Pass the canonical name to such functions. This is only needed
1679 * when calling query() directly.
1681 * @note This function does not sanitize user input. It is not safe to use
1682 * this function to escape user input.
1683 * @param string $name Database table name
1684 * @param string $format One of:
1685 * quoted - Automatically pass the table name through addIdentifierQuotes()
1686 * so that it can be used in a query.
1687 * raw - Do not add identifier quotes to the table name
1688 * @return string Full database name
1690 public function tableName( $name, $format = 'quoted' ) {
1691 # Skip the entire process when we have a string quoted on both ends.
1692 # Note that we check the end so that we will still quote any use of
1693 # use of `database`.table. But won't break things if someone wants
1694 # to query a database table with a dot in the name.
1695 if ( $this->isQuotedIdentifier( $name ) ) {
1699 # Lets test for any bits of text that should never show up in a table
1700 # name. Basically anything like JOIN or ON which are actually part of
1701 # SQL queries, but may end up inside of the table value to combine
1702 # sql. Such as how the API is doing.
1703 # Note that we use a whitespace test rather than a \b test to avoid
1704 # any remote case where a word like on may be inside of a table name
1705 # surrounded by symbols which may be considered word breaks.
1706 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1710 # Split database and table into proper variables.
1711 # We reverse the explode so that database.table and table both output
1712 # the correct table.
1713 $dbDetails = explode( '.', $name, 3 );
1714 if ( count( $dbDetails ) == 3 ) {
1715 list( $database, $schema, $table ) = $dbDetails;
1716 # We don't want any prefix added in this case
1718 } elseif ( count( $dbDetails ) == 2 ) {
1719 list( $database, $table ) = $dbDetails;
1720 # We don't want any prefix added in this case
1721 # In dbs that support it, $database may actually be the schema
1722 # but that doesn't affect any of the functionality here
1726 list( $table ) = $dbDetails;
1727 if ( isset( $this->tableAliases
[$table] ) ) {
1728 $database = $this->tableAliases
[$table]['dbname'];
1729 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1730 ?
$this->tableAliases
[$table]['schema']
1732 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1733 ?
$this->tableAliases
[$table]['prefix']
1734 : $this->mTablePrefix
;
1737 $schema = $this->mSchema
; # Default schema
1738 $prefix = $this->mTablePrefix
; # Default prefix
1742 # Quote $table and apply the prefix if not quoted.
1743 # $tableName might be empty if this is called from Database::replaceVars()
1744 $tableName = "{$prefix}{$table}";
1745 if ( $format == 'quoted'
1746 && !$this->isQuotedIdentifier( $tableName ) && $tableName !== ''
1748 $tableName = $this->addIdentifierQuotes( $tableName );
1751 # Quote $schema and merge it with the table name if needed
1752 if ( strlen( $schema ) ) {
1753 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1754 $schema = $this->addIdentifierQuotes( $schema );
1756 $tableName = $schema . '.' . $tableName;
1759 # Quote $database and merge it with the table name if needed
1760 if ( $database !== '' ) {
1761 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1762 $database = $this->addIdentifierQuotes( $database );
1764 $tableName = $database . '.' . $tableName;
1771 * Fetch a number of table names into an array
1772 * This is handy when you need to construct SQL for joins
1775 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1776 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1777 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1781 public function tableNames() {
1782 $inArray = func_get_args();
1785 foreach ( $inArray as $name ) {
1786 $retVal[$name] = $this->tableName( $name );
1793 * Fetch a number of table names into an zero-indexed numerical array
1794 * This is handy when you need to construct SQL for joins
1797 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1798 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1799 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1803 public function tableNamesN() {
1804 $inArray = func_get_args();
1807 foreach ( $inArray as $name ) {
1808 $retVal[] = $this->tableName( $name );
1815 * Get an aliased table name
1816 * e.g. tableName AS newTableName
1818 * @param string $name Table name, see tableName()
1819 * @param string|bool $alias Alias (optional)
1820 * @return string SQL name for aliased table. Will not alias a table to its own name
1822 protected function tableNameWithAlias( $name, $alias = false ) {
1823 if ( !$alias ||
$alias == $name ) {
1824 return $this->tableName( $name );
1826 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1831 * Gets an array of aliased table names
1833 * @param array $tables [ [alias] => table ]
1834 * @return string[] See tableNameWithAlias()
1836 protected function tableNamesWithAlias( $tables ) {
1838 foreach ( $tables as $alias => $table ) {
1839 if ( is_numeric( $alias ) ) {
1842 $retval[] = $this->tableNameWithAlias( $table, $alias );
1849 * Get an aliased field name
1850 * e.g. fieldName AS newFieldName
1852 * @param string $name Field name
1853 * @param string|bool $alias Alias (optional)
1854 * @return string SQL name for aliased field. Will not alias a field to its own name
1856 protected function fieldNameWithAlias( $name, $alias = false ) {
1857 if ( !$alias ||
(string)$alias === (string)$name ) {
1860 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1865 * Gets an array of aliased field names
1867 * @param array $fields [ [alias] => field ]
1868 * @return string[] See fieldNameWithAlias()
1870 protected function fieldNamesWithAlias( $fields ) {
1872 foreach ( $fields as $alias => $field ) {
1873 if ( is_numeric( $alias ) ) {
1876 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1883 * Get the aliased table name clause for a FROM clause
1884 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1886 * @param array $tables ( [alias] => table )
1887 * @param array $use_index Same as for select()
1888 * @param array $ignore_index Same as for select()
1889 * @param array $join_conds Same as for select()
1892 protected function tableNamesWithIndexClauseOrJOIN(
1893 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1897 $use_index = (array)$use_index;
1898 $ignore_index = (array)$ignore_index;
1899 $join_conds = (array)$join_conds;
1901 foreach ( $tables as $alias => $table ) {
1902 if ( !is_string( $alias ) ) {
1903 // No alias? Set it equal to the table name
1906 // Is there a JOIN clause for this table?
1907 if ( isset( $join_conds[$alias] ) ) {
1908 list( $joinType, $conds ) = $join_conds[$alias];
1909 $tableClause = $joinType;
1910 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1911 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1912 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1914 $tableClause .= ' ' . $use;
1917 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
1918 $ignore = $this->ignoreIndexClause( implode( ',', (array)$ignore_index[$alias] ) );
1919 if ( $ignore != '' ) {
1920 $tableClause .= ' ' . $ignore;
1923 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
1925 $tableClause .= ' ON (' . $on . ')';
1928 $retJOIN[] = $tableClause;
1929 } elseif ( isset( $use_index[$alias] ) ) {
1930 // Is there an INDEX clause for this table?
1931 $tableClause = $this->tableNameWithAlias( $table, $alias );
1932 $tableClause .= ' ' . $this->useIndexClause(
1933 implode( ',', (array)$use_index[$alias] )
1936 $ret[] = $tableClause;
1937 } elseif ( isset( $ignore_index[$alias] ) ) {
1938 // Is there an INDEX clause for this table?
1939 $tableClause = $this->tableNameWithAlias( $table, $alias );
1940 $tableClause .= ' ' . $this->ignoreIndexClause(
1941 implode( ',', (array)$ignore_index[$alias] )
1944 $ret[] = $tableClause;
1946 $tableClause = $this->tableNameWithAlias( $table, $alias );
1948 $ret[] = $tableClause;
1952 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1953 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1954 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1956 // Compile our final table clause
1957 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1961 * Get the name of an index in a given table.
1963 * @param string $index
1966 protected function indexName( $index ) {
1967 // Backwards-compatibility hack
1969 'ar_usertext_timestamp' => 'usertext_timestamp',
1970 'un_user_id' => 'user_id',
1971 'un_user_ip' => 'user_ip',
1974 if ( isset( $renamed[$index] ) ) {
1975 return $renamed[$index];
1981 public function addQuotes( $s ) {
1982 if ( $s instanceof Blob
) {
1985 if ( $s === null ) {
1987 } elseif ( is_bool( $s ) ) {
1990 # This will also quote numeric values. This should be harmless,
1991 # and protects against weird problems that occur when they really
1992 # _are_ strings such as article titles and string->number->string
1993 # conversion is not 1:1.
1994 return "'" . $this->strencode( $s ) . "'";
1999 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2000 * MySQL uses `backticks` while basically everything else uses double quotes.
2001 * Since MySQL is the odd one out here the double quotes are our generic
2002 * and we implement backticks in DatabaseMysql.
2007 public function addIdentifierQuotes( $s ) {
2008 return '"' . str_replace( '"', '""', $s ) . '"';
2012 * Returns if the given identifier looks quoted or not according to
2013 * the database convention for quoting identifiers .
2015 * @note Do not use this to determine if untrusted input is safe.
2016 * A malicious user can trick this function.
2017 * @param string $name
2020 public function isQuotedIdentifier( $name ) {
2021 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2028 protected function escapeLikeInternal( $s ) {
2029 return addcslashes( $s, '\%_' );
2032 public function buildLike() {
2033 $params = func_get_args();
2035 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2036 $params = $params[0];
2041 foreach ( $params as $value ) {
2042 if ( $value instanceof LikeMatch
) {
2043 $s .= $value->toString();
2045 $s .= $this->escapeLikeInternal( $value );
2049 return " LIKE {$this->addQuotes( $s )} ";
2052 public function anyChar() {
2053 return new LikeMatch( '_' );
2056 public function anyString() {
2057 return new LikeMatch( '%' );
2060 public function nextSequenceValue( $seqName ) {
2065 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2066 * is only needed because a) MySQL must be as efficient as possible due to
2067 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2068 * which index to pick. Anyway, other databases might have different
2069 * indexes on a given table. So don't bother overriding this unless you're
2071 * @param string $index
2074 public function useIndexClause( $index ) {
2079 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2080 * is only needed because a) MySQL must be as efficient as possible due to
2081 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2082 * which index to pick. Anyway, other databases might have different
2083 * indexes on a given table. So don't bother overriding this unless you're
2085 * @param string $index
2088 public function ignoreIndexClause( $index ) {
2092 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2093 $quotedTable = $this->tableName( $table );
2095 if ( count( $rows ) == 0 ) {
2100 if ( !is_array( reset( $rows ) ) ) {
2104 // @FXIME: this is not atomic, but a trx would break affectedRows()
2105 foreach ( $rows as $row ) {
2106 # Delete rows which collide
2107 if ( $uniqueIndexes ) {
2108 $sql = "DELETE FROM $quotedTable WHERE ";
2110 foreach ( $uniqueIndexes as $index ) {
2117 if ( is_array( $index ) ) {
2119 foreach ( $index as $col ) {
2125 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2128 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2132 $this->query( $sql, $fname );
2135 # Now insert the row
2136 $this->insert( $table, $row, $fname );
2141 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2144 * @param string $table Table name
2145 * @param array|string $rows Row(s) to insert
2146 * @param string $fname Caller function name
2148 * @return ResultWrapper
2150 protected function nativeReplace( $table, $rows, $fname ) {
2151 $table = $this->tableName( $table );
2154 if ( !is_array( reset( $rows ) ) ) {
2158 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2161 foreach ( $rows as $row ) {
2168 $sql .= '(' . $this->makeList( $row ) . ')';
2171 return $this->query( $sql, $fname );
2174 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2177 if ( !count( $rows ) ) {
2178 return true; // nothing to do
2181 if ( !is_array( reset( $rows ) ) ) {
2185 if ( count( $uniqueIndexes ) ) {
2186 $clauses = []; // list WHERE clauses that each identify a single row
2187 foreach ( $rows as $row ) {
2188 foreach ( $uniqueIndexes as $index ) {
2189 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2190 $rowKey = []; // unique key to this row
2191 foreach ( $index as $column ) {
2192 $rowKey[$column] = $row[$column];
2194 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2197 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2202 $useTrx = !$this->mTrxLevel
;
2204 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2207 # Update any existing conflicting row(s)
2208 if ( $where !== false ) {
2209 $ok = $this->update( $table, $set, $where, $fname );
2213 # Now insert any non-conflicting row(s)
2214 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2215 } catch ( Exception
$e ) {
2217 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2222 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2228 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2232 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2235 $delTable = $this->tableName( $delTable );
2236 $joinTable = $this->tableName( $joinTable );
2237 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2238 if ( $conds != '*' ) {
2239 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2243 $this->query( $sql, $fname );
2247 * Returns the size of a text field, or -1 for "unlimited"
2249 * @param string $table
2250 * @param string $field
2253 public function textFieldSize( $table, $field ) {
2254 $table = $this->tableName( $table );
2255 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2256 $res = $this->query( $sql, __METHOD__
);
2257 $row = $this->fetchObject( $res );
2261 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2270 public function delete( $table, $conds, $fname = __METHOD__
) {
2272 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2275 $table = $this->tableName( $table );
2276 $sql = "DELETE FROM $table";
2278 if ( $conds != '*' ) {
2279 if ( is_array( $conds ) ) {
2280 $conds = $this->makeList( $conds, self
::LIST_AND
);
2282 $sql .= ' WHERE ' . $conds;
2285 return $this->query( $sql, $fname );
2288 public function insertSelect(
2289 $destTable, $srcTable, $varMap, $conds,
2290 $fname = __METHOD__
, $insertOptions = [], $selectOptions = []
2292 if ( $this->cliMode
) {
2293 // For massive migrations with downtime, we don't want to select everything
2294 // into memory and OOM, so do all this native on the server side if possible.
2295 return $this->nativeInsertSelect(
2306 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2307 // on only the master (without needing row-based-replication). It also makes it easy to
2308 // know how big the INSERT is going to be.
2310 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2311 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2313 $selectOptions[] = 'FOR UPDATE';
2314 $res = $this->select( $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions );
2320 foreach ( $res as $row ) {
2321 $rows[] = (array)$row;
2324 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2327 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2328 $fname = __METHOD__
,
2329 $insertOptions = [], $selectOptions = []
2331 $destTable = $this->tableName( $destTable );
2333 if ( !is_array( $insertOptions ) ) {
2334 $insertOptions = [ $insertOptions ];
2337 $insertOptions = $this->makeInsertOptions( $insertOptions );
2339 if ( !is_array( $selectOptions ) ) {
2340 $selectOptions = [ $selectOptions ];
2343 list( $startOpts, $useIndex, $tailOpts, $ignoreIndex ) = $this->makeSelectOptions(
2346 if ( is_array( $srcTable ) ) {
2347 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2349 $srcTable = $this->tableName( $srcTable );
2352 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2353 " SELECT $startOpts " . implode( ',', $varMap ) .
2354 " FROM $srcTable $useIndex $ignoreIndex ";
2356 if ( $conds != '*' ) {
2357 if ( is_array( $conds ) ) {
2358 $conds = $this->makeList( $conds, self
::LIST_AND
);
2360 $sql .= " WHERE $conds";
2363 $sql .= " $tailOpts";
2365 return $this->query( $sql, $fname );
2369 * Construct a LIMIT query with optional offset. This is used for query
2370 * pages. The SQL should be adjusted so that only the first $limit rows
2371 * are returned. If $offset is provided as well, then the first $offset
2372 * rows should be discarded, and the next $limit rows should be returned.
2373 * If the result of the query is not ordered, then the rows to be returned
2374 * are theoretically arbitrary.
2376 * $sql is expected to be a SELECT, if that makes a difference.
2378 * The version provided by default works in MySQL and SQLite. It will very
2379 * likely need to be overridden for most other DBMSes.
2381 * @param string $sql SQL query we will append the limit too
2382 * @param int $limit The SQL limit
2383 * @param int|bool $offset The SQL offset (default false)
2384 * @throws DBUnexpectedError
2387 public function limitResult( $sql, $limit, $offset = false ) {
2388 if ( !is_numeric( $limit ) ) {
2389 throw new DBUnexpectedError( $this,
2390 "Invalid non-numeric limit passed to limitResult()\n" );
2393 return "$sql LIMIT "
2394 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2398 public function unionSupportsOrderAndLimit() {
2399 return true; // True for almost every DB supported
2402 public function unionQueries( $sqls, $all ) {
2403 $glue = $all ?
') UNION ALL (' : ') UNION (';
2405 return '(' . implode( $glue, $sqls ) . ')';
2408 public function conditional( $cond, $trueVal, $falseVal ) {
2409 if ( is_array( $cond ) ) {
2410 $cond = $this->makeList( $cond, self
::LIST_AND
);
2413 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2416 public function strreplace( $orig, $old, $new ) {
2417 return "REPLACE({$orig}, {$old}, {$new})";
2420 public function getServerUptime() {
2424 public function wasDeadlock() {
2428 public function wasLockTimeout() {
2432 public function wasErrorReissuable() {
2436 public function wasReadOnlyError() {
2441 * Do no use the class outside of Database/DBError classes
2443 * @param integer|string $errno
2444 * @return bool Whether the given query error was a connection drop
2446 public function wasConnectionError( $errno ) {
2451 * Perform a deadlock-prone transaction.
2453 * This function invokes a callback function to perform a set of write
2454 * queries. If a deadlock occurs during the processing, the transaction
2455 * will be rolled back and the callback function will be called again.
2457 * Avoid using this method outside of Job or Maintenance classes.
2460 * $dbw->deadlockLoop( callback, ... );
2462 * Extra arguments are passed through to the specified callback function.
2463 * This method requires that no transactions are already active to avoid
2464 * causing premature commits or exceptions.
2466 * Returns whatever the callback function returned on its successful,
2467 * iteration, or false on error, for example if the retry limit was
2471 * @throws DBUnexpectedError
2474 public function deadlockLoop() {
2475 $args = func_get_args();
2476 $function = array_shift( $args );
2477 $tries = self
::DEADLOCK_TRIES
;
2479 $this->begin( __METHOD__
);
2482 /** @var Exception $e */
2486 $retVal = call_user_func_array( $function, $args );
2488 } catch ( DBQueryError
$e ) {
2489 if ( $this->wasDeadlock() ) {
2490 // Retry after a randomized delay
2491 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2493 // Throw the error back up
2497 } while ( --$tries > 0 );
2499 if ( $tries <= 0 ) {
2500 // Too many deadlocks; give up
2501 $this->rollback( __METHOD__
);
2504 $this->commit( __METHOD__
);
2510 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2511 # Real waits are implemented in the subclass.
2515 public function getSlavePos() {
2520 public function getMasterPos() {
2525 public function serverIsReadOnly() {
2529 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2530 if ( !$this->mTrxLevel
) {
2531 throw new DBUnexpectedError( $this, "No transaction is active." );
2533 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2536 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2537 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2538 if ( !$this->mTrxLevel
) {
2539 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2543 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2544 if ( $this->mTrxLevel
) {
2545 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2547 // If no transaction is active, then make one for this callback
2548 $this->startAtomic( __METHOD__
);
2550 call_user_func( $callback );
2551 $this->endAtomic( __METHOD__
);
2552 } catch ( Exception
$e ) {
2553 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2559 final public function setTransactionListener( $name, callable
$callback = null ) {
2561 $this->mTrxRecurringCallbacks
[$name] = $callback;
2563 unset( $this->mTrxRecurringCallbacks
[$name] );
2568 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2570 * This method should not be used outside of Database/LoadBalancer
2572 * @param bool $suppress
2575 final public function setTrxEndCallbackSuppression( $suppress ) {
2576 $this->mTrxEndCallbacksSuppressed
= $suppress;
2580 * Actually run and consume any "on transaction idle/resolution" callbacks.
2582 * This method should not be used outside of Database/LoadBalancer
2584 * @param integer $trigger IDatabase::TRIGGER_* constant
2588 public function runOnTransactionIdleCallbacks( $trigger ) {
2589 if ( $this->mTrxEndCallbacksSuppressed
) {
2593 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2594 /** @var Exception $e */
2595 $e = null; // first exception
2596 do { // callbacks may add callbacks :)
2597 $callbacks = array_merge(
2598 $this->mTrxIdleCallbacks
,
2599 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2601 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2602 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2603 foreach ( $callbacks as $callback ) {
2605 list( $phpCallback ) = $callback;
2606 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2607 call_user_func_array( $phpCallback, [ $trigger ] );
2609 $this->setFlag( DBO_TRX
); // restore automatic begin()
2611 $this->clearFlag( DBO_TRX
); // restore auto-commit
2613 } catch ( Exception
$ex ) {
2614 call_user_func( $this->errorLogger
, $ex );
2616 // Some callbacks may use startAtomic/endAtomic, so make sure
2617 // their transactions are ended so other callbacks don't fail
2618 if ( $this->trxLevel() ) {
2619 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2623 } while ( count( $this->mTrxIdleCallbacks
) );
2625 if ( $e instanceof Exception
) {
2626 throw $e; // re-throw any first exception
2631 * Actually run and consume any "on transaction pre-commit" callbacks.
2633 * This method should not be used outside of Database/LoadBalancer
2638 public function runOnTransactionPreCommitCallbacks() {
2639 $e = null; // first exception
2640 do { // callbacks may add callbacks :)
2641 $callbacks = $this->mTrxPreCommitCallbacks
;
2642 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2643 foreach ( $callbacks as $callback ) {
2645 list( $phpCallback ) = $callback;
2646 call_user_func( $phpCallback );
2647 } catch ( Exception
$ex ) {
2648 call_user_func( $this->errorLogger
, $ex );
2652 } while ( count( $this->mTrxPreCommitCallbacks
) );
2654 if ( $e instanceof Exception
) {
2655 throw $e; // re-throw any first exception
2660 * Actually run any "transaction listener" callbacks.
2662 * This method should not be used outside of Database/LoadBalancer
2664 * @param integer $trigger IDatabase::TRIGGER_* constant
2668 public function runTransactionListenerCallbacks( $trigger ) {
2669 if ( $this->mTrxEndCallbacksSuppressed
) {
2673 /** @var Exception $e */
2674 $e = null; // first exception
2676 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2678 $phpCallback( $trigger, $this );
2679 } catch ( Exception
$ex ) {
2680 call_user_func( $this->errorLogger
, $ex );
2685 if ( $e instanceof Exception
) {
2686 throw $e; // re-throw any first exception
2690 final public function startAtomic( $fname = __METHOD__
) {
2691 if ( !$this->mTrxLevel
) {
2692 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2693 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2694 // in all changes being in one transaction to keep requests transactional.
2695 if ( !$this->getFlag( DBO_TRX
) ) {
2696 $this->mTrxAutomaticAtomic
= true;
2700 $this->mTrxAtomicLevels
[] = $fname;
2703 final public function endAtomic( $fname = __METHOD__
) {
2704 if ( !$this->mTrxLevel
) {
2705 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2707 if ( !$this->mTrxAtomicLevels ||
2708 array_pop( $this->mTrxAtomicLevels
) !== $fname
2710 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2713 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2714 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2718 final public function doAtomicSection( $fname, callable
$callback ) {
2719 $this->startAtomic( $fname );
2721 $res = call_user_func_array( $callback, [ $this, $fname ] );
2722 } catch ( Exception
$e ) {
2723 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2726 $this->endAtomic( $fname );
2731 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2732 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2733 if ( $this->mTrxLevel
) {
2734 if ( $this->mTrxAtomicLevels
) {
2735 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2736 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2737 throw new DBUnexpectedError( $this, $msg );
2738 } elseif ( !$this->mTrxAutomatic
) {
2739 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2740 throw new DBUnexpectedError( $this, $msg );
2742 // @TODO: make this an exception at some point
2743 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2744 $this->queryLogger
->error( $msg );
2745 return; // join the main transaction set
2747 } elseif ( $this->getFlag( DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2748 // @TODO: make this an exception at some point
2749 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2750 $this->queryLogger
->error( $msg );
2751 return; // let any writes be in the main transaction
2754 // Avoid fatals if close() was called
2755 $this->assertOpen();
2757 $this->doBegin( $fname );
2758 $this->mTrxTimestamp
= microtime( true );
2759 $this->mTrxFname
= $fname;
2760 $this->mTrxDoneWrites
= false;
2761 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2762 $this->mTrxAutomaticAtomic
= false;
2763 $this->mTrxAtomicLevels
= [];
2764 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2765 $this->mTrxWriteDuration
= 0.0;
2766 $this->mTrxWriteQueryCount
= 0;
2767 $this->mTrxWriteAdjDuration
= 0.0;
2768 $this->mTrxWriteAdjQueryCount
= 0;
2769 $this->mTrxWriteCallers
= [];
2770 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2771 // Get an estimate of the replica DB lag before then, treating estimate staleness
2772 // as lag itself just to be safe
2773 $status = $this->getApproximateLagStatus();
2774 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2778 * Issues the BEGIN command to the database server.
2780 * @see DatabaseBase::begin()
2781 * @param string $fname
2783 protected function doBegin( $fname ) {
2784 $this->query( 'BEGIN', $fname );
2785 $this->mTrxLevel
= 1;
2788 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2789 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2790 // There are still atomic sections open. This cannot be ignored
2791 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2792 throw new DBUnexpectedError(
2794 "$fname: Got COMMIT while atomic sections $levels are still open."
2798 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2799 if ( !$this->mTrxLevel
) {
2800 return; // nothing to do
2801 } elseif ( !$this->mTrxAutomatic
) {
2802 throw new DBUnexpectedError(
2804 "$fname: Flushing an explicit transaction, getting out of sync."
2808 if ( !$this->mTrxLevel
) {
2809 $this->queryLogger
->error( "$fname: No transaction to commit, something got out of sync." );
2810 return; // nothing to do
2811 } elseif ( $this->mTrxAutomatic
) {
2812 // @TODO: make this an exception at some point
2813 $msg = "$fname: Explicit commit of implicit transaction.";
2814 $this->queryLogger
->error( $msg );
2815 return; // wait for the main transaction set commit round
2819 // Avoid fatals if close() was called
2820 $this->assertOpen();
2822 $this->runOnTransactionPreCommitCallbacks();
2823 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2824 $this->doCommit( $fname );
2825 if ( $this->mTrxDoneWrites
) {
2826 $this->mDoneWrites
= microtime( true );
2827 $this->trxProfiler
->transactionWritingOut(
2828 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2831 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2832 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2836 * Issues the COMMIT command to the database server.
2838 * @see DatabaseBase::commit()
2839 * @param string $fname
2841 protected function doCommit( $fname ) {
2842 if ( $this->mTrxLevel
) {
2843 $this->query( 'COMMIT', $fname );
2844 $this->mTrxLevel
= 0;
2848 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2849 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2850 if ( !$this->mTrxLevel
) {
2851 return; // nothing to do
2854 if ( !$this->mTrxLevel
) {
2855 $this->queryLogger
->error(
2856 "$fname: No transaction to rollback, something got out of sync." );
2857 return; // nothing to do
2858 } elseif ( $this->getFlag( DBO_TRX
) ) {
2859 throw new DBUnexpectedError(
2861 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2866 // Avoid fatals if close() was called
2867 $this->assertOpen();
2869 $this->doRollback( $fname );
2870 $this->mTrxAtomicLevels
= [];
2871 if ( $this->mTrxDoneWrites
) {
2872 $this->trxProfiler
->transactionWritingOut(
2873 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2876 $this->mTrxIdleCallbacks
= []; // clear
2877 $this->mTrxPreCommitCallbacks
= []; // clear
2878 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
2879 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
2883 * Issues the ROLLBACK command to the database server.
2885 * @see DatabaseBase::rollback()
2886 * @param string $fname
2888 protected function doRollback( $fname ) {
2889 if ( $this->mTrxLevel
) {
2890 # Disconnects cause rollback anyway, so ignore those errors
2891 $ignoreErrors = true;
2892 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
2893 $this->mTrxLevel
= 0;
2897 public function flushSnapshot( $fname = __METHOD__
) {
2898 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
2899 // This only flushes transactions to clear snapshots, not to write data
2900 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
2901 throw new DBUnexpectedError(
2903 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
2907 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2910 public function explicitTrxActive() {
2911 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
2915 * Creates a new table with structure copied from existing table
2916 * Note that unlike most database abstraction functions, this function does not
2917 * automatically append database prefix, because it works at a lower
2918 * abstraction level.
2919 * The table names passed to this function shall not be quoted (this
2920 * function calls addIdentifierQuotes when needed).
2922 * @param string $oldName Name of table whose structure should be copied
2923 * @param string $newName Name of table to be created
2924 * @param bool $temporary Whether the new table should be temporary
2925 * @param string $fname Calling function name
2926 * @throws RuntimeException
2927 * @return bool True if operation was successful
2929 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2932 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2935 public function listTables( $prefix = null, $fname = __METHOD__
) {
2936 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2940 * Reset the views process cache set by listViews()
2943 final public function clearViewsCache() {
2944 $this->allViews
= null;
2948 * Lists all the VIEWs in the database
2950 * For caching purposes the list of all views should be stored in
2951 * $this->allViews. The process cache can be cleared with clearViewsCache()
2953 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2954 * @param string $fname Name of calling function
2955 * @throws RuntimeException
2959 public function listViews( $prefix = null, $fname = __METHOD__
) {
2960 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2964 * Differentiates between a TABLE and a VIEW
2966 * @param string $name Name of the database-structure to test.
2967 * @throws RuntimeException
2971 public function isView( $name ) {
2972 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
2975 public function timestamp( $ts = 0 ) {
2976 $t = new ConvertibleTimestamp( $ts );
2977 // Let errors bubble up to avoid putting garbage in the DB
2978 return $t->getTimestamp( TS_MW
);
2981 public function timestampOrNull( $ts = null ) {
2982 if ( is_null( $ts ) ) {
2985 return $this->timestamp( $ts );
2990 * Take the result from a query, and wrap it in a ResultWrapper if
2991 * necessary. Boolean values are passed through as is, to indicate success
2992 * of write queries or failure.
2994 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2995 * resource, and it was necessary to call this function to convert it to
2996 * a wrapper. Nowadays, raw database objects are never exposed to external
2997 * callers, so this is unnecessary in external code.
2999 * @param bool|ResultWrapper|resource|object $result
3000 * @return bool|ResultWrapper
3002 protected function resultObject( $result ) {
3005 } elseif ( $result instanceof ResultWrapper
) {
3007 } elseif ( $result === true ) {
3008 // Successful write query
3011 return new ResultWrapper( $this, $result );
3015 public function ping( &$rtt = null ) {
3016 // Avoid hitting the server if it was hit recently
3017 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3018 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3019 $rtt = $this->mRTTEstimate
;
3020 return true; // don't care about $rtt
3024 // This will reconnect if possible or return false if not
3025 $this->clearFlag( DBO_TRX
, self
::REMEMBER_PRIOR
);
3026 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3027 $this->restoreFlags( self
::RESTORE_PRIOR
);
3030 $rtt = $this->mRTTEstimate
;
3039 protected function reconnect() {
3040 $this->closeConnection();
3041 $this->mOpened
= false;
3042 $this->mConn
= false;
3044 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3045 $this->lastPing
= microtime( true );
3047 } catch ( DBConnectionError
$e ) {
3054 public function getSessionLagStatus() {
3055 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3059 * Get the replica DB lag when the current transaction started
3061 * This is useful when transactions might use snapshot isolation
3062 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3063 * is this lag plus transaction duration. If they don't, it is still
3064 * safe to be pessimistic. This returns null if there is no transaction.
3066 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3069 protected function getTransactionLagStatus() {
3070 return $this->mTrxLevel
3071 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3076 * Get a replica DB lag estimate for this server
3078 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3081 protected function getApproximateLagStatus() {
3083 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3084 'since' => microtime( true )
3089 * Merge the result of getSessionLagStatus() for several DBs
3090 * using the most pessimistic values to estimate the lag of
3091 * any data derived from them in combination
3093 * This is information is useful for caching modules
3095 * @see WANObjectCache::set()
3096 * @see WANObjectCache::getWithSetCallback()
3098 * @param IDatabase $db1
3099 * @param IDatabase ...
3100 * @return array Map of values:
3101 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3102 * - since: oldest UNIX timestamp of any of the DB lag estimates
3103 * - pending: whether any of the DBs have uncommitted changes
3106 public static function getCacheSetOptions( IDatabase
$db1 ) {
3107 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3108 foreach ( func_get_args() as $db ) {
3109 /** @var IDatabase $db */
3110 $status = $db->getSessionLagStatus();
3111 if ( $status['lag'] === false ) {
3112 $res['lag'] = false;
3113 } elseif ( $res['lag'] !== false ) {
3114 $res['lag'] = max( $res['lag'], $status['lag'] );
3116 $res['since'] = min( $res['since'], $status['since'] );
3117 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3123 public function getLag() {
3127 public function maxListLen() {
3131 public function encodeBlob( $b ) {
3135 public function decodeBlob( $b ) {
3136 if ( $b instanceof Blob
) {
3142 public function setSessionOptions( array $options ) {
3146 * Read and execute SQL commands from a file.
3148 * Returns true on success, error string or exception on failure (depending
3149 * on object's error ignore settings).
3151 * @param string $filename File name to open
3152 * @param bool|callable $lineCallback Optional function called before reading each line
3153 * @param bool|callable $resultCallback Optional function called for each MySQL result
3154 * @param bool|string $fname Calling function name or false if name should be
3155 * generated dynamically using $filename
3156 * @param bool|callable $inputCallback Optional function called for each
3157 * complete line sent
3158 * @return bool|string
3161 public function sourceFile(
3162 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3164 MediaWiki\
suppressWarnings();
3165 $fp = fopen( $filename, 'r' );
3166 MediaWiki\restoreWarnings
();
3168 if ( false === $fp ) {
3169 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3173 $fname = __METHOD__
. "( $filename )";
3177 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3178 } catch ( Exception
$e ) {
3188 public function setSchemaVars( $vars ) {
3189 $this->mSchemaVars
= $vars;
3193 * Read and execute commands from an open file handle.
3195 * Returns true on success, error string or exception on failure (depending
3196 * on object's error ignore settings).
3198 * @param resource $fp File handle
3199 * @param bool|callable $lineCallback Optional function called before reading each query
3200 * @param bool|callable $resultCallback Optional function called for each MySQL result
3201 * @param string $fname Calling function name
3202 * @param bool|callable $inputCallback Optional function called for each complete query sent
3203 * @return bool|string
3205 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3206 $fname = __METHOD__
, $inputCallback = false
3210 while ( !feof( $fp ) ) {
3211 if ( $lineCallback ) {
3212 call_user_func( $lineCallback );
3215 $line = trim( fgets( $fp ) );
3217 if ( $line == '' ) {
3221 if ( '-' == $line[0] && '-' == $line[1] ) {
3229 $done = $this->streamStatementEnd( $cmd, $line );
3233 if ( $done ||
feof( $fp ) ) {
3234 $cmd = $this->replaceVars( $cmd );
3236 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3237 $res = $this->query( $cmd, $fname );
3239 if ( $resultCallback ) {
3240 call_user_func( $resultCallback, $res, $this );
3243 if ( false === $res ) {
3244 $err = $this->lastError();
3246 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3257 * Called by sourceStream() to check if we've reached a statement end
3259 * @param string $sql SQL assembled so far
3260 * @param string $newLine New line about to be added to $sql
3261 * @return bool Whether $newLine contains end of the statement
3263 public function streamStatementEnd( &$sql, &$newLine ) {
3264 if ( $this->delimiter
) {
3266 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3267 if ( $newLine != $prev ) {
3276 * Database independent variable replacement. Replaces a set of variables
3277 * in an SQL statement with their contents as given by $this->getSchemaVars().
3279 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3281 * - '{$var}' should be used for text and is passed through the database's
3283 * - `{$var}` should be used for identifiers (e.g. table and database names).
3284 * It is passed through the database's addIdentifierQuotes method which
3285 * can be overridden if the database uses something other than backticks.
3286 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3287 * database's tableName method.
3288 * - / *i* / passes the name that follows through the database's indexName method.
3289 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3290 * its use should be avoided. In 1.24 and older, string encoding was applied.
3292 * @param string $ins SQL statement to replace variables in
3293 * @return string The new SQL statement with variables replaced
3295 protected function replaceVars( $ins ) {
3296 $vars = $this->getSchemaVars();
3297 return preg_replace_callback(
3299 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3300 \'\{\$ (\w+) }\' | # 3. addQuotes
3301 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3302 /\*\$ (\w+) \*/ # 5. leave unencoded
3304 function ( $m ) use ( $vars ) {
3305 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3306 // check for both nonexistent keys *and* the empty string.
3307 if ( isset( $m[1] ) && $m[1] !== '' ) {
3308 if ( $m[1] === 'i' ) {
3309 return $this->indexName( $m[2] );
3311 return $this->tableName( $m[2] );
3313 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3314 return $this->addQuotes( $vars[$m[3]] );
3315 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3316 return $this->addIdentifierQuotes( $vars[$m[4]] );
3317 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3318 return $vars[$m[5]];
3328 * Get schema variables. If none have been set via setSchemaVars(), then
3329 * use some defaults from the current object.
3333 protected function getSchemaVars() {
3334 if ( $this->mSchemaVars
) {
3335 return $this->mSchemaVars
;
3337 return $this->getDefaultSchemaVars();
3342 * Get schema variables to use if none have been set via setSchemaVars().
3344 * Override this in derived classes to provide variables for tables.sql
3345 * and SQL patch files.
3349 protected function getDefaultSchemaVars() {
3353 public function lockIsFree( $lockName, $method ) {
3357 public function lock( $lockName, $method, $timeout = 5 ) {
3358 $this->mNamedLocksHeld
[$lockName] = 1;
3363 public function unlock( $lockName, $method ) {
3364 unset( $this->mNamedLocksHeld
[$lockName] );
3369 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3370 if ( $this->writesOrCallbacksPending() ) {
3371 // This only flushes transactions to clear snapshots, not to write data
3372 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3373 throw new DBUnexpectedError(
3375 "$fname: Cannot COMMIT to clear snapshot because writes are pending ($fnames)."
3379 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3383 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3384 if ( $this->trxLevel() ) {
3385 // There is a good chance an exception was thrown, causing any early return
3386 // from the caller. Let any error handler get a chance to issue rollback().
3387 // If there isn't one, let the error bubble up and trigger server-side rollback.
3388 $this->onTransactionResolution(
3389 function () use ( $lockKey, $fname ) {
3390 $this->unlock( $lockKey, $fname );
3395 $this->unlock( $lockKey, $fname );
3399 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3404 public function namedLocksEnqueue() {
3409 * Lock specific tables
3411 * @param array $read Array of tables to lock for read access
3412 * @param array $write Array of tables to lock for write access
3413 * @param string $method Name of caller
3414 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3417 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3422 * Unlock specific tables
3424 * @param string $method The caller
3427 public function unlockTables( $method ) {
3433 * @param string $tableName
3434 * @param string $fName
3435 * @return bool|ResultWrapper
3438 public function dropTable( $tableName, $fName = __METHOD__
) {
3439 if ( !$this->tableExists( $tableName, $fName ) ) {
3442 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3444 return $this->query( $sql, $fName );
3447 public function getInfinity() {
3451 public function encodeExpiry( $expiry ) {
3452 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3453 ?
$this->getInfinity()
3454 : $this->timestamp( $expiry );
3457 public function decodeExpiry( $expiry, $format = TS_MW
) {
3458 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3462 return ConvertibleTimestamp
::convert( $format, $expiry );
3465 public function setBigSelects( $value = true ) {
3469 public function isReadOnly() {
3470 return ( $this->getReadOnlyReason() !== false );
3474 * @return string|bool Reason this DB is read-only or false if it is not
3476 protected function getReadOnlyReason() {
3477 $reason = $this->getLBInfo( 'readOnlyReason' );
3479 return is_string( $reason ) ?
$reason : false;
3482 public function setTableAliases( array $aliases ) {
3483 $this->tableAliases
= $aliases;
3487 * @return bool Whether a DB user is required to access the DB
3490 protected function requiresDatabaseUser() {
3498 public function __toString() {
3499 return (string)$this->mConn
;
3503 * Make sure that copies do not share the same client binding handle
3504 * @throws DBConnectionError
3506 public function __clone() {
3507 $this->connLogger
->warning(
3508 "Cloning " . get_class( $this ) . " is not recomended; forking connection:\n" .
3509 ( new RuntimeException() )->getTraceAsString()
3512 if ( $this->isOpen() ) {
3513 // Open a new connection resource without messing with the old one
3514 $this->mOpened
= false;
3515 $this->mConn
= false;
3516 $this->mTrxEndCallbacks
= []; // don't copy
3517 $this->handleSessionLoss(); // no trx or locks anymore
3518 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3519 $this->lastPing
= microtime( true );
3524 * Called by serialize. Throw an exception when DB connection is serialized.
3525 * This causes problems on some database engines because the connection is
3526 * not restored on unserialize.
3528 public function __sleep() {
3529 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3530 'the connection is not restored on wakeup.' );
3534 * Run a few simple sanity checks and close dangling connections
3536 public function __destruct() {
3537 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3538 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3541 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3542 if ( $danglingWriters ) {
3543 $fnames = implode( ', ', $danglingWriters );
3544 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3547 if ( $this->mConn
) {
3548 // Avoid connection leaks for sanity
3549 $this->closeConnection();
3550 $this->mConn
= false;
3551 $this->mOpened
= false;