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 Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
36 use InvalidArgumentException
;
41 * Relational database abstraction object
46 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
47 /** Number of times to re-try an operation in case of deadlock */
48 const DEADLOCK_TRIES
= 4;
49 /** Minimum time to wait before retry, in microseconds */
50 const DEADLOCK_DELAY_MIN
= 500000;
51 /** Maximum time to wait before retry */
52 const DEADLOCK_DELAY_MAX
= 1500000;
54 /** How long before it is worth doing a dummy query to test the connection */
56 const PING_QUERY
= 'SELECT 1 AS ping';
58 const TINY_WRITE_SEC
= 0.010;
59 const SLOW_WRITE_SEC
= 0.500;
60 const SMALL_WRITE_ROWS
= 100;
62 /** @var string Whether lock granularity is on the level of the entire database */
63 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
65 /** @var string SQL query */
66 protected $lastQuery = '';
67 /** @var float|bool UNIX timestamp of last write query */
68 protected $lastWriteTime = false;
69 /** @var string|bool */
70 protected $phpError = false;
79 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
80 protected $tableAliases = [];
81 /** @var string[] Map of (index alias => index) */
82 protected $indexAliases = [];
83 /** @var bool Whether this PHP instance is for a CLI script */
85 /** @var string Agent name for query profiling */
88 /** @var BagOStuff APC cache */
90 /** @var LoggerInterface */
91 protected $connLogger;
92 /** @var LoggerInterface */
93 protected $queryLogger;
94 /** @var callback Error logging callback */
95 protected $errorLogger;
97 /** @var resource|null Database connection */
98 protected $conn = null;
100 protected $opened = false;
102 /** @var array[] List of (callable, method name) */
103 protected $trxIdleCallbacks = [];
104 /** @var array[] List of (callable, method name) */
105 protected $trxPreCommitCallbacks = [];
106 /** @var array[] List of (callable, method name) */
107 protected $trxEndCallbacks = [];
108 /** @var callable[] Map of (name => callable) */
109 protected $trxRecurringCallbacks = [];
110 /** @var bool Whether to suppress triggering of transaction end callbacks */
111 protected $trxEndCallbacksSuppressed = false;
114 protected $tablePrefix = '';
116 protected $schema = '';
120 protected $lbInfo = [];
121 /** @var array|bool */
122 protected $schemaVars = false;
124 protected $sessionVars = [];
125 /** @var array|null */
126 protected $preparedArgs;
127 /** @var string|bool|null Stashed value of html_errors INI setting */
128 protected $htmlErrors;
130 protected $delimiter = ';';
131 /** @var DatabaseDomain */
132 protected $currentDomain;
133 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
134 protected $affectedRowCount;
137 * Either 1 if a transaction is active or 0 otherwise.
138 * The other Trx fields may not be meaningfull if this is 0.
142 protected $trxLevel = 0;
144 * Either a short hexidecimal string if a transaction is active or ""
147 * @see Database::trxLevel
149 protected $trxShortId = '';
151 * The UNIX time that the transaction started. Callers can assume that if
152 * snapshot isolation is used, then the data is *at least* up to date to that
153 * point (possibly more up-to-date since the first SELECT defines the snapshot).
156 * @see Database::trxLevel
158 private $trxTimestamp = null;
159 /** @var float Lag estimate at the time of BEGIN */
160 private $trxReplicaLag = null;
162 * Remembers the function name given for starting the most recent transaction via begin().
163 * Used to provide additional context for error reporting.
166 * @see Database::trxLevel
168 private $trxFname = null;
170 * Record if possible write queries were done in the last transaction started
173 * @see Database::trxLevel
175 private $trxDoneWrites = false;
177 * Record if the current transaction was started implicitly due to DBO_TRX being set.
180 * @see Database::trxLevel
182 private $trxAutomatic = false;
184 * Array of levels of atomicity within transactions
188 private $trxAtomicLevels = [];
190 * Record if the current transaction was started implicitly by Database::startAtomic
194 private $trxAutomaticAtomic = false;
196 * Track the write query callers of the current transaction
200 private $trxWriteCallers = [];
202 * @var float Seconds spent in write queries for the current transaction
204 private $trxWriteDuration = 0.0;
206 * @var int Number of write queries for the current transaction
208 private $trxWriteQueryCount = 0;
210 * @var int Number of rows affected by write queries for the current transaction
212 private $trxWriteAffectedRows = 0;
214 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
216 private $trxWriteAdjDuration = 0.0;
218 * @var int Number of write queries counted in trxWriteAdjDuration
220 private $trxWriteAdjQueryCount = 0;
222 * @var float RTT time estimate
224 private $rttEstimate = 0.0;
226 /** @var array Map of (name => 1) for locks obtained via lock() */
227 private $namedLocksHeld = [];
228 /** @var array Map of (table name => 1) for TEMPORARY tables */
229 protected $sessionTempTables = [];
231 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
232 private $lazyMasterHandle;
234 /** @var float UNIX timestamp */
235 protected $lastPing = 0.0;
237 /** @var int[] Prior flags member variable values */
238 private $priorFlags = [];
240 /** @var object|string Class name or object With profileIn/profileOut methods */
242 /** @var TransactionProfiler */
243 protected $trxProfiler;
246 protected $nonNativeInsertSelectBatchSize = 10000;
249 * Constructor and database handle and attempt to connect to the DB server
251 * IDatabase classes should not be constructed directly in external
252 * code. Database::factory() should be used instead.
254 * @param array $params Parameters passed from Database::factory()
256 function __construct( array $params ) {
257 $server = $params['host'];
258 $user = $params['user'];
259 $password = $params['password'];
260 $dbName = $params['dbname'];
262 $this->schema
= $params['schema'];
263 $this->tablePrefix
= $params['tablePrefix'];
265 $this->cliMode
= $params['cliMode'];
266 // Agent name is added to SQL queries in a comment, so make sure it can't break out
267 $this->agent
= str_replace( '/', '-', $params['agent'] );
269 $this->flags
= $params['flags'];
270 if ( $this->flags
& self
::DBO_DEFAULT
) {
271 if ( $this->cliMode
) {
272 $this->flags
&= ~self
::DBO_TRX
;
274 $this->flags |
= self
::DBO_TRX
;
278 $this->sessionVars
= $params['variables'];
280 $this->srvCache
= isset( $params['srvCache'] )
281 ?
$params['srvCache']
282 : new HashBagOStuff();
284 $this->profiler
= $params['profiler'];
285 $this->trxProfiler
= $params['trxProfiler'];
286 $this->connLogger
= $params['connLogger'];
287 $this->queryLogger
= $params['queryLogger'];
288 $this->errorLogger
= $params['errorLogger'];
290 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
291 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
294 // Set initial dummy domain until open() sets the final DB/prefix
295 $this->currentDomain
= DatabaseDomain
::newUnspecified();
298 $this->open( $server, $user, $password, $dbName );
299 } elseif ( $this->requiresDatabaseUser() ) {
300 throw new InvalidArgumentException( "No database user provided." );
303 // Set the domain object after open() sets the relevant fields
304 if ( $this->dbName
!= '' ) {
305 // Domains with server scope but a table prefix are not used by IDatabase classes
306 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
311 * Construct a Database subclass instance given a database type and parameters
313 * This also connects to the database immediately upon object construction
315 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
316 * @param array $p Parameter map with keys:
317 * - host : The hostname of the DB server
318 * - user : The name of the database user the client operates under
319 * - password : The password for the database user
320 * - dbname : The name of the database to use where queries do not specify one.
321 * The database must exist or an error might be thrown. Setting this to the empty string
322 * will avoid any such errors and make the handle have no implicit database scope. This is
323 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
324 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
325 * in which user names and such are defined, e.g. users are database-specific in Postgres.
326 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
327 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
328 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
329 * recognized in queries. This can be used in place of schemas for handle site farms.
330 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
331 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
332 * flag in place UNLESS this this database simply acts as a key/value store.
333 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
334 * 'mysqli' driver; the old one 'mysql' has been removed.
335 * - variables: Optional map of session variables to set after connecting. This can be
336 * used to adjust lock timeouts or encoding modes and the like.
337 * - connLogger: Optional PSR-3 logger interface instance.
338 * - queryLogger: Optional PSR-3 logger interface instance.
339 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
340 * These will be called in query(), using a simplified version of the SQL that also
341 * includes the agent as a SQL comment.
342 * - trxProfiler: Optional TransactionProfiler instance.
343 * - errorLogger: Optional callback that takes an Exception and logs it.
344 * - cliMode: Whether to consider the execution context that of a CLI script.
345 * - agent: Optional name used to identify the end-user in query profiling/logging.
346 * - srvCache: Optional BagOStuff instance to an APC-style cache.
347 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
348 * @return Database|null If the database driver or extension cannot be found
349 * @throws InvalidArgumentException If the database driver or extension cannot be found
352 final public static function factory( $dbType, $p = [] ) {
353 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
355 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
356 // Resolve some defaults for b/c
357 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
358 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
359 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
360 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
361 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
362 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
363 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
364 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
365 $p['cliMode'] = isset( $p['cliMode'] )
367 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
368 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
369 if ( !isset( $p['connLogger'] ) ) {
370 $p['connLogger'] = new NullLogger();
372 if ( !isset( $p['queryLogger'] ) ) {
373 $p['queryLogger'] = new NullLogger();
375 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
376 if ( !isset( $p['trxProfiler'] ) ) {
377 $p['trxProfiler'] = new TransactionProfiler();
379 if ( !isset( $p['errorLogger'] ) ) {
380 $p['errorLogger'] = function ( Exception
$e ) {
381 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
385 $conn = new $class( $p );
394 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
395 * @param string|null $driver Optional name of a specific DB client driver
396 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
397 * @throws InvalidArgumentException
400 final public static function attributesFromType( $dbType, $driver = null ) {
401 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
403 $class = self
::getClass( $dbType, $driver );
405 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
409 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
410 * @param string|null $driver Optional name of a specific DB client driver
411 * @return string Database subclass name to use
412 * @throws InvalidArgumentException
414 private static function getClass( $dbType, $driver = null ) {
415 // For database types with built-in support, the below maps type to IDatabase
416 // implementations. For types with multipe driver implementations (PHP extensions),
417 // an array can be used, keyed by extension name. In case of an array, the
418 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
419 // we auto-detect the first available driver. For types without built-in support,
420 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
421 static $builtinTypes = [
422 'mssql' => DatabaseMssql
::class,
423 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
424 'sqlite' => DatabaseSqlite
::class,
425 'postgres' => DatabasePostgres
::class,
428 $dbType = strtolower( $dbType );
431 if ( isset( $builtinTypes[$dbType] ) ) {
432 $possibleDrivers = $builtinTypes[$dbType];
433 if ( is_string( $possibleDrivers ) ) {
434 $class = $possibleDrivers;
436 if ( (string)$driver !== '' ) {
437 if ( !isset( $possibleDrivers[$driver] ) ) {
438 throw new InvalidArgumentException( __METHOD__
.
439 " type '$dbType' does not support driver '{$driver}'" );
441 $class = $possibleDrivers[$driver];
444 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
445 if ( extension_loaded( $posDriver ) ) {
446 $class = $possibleClass;
453 $class = 'Database' . ucfirst( $dbType );
456 if ( $class === false ) {
457 throw new InvalidArgumentException( __METHOD__
.
458 " no viable database extension found for type '$dbType'" );
465 * @return array Map of (Database::ATTRIBUTE_* constant => value
468 protected static function getAttributes() {
473 * Set the PSR-3 logger interface to use for query logging. (The logger
474 * interfaces for connection logging and error logging can be set with the
477 * @param LoggerInterface $logger
479 public function setLogger( LoggerInterface
$logger ) {
480 $this->queryLogger
= $logger;
483 public function getServerInfo() {
484 return $this->getServerVersion();
487 public function bufferResults( $buffer = null ) {
488 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
489 if ( $buffer !== null ) {
491 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
492 : $this->setFlag( self
::DBO_NOBUFFER
);
499 * Turns on (false) or off (true) the automatic generation and sending
500 * of a "we're sorry, but there has been a database error" page on
501 * database errors. Default is on (false). When turned off, the
502 * code should use lastErrno() and lastError() to handle the
503 * situation as appropriate.
505 * Do not use this function outside of the Database classes.
507 * @param null|bool $ignoreErrors
508 * @return bool The previous value of the flag.
510 protected function ignoreErrors( $ignoreErrors = null ) {
511 $res = $this->getFlag( self
::DBO_IGNORE
);
512 if ( $ignoreErrors !== null ) {
513 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
514 if ( $ignoreErrors ) {
515 $this->flags |
= self
::DBO_IGNORE
;
517 $this->flags
&= ~self
::DBO_IGNORE
;
524 public function trxLevel() {
525 return $this->trxLevel
;
528 public function trxTimestamp() {
529 return $this->trxLevel ?
$this->trxTimestamp
: null;
532 public function tablePrefix( $prefix = null ) {
533 $old = $this->tablePrefix
;
534 if ( $prefix !== null ) {
535 $this->tablePrefix
= $prefix;
536 $this->currentDomain
= ( $this->dbName
!= '' )
537 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
538 : DatabaseDomain
::newUnspecified();
544 public function dbSchema( $schema = null ) {
545 $old = $this->schema
;
546 if ( $schema !== null ) {
547 $this->schema
= $schema;
553 public function getLBInfo( $name = null ) {
554 if ( is_null( $name ) ) {
555 return $this->lbInfo
;
557 if ( array_key_exists( $name, $this->lbInfo
) ) {
558 return $this->lbInfo
[$name];
565 public function setLBInfo( $name, $value = null ) {
566 if ( is_null( $value ) ) {
567 $this->lbInfo
= $name;
569 $this->lbInfo
[$name] = $value;
573 public function setLazyMasterHandle( IDatabase
$conn ) {
574 $this->lazyMasterHandle
= $conn;
578 * @return IDatabase|null
579 * @see setLazyMasterHandle()
582 protected function getLazyMasterHandle() {
583 return $this->lazyMasterHandle
;
586 public function implicitGroupby() {
590 public function implicitOrderby() {
594 public function lastQuery() {
595 return $this->lastQuery
;
598 public function doneWrites() {
599 return (bool)$this->lastWriteTime
;
602 public function lastDoneWrites() {
603 return $this->lastWriteTime ?
: false;
606 public function writesPending() {
607 return $this->trxLevel
&& $this->trxDoneWrites
;
610 public function writesOrCallbacksPending() {
611 return $this->trxLevel
&& (
612 $this->trxDoneWrites ||
613 $this->trxIdleCallbacks ||
614 $this->trxPreCommitCallbacks ||
615 $this->trxEndCallbacks
619 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
620 if ( !$this->trxLevel
) {
622 } elseif ( !$this->trxDoneWrites
) {
627 case self
::ESTIMATE_DB_APPLY
:
629 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
630 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
631 // For omitted queries, make them count as something at least
632 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
633 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
636 default: // everything
637 return $this->trxWriteDuration
;
641 public function pendingWriteCallers() {
642 return $this->trxLevel ?
$this->trxWriteCallers
: [];
645 public function pendingWriteRowsAffected() {
646 return $this->trxWriteAffectedRows
;
650 * Get the list of method names that have pending write queries or callbacks
651 * for this transaction
655 protected function pendingWriteAndCallbackCallers() {
656 if ( !$this->trxLevel
) {
660 $fnames = $this->trxWriteCallers
;
662 $this->trxIdleCallbacks
,
663 $this->trxPreCommitCallbacks
,
664 $this->trxEndCallbacks
666 foreach ( $callbacks as $callback ) {
667 $fnames[] = $callback[1];
674 public function isOpen() {
675 return $this->opened
;
678 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
679 if ( ( $flag & self
::DBO_IGNORE
) ) {
680 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
683 if ( $remember === self
::REMEMBER_PRIOR
) {
684 array_push( $this->priorFlags
, $this->flags
);
686 $this->flags |
= $flag;
689 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
690 if ( ( $flag & self
::DBO_IGNORE
) ) {
691 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
694 if ( $remember === self
::REMEMBER_PRIOR
) {
695 array_push( $this->priorFlags
, $this->flags
);
697 $this->flags
&= ~
$flag;
700 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
701 if ( !$this->priorFlags
) {
705 if ( $state === self
::RESTORE_INITIAL
) {
706 $this->flags
= reset( $this->priorFlags
);
707 $this->priorFlags
= [];
709 $this->flags
= array_pop( $this->priorFlags
);
713 public function getFlag( $flag ) {
714 return !!( $this->flags
& $flag );
718 * @param string $name Class field name
720 * @deprecated Since 1.28
722 public function getProperty( $name ) {
726 public function getDomainID() {
727 return $this->currentDomain
->getId();
730 final public function getWikiID() {
731 return $this->getDomainID();
735 * Get information about an index into an object
736 * @param string $table Table name
737 * @param string $index Index name
738 * @param string $fname Calling function name
739 * @return mixed Database-specific index description class or false if the index does not exist
741 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
744 * Wrapper for addslashes()
746 * @param string $s String to be slashed.
747 * @return string Slashed string.
749 abstract function strencode( $s );
752 * Set a custom error handler for logging errors during database connection
754 protected function installErrorHandler() {
755 $this->phpError
= false;
756 $this->htmlErrors
= ini_set( 'html_errors', '0' );
757 set_error_handler( [ $this, 'connectionErrorLogger' ] );
761 * Restore the previous error handler and return the last PHP error for this DB
763 * @return bool|string
765 protected function restoreErrorHandler() {
766 restore_error_handler();
767 if ( $this->htmlErrors
!== false ) {
768 ini_set( 'html_errors', $this->htmlErrors
);
771 return $this->getLastPHPError();
775 * @return string|bool Last PHP error for this DB (typically connection errors)
777 protected function getLastPHPError() {
778 if ( $this->phpError
) {
779 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
780 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
789 * Error handler for logging errors during database connection
790 * This method should not be used outside of Database classes
793 * @param string $errstr
795 public function connectionErrorLogger( $errno, $errstr ) {
796 $this->phpError
= $errstr;
800 * Create a log context to pass to PSR-3 logger functions.
802 * @param array $extras Additional data to add to context
805 protected function getLogContext( array $extras = [] ) {
808 'db_server' => $this->server
,
809 'db_name' => $this->dbName
,
810 'db_user' => $this->user
,
816 public function close() {
818 // Resolve any dangling transaction first
819 if ( $this->trxLevel() ) {
820 // Meaningful transactions should ideally have been resolved by now
821 if ( $this->writesOrCallbacksPending() ) {
822 $this->queryLogger
->warning(
823 __METHOD__
. ": writes or callbacks still pending.",
824 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
827 // Check if it is possible to properly commit and trigger callbacks
828 if ( $this->trxEndCallbacksSuppressed
) {
829 throw new DBUnexpectedError(
831 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
834 // Commit the changes and run any callbacks as needed
835 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
837 // Close the actual connection in the binding handle
838 $closed = $this->closeConnection();
840 // Sanity check that no callbacks are dangling
842 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
844 throw new RuntimeException( "Transaction callbacks still pending." );
847 $closed = true; // already closed; nothing to do
850 $this->opened
= false;
856 * Make sure isOpen() returns true as a sanity check
858 * @throws DBUnexpectedError
860 protected function assertOpen() {
861 if ( !$this->isOpen() ) {
862 throw new DBUnexpectedError( $this, "DB connection was already closed." );
867 * Closes underlying database connection
869 * @return bool Whether connection was closed successfully
871 abstract protected function closeConnection();
873 public function reportConnectionError( $error = 'Unknown error' ) {
874 $myError = $this->lastError();
880 throw new DBConnectionError( $this, $error );
884 * The DBMS-dependent part of query()
886 * @param string $sql SQL query.
887 * @return ResultWrapper|bool Result object to feed to fetchObject,
888 * fetchRow, ...; or false on failure
890 abstract protected function doQuery( $sql );
893 * Determine whether a query writes to the DB.
894 * Should return true if unsure.
899 protected function isWriteQuery( $sql ) {
901 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
906 * @return string|null
908 protected function getQueryVerb( $sql ) {
909 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
913 * Determine whether a SQL statement is sensitive to isolation level.
914 * A SQL statement is considered transactable if its result could vary
915 * depending on the transaction isolation level. Operational commands
916 * such as 'SET' and 'SHOW' are not considered to be transactable.
921 protected function isTransactableQuery( $sql ) {
923 $this->getQueryVerb( $sql ),
924 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
930 * @param string $sql A SQL query
931 * @return bool Whether $sql is SQL for TEMPORARY table operation
933 protected function registerTempTableOperation( $sql ) {
935 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
939 $this->sessionTempTables
[$matches[1]] = 1;
942 } elseif ( preg_match(
943 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
947 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
948 unset( $this->sessionTempTables
[$matches[1]] );
951 } elseif ( preg_match(
952 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
956 return isset( $this->sessionTempTables
[$matches[1]] );
957 } elseif ( preg_match(
958 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
962 return isset( $this->sessionTempTables
[$matches[1]] );
968 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
969 $priorWritesPending = $this->writesOrCallbacksPending();
970 $this->lastQuery
= $sql;
972 $isWrite = $this->isWriteQuery( $sql );
974 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
976 $isNonTempWrite = false;
980 if ( $this->getLBInfo( 'replica' ) === true ) {
983 'Write operations are not allowed on replica database connections.'
986 # In theory, non-persistent writes are allowed in read-only mode, but due to things
987 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
988 $reason = $this->getReadOnlyReason();
989 if ( $reason !== false ) {
990 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
992 # Set a flag indicating that writes have been done
993 $this->lastWriteTime
= microtime( true );
996 # Add trace comment to the begin of the sql string, right after the operator.
997 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
998 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1000 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1001 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1002 && $this->isTransactableQuery( $sql )
1004 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1005 $this->trxAutomatic
= true;
1008 # Keep track of whether the transaction has write queries pending
1009 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1010 $this->trxDoneWrites
= true;
1011 $this->trxProfiler
->transactionWritingIn(
1012 $this->server
, $this->dbName
, $this->trxShortId
);
1015 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1016 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1019 # Avoid fatals if close() was called
1020 $this->assertOpen();
1022 # Send the query to the server
1023 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1025 # Try reconnecting if the connection was lost
1026 if ( false === $ret && $this->wasErrorReissuable() ) {
1027 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1028 # Stash the last error values before anything might clear them
1029 $lastError = $this->lastError();
1030 $lastErrno = $this->lastErrno();
1031 # Update state tracking to reflect transaction loss due to disconnection
1032 $this->handleSessionLoss();
1033 if ( $this->reconnect() ) {
1034 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1035 $params = [ 'dbserver' => $this->getServer() ];
1036 $this->connLogger
->warning( $msg, $params );
1037 $this->queryLogger
->warning( $msg, $params +
1038 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1040 if ( $recoverable ) {
1041 # Should be safe to silently retry the query
1042 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1044 # Callers may catch the exception and continue to use the DB
1045 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1048 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1049 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1053 if ( false === $ret ) {
1054 # Deadlocks cause the entire transaction to abort, not just the statement.
1055 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1056 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1057 if ( $this->wasDeadlock() ) {
1058 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1059 $tempIgnore = false; // not recoverable
1061 # Update state tracking to reflect transaction loss
1062 $this->handleSessionLoss();
1065 $this->reportQueryError(
1066 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1069 $res = $this->resultObject( $ret );
1075 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1077 * @param string $sql Original SQL query
1078 * @param string $commentedSql SQL query with debugging/trace comment
1079 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1080 * @param string $fname Name of the calling function
1081 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1082 * object for a successful read query, or false on failure
1084 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1085 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1086 # generalizeSQL() will probably cut down the query to reasonable
1087 # logging size most of the time. The substr is really just a sanity check.
1089 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1091 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1094 # Include query transaction state
1095 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1097 $startTime = microtime( true );
1098 if ( $this->profiler
) {
1099 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1101 $this->affectedRowCount
= null;
1102 $ret = $this->doQuery( $commentedSql );
1103 $this->affectedRowCount
= $this->affectedRows();
1104 if ( $this->profiler
) {
1105 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1107 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1109 unset( $queryProfSection ); // profile out (if set)
1111 if ( $ret !== false ) {
1112 $this->lastPing
= $startTime;
1113 if ( $isWrite && $this->trxLevel
) {
1114 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1115 $this->trxWriteCallers
[] = $fname;
1119 if ( $sql === self
::PING_QUERY
) {
1120 $this->rttEstimate
= $queryRuntime;
1123 $this->trxProfiler
->recordQueryCompletion(
1124 $queryProf, $startTime, $isWrite, $this->affectedRows()
1126 $this->queryLogger
->debug( $sql, [
1128 'master' => $isMaster,
1129 'runtime' => $queryRuntime,
1136 * Update the estimated run-time of a query, not counting large row lock times
1138 * LoadBalancer can be set to rollback transactions that will create huge replication
1139 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1140 * queries, like inserting a row can take a long time due to row locking. This method
1141 * uses some simple heuristics to discount those cases.
1143 * @param string $sql A SQL write query
1144 * @param float $runtime Total runtime, including RTT
1145 * @param int $affected Affected row count
1147 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1148 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1149 $indicativeOfReplicaRuntime = true;
1150 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1151 $verb = $this->getQueryVerb( $sql );
1152 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1153 if ( $verb === 'INSERT' ) {
1154 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1155 } elseif ( $verb === 'REPLACE' ) {
1156 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1160 $this->trxWriteDuration +
= $runtime;
1161 $this->trxWriteQueryCount +
= 1;
1162 $this->trxWriteAffectedRows +
= $affected;
1163 if ( $indicativeOfReplicaRuntime ) {
1164 $this->trxWriteAdjDuration +
= $runtime;
1165 $this->trxWriteAdjQueryCount +
= 1;
1170 * Determine whether or not it is safe to retry queries after a database
1171 * connection is lost
1173 * @param string $sql SQL query
1174 * @param bool $priorWritesPending Whether there is a transaction open with
1175 * possible write queries or transaction pre-commit/idle callbacks
1176 * waiting on it to finish.
1177 * @return bool True if it is safe to retry the query, false otherwise
1179 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1180 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1181 # Dropped connections also mean that named locks are automatically released.
1182 # Only allow error suppression in autocommit mode or when the lost transaction
1183 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1184 if ( $this->namedLocksHeld
) {
1185 return false; // possible critical section violation
1186 } elseif ( $sql === 'COMMIT' ) {
1187 return !$priorWritesPending; // nothing written anyway? (T127428)
1188 } elseif ( $sql === 'ROLLBACK' ) {
1189 return true; // transaction lost...which is also what was requested :)
1190 } elseif ( $this->explicitTrxActive() ) {
1191 return false; // don't drop atomocity
1192 } elseif ( $priorWritesPending ) {
1193 return false; // prior writes lost from implicit transaction
1200 * Clean things up after transaction loss due to disconnection
1202 * @return null|Exception
1204 private function handleSessionLoss() {
1205 $this->trxLevel
= 0;
1206 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1207 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1208 $this->sessionTempTables
= [];
1209 $this->namedLocksHeld
= [];
1211 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1214 // Handle callbacks in trxEndCallbacks
1215 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1216 } catch ( Exception
$ex ) {
1217 // Already logged; move on...
1221 // Handle callbacks in trxRecurringCallbacks
1222 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1223 } catch ( Exception
$ex ) {
1224 // Already logged; move on...
1232 * Checks whether the cause of the error is detected to be a timeout.
1234 * It returns false by default, and not all engines support detecting this yet.
1235 * If this returns false, it will be treated as a generic query error.
1237 * @param string $error Error text
1238 * @param int $errno Error number
1241 protected function wasQueryTimeout( $error, $errno ) {
1245 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1246 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1247 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1249 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1250 $this->queryLogger
->error(
1251 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1252 $this->getLogContext( [
1253 'method' => __METHOD__
,
1256 'sql1line' => $sql1line,
1260 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1261 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1262 if ( $wasQueryTimeout ) {
1263 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1265 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1270 public function freeResult( $res ) {
1273 public function selectField(
1274 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1276 if ( $var === '*' ) { // sanity
1277 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1280 if ( !is_array( $options ) ) {
1281 $options = [ $options ];
1284 $options['LIMIT'] = 1;
1286 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1287 if ( $res === false ||
!$this->numRows( $res ) ) {
1291 $row = $this->fetchRow( $res );
1293 if ( $row !== false ) {
1294 return reset( $row );
1300 public function selectFieldValues(
1301 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1303 if ( $var === '*' ) { // sanity
1304 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1305 } elseif ( !is_string( $var ) ) { // sanity
1306 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1309 if ( !is_array( $options ) ) {
1310 $options = [ $options ];
1313 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1314 if ( $res === false ) {
1319 foreach ( $res as $row ) {
1320 $values[] = $row->$var;
1327 * Returns an optional USE INDEX clause to go after the table, and a
1328 * string to go at the end of the query.
1330 * @param array $options Associative array of options to be turned into
1331 * an SQL query, valid keys are listed in the function.
1333 * @see Database::select()
1335 protected function makeSelectOptions( $options ) {
1336 $preLimitTail = $postLimitTail = '';
1341 foreach ( $options as $key => $option ) {
1342 if ( is_numeric( $key ) ) {
1343 $noKeyOptions[$option] = true;
1347 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1349 $preLimitTail .= $this->makeOrderBy( $options );
1351 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1352 $postLimitTail .= ' FOR UPDATE';
1355 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1356 $postLimitTail .= ' LOCK IN SHARE MODE';
1359 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1360 $startOpts .= 'DISTINCT';
1363 # Various MySQL extensions
1364 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1365 $startOpts .= ' /*! STRAIGHT_JOIN */';
1368 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1369 $startOpts .= ' HIGH_PRIORITY';
1372 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1373 $startOpts .= ' SQL_BIG_RESULT';
1376 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1377 $startOpts .= ' SQL_BUFFER_RESULT';
1380 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1381 $startOpts .= ' SQL_SMALL_RESULT';
1384 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1385 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1388 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1389 $startOpts .= ' SQL_CACHE';
1392 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1393 $startOpts .= ' SQL_NO_CACHE';
1396 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1397 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1401 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1402 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1407 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1411 * Returns an optional GROUP BY with an optional HAVING
1413 * @param array $options Associative array of options
1415 * @see Database::select()
1418 protected function makeGroupByWithHaving( $options ) {
1420 if ( isset( $options['GROUP BY'] ) ) {
1421 $gb = is_array( $options['GROUP BY'] )
1422 ?
implode( ',', $options['GROUP BY'] )
1423 : $options['GROUP BY'];
1424 $sql .= ' GROUP BY ' . $gb;
1426 if ( isset( $options['HAVING'] ) ) {
1427 $having = is_array( $options['HAVING'] )
1428 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1429 : $options['HAVING'];
1430 $sql .= ' HAVING ' . $having;
1437 * Returns an optional ORDER BY
1439 * @param array $options Associative array of options
1441 * @see Database::select()
1444 protected function makeOrderBy( $options ) {
1445 if ( isset( $options['ORDER BY'] ) ) {
1446 $ob = is_array( $options['ORDER BY'] )
1447 ?
implode( ',', $options['ORDER BY'] )
1448 : $options['ORDER BY'];
1450 return ' ORDER BY ' . $ob;
1456 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1457 $options = [], $join_conds = [] ) {
1458 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1460 return $this->query( $sql, $fname );
1463 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1464 $options = [], $join_conds = []
1466 if ( is_array( $vars ) ) {
1467 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1470 $options = (array)$options;
1471 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1472 ?
$options['USE INDEX']
1475 isset( $options['IGNORE INDEX'] ) &&
1476 is_array( $options['IGNORE INDEX'] )
1478 ?
$options['IGNORE INDEX']
1481 if ( is_array( $table ) ) {
1483 $this->tableNamesWithIndexClauseOrJOIN(
1484 $table, $useIndexes, $ignoreIndexes, $join_conds );
1485 } elseif ( $table != '' ) {
1487 $this->tableNamesWithIndexClauseOrJOIN(
1488 [ $table ], $useIndexes, $ignoreIndexes, [] );
1493 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1494 $this->makeSelectOptions( $options );
1496 if ( is_array( $conds ) ) {
1497 $conds = $this->makeList( $conds, self
::LIST_AND
);
1500 if ( $conds === null ||
$conds === false ) {
1501 $this->queryLogger
->warning(
1505 . ' with incorrect parameters: $conds must be a string or an array'
1510 if ( $conds === '' ) {
1511 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1512 } elseif ( is_string( $conds ) ) {
1513 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1514 "WHERE $conds $preLimitTail";
1516 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1519 if ( isset( $options['LIMIT'] ) ) {
1520 $sql = $this->limitResult( $sql, $options['LIMIT'],
1521 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1523 $sql = "$sql $postLimitTail";
1525 if ( isset( $options['EXPLAIN'] ) ) {
1526 $sql = 'EXPLAIN ' . $sql;
1532 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1533 $options = [], $join_conds = []
1535 $options = (array)$options;
1536 $options['LIMIT'] = 1;
1537 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1539 if ( $res === false ) {
1543 if ( !$this->numRows( $res ) ) {
1547 $obj = $this->fetchObject( $res );
1552 public function estimateRowCount(
1553 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1556 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1559 $row = $this->fetchRow( $res );
1560 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1566 public function selectRowCount(
1567 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1570 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1571 // The identifier quotes is primarily for MSSQL.
1572 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1573 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1574 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1577 $row = $this->fetchRow( $res );
1578 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1585 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1586 * It's only slightly flawed. Don't use for anything important.
1588 * @param string $sql A SQL Query
1592 protected static function generalizeSQL( $sql ) {
1593 # This does the same as the regexp below would do, but in such a way
1594 # as to avoid crashing php on some large strings.
1595 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1597 $sql = str_replace( "\\\\", '', $sql );
1598 $sql = str_replace( "\\'", '', $sql );
1599 $sql = str_replace( "\\\"", '', $sql );
1600 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1601 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1603 # All newlines, tabs, etc replaced by single space
1604 $sql = preg_replace( '/\s+/', ' ', $sql );
1607 # except the ones surrounded by characters, e.g. l10n
1608 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1609 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1614 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1615 $info = $this->fieldInfo( $table, $field );
1620 public function indexExists( $table, $index, $fname = __METHOD__
) {
1621 if ( !$this->tableExists( $table ) ) {
1625 $info = $this->indexInfo( $table, $index, $fname );
1626 if ( is_null( $info ) ) {
1629 return $info !== false;
1633 public function tableExists( $table, $fname = __METHOD__
) {
1634 $tableRaw = $this->tableName( $table, 'raw' );
1635 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1636 return true; // already known to exist
1639 $table = $this->tableName( $table );
1640 $ignoreErrors = true;
1641 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1646 public function indexUnique( $table, $index ) {
1647 $indexInfo = $this->indexInfo( $table, $index );
1649 if ( !$indexInfo ) {
1653 return !$indexInfo[0]->Non_unique
;
1657 * Helper for Database::insert().
1659 * @param array $options
1662 protected function makeInsertOptions( $options ) {
1663 return implode( ' ', $options );
1666 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1667 # No rows to insert, easy just return now
1668 if ( !count( $a ) ) {
1672 $table = $this->tableName( $table );
1674 if ( !is_array( $options ) ) {
1675 $options = [ $options ];
1679 if ( isset( $options['fileHandle'] ) ) {
1680 $fh = $options['fileHandle'];
1682 $options = $this->makeInsertOptions( $options );
1684 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1686 $keys = array_keys( $a[0] );
1689 $keys = array_keys( $a );
1692 $sql = 'INSERT ' . $options .
1693 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1697 foreach ( $a as $row ) {
1703 $sql .= '(' . $this->makeList( $row ) . ')';
1706 $sql .= '(' . $this->makeList( $a ) . ')';
1709 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1711 } elseif ( $fh !== null ) {
1715 return (bool)$this->query( $sql, $fname );
1719 * Make UPDATE options array for Database::makeUpdateOptions
1721 * @param array $options
1724 protected function makeUpdateOptionsArray( $options ) {
1725 if ( !is_array( $options ) ) {
1726 $options = [ $options ];
1731 if ( in_array( 'IGNORE', $options ) ) {
1739 * Make UPDATE options for the Database::update function
1741 * @param array $options The options passed to Database::update
1744 protected function makeUpdateOptions( $options ) {
1745 $opts = $this->makeUpdateOptionsArray( $options );
1747 return implode( ' ', $opts );
1750 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1751 $table = $this->tableName( $table );
1752 $opts = $this->makeUpdateOptions( $options );
1753 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1755 if ( $conds !== [] && $conds !== '*' ) {
1756 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1759 return (bool)$this->query( $sql, $fname );
1762 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1763 if ( !is_array( $a ) ) {
1764 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1770 foreach ( $a as $field => $value ) {
1772 if ( $mode == self
::LIST_AND
) {
1774 } elseif ( $mode == self
::LIST_OR
) {
1783 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1784 $list .= "($value)";
1785 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1788 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1790 // Remove null from array to be handled separately if found
1791 $includeNull = false;
1792 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1793 $includeNull = true;
1794 unset( $value[$nullKey] );
1796 if ( count( $value ) == 0 && !$includeNull ) {
1797 throw new InvalidArgumentException(
1798 __METHOD__
. ": empty input for field $field" );
1799 } elseif ( count( $value ) == 0 ) {
1800 // only check if $field is null
1801 $list .= "$field IS NULL";
1803 // IN clause contains at least one valid element
1804 if ( $includeNull ) {
1805 // Group subconditions to ensure correct precedence
1808 if ( count( $value ) == 1 ) {
1809 // Special-case single values, as IN isn't terribly efficient
1810 // Don't necessarily assume the single key is 0; we don't
1811 // enforce linear numeric ordering on other arrays here.
1812 $value = array_values( $value )[0];
1813 $list .= $field . " = " . $this->addQuotes( $value );
1815 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1817 // if null present in array, append IS NULL
1818 if ( $includeNull ) {
1819 $list .= " OR $field IS NULL)";
1822 } elseif ( $value === null ) {
1823 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1824 $list .= "$field IS ";
1825 } elseif ( $mode == self
::LIST_SET
) {
1826 $list .= "$field = ";
1831 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1833 $list .= "$field = ";
1835 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1842 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1845 foreach ( $data as $base => $sub ) {
1846 if ( count( $sub ) ) {
1847 $conds[] = $this->makeList(
1848 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1854 return $this->makeList( $conds, self
::LIST_OR
);
1856 // Nothing to search for...
1861 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1865 public function bitNot( $field ) {
1869 public function bitAnd( $fieldLeft, $fieldRight ) {
1870 return "($fieldLeft & $fieldRight)";
1873 public function bitOr( $fieldLeft, $fieldRight ) {
1874 return "($fieldLeft | $fieldRight)";
1877 public function buildConcat( $stringList ) {
1878 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1881 public function buildGroupConcatField(
1882 $delim, $table, $field, $conds = '', $join_conds = []
1884 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1886 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1889 public function buildSubstring( $input, $startPosition, $length = null ) {
1890 $this->assertBuildSubstringParams( $startPosition, $length );
1891 $functionBody = "$input FROM $startPosition";
1892 if ( $length !== null ) {
1893 $functionBody .= " FOR $length";
1895 return 'SUBSTRING(' . $functionBody . ')';
1899 * Check type and bounds for parameters to self::buildSubstring()
1901 * All supported databases have substring functions that behave the same for
1902 * positive $startPosition and non-negative $length, but behaviors differ when
1903 * given 0 or negative $startPosition or negative $length. The simplest
1904 * solution to that is to just forbid those values.
1906 * @param int $startPosition
1907 * @param int|null $length
1910 protected function assertBuildSubstringParams( $startPosition, $length ) {
1911 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
1912 throw new InvalidArgumentException(
1913 '$startPosition must be a positive integer'
1916 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
1917 throw new InvalidArgumentException(
1918 '$length must be null or an integer greater than or equal to 0'
1923 public function buildStringCast( $field ) {
1927 public function buildIntegerCast( $field ) {
1928 return 'CAST( ' . $field . ' AS INTEGER )';
1931 public function databasesAreIndependent() {
1935 public function selectDB( $db ) {
1936 # Stub. Shouldn't cause serious problems if it's not overridden, but
1937 # if your database engine supports a concept similar to MySQL's
1938 # databases you may as well.
1939 $this->dbName
= $db;
1944 public function getDBname() {
1945 return $this->dbName
;
1948 public function getServer() {
1949 return $this->server
;
1952 public function tableName( $name, $format = 'quoted' ) {
1953 # Skip the entire process when we have a string quoted on both ends.
1954 # Note that we check the end so that we will still quote any use of
1955 # use of `database`.table. But won't break things if someone wants
1956 # to query a database table with a dot in the name.
1957 if ( $this->isQuotedIdentifier( $name ) ) {
1961 # Lets test for any bits of text that should never show up in a table
1962 # name. Basically anything like JOIN or ON which are actually part of
1963 # SQL queries, but may end up inside of the table value to combine
1964 # sql. Such as how the API is doing.
1965 # Note that we use a whitespace test rather than a \b test to avoid
1966 # any remote case where a word like on may be inside of a table name
1967 # surrounded by symbols which may be considered word breaks.
1968 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1972 # Split database and table into proper variables.
1973 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1975 # Quote $table and apply the prefix if not quoted.
1976 # $tableName might be empty if this is called from Database::replaceVars()
1977 $tableName = "{$prefix}{$table}";
1978 if ( $format === 'quoted'
1979 && !$this->isQuotedIdentifier( $tableName )
1980 && $tableName !== ''
1982 $tableName = $this->addIdentifierQuotes( $tableName );
1985 # Quote $schema and $database and merge them with the table name if needed
1986 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1987 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1993 * Get the table components needed for a query given the currently selected database
1995 * @param string $name Table name in the form of db.schema.table, db.table, or table
1996 * @return array (DB name or "" for default, schema name, table prefix, table name)
1998 protected function qualifiedTableComponents( $name ) {
1999 # We reverse the explode so that database.table and table both output the correct table.
2000 $dbDetails = explode( '.', $name, 3 );
2001 if ( count( $dbDetails ) == 3 ) {
2002 list( $database, $schema, $table ) = $dbDetails;
2003 # We don't want any prefix added in this case
2005 } elseif ( count( $dbDetails ) == 2 ) {
2006 list( $database, $table ) = $dbDetails;
2007 # We don't want any prefix added in this case
2009 # In dbs that support it, $database may actually be the schema
2010 # but that doesn't affect any of the functionality here
2013 list( $table ) = $dbDetails;
2014 if ( isset( $this->tableAliases
[$table] ) ) {
2015 $database = $this->tableAliases
[$table]['dbname'];
2016 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2017 ?
$this->tableAliases
[$table]['schema']
2019 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2020 ?
$this->tableAliases
[$table]['prefix']
2021 : $this->tablePrefix
;
2024 $schema = $this->schema
; # Default schema
2025 $prefix = $this->tablePrefix
; # Default prefix
2029 return [ $database, $schema, $prefix, $table ];
2033 * @param string|null $namespace Database or schema
2034 * @param string $relation Name of table, view, sequence, etc...
2035 * @param string $format One of (raw, quoted)
2036 * @return string Relation name with quoted and merged $namespace as needed
2038 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2039 if ( strlen( $namespace ) ) {
2040 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2041 $namespace = $this->addIdentifierQuotes( $namespace );
2043 $relation = $namespace . '.' . $relation;
2049 public function tableNames() {
2050 $inArray = func_get_args();
2053 foreach ( $inArray as $name ) {
2054 $retVal[$name] = $this->tableName( $name );
2060 public function tableNamesN() {
2061 $inArray = func_get_args();
2064 foreach ( $inArray as $name ) {
2065 $retVal[] = $this->tableName( $name );
2072 * Get an aliased table name
2073 * e.g. tableName AS newTableName
2075 * @param string $name Table name, see tableName()
2076 * @param string|bool $alias Alias (optional)
2077 * @return string SQL name for aliased table. Will not alias a table to its own name
2079 protected function tableNameWithAlias( $name, $alias = false ) {
2080 if ( !$alias ||
$alias == $name ) {
2081 return $this->tableName( $name );
2083 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2088 * Gets an array of aliased table names
2090 * @param array $tables [ [alias] => table ]
2091 * @return string[] See tableNameWithAlias()
2093 protected function tableNamesWithAlias( $tables ) {
2095 foreach ( $tables as $alias => $table ) {
2096 if ( is_numeric( $alias ) ) {
2099 $retval[] = $this->tableNameWithAlias( $table, $alias );
2106 * Get an aliased field name
2107 * e.g. fieldName AS newFieldName
2109 * @param string $name Field name
2110 * @param string|bool $alias Alias (optional)
2111 * @return string SQL name for aliased field. Will not alias a field to its own name
2113 protected function fieldNameWithAlias( $name, $alias = false ) {
2114 if ( !$alias ||
(string)$alias === (string)$name ) {
2117 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2122 * Gets an array of aliased field names
2124 * @param array $fields [ [alias] => field ]
2125 * @return string[] See fieldNameWithAlias()
2127 protected function fieldNamesWithAlias( $fields ) {
2129 foreach ( $fields as $alias => $field ) {
2130 if ( is_numeric( $alias ) ) {
2133 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2140 * Get the aliased table name clause for a FROM clause
2141 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2143 * @param array $tables ( [alias] => table )
2144 * @param array $use_index Same as for select()
2145 * @param array $ignore_index Same as for select()
2146 * @param array $join_conds Same as for select()
2149 protected function tableNamesWithIndexClauseOrJOIN(
2150 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2154 $use_index = (array)$use_index;
2155 $ignore_index = (array)$ignore_index;
2156 $join_conds = (array)$join_conds;
2158 foreach ( $tables as $alias => $table ) {
2159 if ( !is_string( $alias ) ) {
2160 // No alias? Set it equal to the table name
2164 if ( is_array( $table ) ) {
2165 // A parenthesized group
2166 if ( count( $table ) > 1 ) {
2168 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2172 $innerTable = reset( $table );
2173 $innerAlias = key( $table );
2174 $joinedTable = $this->tableNameWithAlias(
2176 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2180 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2183 // Is there a JOIN clause for this table?
2184 if ( isset( $join_conds[$alias] ) ) {
2185 list( $joinType, $conds ) = $join_conds[$alias];
2186 $tableClause = $joinType;
2187 $tableClause .= ' ' . $joinedTable;
2188 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2189 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2191 $tableClause .= ' ' . $use;
2194 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2195 $ignore = $this->ignoreIndexClause(
2196 implode( ',', (array)$ignore_index[$alias] ) );
2197 if ( $ignore != '' ) {
2198 $tableClause .= ' ' . $ignore;
2201 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2203 $tableClause .= ' ON (' . $on . ')';
2206 $retJOIN[] = $tableClause;
2207 } elseif ( isset( $use_index[$alias] ) ) {
2208 // Is there an INDEX clause for this table?
2209 $tableClause = $joinedTable;
2210 $tableClause .= ' ' . $this->useIndexClause(
2211 implode( ',', (array)$use_index[$alias] )
2214 $ret[] = $tableClause;
2215 } elseif ( isset( $ignore_index[$alias] ) ) {
2216 // Is there an INDEX clause for this table?
2217 $tableClause = $joinedTable;
2218 $tableClause .= ' ' . $this->ignoreIndexClause(
2219 implode( ',', (array)$ignore_index[$alias] )
2222 $ret[] = $tableClause;
2224 $tableClause = $joinedTable;
2226 $ret[] = $tableClause;
2230 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2231 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2232 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2234 // Compile our final table clause
2235 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2239 * Allows for index remapping in queries where this is not consistent across DBMS
2241 * @param string $index
2244 protected function indexName( $index ) {
2245 return isset( $this->indexAliases
[$index] )
2246 ?
$this->indexAliases
[$index]
2250 public function addQuotes( $s ) {
2251 if ( $s instanceof Blob
) {
2254 if ( $s === null ) {
2256 } elseif ( is_bool( $s ) ) {
2259 # This will also quote numeric values. This should be harmless,
2260 # and protects against weird problems that occur when they really
2261 # _are_ strings such as article titles and string->number->string
2262 # conversion is not 1:1.
2263 return "'" . $this->strencode( $s ) . "'";
2268 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2269 * MySQL uses `backticks` while basically everything else uses double quotes.
2270 * Since MySQL is the odd one out here the double quotes are our generic
2271 * and we implement backticks in DatabaseMysqlBase.
2276 public function addIdentifierQuotes( $s ) {
2277 return '"' . str_replace( '"', '""', $s ) . '"';
2281 * Returns if the given identifier looks quoted or not according to
2282 * the database convention for quoting identifiers .
2284 * @note Do not use this to determine if untrusted input is safe.
2285 * A malicious user can trick this function.
2286 * @param string $name
2289 public function isQuotedIdentifier( $name ) {
2290 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2295 * @param string $escapeChar
2298 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2299 return str_replace( [ $escapeChar, '%', '_' ],
2300 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2304 public function buildLike() {
2305 $params = func_get_args();
2307 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2308 $params = $params[0];
2313 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2314 // may escape backslashes, creating problems of double escaping. The `
2315 // character has good cross-DBMS compatibility, avoiding special operators
2316 // in MS SQL like ^ and %
2319 foreach ( $params as $value ) {
2320 if ( $value instanceof LikeMatch
) {
2321 $s .= $value->toString();
2323 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2327 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2330 public function anyChar() {
2331 return new LikeMatch( '_' );
2334 public function anyString() {
2335 return new LikeMatch( '%' );
2338 public function nextSequenceValue( $seqName ) {
2343 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2344 * is only needed because a) MySQL must be as efficient as possible due to
2345 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2346 * which index to pick. Anyway, other databases might have different
2347 * indexes on a given table. So don't bother overriding this unless you're
2349 * @param string $index
2352 public function useIndexClause( $index ) {
2357 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2358 * is only needed because a) MySQL must be as efficient as possible due to
2359 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2360 * which index to pick. Anyway, other databases might have different
2361 * indexes on a given table. So don't bother overriding this unless you're
2363 * @param string $index
2366 public function ignoreIndexClause( $index ) {
2370 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2371 if ( count( $rows ) == 0 ) {
2376 if ( !is_array( reset( $rows ) ) ) {
2381 $this->startAtomic( $fname );
2382 $affectedRowCount = 0;
2383 foreach ( $rows as $row ) {
2384 // Delete rows which collide with this one
2385 $indexWhereClauses = [];
2386 foreach ( $uniqueIndexes as $index ) {
2387 $indexColumns = (array)$index;
2388 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2389 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2390 throw new DBUnexpectedError(
2392 'New record does not provide all values for unique key (' .
2393 implode( ', ', $indexColumns ) . ')'
2395 } elseif ( in_array( null, $indexRowValues, true ) ) {
2396 throw new DBUnexpectedError(
2398 'New record has a null value for unique key (' .
2399 implode( ', ', $indexColumns ) . ')'
2402 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2405 if ( $indexWhereClauses ) {
2406 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2407 $affectedRowCount +
= $this->affectedRows();
2410 // Now insert the row
2411 $this->insert( $table, $row, $fname );
2412 $affectedRowCount +
= $this->affectedRows();
2414 $this->endAtomic( $fname );
2415 $this->affectedRowCount
= $affectedRowCount;
2416 } catch ( Exception
$e ) {
2417 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2423 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2426 * @param string $table Table name
2427 * @param array|string $rows Row(s) to insert
2428 * @param string $fname Caller function name
2430 * @return ResultWrapper
2432 protected function nativeReplace( $table, $rows, $fname ) {
2433 $table = $this->tableName( $table );
2436 if ( !is_array( reset( $rows ) ) ) {
2440 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2443 foreach ( $rows as $row ) {
2450 $sql .= '(' . $this->makeList( $row ) . ')';
2453 return $this->query( $sql, $fname );
2456 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2459 if ( !count( $rows ) ) {
2460 return true; // nothing to do
2463 if ( !is_array( reset( $rows ) ) ) {
2467 if ( count( $uniqueIndexes ) ) {
2468 $clauses = []; // list WHERE clauses that each identify a single row
2469 foreach ( $rows as $row ) {
2470 foreach ( $uniqueIndexes as $index ) {
2471 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2472 $rowKey = []; // unique key to this row
2473 foreach ( $index as $column ) {
2474 $rowKey[$column] = $row[$column];
2476 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2479 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2484 $affectedRowCount = 0;
2486 $this->startAtomic( $fname );
2487 # Update any existing conflicting row(s)
2488 if ( $where !== false ) {
2489 $ok = $this->update( $table, $set, $where, $fname );
2490 $affectedRowCount +
= $this->affectedRows();
2494 # Now insert any non-conflicting row(s)
2495 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2496 $affectedRowCount +
= $this->affectedRows();
2497 $this->endAtomic( $fname );
2498 $this->affectedRowCount
= $affectedRowCount;
2499 } catch ( Exception
$e ) {
2500 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2507 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2511 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2514 $delTable = $this->tableName( $delTable );
2515 $joinTable = $this->tableName( $joinTable );
2516 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2517 if ( $conds != '*' ) {
2518 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2522 $this->query( $sql, $fname );
2525 public function textFieldSize( $table, $field ) {
2526 $table = $this->tableName( $table );
2527 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2528 $res = $this->query( $sql, __METHOD__
);
2529 $row = $this->fetchObject( $res );
2533 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2542 public function delete( $table, $conds, $fname = __METHOD__
) {
2544 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2547 $table = $this->tableName( $table );
2548 $sql = "DELETE FROM $table";
2550 if ( $conds != '*' ) {
2551 if ( is_array( $conds ) ) {
2552 $conds = $this->makeList( $conds, self
::LIST_AND
);
2554 $sql .= ' WHERE ' . $conds;
2557 return $this->query( $sql, $fname );
2560 final public function insertSelect(
2561 $destTable, $srcTable, $varMap, $conds,
2562 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2564 static $hints = [ 'NO_AUTO_COLUMNS' ];
2566 $insertOptions = (array)$insertOptions;
2567 $selectOptions = (array)$selectOptions;
2569 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2570 // For massive migrations with downtime, we don't want to select everything
2571 // into memory and OOM, so do all this native on the server side if possible.
2572 return $this->nativeInsertSelect(
2578 array_diff( $insertOptions, $hints ),
2584 return $this->nonNativeInsertSelect(
2590 array_diff( $insertOptions, $hints ),
2597 * @param array $insertOptions INSERT options
2598 * @param array $selectOptions SELECT options
2599 * @return bool Whether an INSERT SELECT with these options will be replication safe
2602 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2607 * Implementation of insertSelect() based on select() and insert()
2609 * @see IDatabase::insertSelect()
2611 * @param string $destTable
2612 * @param string|array $srcTable
2613 * @param array $varMap
2614 * @param array $conds
2615 * @param string $fname
2616 * @param array $insertOptions
2617 * @param array $selectOptions
2618 * @param array $selectJoinConds
2621 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2622 $fname = __METHOD__
,
2623 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2625 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2626 // on only the master (without needing row-based-replication). It also makes it easy to
2627 // know how big the INSERT is going to be.
2629 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2630 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2632 $selectOptions[] = 'FOR UPDATE';
2633 $res = $this->select(
2634 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2641 $affectedRowCount = 0;
2642 $this->startAtomic( $fname );
2645 foreach ( $res as $row ) {
2646 $rows[] = (array)$row;
2648 // Avoid inserts that are too huge
2649 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2650 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2654 $affectedRowCount +
= $this->affectedRows();
2658 if ( $rows && $ok ) {
2659 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2661 $affectedRowCount +
= $this->affectedRows();
2665 $this->endAtomic( $fname );
2666 $this->affectedRowCount
= $affectedRowCount;
2668 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2671 } catch ( Exception
$e ) {
2672 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2678 * Native server-side implementation of insertSelect() for situations where
2679 * we don't want to select everything into memory
2681 * @see IDatabase::insertSelect()
2682 * @param string $destTable
2683 * @param string|array $srcTable
2684 * @param array $varMap
2685 * @param array $conds
2686 * @param string $fname
2687 * @param array $insertOptions
2688 * @param array $selectOptions
2689 * @param array $selectJoinConds
2692 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2693 $fname = __METHOD__
,
2694 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2696 $destTable = $this->tableName( $destTable );
2698 if ( !is_array( $insertOptions ) ) {
2699 $insertOptions = [ $insertOptions ];
2702 $insertOptions = $this->makeInsertOptions( $insertOptions );
2704 $selectSql = $this->selectSQLText(
2706 array_values( $varMap ),
2713 $sql = "INSERT $insertOptions" .
2714 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2717 return $this->query( $sql, $fname );
2721 * Construct a LIMIT query with optional offset. This is used for query
2722 * pages. The SQL should be adjusted so that only the first $limit rows
2723 * are returned. If $offset is provided as well, then the first $offset
2724 * rows should be discarded, and the next $limit rows should be returned.
2725 * If the result of the query is not ordered, then the rows to be returned
2726 * are theoretically arbitrary.
2728 * $sql is expected to be a SELECT, if that makes a difference.
2730 * The version provided by default works in MySQL and SQLite. It will very
2731 * likely need to be overridden for most other DBMSes.
2733 * @param string $sql SQL query we will append the limit too
2734 * @param int $limit The SQL limit
2735 * @param int|bool $offset The SQL offset (default false)
2736 * @throws DBUnexpectedError
2739 public function limitResult( $sql, $limit, $offset = false ) {
2740 if ( !is_numeric( $limit ) ) {
2741 throw new DBUnexpectedError( $this,
2742 "Invalid non-numeric limit passed to limitResult()\n" );
2745 return "$sql LIMIT "
2746 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2750 public function unionSupportsOrderAndLimit() {
2751 return true; // True for almost every DB supported
2754 public function unionQueries( $sqls, $all ) {
2755 $glue = $all ?
') UNION ALL (' : ') UNION (';
2757 return '(' . implode( $glue, $sqls ) . ')';
2760 public function unionConditionPermutations(
2761 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2762 $options = [], $join_conds = []
2764 // First, build the Cartesian product of $permute_conds
2766 foreach ( $permute_conds as $field => $values ) {
2768 // Skip empty $values
2771 $values = array_unique( $values ); // For sanity
2773 foreach ( $conds as $cond ) {
2774 foreach ( $values as $value ) {
2775 $cond[$field] = $value;
2776 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2782 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2784 // If there's just one condition and no subordering, hand off to
2785 // selectSQLText directly.
2786 if ( count( $conds ) === 1 &&
2787 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2789 return $this->selectSQLText(
2790 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2794 // Otherwise, we need to pull out the order and limit to apply after
2795 // the union. Then build the SQL queries for each set of conditions in
2796 // $conds. Then union them together (using UNION ALL, because the
2797 // product *should* already be distinct).
2798 $orderBy = $this->makeOrderBy( $options );
2799 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2800 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2801 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2802 if ( !$this->unionSupportsOrderAndLimit() ) {
2803 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2805 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2806 $options['ORDER BY'] = $options['INNER ORDER BY'];
2808 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2809 // We need to increase the limit by the offset rather than
2810 // using the offset directly, otherwise it'll skip incorrectly
2811 // in the subqueries.
2812 $options['LIMIT'] = $limit +
$offset;
2813 unset( $options['OFFSET'] );
2818 foreach ( $conds as $cond ) {
2819 $sqls[] = $this->selectSQLText(
2820 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2823 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2824 if ( $limit !== null ) {
2825 $sql = $this->limitResult( $sql, $limit, $offset );
2831 public function conditional( $cond, $trueVal, $falseVal ) {
2832 if ( is_array( $cond ) ) {
2833 $cond = $this->makeList( $cond, self
::LIST_AND
);
2836 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2839 public function strreplace( $orig, $old, $new ) {
2840 return "REPLACE({$orig}, {$old}, {$new})";
2843 public function getServerUptime() {
2847 public function wasDeadlock() {
2851 public function wasLockTimeout() {
2855 public function wasErrorReissuable() {
2859 public function wasReadOnlyError() {
2864 * Do not use this method outside of Database/DBError classes
2866 * @param int|string $errno
2867 * @return bool Whether the given query error was a connection drop
2869 public function wasConnectionError( $errno ) {
2873 public function deadlockLoop() {
2874 $args = func_get_args();
2875 $function = array_shift( $args );
2876 $tries = self
::DEADLOCK_TRIES
;
2878 $this->begin( __METHOD__
);
2881 /** @var Exception $e */
2885 $retVal = call_user_func_array( $function, $args );
2887 } catch ( DBQueryError
$e ) {
2888 if ( $this->wasDeadlock() ) {
2889 // Retry after a randomized delay
2890 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2892 // Throw the error back up
2896 } while ( --$tries > 0 );
2898 if ( $tries <= 0 ) {
2899 // Too many deadlocks; give up
2900 $this->rollback( __METHOD__
);
2903 $this->commit( __METHOD__
);
2909 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2910 # Real waits are implemented in the subclass.
2914 public function getReplicaPos() {
2919 public function getMasterPos() {
2924 public function serverIsReadOnly() {
2928 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2929 if ( !$this->trxLevel
) {
2930 throw new DBUnexpectedError( $this, "No transaction is active." );
2932 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2935 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2936 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2937 if ( !$this->trxLevel
) {
2938 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2942 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2943 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2944 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2945 // an implicit commit of all peer databases. This is true even if a transaction has
2946 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2947 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2949 // No transaction is active nor will start implicitly, so make one for this callback
2950 $this->startAtomic( __METHOD__
);
2952 call_user_func( $callback );
2953 $this->endAtomic( __METHOD__
);
2954 } catch ( Exception
$e ) {
2955 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2961 final public function setTransactionListener( $name, callable
$callback = null ) {
2963 $this->trxRecurringCallbacks
[$name] = $callback;
2965 unset( $this->trxRecurringCallbacks
[$name] );
2970 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2972 * This method should not be used outside of Database/LoadBalancer
2974 * @param bool $suppress
2977 final public function setTrxEndCallbackSuppression( $suppress ) {
2978 $this->trxEndCallbacksSuppressed
= $suppress;
2982 * Actually run and consume any "on transaction idle/resolution" callbacks.
2984 * This method should not be used outside of Database/LoadBalancer
2986 * @param int $trigger IDatabase::TRIGGER_* constant
2990 public function runOnTransactionIdleCallbacks( $trigger ) {
2991 if ( $this->trxEndCallbacksSuppressed
) {
2995 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2996 /** @var Exception $e */
2997 $e = null; // first exception
2998 do { // callbacks may add callbacks :)
2999 $callbacks = array_merge(
3000 $this->trxIdleCallbacks
,
3001 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3003 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3004 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3005 foreach ( $callbacks as $callback ) {
3007 list( $phpCallback ) = $callback;
3008 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3009 call_user_func_array( $phpCallback, [ $trigger ] );
3011 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3013 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3015 } catch ( Exception
$ex ) {
3016 call_user_func( $this->errorLogger
, $ex );
3018 // Some callbacks may use startAtomic/endAtomic, so make sure
3019 // their transactions are ended so other callbacks don't fail
3020 if ( $this->trxLevel() ) {
3021 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3025 } while ( count( $this->trxIdleCallbacks
) );
3027 if ( $e instanceof Exception
) {
3028 throw $e; // re-throw any first exception
3033 * Actually run and consume any "on transaction pre-commit" callbacks.
3035 * This method should not be used outside of Database/LoadBalancer
3040 public function runOnTransactionPreCommitCallbacks() {
3041 $e = null; // first exception
3042 do { // callbacks may add callbacks :)
3043 $callbacks = $this->trxPreCommitCallbacks
;
3044 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3045 foreach ( $callbacks as $callback ) {
3047 list( $phpCallback ) = $callback;
3048 call_user_func( $phpCallback );
3049 } catch ( Exception
$ex ) {
3050 call_user_func( $this->errorLogger
, $ex );
3054 } while ( count( $this->trxPreCommitCallbacks
) );
3056 if ( $e instanceof Exception
) {
3057 throw $e; // re-throw any first exception
3062 * Actually run any "transaction listener" callbacks.
3064 * This method should not be used outside of Database/LoadBalancer
3066 * @param int $trigger IDatabase::TRIGGER_* constant
3070 public function runTransactionListenerCallbacks( $trigger ) {
3071 if ( $this->trxEndCallbacksSuppressed
) {
3075 /** @var Exception $e */
3076 $e = null; // first exception
3078 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3080 $phpCallback( $trigger, $this );
3081 } catch ( Exception
$ex ) {
3082 call_user_func( $this->errorLogger
, $ex );
3087 if ( $e instanceof Exception
) {
3088 throw $e; // re-throw any first exception
3092 final public function startAtomic( $fname = __METHOD__
) {
3093 if ( !$this->trxLevel
) {
3094 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3095 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3096 // in all changes being in one transaction to keep requests transactional.
3097 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3098 $this->trxAutomaticAtomic
= true;
3102 $this->trxAtomicLevels
[] = $fname;
3105 final public function endAtomic( $fname = __METHOD__
) {
3106 if ( !$this->trxLevel
) {
3107 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3109 if ( !$this->trxAtomicLevels ||
3110 array_pop( $this->trxAtomicLevels
) !== $fname
3112 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3115 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3116 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3120 final public function doAtomicSection( $fname, callable
$callback ) {
3121 $this->startAtomic( $fname );
3123 $res = call_user_func_array( $callback, [ $this, $fname ] );
3124 } catch ( Exception
$e ) {
3125 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3128 $this->endAtomic( $fname );
3133 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3134 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3135 if ( $this->trxLevel
) {
3136 if ( $this->trxAtomicLevels
) {
3137 $levels = implode( ', ', $this->trxAtomicLevels
);
3138 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3139 throw new DBUnexpectedError( $this, $msg );
3140 } elseif ( !$this->trxAutomatic
) {
3141 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3142 throw new DBUnexpectedError( $this, $msg );
3144 // @TODO: make this an exception at some point
3145 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3146 $this->queryLogger
->error( $msg );
3147 return; // join the main transaction set
3149 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3150 // @TODO: make this an exception at some point
3151 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3152 $this->queryLogger
->error( $msg );
3153 return; // let any writes be in the main transaction
3156 // Avoid fatals if close() was called
3157 $this->assertOpen();
3159 $this->doBegin( $fname );
3160 $this->trxTimestamp
= microtime( true );
3161 $this->trxFname
= $fname;
3162 $this->trxDoneWrites
= false;
3163 $this->trxAutomaticAtomic
= false;
3164 $this->trxAtomicLevels
= [];
3165 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3166 $this->trxWriteDuration
= 0.0;
3167 $this->trxWriteQueryCount
= 0;
3168 $this->trxWriteAffectedRows
= 0;
3169 $this->trxWriteAdjDuration
= 0.0;
3170 $this->trxWriteAdjQueryCount
= 0;
3171 $this->trxWriteCallers
= [];
3172 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3173 // Get an estimate of the replica DB lag before then, treating estimate staleness
3174 // as lag itself just to be safe
3175 $status = $this->getApproximateLagStatus();
3176 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3177 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3178 // caller will think its OK to muck around with the transaction just because startAtomic()
3179 // has not yet completed (e.g. setting trxAtomicLevels).
3180 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3184 * Issues the BEGIN command to the database server.
3186 * @see Database::begin()
3187 * @param string $fname
3189 protected function doBegin( $fname ) {
3190 $this->query( 'BEGIN', $fname );
3191 $this->trxLevel
= 1;
3194 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3195 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3196 // There are still atomic sections open. This cannot be ignored
3197 $levels = implode( ', ', $this->trxAtomicLevels
);
3198 throw new DBUnexpectedError(
3200 "$fname: Got COMMIT while atomic sections $levels are still open."
3204 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3205 if ( !$this->trxLevel
) {
3206 return; // nothing to do
3207 } elseif ( !$this->trxAutomatic
) {
3208 throw new DBUnexpectedError(
3210 "$fname: Flushing an explicit transaction, getting out of sync."
3214 if ( !$this->trxLevel
) {
3215 $this->queryLogger
->error(
3216 "$fname: No transaction to commit, something got out of sync." );
3217 return; // nothing to do
3218 } elseif ( $this->trxAutomatic
) {
3219 // @TODO: make this an exception at some point
3220 $msg = "$fname: Explicit commit of implicit transaction.";
3221 $this->queryLogger
->error( $msg );
3222 return; // wait for the main transaction set commit round
3226 // Avoid fatals if close() was called
3227 $this->assertOpen();
3229 $this->runOnTransactionPreCommitCallbacks();
3230 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3231 $this->doCommit( $fname );
3232 if ( $this->trxDoneWrites
) {
3233 $this->lastWriteTime
= microtime( true );
3234 $this->trxProfiler
->transactionWritingOut(
3239 $this->trxWriteAffectedRows
3243 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3244 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3248 * Issues the COMMIT command to the database server.
3250 * @see Database::commit()
3251 * @param string $fname
3253 protected function doCommit( $fname ) {
3254 if ( $this->trxLevel
) {
3255 $this->query( 'COMMIT', $fname );
3256 $this->trxLevel
= 0;
3260 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3261 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3262 if ( !$this->trxLevel
) {
3263 return; // nothing to do
3266 if ( !$this->trxLevel
) {
3267 $this->queryLogger
->error(
3268 "$fname: No transaction to rollback, something got out of sync." );
3269 return; // nothing to do
3270 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3271 throw new DBUnexpectedError(
3273 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3278 // Avoid fatals if close() was called
3279 $this->assertOpen();
3281 $this->doRollback( $fname );
3282 $this->trxAtomicLevels
= [];
3283 if ( $this->trxDoneWrites
) {
3284 $this->trxProfiler
->transactionWritingOut(
3291 $this->trxIdleCallbacks
= []; // clear
3292 $this->trxPreCommitCallbacks
= []; // clear
3294 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3295 } catch ( Exception
$e ) {
3296 // already logged; finish and let LoadBalancer move on during mass-rollback
3299 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3300 } catch ( Exception
$e ) {
3301 // already logged; let LoadBalancer move on during mass-rollback
3304 $this->affectedRowCount
= 0; // for the sake of consistency
3308 * Issues the ROLLBACK command to the database server.
3310 * @see Database::rollback()
3311 * @param string $fname
3313 protected function doRollback( $fname ) {
3314 if ( $this->trxLevel
) {
3315 # Disconnects cause rollback anyway, so ignore those errors
3316 $ignoreErrors = true;
3317 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3318 $this->trxLevel
= 0;
3322 public function flushSnapshot( $fname = __METHOD__
) {
3323 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3324 // This only flushes transactions to clear snapshots, not to write data
3325 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3326 throw new DBUnexpectedError(
3328 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3332 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3335 public function explicitTrxActive() {
3336 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3339 public function duplicateTableStructure(
3340 $oldName, $newName, $temporary = false, $fname = __METHOD__
3342 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3345 public function listTables( $prefix = null, $fname = __METHOD__
) {
3346 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3349 public function listViews( $prefix = null, $fname = __METHOD__
) {
3350 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3353 public function timestamp( $ts = 0 ) {
3354 $t = new ConvertibleTimestamp( $ts );
3355 // Let errors bubble up to avoid putting garbage in the DB
3356 return $t->getTimestamp( TS_MW
);
3359 public function timestampOrNull( $ts = null ) {
3360 if ( is_null( $ts ) ) {
3363 return $this->timestamp( $ts );
3367 public function affectedRows() {
3368 return ( $this->affectedRowCount
=== null )
3369 ?
$this->fetchAffectedRowCount() // default to driver value
3370 : $this->affectedRowCount
;
3374 * @return int Number of retrieved rows according to the driver
3376 abstract protected function fetchAffectedRowCount();
3379 * Take the result from a query, and wrap it in a ResultWrapper if
3380 * necessary. Boolean values are passed through as is, to indicate success
3381 * of write queries or failure.
3383 * Once upon a time, Database::query() returned a bare MySQL result
3384 * resource, and it was necessary to call this function to convert it to
3385 * a wrapper. Nowadays, raw database objects are never exposed to external
3386 * callers, so this is unnecessary in external code.
3388 * @param bool|ResultWrapper|resource|object $result
3389 * @return bool|ResultWrapper
3391 protected function resultObject( $result ) {
3394 } elseif ( $result instanceof ResultWrapper
) {
3396 } elseif ( $result === true ) {
3397 // Successful write query
3400 return new ResultWrapper( $this, $result );
3404 public function ping( &$rtt = null ) {
3405 // Avoid hitting the server if it was hit recently
3406 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3407 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3408 $rtt = $this->rttEstimate
;
3409 return true; // don't care about $rtt
3413 // This will reconnect if possible or return false if not
3414 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3415 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3416 $this->restoreFlags( self
::RESTORE_PRIOR
);
3419 $rtt = $this->rttEstimate
;
3426 * Close existing database connection and open a new connection
3428 * @return bool True if new connection is opened successfully, false if error
3430 protected function reconnect() {
3431 $this->closeConnection();
3432 $this->opened
= false;
3433 $this->conn
= false;
3435 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3436 $this->lastPing
= microtime( true );
3438 } catch ( DBConnectionError
$e ) {
3445 public function getSessionLagStatus() {
3446 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3450 * Get the replica DB lag when the current transaction started
3452 * This is useful when transactions might use snapshot isolation
3453 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3454 * is this lag plus transaction duration. If they don't, it is still
3455 * safe to be pessimistic. This returns null if there is no transaction.
3457 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3460 protected function getTransactionLagStatus() {
3461 return $this->trxLevel
3462 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3467 * Get a replica DB lag estimate for this server
3469 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3472 protected function getApproximateLagStatus() {
3474 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3475 'since' => microtime( true )
3480 * Merge the result of getSessionLagStatus() for several DBs
3481 * using the most pessimistic values to estimate the lag of
3482 * any data derived from them in combination
3484 * This is information is useful for caching modules
3486 * @see WANObjectCache::set()
3487 * @see WANObjectCache::getWithSetCallback()
3489 * @param IDatabase $db1
3490 * @param IDatabase $db2 [optional]
3491 * @return array Map of values:
3492 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3493 * - since: oldest UNIX timestamp of any of the DB lag estimates
3494 * - pending: whether any of the DBs have uncommitted changes
3498 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3499 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3500 foreach ( func_get_args() as $db ) {
3501 /** @var IDatabase $db */
3502 $status = $db->getSessionLagStatus();
3503 if ( $status['lag'] === false ) {
3504 $res['lag'] = false;
3505 } elseif ( $res['lag'] !== false ) {
3506 $res['lag'] = max( $res['lag'], $status['lag'] );
3508 $res['since'] = min( $res['since'], $status['since'] );
3509 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3515 public function getLag() {
3519 public function maxListLen() {
3523 public function encodeBlob( $b ) {
3527 public function decodeBlob( $b ) {
3528 if ( $b instanceof Blob
) {
3534 public function setSessionOptions( array $options ) {
3537 public function sourceFile(
3539 callable
$lineCallback = null,
3540 callable
$resultCallback = null,
3542 callable
$inputCallback = null
3544 Wikimedia\
suppressWarnings();
3545 $fp = fopen( $filename, 'r' );
3546 Wikimedia\restoreWarnings
();
3548 if ( false === $fp ) {
3549 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3553 $fname = __METHOD__
. "( $filename )";
3557 $error = $this->sourceStream(
3558 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3559 } catch ( Exception
$e ) {
3569 public function setSchemaVars( $vars ) {
3570 $this->schemaVars
= $vars;
3573 public function sourceStream(
3575 callable
$lineCallback = null,
3576 callable
$resultCallback = null,
3577 $fname = __METHOD__
,
3578 callable
$inputCallback = null
3580 $delimiterReset = new ScopedCallback(
3581 function ( $delimiter ) {
3582 $this->delimiter
= $delimiter;
3584 [ $this->delimiter
]
3588 while ( !feof( $fp ) ) {
3589 if ( $lineCallback ) {
3590 call_user_func( $lineCallback );
3593 $line = trim( fgets( $fp ) );
3595 if ( $line == '' ) {
3599 if ( '-' == $line[0] && '-' == $line[1] ) {
3607 $done = $this->streamStatementEnd( $cmd, $line );
3611 if ( $done ||
feof( $fp ) ) {
3612 $cmd = $this->replaceVars( $cmd );
3614 if ( $inputCallback ) {
3615 $callbackResult = call_user_func( $inputCallback, $cmd );
3617 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3618 $cmd = $callbackResult;
3623 $res = $this->query( $cmd, $fname );
3625 if ( $resultCallback ) {
3626 call_user_func( $resultCallback, $res, $this );
3629 if ( false === $res ) {
3630 $err = $this->lastError();
3632 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3639 ScopedCallback
::consume( $delimiterReset );
3644 * Called by sourceStream() to check if we've reached a statement end
3646 * @param string &$sql SQL assembled so far
3647 * @param string &$newLine New line about to be added to $sql
3648 * @return bool Whether $newLine contains end of the statement
3650 public function streamStatementEnd( &$sql, &$newLine ) {
3651 if ( $this->delimiter
) {
3653 $newLine = preg_replace(
3654 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3655 if ( $newLine != $prev ) {
3664 * Database independent variable replacement. Replaces a set of variables
3665 * in an SQL statement with their contents as given by $this->getSchemaVars().
3667 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3669 * - '{$var}' should be used for text and is passed through the database's
3671 * - `{$var}` should be used for identifiers (e.g. table and database names).
3672 * It is passed through the database's addIdentifierQuotes method which
3673 * can be overridden if the database uses something other than backticks.
3674 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3675 * database's tableName method.
3676 * - / *i* / passes the name that follows through the database's indexName method.
3677 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3678 * its use should be avoided. In 1.24 and older, string encoding was applied.
3680 * @param string $ins SQL statement to replace variables in
3681 * @return string The new SQL statement with variables replaced
3683 protected function replaceVars( $ins ) {
3684 $vars = $this->getSchemaVars();
3685 return preg_replace_callback(
3687 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3688 \'\{\$ (\w+) }\' | # 3. addQuotes
3689 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3690 /\*\$ (\w+) \*/ # 5. leave unencoded
3692 function ( $m ) use ( $vars ) {
3693 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3694 // check for both nonexistent keys *and* the empty string.
3695 if ( isset( $m[1] ) && $m[1] !== '' ) {
3696 if ( $m[1] === 'i' ) {
3697 return $this->indexName( $m[2] );
3699 return $this->tableName( $m[2] );
3701 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3702 return $this->addQuotes( $vars[$m[3]] );
3703 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3704 return $this->addIdentifierQuotes( $vars[$m[4]] );
3705 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3706 return $vars[$m[5]];
3716 * Get schema variables. If none have been set via setSchemaVars(), then
3717 * use some defaults from the current object.
3721 protected function getSchemaVars() {
3722 if ( $this->schemaVars
) {
3723 return $this->schemaVars
;
3725 return $this->getDefaultSchemaVars();
3730 * Get schema variables to use if none have been set via setSchemaVars().
3732 * Override this in derived classes to provide variables for tables.sql
3733 * and SQL patch files.
3737 protected function getDefaultSchemaVars() {
3741 public function lockIsFree( $lockName, $method ) {
3742 // RDBMs methods for checking named locks may or may not count this thread itself.
3743 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3744 // the behavior choosen by the interface for this method.
3745 return !isset( $this->namedLocksHeld
[$lockName] );
3748 public function lock( $lockName, $method, $timeout = 5 ) {
3749 $this->namedLocksHeld
[$lockName] = 1;
3754 public function unlock( $lockName, $method ) {
3755 unset( $this->namedLocksHeld
[$lockName] );
3760 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3761 if ( $this->writesOrCallbacksPending() ) {
3762 // This only flushes transactions to clear snapshots, not to write data
3763 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3764 throw new DBUnexpectedError(
3766 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3770 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3774 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3775 if ( $this->trxLevel() ) {
3776 // There is a good chance an exception was thrown, causing any early return
3777 // from the caller. Let any error handler get a chance to issue rollback().
3778 // If there isn't one, let the error bubble up and trigger server-side rollback.
3779 $this->onTransactionResolution(
3780 function () use ( $lockKey, $fname ) {
3781 $this->unlock( $lockKey, $fname );
3786 $this->unlock( $lockKey, $fname );
3790 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3795 public function namedLocksEnqueue() {
3799 public function tableLocksHaveTransactionScope() {
3803 final public function lockTables( array $read, array $write, $method ) {
3804 if ( $this->writesOrCallbacksPending() ) {
3805 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3808 if ( $this->tableLocksHaveTransactionScope() ) {
3809 $this->startAtomic( $method );
3812 return $this->doLockTables( $read, $write, $method );
3816 * Helper function for lockTables() that handles the actual table locking
3818 * @param array $read Array of tables to lock for read access
3819 * @param array $write Array of tables to lock for write access
3820 * @param string $method Name of caller
3823 protected function doLockTables( array $read, array $write, $method ) {
3827 final public function unlockTables( $method ) {
3828 if ( $this->tableLocksHaveTransactionScope() ) {
3829 $this->endAtomic( $method );
3831 return true; // locks released on COMMIT/ROLLBACK
3834 return $this->doUnlockTables( $method );
3838 * Helper function for unlockTables() that handles the actual table unlocking
3840 * @param string $method Name of caller
3843 protected function doUnlockTables( $method ) {
3849 * @param string $tableName
3850 * @param string $fName
3851 * @return bool|ResultWrapper
3854 public function dropTable( $tableName, $fName = __METHOD__
) {
3855 if ( !$this->tableExists( $tableName, $fName ) ) {
3858 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3860 return $this->query( $sql, $fName );
3863 public function getInfinity() {
3867 public function encodeExpiry( $expiry ) {
3868 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3869 ?
$this->getInfinity()
3870 : $this->timestamp( $expiry );
3873 public function decodeExpiry( $expiry, $format = TS_MW
) {
3874 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3878 return ConvertibleTimestamp
::convert( $format, $expiry );
3881 public function setBigSelects( $value = true ) {
3885 public function isReadOnly() {
3886 return ( $this->getReadOnlyReason() !== false );
3890 * @return string|bool Reason this DB is read-only or false if it is not
3892 protected function getReadOnlyReason() {
3893 $reason = $this->getLBInfo( 'readOnlyReason' );
3895 return is_string( $reason ) ?
$reason : false;
3898 public function setTableAliases( array $aliases ) {
3899 $this->tableAliases
= $aliases;
3902 public function setIndexAliases( array $aliases ) {
3903 $this->indexAliases
= $aliases;
3907 * @return bool Whether a DB user is required to access the DB
3910 protected function requiresDatabaseUser() {
3915 * Get the underlying binding connection handle
3917 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3918 * This catches broken callers than catch and ignore disconnection exceptions.
3919 * Unlike checking isOpen(), this is safe to call inside of open().
3921 * @return resource|object
3922 * @throws DBUnexpectedError
3925 protected function getBindingHandle() {
3926 if ( !$this->conn
) {
3927 throw new DBUnexpectedError(
3929 'DB connection was already closed or the connection dropped.'
3940 public function __toString() {
3941 return (string)$this->conn
;
3945 * Make sure that copies do not share the same client binding handle
3946 * @throws DBConnectionError
3948 public function __clone() {
3949 $this->connLogger
->warning(
3950 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3951 ( new RuntimeException() )->getTraceAsString()
3954 if ( $this->isOpen() ) {
3955 // Open a new connection resource without messing with the old one
3956 $this->opened
= false;
3957 $this->conn
= false;
3958 $this->trxEndCallbacks
= []; // don't copy
3959 $this->handleSessionLoss(); // no trx or locks anymore
3960 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3961 $this->lastPing
= microtime( true );
3966 * Called by serialize. Throw an exception when DB connection is serialized.
3967 * This causes problems on some database engines because the connection is
3968 * not restored on unserialize.
3970 public function __sleep() {
3971 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3972 'the connection is not restored on wakeup.' );
3976 * Run a few simple sanity checks and close dangling connections
3978 public function __destruct() {
3979 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3980 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3983 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3984 if ( $danglingWriters ) {
3985 $fnames = implode( ', ', $danglingWriters );
3986 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3989 if ( $this->conn
) {
3990 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3991 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3992 Wikimedia\
suppressWarnings();
3993 $this->closeConnection();
3994 Wikimedia\restoreWarnings
();
3995 $this->conn
= false;
3996 $this->opened
= false;
4001 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4002 class_alias( Database
::class, 'Database' ); // b/c global alias