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
;
37 use InvalidArgumentException
;
42 * Relational database abstraction object
47 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
48 /** Number of times to re-try an operation in case of deadlock */
49 const DEADLOCK_TRIES
= 4;
50 /** Minimum time to wait before retry, in microseconds */
51 const DEADLOCK_DELAY_MIN
= 500000;
52 /** Maximum time to wait before retry */
53 const DEADLOCK_DELAY_MAX
= 1500000;
55 /** How long before it is worth doing a dummy query to test the connection */
57 const PING_QUERY
= 'SELECT 1 AS ping';
59 const TINY_WRITE_SEC
= 0.010;
60 const SLOW_WRITE_SEC
= 0.500;
61 const SMALL_WRITE_ROWS
= 100;
63 /** @var string Whether lock granularity is on the level of the entire database */
64 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
66 /** @var int New Database instance will not be connected yet when returned */
67 const NEW_UNCONNECTED
= 0;
68 /** @var int New Database instance will already be connected when returned */
69 const NEW_CONNECTED
= 1;
71 /** @var string SQL query */
72 protected $lastQuery = '';
73 /** @var float|bool UNIX timestamp of last write query */
74 protected $lastWriteTime = false;
75 /** @var string|bool */
76 protected $phpError = false;
77 /** @var string Server that this instance is currently connected to */
79 /** @var string User that this instance is currently connected under the name of */
81 /** @var string Password used to establish the current connection */
83 /** @var string Database that this instance is currently connected to */
85 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
86 protected $tableAliases = [];
87 /** @var string[] Map of (index alias => index) */
88 protected $indexAliases = [];
89 /** @var bool Whether this PHP instance is for a CLI script */
91 /** @var string Agent name for query profiling */
93 /** @var array Parameters used by initConnection() to establish a connection */
94 protected $connectionParams = [];
95 /** @var BagOStuff APC cache */
97 /** @var LoggerInterface */
98 protected $connLogger;
99 /** @var LoggerInterface */
100 protected $queryLogger;
101 /** @var callback Error logging callback */
102 protected $errorLogger;
104 /** @var resource|null Database connection */
105 protected $conn = null;
107 protected $opened = false;
109 /** @var array[] List of (callable, method name) */
110 protected $trxIdleCallbacks = [];
111 /** @var array[] List of (callable, method name) */
112 protected $trxPreCommitCallbacks = [];
113 /** @var array[] List of (callable, method name) */
114 protected $trxEndCallbacks = [];
115 /** @var callable[] Map of (name => callable) */
116 protected $trxRecurringCallbacks = [];
117 /** @var bool Whether to suppress triggering of transaction end callbacks */
118 protected $trxEndCallbacksSuppressed = false;
121 protected $tablePrefix = '';
123 protected $schema = '';
127 protected $lbInfo = [];
128 /** @var array|bool */
129 protected $schemaVars = false;
131 protected $sessionVars = [];
132 /** @var array|null */
133 protected $preparedArgs;
134 /** @var string|bool|null Stashed value of html_errors INI setting */
135 protected $htmlErrors;
137 protected $delimiter = ';';
138 /** @var DatabaseDomain */
139 protected $currentDomain;
140 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
141 protected $affectedRowCount;
144 * Either 1 if a transaction is active or 0 otherwise.
145 * The other Trx fields may not be meaningfull if this is 0.
149 protected $trxLevel = 0;
151 * Either a short hexidecimal string if a transaction is active or ""
154 * @see Database::trxLevel
156 protected $trxShortId = '';
158 * The UNIX time that the transaction started. Callers can assume that if
159 * snapshot isolation is used, then the data is *at least* up to date to that
160 * point (possibly more up-to-date since the first SELECT defines the snapshot).
163 * @see Database::trxLevel
165 private $trxTimestamp = null;
166 /** @var float Lag estimate at the time of BEGIN */
167 private $trxReplicaLag = null;
169 * Remembers the function name given for starting the most recent transaction via begin().
170 * Used to provide additional context for error reporting.
173 * @see Database::trxLevel
175 private $trxFname = null;
177 * Record if possible write queries were done in the last transaction started
180 * @see Database::trxLevel
182 private $trxDoneWrites = false;
184 * Record if the current transaction was started implicitly due to DBO_TRX being set.
187 * @see Database::trxLevel
189 private $trxAutomatic = false;
191 * Array of levels of atomicity within transactions
195 private $trxAtomicLevels = [];
197 * Record if the current transaction was started implicitly by Database::startAtomic
201 private $trxAutomaticAtomic = false;
203 * Track the write query callers of the current transaction
207 private $trxWriteCallers = [];
209 * @var float Seconds spent in write queries for the current transaction
211 private $trxWriteDuration = 0.0;
213 * @var int Number of write queries for the current transaction
215 private $trxWriteQueryCount = 0;
217 * @var int Number of rows affected by write queries for the current transaction
219 private $trxWriteAffectedRows = 0;
221 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
223 private $trxWriteAdjDuration = 0.0;
225 * @var int Number of write queries counted in trxWriteAdjDuration
227 private $trxWriteAdjQueryCount = 0;
229 * @var float RTT time estimate
231 private $rttEstimate = 0.0;
233 /** @var array Map of (name => 1) for locks obtained via lock() */
234 private $namedLocksHeld = [];
235 /** @var array Map of (table name => 1) for TEMPORARY tables */
236 protected $sessionTempTables = [];
238 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
239 private $lazyMasterHandle;
241 /** @var float UNIX timestamp */
242 protected $lastPing = 0.0;
244 /** @var int[] Prior flags member variable values */
245 private $priorFlags = [];
247 /** @var object|string Class name or object With profileIn/profileOut methods */
249 /** @var TransactionProfiler */
250 protected $trxProfiler;
253 protected $nonNativeInsertSelectBatchSize = 10000;
256 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
257 * @param array $params Parameters passed from Database::factory()
259 protected function __construct( array $params ) {
260 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
261 $this->connectionParams
[$name] = $params[$name];
264 $this->schema
= $params['schema'];
265 $this->tablePrefix
= $params['tablePrefix'];
267 $this->cliMode
= $params['cliMode'];
268 // Agent name is added to SQL queries in a comment, so make sure it can't break out
269 $this->agent
= str_replace( '/', '-', $params['agent'] );
271 $this->flags
= $params['flags'];
272 if ( $this->flags
& self
::DBO_DEFAULT
) {
273 if ( $this->cliMode
) {
274 $this->flags
&= ~self
::DBO_TRX
;
276 $this->flags |
= self
::DBO_TRX
;
280 $this->sessionVars
= $params['variables'];
282 $this->srvCache
= isset( $params['srvCache'] )
283 ?
$params['srvCache']
284 : new HashBagOStuff();
286 $this->profiler
= $params['profiler'];
287 $this->trxProfiler
= $params['trxProfiler'];
288 $this->connLogger
= $params['connLogger'];
289 $this->queryLogger
= $params['queryLogger'];
290 $this->errorLogger
= $params['errorLogger'];
292 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
293 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
296 // Set initial dummy domain until open() sets the final DB/prefix
297 $this->currentDomain
= DatabaseDomain
::newUnspecified();
301 * Initialize the connection to the database over the wire (or to local files)
303 * @throws LogicException
304 * @throws InvalidArgumentException
305 * @throws DBConnectionError
308 final public function initConnection() {
309 if ( $this->isOpen() ) {
310 throw new LogicException( __METHOD__
. ': already connected.' );
312 // Establish the connection
313 $this->doInitConnection();
314 // Set the domain object after open() sets the relevant fields
315 if ( $this->dbName
!= '' ) {
316 // Domains with server scope but a table prefix are not used by IDatabase classes
317 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
322 * Actually connect to the database over the wire (or to local files)
324 * @throws InvalidArgumentException
325 * @throws DBConnectionError
328 protected function doInitConnection() {
329 if ( strlen( $this->connectionParams
['user'] ) ) {
331 $this->connectionParams
['host'],
332 $this->connectionParams
['user'],
333 $this->connectionParams
['password'],
334 $this->connectionParams
['dbname']
337 throw new InvalidArgumentException( "No database user provided." );
342 * Construct a Database subclass instance given a database type and parameters
344 * This also connects to the database immediately upon object construction
346 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
347 * @param array $p Parameter map with keys:
348 * - host : The hostname of the DB server
349 * - user : The name of the database user the client operates under
350 * - password : The password for the database user
351 * - dbname : The name of the database to use where queries do not specify one.
352 * The database must exist or an error might be thrown. Setting this to the empty string
353 * will avoid any such errors and make the handle have no implicit database scope. This is
354 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
355 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
356 * in which user names and such are defined, e.g. users are database-specific in Postgres.
357 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
358 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
359 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
360 * recognized in queries. This can be used in place of schemas for handle site farms.
361 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
362 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
363 * flag in place UNLESS this this database simply acts as a key/value store.
364 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
365 * 'mysqli' driver; the old one 'mysql' has been removed.
366 * - variables: Optional map of session variables to set after connecting. This can be
367 * used to adjust lock timeouts or encoding modes and the like.
368 * - connLogger: Optional PSR-3 logger interface instance.
369 * - queryLogger: Optional PSR-3 logger interface instance.
370 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
371 * These will be called in query(), using a simplified version of the SQL that also
372 * includes the agent as a SQL comment.
373 * - trxProfiler: Optional TransactionProfiler instance.
374 * - errorLogger: Optional callback that takes an Exception and logs it.
375 * - cliMode: Whether to consider the execution context that of a CLI script.
376 * - agent: Optional name used to identify the end-user in query profiling/logging.
377 * - srvCache: Optional BagOStuff instance to an APC-style cache.
378 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
379 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
380 * @return Database|null If the database driver or extension cannot be found
381 * @throws InvalidArgumentException If the database driver or extension cannot be found
384 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
385 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
387 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
388 // Resolve some defaults for b/c
389 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
390 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
391 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
392 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
393 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
394 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
395 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
396 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
397 $p['cliMode'] = isset( $p['cliMode'] )
399 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
400 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
401 if ( !isset( $p['connLogger'] ) ) {
402 $p['connLogger'] = new NullLogger();
404 if ( !isset( $p['queryLogger'] ) ) {
405 $p['queryLogger'] = new NullLogger();
407 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
408 if ( !isset( $p['trxProfiler'] ) ) {
409 $p['trxProfiler'] = new TransactionProfiler();
411 if ( !isset( $p['errorLogger'] ) ) {
412 $p['errorLogger'] = function ( Exception
$e ) {
413 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
417 /** @var Database $conn */
418 $conn = new $class( $p );
419 if ( $connect == self
::NEW_CONNECTED
) {
420 $conn->initConnection();
430 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
431 * @param string|null $driver Optional name of a specific DB client driver
432 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
433 * @throws InvalidArgumentException
436 final public static function attributesFromType( $dbType, $driver = null ) {
437 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
439 $class = self
::getClass( $dbType, $driver );
441 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
445 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
446 * @param string|null $driver Optional name of a specific DB client driver
447 * @return string Database subclass name to use
448 * @throws InvalidArgumentException
450 private static function getClass( $dbType, $driver = null ) {
451 // For database types with built-in support, the below maps type to IDatabase
452 // implementations. For types with multipe driver implementations (PHP extensions),
453 // an array can be used, keyed by extension name. In case of an array, the
454 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
455 // we auto-detect the first available driver. For types without built-in support,
456 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
457 static $builtinTypes = [
458 'mssql' => DatabaseMssql
::class,
459 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
460 'sqlite' => DatabaseSqlite
::class,
461 'postgres' => DatabasePostgres
::class,
464 $dbType = strtolower( $dbType );
467 if ( isset( $builtinTypes[$dbType] ) ) {
468 $possibleDrivers = $builtinTypes[$dbType];
469 if ( is_string( $possibleDrivers ) ) {
470 $class = $possibleDrivers;
472 if ( (string)$driver !== '' ) {
473 if ( !isset( $possibleDrivers[$driver] ) ) {
474 throw new InvalidArgumentException( __METHOD__
.
475 " type '$dbType' does not support driver '{$driver}'" );
477 $class = $possibleDrivers[$driver];
480 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
481 if ( extension_loaded( $posDriver ) ) {
482 $class = $possibleClass;
489 $class = 'Database' . ucfirst( $dbType );
492 if ( $class === false ) {
493 throw new InvalidArgumentException( __METHOD__
.
494 " no viable database extension found for type '$dbType'" );
501 * @return array Map of (Database::ATTRIBUTE_* constant => value
504 protected static function getAttributes() {
509 * Set the PSR-3 logger interface to use for query logging. (The logger
510 * interfaces for connection logging and error logging can be set with the
513 * @param LoggerInterface $logger
515 public function setLogger( LoggerInterface
$logger ) {
516 $this->queryLogger
= $logger;
519 public function getServerInfo() {
520 return $this->getServerVersion();
523 public function bufferResults( $buffer = null ) {
524 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
525 if ( $buffer !== null ) {
527 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
528 : $this->setFlag( self
::DBO_NOBUFFER
);
535 * Turns on (false) or off (true) the automatic generation and sending
536 * of a "we're sorry, but there has been a database error" page on
537 * database errors. Default is on (false). When turned off, the
538 * code should use lastErrno() and lastError() to handle the
539 * situation as appropriate.
541 * Do not use this function outside of the Database classes.
543 * @param null|bool $ignoreErrors
544 * @return bool The previous value of the flag.
546 protected function ignoreErrors( $ignoreErrors = null ) {
547 $res = $this->getFlag( self
::DBO_IGNORE
);
548 if ( $ignoreErrors !== null ) {
549 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
550 if ( $ignoreErrors ) {
551 $this->flags |
= self
::DBO_IGNORE
;
553 $this->flags
&= ~self
::DBO_IGNORE
;
560 public function trxLevel() {
561 return $this->trxLevel
;
564 public function trxTimestamp() {
565 return $this->trxLevel ?
$this->trxTimestamp
: null;
568 public function tablePrefix( $prefix = null ) {
569 $old = $this->tablePrefix
;
570 if ( $prefix !== null ) {
571 $this->tablePrefix
= $prefix;
572 $this->currentDomain
= ( $this->dbName
!= '' )
573 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
574 : DatabaseDomain
::newUnspecified();
580 public function dbSchema( $schema = null ) {
581 $old = $this->schema
;
582 if ( $schema !== null ) {
583 $this->schema
= $schema;
589 public function getLBInfo( $name = null ) {
590 if ( is_null( $name ) ) {
591 return $this->lbInfo
;
593 if ( array_key_exists( $name, $this->lbInfo
) ) {
594 return $this->lbInfo
[$name];
601 public function setLBInfo( $name, $value = null ) {
602 if ( is_null( $value ) ) {
603 $this->lbInfo
= $name;
605 $this->lbInfo
[$name] = $value;
609 public function setLazyMasterHandle( IDatabase
$conn ) {
610 $this->lazyMasterHandle
= $conn;
614 * @return IDatabase|null
615 * @see setLazyMasterHandle()
618 protected function getLazyMasterHandle() {
619 return $this->lazyMasterHandle
;
622 public function implicitGroupby() {
626 public function implicitOrderby() {
630 public function lastQuery() {
631 return $this->lastQuery
;
634 public function doneWrites() {
635 return (bool)$this->lastWriteTime
;
638 public function lastDoneWrites() {
639 return $this->lastWriteTime ?
: false;
642 public function writesPending() {
643 return $this->trxLevel
&& $this->trxDoneWrites
;
646 public function writesOrCallbacksPending() {
647 return $this->trxLevel
&& (
648 $this->trxDoneWrites ||
649 $this->trxIdleCallbacks ||
650 $this->trxPreCommitCallbacks ||
651 $this->trxEndCallbacks
655 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
656 if ( !$this->trxLevel
) {
658 } elseif ( !$this->trxDoneWrites
) {
663 case self
::ESTIMATE_DB_APPLY
:
665 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
666 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
667 // For omitted queries, make them count as something at least
668 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
669 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
672 default: // everything
673 return $this->trxWriteDuration
;
677 public function pendingWriteCallers() {
678 return $this->trxLevel ?
$this->trxWriteCallers
: [];
681 public function pendingWriteRowsAffected() {
682 return $this->trxWriteAffectedRows
;
686 * Get the list of method names that have pending write queries or callbacks
687 * for this transaction
691 protected function pendingWriteAndCallbackCallers() {
692 if ( !$this->trxLevel
) {
696 $fnames = $this->trxWriteCallers
;
698 $this->trxIdleCallbacks
,
699 $this->trxPreCommitCallbacks
,
700 $this->trxEndCallbacks
702 foreach ( $callbacks as $callback ) {
703 $fnames[] = $callback[1];
710 public function isOpen() {
711 return $this->opened
;
714 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
715 if ( ( $flag & self
::DBO_IGNORE
) ) {
716 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
719 if ( $remember === self
::REMEMBER_PRIOR
) {
720 array_push( $this->priorFlags
, $this->flags
);
722 $this->flags |
= $flag;
725 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
726 if ( ( $flag & self
::DBO_IGNORE
) ) {
727 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
730 if ( $remember === self
::REMEMBER_PRIOR
) {
731 array_push( $this->priorFlags
, $this->flags
);
733 $this->flags
&= ~
$flag;
736 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
737 if ( !$this->priorFlags
) {
741 if ( $state === self
::RESTORE_INITIAL
) {
742 $this->flags
= reset( $this->priorFlags
);
743 $this->priorFlags
= [];
745 $this->flags
= array_pop( $this->priorFlags
);
749 public function getFlag( $flag ) {
750 return !!( $this->flags
& $flag );
754 * @param string $name Class field name
756 * @deprecated Since 1.28
758 public function getProperty( $name ) {
762 public function getDomainID() {
763 return $this->currentDomain
->getId();
766 final public function getWikiID() {
767 return $this->getDomainID();
771 * Get information about an index into an object
772 * @param string $table Table name
773 * @param string $index Index name
774 * @param string $fname Calling function name
775 * @return mixed Database-specific index description class or false if the index does not exist
777 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
780 * Wrapper for addslashes()
782 * @param string $s String to be slashed.
783 * @return string Slashed string.
785 abstract function strencode( $s );
788 * Set a custom error handler for logging errors during database connection
790 protected function installErrorHandler() {
791 $this->phpError
= false;
792 $this->htmlErrors
= ini_set( 'html_errors', '0' );
793 set_error_handler( [ $this, 'connectionErrorLogger' ] );
797 * Restore the previous error handler and return the last PHP error for this DB
799 * @return bool|string
801 protected function restoreErrorHandler() {
802 restore_error_handler();
803 if ( $this->htmlErrors
!== false ) {
804 ini_set( 'html_errors', $this->htmlErrors
);
807 return $this->getLastPHPError();
811 * @return string|bool Last PHP error for this DB (typically connection errors)
813 protected function getLastPHPError() {
814 if ( $this->phpError
) {
815 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
816 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
825 * Error handler for logging errors during database connection
826 * This method should not be used outside of Database classes
829 * @param string $errstr
831 public function connectionErrorLogger( $errno, $errstr ) {
832 $this->phpError
= $errstr;
836 * Create a log context to pass to PSR-3 logger functions.
838 * @param array $extras Additional data to add to context
841 protected function getLogContext( array $extras = [] ) {
844 'db_server' => $this->server
,
845 'db_name' => $this->dbName
,
846 'db_user' => $this->user
,
852 public function close() {
854 // Resolve any dangling transaction first
855 if ( $this->trxLevel() ) {
856 // Meaningful transactions should ideally have been resolved by now
857 if ( $this->writesOrCallbacksPending() ) {
858 $this->queryLogger
->warning(
859 __METHOD__
. ": writes or callbacks still pending.",
860 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
863 // Check if it is possible to properly commit and trigger callbacks
864 if ( $this->trxEndCallbacksSuppressed
) {
865 throw new DBUnexpectedError(
867 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
870 // Commit the changes and run any callbacks as needed
871 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
873 // Close the actual connection in the binding handle
874 $closed = $this->closeConnection();
876 // Sanity check that no callbacks are dangling
878 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
880 throw new RuntimeException( "Transaction callbacks still pending." );
883 $closed = true; // already closed; nothing to do
886 $this->opened
= false;
892 * Make sure isOpen() returns true as a sanity check
894 * @throws DBUnexpectedError
896 protected function assertOpen() {
897 if ( !$this->isOpen() ) {
898 throw new DBUnexpectedError( $this, "DB connection was already closed." );
903 * Closes underlying database connection
905 * @return bool Whether connection was closed successfully
907 abstract protected function closeConnection();
909 public function reportConnectionError( $error = 'Unknown error' ) {
910 $myError = $this->lastError();
916 throw new DBConnectionError( $this, $error );
920 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
922 * This might return things, such as mysqli_result, that do not formally implement
923 * IResultWrapper, but nonetheless implement all of its methods correctly
925 * @param string $sql SQL query.
926 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
928 abstract protected function doQuery( $sql );
931 * Determine whether a query writes to the DB.
932 * Should return true if unsure.
937 protected function isWriteQuery( $sql ) {
939 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
944 * @return string|null
946 protected function getQueryVerb( $sql ) {
947 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
951 * Determine whether a SQL statement is sensitive to isolation level.
952 * A SQL statement is considered transactable if its result could vary
953 * depending on the transaction isolation level. Operational commands
954 * such as 'SET' and 'SHOW' are not considered to be transactable.
959 protected function isTransactableQuery( $sql ) {
961 $this->getQueryVerb( $sql ),
962 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
968 * @param string $sql A SQL query
969 * @return bool Whether $sql is SQL for TEMPORARY table operation
971 protected function registerTempTableOperation( $sql ) {
973 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
977 $this->sessionTempTables
[$matches[1]] = 1;
980 } elseif ( preg_match(
981 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
985 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
986 unset( $this->sessionTempTables
[$matches[1]] );
989 } elseif ( preg_match(
990 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
994 return isset( $this->sessionTempTables
[$matches[1]] );
995 } elseif ( preg_match(
996 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1000 return isset( $this->sessionTempTables
[$matches[1]] );
1006 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1007 $priorWritesPending = $this->writesOrCallbacksPending();
1008 $this->lastQuery
= $sql;
1010 $isWrite = $this->isWriteQuery( $sql );
1012 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1014 $isNonTempWrite = false;
1018 if ( $this->getLBInfo( 'replica' ) === true ) {
1021 'Write operations are not allowed on replica database connections.'
1024 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1025 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1026 $reason = $this->getReadOnlyReason();
1027 if ( $reason !== false ) {
1028 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1030 # Set a flag indicating that writes have been done
1031 $this->lastWriteTime
= microtime( true );
1034 # Add trace comment to the begin of the sql string, right after the operator.
1035 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1036 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1038 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1039 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1040 && $this->isTransactableQuery( $sql )
1042 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1043 $this->trxAutomatic
= true;
1046 # Keep track of whether the transaction has write queries pending
1047 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1048 $this->trxDoneWrites
= true;
1049 $this->trxProfiler
->transactionWritingIn(
1050 $this->server
, $this->dbName
, $this->trxShortId
);
1053 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1054 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1057 # Avoid fatals if close() was called
1058 $this->assertOpen();
1060 # Send the query to the server
1061 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1063 # Try reconnecting if the connection was lost
1064 if ( false === $ret && $this->wasConnectionLoss() ) {
1065 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1066 # Stash the last error values before anything might clear them
1067 $lastError = $this->lastError();
1068 $lastErrno = $this->lastErrno();
1069 # Update state tracking to reflect transaction loss due to disconnection
1070 $this->handleSessionLoss();
1071 if ( $this->reconnect() ) {
1072 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1073 $params = [ 'dbserver' => $this->getServer() ];
1074 $this->connLogger
->warning( $msg, $params );
1075 $this->queryLogger
->warning( $msg, $params +
1076 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1078 if ( $recoverable ) {
1079 # Should be safe to silently retry the query
1080 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1082 # Callers may catch the exception and continue to use the DB
1083 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1086 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1087 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1091 if ( false === $ret ) {
1092 # Deadlocks cause the entire transaction to abort, not just the statement.
1093 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1094 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1095 if ( $this->wasDeadlock() ) {
1096 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1097 $tempIgnore = false; // not recoverable
1099 # Update state tracking to reflect transaction loss
1100 $this->handleSessionLoss();
1103 $this->reportQueryError(
1104 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1107 $res = $this->resultObject( $ret );
1113 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1115 * @param string $sql Original SQL query
1116 * @param string $commentedSql SQL query with debugging/trace comment
1117 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1118 * @param string $fname Name of the calling function
1119 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1120 * object for a successful read query, or false on failure
1122 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1123 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1124 # generalizeSQL() will probably cut down the query to reasonable
1125 # logging size most of the time. The substr is really just a sanity check.
1127 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1129 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1132 # Include query transaction state
1133 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1135 $startTime = microtime( true );
1136 if ( $this->profiler
) {
1137 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1139 $this->affectedRowCount
= null;
1140 $ret = $this->doQuery( $commentedSql );
1141 $this->affectedRowCount
= $this->affectedRows();
1142 if ( $this->profiler
) {
1143 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1145 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1147 unset( $queryProfSection ); // profile out (if set)
1149 if ( $ret !== false ) {
1150 $this->lastPing
= $startTime;
1151 if ( $isWrite && $this->trxLevel
) {
1152 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1153 $this->trxWriteCallers
[] = $fname;
1157 if ( $sql === self
::PING_QUERY
) {
1158 $this->rttEstimate
= $queryRuntime;
1161 $this->trxProfiler
->recordQueryCompletion(
1162 $queryProf, $startTime, $isWrite, $this->affectedRows()
1164 $this->queryLogger
->debug( $sql, [
1166 'master' => $isMaster,
1167 'runtime' => $queryRuntime,
1174 * Update the estimated run-time of a query, not counting large row lock times
1176 * LoadBalancer can be set to rollback transactions that will create huge replication
1177 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1178 * queries, like inserting a row can take a long time due to row locking. This method
1179 * uses some simple heuristics to discount those cases.
1181 * @param string $sql A SQL write query
1182 * @param float $runtime Total runtime, including RTT
1183 * @param int $affected Affected row count
1185 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1186 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1187 $indicativeOfReplicaRuntime = true;
1188 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1189 $verb = $this->getQueryVerb( $sql );
1190 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1191 if ( $verb === 'INSERT' ) {
1192 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1193 } elseif ( $verb === 'REPLACE' ) {
1194 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1198 $this->trxWriteDuration +
= $runtime;
1199 $this->trxWriteQueryCount +
= 1;
1200 $this->trxWriteAffectedRows +
= $affected;
1201 if ( $indicativeOfReplicaRuntime ) {
1202 $this->trxWriteAdjDuration +
= $runtime;
1203 $this->trxWriteAdjQueryCount +
= 1;
1208 * Determine whether or not it is safe to retry queries after a database
1209 * connection is lost
1211 * @param string $sql SQL query
1212 * @param bool $priorWritesPending Whether there is a transaction open with
1213 * possible write queries or transaction pre-commit/idle callbacks
1214 * waiting on it to finish.
1215 * @return bool True if it is safe to retry the query, false otherwise
1217 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1218 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1219 # Dropped connections also mean that named locks are automatically released.
1220 # Only allow error suppression in autocommit mode or when the lost transaction
1221 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1222 if ( $this->namedLocksHeld
) {
1223 return false; // possible critical section violation
1224 } elseif ( $sql === 'COMMIT' ) {
1225 return !$priorWritesPending; // nothing written anyway? (T127428)
1226 } elseif ( $sql === 'ROLLBACK' ) {
1227 return true; // transaction lost...which is also what was requested :)
1228 } elseif ( $this->explicitTrxActive() ) {
1229 return false; // don't drop atomocity
1230 } elseif ( $priorWritesPending ) {
1231 return false; // prior writes lost from implicit transaction
1238 * Clean things up after transaction loss due to disconnection
1240 * @return null|Exception
1242 private function handleSessionLoss() {
1243 $this->trxLevel
= 0;
1244 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1245 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1246 $this->sessionTempTables
= [];
1247 $this->namedLocksHeld
= [];
1249 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1252 // Handle callbacks in trxEndCallbacks
1253 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1254 } catch ( Exception
$ex ) {
1255 // Already logged; move on...
1259 // Handle callbacks in trxRecurringCallbacks
1260 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1261 } catch ( Exception
$ex ) {
1262 // Already logged; move on...
1270 * Checks whether the cause of the error is detected to be a timeout.
1272 * It returns false by default, and not all engines support detecting this yet.
1273 * If this returns false, it will be treated as a generic query error.
1275 * @param string $error Error text
1276 * @param int $errno Error number
1279 protected function wasQueryTimeout( $error, $errno ) {
1283 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1284 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1285 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1287 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1288 $this->queryLogger
->error(
1289 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1290 $this->getLogContext( [
1291 'method' => __METHOD__
,
1294 'sql1line' => $sql1line,
1298 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1299 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1300 if ( $wasQueryTimeout ) {
1301 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1303 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1308 public function freeResult( $res ) {
1311 public function selectField(
1312 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1314 if ( $var === '*' ) { // sanity
1315 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1318 if ( !is_array( $options ) ) {
1319 $options = [ $options ];
1322 $options['LIMIT'] = 1;
1324 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1325 if ( $res === false ||
!$this->numRows( $res ) ) {
1329 $row = $this->fetchRow( $res );
1331 if ( $row !== false ) {
1332 return reset( $row );
1338 public function selectFieldValues(
1339 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1341 if ( $var === '*' ) { // sanity
1342 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1343 } elseif ( !is_string( $var ) ) { // sanity
1344 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1347 if ( !is_array( $options ) ) {
1348 $options = [ $options ];
1351 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1352 if ( $res === false ) {
1357 foreach ( $res as $row ) {
1358 $values[] = $row->$var;
1365 * Returns an optional USE INDEX clause to go after the table, and a
1366 * string to go at the end of the query.
1368 * @param array $options Associative array of options to be turned into
1369 * an SQL query, valid keys are listed in the function.
1371 * @see Database::select()
1373 protected function makeSelectOptions( $options ) {
1374 $preLimitTail = $postLimitTail = '';
1379 foreach ( $options as $key => $option ) {
1380 if ( is_numeric( $key ) ) {
1381 $noKeyOptions[$option] = true;
1385 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1387 $preLimitTail .= $this->makeOrderBy( $options );
1389 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1390 $postLimitTail .= ' FOR UPDATE';
1393 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1394 $postLimitTail .= ' LOCK IN SHARE MODE';
1397 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1398 $startOpts .= 'DISTINCT';
1401 # Various MySQL extensions
1402 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1403 $startOpts .= ' /*! STRAIGHT_JOIN */';
1406 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1407 $startOpts .= ' HIGH_PRIORITY';
1410 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1411 $startOpts .= ' SQL_BIG_RESULT';
1414 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1415 $startOpts .= ' SQL_BUFFER_RESULT';
1418 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1419 $startOpts .= ' SQL_SMALL_RESULT';
1422 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1423 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1426 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1427 $startOpts .= ' SQL_CACHE';
1430 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1431 $startOpts .= ' SQL_NO_CACHE';
1434 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1435 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1439 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1440 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1445 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1449 * Returns an optional GROUP BY with an optional HAVING
1451 * @param array $options Associative array of options
1453 * @see Database::select()
1456 protected function makeGroupByWithHaving( $options ) {
1458 if ( isset( $options['GROUP BY'] ) ) {
1459 $gb = is_array( $options['GROUP BY'] )
1460 ?
implode( ',', $options['GROUP BY'] )
1461 : $options['GROUP BY'];
1462 $sql .= ' GROUP BY ' . $gb;
1464 if ( isset( $options['HAVING'] ) ) {
1465 $having = is_array( $options['HAVING'] )
1466 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1467 : $options['HAVING'];
1468 $sql .= ' HAVING ' . $having;
1475 * Returns an optional ORDER BY
1477 * @param array $options Associative array of options
1479 * @see Database::select()
1482 protected function makeOrderBy( $options ) {
1483 if ( isset( $options['ORDER BY'] ) ) {
1484 $ob = is_array( $options['ORDER BY'] )
1485 ?
implode( ',', $options['ORDER BY'] )
1486 : $options['ORDER BY'];
1488 return ' ORDER BY ' . $ob;
1494 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1495 $options = [], $join_conds = [] ) {
1496 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1498 return $this->query( $sql, $fname );
1501 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1502 $options = [], $join_conds = []
1504 if ( is_array( $vars ) ) {
1505 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1508 $options = (array)$options;
1509 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1510 ?
$options['USE INDEX']
1513 isset( $options['IGNORE INDEX'] ) &&
1514 is_array( $options['IGNORE INDEX'] )
1516 ?
$options['IGNORE INDEX']
1519 if ( is_array( $table ) ) {
1521 $this->tableNamesWithIndexClauseOrJOIN(
1522 $table, $useIndexes, $ignoreIndexes, $join_conds );
1523 } elseif ( $table != '' ) {
1525 $this->tableNamesWithIndexClauseOrJOIN(
1526 [ $table ], $useIndexes, $ignoreIndexes, [] );
1531 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1532 $this->makeSelectOptions( $options );
1534 if ( is_array( $conds ) ) {
1535 $conds = $this->makeList( $conds, self
::LIST_AND
);
1538 if ( $conds === null ||
$conds === false ) {
1539 $this->queryLogger
->warning(
1543 . ' with incorrect parameters: $conds must be a string or an array'
1548 if ( $conds === '' ) {
1549 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1550 } elseif ( is_string( $conds ) ) {
1551 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1552 "WHERE $conds $preLimitTail";
1554 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1557 if ( isset( $options['LIMIT'] ) ) {
1558 $sql = $this->limitResult( $sql, $options['LIMIT'],
1559 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1561 $sql = "$sql $postLimitTail";
1563 if ( isset( $options['EXPLAIN'] ) ) {
1564 $sql = 'EXPLAIN ' . $sql;
1570 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1571 $options = [], $join_conds = []
1573 $options = (array)$options;
1574 $options['LIMIT'] = 1;
1575 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1577 if ( $res === false ) {
1581 if ( !$this->numRows( $res ) ) {
1585 $obj = $this->fetchObject( $res );
1590 public function estimateRowCount(
1591 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1593 $res = $this->select(
1594 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1596 $row = $res ?
$this->fetchRow( $res ) : [];
1598 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1601 public function selectRowCount(
1602 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1605 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1606 // The identifier quotes is primarily for MSSQL.
1607 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1608 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1609 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1612 $row = $this->fetchRow( $res );
1613 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1620 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1621 * It's only slightly flawed. Don't use for anything important.
1623 * @param string $sql A SQL Query
1627 protected static function generalizeSQL( $sql ) {
1628 # This does the same as the regexp below would do, but in such a way
1629 # as to avoid crashing php on some large strings.
1630 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1632 $sql = str_replace( "\\\\", '', $sql );
1633 $sql = str_replace( "\\'", '', $sql );
1634 $sql = str_replace( "\\\"", '', $sql );
1635 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1636 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1638 # All newlines, tabs, etc replaced by single space
1639 $sql = preg_replace( '/\s+/', ' ', $sql );
1642 # except the ones surrounded by characters, e.g. l10n
1643 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1644 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1649 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1650 $info = $this->fieldInfo( $table, $field );
1655 public function indexExists( $table, $index, $fname = __METHOD__
) {
1656 if ( !$this->tableExists( $table ) ) {
1660 $info = $this->indexInfo( $table, $index, $fname );
1661 if ( is_null( $info ) ) {
1664 return $info !== false;
1668 public function tableExists( $table, $fname = __METHOD__
) {
1669 $tableRaw = $this->tableName( $table, 'raw' );
1670 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1671 return true; // already known to exist
1674 $table = $this->tableName( $table );
1675 $ignoreErrors = true;
1676 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1681 public function indexUnique( $table, $index ) {
1682 $indexInfo = $this->indexInfo( $table, $index );
1684 if ( !$indexInfo ) {
1688 return !$indexInfo[0]->Non_unique
;
1692 * Helper for Database::insert().
1694 * @param array $options
1697 protected function makeInsertOptions( $options ) {
1698 return implode( ' ', $options );
1701 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1702 # No rows to insert, easy just return now
1703 if ( !count( $a ) ) {
1707 $table = $this->tableName( $table );
1709 if ( !is_array( $options ) ) {
1710 $options = [ $options ];
1714 if ( isset( $options['fileHandle'] ) ) {
1715 $fh = $options['fileHandle'];
1717 $options = $this->makeInsertOptions( $options );
1719 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1721 $keys = array_keys( $a[0] );
1724 $keys = array_keys( $a );
1727 $sql = 'INSERT ' . $options .
1728 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1732 foreach ( $a as $row ) {
1738 $sql .= '(' . $this->makeList( $row ) . ')';
1741 $sql .= '(' . $this->makeList( $a ) . ')';
1744 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1746 } elseif ( $fh !== null ) {
1750 return (bool)$this->query( $sql, $fname );
1754 * Make UPDATE options array for Database::makeUpdateOptions
1756 * @param array $options
1759 protected function makeUpdateOptionsArray( $options ) {
1760 if ( !is_array( $options ) ) {
1761 $options = [ $options ];
1766 if ( in_array( 'IGNORE', $options ) ) {
1774 * Make UPDATE options for the Database::update function
1776 * @param array $options The options passed to Database::update
1779 protected function makeUpdateOptions( $options ) {
1780 $opts = $this->makeUpdateOptionsArray( $options );
1782 return implode( ' ', $opts );
1785 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1786 $table = $this->tableName( $table );
1787 $opts = $this->makeUpdateOptions( $options );
1788 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1790 if ( $conds !== [] && $conds !== '*' ) {
1791 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1794 return (bool)$this->query( $sql, $fname );
1797 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1798 if ( !is_array( $a ) ) {
1799 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1805 foreach ( $a as $field => $value ) {
1807 if ( $mode == self
::LIST_AND
) {
1809 } elseif ( $mode == self
::LIST_OR
) {
1818 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1819 $list .= "($value)";
1820 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1823 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1825 // Remove null from array to be handled separately if found
1826 $includeNull = false;
1827 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1828 $includeNull = true;
1829 unset( $value[$nullKey] );
1831 if ( count( $value ) == 0 && !$includeNull ) {
1832 throw new InvalidArgumentException(
1833 __METHOD__
. ": empty input for field $field" );
1834 } elseif ( count( $value ) == 0 ) {
1835 // only check if $field is null
1836 $list .= "$field IS NULL";
1838 // IN clause contains at least one valid element
1839 if ( $includeNull ) {
1840 // Group subconditions to ensure correct precedence
1843 if ( count( $value ) == 1 ) {
1844 // Special-case single values, as IN isn't terribly efficient
1845 // Don't necessarily assume the single key is 0; we don't
1846 // enforce linear numeric ordering on other arrays here.
1847 $value = array_values( $value )[0];
1848 $list .= $field . " = " . $this->addQuotes( $value );
1850 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1852 // if null present in array, append IS NULL
1853 if ( $includeNull ) {
1854 $list .= " OR $field IS NULL)";
1857 } elseif ( $value === null ) {
1858 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1859 $list .= "$field IS ";
1860 } elseif ( $mode == self
::LIST_SET
) {
1861 $list .= "$field = ";
1866 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1868 $list .= "$field = ";
1870 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1877 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1880 foreach ( $data as $base => $sub ) {
1881 if ( count( $sub ) ) {
1882 $conds[] = $this->makeList(
1883 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1889 return $this->makeList( $conds, self
::LIST_OR
);
1891 // Nothing to search for...
1896 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1900 public function bitNot( $field ) {
1904 public function bitAnd( $fieldLeft, $fieldRight ) {
1905 return "($fieldLeft & $fieldRight)";
1908 public function bitOr( $fieldLeft, $fieldRight ) {
1909 return "($fieldLeft | $fieldRight)";
1912 public function buildConcat( $stringList ) {
1913 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1916 public function buildGroupConcatField(
1917 $delim, $table, $field, $conds = '', $join_conds = []
1919 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1921 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1924 public function buildSubstring( $input, $startPosition, $length = null ) {
1925 $this->assertBuildSubstringParams( $startPosition, $length );
1926 $functionBody = "$input FROM $startPosition";
1927 if ( $length !== null ) {
1928 $functionBody .= " FOR $length";
1930 return 'SUBSTRING(' . $functionBody . ')';
1934 * Check type and bounds for parameters to self::buildSubstring()
1936 * All supported databases have substring functions that behave the same for
1937 * positive $startPosition and non-negative $length, but behaviors differ when
1938 * given 0 or negative $startPosition or negative $length. The simplest
1939 * solution to that is to just forbid those values.
1941 * @param int $startPosition
1942 * @param int|null $length
1945 protected function assertBuildSubstringParams( $startPosition, $length ) {
1946 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
1947 throw new InvalidArgumentException(
1948 '$startPosition must be a positive integer'
1951 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
1952 throw new InvalidArgumentException(
1953 '$length must be null or an integer greater than or equal to 0'
1958 public function buildStringCast( $field ) {
1962 public function buildIntegerCast( $field ) {
1963 return 'CAST( ' . $field . ' AS INTEGER )';
1966 public function databasesAreIndependent() {
1970 public function selectDB( $db ) {
1971 # Stub. Shouldn't cause serious problems if it's not overridden, but
1972 # if your database engine supports a concept similar to MySQL's
1973 # databases you may as well.
1974 $this->dbName
= $db;
1979 public function getDBname() {
1980 return $this->dbName
;
1983 public function getServer() {
1984 return $this->server
;
1987 public function tableName( $name, $format = 'quoted' ) {
1988 # Skip the entire process when we have a string quoted on both ends.
1989 # Note that we check the end so that we will still quote any use of
1990 # use of `database`.table. But won't break things if someone wants
1991 # to query a database table with a dot in the name.
1992 if ( $this->isQuotedIdentifier( $name ) ) {
1996 # Lets test for any bits of text that should never show up in a table
1997 # name. Basically anything like JOIN or ON which are actually part of
1998 # SQL queries, but may end up inside of the table value to combine
1999 # sql. Such as how the API is doing.
2000 # Note that we use a whitespace test rather than a \b test to avoid
2001 # any remote case where a word like on may be inside of a table name
2002 # surrounded by symbols which may be considered word breaks.
2003 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2007 # Split database and table into proper variables.
2008 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2010 # Quote $table and apply the prefix if not quoted.
2011 # $tableName might be empty if this is called from Database::replaceVars()
2012 $tableName = "{$prefix}{$table}";
2013 if ( $format === 'quoted'
2014 && !$this->isQuotedIdentifier( $tableName )
2015 && $tableName !== ''
2017 $tableName = $this->addIdentifierQuotes( $tableName );
2020 # Quote $schema and $database and merge them with the table name if needed
2021 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2022 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2028 * Get the table components needed for a query given the currently selected database
2030 * @param string $name Table name in the form of db.schema.table, db.table, or table
2031 * @return array (DB name or "" for default, schema name, table prefix, table name)
2033 protected function qualifiedTableComponents( $name ) {
2034 # We reverse the explode so that database.table and table both output the correct table.
2035 $dbDetails = explode( '.', $name, 3 );
2036 if ( count( $dbDetails ) == 3 ) {
2037 list( $database, $schema, $table ) = $dbDetails;
2038 # We don't want any prefix added in this case
2040 } elseif ( count( $dbDetails ) == 2 ) {
2041 list( $database, $table ) = $dbDetails;
2042 # We don't want any prefix added in this case
2044 # In dbs that support it, $database may actually be the schema
2045 # but that doesn't affect any of the functionality here
2048 list( $table ) = $dbDetails;
2049 if ( isset( $this->tableAliases
[$table] ) ) {
2050 $database = $this->tableAliases
[$table]['dbname'];
2051 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2052 ?
$this->tableAliases
[$table]['schema']
2054 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2055 ?
$this->tableAliases
[$table]['prefix']
2056 : $this->tablePrefix
;
2059 $schema = $this->schema
; # Default schema
2060 $prefix = $this->tablePrefix
; # Default prefix
2064 return [ $database, $schema, $prefix, $table ];
2068 * @param string|null $namespace Database or schema
2069 * @param string $relation Name of table, view, sequence, etc...
2070 * @param string $format One of (raw, quoted)
2071 * @return string Relation name with quoted and merged $namespace as needed
2073 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2074 if ( strlen( $namespace ) ) {
2075 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2076 $namespace = $this->addIdentifierQuotes( $namespace );
2078 $relation = $namespace . '.' . $relation;
2084 public function tableNames() {
2085 $inArray = func_get_args();
2088 foreach ( $inArray as $name ) {
2089 $retVal[$name] = $this->tableName( $name );
2095 public function tableNamesN() {
2096 $inArray = func_get_args();
2099 foreach ( $inArray as $name ) {
2100 $retVal[] = $this->tableName( $name );
2107 * Get an aliased table name
2108 * e.g. tableName AS newTableName
2110 * @param string $name Table name, see tableName()
2111 * @param string|bool $alias Alias (optional)
2112 * @return string SQL name for aliased table. Will not alias a table to its own name
2114 protected function tableNameWithAlias( $name, $alias = false ) {
2115 if ( !$alias ||
$alias == $name ) {
2116 return $this->tableName( $name );
2118 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2123 * Gets an array of aliased table names
2125 * @param array $tables [ [alias] => table ]
2126 * @return string[] See tableNameWithAlias()
2128 protected function tableNamesWithAlias( $tables ) {
2130 foreach ( $tables as $alias => $table ) {
2131 if ( is_numeric( $alias ) ) {
2134 $retval[] = $this->tableNameWithAlias( $table, $alias );
2141 * Get an aliased field name
2142 * e.g. fieldName AS newFieldName
2144 * @param string $name Field name
2145 * @param string|bool $alias Alias (optional)
2146 * @return string SQL name for aliased field. Will not alias a field to its own name
2148 protected function fieldNameWithAlias( $name, $alias = false ) {
2149 if ( !$alias ||
(string)$alias === (string)$name ) {
2152 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2157 * Gets an array of aliased field names
2159 * @param array $fields [ [alias] => field ]
2160 * @return string[] See fieldNameWithAlias()
2162 protected function fieldNamesWithAlias( $fields ) {
2164 foreach ( $fields as $alias => $field ) {
2165 if ( is_numeric( $alias ) ) {
2168 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2175 * Get the aliased table name clause for a FROM clause
2176 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2178 * @param array $tables ( [alias] => table )
2179 * @param array $use_index Same as for select()
2180 * @param array $ignore_index Same as for select()
2181 * @param array $join_conds Same as for select()
2184 protected function tableNamesWithIndexClauseOrJOIN(
2185 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2189 $use_index = (array)$use_index;
2190 $ignore_index = (array)$ignore_index;
2191 $join_conds = (array)$join_conds;
2193 foreach ( $tables as $alias => $table ) {
2194 if ( !is_string( $alias ) ) {
2195 // No alias? Set it equal to the table name
2199 if ( is_array( $table ) ) {
2200 // A parenthesized group
2201 if ( count( $table ) > 1 ) {
2202 $joinedTable = '(' .
2203 $this->tableNamesWithIndexClauseOrJOIN(
2204 $table, $use_index, $ignore_index, $join_conds ) . ')';
2207 $innerTable = reset( $table );
2208 $innerAlias = key( $table );
2209 $joinedTable = $this->tableNameWithAlias(
2211 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2215 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2218 // Is there a JOIN clause for this table?
2219 if ( isset( $join_conds[$alias] ) ) {
2220 list( $joinType, $conds ) = $join_conds[$alias];
2221 $tableClause = $joinType;
2222 $tableClause .= ' ' . $joinedTable;
2223 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2224 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2226 $tableClause .= ' ' . $use;
2229 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2230 $ignore = $this->ignoreIndexClause(
2231 implode( ',', (array)$ignore_index[$alias] ) );
2232 if ( $ignore != '' ) {
2233 $tableClause .= ' ' . $ignore;
2236 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2238 $tableClause .= ' ON (' . $on . ')';
2241 $retJOIN[] = $tableClause;
2242 } elseif ( isset( $use_index[$alias] ) ) {
2243 // Is there an INDEX clause for this table?
2244 $tableClause = $joinedTable;
2245 $tableClause .= ' ' . $this->useIndexClause(
2246 implode( ',', (array)$use_index[$alias] )
2249 $ret[] = $tableClause;
2250 } elseif ( isset( $ignore_index[$alias] ) ) {
2251 // Is there an INDEX clause for this table?
2252 $tableClause = $joinedTable;
2253 $tableClause .= ' ' . $this->ignoreIndexClause(
2254 implode( ',', (array)$ignore_index[$alias] )
2257 $ret[] = $tableClause;
2259 $tableClause = $joinedTable;
2261 $ret[] = $tableClause;
2265 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2266 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2267 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2269 // Compile our final table clause
2270 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2274 * Allows for index remapping in queries where this is not consistent across DBMS
2276 * @param string $index
2279 protected function indexName( $index ) {
2280 return isset( $this->indexAliases
[$index] )
2281 ?
$this->indexAliases
[$index]
2285 public function addQuotes( $s ) {
2286 if ( $s instanceof Blob
) {
2289 if ( $s === null ) {
2291 } elseif ( is_bool( $s ) ) {
2294 # This will also quote numeric values. This should be harmless,
2295 # and protects against weird problems that occur when they really
2296 # _are_ strings such as article titles and string->number->string
2297 # conversion is not 1:1.
2298 return "'" . $this->strencode( $s ) . "'";
2303 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2304 * MySQL uses `backticks` while basically everything else uses double quotes.
2305 * Since MySQL is the odd one out here the double quotes are our generic
2306 * and we implement backticks in DatabaseMysqlBase.
2311 public function addIdentifierQuotes( $s ) {
2312 return '"' . str_replace( '"', '""', $s ) . '"';
2316 * Returns if the given identifier looks quoted or not according to
2317 * the database convention for quoting identifiers .
2319 * @note Do not use this to determine if untrusted input is safe.
2320 * A malicious user can trick this function.
2321 * @param string $name
2324 public function isQuotedIdentifier( $name ) {
2325 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2330 * @param string $escapeChar
2333 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2334 return str_replace( [ $escapeChar, '%', '_' ],
2335 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2339 public function buildLike() {
2340 $params = func_get_args();
2342 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2343 $params = $params[0];
2348 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2349 // may escape backslashes, creating problems of double escaping. The `
2350 // character has good cross-DBMS compatibility, avoiding special operators
2351 // in MS SQL like ^ and %
2354 foreach ( $params as $value ) {
2355 if ( $value instanceof LikeMatch
) {
2356 $s .= $value->toString();
2358 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2363 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2366 public function anyChar() {
2367 return new LikeMatch( '_' );
2370 public function anyString() {
2371 return new LikeMatch( '%' );
2374 public function nextSequenceValue( $seqName ) {
2379 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2380 * is only needed because a) MySQL must be as efficient as possible due to
2381 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2382 * which index to pick. Anyway, other databases might have different
2383 * indexes on a given table. So don't bother overriding this unless you're
2385 * @param string $index
2388 public function useIndexClause( $index ) {
2393 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2394 * is only needed because a) MySQL must be as efficient as possible due to
2395 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2396 * which index to pick. Anyway, other databases might have different
2397 * indexes on a given table. So don't bother overriding this unless you're
2399 * @param string $index
2402 public function ignoreIndexClause( $index ) {
2406 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2407 if ( count( $rows ) == 0 ) {
2412 if ( !is_array( reset( $rows ) ) ) {
2417 $this->startAtomic( $fname );
2418 $affectedRowCount = 0;
2419 foreach ( $rows as $row ) {
2420 // Delete rows which collide with this one
2421 $indexWhereClauses = [];
2422 foreach ( $uniqueIndexes as $index ) {
2423 $indexColumns = (array)$index;
2424 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2425 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2426 throw new DBUnexpectedError(
2428 'New record does not provide all values for unique key (' .
2429 implode( ', ', $indexColumns ) . ')'
2431 } elseif ( in_array( null, $indexRowValues, true ) ) {
2432 throw new DBUnexpectedError(
2434 'New record has a null value for unique key (' .
2435 implode( ', ', $indexColumns ) . ')'
2438 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2441 if ( $indexWhereClauses ) {
2442 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2443 $affectedRowCount +
= $this->affectedRows();
2446 // Now insert the row
2447 $this->insert( $table, $row, $fname );
2448 $affectedRowCount +
= $this->affectedRows();
2450 $this->endAtomic( $fname );
2451 $this->affectedRowCount
= $affectedRowCount;
2452 } catch ( Exception
$e ) {
2453 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2459 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2462 * @param string $table Table name
2463 * @param array|string $rows Row(s) to insert
2464 * @param string $fname Caller function name
2466 * @return ResultWrapper
2468 protected function nativeReplace( $table, $rows, $fname ) {
2469 $table = $this->tableName( $table );
2472 if ( !is_array( reset( $rows ) ) ) {
2476 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2479 foreach ( $rows as $row ) {
2486 $sql .= '(' . $this->makeList( $row ) . ')';
2489 return $this->query( $sql, $fname );
2492 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2495 if ( !count( $rows ) ) {
2496 return true; // nothing to do
2499 if ( !is_array( reset( $rows ) ) ) {
2503 if ( count( $uniqueIndexes ) ) {
2504 $clauses = []; // list WHERE clauses that each identify a single row
2505 foreach ( $rows as $row ) {
2506 foreach ( $uniqueIndexes as $index ) {
2507 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2508 $rowKey = []; // unique key to this row
2509 foreach ( $index as $column ) {
2510 $rowKey[$column] = $row[$column];
2512 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2515 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2520 $affectedRowCount = 0;
2522 $this->startAtomic( $fname );
2523 # Update any existing conflicting row(s)
2524 if ( $where !== false ) {
2525 $ok = $this->update( $table, $set, $where, $fname );
2526 $affectedRowCount +
= $this->affectedRows();
2530 # Now insert any non-conflicting row(s)
2531 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2532 $affectedRowCount +
= $this->affectedRows();
2533 $this->endAtomic( $fname );
2534 $this->affectedRowCount
= $affectedRowCount;
2535 } catch ( Exception
$e ) {
2536 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2543 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2547 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2550 $delTable = $this->tableName( $delTable );
2551 $joinTable = $this->tableName( $joinTable );
2552 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2553 if ( $conds != '*' ) {
2554 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2558 $this->query( $sql, $fname );
2561 public function textFieldSize( $table, $field ) {
2562 $table = $this->tableName( $table );
2563 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2564 $res = $this->query( $sql, __METHOD__
);
2565 $row = $this->fetchObject( $res );
2569 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2578 public function delete( $table, $conds, $fname = __METHOD__
) {
2580 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2583 $table = $this->tableName( $table );
2584 $sql = "DELETE FROM $table";
2586 if ( $conds != '*' ) {
2587 if ( is_array( $conds ) ) {
2588 $conds = $this->makeList( $conds, self
::LIST_AND
);
2590 $sql .= ' WHERE ' . $conds;
2593 return $this->query( $sql, $fname );
2596 final public function insertSelect(
2597 $destTable, $srcTable, $varMap, $conds,
2598 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2600 static $hints = [ 'NO_AUTO_COLUMNS' ];
2602 $insertOptions = (array)$insertOptions;
2603 $selectOptions = (array)$selectOptions;
2605 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2606 // For massive migrations with downtime, we don't want to select everything
2607 // into memory and OOM, so do all this native on the server side if possible.
2608 return $this->nativeInsertSelect(
2614 array_diff( $insertOptions, $hints ),
2620 return $this->nonNativeInsertSelect(
2626 array_diff( $insertOptions, $hints ),
2633 * @param array $insertOptions INSERT options
2634 * @param array $selectOptions SELECT options
2635 * @return bool Whether an INSERT SELECT with these options will be replication safe
2638 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2643 * Implementation of insertSelect() based on select() and insert()
2645 * @see IDatabase::insertSelect()
2647 * @param string $destTable
2648 * @param string|array $srcTable
2649 * @param array $varMap
2650 * @param array $conds
2651 * @param string $fname
2652 * @param array $insertOptions
2653 * @param array $selectOptions
2654 * @param array $selectJoinConds
2657 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2658 $fname = __METHOD__
,
2659 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2661 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2662 // on only the master (without needing row-based-replication). It also makes it easy to
2663 // know how big the INSERT is going to be.
2665 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2666 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2668 $selectOptions[] = 'FOR UPDATE';
2669 $res = $this->select(
2670 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2677 $affectedRowCount = 0;
2678 $this->startAtomic( $fname );
2681 foreach ( $res as $row ) {
2682 $rows[] = (array)$row;
2684 // Avoid inserts that are too huge
2685 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2686 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2690 $affectedRowCount +
= $this->affectedRows();
2694 if ( $rows && $ok ) {
2695 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2697 $affectedRowCount +
= $this->affectedRows();
2701 $this->endAtomic( $fname );
2702 $this->affectedRowCount
= $affectedRowCount;
2704 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2707 } catch ( Exception
$e ) {
2708 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2714 * Native server-side implementation of insertSelect() for situations where
2715 * we don't want to select everything into memory
2717 * @see IDatabase::insertSelect()
2718 * @param string $destTable
2719 * @param string|array $srcTable
2720 * @param array $varMap
2721 * @param array $conds
2722 * @param string $fname
2723 * @param array $insertOptions
2724 * @param array $selectOptions
2725 * @param array $selectJoinConds
2728 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2729 $fname = __METHOD__
,
2730 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2732 $destTable = $this->tableName( $destTable );
2734 if ( !is_array( $insertOptions ) ) {
2735 $insertOptions = [ $insertOptions ];
2738 $insertOptions = $this->makeInsertOptions( $insertOptions );
2740 $selectSql = $this->selectSQLText(
2742 array_values( $varMap ),
2749 $sql = "INSERT $insertOptions" .
2750 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2753 return $this->query( $sql, $fname );
2757 * Construct a LIMIT query with optional offset. This is used for query
2758 * pages. The SQL should be adjusted so that only the first $limit rows
2759 * are returned. If $offset is provided as well, then the first $offset
2760 * rows should be discarded, and the next $limit rows should be returned.
2761 * If the result of the query is not ordered, then the rows to be returned
2762 * are theoretically arbitrary.
2764 * $sql is expected to be a SELECT, if that makes a difference.
2766 * The version provided by default works in MySQL and SQLite. It will very
2767 * likely need to be overridden for most other DBMSes.
2769 * @param string $sql SQL query we will append the limit too
2770 * @param int $limit The SQL limit
2771 * @param int|bool $offset The SQL offset (default false)
2772 * @throws DBUnexpectedError
2775 public function limitResult( $sql, $limit, $offset = false ) {
2776 if ( !is_numeric( $limit ) ) {
2777 throw new DBUnexpectedError( $this,
2778 "Invalid non-numeric limit passed to limitResult()\n" );
2781 return "$sql LIMIT "
2782 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2786 public function unionSupportsOrderAndLimit() {
2787 return true; // True for almost every DB supported
2790 public function unionQueries( $sqls, $all ) {
2791 $glue = $all ?
') UNION ALL (' : ') UNION (';
2793 return '(' . implode( $glue, $sqls ) . ')';
2796 public function unionConditionPermutations(
2797 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2798 $options = [], $join_conds = []
2800 // First, build the Cartesian product of $permute_conds
2802 foreach ( $permute_conds as $field => $values ) {
2804 // Skip empty $values
2807 $values = array_unique( $values ); // For sanity
2809 foreach ( $conds as $cond ) {
2810 foreach ( $values as $value ) {
2811 $cond[$field] = $value;
2812 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2818 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2820 // If there's just one condition and no subordering, hand off to
2821 // selectSQLText directly.
2822 if ( count( $conds ) === 1 &&
2823 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2825 return $this->selectSQLText(
2826 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2830 // Otherwise, we need to pull out the order and limit to apply after
2831 // the union. Then build the SQL queries for each set of conditions in
2832 // $conds. Then union them together (using UNION ALL, because the
2833 // product *should* already be distinct).
2834 $orderBy = $this->makeOrderBy( $options );
2835 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2836 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2837 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2838 if ( !$this->unionSupportsOrderAndLimit() ) {
2839 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2841 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2842 $options['ORDER BY'] = $options['INNER ORDER BY'];
2844 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2845 // We need to increase the limit by the offset rather than
2846 // using the offset directly, otherwise it'll skip incorrectly
2847 // in the subqueries.
2848 $options['LIMIT'] = $limit +
$offset;
2849 unset( $options['OFFSET'] );
2854 foreach ( $conds as $cond ) {
2855 $sqls[] = $this->selectSQLText(
2856 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2859 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2860 if ( $limit !== null ) {
2861 $sql = $this->limitResult( $sql, $limit, $offset );
2867 public function conditional( $cond, $trueVal, $falseVal ) {
2868 if ( is_array( $cond ) ) {
2869 $cond = $this->makeList( $cond, self
::LIST_AND
);
2872 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2875 public function strreplace( $orig, $old, $new ) {
2876 return "REPLACE({$orig}, {$old}, {$new})";
2879 public function getServerUptime() {
2883 public function wasDeadlock() {
2887 public function wasLockTimeout() {
2891 public function wasConnectionLoss() {
2892 return $this->wasConnectionError( $this->lastErrno() );
2895 public function wasReadOnlyError() {
2899 public function wasErrorReissuable() {
2901 $this->wasDeadlock() ||
2902 $this->wasLockTimeout() ||
2903 $this->wasConnectionLoss()
2908 * Do not use this method outside of Database/DBError classes
2910 * @param int|string $errno
2911 * @return bool Whether the given query error was a connection drop
2913 public function wasConnectionError( $errno ) {
2917 public function deadlockLoop() {
2918 $args = func_get_args();
2919 $function = array_shift( $args );
2920 $tries = self
::DEADLOCK_TRIES
;
2922 $this->begin( __METHOD__
);
2925 /** @var Exception $e */
2929 $retVal = call_user_func_array( $function, $args );
2931 } catch ( DBQueryError
$e ) {
2932 if ( $this->wasDeadlock() ) {
2933 // Retry after a randomized delay
2934 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2936 // Throw the error back up
2940 } while ( --$tries > 0 );
2942 if ( $tries <= 0 ) {
2943 // Too many deadlocks; give up
2944 $this->rollback( __METHOD__
);
2947 $this->commit( __METHOD__
);
2953 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2954 # Real waits are implemented in the subclass.
2958 public function getReplicaPos() {
2963 public function getMasterPos() {
2968 public function serverIsReadOnly() {
2972 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2973 if ( !$this->trxLevel
) {
2974 throw new DBUnexpectedError( $this, "No transaction is active." );
2976 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2979 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2980 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2981 if ( !$this->trxLevel
) {
2982 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2986 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2987 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2988 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2989 // an implicit commit of all peer databases. This is true even if a transaction has
2990 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2991 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2993 // No transaction is active nor will start implicitly, so make one for this callback
2994 $this->startAtomic( __METHOD__
);
2996 call_user_func( $callback );
2997 $this->endAtomic( __METHOD__
);
2998 } catch ( Exception
$e ) {
2999 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3005 final public function setTransactionListener( $name, callable
$callback = null ) {
3007 $this->trxRecurringCallbacks
[$name] = $callback;
3009 unset( $this->trxRecurringCallbacks
[$name] );
3014 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3016 * This method should not be used outside of Database/LoadBalancer
3018 * @param bool $suppress
3021 final public function setTrxEndCallbackSuppression( $suppress ) {
3022 $this->trxEndCallbacksSuppressed
= $suppress;
3026 * Actually run and consume any "on transaction idle/resolution" callbacks.
3028 * This method should not be used outside of Database/LoadBalancer
3030 * @param int $trigger IDatabase::TRIGGER_* constant
3034 public function runOnTransactionIdleCallbacks( $trigger ) {
3035 if ( $this->trxEndCallbacksSuppressed
) {
3039 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3040 /** @var Exception $e */
3041 $e = null; // first exception
3042 do { // callbacks may add callbacks :)
3043 $callbacks = array_merge(
3044 $this->trxIdleCallbacks
,
3045 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3047 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3048 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3049 foreach ( $callbacks as $callback ) {
3051 list( $phpCallback ) = $callback;
3052 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3053 call_user_func_array( $phpCallback, [ $trigger ] );
3055 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3057 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3059 } catch ( Exception
$ex ) {
3060 call_user_func( $this->errorLogger
, $ex );
3062 // Some callbacks may use startAtomic/endAtomic, so make sure
3063 // their transactions are ended so other callbacks don't fail
3064 if ( $this->trxLevel() ) {
3065 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3069 } while ( count( $this->trxIdleCallbacks
) );
3071 if ( $e instanceof Exception
) {
3072 throw $e; // re-throw any first exception
3077 * Actually run and consume any "on transaction pre-commit" callbacks.
3079 * This method should not be used outside of Database/LoadBalancer
3084 public function runOnTransactionPreCommitCallbacks() {
3085 $e = null; // first exception
3086 do { // callbacks may add callbacks :)
3087 $callbacks = $this->trxPreCommitCallbacks
;
3088 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3089 foreach ( $callbacks as $callback ) {
3091 list( $phpCallback ) = $callback;
3092 call_user_func( $phpCallback );
3093 } catch ( Exception
$ex ) {
3094 call_user_func( $this->errorLogger
, $ex );
3098 } while ( count( $this->trxPreCommitCallbacks
) );
3100 if ( $e instanceof Exception
) {
3101 throw $e; // re-throw any first exception
3106 * Actually run any "transaction listener" callbacks.
3108 * This method should not be used outside of Database/LoadBalancer
3110 * @param int $trigger IDatabase::TRIGGER_* constant
3114 public function runTransactionListenerCallbacks( $trigger ) {
3115 if ( $this->trxEndCallbacksSuppressed
) {
3119 /** @var Exception $e */
3120 $e = null; // first exception
3122 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3124 $phpCallback( $trigger, $this );
3125 } catch ( Exception
$ex ) {
3126 call_user_func( $this->errorLogger
, $ex );
3131 if ( $e instanceof Exception
) {
3132 throw $e; // re-throw any first exception
3136 final public function startAtomic( $fname = __METHOD__
) {
3137 if ( !$this->trxLevel
) {
3138 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3139 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3140 // in all changes being in one transaction to keep requests transactional.
3141 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3142 $this->trxAutomaticAtomic
= true;
3146 $this->trxAtomicLevels
[] = $fname;
3149 final public function endAtomic( $fname = __METHOD__
) {
3150 if ( !$this->trxLevel
) {
3151 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3153 if ( !$this->trxAtomicLevels ||
3154 array_pop( $this->trxAtomicLevels
) !== $fname
3156 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3159 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3160 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3164 final public function doAtomicSection( $fname, callable
$callback ) {
3165 $this->startAtomic( $fname );
3167 $res = call_user_func_array( $callback, [ $this, $fname ] );
3168 } catch ( Exception
$e ) {
3169 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3172 $this->endAtomic( $fname );
3177 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3178 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3179 if ( $this->trxLevel
) {
3180 if ( $this->trxAtomicLevels
) {
3181 $levels = implode( ', ', $this->trxAtomicLevels
);
3182 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3183 throw new DBUnexpectedError( $this, $msg );
3184 } elseif ( !$this->trxAutomatic
) {
3185 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3186 throw new DBUnexpectedError( $this, $msg );
3188 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3189 throw new DBUnexpectedError( $this, $msg );
3191 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3192 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3193 throw new DBUnexpectedError( $this, $msg );
3196 // Avoid fatals if close() was called
3197 $this->assertOpen();
3199 $this->doBegin( $fname );
3200 $this->trxTimestamp
= microtime( true );
3201 $this->trxFname
= $fname;
3202 $this->trxDoneWrites
= false;
3203 $this->trxAutomaticAtomic
= false;
3204 $this->trxAtomicLevels
= [];
3205 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3206 $this->trxWriteDuration
= 0.0;
3207 $this->trxWriteQueryCount
= 0;
3208 $this->trxWriteAffectedRows
= 0;
3209 $this->trxWriteAdjDuration
= 0.0;
3210 $this->trxWriteAdjQueryCount
= 0;
3211 $this->trxWriteCallers
= [];
3212 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3213 // Get an estimate of the replica DB lag before then, treating estimate staleness
3214 // as lag itself just to be safe
3215 $status = $this->getApproximateLagStatus();
3216 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3217 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3218 // caller will think its OK to muck around with the transaction just because startAtomic()
3219 // has not yet completed (e.g. setting trxAtomicLevels).
3220 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3224 * Issues the BEGIN command to the database server.
3226 * @see Database::begin()
3227 * @param string $fname
3229 protected function doBegin( $fname ) {
3230 $this->query( 'BEGIN', $fname );
3231 $this->trxLevel
= 1;
3234 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3235 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3236 // There are still atomic sections open. This cannot be ignored
3237 $levels = implode( ', ', $this->trxAtomicLevels
);
3238 throw new DBUnexpectedError(
3240 "$fname: Got COMMIT while atomic sections $levels are still open."
3244 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3245 if ( !$this->trxLevel
) {
3246 return; // nothing to do
3247 } elseif ( !$this->trxAutomatic
) {
3248 throw new DBUnexpectedError(
3250 "$fname: Flushing an explicit transaction, getting out of sync."
3254 if ( !$this->trxLevel
) {
3255 $this->queryLogger
->error(
3256 "$fname: No transaction to commit, something got out of sync." );
3257 return; // nothing to do
3258 } elseif ( $this->trxAutomatic
) {
3259 throw new DBUnexpectedError(
3261 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3266 // Avoid fatals if close() was called
3267 $this->assertOpen();
3269 $this->runOnTransactionPreCommitCallbacks();
3270 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3271 $this->doCommit( $fname );
3272 if ( $this->trxDoneWrites
) {
3273 $this->lastWriteTime
= microtime( true );
3274 $this->trxProfiler
->transactionWritingOut(
3279 $this->trxWriteAffectedRows
3283 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3284 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3288 * Issues the COMMIT command to the database server.
3290 * @see Database::commit()
3291 * @param string $fname
3293 protected function doCommit( $fname ) {
3294 if ( $this->trxLevel
) {
3295 $this->query( 'COMMIT', $fname );
3296 $this->trxLevel
= 0;
3300 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3301 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3302 if ( !$this->trxLevel
) {
3303 return; // nothing to do
3306 if ( !$this->trxLevel
) {
3307 $this->queryLogger
->error(
3308 "$fname: No transaction to rollback, something got out of sync." );
3309 return; // nothing to do
3310 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3311 throw new DBUnexpectedError(
3313 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3318 // Avoid fatals if close() was called
3319 $this->assertOpen();
3321 $this->doRollback( $fname );
3322 $this->trxAtomicLevels
= [];
3323 if ( $this->trxDoneWrites
) {
3324 $this->trxProfiler
->transactionWritingOut(
3331 $this->trxIdleCallbacks
= []; // clear
3332 $this->trxPreCommitCallbacks
= []; // clear
3334 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3335 } catch ( Exception
$e ) {
3336 // already logged; finish and let LoadBalancer move on during mass-rollback
3339 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3340 } catch ( Exception
$e ) {
3341 // already logged; let LoadBalancer move on during mass-rollback
3344 $this->affectedRowCount
= 0; // for the sake of consistency
3348 * Issues the ROLLBACK command to the database server.
3350 * @see Database::rollback()
3351 * @param string $fname
3353 protected function doRollback( $fname ) {
3354 if ( $this->trxLevel
) {
3355 # Disconnects cause rollback anyway, so ignore those errors
3356 $ignoreErrors = true;
3357 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3358 $this->trxLevel
= 0;
3362 public function flushSnapshot( $fname = __METHOD__
) {
3363 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3364 // This only flushes transactions to clear snapshots, not to write data
3365 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3366 throw new DBUnexpectedError(
3368 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3372 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3375 public function explicitTrxActive() {
3376 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3379 public function duplicateTableStructure(
3380 $oldName, $newName, $temporary = false, $fname = __METHOD__
3382 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3385 public function listTables( $prefix = null, $fname = __METHOD__
) {
3386 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3389 public function listViews( $prefix = null, $fname = __METHOD__
) {
3390 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3393 public function timestamp( $ts = 0 ) {
3394 $t = new ConvertibleTimestamp( $ts );
3395 // Let errors bubble up to avoid putting garbage in the DB
3396 return $t->getTimestamp( TS_MW
);
3399 public function timestampOrNull( $ts = null ) {
3400 if ( is_null( $ts ) ) {
3403 return $this->timestamp( $ts );
3407 public function affectedRows() {
3408 return ( $this->affectedRowCount
=== null )
3409 ?
$this->fetchAffectedRowCount() // default to driver value
3410 : $this->affectedRowCount
;
3414 * @return int Number of retrieved rows according to the driver
3416 abstract protected function fetchAffectedRowCount();
3419 * Take the result from a query, and wrap it in a ResultWrapper if
3420 * necessary. Boolean values are passed through as is, to indicate success
3421 * of write queries or failure.
3423 * Once upon a time, Database::query() returned a bare MySQL result
3424 * resource, and it was necessary to call this function to convert it to
3425 * a wrapper. Nowadays, raw database objects are never exposed to external
3426 * callers, so this is unnecessary in external code.
3428 * @param bool|ResultWrapper|resource|object $result
3429 * @return bool|ResultWrapper
3431 protected function resultObject( $result ) {
3434 } elseif ( $result instanceof ResultWrapper
) {
3436 } elseif ( $result === true ) {
3437 // Successful write query
3440 return new ResultWrapper( $this, $result );
3444 public function ping( &$rtt = null ) {
3445 // Avoid hitting the server if it was hit recently
3446 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3447 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3448 $rtt = $this->rttEstimate
;
3449 return true; // don't care about $rtt
3453 // This will reconnect if possible or return false if not
3454 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3455 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3456 $this->restoreFlags( self
::RESTORE_PRIOR
);
3459 $rtt = $this->rttEstimate
;
3466 * Close existing database connection and open a new connection
3468 * @return bool True if new connection is opened successfully, false if error
3470 protected function reconnect() {
3471 $this->closeConnection();
3472 $this->opened
= false;
3473 $this->conn
= false;
3475 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3476 $this->lastPing
= microtime( true );
3478 } catch ( DBConnectionError
$e ) {
3485 public function getSessionLagStatus() {
3486 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3490 * Get the replica DB lag when the current transaction started
3492 * This is useful when transactions might use snapshot isolation
3493 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3494 * is this lag plus transaction duration. If they don't, it is still
3495 * safe to be pessimistic. This returns null if there is no transaction.
3497 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3500 protected function getTransactionLagStatus() {
3501 return $this->trxLevel
3502 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3507 * Get a replica DB lag estimate for this server
3509 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3512 protected function getApproximateLagStatus() {
3514 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3515 'since' => microtime( true )
3520 * Merge the result of getSessionLagStatus() for several DBs
3521 * using the most pessimistic values to estimate the lag of
3522 * any data derived from them in combination
3524 * This is information is useful for caching modules
3526 * @see WANObjectCache::set()
3527 * @see WANObjectCache::getWithSetCallback()
3529 * @param IDatabase $db1
3530 * @param IDatabase $db2 [optional]
3531 * @return array Map of values:
3532 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3533 * - since: oldest UNIX timestamp of any of the DB lag estimates
3534 * - pending: whether any of the DBs have uncommitted changes
3538 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3539 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3540 foreach ( func_get_args() as $db ) {
3541 /** @var IDatabase $db */
3542 $status = $db->getSessionLagStatus();
3543 if ( $status['lag'] === false ) {
3544 $res['lag'] = false;
3545 } elseif ( $res['lag'] !== false ) {
3546 $res['lag'] = max( $res['lag'], $status['lag'] );
3548 $res['since'] = min( $res['since'], $status['since'] );
3549 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3555 public function getLag() {
3559 public function maxListLen() {
3563 public function encodeBlob( $b ) {
3567 public function decodeBlob( $b ) {
3568 if ( $b instanceof Blob
) {
3574 public function setSessionOptions( array $options ) {
3577 public function sourceFile(
3579 callable
$lineCallback = null,
3580 callable
$resultCallback = null,
3582 callable
$inputCallback = null
3584 Wikimedia\
suppressWarnings();
3585 $fp = fopen( $filename, 'r' );
3586 Wikimedia\restoreWarnings
();
3588 if ( false === $fp ) {
3589 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3593 $fname = __METHOD__
. "( $filename )";
3597 $error = $this->sourceStream(
3598 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3599 } catch ( Exception
$e ) {
3609 public function setSchemaVars( $vars ) {
3610 $this->schemaVars
= $vars;
3613 public function sourceStream(
3615 callable
$lineCallback = null,
3616 callable
$resultCallback = null,
3617 $fname = __METHOD__
,
3618 callable
$inputCallback = null
3620 $delimiterReset = new ScopedCallback(
3621 function ( $delimiter ) {
3622 $this->delimiter
= $delimiter;
3624 [ $this->delimiter
]
3628 while ( !feof( $fp ) ) {
3629 if ( $lineCallback ) {
3630 call_user_func( $lineCallback );
3633 $line = trim( fgets( $fp ) );
3635 if ( $line == '' ) {
3639 if ( '-' == $line[0] && '-' == $line[1] ) {
3647 $done = $this->streamStatementEnd( $cmd, $line );
3651 if ( $done ||
feof( $fp ) ) {
3652 $cmd = $this->replaceVars( $cmd );
3654 if ( $inputCallback ) {
3655 $callbackResult = call_user_func( $inputCallback, $cmd );
3657 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3658 $cmd = $callbackResult;
3663 $res = $this->query( $cmd, $fname );
3665 if ( $resultCallback ) {
3666 call_user_func( $resultCallback, $res, $this );
3669 if ( false === $res ) {
3670 $err = $this->lastError();
3672 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3679 ScopedCallback
::consume( $delimiterReset );
3684 * Called by sourceStream() to check if we've reached a statement end
3686 * @param string &$sql SQL assembled so far
3687 * @param string &$newLine New line about to be added to $sql
3688 * @return bool Whether $newLine contains end of the statement
3690 public function streamStatementEnd( &$sql, &$newLine ) {
3691 if ( $this->delimiter
) {
3693 $newLine = preg_replace(
3694 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3695 if ( $newLine != $prev ) {
3704 * Database independent variable replacement. Replaces a set of variables
3705 * in an SQL statement with their contents as given by $this->getSchemaVars().
3707 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3709 * - '{$var}' should be used for text and is passed through the database's
3711 * - `{$var}` should be used for identifiers (e.g. table and database names).
3712 * It is passed through the database's addIdentifierQuotes method which
3713 * can be overridden if the database uses something other than backticks.
3714 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3715 * database's tableName method.
3716 * - / *i* / passes the name that follows through the database's indexName method.
3717 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3718 * its use should be avoided. In 1.24 and older, string encoding was applied.
3720 * @param string $ins SQL statement to replace variables in
3721 * @return string The new SQL statement with variables replaced
3723 protected function replaceVars( $ins ) {
3724 $vars = $this->getSchemaVars();
3725 return preg_replace_callback(
3727 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3728 \'\{\$ (\w+) }\' | # 3. addQuotes
3729 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3730 /\*\$ (\w+) \*/ # 5. leave unencoded
3732 function ( $m ) use ( $vars ) {
3733 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3734 // check for both nonexistent keys *and* the empty string.
3735 if ( isset( $m[1] ) && $m[1] !== '' ) {
3736 if ( $m[1] === 'i' ) {
3737 return $this->indexName( $m[2] );
3739 return $this->tableName( $m[2] );
3741 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3742 return $this->addQuotes( $vars[$m[3]] );
3743 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3744 return $this->addIdentifierQuotes( $vars[$m[4]] );
3745 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3746 return $vars[$m[5]];
3756 * Get schema variables. If none have been set via setSchemaVars(), then
3757 * use some defaults from the current object.
3761 protected function getSchemaVars() {
3762 if ( $this->schemaVars
) {
3763 return $this->schemaVars
;
3765 return $this->getDefaultSchemaVars();
3770 * Get schema variables to use if none have been set via setSchemaVars().
3772 * Override this in derived classes to provide variables for tables.sql
3773 * and SQL patch files.
3777 protected function getDefaultSchemaVars() {
3781 public function lockIsFree( $lockName, $method ) {
3782 // RDBMs methods for checking named locks may or may not count this thread itself.
3783 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3784 // the behavior choosen by the interface for this method.
3785 return !isset( $this->namedLocksHeld
[$lockName] );
3788 public function lock( $lockName, $method, $timeout = 5 ) {
3789 $this->namedLocksHeld
[$lockName] = 1;
3794 public function unlock( $lockName, $method ) {
3795 unset( $this->namedLocksHeld
[$lockName] );
3800 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3801 if ( $this->writesOrCallbacksPending() ) {
3802 // This only flushes transactions to clear snapshots, not to write data
3803 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3804 throw new DBUnexpectedError(
3806 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3810 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3814 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3815 if ( $this->trxLevel() ) {
3816 // There is a good chance an exception was thrown, causing any early return
3817 // from the caller. Let any error handler get a chance to issue rollback().
3818 // If there isn't one, let the error bubble up and trigger server-side rollback.
3819 $this->onTransactionResolution(
3820 function () use ( $lockKey, $fname ) {
3821 $this->unlock( $lockKey, $fname );
3826 $this->unlock( $lockKey, $fname );
3830 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3835 public function namedLocksEnqueue() {
3839 public function tableLocksHaveTransactionScope() {
3843 final public function lockTables( array $read, array $write, $method ) {
3844 if ( $this->writesOrCallbacksPending() ) {
3845 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3848 if ( $this->tableLocksHaveTransactionScope() ) {
3849 $this->startAtomic( $method );
3852 return $this->doLockTables( $read, $write, $method );
3856 * Helper function for lockTables() that handles the actual table locking
3858 * @param array $read Array of tables to lock for read access
3859 * @param array $write Array of tables to lock for write access
3860 * @param string $method Name of caller
3863 protected function doLockTables( array $read, array $write, $method ) {
3867 final public function unlockTables( $method ) {
3868 if ( $this->tableLocksHaveTransactionScope() ) {
3869 $this->endAtomic( $method );
3871 return true; // locks released on COMMIT/ROLLBACK
3874 return $this->doUnlockTables( $method );
3878 * Helper function for unlockTables() that handles the actual table unlocking
3880 * @param string $method Name of caller
3883 protected function doUnlockTables( $method ) {
3889 * @param string $tableName
3890 * @param string $fName
3891 * @return bool|ResultWrapper
3894 public function dropTable( $tableName, $fName = __METHOD__
) {
3895 if ( !$this->tableExists( $tableName, $fName ) ) {
3898 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3900 return $this->query( $sql, $fName );
3903 public function getInfinity() {
3907 public function encodeExpiry( $expiry ) {
3908 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3909 ?
$this->getInfinity()
3910 : $this->timestamp( $expiry );
3913 public function decodeExpiry( $expiry, $format = TS_MW
) {
3914 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3918 return ConvertibleTimestamp
::convert( $format, $expiry );
3921 public function setBigSelects( $value = true ) {
3925 public function isReadOnly() {
3926 return ( $this->getReadOnlyReason() !== false );
3930 * @return string|bool Reason this DB is read-only or false if it is not
3932 protected function getReadOnlyReason() {
3933 $reason = $this->getLBInfo( 'readOnlyReason' );
3935 return is_string( $reason ) ?
$reason : false;
3938 public function setTableAliases( array $aliases ) {
3939 $this->tableAliases
= $aliases;
3942 public function setIndexAliases( array $aliases ) {
3943 $this->indexAliases
= $aliases;
3947 * Get the underlying binding connection handle
3949 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3950 * This catches broken callers than catch and ignore disconnection exceptions.
3951 * Unlike checking isOpen(), this is safe to call inside of open().
3954 * @throws DBUnexpectedError
3957 protected function getBindingHandle() {
3958 if ( !$this->conn
) {
3959 throw new DBUnexpectedError(
3961 'DB connection was already closed or the connection dropped.'
3972 public function __toString() {
3973 return (string)$this->conn
;
3977 * Make sure that copies do not share the same client binding handle
3978 * @throws DBConnectionError
3980 public function __clone() {
3981 $this->connLogger
->warning(
3982 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3983 ( new RuntimeException() )->getTraceAsString()
3986 if ( $this->isOpen() ) {
3987 // Open a new connection resource without messing with the old one
3988 $this->opened
= false;
3989 $this->conn
= false;
3990 $this->trxEndCallbacks
= []; // don't copy
3991 $this->handleSessionLoss(); // no trx or locks anymore
3992 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3993 $this->lastPing
= microtime( true );
3998 * Called by serialize. Throw an exception when DB connection is serialized.
3999 * This causes problems on some database engines because the connection is
4000 * not restored on unserialize.
4002 public function __sleep() {
4003 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4004 'the connection is not restored on wakeup.' );
4008 * Run a few simple sanity checks and close dangling connections
4010 public function __destruct() {
4011 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4012 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4015 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4016 if ( $danglingWriters ) {
4017 $fnames = implode( ', ', $danglingWriters );
4018 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4021 if ( $this->conn
) {
4022 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4023 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4024 Wikimedia\
suppressWarnings();
4025 $this->closeConnection();
4026 Wikimedia\restoreWarnings
();
4027 $this->conn
= false;
4028 $this->opened
= false;
4033 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4034 class_alias( Database
::class, 'Database' ); // b/c global alias