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 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Wikimedia\ScopedCallback
;
31 use Wikimedia\Timestamp\ConvertibleTimestamp
;
35 use InvalidArgumentException
;
40 * Relational database abstraction object
45 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
46 /** Number of times to re-try an operation in case of deadlock */
47 const DEADLOCK_TRIES
= 4;
48 /** Minimum time to wait before retry, in microseconds */
49 const DEADLOCK_DELAY_MIN
= 500000;
50 /** Maximum time to wait before retry */
51 const DEADLOCK_DELAY_MAX
= 1500000;
53 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_QUERY
= 'SELECT 1 AS ping';
57 const TINY_WRITE_SEC
= .010;
58 const SLOW_WRITE_SEC
= .500;
59 const SMALL_WRITE_ROWS
= 100;
61 /** @var string SQL query */
62 protected $mLastQuery = '';
63 /** @var float|bool UNIX timestamp of last write query */
64 protected $mLastWriteTime = false;
65 /** @var string|bool */
66 protected $mPHPError = false;
75 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
76 protected $tableAliases = [];
77 /** @var bool Whether this PHP instance is for a CLI script */
79 /** @var string Agent name for query profiling */
82 /** @var BagOStuff APC cache */
84 /** @var LoggerInterface */
85 protected $connLogger;
86 /** @var LoggerInterface */
87 protected $queryLogger;
88 /** @var callback Error logging callback */
89 protected $errorLogger;
91 /** @var resource|null Database connection */
92 protected $mConn = null;
94 protected $mOpened = false;
96 /** @var array[] List of (callable, method name) */
97 protected $mTrxIdleCallbacks = [];
98 /** @var array[] List of (callable, method name) */
99 protected $mTrxPreCommitCallbacks = [];
100 /** @var array[] List of (callable, method name) */
101 protected $mTrxEndCallbacks = [];
102 /** @var callable[] Map of (name => callable) */
103 protected $mTrxRecurringCallbacks = [];
104 /** @var bool Whether to suppress triggering of transaction end callbacks */
105 protected $mTrxEndCallbacksSuppressed = false;
108 protected $mTablePrefix = '';
110 protected $mSchema = '';
114 protected $mLBInfo = [];
115 /** @var bool|null */
116 protected $mDefaultBigSelects = null;
117 /** @var array|bool */
118 protected $mSchemaVars = false;
120 protected $mSessionVars = [];
121 /** @var array|null */
122 protected $preparedArgs;
123 /** @var string|bool|null Stashed value of html_errors INI setting */
124 protected $htmlErrors;
126 protected $delimiter = ';';
127 /** @var DatabaseDomain */
128 protected $currentDomain;
131 * Either 1 if a transaction is active or 0 otherwise.
132 * The other Trx fields may not be meaningfull if this is 0.
136 protected $mTrxLevel = 0;
138 * Either a short hexidecimal string if a transaction is active or ""
141 * @see Database::mTrxLevel
143 protected $mTrxShortId = '';
145 * The UNIX time that the transaction started. Callers can assume that if
146 * snapshot isolation is used, then the data is *at least* up to date to that
147 * point (possibly more up-to-date since the first SELECT defines the snapshot).
150 * @see Database::mTrxLevel
152 private $mTrxTimestamp = null;
153 /** @var float Lag estimate at the time of BEGIN */
154 private $mTrxReplicaLag = null;
156 * Remembers the function name given for starting the most recent transaction via begin().
157 * Used to provide additional context for error reporting.
160 * @see Database::mTrxLevel
162 private $mTrxFname = null;
164 * Record if possible write queries were done in the last transaction started
167 * @see Database::mTrxLevel
169 private $mTrxDoneWrites = false;
171 * Record if the current transaction was started implicitly due to DBO_TRX being set.
174 * @see Database::mTrxLevel
176 private $mTrxAutomatic = false;
178 * Array of levels of atomicity within transactions
182 private $mTrxAtomicLevels = [];
184 * Record if the current transaction was started implicitly by Database::startAtomic
188 private $mTrxAutomaticAtomic = false;
190 * Track the write query callers of the current transaction
194 private $mTrxWriteCallers = [];
196 * @var float Seconds spent in write queries for the current transaction
198 private $mTrxWriteDuration = 0.0;
200 * @var integer Number of write queries for the current transaction
202 private $mTrxWriteQueryCount = 0;
204 * @var integer Number of rows affected by write queries for the current transaction
206 private $mTrxWriteAffectedRows = 0;
208 * @var float Like mTrxWriteQueryCount but excludes lock-bound, easy to replicate, queries
210 private $mTrxWriteAdjDuration = 0.0;
212 * @var integer Number of write queries counted in mTrxWriteAdjDuration
214 private $mTrxWriteAdjQueryCount = 0;
216 * @var float RTT time estimate
218 private $mRTTEstimate = 0.0;
220 /** @var array Map of (name => 1) for locks obtained via lock() */
221 private $mNamedLocksHeld = [];
222 /** @var array Map of (table name => 1) for TEMPORARY tables */
223 protected $mSessionTempTables = [];
225 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
226 private $lazyMasterHandle;
228 /** @var float UNIX timestamp */
229 protected $lastPing = 0.0;
231 /** @var int[] Prior mFlags values */
232 private $priorFlags = [];
234 /** @var object|string Class name or object With profileIn/profileOut methods */
236 /** @var TransactionProfiler */
237 protected $trxProfiler;
240 * Constructor and database handle and attempt to connect to the DB server
242 * IDatabase classes should not be constructed directly in external
243 * code. Database::factory() should be used instead.
245 * @param array $params Parameters passed from Database::factory()
247 function __construct( array $params ) {
248 $server = $params['host'];
249 $user = $params['user'];
250 $password = $params['password'];
251 $dbName = $params['dbname'];
253 $this->mSchema
= $params['schema'];
254 $this->mTablePrefix
= $params['tablePrefix'];
256 $this->cliMode
= $params['cliMode'];
257 // Agent name is added to SQL queries in a comment, so make sure it can't break out
258 $this->agent
= str_replace( '/', '-', $params['agent'] );
260 $this->mFlags
= $params['flags'];
261 if ( $this->mFlags
& self
::DBO_DEFAULT
) {
262 if ( $this->cliMode
) {
263 $this->mFlags
&= ~self
::DBO_TRX
;
265 $this->mFlags |
= self
::DBO_TRX
;
269 $this->mSessionVars
= $params['variables'];
271 $this->srvCache
= isset( $params['srvCache'] )
272 ?
$params['srvCache']
273 : new HashBagOStuff();
275 $this->profiler
= $params['profiler'];
276 $this->trxProfiler
= $params['trxProfiler'];
277 $this->connLogger
= $params['connLogger'];
278 $this->queryLogger
= $params['queryLogger'];
279 $this->errorLogger
= $params['errorLogger'];
281 // Set initial dummy domain until open() sets the final DB/prefix
282 $this->currentDomain
= DatabaseDomain
::newUnspecified();
285 $this->open( $server, $user, $password, $dbName );
286 } elseif ( $this->requiresDatabaseUser() ) {
287 throw new InvalidArgumentException( "No database user provided." );
290 // Set the domain object after open() sets the relevant fields
291 if ( $this->mDBname
!= '' ) {
292 // Domains with server scope but a table prefix are not used by IDatabase classes
293 $this->currentDomain
= new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
);
298 * Construct a Database subclass instance given a database type and parameters
300 * This also connects to the database immediately upon object construction
302 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
303 * @param array $p Parameter map with keys:
304 * - host : The hostname of the DB server
305 * - user : The name of the database user the client operates under
306 * - password : The password for the database user
307 * - dbname : The name of the database to use where queries do not specify one.
308 * The database must exist or an error might be thrown. Setting this to the empty string
309 * will avoid any such errors and make the handle have no implicit database scope. This is
310 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
311 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
312 * in which user names and such are defined, e.g. users are database-specific in Postgres.
313 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
314 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
315 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
316 * recognized in queries. This can be used in place of schemas for handle site farms.
317 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
318 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
319 * flag in place UNLESS this this database simply acts as a key/value store.
320 * - driver: Optional name of a specific DB client driver. For MySQL, there is the old
321 * 'mysql' driver and the newer 'mysqli' driver.
322 * - variables: Optional map of session variables to set after connecting. This can be
323 * used to adjust lock timeouts or encoding modes and the like.
324 * - connLogger: Optional PSR-3 logger interface instance.
325 * - queryLogger: Optional PSR-3 logger interface instance.
326 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
327 * These will be called in query(), using a simplified version of the SQL that also
328 * includes the agent as a SQL comment.
329 * - trxProfiler: Optional TransactionProfiler instance.
330 * - errorLogger: Optional callback that takes an Exception and logs it.
331 * - cliMode: Whether to consider the execution context that of a CLI script.
332 * - agent: Optional name used to identify the end-user in query profiling/logging.
333 * - srvCache: Optional BagOStuff instance to an APC-style cache.
334 * @return Database|null If the database driver or extension cannot be found
335 * @throws InvalidArgumentException If the database driver or extension cannot be found
338 final public static function factory( $dbType, $p = [] ) {
339 static $canonicalDBTypes = [
340 'mysql' => [ 'mysqli', 'mysql' ],
346 static $classAliases = [
347 'DatabaseMssql' => DatabaseMssql
::class,
348 'DatabaseMysql' => DatabaseMysql
::class,
349 'DatabaseMysqli' => DatabaseMysqli
::class,
350 'DatabaseSqlite' => DatabaseSqlite
::class,
351 'DatabasePostgres' => DatabasePostgres
::class
355 $dbType = strtolower( $dbType );
356 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
357 $possibleDrivers = $canonicalDBTypes[$dbType];
358 if ( !empty( $p['driver'] ) ) {
359 if ( in_array( $p['driver'], $possibleDrivers ) ) {
360 $driver = $p['driver'];
362 throw new InvalidArgumentException( __METHOD__
.
363 " type '$dbType' does not support driver '{$p['driver']}'" );
366 foreach ( $possibleDrivers as $posDriver ) {
367 if ( extension_loaded( $posDriver ) ) {
368 $driver = $posDriver;
377 if ( $driver === false ||
$driver === '' ) {
378 throw new InvalidArgumentException( __METHOD__
.
379 " no viable database extension found for type '$dbType'" );
382 $class = 'Database' . ucfirst( $driver );
383 if ( isset( $classAliases[$class] ) ) {
384 $class = $classAliases[$class];
387 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
388 // Resolve some defaults for b/c
389 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
390 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
391 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
392 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
393 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
394 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
395 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
396 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
397 $p['cliMode'] = isset( $p['cliMode'] ) ?
$p['cliMode'] : ( PHP_SAPI
=== 'cli' );
398 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
399 if ( !isset( $p['connLogger'] ) ) {
400 $p['connLogger'] = new \Psr\Log\
NullLogger();
402 if ( !isset( $p['queryLogger'] ) ) {
403 $p['queryLogger'] = new \Psr\Log\
NullLogger();
405 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
406 if ( !isset( $p['trxProfiler'] ) ) {
407 $p['trxProfiler'] = new TransactionProfiler();
409 if ( !isset( $p['errorLogger'] ) ) {
410 $p['errorLogger'] = function ( Exception
$e ) {
411 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
415 $conn = new $class( $p );
424 * Set the PSR-3 logger interface to use for query logging. (The logger
425 * interfaces for connection logging and error logging can be set with the
428 * @param LoggerInterface $logger
430 public function setLogger( LoggerInterface
$logger ) {
431 $this->queryLogger
= $logger;
434 public function getServerInfo() {
435 return $this->getServerVersion();
438 public function bufferResults( $buffer = null ) {
439 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
440 if ( $buffer !== null ) {
442 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
443 : $this->setFlag( self
::DBO_NOBUFFER
);
450 * Turns on (false) or off (true) the automatic generation and sending
451 * of a "we're sorry, but there has been a database error" page on
452 * database errors. Default is on (false). When turned off, the
453 * code should use lastErrno() and lastError() to handle the
454 * situation as appropriate.
456 * Do not use this function outside of the Database classes.
458 * @param null|bool $ignoreErrors
459 * @return bool The previous value of the flag.
461 protected function ignoreErrors( $ignoreErrors = null ) {
462 $res = $this->getFlag( self
::DBO_IGNORE
);
463 if ( $ignoreErrors !== null ) {
465 ?
$this->setFlag( self
::DBO_IGNORE
)
466 : $this->clearFlag( self
::DBO_IGNORE
);
472 public function trxLevel() {
473 return $this->mTrxLevel
;
476 public function trxTimestamp() {
477 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
480 public function tablePrefix( $prefix = null ) {
481 $old = $this->mTablePrefix
;
482 if ( $prefix !== null ) {
483 $this->mTablePrefix
= $prefix;
484 $this->currentDomain
= ( $this->mDBname
!= '' )
485 ?
new DatabaseDomain( $this->mDBname
, null, $this->mTablePrefix
)
486 : DatabaseDomain
::newUnspecified();
492 public function dbSchema( $schema = null ) {
493 $old = $this->mSchema
;
494 if ( $schema !== null ) {
495 $this->mSchema
= $schema;
501 public function getLBInfo( $name = null ) {
502 if ( is_null( $name ) ) {
503 return $this->mLBInfo
;
505 if ( array_key_exists( $name, $this->mLBInfo
) ) {
506 return $this->mLBInfo
[$name];
513 public function setLBInfo( $name, $value = null ) {
514 if ( is_null( $value ) ) {
515 $this->mLBInfo
= $name;
517 $this->mLBInfo
[$name] = $value;
521 public function setLazyMasterHandle( IDatabase
$conn ) {
522 $this->lazyMasterHandle
= $conn;
526 * @return IDatabase|null
527 * @see setLazyMasterHandle()
530 protected function getLazyMasterHandle() {
531 return $this->lazyMasterHandle
;
534 public function implicitGroupby() {
538 public function implicitOrderby() {
542 public function lastQuery() {
543 return $this->mLastQuery
;
546 public function doneWrites() {
547 return (bool)$this->mLastWriteTime
;
550 public function lastDoneWrites() {
551 return $this->mLastWriteTime ?
: false;
554 public function writesPending() {
555 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
558 public function writesOrCallbacksPending() {
559 return $this->mTrxLevel
&& (
560 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
564 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
565 if ( !$this->mTrxLevel
) {
567 } elseif ( !$this->mTrxDoneWrites
) {
572 case self
::ESTIMATE_DB_APPLY
:
574 $rttAdjTotal = $this->mTrxWriteAdjQueryCount
* $rtt;
575 $applyTime = max( $this->mTrxWriteAdjDuration
- $rttAdjTotal, 0 );
576 // For omitted queries, make them count as something at least
577 $omitted = $this->mTrxWriteQueryCount
- $this->mTrxWriteAdjQueryCount
;
578 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
581 default: // everything
582 return $this->mTrxWriteDuration
;
586 public function pendingWriteCallers() {
587 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
590 public function pendingWriteRowsAffected() {
591 return $this->mTrxWriteAffectedRows
;
595 * Get the list of method names that have pending write queries or callbacks
596 * for this transaction
600 protected function pendingWriteAndCallbackCallers() {
601 if ( !$this->mTrxLevel
) {
605 $fnames = $this->mTrxWriteCallers
;
607 $this->mTrxIdleCallbacks
,
608 $this->mTrxPreCommitCallbacks
,
609 $this->mTrxEndCallbacks
611 foreach ( $callbacks as $callback ) {
612 $fnames[] = $callback[1];
619 public function isOpen() {
620 return $this->mOpened
;
623 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
624 if ( $remember === self
::REMEMBER_PRIOR
) {
625 array_push( $this->priorFlags
, $this->mFlags
);
627 $this->mFlags |
= $flag;
630 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
631 if ( $remember === self
::REMEMBER_PRIOR
) {
632 array_push( $this->priorFlags
, $this->mFlags
);
634 $this->mFlags
&= ~
$flag;
637 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
638 if ( !$this->priorFlags
) {
642 if ( $state === self
::RESTORE_INITIAL
) {
643 $this->mFlags
= reset( $this->priorFlags
);
644 $this->priorFlags
= [];
646 $this->mFlags
= array_pop( $this->priorFlags
);
650 public function getFlag( $flag ) {
651 return !!( $this->mFlags
& $flag );
655 * @param string $name Class field name
657 * @deprecated Since 1.28
659 public function getProperty( $name ) {
663 public function getDomainID() {
664 return $this->currentDomain
->getId();
667 final public function getWikiID() {
668 return $this->getDomainID();
672 * Get information about an index into an object
673 * @param string $table Table name
674 * @param string $index Index name
675 * @param string $fname Calling function name
676 * @return mixed Database-specific index description class or false if the index does not exist
678 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
681 * Wrapper for addslashes()
683 * @param string $s String to be slashed.
684 * @return string Slashed string.
686 abstract function strencode( $s );
689 * Set a custom error handler for logging errors during database connection
691 protected function installErrorHandler() {
692 $this->mPHPError
= false;
693 $this->htmlErrors
= ini_set( 'html_errors', '0' );
694 set_error_handler( [ $this, 'connectionErrorLogger' ] );
698 * Restore the previous error handler and return the last PHP error for this DB
700 * @return bool|string
702 protected function restoreErrorHandler() {
703 restore_error_handler();
704 if ( $this->htmlErrors
!== false ) {
705 ini_set( 'html_errors', $this->htmlErrors
);
708 return $this->getLastPHPError();
712 * @return string|bool Last PHP error for this DB (typically connection errors)
714 protected function getLastPHPError() {
715 if ( $this->mPHPError
) {
716 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
717 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
726 * Error handler for logging errors during database connection
727 * This method should not be used outside of Database classes
730 * @param string $errstr
732 public function connectionErrorLogger( $errno, $errstr ) {
733 $this->mPHPError
= $errstr;
737 * Create a log context to pass to PSR-3 logger functions.
739 * @param array $extras Additional data to add to context
742 protected function getLogContext( array $extras = [] ) {
745 'db_server' => $this->mServer
,
746 'db_name' => $this->mDBname
,
747 'db_user' => $this->mUser
,
753 public function close() {
754 if ( $this->mConn
) {
755 if ( $this->trxLevel() ) {
756 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
759 $closed = $this->closeConnection();
760 $this->mConn
= false;
761 } elseif ( $this->mTrxIdleCallbacks ||
$this->mTrxEndCallbacks
) { // sanity
762 throw new RuntimeException( "Transaction callbacks still pending." );
766 $this->mOpened
= false;
772 * Make sure isOpen() returns true as a sanity check
774 * @throws DBUnexpectedError
776 protected function assertOpen() {
777 if ( !$this->isOpen() ) {
778 throw new DBUnexpectedError( $this, "DB connection was already closed." );
783 * Closes underlying database connection
785 * @return bool Whether connection was closed successfully
787 abstract protected function closeConnection();
789 public function reportConnectionError( $error = 'Unknown error' ) {
790 $myError = $this->lastError();
796 throw new DBConnectionError( $this, $error );
800 * The DBMS-dependent part of query()
802 * @param string $sql SQL query.
803 * @return ResultWrapper|bool Result object to feed to fetchObject,
804 * fetchRow, ...; or false on failure
806 abstract protected function doQuery( $sql );
809 * Determine whether a query writes to the DB.
810 * Should return true if unsure.
815 protected function isWriteQuery( $sql ) {
817 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
822 * @return string|null
824 protected function getQueryVerb( $sql ) {
825 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
829 * Determine whether a SQL statement is sensitive to isolation level.
830 * A SQL statement is considered transactable if its result could vary
831 * depending on the transaction isolation level. Operational commands
832 * such as 'SET' and 'SHOW' are not considered to be transactable.
837 protected function isTransactableQuery( $sql ) {
839 $this->getQueryVerb( $sql ),
840 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
846 * @param string $sql A SQL query
847 * @return bool Whether $sql is SQL for TEMPORARY table operation
849 protected function registerTempTableOperation( $sql ) {
851 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
855 $this->mSessionTempTables
[$matches[1]] = 1;
858 } elseif ( preg_match(
859 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
863 $isTemp = isset( $this->mSessionTempTables
[$matches[1]] );
864 unset( $this->mSessionTempTables
[$matches[1]] );
867 } elseif ( preg_match(
868 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
872 return isset( $this->mSessionTempTables
[$matches[1]] );
873 } elseif ( preg_match(
874 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
878 return isset( $this->mSessionTempTables
[$matches[1]] );
884 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
885 $priorWritesPending = $this->writesOrCallbacksPending();
886 $this->mLastQuery
= $sql;
888 $isWrite = $this->isWriteQuery( $sql );
890 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
892 $isNonTempWrite = false;
896 # In theory, non-persistent writes are allowed in read-only mode, but due to things
897 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
898 $reason = $this->getReadOnlyReason();
899 if ( $reason !== false ) {
900 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
902 # Set a flag indicating that writes have been done
903 $this->mLastWriteTime
= microtime( true );
906 # Add trace comment to the begin of the sql string, right after the operator.
907 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
908 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
910 # Start implicit transactions that wrap the request if DBO_TRX is enabled
911 if ( !$this->mTrxLevel
&& $this->getFlag( self
::DBO_TRX
)
912 && $this->isTransactableQuery( $sql )
914 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
915 $this->mTrxAutomatic
= true;
918 # Keep track of whether the transaction has write queries pending
919 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWrite ) {
920 $this->mTrxDoneWrites
= true;
921 $this->trxProfiler
->transactionWritingIn(
922 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
925 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
926 $this->queryLogger
->debug( "{$this->mDBname} {$commentedSql}" );
929 # Avoid fatals if close() was called
932 # Send the query to the server
933 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
935 # Try reconnecting if the connection was lost
936 if ( false === $ret && $this->wasErrorReissuable() ) {
937 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
938 # Stash the last error values before anything might clear them
939 $lastError = $this->lastError();
940 $lastErrno = $this->lastErrno();
941 # Update state tracking to reflect transaction loss due to disconnection
942 $this->handleSessionLoss();
943 if ( $this->reconnect() ) {
944 $msg = __METHOD__
. ": lost connection to {$this->getServer()}; reconnected";
945 $this->connLogger
->warning( $msg );
946 $this->queryLogger
->warning(
947 "$msg:\n" . ( new RuntimeException() )->getTraceAsString() );
949 if ( !$recoverable ) {
950 # Callers may catch the exception and continue to use the DB
951 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
953 # Should be safe to silently retry the query
954 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
957 $msg = __METHOD__
. ": lost connection to {$this->getServer()} permanently";
958 $this->connLogger
->error( $msg );
962 if ( false === $ret ) {
963 # Deadlocks cause the entire transaction to abort, not just the statement.
964 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
965 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
966 if ( $this->wasDeadlock() ) {
967 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
968 $tempIgnore = false; // not recoverable
970 # Update state tracking to reflect transaction loss
971 $this->handleSessionLoss();
974 $this->reportQueryError(
975 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
978 $res = $this->resultObject( $ret );
984 * Helper method for query() that handles profiling and logging and sends
985 * the query to doQuery()
987 * @param string $sql Original SQL query
988 * @param string $commentedSql SQL query with debugging/trace comment
989 * @param bool $isWrite Whether the query is a (non-temporary) write operation
990 * @param string $fname Name of the calling function
991 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
992 * object for a successful read query, or false on failure
994 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
995 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
996 # generalizeSQL() will probably cut down the query to reasonable
997 # logging size most of the time. The substr is really just a sanity check.
999 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1001 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1004 # Include query transaction state
1005 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1007 $startTime = microtime( true );
1008 if ( $this->profiler
) {
1009 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1011 $ret = $this->doQuery( $commentedSql );
1012 if ( $this->profiler
) {
1013 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1015 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1017 unset( $queryProfSection ); // profile out (if set)
1019 if ( $ret !== false ) {
1020 $this->lastPing
= $startTime;
1021 if ( $isWrite && $this->mTrxLevel
) {
1022 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1023 $this->mTrxWriteCallers
[] = $fname;
1027 if ( $sql === self
::PING_QUERY
) {
1028 $this->mRTTEstimate
= $queryRuntime;
1031 $this->trxProfiler
->recordQueryCompletion(
1032 $queryProf, $startTime, $isWrite, $this->affectedRows()
1034 $this->queryLogger
->debug( $sql, [
1036 'master' => $isMaster,
1037 'runtime' => $queryRuntime,
1044 * Update the estimated run-time of a query, not counting large row lock times
1046 * LoadBalancer can be set to rollback transactions that will create huge replication
1047 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1048 * queries, like inserting a row can take a long time due to row locking. This method
1049 * uses some simple heuristics to discount those cases.
1051 * @param string $sql A SQL write query
1052 * @param float $runtime Total runtime, including RTT
1053 * @param integer $affected Affected row count
1055 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1056 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1057 $indicativeOfReplicaRuntime = true;
1058 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1059 $verb = $this->getQueryVerb( $sql );
1060 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1061 if ( $verb === 'INSERT' ) {
1062 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1063 } elseif ( $verb === 'REPLACE' ) {
1064 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1068 $this->mTrxWriteDuration +
= $runtime;
1069 $this->mTrxWriteQueryCount +
= 1;
1070 $this->mTrxWriteAffectedRows +
= $affected;
1071 if ( $indicativeOfReplicaRuntime ) {
1072 $this->mTrxWriteAdjDuration +
= $runtime;
1073 $this->mTrxWriteAdjQueryCount +
= 1;
1078 * Determine whether or not it is safe to retry queries after a database
1079 * connection is lost
1081 * @param string $sql SQL query
1082 * @param bool $priorWritesPending Whether there is a transaction open with
1083 * possible write queries or transaction pre-commit/idle callbacks
1084 * waiting on it to finish.
1085 * @return bool True if it is safe to retry the query, false otherwise
1087 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1088 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1089 # Dropped connections also mean that named locks are automatically released.
1090 # Only allow error suppression in autocommit mode or when the lost transaction
1091 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1092 if ( $this->mNamedLocksHeld
) {
1093 return false; // possible critical section violation
1094 } elseif ( $sql === 'COMMIT' ) {
1095 return !$priorWritesPending; // nothing written anyway? (T127428)
1096 } elseif ( $sql === 'ROLLBACK' ) {
1097 return true; // transaction lost...which is also what was requested :)
1098 } elseif ( $this->explicitTrxActive() ) {
1099 return false; // don't drop atomocity
1100 } elseif ( $priorWritesPending ) {
1101 return false; // prior writes lost from implicit transaction
1108 * Clean things up after transaction loss due to disconnection
1110 * @return null|Exception
1112 private function handleSessionLoss() {
1113 $this->mTrxLevel
= 0;
1114 $this->mTrxIdleCallbacks
= []; // T67263
1115 $this->mTrxPreCommitCallbacks
= []; // T67263
1116 $this->mSessionTempTables
= [];
1117 $this->mNamedLocksHeld
= [];
1119 // Handle callbacks in mTrxEndCallbacks
1120 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1121 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1123 } catch ( Exception
$e ) {
1124 // Already logged; move on...
1129 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1130 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1131 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1133 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1134 $this->queryLogger
->error(
1135 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1136 $this->getLogContext( [
1137 'method' => __METHOD__
,
1140 'sql1line' => $sql1line,
1144 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1145 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1149 public function freeResult( $res ) {
1152 public function selectField(
1153 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1155 if ( $var === '*' ) { // sanity
1156 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1159 if ( !is_array( $options ) ) {
1160 $options = [ $options ];
1163 $options['LIMIT'] = 1;
1165 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1166 if ( $res === false ||
!$this->numRows( $res ) ) {
1170 $row = $this->fetchRow( $res );
1172 if ( $row !== false ) {
1173 return reset( $row );
1179 public function selectFieldValues(
1180 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1182 if ( $var === '*' ) { // sanity
1183 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1184 } elseif ( !is_string( $var ) ) { // sanity
1185 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1188 if ( !is_array( $options ) ) {
1189 $options = [ $options ];
1192 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1193 if ( $res === false ) {
1198 foreach ( $res as $row ) {
1199 $values[] = $row->$var;
1206 * Returns an optional USE INDEX clause to go after the table, and a
1207 * string to go at the end of the query.
1209 * @param array $options Associative array of options to be turned into
1210 * an SQL query, valid keys are listed in the function.
1212 * @see Database::select()
1214 protected function makeSelectOptions( $options ) {
1215 $preLimitTail = $postLimitTail = '';
1220 foreach ( $options as $key => $option ) {
1221 if ( is_numeric( $key ) ) {
1222 $noKeyOptions[$option] = true;
1226 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1228 $preLimitTail .= $this->makeOrderBy( $options );
1230 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1231 $postLimitTail .= ' FOR UPDATE';
1234 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1235 $postLimitTail .= ' LOCK IN SHARE MODE';
1238 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1239 $startOpts .= 'DISTINCT';
1242 # Various MySQL extensions
1243 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1244 $startOpts .= ' /*! STRAIGHT_JOIN */';
1247 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1248 $startOpts .= ' HIGH_PRIORITY';
1251 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1252 $startOpts .= ' SQL_BIG_RESULT';
1255 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1256 $startOpts .= ' SQL_BUFFER_RESULT';
1259 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1260 $startOpts .= ' SQL_SMALL_RESULT';
1263 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1264 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1267 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1268 $startOpts .= ' SQL_CACHE';
1271 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1272 $startOpts .= ' SQL_NO_CACHE';
1275 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1276 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1280 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1281 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1286 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1290 * Returns an optional GROUP BY with an optional HAVING
1292 * @param array $options Associative array of options
1294 * @see Database::select()
1297 protected function makeGroupByWithHaving( $options ) {
1299 if ( isset( $options['GROUP BY'] ) ) {
1300 $gb = is_array( $options['GROUP BY'] )
1301 ?
implode( ',', $options['GROUP BY'] )
1302 : $options['GROUP BY'];
1303 $sql .= ' GROUP BY ' . $gb;
1305 if ( isset( $options['HAVING'] ) ) {
1306 $having = is_array( $options['HAVING'] )
1307 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1308 : $options['HAVING'];
1309 $sql .= ' HAVING ' . $having;
1316 * Returns an optional ORDER BY
1318 * @param array $options Associative array of options
1320 * @see Database::select()
1323 protected function makeOrderBy( $options ) {
1324 if ( isset( $options['ORDER BY'] ) ) {
1325 $ob = is_array( $options['ORDER BY'] )
1326 ?
implode( ',', $options['ORDER BY'] )
1327 : $options['ORDER BY'];
1329 return ' ORDER BY ' . $ob;
1335 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1336 $options = [], $join_conds = [] ) {
1337 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1339 return $this->query( $sql, $fname );
1342 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1343 $options = [], $join_conds = []
1345 if ( is_array( $vars ) ) {
1346 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1349 $options = (array)$options;
1350 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1351 ?
$options['USE INDEX']
1354 isset( $options['IGNORE INDEX'] ) &&
1355 is_array( $options['IGNORE INDEX'] )
1357 ?
$options['IGNORE INDEX']
1360 if ( is_array( $table ) ) {
1362 $this->tableNamesWithIndexClauseOrJOIN(
1363 $table, $useIndexes, $ignoreIndexes, $join_conds );
1364 } elseif ( $table != '' ) {
1365 if ( $table[0] == ' ' ) {
1366 $from = ' FROM ' . $table;
1369 $this->tableNamesWithIndexClauseOrJOIN(
1370 [ $table ], $useIndexes, $ignoreIndexes, [] );
1376 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1377 $this->makeSelectOptions( $options );
1379 if ( !empty( $conds ) ) {
1380 if ( is_array( $conds ) ) {
1381 $conds = $this->makeList( $conds, self
::LIST_AND
);
1383 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1384 "WHERE $conds $preLimitTail";
1386 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1389 if ( isset( $options['LIMIT'] ) ) {
1390 $sql = $this->limitResult( $sql, $options['LIMIT'],
1391 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1393 $sql = "$sql $postLimitTail";
1395 if ( isset( $options['EXPLAIN'] ) ) {
1396 $sql = 'EXPLAIN ' . $sql;
1402 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1403 $options = [], $join_conds = []
1405 $options = (array)$options;
1406 $options['LIMIT'] = 1;
1407 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1409 if ( $res === false ) {
1413 if ( !$this->numRows( $res ) ) {
1417 $obj = $this->fetchObject( $res );
1422 public function estimateRowCount(
1423 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1426 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1429 $row = $this->fetchRow( $res );
1430 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1436 public function selectRowCount(
1437 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1440 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1441 // The identifier quotes is primarily for MSSQL.
1442 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1443 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1444 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1447 $row = $this->fetchRow( $res );
1448 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1455 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1456 * It's only slightly flawed. Don't use for anything important.
1458 * @param string $sql A SQL Query
1462 protected static function generalizeSQL( $sql ) {
1463 # This does the same as the regexp below would do, but in such a way
1464 # as to avoid crashing php on some large strings.
1465 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1467 $sql = str_replace( "\\\\", '', $sql );
1468 $sql = str_replace( "\\'", '', $sql );
1469 $sql = str_replace( "\\\"", '', $sql );
1470 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1471 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1473 # All newlines, tabs, etc replaced by single space
1474 $sql = preg_replace( '/\s+/', ' ', $sql );
1477 # except the ones surrounded by characters, e.g. l10n
1478 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1479 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1484 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1485 $info = $this->fieldInfo( $table, $field );
1490 public function indexExists( $table, $index, $fname = __METHOD__
) {
1491 if ( !$this->tableExists( $table ) ) {
1495 $info = $this->indexInfo( $table, $index, $fname );
1496 if ( is_null( $info ) ) {
1499 return $info !== false;
1503 public function tableExists( $table, $fname = __METHOD__
) {
1504 $tableRaw = $this->tableName( $table, 'raw' );
1505 if ( isset( $this->mSessionTempTables
[$tableRaw] ) ) {
1506 return true; // already known to exist
1509 $table = $this->tableName( $table );
1510 $ignoreErrors = true;
1511 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1516 public function indexUnique( $table, $index ) {
1517 $indexInfo = $this->indexInfo( $table, $index );
1519 if ( !$indexInfo ) {
1523 return !$indexInfo[0]->Non_unique
;
1527 * Helper for Database::insert().
1529 * @param array $options
1532 protected function makeInsertOptions( $options ) {
1533 return implode( ' ', $options );
1536 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1537 # No rows to insert, easy just return now
1538 if ( !count( $a ) ) {
1542 $table = $this->tableName( $table );
1544 if ( !is_array( $options ) ) {
1545 $options = [ $options ];
1549 if ( isset( $options['fileHandle'] ) ) {
1550 $fh = $options['fileHandle'];
1552 $options = $this->makeInsertOptions( $options );
1554 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1556 $keys = array_keys( $a[0] );
1559 $keys = array_keys( $a );
1562 $sql = 'INSERT ' . $options .
1563 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1567 foreach ( $a as $row ) {
1573 $sql .= '(' . $this->makeList( $row ) . ')';
1576 $sql .= '(' . $this->makeList( $a ) . ')';
1579 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1581 } elseif ( $fh !== null ) {
1585 return (bool)$this->query( $sql, $fname );
1589 * Make UPDATE options array for Database::makeUpdateOptions
1591 * @param array $options
1594 protected function makeUpdateOptionsArray( $options ) {
1595 if ( !is_array( $options ) ) {
1596 $options = [ $options ];
1601 if ( in_array( 'IGNORE', $options ) ) {
1609 * Make UPDATE options for the Database::update function
1611 * @param array $options The options passed to Database::update
1614 protected function makeUpdateOptions( $options ) {
1615 $opts = $this->makeUpdateOptionsArray( $options );
1617 return implode( ' ', $opts );
1620 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1621 $table = $this->tableName( $table );
1622 $opts = $this->makeUpdateOptions( $options );
1623 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1625 if ( $conds !== [] && $conds !== '*' ) {
1626 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1629 return (bool)$this->query( $sql, $fname );
1632 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1633 if ( !is_array( $a ) ) {
1634 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1640 foreach ( $a as $field => $value ) {
1642 if ( $mode == self
::LIST_AND
) {
1644 } elseif ( $mode == self
::LIST_OR
) {
1653 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1654 $list .= "($value)";
1655 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1658 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1660 // Remove null from array to be handled separately if found
1661 $includeNull = false;
1662 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1663 $includeNull = true;
1664 unset( $value[$nullKey] );
1666 if ( count( $value ) == 0 && !$includeNull ) {
1667 throw new InvalidArgumentException(
1668 __METHOD__
. ": empty input for field $field" );
1669 } elseif ( count( $value ) == 0 ) {
1670 // only check if $field is null
1671 $list .= "$field IS NULL";
1673 // IN clause contains at least one valid element
1674 if ( $includeNull ) {
1675 // Group subconditions to ensure correct precedence
1678 if ( count( $value ) == 1 ) {
1679 // Special-case single values, as IN isn't terribly efficient
1680 // Don't necessarily assume the single key is 0; we don't
1681 // enforce linear numeric ordering on other arrays here.
1682 $value = array_values( $value )[0];
1683 $list .= $field . " = " . $this->addQuotes( $value );
1685 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1687 // if null present in array, append IS NULL
1688 if ( $includeNull ) {
1689 $list .= " OR $field IS NULL)";
1692 } elseif ( $value === null ) {
1693 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1694 $list .= "$field IS ";
1695 } elseif ( $mode == self
::LIST_SET
) {
1696 $list .= "$field = ";
1701 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1703 $list .= "$field = ";
1705 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1712 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1715 foreach ( $data as $base => $sub ) {
1716 if ( count( $sub ) ) {
1717 $conds[] = $this->makeList(
1718 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1724 return $this->makeList( $conds, self
::LIST_OR
);
1726 // Nothing to search for...
1731 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1735 public function bitNot( $field ) {
1739 public function bitAnd( $fieldLeft, $fieldRight ) {
1740 return "($fieldLeft & $fieldRight)";
1743 public function bitOr( $fieldLeft, $fieldRight ) {
1744 return "($fieldLeft | $fieldRight)";
1747 public function buildConcat( $stringList ) {
1748 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1751 public function buildGroupConcatField(
1752 $delim, $table, $field, $conds = '', $join_conds = []
1754 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1756 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1759 public function buildStringCast( $field ) {
1763 public function databasesAreIndependent() {
1767 public function selectDB( $db ) {
1768 # Stub. Shouldn't cause serious problems if it's not overridden, but
1769 # if your database engine supports a concept similar to MySQL's
1770 # databases you may as well.
1771 $this->mDBname
= $db;
1776 public function getDBname() {
1777 return $this->mDBname
;
1780 public function getServer() {
1781 return $this->mServer
;
1784 public function tableName( $name, $format = 'quoted' ) {
1785 # Skip the entire process when we have a string quoted on both ends.
1786 # Note that we check the end so that we will still quote any use of
1787 # use of `database`.table. But won't break things if someone wants
1788 # to query a database table with a dot in the name.
1789 if ( $this->isQuotedIdentifier( $name ) ) {
1793 # Lets test for any bits of text that should never show up in a table
1794 # name. Basically anything like JOIN or ON which are actually part of
1795 # SQL queries, but may end up inside of the table value to combine
1796 # sql. Such as how the API is doing.
1797 # Note that we use a whitespace test rather than a \b test to avoid
1798 # any remote case where a word like on may be inside of a table name
1799 # surrounded by symbols which may be considered word breaks.
1800 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1804 # Split database and table into proper variables.
1805 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1807 # Quote $table and apply the prefix if not quoted.
1808 # $tableName might be empty if this is called from Database::replaceVars()
1809 $tableName = "{$prefix}{$table}";
1810 if ( $format === 'quoted'
1811 && !$this->isQuotedIdentifier( $tableName )
1812 && $tableName !== ''
1814 $tableName = $this->addIdentifierQuotes( $tableName );
1817 # Quote $schema and $database and merge them with the table name if needed
1818 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1819 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1825 * Get the table components needed for a query given the currently selected database
1827 * @param string $name Table name in the form of db.schema.table, db.table, or table
1828 * @return array (DB name or "" for default, schema name, table prefix, table name)
1830 protected function qualifiedTableComponents( $name ) {
1831 # We reverse the explode so that database.table and table both output the correct table.
1832 $dbDetails = explode( '.', $name, 3 );
1833 if ( count( $dbDetails ) == 3 ) {
1834 list( $database, $schema, $table ) = $dbDetails;
1835 # We don't want any prefix added in this case
1837 } elseif ( count( $dbDetails ) == 2 ) {
1838 list( $database, $table ) = $dbDetails;
1839 # We don't want any prefix added in this case
1841 # In dbs that support it, $database may actually be the schema
1842 # but that doesn't affect any of the functionality here
1845 list( $table ) = $dbDetails;
1846 if ( isset( $this->tableAliases
[$table] ) ) {
1847 $database = $this->tableAliases
[$table]['dbname'];
1848 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1849 ?
$this->tableAliases
[$table]['schema']
1851 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1852 ?
$this->tableAliases
[$table]['prefix']
1853 : $this->mTablePrefix
;
1856 $schema = $this->mSchema
; # Default schema
1857 $prefix = $this->mTablePrefix
; # Default prefix
1861 return [ $database, $schema, $prefix, $table ];
1865 * @param string|null $namespace Database or schema
1866 * @param string $relation Name of table, view, sequence, etc...
1867 * @param string $format One of (raw, quoted)
1868 * @return string Relation name with quoted and merged $namespace as needed
1870 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1871 if ( strlen( $namespace ) ) {
1872 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1873 $namespace = $this->addIdentifierQuotes( $namespace );
1875 $relation = $namespace . '.' . $relation;
1881 public function tableNames() {
1882 $inArray = func_get_args();
1885 foreach ( $inArray as $name ) {
1886 $retVal[$name] = $this->tableName( $name );
1892 public function tableNamesN() {
1893 $inArray = func_get_args();
1896 foreach ( $inArray as $name ) {
1897 $retVal[] = $this->tableName( $name );
1904 * Get an aliased table name
1905 * e.g. tableName AS newTableName
1907 * @param string $name Table name, see tableName()
1908 * @param string|bool $alias Alias (optional)
1909 * @return string SQL name for aliased table. Will not alias a table to its own name
1911 protected function tableNameWithAlias( $name, $alias = false ) {
1912 if ( !$alias ||
$alias == $name ) {
1913 return $this->tableName( $name );
1915 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1920 * Gets an array of aliased table names
1922 * @param array $tables [ [alias] => table ]
1923 * @return string[] See tableNameWithAlias()
1925 protected function tableNamesWithAlias( $tables ) {
1927 foreach ( $tables as $alias => $table ) {
1928 if ( is_numeric( $alias ) ) {
1931 $retval[] = $this->tableNameWithAlias( $table, $alias );
1938 * Get an aliased field name
1939 * e.g. fieldName AS newFieldName
1941 * @param string $name Field name
1942 * @param string|bool $alias Alias (optional)
1943 * @return string SQL name for aliased field. Will not alias a field to its own name
1945 protected function fieldNameWithAlias( $name, $alias = false ) {
1946 if ( !$alias ||
(string)$alias === (string)$name ) {
1949 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1954 * Gets an array of aliased field names
1956 * @param array $fields [ [alias] => field ]
1957 * @return string[] See fieldNameWithAlias()
1959 protected function fieldNamesWithAlias( $fields ) {
1961 foreach ( $fields as $alias => $field ) {
1962 if ( is_numeric( $alias ) ) {
1965 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1972 * Get the aliased table name clause for a FROM clause
1973 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
1975 * @param array $tables ( [alias] => table )
1976 * @param array $use_index Same as for select()
1977 * @param array $ignore_index Same as for select()
1978 * @param array $join_conds Same as for select()
1981 protected function tableNamesWithIndexClauseOrJOIN(
1982 $tables, $use_index = [], $ignore_index = [], $join_conds = []
1986 $use_index = (array)$use_index;
1987 $ignore_index = (array)$ignore_index;
1988 $join_conds = (array)$join_conds;
1990 foreach ( $tables as $alias => $table ) {
1991 if ( !is_string( $alias ) ) {
1992 // No alias? Set it equal to the table name
1995 // Is there a JOIN clause for this table?
1996 if ( isset( $join_conds[$alias] ) ) {
1997 list( $joinType, $conds ) = $join_conds[$alias];
1998 $tableClause = $joinType;
1999 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2000 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2001 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2003 $tableClause .= ' ' . $use;
2006 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2007 $ignore = $this->ignoreIndexClause(
2008 implode( ',', (array)$ignore_index[$alias] ) );
2009 if ( $ignore != '' ) {
2010 $tableClause .= ' ' . $ignore;
2013 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2015 $tableClause .= ' ON (' . $on . ')';
2018 $retJOIN[] = $tableClause;
2019 } elseif ( isset( $use_index[$alias] ) ) {
2020 // Is there an INDEX clause for this table?
2021 $tableClause = $this->tableNameWithAlias( $table, $alias );
2022 $tableClause .= ' ' . $this->useIndexClause(
2023 implode( ',', (array)$use_index[$alias] )
2026 $ret[] = $tableClause;
2027 } elseif ( isset( $ignore_index[$alias] ) ) {
2028 // Is there an INDEX clause for this table?
2029 $tableClause = $this->tableNameWithAlias( $table, $alias );
2030 $tableClause .= ' ' . $this->ignoreIndexClause(
2031 implode( ',', (array)$ignore_index[$alias] )
2034 $ret[] = $tableClause;
2036 $tableClause = $this->tableNameWithAlias( $table, $alias );
2038 $ret[] = $tableClause;
2042 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2043 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2044 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2046 // Compile our final table clause
2047 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2051 * Allows for index remapping in queries where this is not consistent across DBMS
2053 * @param string $index
2056 protected function indexName( $index ) {
2060 public function addQuotes( $s ) {
2061 if ( $s instanceof Blob
) {
2064 if ( $s === null ) {
2066 } elseif ( is_bool( $s ) ) {
2069 # This will also quote numeric values. This should be harmless,
2070 # and protects against weird problems that occur when they really
2071 # _are_ strings such as article titles and string->number->string
2072 # conversion is not 1:1.
2073 return "'" . $this->strencode( $s ) . "'";
2078 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2079 * MySQL uses `backticks` while basically everything else uses double quotes.
2080 * Since MySQL is the odd one out here the double quotes are our generic
2081 * and we implement backticks in DatabaseMysql.
2086 public function addIdentifierQuotes( $s ) {
2087 return '"' . str_replace( '"', '""', $s ) . '"';
2091 * Returns if the given identifier looks quoted or not according to
2092 * the database convention for quoting identifiers .
2094 * @note Do not use this to determine if untrusted input is safe.
2095 * A malicious user can trick this function.
2096 * @param string $name
2099 public function isQuotedIdentifier( $name ) {
2100 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2107 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2108 return str_replace( [ $escapeChar, '%', '_' ],
2109 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2113 public function buildLike() {
2114 $params = func_get_args();
2116 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2117 $params = $params[0];
2122 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2123 // may escape backslashes, creating problems of double escaping. The `
2124 // character has good cross-DBMS compatibility, avoiding special operators
2125 // in MS SQL like ^ and %
2128 foreach ( $params as $value ) {
2129 if ( $value instanceof LikeMatch
) {
2130 $s .= $value->toString();
2132 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2136 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2139 public function anyChar() {
2140 return new LikeMatch( '_' );
2143 public function anyString() {
2144 return new LikeMatch( '%' );
2147 public function nextSequenceValue( $seqName ) {
2152 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2153 * is only needed because a) MySQL must be as efficient as possible due to
2154 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2155 * which index to pick. Anyway, other databases might have different
2156 * indexes on a given table. So don't bother overriding this unless you're
2158 * @param string $index
2161 public function useIndexClause( $index ) {
2166 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2167 * is only needed because a) MySQL must be as efficient as possible due to
2168 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2169 * which index to pick. Anyway, other databases might have different
2170 * indexes on a given table. So don't bother overriding this unless you're
2172 * @param string $index
2175 public function ignoreIndexClause( $index ) {
2179 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2180 $quotedTable = $this->tableName( $table );
2182 if ( count( $rows ) == 0 ) {
2187 if ( !is_array( reset( $rows ) ) ) {
2191 // @FXIME: this is not atomic, but a trx would break affectedRows()
2192 foreach ( $rows as $row ) {
2193 # Delete rows which collide
2194 if ( $uniqueIndexes ) {
2195 $sql = "DELETE FROM $quotedTable WHERE ";
2197 foreach ( $uniqueIndexes as $index ) {
2204 if ( is_array( $index ) ) {
2206 foreach ( $index as $col ) {
2212 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2215 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2219 $this->query( $sql, $fname );
2222 # Now insert the row
2223 $this->insert( $table, $row, $fname );
2228 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2231 * @param string $table Table name
2232 * @param array|string $rows Row(s) to insert
2233 * @param string $fname Caller function name
2235 * @return ResultWrapper
2237 protected function nativeReplace( $table, $rows, $fname ) {
2238 $table = $this->tableName( $table );
2241 if ( !is_array( reset( $rows ) ) ) {
2245 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2248 foreach ( $rows as $row ) {
2255 $sql .= '(' . $this->makeList( $row ) . ')';
2258 return $this->query( $sql, $fname );
2261 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2264 if ( !count( $rows ) ) {
2265 return true; // nothing to do
2268 if ( !is_array( reset( $rows ) ) ) {
2272 if ( count( $uniqueIndexes ) ) {
2273 $clauses = []; // list WHERE clauses that each identify a single row
2274 foreach ( $rows as $row ) {
2275 foreach ( $uniqueIndexes as $index ) {
2276 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2277 $rowKey = []; // unique key to this row
2278 foreach ( $index as $column ) {
2279 $rowKey[$column] = $row[$column];
2281 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2284 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2289 $useTrx = !$this->mTrxLevel
;
2291 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2294 # Update any existing conflicting row(s)
2295 if ( $where !== false ) {
2296 $ok = $this->update( $table, $set, $where, $fname );
2300 # Now insert any non-conflicting row(s)
2301 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2302 } catch ( Exception
$e ) {
2304 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2309 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2315 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2319 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2322 $delTable = $this->tableName( $delTable );
2323 $joinTable = $this->tableName( $joinTable );
2324 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2325 if ( $conds != '*' ) {
2326 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2330 $this->query( $sql, $fname );
2333 public function textFieldSize( $table, $field ) {
2334 $table = $this->tableName( $table );
2335 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2336 $res = $this->query( $sql, __METHOD__
);
2337 $row = $this->fetchObject( $res );
2341 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2350 public function delete( $table, $conds, $fname = __METHOD__
) {
2352 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2355 $table = $this->tableName( $table );
2356 $sql = "DELETE FROM $table";
2358 if ( $conds != '*' ) {
2359 if ( is_array( $conds ) ) {
2360 $conds = $this->makeList( $conds, self
::LIST_AND
);
2362 $sql .= ' WHERE ' . $conds;
2365 return $this->query( $sql, $fname );
2368 public function insertSelect(
2369 $destTable, $srcTable, $varMap, $conds,
2370 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2372 if ( $this->cliMode
) {
2373 // For massive migrations with downtime, we don't want to select everything
2374 // into memory and OOM, so do all this native on the server side if possible.
2375 return $this->nativeInsertSelect(
2387 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2388 // on only the master (without needing row-based-replication). It also makes it easy to
2389 // know how big the INSERT is going to be.
2391 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2392 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2394 $selectOptions[] = 'FOR UPDATE';
2395 $res = $this->select(
2396 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2403 foreach ( $res as $row ) {
2404 $rows[] = (array)$row;
2407 return $this->insert( $destTable, $rows, $fname, $insertOptions );
2411 * Native server-side implementation of insertSelect() for situations where
2412 * we don't want to select everything into memory
2414 * @see IDatabase::insertSelect()
2416 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2417 $fname = __METHOD__
,
2418 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2420 $destTable = $this->tableName( $destTable );
2422 if ( !is_array( $insertOptions ) ) {
2423 $insertOptions = [ $insertOptions ];
2426 $insertOptions = $this->makeInsertOptions( $insertOptions );
2428 $selectSql = $this->selectSQLText(
2430 array_values( $varMap ),
2437 $sql = "INSERT $insertOptions" .
2438 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2441 return $this->query( $sql, $fname );
2445 * Construct a LIMIT query with optional offset. This is used for query
2446 * pages. The SQL should be adjusted so that only the first $limit rows
2447 * are returned. If $offset is provided as well, then the first $offset
2448 * rows should be discarded, and the next $limit rows should be returned.
2449 * If the result of the query is not ordered, then the rows to be returned
2450 * are theoretically arbitrary.
2452 * $sql is expected to be a SELECT, if that makes a difference.
2454 * The version provided by default works in MySQL and SQLite. It will very
2455 * likely need to be overridden for most other DBMSes.
2457 * @param string $sql SQL query we will append the limit too
2458 * @param int $limit The SQL limit
2459 * @param int|bool $offset The SQL offset (default false)
2460 * @throws DBUnexpectedError
2463 public function limitResult( $sql, $limit, $offset = false ) {
2464 if ( !is_numeric( $limit ) ) {
2465 throw new DBUnexpectedError( $this,
2466 "Invalid non-numeric limit passed to limitResult()\n" );
2469 return "$sql LIMIT "
2470 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2474 public function unionSupportsOrderAndLimit() {
2475 return true; // True for almost every DB supported
2478 public function unionQueries( $sqls, $all ) {
2479 $glue = $all ?
') UNION ALL (' : ') UNION (';
2481 return '(' . implode( $glue, $sqls ) . ')';
2484 public function unionConditionPermutations(
2485 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2486 $options = [], $join_conds = []
2488 // First, build the Cartesian product of $permute_conds
2490 foreach ( $permute_conds as $field => $values ) {
2492 // Skip empty $values
2495 $values = array_unique( $values ); // For sanity
2497 foreach ( $conds as $cond ) {
2498 foreach ( $values as $value ) {
2499 $cond[$field] = $value;
2500 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2506 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2508 // If there's just one condition and no subordering, hand off to
2509 // selectSQLText directly.
2510 if ( count( $conds ) === 1 &&
2511 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2513 return $this->selectSQLText(
2514 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2518 // Otherwise, we need to pull out the order and limit to apply after
2519 // the union. Then build the SQL queries for each set of conditions in
2520 // $conds. Then union them together (using UNION ALL, because the
2521 // product *should* already be distinct).
2522 $orderBy = $this->makeOrderBy( $options );
2523 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2524 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2525 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2526 if ( !$this->unionSupportsOrderAndLimit() ) {
2527 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2529 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2530 $options['ORDER BY'] = $options['INNER ORDER BY'];
2532 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2533 // We need to increase the limit by the offset rather than
2534 // using the offset directly, otherwise it'll skip incorrectly
2535 // in the subqueries.
2536 $options['LIMIT'] = $limit +
$offset;
2537 unset( $options['OFFSET'] );
2542 foreach ( $conds as $cond ) {
2543 $sqls[] = $this->selectSQLText(
2544 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2547 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2548 if ( $limit !== null ) {
2549 $sql = $this->limitResult( $sql, $limit, $offset );
2555 public function conditional( $cond, $trueVal, $falseVal ) {
2556 if ( is_array( $cond ) ) {
2557 $cond = $this->makeList( $cond, self
::LIST_AND
);
2560 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2563 public function strreplace( $orig, $old, $new ) {
2564 return "REPLACE({$orig}, {$old}, {$new})";
2567 public function getServerUptime() {
2571 public function wasDeadlock() {
2575 public function wasLockTimeout() {
2579 public function wasErrorReissuable() {
2583 public function wasReadOnlyError() {
2588 * Do not use this method outside of Database/DBError classes
2590 * @param integer|string $errno
2591 * @return bool Whether the given query error was a connection drop
2593 public function wasConnectionError( $errno ) {
2597 public function deadlockLoop() {
2598 $args = func_get_args();
2599 $function = array_shift( $args );
2600 $tries = self
::DEADLOCK_TRIES
;
2602 $this->begin( __METHOD__
);
2605 /** @var Exception $e */
2609 $retVal = call_user_func_array( $function, $args );
2611 } catch ( DBQueryError
$e ) {
2612 if ( $this->wasDeadlock() ) {
2613 // Retry after a randomized delay
2614 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2616 // Throw the error back up
2620 } while ( --$tries > 0 );
2622 if ( $tries <= 0 ) {
2623 // Too many deadlocks; give up
2624 $this->rollback( __METHOD__
);
2627 $this->commit( __METHOD__
);
2633 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2634 # Real waits are implemented in the subclass.
2638 public function getReplicaPos() {
2643 public function getMasterPos() {
2648 public function serverIsReadOnly() {
2652 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2653 if ( !$this->mTrxLevel
) {
2654 throw new DBUnexpectedError( $this, "No transaction is active." );
2656 $this->mTrxEndCallbacks
[] = [ $callback, $fname ];
2659 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2660 $this->mTrxIdleCallbacks
[] = [ $callback, $fname ];
2661 if ( !$this->mTrxLevel
) {
2662 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2666 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2667 if ( $this->mTrxLevel
) {
2668 $this->mTrxPreCommitCallbacks
[] = [ $callback, $fname ];
2670 // If no transaction is active, then make one for this callback
2671 $this->startAtomic( __METHOD__
);
2673 call_user_func( $callback );
2674 $this->endAtomic( __METHOD__
);
2675 } catch ( Exception
$e ) {
2676 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2682 final public function setTransactionListener( $name, callable
$callback = null ) {
2684 $this->mTrxRecurringCallbacks
[$name] = $callback;
2686 unset( $this->mTrxRecurringCallbacks
[$name] );
2691 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2693 * This method should not be used outside of Database/LoadBalancer
2695 * @param bool $suppress
2698 final public function setTrxEndCallbackSuppression( $suppress ) {
2699 $this->mTrxEndCallbacksSuppressed
= $suppress;
2703 * Actually run and consume any "on transaction idle/resolution" callbacks.
2705 * This method should not be used outside of Database/LoadBalancer
2707 * @param integer $trigger IDatabase::TRIGGER_* constant
2711 public function runOnTransactionIdleCallbacks( $trigger ) {
2712 if ( $this->mTrxEndCallbacksSuppressed
) {
2716 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2717 /** @var Exception $e */
2718 $e = null; // first exception
2719 do { // callbacks may add callbacks :)
2720 $callbacks = array_merge(
2721 $this->mTrxIdleCallbacks
,
2722 $this->mTrxEndCallbacks
// include "transaction resolution" callbacks
2724 $this->mTrxIdleCallbacks
= []; // consumed (and recursion guard)
2725 $this->mTrxEndCallbacks
= []; // consumed (recursion guard)
2726 foreach ( $callbacks as $callback ) {
2728 list( $phpCallback ) = $callback;
2729 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2730 call_user_func_array( $phpCallback, [ $trigger ] );
2732 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2734 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2736 } catch ( Exception
$ex ) {
2737 call_user_func( $this->errorLogger
, $ex );
2739 // Some callbacks may use startAtomic/endAtomic, so make sure
2740 // their transactions are ended so other callbacks don't fail
2741 if ( $this->trxLevel() ) {
2742 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2746 } while ( count( $this->mTrxIdleCallbacks
) );
2748 if ( $e instanceof Exception
) {
2749 throw $e; // re-throw any first exception
2754 * Actually run and consume any "on transaction pre-commit" callbacks.
2756 * This method should not be used outside of Database/LoadBalancer
2761 public function runOnTransactionPreCommitCallbacks() {
2762 $e = null; // first exception
2763 do { // callbacks may add callbacks :)
2764 $callbacks = $this->mTrxPreCommitCallbacks
;
2765 $this->mTrxPreCommitCallbacks
= []; // consumed (and recursion guard)
2766 foreach ( $callbacks as $callback ) {
2768 list( $phpCallback ) = $callback;
2769 call_user_func( $phpCallback );
2770 } catch ( Exception
$ex ) {
2771 call_user_func( $this->errorLogger
, $ex );
2775 } while ( count( $this->mTrxPreCommitCallbacks
) );
2777 if ( $e instanceof Exception
) {
2778 throw $e; // re-throw any first exception
2783 * Actually run any "transaction listener" callbacks.
2785 * This method should not be used outside of Database/LoadBalancer
2787 * @param integer $trigger IDatabase::TRIGGER_* constant
2791 public function runTransactionListenerCallbacks( $trigger ) {
2792 if ( $this->mTrxEndCallbacksSuppressed
) {
2796 /** @var Exception $e */
2797 $e = null; // first exception
2799 foreach ( $this->mTrxRecurringCallbacks
as $phpCallback ) {
2801 $phpCallback( $trigger, $this );
2802 } catch ( Exception
$ex ) {
2803 call_user_func( $this->errorLogger
, $ex );
2808 if ( $e instanceof Exception
) {
2809 throw $e; // re-throw any first exception
2813 final public function startAtomic( $fname = __METHOD__
) {
2814 if ( !$this->mTrxLevel
) {
2815 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2816 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2817 // in all changes being in one transaction to keep requests transactional.
2818 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2819 $this->mTrxAutomaticAtomic
= true;
2823 $this->mTrxAtomicLevels
[] = $fname;
2826 final public function endAtomic( $fname = __METHOD__
) {
2827 if ( !$this->mTrxLevel
) {
2828 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2830 if ( !$this->mTrxAtomicLevels ||
2831 array_pop( $this->mTrxAtomicLevels
) !== $fname
2833 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2836 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2837 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2841 final public function doAtomicSection( $fname, callable
$callback ) {
2842 $this->startAtomic( $fname );
2844 $res = call_user_func_array( $callback, [ $this, $fname ] );
2845 } catch ( Exception
$e ) {
2846 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2849 $this->endAtomic( $fname );
2854 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
2855 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
2856 if ( $this->mTrxLevel
) {
2857 if ( $this->mTrxAtomicLevels
) {
2858 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2859 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
2860 throw new DBUnexpectedError( $this, $msg );
2861 } elseif ( !$this->mTrxAutomatic
) {
2862 $msg = "$fname: Explicit transaction already active (from {$this->mTrxFname}).";
2863 throw new DBUnexpectedError( $this, $msg );
2865 // @TODO: make this an exception at some point
2866 $msg = "$fname: Implicit transaction already active (from {$this->mTrxFname}).";
2867 $this->queryLogger
->error( $msg );
2868 return; // join the main transaction set
2870 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
2871 // @TODO: make this an exception at some point
2872 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
2873 $this->queryLogger
->error( $msg );
2874 return; // let any writes be in the main transaction
2877 // Avoid fatals if close() was called
2878 $this->assertOpen();
2880 $this->doBegin( $fname );
2881 $this->mTrxTimestamp
= microtime( true );
2882 $this->mTrxFname
= $fname;
2883 $this->mTrxDoneWrites
= false;
2884 $this->mTrxAutomaticAtomic
= false;
2885 $this->mTrxAtomicLevels
= [];
2886 $this->mTrxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
2887 $this->mTrxWriteDuration
= 0.0;
2888 $this->mTrxWriteQueryCount
= 0;
2889 $this->mTrxWriteAffectedRows
= 0;
2890 $this->mTrxWriteAdjDuration
= 0.0;
2891 $this->mTrxWriteAdjQueryCount
= 0;
2892 $this->mTrxWriteCallers
= [];
2893 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2894 // Get an estimate of the replica DB lag before then, treating estimate staleness
2895 // as lag itself just to be safe
2896 $status = $this->getApproximateLagStatus();
2897 $this->mTrxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2898 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
2899 // caller will think its OK to muck around with the transaction just because startAtomic()
2900 // has not yet completed (e.g. setting mTrxAtomicLevels).
2901 $this->mTrxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
2905 * Issues the BEGIN command to the database server.
2907 * @see Database::begin()
2908 * @param string $fname
2910 protected function doBegin( $fname ) {
2911 $this->query( 'BEGIN', $fname );
2912 $this->mTrxLevel
= 1;
2915 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2916 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2917 // There are still atomic sections open. This cannot be ignored
2918 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2919 throw new DBUnexpectedError(
2921 "$fname: Got COMMIT while atomic sections $levels are still open."
2925 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2926 if ( !$this->mTrxLevel
) {
2927 return; // nothing to do
2928 } elseif ( !$this->mTrxAutomatic
) {
2929 throw new DBUnexpectedError(
2931 "$fname: Flushing an explicit transaction, getting out of sync."
2935 if ( !$this->mTrxLevel
) {
2936 $this->queryLogger
->error(
2937 "$fname: No transaction to commit, something got out of sync." );
2938 return; // nothing to do
2939 } elseif ( $this->mTrxAutomatic
) {
2940 // @TODO: make this an exception at some point
2941 $msg = "$fname: Explicit commit of implicit transaction.";
2942 $this->queryLogger
->error( $msg );
2943 return; // wait for the main transaction set commit round
2947 // Avoid fatals if close() was called
2948 $this->assertOpen();
2950 $this->runOnTransactionPreCommitCallbacks();
2951 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
2952 $this->doCommit( $fname );
2953 if ( $this->mTrxDoneWrites
) {
2954 $this->mLastWriteTime
= microtime( true );
2955 $this->trxProfiler
->transactionWritingOut(
2960 $this->mTrxWriteAffectedRows
2964 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
2965 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
2969 * Issues the COMMIT command to the database server.
2971 * @see Database::commit()
2972 * @param string $fname
2974 protected function doCommit( $fname ) {
2975 if ( $this->mTrxLevel
) {
2976 $this->query( 'COMMIT', $fname );
2977 $this->mTrxLevel
= 0;
2981 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2982 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
2983 if ( !$this->mTrxLevel
) {
2984 return; // nothing to do
2987 if ( !$this->mTrxLevel
) {
2988 $this->queryLogger
->error(
2989 "$fname: No transaction to rollback, something got out of sync." );
2990 return; // nothing to do
2991 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
2992 throw new DBUnexpectedError(
2994 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
2999 // Avoid fatals if close() was called
3000 $this->assertOpen();
3002 $this->doRollback( $fname );
3003 $this->mTrxAtomicLevels
= [];
3004 if ( $this->mTrxDoneWrites
) {
3005 $this->trxProfiler
->transactionWritingOut(
3012 $this->mTrxIdleCallbacks
= []; // clear
3013 $this->mTrxPreCommitCallbacks
= []; // clear
3014 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3015 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3019 * Issues the ROLLBACK command to the database server.
3021 * @see Database::rollback()
3022 * @param string $fname
3024 protected function doRollback( $fname ) {
3025 if ( $this->mTrxLevel
) {
3026 # Disconnects cause rollback anyway, so ignore those errors
3027 $ignoreErrors = true;
3028 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3029 $this->mTrxLevel
= 0;
3033 public function flushSnapshot( $fname = __METHOD__
) {
3034 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3035 // This only flushes transactions to clear snapshots, not to write data
3036 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3037 throw new DBUnexpectedError(
3039 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3043 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3046 public function explicitTrxActive() {
3047 return $this->mTrxLevel
&& ( $this->mTrxAtomicLevels ||
!$this->mTrxAutomatic
);
3050 public function duplicateTableStructure(
3051 $oldName, $newName, $temporary = false, $fname = __METHOD__
3053 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3056 public function listTables( $prefix = null, $fname = __METHOD__
) {
3057 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3060 public function listViews( $prefix = null, $fname = __METHOD__
) {
3061 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3064 public function timestamp( $ts = 0 ) {
3065 $t = new ConvertibleTimestamp( $ts );
3066 // Let errors bubble up to avoid putting garbage in the DB
3067 return $t->getTimestamp( TS_MW
);
3070 public function timestampOrNull( $ts = null ) {
3071 if ( is_null( $ts ) ) {
3074 return $this->timestamp( $ts );
3079 * Take the result from a query, and wrap it in a ResultWrapper if
3080 * necessary. Boolean values are passed through as is, to indicate success
3081 * of write queries or failure.
3083 * Once upon a time, Database::query() returned a bare MySQL result
3084 * resource, and it was necessary to call this function to convert it to
3085 * a wrapper. Nowadays, raw database objects are never exposed to external
3086 * callers, so this is unnecessary in external code.
3088 * @param bool|ResultWrapper|resource|object $result
3089 * @return bool|ResultWrapper
3091 protected function resultObject( $result ) {
3094 } elseif ( $result instanceof ResultWrapper
) {
3096 } elseif ( $result === true ) {
3097 // Successful write query
3100 return new ResultWrapper( $this, $result );
3104 public function ping( &$rtt = null ) {
3105 // Avoid hitting the server if it was hit recently
3106 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3107 if ( !func_num_args() ||
$this->mRTTEstimate
> 0 ) {
3108 $rtt = $this->mRTTEstimate
;
3109 return true; // don't care about $rtt
3113 // This will reconnect if possible or return false if not
3114 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3115 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3116 $this->restoreFlags( self
::RESTORE_PRIOR
);
3119 $rtt = $this->mRTTEstimate
;
3126 * Close existing database connection and open a new connection
3128 * @return bool True if new connection is opened successfully, false if error
3130 protected function reconnect() {
3131 $this->closeConnection();
3132 $this->mOpened
= false;
3133 $this->mConn
= false;
3135 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3136 $this->lastPing
= microtime( true );
3138 } catch ( DBConnectionError
$e ) {
3145 public function getSessionLagStatus() {
3146 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3150 * Get the replica DB lag when the current transaction started
3152 * This is useful when transactions might use snapshot isolation
3153 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3154 * is this lag plus transaction duration. If they don't, it is still
3155 * safe to be pessimistic. This returns null if there is no transaction.
3157 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3160 protected function getTransactionLagStatus() {
3161 return $this->mTrxLevel
3162 ?
[ 'lag' => $this->mTrxReplicaLag
, 'since' => $this->trxTimestamp() ]
3167 * Get a replica DB lag estimate for this server
3169 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3172 protected function getApproximateLagStatus() {
3174 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3175 'since' => microtime( true )
3180 * Merge the result of getSessionLagStatus() for several DBs
3181 * using the most pessimistic values to estimate the lag of
3182 * any data derived from them in combination
3184 * This is information is useful for caching modules
3186 * @see WANObjectCache::set()
3187 * @see WANObjectCache::getWithSetCallback()
3189 * @param IDatabase $db1
3190 * @param IDatabase ...
3191 * @return array Map of values:
3192 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3193 * - since: oldest UNIX timestamp of any of the DB lag estimates
3194 * - pending: whether any of the DBs have uncommitted changes
3197 public static function getCacheSetOptions( IDatabase
$db1 ) {
3198 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3199 foreach ( func_get_args() as $db ) {
3200 /** @var IDatabase $db */
3201 $status = $db->getSessionLagStatus();
3202 if ( $status['lag'] === false ) {
3203 $res['lag'] = false;
3204 } elseif ( $res['lag'] !== false ) {
3205 $res['lag'] = max( $res['lag'], $status['lag'] );
3207 $res['since'] = min( $res['since'], $status['since'] );
3208 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3214 public function getLag() {
3218 public function maxListLen() {
3222 public function encodeBlob( $b ) {
3226 public function decodeBlob( $b ) {
3227 if ( $b instanceof Blob
) {
3233 public function setSessionOptions( array $options ) {
3236 public function sourceFile(
3238 callable
$lineCallback = null,
3239 callable
$resultCallback = null,
3241 callable
$inputCallback = null
3243 MediaWiki\
suppressWarnings();
3244 $fp = fopen( $filename, 'r' );
3245 MediaWiki\restoreWarnings
();
3247 if ( false === $fp ) {
3248 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3252 $fname = __METHOD__
. "( $filename )";
3256 $error = $this->sourceStream(
3257 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3258 } catch ( Exception
$e ) {
3268 public function setSchemaVars( $vars ) {
3269 $this->mSchemaVars
= $vars;
3272 public function sourceStream(
3274 callable
$lineCallback = null,
3275 callable
$resultCallback = null,
3276 $fname = __METHOD__
,
3277 callable
$inputCallback = null
3281 while ( !feof( $fp ) ) {
3282 if ( $lineCallback ) {
3283 call_user_func( $lineCallback );
3286 $line = trim( fgets( $fp ) );
3288 if ( $line == '' ) {
3292 if ( '-' == $line[0] && '-' == $line[1] ) {
3300 $done = $this->streamStatementEnd( $cmd, $line );
3304 if ( $done ||
feof( $fp ) ) {
3305 $cmd = $this->replaceVars( $cmd );
3307 if ( !$inputCallback ||
call_user_func( $inputCallback, $cmd ) ) {
3308 $res = $this->query( $cmd, $fname );
3310 if ( $resultCallback ) {
3311 call_user_func( $resultCallback, $res, $this );
3314 if ( false === $res ) {
3315 $err = $this->lastError();
3317 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3328 * Called by sourceStream() to check if we've reached a statement end
3330 * @param string &$sql SQL assembled so far
3331 * @param string &$newLine New line about to be added to $sql
3332 * @return bool Whether $newLine contains end of the statement
3334 public function streamStatementEnd( &$sql, &$newLine ) {
3335 if ( $this->delimiter
) {
3337 $newLine = preg_replace(
3338 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3339 if ( $newLine != $prev ) {
3348 * Database independent variable replacement. Replaces a set of variables
3349 * in an SQL statement with their contents as given by $this->getSchemaVars().
3351 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3353 * - '{$var}' should be used for text and is passed through the database's
3355 * - `{$var}` should be used for identifiers (e.g. table and database names).
3356 * It is passed through the database's addIdentifierQuotes method which
3357 * can be overridden if the database uses something other than backticks.
3358 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3359 * database's tableName method.
3360 * - / *i* / passes the name that follows through the database's indexName method.
3361 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3362 * its use should be avoided. In 1.24 and older, string encoding was applied.
3364 * @param string $ins SQL statement to replace variables in
3365 * @return string The new SQL statement with variables replaced
3367 protected function replaceVars( $ins ) {
3368 $vars = $this->getSchemaVars();
3369 return preg_replace_callback(
3371 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3372 \'\{\$ (\w+) }\' | # 3. addQuotes
3373 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3374 /\*\$ (\w+) \*/ # 5. leave unencoded
3376 function ( $m ) use ( $vars ) {
3377 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3378 // check for both nonexistent keys *and* the empty string.
3379 if ( isset( $m[1] ) && $m[1] !== '' ) {
3380 if ( $m[1] === 'i' ) {
3381 return $this->indexName( $m[2] );
3383 return $this->tableName( $m[2] );
3385 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3386 return $this->addQuotes( $vars[$m[3]] );
3387 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3388 return $this->addIdentifierQuotes( $vars[$m[4]] );
3389 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3390 return $vars[$m[5]];
3400 * Get schema variables. If none have been set via setSchemaVars(), then
3401 * use some defaults from the current object.
3405 protected function getSchemaVars() {
3406 if ( $this->mSchemaVars
) {
3407 return $this->mSchemaVars
;
3409 return $this->getDefaultSchemaVars();
3414 * Get schema variables to use if none have been set via setSchemaVars().
3416 * Override this in derived classes to provide variables for tables.sql
3417 * and SQL patch files.
3421 protected function getDefaultSchemaVars() {
3425 public function lockIsFree( $lockName, $method ) {
3429 public function lock( $lockName, $method, $timeout = 5 ) {
3430 $this->mNamedLocksHeld
[$lockName] = 1;
3435 public function unlock( $lockName, $method ) {
3436 unset( $this->mNamedLocksHeld
[$lockName] );
3441 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3442 if ( $this->writesOrCallbacksPending() ) {
3443 // This only flushes transactions to clear snapshots, not to write data
3444 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3445 throw new DBUnexpectedError(
3447 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3451 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3455 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3456 if ( $this->trxLevel() ) {
3457 // There is a good chance an exception was thrown, causing any early return
3458 // from the caller. Let any error handler get a chance to issue rollback().
3459 // If there isn't one, let the error bubble up and trigger server-side rollback.
3460 $this->onTransactionResolution(
3461 function () use ( $lockKey, $fname ) {
3462 $this->unlock( $lockKey, $fname );
3467 $this->unlock( $lockKey, $fname );
3471 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3476 public function namedLocksEnqueue() {
3480 public function tableLocksHaveTransactionScope() {
3484 final public function lockTables( array $read, array $write, $method ) {
3485 if ( $this->writesOrCallbacksPending() ) {
3486 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3489 if ( $this->tableLocksHaveTransactionScope() ) {
3490 $this->startAtomic( $method );
3493 return $this->doLockTables( $read, $write, $method );
3497 * Helper function for lockTables() that handles the actual table locking
3499 * @param array $read Array of tables to lock for read access
3500 * @param array $write Array of tables to lock for write access
3501 * @param string $method Name of caller
3504 protected function doLockTables( array $read, array $write, $method ) {
3508 final public function unlockTables( $method ) {
3509 if ( $this->tableLocksHaveTransactionScope() ) {
3510 $this->endAtomic( $method );
3512 return true; // locks released on COMMIT/ROLLBACK
3515 return $this->doUnlockTables( $method );
3519 * Helper function for unlockTables() that handles the actual table unlocking
3521 * @param string $method Name of caller
3524 protected function doUnlockTables( $method ) {
3530 * @param string $tableName
3531 * @param string $fName
3532 * @return bool|ResultWrapper
3535 public function dropTable( $tableName, $fName = __METHOD__
) {
3536 if ( !$this->tableExists( $tableName, $fName ) ) {
3539 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3541 return $this->query( $sql, $fName );
3544 public function getInfinity() {
3548 public function encodeExpiry( $expiry ) {
3549 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3550 ?
$this->getInfinity()
3551 : $this->timestamp( $expiry );
3554 public function decodeExpiry( $expiry, $format = TS_MW
) {
3555 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3559 return ConvertibleTimestamp
::convert( $format, $expiry );
3562 public function setBigSelects( $value = true ) {
3566 public function isReadOnly() {
3567 return ( $this->getReadOnlyReason() !== false );
3571 * @return string|bool Reason this DB is read-only or false if it is not
3573 protected function getReadOnlyReason() {
3574 $reason = $this->getLBInfo( 'readOnlyReason' );
3576 return is_string( $reason ) ?
$reason : false;
3579 public function setTableAliases( array $aliases ) {
3580 $this->tableAliases
= $aliases;
3584 * @return bool Whether a DB user is required to access the DB
3587 protected function requiresDatabaseUser() {
3592 * Get the underlying binding handle, mConn
3594 * Makes sure that mConn is set (disconnects and ping() failure can unset it).
3595 * This catches broken callers than catch and ignore disconnection exceptions.
3596 * Unlike checking isOpen(), this is safe to call inside of open().
3598 * @return resource|object
3599 * @throws DBUnexpectedError
3602 protected function getBindingHandle() {
3603 if ( !$this->mConn
) {
3604 throw new DBUnexpectedError(
3606 'DB connection was already closed or the connection dropped.'
3610 return $this->mConn
;
3617 public function __toString() {
3618 return (string)$this->mConn
;
3622 * Make sure that copies do not share the same client binding handle
3623 * @throws DBConnectionError
3625 public function __clone() {
3626 $this->connLogger
->warning(
3627 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3628 ( new RuntimeException() )->getTraceAsString()
3631 if ( $this->isOpen() ) {
3632 // Open a new connection resource without messing with the old one
3633 $this->mOpened
= false;
3634 $this->mConn
= false;
3635 $this->mTrxEndCallbacks
= []; // don't copy
3636 $this->handleSessionLoss(); // no trx or locks anymore
3637 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
3638 $this->lastPing
= microtime( true );
3643 * Called by serialize. Throw an exception when DB connection is serialized.
3644 * This causes problems on some database engines because the connection is
3645 * not restored on unserialize.
3647 public function __sleep() {
3648 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3649 'the connection is not restored on wakeup.' );
3653 * Run a few simple sanity checks and close dangling connections
3655 public function __destruct() {
3656 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3657 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3660 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3661 if ( $danglingWriters ) {
3662 $fnames = implode( ', ', $danglingWriters );
3663 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3666 if ( $this->mConn
) {
3667 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3668 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3669 \MediaWiki\
suppressWarnings();
3670 $this->closeConnection();
3671 \MediaWiki\restoreWarnings
();
3672 $this->mConn
= false;
3673 $this->mOpened
= false;
3678 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3679 class_alias( Database
::class, 'Database' ); // b/c global alias