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[] $aliases Map of (table => (dbname, schema, prefix) map) */
86 protected $tableAliases = [];
87 /** @var bool Whether this PHP instance is for a CLI script */
89 /** @var string Agent name for query profiling */
91 /** @var array Parameters used by initConnection() to establish a connection */
92 protected $connectionParams = [];
93 /** @var BagOStuff APC cache */
95 /** @var LoggerInterface */
96 protected $connLogger;
97 /** @var LoggerInterface */
98 protected $queryLogger;
99 /** @var callback Error logging callback */
100 protected $errorLogger;
102 /** @var resource|null Database connection */
103 protected $conn = null;
105 protected $opened = false;
107 /** @var array[] List of (callable, method name) */
108 protected $trxIdleCallbacks = [];
109 /** @var array[] List of (callable, method name) */
110 protected $trxPreCommitCallbacks = [];
111 /** @var array[] List of (callable, method name) */
112 protected $trxEndCallbacks = [];
113 /** @var callable[] Map of (name => callable) */
114 protected $trxRecurringCallbacks = [];
115 /** @var bool Whether to suppress triggering of transaction end callbacks */
116 protected $trxEndCallbacksSuppressed = false;
119 protected $tablePrefix = '';
121 protected $schema = '';
125 protected $lbInfo = [];
126 /** @var array|bool */
127 protected $schemaVars = false;
129 protected $sessionVars = [];
130 /** @var array|null */
131 protected $preparedArgs;
132 /** @var string|bool|null Stashed value of html_errors INI setting */
133 protected $htmlErrors;
135 protected $delimiter = ';';
136 /** @var DatabaseDomain */
137 protected $currentDomain;
138 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
139 protected $affectedRowCount;
142 * Either 1 if a transaction is active or 0 otherwise.
143 * The other Trx fields may not be meaningfull if this is 0.
147 protected $trxLevel = 0;
149 * Either a short hexidecimal string if a transaction is active or ""
152 * @see Database::trxLevel
154 protected $trxShortId = '';
156 * The UNIX time that the transaction started. Callers can assume that if
157 * snapshot isolation is used, then the data is *at least* up to date to that
158 * point (possibly more up-to-date since the first SELECT defines the snapshot).
161 * @see Database::trxLevel
163 private $trxTimestamp = null;
164 /** @var float Lag estimate at the time of BEGIN */
165 private $trxReplicaLag = null;
167 * Remembers the function name given for starting the most recent transaction via begin().
168 * Used to provide additional context for error reporting.
171 * @see Database::trxLevel
173 private $trxFname = null;
175 * Record if possible write queries were done in the last transaction started
178 * @see Database::trxLevel
180 private $trxDoneWrites = false;
182 * Record if the current transaction was started implicitly due to DBO_TRX being set.
185 * @see Database::trxLevel
187 private $trxAutomatic = false;
189 * Array of levels of atomicity within transactions
193 private $trxAtomicLevels = [];
195 * Record if the current transaction was started implicitly by Database::startAtomic
199 private $trxAutomaticAtomic = false;
201 * Track the write query callers of the current transaction
205 private $trxWriteCallers = [];
207 * @var float Seconds spent in write queries for the current transaction
209 private $trxWriteDuration = 0.0;
211 * @var int Number of write queries for the current transaction
213 private $trxWriteQueryCount = 0;
215 * @var int Number of rows affected by write queries for the current transaction
217 private $trxWriteAffectedRows = 0;
219 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
221 private $trxWriteAdjDuration = 0.0;
223 * @var int Number of write queries counted in trxWriteAdjDuration
225 private $trxWriteAdjQueryCount = 0;
227 * @var float RTT time estimate
229 private $rttEstimate = 0.0;
231 /** @var array Map of (name => 1) for locks obtained via lock() */
232 private $namedLocksHeld = [];
233 /** @var array Map of (table name => 1) for TEMPORARY tables */
234 protected $sessionTempTables = [];
236 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
237 private $lazyMasterHandle;
239 /** @var float UNIX timestamp */
240 protected $lastPing = 0.0;
242 /** @var int[] Prior flags member variable values */
243 private $priorFlags = [];
245 /** @var object|string Class name or object With profileIn/profileOut methods */
247 /** @var TransactionProfiler */
248 protected $trxProfiler;
251 protected $nonNativeInsertSelectBatchSize = 10000;
254 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
255 * @param array $params Parameters passed from Database::factory()
257 protected function __construct( array $params ) {
258 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
259 $this->connectionParams
[$name] = $params[$name];
262 $this->schema
= $params['schema'];
263 $this->tablePrefix
= $params['tablePrefix'];
265 $this->cliMode
= $params['cliMode'];
266 // Agent name is added to SQL queries in a comment, so make sure it can't break out
267 $this->agent
= str_replace( '/', '-', $params['agent'] );
269 $this->flags
= $params['flags'];
270 if ( $this->flags
& self
::DBO_DEFAULT
) {
271 if ( $this->cliMode
) {
272 $this->flags
&= ~self
::DBO_TRX
;
274 $this->flags |
= self
::DBO_TRX
;
278 $this->sessionVars
= $params['variables'];
280 $this->srvCache
= isset( $params['srvCache'] )
281 ?
$params['srvCache']
282 : new HashBagOStuff();
284 $this->profiler
= $params['profiler'];
285 $this->trxProfiler
= $params['trxProfiler'];
286 $this->connLogger
= $params['connLogger'];
287 $this->queryLogger
= $params['queryLogger'];
288 $this->errorLogger
= $params['errorLogger'];
290 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
291 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
294 // Set initial dummy domain until open() sets the final DB/prefix
295 $this->currentDomain
= DatabaseDomain
::newUnspecified();
299 * Initialize the connection to the database over the wire (or to local files)
301 * @throws LogicException
302 * @throws InvalidArgumentException
303 * @throws DBConnectionError
306 final public function initConnection() {
307 if ( $this->isOpen() ) {
308 throw new LogicException( __METHOD__
. ': already connected.' );
310 // Establish the connection
311 $this->doInitConnection();
312 // Set the domain object after open() sets the relevant fields
313 if ( $this->dbName
!= '' ) {
314 // Domains with server scope but a table prefix are not used by IDatabase classes
315 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
320 * Actually connect to the database over the wire (or to local files)
322 * @throws InvalidArgumentException
323 * @throws DBConnectionError
326 protected function doInitConnection() {
327 if ( strlen( $this->connectionParams
['user'] ) ) {
329 $this->connectionParams
['host'],
330 $this->connectionParams
['user'],
331 $this->connectionParams
['password'],
332 $this->connectionParams
['dbname']
335 throw new InvalidArgumentException( "No database user provided." );
340 * Construct a Database subclass instance given a database type and parameters
342 * This also connects to the database immediately upon object construction
344 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
345 * @param array $p Parameter map with keys:
346 * - host : The hostname of the DB server
347 * - user : The name of the database user the client operates under
348 * - password : The password for the database user
349 * - dbname : The name of the database to use where queries do not specify one.
350 * The database must exist or an error might be thrown. Setting this to the empty string
351 * will avoid any such errors and make the handle have no implicit database scope. This is
352 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
353 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
354 * in which user names and such are defined, e.g. users are database-specific in Postgres.
355 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
356 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
357 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
358 * recognized in queries. This can be used in place of schemas for handle site farms.
359 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
360 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
361 * flag in place UNLESS this this database simply acts as a key/value store.
362 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
363 * 'mysqli' driver; the old one 'mysql' has been removed.
364 * - variables: Optional map of session variables to set after connecting. This can be
365 * used to adjust lock timeouts or encoding modes and the like.
366 * - connLogger: Optional PSR-3 logger interface instance.
367 * - queryLogger: Optional PSR-3 logger interface instance.
368 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
369 * These will be called in query(), using a simplified version of the SQL that also
370 * includes the agent as a SQL comment.
371 * - trxProfiler: Optional TransactionProfiler instance.
372 * - errorLogger: Optional callback that takes an Exception and logs it.
373 * - cliMode: Whether to consider the execution context that of a CLI script.
374 * - agent: Optional name used to identify the end-user in query profiling/logging.
375 * - srvCache: Optional BagOStuff instance to an APC-style cache.
376 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
377 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
378 * @return Database|null If the database driver or extension cannot be found
379 * @throws InvalidArgumentException If the database driver or extension cannot be found
382 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
383 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
385 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
386 // Resolve some defaults for b/c
387 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
388 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
389 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
390 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
391 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
392 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
393 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
394 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
395 $p['cliMode'] = isset( $p['cliMode'] )
397 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
398 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
399 if ( !isset( $p['connLogger'] ) ) {
400 $p['connLogger'] = new NullLogger();
402 if ( !isset( $p['queryLogger'] ) ) {
403 $p['queryLogger'] = new NullLogger();
405 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
406 if ( !isset( $p['trxProfiler'] ) ) {
407 $p['trxProfiler'] = new TransactionProfiler();
409 if ( !isset( $p['errorLogger'] ) ) {
410 $p['errorLogger'] = function ( Exception
$e ) {
411 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
415 /** @var Database $conn */
416 $conn = new $class( $p );
417 if ( $connect == self
::NEW_CONNECTED
) {
418 $conn->initConnection();
428 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
429 * @param string|null $driver Optional name of a specific DB client driver
430 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
431 * @throws InvalidArgumentException
434 final public static function attributesFromType( $dbType, $driver = null ) {
435 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
437 $class = self
::getClass( $dbType, $driver );
439 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
443 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
444 * @param string|null $driver Optional name of a specific DB client driver
445 * @return string Database subclass name to use
446 * @throws InvalidArgumentException
448 private static function getClass( $dbType, $driver = null ) {
449 // For database types with built-in support, the below maps type to IDatabase
450 // implementations. For types with multipe driver implementations (PHP extensions),
451 // an array can be used, keyed by extension name. In case of an array, the
452 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
453 // we auto-detect the first available driver. For types without built-in support,
454 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
455 static $builtinTypes = [
456 'mssql' => DatabaseMssql
::class,
457 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
458 'sqlite' => DatabaseSqlite
::class,
459 'postgres' => DatabasePostgres
::class,
462 $dbType = strtolower( $dbType );
465 if ( isset( $builtinTypes[$dbType] ) ) {
466 $possibleDrivers = $builtinTypes[$dbType];
467 if ( is_string( $possibleDrivers ) ) {
468 $class = $possibleDrivers;
470 if ( (string)$driver !== '' ) {
471 if ( !isset( $possibleDrivers[$driver] ) ) {
472 throw new InvalidArgumentException( __METHOD__
.
473 " type '$dbType' does not support driver '{$driver}'" );
475 $class = $possibleDrivers[$driver];
478 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
479 if ( extension_loaded( $posDriver ) ) {
480 $class = $possibleClass;
487 $class = 'Database' . ucfirst( $dbType );
490 if ( $class === false ) {
491 throw new InvalidArgumentException( __METHOD__
.
492 " no viable database extension found for type '$dbType'" );
499 * @return array Map of (Database::ATTRIBUTE_* constant => value
502 protected static function getAttributes() {
507 * Set the PSR-3 logger interface to use for query logging. (The logger
508 * interfaces for connection logging and error logging can be set with the
511 * @param LoggerInterface $logger
513 public function setLogger( LoggerInterface
$logger ) {
514 $this->queryLogger
= $logger;
517 public function getServerInfo() {
518 return $this->getServerVersion();
521 public function bufferResults( $buffer = null ) {
522 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
523 if ( $buffer !== null ) {
525 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
526 : $this->setFlag( self
::DBO_NOBUFFER
);
533 * Turns on (false) or off (true) the automatic generation and sending
534 * of a "we're sorry, but there has been a database error" page on
535 * database errors. Default is on (false). When turned off, the
536 * code should use lastErrno() and lastError() to handle the
537 * situation as appropriate.
539 * Do not use this function outside of the Database classes.
541 * @param null|bool $ignoreErrors
542 * @return bool The previous value of the flag.
544 protected function ignoreErrors( $ignoreErrors = null ) {
545 $res = $this->getFlag( self
::DBO_IGNORE
);
546 if ( $ignoreErrors !== null ) {
547 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
548 if ( $ignoreErrors ) {
549 $this->flags |
= self
::DBO_IGNORE
;
551 $this->flags
&= ~self
::DBO_IGNORE
;
558 public function trxLevel() {
559 return $this->trxLevel
;
562 public function trxTimestamp() {
563 return $this->trxLevel ?
$this->trxTimestamp
: null;
566 public function tablePrefix( $prefix = null ) {
567 $old = $this->tablePrefix
;
568 if ( $prefix !== null ) {
569 $this->tablePrefix
= $prefix;
570 $this->currentDomain
= ( $this->dbName
!= '' )
571 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
572 : DatabaseDomain
::newUnspecified();
578 public function dbSchema( $schema = null ) {
579 $old = $this->schema
;
580 if ( $schema !== null ) {
581 $this->schema
= $schema;
587 public function getLBInfo( $name = null ) {
588 if ( is_null( $name ) ) {
589 return $this->lbInfo
;
591 if ( array_key_exists( $name, $this->lbInfo
) ) {
592 return $this->lbInfo
[$name];
599 public function setLBInfo( $name, $value = null ) {
600 if ( is_null( $value ) ) {
601 $this->lbInfo
= $name;
603 $this->lbInfo
[$name] = $value;
607 public function setLazyMasterHandle( IDatabase
$conn ) {
608 $this->lazyMasterHandle
= $conn;
612 * @return IDatabase|null
613 * @see setLazyMasterHandle()
616 protected function getLazyMasterHandle() {
617 return $this->lazyMasterHandle
;
620 public function implicitGroupby() {
624 public function implicitOrderby() {
628 public function lastQuery() {
629 return $this->lastQuery
;
632 public function doneWrites() {
633 return (bool)$this->lastWriteTime
;
636 public function lastDoneWrites() {
637 return $this->lastWriteTime ?
: false;
640 public function writesPending() {
641 return $this->trxLevel
&& $this->trxDoneWrites
;
644 public function writesOrCallbacksPending() {
645 return $this->trxLevel
&& (
646 $this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks
650 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
651 if ( !$this->trxLevel
) {
653 } elseif ( !$this->trxDoneWrites
) {
658 case self
::ESTIMATE_DB_APPLY
:
660 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
661 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
662 // For omitted queries, make them count as something at least
663 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
664 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
667 default: // everything
668 return $this->trxWriteDuration
;
672 public function pendingWriteCallers() {
673 return $this->trxLevel ?
$this->trxWriteCallers
: [];
676 public function pendingWriteRowsAffected() {
677 return $this->trxWriteAffectedRows
;
681 * Get the list of method names that have pending write queries or callbacks
682 * for this transaction
686 protected function pendingWriteAndCallbackCallers() {
687 if ( !$this->trxLevel
) {
691 $fnames = $this->trxWriteCallers
;
693 $this->trxIdleCallbacks
,
694 $this->trxPreCommitCallbacks
,
695 $this->trxEndCallbacks
697 foreach ( $callbacks as $callback ) {
698 $fnames[] = $callback[1];
705 public function isOpen() {
706 return $this->opened
;
709 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
710 if ( ( $flag & self
::DBO_IGNORE
) ) {
711 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
714 if ( $remember === self
::REMEMBER_PRIOR
) {
715 array_push( $this->priorFlags
, $this->flags
);
717 $this->flags |
= $flag;
720 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
721 if ( ( $flag & self
::DBO_IGNORE
) ) {
722 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
725 if ( $remember === self
::REMEMBER_PRIOR
) {
726 array_push( $this->priorFlags
, $this->flags
);
728 $this->flags
&= ~
$flag;
731 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
732 if ( !$this->priorFlags
) {
736 if ( $state === self
::RESTORE_INITIAL
) {
737 $this->flags
= reset( $this->priorFlags
);
738 $this->priorFlags
= [];
740 $this->flags
= array_pop( $this->priorFlags
);
744 public function getFlag( $flag ) {
745 return !!( $this->flags
& $flag );
749 * @param string $name Class field name
751 * @deprecated Since 1.28
753 public function getProperty( $name ) {
757 public function getDomainID() {
758 return $this->currentDomain
->getId();
761 final public function getWikiID() {
762 return $this->getDomainID();
766 * Get information about an index into an object
767 * @param string $table Table name
768 * @param string $index Index name
769 * @param string $fname Calling function name
770 * @return mixed Database-specific index description class or false if the index does not exist
772 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
775 * Wrapper for addslashes()
777 * @param string $s String to be slashed.
778 * @return string Slashed string.
780 abstract function strencode( $s );
783 * Set a custom error handler for logging errors during database connection
785 protected function installErrorHandler() {
786 $this->phpError
= false;
787 $this->htmlErrors
= ini_set( 'html_errors', '0' );
788 set_error_handler( [ $this, 'connectionErrorLogger' ] );
792 * Restore the previous error handler and return the last PHP error for this DB
794 * @return bool|string
796 protected function restoreErrorHandler() {
797 restore_error_handler();
798 if ( $this->htmlErrors
!== false ) {
799 ini_set( 'html_errors', $this->htmlErrors
);
802 return $this->getLastPHPError();
806 * @return string|bool Last PHP error for this DB (typically connection errors)
808 protected function getLastPHPError() {
809 if ( $this->phpError
) {
810 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
811 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
820 * Error handler for logging errors during database connection
821 * This method should not be used outside of Database classes
824 * @param string $errstr
826 public function connectionErrorLogger( $errno, $errstr ) {
827 $this->phpError
= $errstr;
831 * Create a log context to pass to PSR-3 logger functions.
833 * @param array $extras Additional data to add to context
836 protected function getLogContext( array $extras = [] ) {
839 'db_server' => $this->server
,
840 'db_name' => $this->dbName
,
841 'db_user' => $this->user
,
847 public function close() {
849 if ( $this->trxLevel() ) {
850 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
853 $closed = $this->closeConnection();
856 $this->trxIdleCallbacks ||
857 $this->trxPreCommitCallbacks ||
858 $this->trxEndCallbacks
860 throw new RuntimeException( "Transaction callbacks still pending." );
864 $this->opened
= false;
870 * Make sure isOpen() returns true as a sanity check
872 * @throws DBUnexpectedError
874 protected function assertOpen() {
875 if ( !$this->isOpen() ) {
876 throw new DBUnexpectedError( $this, "DB connection was already closed." );
881 * Closes underlying database connection
883 * @return bool Whether connection was closed successfully
885 abstract protected function closeConnection();
887 public function reportConnectionError( $error = 'Unknown error' ) {
888 $myError = $this->lastError();
894 throw new DBConnectionError( $this, $error );
898 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
900 * This might return things, such as mysqli_result, that do not formally implement
901 * IResultWrapper, but nonetheless implement all of its methods correctly
903 * @param string $sql SQL query.
904 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
906 abstract protected function doQuery( $sql );
909 * Determine whether a query writes to the DB.
910 * Should return true if unsure.
915 protected function isWriteQuery( $sql ) {
917 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
922 * @return string|null
924 protected function getQueryVerb( $sql ) {
925 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
929 * Determine whether a SQL statement is sensitive to isolation level.
930 * A SQL statement is considered transactable if its result could vary
931 * depending on the transaction isolation level. Operational commands
932 * such as 'SET' and 'SHOW' are not considered to be transactable.
937 protected function isTransactableQuery( $sql ) {
939 $this->getQueryVerb( $sql ),
940 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
946 * @param string $sql A SQL query
947 * @return bool Whether $sql is SQL for TEMPORARY table operation
949 protected function registerTempTableOperation( $sql ) {
951 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
955 $this->sessionTempTables
[$matches[1]] = 1;
958 } elseif ( preg_match(
959 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
963 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
964 unset( $this->sessionTempTables
[$matches[1]] );
967 } elseif ( preg_match(
968 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
972 return isset( $this->sessionTempTables
[$matches[1]] );
973 } elseif ( preg_match(
974 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
978 return isset( $this->sessionTempTables
[$matches[1]] );
984 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
985 $priorWritesPending = $this->writesOrCallbacksPending();
986 $this->lastQuery
= $sql;
988 $isWrite = $this->isWriteQuery( $sql );
990 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
992 $isNonTempWrite = false;
996 if ( $this->getLBInfo( 'replica' ) === true ) {
999 'Write operations are not allowed on replica database connections.'
1002 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1003 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1004 $reason = $this->getReadOnlyReason();
1005 if ( $reason !== false ) {
1006 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1008 # Set a flag indicating that writes have been done
1009 $this->lastWriteTime
= microtime( true );
1012 # Add trace comment to the begin of the sql string, right after the operator.
1013 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1014 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1016 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1017 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1018 && $this->isTransactableQuery( $sql )
1020 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1021 $this->trxAutomatic
= true;
1024 # Keep track of whether the transaction has write queries pending
1025 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1026 $this->trxDoneWrites
= true;
1027 $this->trxProfiler
->transactionWritingIn(
1028 $this->server
, $this->dbName
, $this->trxShortId
);
1031 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1032 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1035 # Avoid fatals if close() was called
1036 $this->assertOpen();
1038 # Send the query to the server
1039 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1041 # Try reconnecting if the connection was lost
1042 if ( false === $ret && $this->wasErrorReissuable() ) {
1043 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1044 # Stash the last error values before anything might clear them
1045 $lastError = $this->lastError();
1046 $lastErrno = $this->lastErrno();
1047 # Update state tracking to reflect transaction loss due to disconnection
1048 $this->handleSessionLoss();
1049 if ( $this->reconnect() ) {
1050 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1051 $params = [ 'dbserver' => $this->getServer() ];
1052 $this->connLogger
->warning( $msg, $params );
1053 $this->queryLogger
->warning( $msg, $params +
1054 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1056 if ( !$recoverable ) {
1057 # Callers may catch the exception and continue to use the DB
1058 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1060 # Should be safe to silently retry the query
1061 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1064 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1065 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1069 if ( false === $ret ) {
1070 # Deadlocks cause the entire transaction to abort, not just the statement.
1071 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1072 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1073 if ( $this->wasDeadlock() ) {
1074 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1075 $tempIgnore = false; // not recoverable
1077 # Update state tracking to reflect transaction loss
1078 $this->handleSessionLoss();
1081 $this->reportQueryError(
1082 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1085 $res = $this->resultObject( $ret );
1091 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1093 * @param string $sql Original SQL query
1094 * @param string $commentedSql SQL query with debugging/trace comment
1095 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1096 * @param string $fname Name of the calling function
1097 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1098 * object for a successful read query, or false on failure
1100 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1101 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1102 # generalizeSQL() will probably cut down the query to reasonable
1103 # logging size most of the time. The substr is really just a sanity check.
1105 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1107 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1110 # Include query transaction state
1111 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1113 $startTime = microtime( true );
1114 if ( $this->profiler
) {
1115 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1117 $this->affectedRowCount
= null;
1118 $ret = $this->doQuery( $commentedSql );
1119 $this->affectedRowCount
= $this->affectedRows();
1120 if ( $this->profiler
) {
1121 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1123 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1125 unset( $queryProfSection ); // profile out (if set)
1127 if ( $ret !== false ) {
1128 $this->lastPing
= $startTime;
1129 if ( $isWrite && $this->trxLevel
) {
1130 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1131 $this->trxWriteCallers
[] = $fname;
1135 if ( $sql === self
::PING_QUERY
) {
1136 $this->rttEstimate
= $queryRuntime;
1139 $this->trxProfiler
->recordQueryCompletion(
1140 $queryProf, $startTime, $isWrite, $this->affectedRows()
1142 $this->queryLogger
->debug( $sql, [
1144 'master' => $isMaster,
1145 'runtime' => $queryRuntime,
1152 * Update the estimated run-time of a query, not counting large row lock times
1154 * LoadBalancer can be set to rollback transactions that will create huge replication
1155 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1156 * queries, like inserting a row can take a long time due to row locking. This method
1157 * uses some simple heuristics to discount those cases.
1159 * @param string $sql A SQL write query
1160 * @param float $runtime Total runtime, including RTT
1161 * @param int $affected Affected row count
1163 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1164 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1165 $indicativeOfReplicaRuntime = true;
1166 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1167 $verb = $this->getQueryVerb( $sql );
1168 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1169 if ( $verb === 'INSERT' ) {
1170 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1171 } elseif ( $verb === 'REPLACE' ) {
1172 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1176 $this->trxWriteDuration +
= $runtime;
1177 $this->trxWriteQueryCount +
= 1;
1178 $this->trxWriteAffectedRows +
= $affected;
1179 if ( $indicativeOfReplicaRuntime ) {
1180 $this->trxWriteAdjDuration +
= $runtime;
1181 $this->trxWriteAdjQueryCount +
= 1;
1186 * Determine whether or not it is safe to retry queries after a database
1187 * connection is lost
1189 * @param string $sql SQL query
1190 * @param bool $priorWritesPending Whether there is a transaction open with
1191 * possible write queries or transaction pre-commit/idle callbacks
1192 * waiting on it to finish.
1193 * @return bool True if it is safe to retry the query, false otherwise
1195 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1196 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1197 # Dropped connections also mean that named locks are automatically released.
1198 # Only allow error suppression in autocommit mode or when the lost transaction
1199 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1200 if ( $this->namedLocksHeld
) {
1201 return false; // possible critical section violation
1202 } elseif ( $sql === 'COMMIT' ) {
1203 return !$priorWritesPending; // nothing written anyway? (T127428)
1204 } elseif ( $sql === 'ROLLBACK' ) {
1205 return true; // transaction lost...which is also what was requested :)
1206 } elseif ( $this->explicitTrxActive() ) {
1207 return false; // don't drop atomocity
1208 } elseif ( $priorWritesPending ) {
1209 return false; // prior writes lost from implicit transaction
1216 * Clean things up after transaction loss due to disconnection
1218 * @return null|Exception
1220 private function handleSessionLoss() {
1221 $this->trxLevel
= 0;
1222 $this->trxIdleCallbacks
= []; // T67263
1223 $this->trxPreCommitCallbacks
= []; // T67263
1224 $this->sessionTempTables
= [];
1225 $this->namedLocksHeld
= [];
1227 // Handle callbacks in trxEndCallbacks
1228 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1229 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1231 } catch ( Exception
$e ) {
1232 // Already logged; move on...
1238 * Checks whether the cause of the error is detected to be a timeout.
1240 * It returns false by default, and not all engines support detecting this yet.
1241 * If this returns false, it will be treated as a generic query error.
1243 * @param string $error Error text
1244 * @param int $errno Error number
1247 protected function wasQueryTimeout( $error, $errno ) {
1251 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1252 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1253 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1255 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1256 $this->queryLogger
->error(
1257 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1258 $this->getLogContext( [
1259 'method' => __METHOD__
,
1262 'sql1line' => $sql1line,
1266 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1267 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1268 if ( $wasQueryTimeout ) {
1269 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1271 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1276 public function freeResult( $res ) {
1279 public function selectField(
1280 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1282 if ( $var === '*' ) { // sanity
1283 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1286 if ( !is_array( $options ) ) {
1287 $options = [ $options ];
1290 $options['LIMIT'] = 1;
1292 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1293 if ( $res === false ||
!$this->numRows( $res ) ) {
1297 $row = $this->fetchRow( $res );
1299 if ( $row !== false ) {
1300 return reset( $row );
1306 public function selectFieldValues(
1307 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1309 if ( $var === '*' ) { // sanity
1310 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1311 } elseif ( !is_string( $var ) ) { // sanity
1312 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1315 if ( !is_array( $options ) ) {
1316 $options = [ $options ];
1319 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1320 if ( $res === false ) {
1325 foreach ( $res as $row ) {
1326 $values[] = $row->$var;
1333 * Returns an optional USE INDEX clause to go after the table, and a
1334 * string to go at the end of the query.
1336 * @param array $options Associative array of options to be turned into
1337 * an SQL query, valid keys are listed in the function.
1339 * @see Database::select()
1341 protected function makeSelectOptions( $options ) {
1342 $preLimitTail = $postLimitTail = '';
1347 foreach ( $options as $key => $option ) {
1348 if ( is_numeric( $key ) ) {
1349 $noKeyOptions[$option] = true;
1353 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1355 $preLimitTail .= $this->makeOrderBy( $options );
1357 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1358 $postLimitTail .= ' FOR UPDATE';
1361 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1362 $postLimitTail .= ' LOCK IN SHARE MODE';
1365 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1366 $startOpts .= 'DISTINCT';
1369 # Various MySQL extensions
1370 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1371 $startOpts .= ' /*! STRAIGHT_JOIN */';
1374 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1375 $startOpts .= ' HIGH_PRIORITY';
1378 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1379 $startOpts .= ' SQL_BIG_RESULT';
1382 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1383 $startOpts .= ' SQL_BUFFER_RESULT';
1386 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1387 $startOpts .= ' SQL_SMALL_RESULT';
1390 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1391 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1394 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1395 $startOpts .= ' SQL_CACHE';
1398 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1399 $startOpts .= ' SQL_NO_CACHE';
1402 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1403 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1407 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1408 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1413 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1417 * Returns an optional GROUP BY with an optional HAVING
1419 * @param array $options Associative array of options
1421 * @see Database::select()
1424 protected function makeGroupByWithHaving( $options ) {
1426 if ( isset( $options['GROUP BY'] ) ) {
1427 $gb = is_array( $options['GROUP BY'] )
1428 ?
implode( ',', $options['GROUP BY'] )
1429 : $options['GROUP BY'];
1430 $sql .= ' GROUP BY ' . $gb;
1432 if ( isset( $options['HAVING'] ) ) {
1433 $having = is_array( $options['HAVING'] )
1434 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1435 : $options['HAVING'];
1436 $sql .= ' HAVING ' . $having;
1443 * Returns an optional ORDER BY
1445 * @param array $options Associative array of options
1447 * @see Database::select()
1450 protected function makeOrderBy( $options ) {
1451 if ( isset( $options['ORDER BY'] ) ) {
1452 $ob = is_array( $options['ORDER BY'] )
1453 ?
implode( ',', $options['ORDER BY'] )
1454 : $options['ORDER BY'];
1456 return ' ORDER BY ' . $ob;
1462 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1463 $options = [], $join_conds = [] ) {
1464 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1466 return $this->query( $sql, $fname );
1469 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1470 $options = [], $join_conds = []
1472 if ( is_array( $vars ) ) {
1473 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1476 $options = (array)$options;
1477 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1478 ?
$options['USE INDEX']
1481 isset( $options['IGNORE INDEX'] ) &&
1482 is_array( $options['IGNORE INDEX'] )
1484 ?
$options['IGNORE INDEX']
1487 if ( is_array( $table ) ) {
1489 $this->tableNamesWithIndexClauseOrJOIN(
1490 $table, $useIndexes, $ignoreIndexes, $join_conds );
1491 } elseif ( $table != '' ) {
1493 $this->tableNamesWithIndexClauseOrJOIN(
1494 [ $table ], $useIndexes, $ignoreIndexes, [] );
1499 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1500 $this->makeSelectOptions( $options );
1502 if ( is_array( $conds ) ) {
1503 $conds = $this->makeList( $conds, self
::LIST_AND
);
1506 if ( $conds === null ||
$conds === false ) {
1507 $this->queryLogger
->warning(
1511 . ' with incorrect parameters: $conds must be a string or an array'
1516 if ( $conds === '' ) {
1517 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1518 } elseif ( is_string( $conds ) ) {
1519 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1520 "WHERE $conds $preLimitTail";
1522 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1525 if ( isset( $options['LIMIT'] ) ) {
1526 $sql = $this->limitResult( $sql, $options['LIMIT'],
1527 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1529 $sql = "$sql $postLimitTail";
1531 if ( isset( $options['EXPLAIN'] ) ) {
1532 $sql = 'EXPLAIN ' . $sql;
1538 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1539 $options = [], $join_conds = []
1541 $options = (array)$options;
1542 $options['LIMIT'] = 1;
1543 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1545 if ( $res === false ) {
1549 if ( !$this->numRows( $res ) ) {
1553 $obj = $this->fetchObject( $res );
1558 public function estimateRowCount(
1559 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1562 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1565 $row = $this->fetchRow( $res );
1566 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1572 public function selectRowCount(
1573 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1576 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1577 // The identifier quotes is primarily for MSSQL.
1578 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1579 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1580 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1583 $row = $this->fetchRow( $res );
1584 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1591 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1592 * It's only slightly flawed. Don't use for anything important.
1594 * @param string $sql A SQL Query
1598 protected static function generalizeSQL( $sql ) {
1599 # This does the same as the regexp below would do, but in such a way
1600 # as to avoid crashing php on some large strings.
1601 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1603 $sql = str_replace( "\\\\", '', $sql );
1604 $sql = str_replace( "\\'", '', $sql );
1605 $sql = str_replace( "\\\"", '', $sql );
1606 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1607 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1609 # All newlines, tabs, etc replaced by single space
1610 $sql = preg_replace( '/\s+/', ' ', $sql );
1613 # except the ones surrounded by characters, e.g. l10n
1614 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1615 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1620 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1621 $info = $this->fieldInfo( $table, $field );
1626 public function indexExists( $table, $index, $fname = __METHOD__
) {
1627 if ( !$this->tableExists( $table ) ) {
1631 $info = $this->indexInfo( $table, $index, $fname );
1632 if ( is_null( $info ) ) {
1635 return $info !== false;
1639 public function tableExists( $table, $fname = __METHOD__
) {
1640 $tableRaw = $this->tableName( $table, 'raw' );
1641 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1642 return true; // already known to exist
1645 $table = $this->tableName( $table );
1646 $ignoreErrors = true;
1647 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1652 public function indexUnique( $table, $index ) {
1653 $indexInfo = $this->indexInfo( $table, $index );
1655 if ( !$indexInfo ) {
1659 return !$indexInfo[0]->Non_unique
;
1663 * Helper for Database::insert().
1665 * @param array $options
1668 protected function makeInsertOptions( $options ) {
1669 return implode( ' ', $options );
1672 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1673 # No rows to insert, easy just return now
1674 if ( !count( $a ) ) {
1678 $table = $this->tableName( $table );
1680 if ( !is_array( $options ) ) {
1681 $options = [ $options ];
1685 if ( isset( $options['fileHandle'] ) ) {
1686 $fh = $options['fileHandle'];
1688 $options = $this->makeInsertOptions( $options );
1690 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1692 $keys = array_keys( $a[0] );
1695 $keys = array_keys( $a );
1698 $sql = 'INSERT ' . $options .
1699 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1703 foreach ( $a as $row ) {
1709 $sql .= '(' . $this->makeList( $row ) . ')';
1712 $sql .= '(' . $this->makeList( $a ) . ')';
1715 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1717 } elseif ( $fh !== null ) {
1721 return (bool)$this->query( $sql, $fname );
1725 * Make UPDATE options array for Database::makeUpdateOptions
1727 * @param array $options
1730 protected function makeUpdateOptionsArray( $options ) {
1731 if ( !is_array( $options ) ) {
1732 $options = [ $options ];
1737 if ( in_array( 'IGNORE', $options ) ) {
1745 * Make UPDATE options for the Database::update function
1747 * @param array $options The options passed to Database::update
1750 protected function makeUpdateOptions( $options ) {
1751 $opts = $this->makeUpdateOptionsArray( $options );
1753 return implode( ' ', $opts );
1756 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1757 $table = $this->tableName( $table );
1758 $opts = $this->makeUpdateOptions( $options );
1759 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1761 if ( $conds !== [] && $conds !== '*' ) {
1762 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1765 return (bool)$this->query( $sql, $fname );
1768 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1769 if ( !is_array( $a ) ) {
1770 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1776 foreach ( $a as $field => $value ) {
1778 if ( $mode == self
::LIST_AND
) {
1780 } elseif ( $mode == self
::LIST_OR
) {
1789 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1790 $list .= "($value)";
1791 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1794 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1796 // Remove null from array to be handled separately if found
1797 $includeNull = false;
1798 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1799 $includeNull = true;
1800 unset( $value[$nullKey] );
1802 if ( count( $value ) == 0 && !$includeNull ) {
1803 throw new InvalidArgumentException(
1804 __METHOD__
. ": empty input for field $field" );
1805 } elseif ( count( $value ) == 0 ) {
1806 // only check if $field is null
1807 $list .= "$field IS NULL";
1809 // IN clause contains at least one valid element
1810 if ( $includeNull ) {
1811 // Group subconditions to ensure correct precedence
1814 if ( count( $value ) == 1 ) {
1815 // Special-case single values, as IN isn't terribly efficient
1816 // Don't necessarily assume the single key is 0; we don't
1817 // enforce linear numeric ordering on other arrays here.
1818 $value = array_values( $value )[0];
1819 $list .= $field . " = " . $this->addQuotes( $value );
1821 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1823 // if null present in array, append IS NULL
1824 if ( $includeNull ) {
1825 $list .= " OR $field IS NULL)";
1828 } elseif ( $value === null ) {
1829 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1830 $list .= "$field IS ";
1831 } elseif ( $mode == self
::LIST_SET
) {
1832 $list .= "$field = ";
1837 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1839 $list .= "$field = ";
1841 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1848 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1851 foreach ( $data as $base => $sub ) {
1852 if ( count( $sub ) ) {
1853 $conds[] = $this->makeList(
1854 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1860 return $this->makeList( $conds, self
::LIST_OR
);
1862 // Nothing to search for...
1867 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1871 public function bitNot( $field ) {
1875 public function bitAnd( $fieldLeft, $fieldRight ) {
1876 return "($fieldLeft & $fieldRight)";
1879 public function bitOr( $fieldLeft, $fieldRight ) {
1880 return "($fieldLeft | $fieldRight)";
1883 public function buildConcat( $stringList ) {
1884 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1887 public function buildGroupConcatField(
1888 $delim, $table, $field, $conds = '', $join_conds = []
1890 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1892 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1895 public function buildSubstring( $input, $startPosition, $length = null ) {
1896 $this->assertBuildSubstringParams( $startPosition, $length );
1897 $functionBody = "$input FROM $startPosition";
1898 if ( $length !== null ) {
1899 $functionBody .= " FOR $length";
1901 return 'SUBSTRING(' . $functionBody . ')';
1905 * Check type and bounds for parameters to self::buildSubstring()
1907 * All supported databases have substring functions that behave the same for
1908 * positive $startPosition and non-negative $length, but behaviors differ when
1909 * given 0 or negative $startPosition or negative $length. The simplest
1910 * solution to that is to just forbid those values.
1912 * @param int $startPosition
1913 * @param int|null $length
1916 protected function assertBuildSubstringParams( $startPosition, $length ) {
1917 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
1918 throw new InvalidArgumentException(
1919 '$startPosition must be a positive integer'
1922 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
1923 throw new InvalidArgumentException(
1924 '$length must be null or an integer greater than or equal to 0'
1929 public function buildStringCast( $field ) {
1933 public function buildIntegerCast( $field ) {
1934 return 'CAST( ' . $field . ' AS INTEGER )';
1937 public function databasesAreIndependent() {
1941 public function selectDB( $db ) {
1942 # Stub. Shouldn't cause serious problems if it's not overridden, but
1943 # if your database engine supports a concept similar to MySQL's
1944 # databases you may as well.
1945 $this->dbName
= $db;
1950 public function getDBname() {
1951 return $this->dbName
;
1954 public function getServer() {
1955 return $this->server
;
1958 public function tableName( $name, $format = 'quoted' ) {
1959 # Skip the entire process when we have a string quoted on both ends.
1960 # Note that we check the end so that we will still quote any use of
1961 # use of `database`.table. But won't break things if someone wants
1962 # to query a database table with a dot in the name.
1963 if ( $this->isQuotedIdentifier( $name ) ) {
1967 # Lets test for any bits of text that should never show up in a table
1968 # name. Basically anything like JOIN or ON which are actually part of
1969 # SQL queries, but may end up inside of the table value to combine
1970 # sql. Such as how the API is doing.
1971 # Note that we use a whitespace test rather than a \b test to avoid
1972 # any remote case where a word like on may be inside of a table name
1973 # surrounded by symbols which may be considered word breaks.
1974 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1978 # Split database and table into proper variables.
1979 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1981 # Quote $table and apply the prefix if not quoted.
1982 # $tableName might be empty if this is called from Database::replaceVars()
1983 $tableName = "{$prefix}{$table}";
1984 if ( $format === 'quoted'
1985 && !$this->isQuotedIdentifier( $tableName )
1986 && $tableName !== ''
1988 $tableName = $this->addIdentifierQuotes( $tableName );
1991 # Quote $schema and $database and merge them with the table name if needed
1992 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1993 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1999 * Get the table components needed for a query given the currently selected database
2001 * @param string $name Table name in the form of db.schema.table, db.table, or table
2002 * @return array (DB name or "" for default, schema name, table prefix, table name)
2004 protected function qualifiedTableComponents( $name ) {
2005 # We reverse the explode so that database.table and table both output the correct table.
2006 $dbDetails = explode( '.', $name, 3 );
2007 if ( count( $dbDetails ) == 3 ) {
2008 list( $database, $schema, $table ) = $dbDetails;
2009 # We don't want any prefix added in this case
2011 } elseif ( count( $dbDetails ) == 2 ) {
2012 list( $database, $table ) = $dbDetails;
2013 # We don't want any prefix added in this case
2015 # In dbs that support it, $database may actually be the schema
2016 # but that doesn't affect any of the functionality here
2019 list( $table ) = $dbDetails;
2020 if ( isset( $this->tableAliases
[$table] ) ) {
2021 $database = $this->tableAliases
[$table]['dbname'];
2022 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2023 ?
$this->tableAliases
[$table]['schema']
2025 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2026 ?
$this->tableAliases
[$table]['prefix']
2027 : $this->tablePrefix
;
2030 $schema = $this->schema
; # Default schema
2031 $prefix = $this->tablePrefix
; # Default prefix
2035 return [ $database, $schema, $prefix, $table ];
2039 * @param string|null $namespace Database or schema
2040 * @param string $relation Name of table, view, sequence, etc...
2041 * @param string $format One of (raw, quoted)
2042 * @return string Relation name with quoted and merged $namespace as needed
2044 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2045 if ( strlen( $namespace ) ) {
2046 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2047 $namespace = $this->addIdentifierQuotes( $namespace );
2049 $relation = $namespace . '.' . $relation;
2055 public function tableNames() {
2056 $inArray = func_get_args();
2059 foreach ( $inArray as $name ) {
2060 $retVal[$name] = $this->tableName( $name );
2066 public function tableNamesN() {
2067 $inArray = func_get_args();
2070 foreach ( $inArray as $name ) {
2071 $retVal[] = $this->tableName( $name );
2078 * Get an aliased table name
2079 * e.g. tableName AS newTableName
2081 * @param string $name Table name, see tableName()
2082 * @param string|bool $alias Alias (optional)
2083 * @return string SQL name for aliased table. Will not alias a table to its own name
2085 protected function tableNameWithAlias( $name, $alias = false ) {
2086 if ( !$alias ||
$alias == $name ) {
2087 return $this->tableName( $name );
2089 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2094 * Gets an array of aliased table names
2096 * @param array $tables [ [alias] => table ]
2097 * @return string[] See tableNameWithAlias()
2099 protected function tableNamesWithAlias( $tables ) {
2101 foreach ( $tables as $alias => $table ) {
2102 if ( is_numeric( $alias ) ) {
2105 $retval[] = $this->tableNameWithAlias( $table, $alias );
2112 * Get an aliased field name
2113 * e.g. fieldName AS newFieldName
2115 * @param string $name Field name
2116 * @param string|bool $alias Alias (optional)
2117 * @return string SQL name for aliased field. Will not alias a field to its own name
2119 protected function fieldNameWithAlias( $name, $alias = false ) {
2120 if ( !$alias ||
(string)$alias === (string)$name ) {
2123 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2128 * Gets an array of aliased field names
2130 * @param array $fields [ [alias] => field ]
2131 * @return string[] See fieldNameWithAlias()
2133 protected function fieldNamesWithAlias( $fields ) {
2135 foreach ( $fields as $alias => $field ) {
2136 if ( is_numeric( $alias ) ) {
2139 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2146 * Get the aliased table name clause for a FROM clause
2147 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2149 * @param array $tables ( [alias] => table )
2150 * @param array $use_index Same as for select()
2151 * @param array $ignore_index Same as for select()
2152 * @param array $join_conds Same as for select()
2155 protected function tableNamesWithIndexClauseOrJOIN(
2156 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2160 $use_index = (array)$use_index;
2161 $ignore_index = (array)$ignore_index;
2162 $join_conds = (array)$join_conds;
2164 foreach ( $tables as $alias => $table ) {
2165 if ( !is_string( $alias ) ) {
2166 // No alias? Set it equal to the table name
2170 if ( is_array( $table ) ) {
2171 // A parenthesized group
2172 if ( count( $table ) > 1 ) {
2174 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2178 $innerTable = reset( $table );
2179 $innerAlias = key( $table );
2180 $joinedTable = $this->tableNameWithAlias(
2182 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2186 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2189 // Is there a JOIN clause for this table?
2190 if ( isset( $join_conds[$alias] ) ) {
2191 list( $joinType, $conds ) = $join_conds[$alias];
2192 $tableClause = $joinType;
2193 $tableClause .= ' ' . $joinedTable;
2194 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2195 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2197 $tableClause .= ' ' . $use;
2200 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2201 $ignore = $this->ignoreIndexClause(
2202 implode( ',', (array)$ignore_index[$alias] ) );
2203 if ( $ignore != '' ) {
2204 $tableClause .= ' ' . $ignore;
2207 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2209 $tableClause .= ' ON (' . $on . ')';
2212 $retJOIN[] = $tableClause;
2213 } elseif ( isset( $use_index[$alias] ) ) {
2214 // Is there an INDEX clause for this table?
2215 $tableClause = $joinedTable;
2216 $tableClause .= ' ' . $this->useIndexClause(
2217 implode( ',', (array)$use_index[$alias] )
2220 $ret[] = $tableClause;
2221 } elseif ( isset( $ignore_index[$alias] ) ) {
2222 // Is there an INDEX clause for this table?
2223 $tableClause = $joinedTable;
2224 $tableClause .= ' ' . $this->ignoreIndexClause(
2225 implode( ',', (array)$ignore_index[$alias] )
2228 $ret[] = $tableClause;
2230 $tableClause = $joinedTable;
2232 $ret[] = $tableClause;
2236 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2237 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2238 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2240 // Compile our final table clause
2241 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2245 * Allows for index remapping in queries where this is not consistent across DBMS
2247 * @param string $index
2250 protected function indexName( $index ) {
2254 public function addQuotes( $s ) {
2255 if ( $s instanceof Blob
) {
2258 if ( $s === null ) {
2260 } elseif ( is_bool( $s ) ) {
2263 # This will also quote numeric values. This should be harmless,
2264 # and protects against weird problems that occur when they really
2265 # _are_ strings such as article titles and string->number->string
2266 # conversion is not 1:1.
2267 return "'" . $this->strencode( $s ) . "'";
2272 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2273 * MySQL uses `backticks` while basically everything else uses double quotes.
2274 * Since MySQL is the odd one out here the double quotes are our generic
2275 * and we implement backticks in DatabaseMysqlBase.
2280 public function addIdentifierQuotes( $s ) {
2281 return '"' . str_replace( '"', '""', $s ) . '"';
2285 * Returns if the given identifier looks quoted or not according to
2286 * the database convention for quoting identifiers .
2288 * @note Do not use this to determine if untrusted input is safe.
2289 * A malicious user can trick this function.
2290 * @param string $name
2293 public function isQuotedIdentifier( $name ) {
2294 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2299 * @param string $escapeChar
2302 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2303 return str_replace( [ $escapeChar, '%', '_' ],
2304 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2308 public function buildLike() {
2309 $params = func_get_args();
2311 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2312 $params = $params[0];
2317 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2318 // may escape backslashes, creating problems of double escaping. The `
2319 // character has good cross-DBMS compatibility, avoiding special operators
2320 // in MS SQL like ^ and %
2323 foreach ( $params as $value ) {
2324 if ( $value instanceof LikeMatch
) {
2325 $s .= $value->toString();
2327 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2331 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2334 public function anyChar() {
2335 return new LikeMatch( '_' );
2338 public function anyString() {
2339 return new LikeMatch( '%' );
2342 public function nextSequenceValue( $seqName ) {
2347 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2348 * is only needed because a) MySQL must be as efficient as possible due to
2349 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2350 * which index to pick. Anyway, other databases might have different
2351 * indexes on a given table. So don't bother overriding this unless you're
2353 * @param string $index
2356 public function useIndexClause( $index ) {
2361 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2362 * is only needed because a) MySQL must be as efficient as possible due to
2363 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2364 * which index to pick. Anyway, other databases might have different
2365 * indexes on a given table. So don't bother overriding this unless you're
2367 * @param string $index
2370 public function ignoreIndexClause( $index ) {
2374 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2375 if ( count( $rows ) == 0 ) {
2380 if ( !is_array( reset( $rows ) ) ) {
2385 $this->startAtomic( $fname );
2386 $affectedRowCount = 0;
2387 foreach ( $rows as $row ) {
2388 // Delete rows which collide with this one
2389 $indexWhereClauses = [];
2390 foreach ( $uniqueIndexes as $index ) {
2391 $indexColumns = (array)$index;
2392 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2393 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2394 throw new DBUnexpectedError(
2396 'New record does not provide all values for unique key (' .
2397 implode( ', ', $indexColumns ) . ')'
2399 } elseif ( in_array( null, $indexRowValues, true ) ) {
2400 throw new DBUnexpectedError(
2402 'New record has a null value for unique key (' .
2403 implode( ', ', $indexColumns ) . ')'
2406 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2409 if ( $indexWhereClauses ) {
2410 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2411 $affectedRowCount +
= $this->affectedRows();
2414 // Now insert the row
2415 $this->insert( $table, $row, $fname );
2416 $affectedRowCount +
= $this->affectedRows();
2418 $this->endAtomic( $fname );
2419 $this->affectedRowCount
= $affectedRowCount;
2420 } catch ( Exception
$e ) {
2421 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2427 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2430 * @param string $table Table name
2431 * @param array|string $rows Row(s) to insert
2432 * @param string $fname Caller function name
2434 * @return ResultWrapper
2436 protected function nativeReplace( $table, $rows, $fname ) {
2437 $table = $this->tableName( $table );
2440 if ( !is_array( reset( $rows ) ) ) {
2444 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2447 foreach ( $rows as $row ) {
2454 $sql .= '(' . $this->makeList( $row ) . ')';
2457 return $this->query( $sql, $fname );
2460 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2463 if ( !count( $rows ) ) {
2464 return true; // nothing to do
2467 if ( !is_array( reset( $rows ) ) ) {
2471 if ( count( $uniqueIndexes ) ) {
2472 $clauses = []; // list WHERE clauses that each identify a single row
2473 foreach ( $rows as $row ) {
2474 foreach ( $uniqueIndexes as $index ) {
2475 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2476 $rowKey = []; // unique key to this row
2477 foreach ( $index as $column ) {
2478 $rowKey[$column] = $row[$column];
2480 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2483 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2488 $affectedRowCount = 0;
2490 $this->startAtomic( $fname );
2491 # Update any existing conflicting row(s)
2492 if ( $where !== false ) {
2493 $ok = $this->update( $table, $set, $where, $fname );
2494 $affectedRowCount +
= $this->affectedRows();
2498 # Now insert any non-conflicting row(s)
2499 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2500 $affectedRowCount +
= $this->affectedRows();
2501 $this->endAtomic( $fname );
2502 $this->affectedRowCount
= $affectedRowCount;
2503 } catch ( Exception
$e ) {
2504 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2511 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2515 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2518 $delTable = $this->tableName( $delTable );
2519 $joinTable = $this->tableName( $joinTable );
2520 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2521 if ( $conds != '*' ) {
2522 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2526 $this->query( $sql, $fname );
2529 public function textFieldSize( $table, $field ) {
2530 $table = $this->tableName( $table );
2531 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2532 $res = $this->query( $sql, __METHOD__
);
2533 $row = $this->fetchObject( $res );
2537 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2546 public function delete( $table, $conds, $fname = __METHOD__
) {
2548 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2551 $table = $this->tableName( $table );
2552 $sql = "DELETE FROM $table";
2554 if ( $conds != '*' ) {
2555 if ( is_array( $conds ) ) {
2556 $conds = $this->makeList( $conds, self
::LIST_AND
);
2558 $sql .= ' WHERE ' . $conds;
2561 return $this->query( $sql, $fname );
2564 final public function insertSelect(
2565 $destTable, $srcTable, $varMap, $conds,
2566 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2568 static $hints = [ 'NO_AUTO_COLUMNS' ];
2570 $insertOptions = (array)$insertOptions;
2571 $selectOptions = (array)$selectOptions;
2573 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2574 // For massive migrations with downtime, we don't want to select everything
2575 // into memory and OOM, so do all this native on the server side if possible.
2576 return $this->nativeInsertSelect(
2582 array_diff( $insertOptions, $hints ),
2588 return $this->nonNativeInsertSelect(
2594 array_diff( $insertOptions, $hints ),
2601 * @param array $insertOptions INSERT options
2602 * @param array $selectOptions SELECT options
2603 * @return bool Whether an INSERT SELECT with these options will be replication safe
2606 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2611 * Implementation of insertSelect() based on select() and insert()
2613 * @see IDatabase::insertSelect()
2615 * @param string $destTable
2616 * @param string|array $srcTable
2617 * @param array $varMap
2618 * @param array $conds
2619 * @param string $fname
2620 * @param array $insertOptions
2621 * @param array $selectOptions
2622 * @param array $selectJoinConds
2625 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2626 $fname = __METHOD__
,
2627 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2629 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2630 // on only the master (without needing row-based-replication). It also makes it easy to
2631 // know how big the INSERT is going to be.
2633 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2634 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2636 $selectOptions[] = 'FOR UPDATE';
2637 $res = $this->select(
2638 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2645 $affectedRowCount = 0;
2646 $this->startAtomic( $fname );
2649 foreach ( $res as $row ) {
2650 $rows[] = (array)$row;
2652 // Avoid inserts that are too huge
2653 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2654 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2658 $affectedRowCount +
= $this->affectedRows();
2662 if ( $rows && $ok ) {
2663 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2665 $affectedRowCount +
= $this->affectedRows();
2669 $this->endAtomic( $fname );
2670 $this->affectedRowCount
= $affectedRowCount;
2672 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2675 } catch ( Exception
$e ) {
2676 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2682 * Native server-side implementation of insertSelect() for situations where
2683 * we don't want to select everything into memory
2685 * @see IDatabase::insertSelect()
2686 * @param string $destTable
2687 * @param string|array $srcTable
2688 * @param array $varMap
2689 * @param array $conds
2690 * @param string $fname
2691 * @param array $insertOptions
2692 * @param array $selectOptions
2693 * @param array $selectJoinConds
2696 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2697 $fname = __METHOD__
,
2698 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2700 $destTable = $this->tableName( $destTable );
2702 if ( !is_array( $insertOptions ) ) {
2703 $insertOptions = [ $insertOptions ];
2706 $insertOptions = $this->makeInsertOptions( $insertOptions );
2708 $selectSql = $this->selectSQLText(
2710 array_values( $varMap ),
2717 $sql = "INSERT $insertOptions" .
2718 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2721 return $this->query( $sql, $fname );
2725 * Construct a LIMIT query with optional offset. This is used for query
2726 * pages. The SQL should be adjusted so that only the first $limit rows
2727 * are returned. If $offset is provided as well, then the first $offset
2728 * rows should be discarded, and the next $limit rows should be returned.
2729 * If the result of the query is not ordered, then the rows to be returned
2730 * are theoretically arbitrary.
2732 * $sql is expected to be a SELECT, if that makes a difference.
2734 * The version provided by default works in MySQL and SQLite. It will very
2735 * likely need to be overridden for most other DBMSes.
2737 * @param string $sql SQL query we will append the limit too
2738 * @param int $limit The SQL limit
2739 * @param int|bool $offset The SQL offset (default false)
2740 * @throws DBUnexpectedError
2743 public function limitResult( $sql, $limit, $offset = false ) {
2744 if ( !is_numeric( $limit ) ) {
2745 throw new DBUnexpectedError( $this,
2746 "Invalid non-numeric limit passed to limitResult()\n" );
2749 return "$sql LIMIT "
2750 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2754 public function unionSupportsOrderAndLimit() {
2755 return true; // True for almost every DB supported
2758 public function unionQueries( $sqls, $all ) {
2759 $glue = $all ?
') UNION ALL (' : ') UNION (';
2761 return '(' . implode( $glue, $sqls ) . ')';
2764 public function unionConditionPermutations(
2765 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2766 $options = [], $join_conds = []
2768 // First, build the Cartesian product of $permute_conds
2770 foreach ( $permute_conds as $field => $values ) {
2772 // Skip empty $values
2775 $values = array_unique( $values ); // For sanity
2777 foreach ( $conds as $cond ) {
2778 foreach ( $values as $value ) {
2779 $cond[$field] = $value;
2780 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2786 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2788 // If there's just one condition and no subordering, hand off to
2789 // selectSQLText directly.
2790 if ( count( $conds ) === 1 &&
2791 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2793 return $this->selectSQLText(
2794 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2798 // Otherwise, we need to pull out the order and limit to apply after
2799 // the union. Then build the SQL queries for each set of conditions in
2800 // $conds. Then union them together (using UNION ALL, because the
2801 // product *should* already be distinct).
2802 $orderBy = $this->makeOrderBy( $options );
2803 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2804 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2805 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2806 if ( !$this->unionSupportsOrderAndLimit() ) {
2807 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2809 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2810 $options['ORDER BY'] = $options['INNER ORDER BY'];
2812 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2813 // We need to increase the limit by the offset rather than
2814 // using the offset directly, otherwise it'll skip incorrectly
2815 // in the subqueries.
2816 $options['LIMIT'] = $limit +
$offset;
2817 unset( $options['OFFSET'] );
2822 foreach ( $conds as $cond ) {
2823 $sqls[] = $this->selectSQLText(
2824 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2827 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2828 if ( $limit !== null ) {
2829 $sql = $this->limitResult( $sql, $limit, $offset );
2835 public function conditional( $cond, $trueVal, $falseVal ) {
2836 if ( is_array( $cond ) ) {
2837 $cond = $this->makeList( $cond, self
::LIST_AND
);
2840 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2843 public function strreplace( $orig, $old, $new ) {
2844 return "REPLACE({$orig}, {$old}, {$new})";
2847 public function getServerUptime() {
2851 public function wasDeadlock() {
2855 public function wasLockTimeout() {
2859 public function wasErrorReissuable() {
2863 public function wasReadOnlyError() {
2868 * Do not use this method outside of Database/DBError classes
2870 * @param int|string $errno
2871 * @return bool Whether the given query error was a connection drop
2873 public function wasConnectionError( $errno ) {
2877 public function deadlockLoop() {
2878 $args = func_get_args();
2879 $function = array_shift( $args );
2880 $tries = self
::DEADLOCK_TRIES
;
2882 $this->begin( __METHOD__
);
2885 /** @var Exception $e */
2889 $retVal = call_user_func_array( $function, $args );
2891 } catch ( DBQueryError
$e ) {
2892 if ( $this->wasDeadlock() ) {
2893 // Retry after a randomized delay
2894 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2896 // Throw the error back up
2900 } while ( --$tries > 0 );
2902 if ( $tries <= 0 ) {
2903 // Too many deadlocks; give up
2904 $this->rollback( __METHOD__
);
2907 $this->commit( __METHOD__
);
2913 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2914 # Real waits are implemented in the subclass.
2918 public function getReplicaPos() {
2923 public function getMasterPos() {
2928 public function serverIsReadOnly() {
2932 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2933 if ( !$this->trxLevel
) {
2934 throw new DBUnexpectedError( $this, "No transaction is active." );
2936 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2939 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2940 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2941 if ( !$this->trxLevel
) {
2942 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2946 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2947 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2948 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2949 // an implicit commit of all peer databases. This is true even if a transaction has
2950 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2951 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2953 // No transaction is active nor will start implicitly, so make one for this callback
2954 $this->startAtomic( __METHOD__
);
2956 call_user_func( $callback );
2957 $this->endAtomic( __METHOD__
);
2958 } catch ( Exception
$e ) {
2959 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2965 final public function setTransactionListener( $name, callable
$callback = null ) {
2967 $this->trxRecurringCallbacks
[$name] = $callback;
2969 unset( $this->trxRecurringCallbacks
[$name] );
2974 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2976 * This method should not be used outside of Database/LoadBalancer
2978 * @param bool $suppress
2981 final public function setTrxEndCallbackSuppression( $suppress ) {
2982 $this->trxEndCallbacksSuppressed
= $suppress;
2986 * Actually run and consume any "on transaction idle/resolution" callbacks.
2988 * This method should not be used outside of Database/LoadBalancer
2990 * @param int $trigger IDatabase::TRIGGER_* constant
2994 public function runOnTransactionIdleCallbacks( $trigger ) {
2995 if ( $this->trxEndCallbacksSuppressed
) {
2999 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3000 /** @var Exception $e */
3001 $e = null; // first exception
3002 do { // callbacks may add callbacks :)
3003 $callbacks = array_merge(
3004 $this->trxIdleCallbacks
,
3005 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3007 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3008 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3009 foreach ( $callbacks as $callback ) {
3011 list( $phpCallback ) = $callback;
3012 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3013 call_user_func_array( $phpCallback, [ $trigger ] );
3015 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3017 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3019 } catch ( Exception
$ex ) {
3020 call_user_func( $this->errorLogger
, $ex );
3022 // Some callbacks may use startAtomic/endAtomic, so make sure
3023 // their transactions are ended so other callbacks don't fail
3024 if ( $this->trxLevel() ) {
3025 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3029 } while ( count( $this->trxIdleCallbacks
) );
3031 if ( $e instanceof Exception
) {
3032 throw $e; // re-throw any first exception
3037 * Actually run and consume any "on transaction pre-commit" callbacks.
3039 * This method should not be used outside of Database/LoadBalancer
3044 public function runOnTransactionPreCommitCallbacks() {
3045 $e = null; // first exception
3046 do { // callbacks may add callbacks :)
3047 $callbacks = $this->trxPreCommitCallbacks
;
3048 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3049 foreach ( $callbacks as $callback ) {
3051 list( $phpCallback ) = $callback;
3052 call_user_func( $phpCallback );
3053 } catch ( Exception
$ex ) {
3054 call_user_func( $this->errorLogger
, $ex );
3058 } while ( count( $this->trxPreCommitCallbacks
) );
3060 if ( $e instanceof Exception
) {
3061 throw $e; // re-throw any first exception
3066 * Actually run any "transaction listener" callbacks.
3068 * This method should not be used outside of Database/LoadBalancer
3070 * @param int $trigger IDatabase::TRIGGER_* constant
3074 public function runTransactionListenerCallbacks( $trigger ) {
3075 if ( $this->trxEndCallbacksSuppressed
) {
3079 /** @var Exception $e */
3080 $e = null; // first exception
3082 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3084 $phpCallback( $trigger, $this );
3085 } catch ( Exception
$ex ) {
3086 call_user_func( $this->errorLogger
, $ex );
3091 if ( $e instanceof Exception
) {
3092 throw $e; // re-throw any first exception
3096 final public function startAtomic( $fname = __METHOD__
) {
3097 if ( !$this->trxLevel
) {
3098 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3099 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3100 // in all changes being in one transaction to keep requests transactional.
3101 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3102 $this->trxAutomaticAtomic
= true;
3106 $this->trxAtomicLevels
[] = $fname;
3109 final public function endAtomic( $fname = __METHOD__
) {
3110 if ( !$this->trxLevel
) {
3111 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3113 if ( !$this->trxAtomicLevels ||
3114 array_pop( $this->trxAtomicLevels
) !== $fname
3116 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3119 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3120 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3124 final public function doAtomicSection( $fname, callable
$callback ) {
3125 $this->startAtomic( $fname );
3127 $res = call_user_func_array( $callback, [ $this, $fname ] );
3128 } catch ( Exception
$e ) {
3129 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3132 $this->endAtomic( $fname );
3137 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3138 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3139 if ( $this->trxLevel
) {
3140 if ( $this->trxAtomicLevels
) {
3141 $levels = implode( ', ', $this->trxAtomicLevels
);
3142 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3143 throw new DBUnexpectedError( $this, $msg );
3144 } elseif ( !$this->trxAutomatic
) {
3145 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3146 throw new DBUnexpectedError( $this, $msg );
3148 // @TODO: make this an exception at some point
3149 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3150 $this->queryLogger
->error( $msg );
3151 return; // join the main transaction set
3153 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3154 // @TODO: make this an exception at some point
3155 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3156 $this->queryLogger
->error( $msg );
3157 return; // let any writes be in the main transaction
3160 // Avoid fatals if close() was called
3161 $this->assertOpen();
3163 $this->doBegin( $fname );
3164 $this->trxTimestamp
= microtime( true );
3165 $this->trxFname
= $fname;
3166 $this->trxDoneWrites
= false;
3167 $this->trxAutomaticAtomic
= false;
3168 $this->trxAtomicLevels
= [];
3169 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3170 $this->trxWriteDuration
= 0.0;
3171 $this->trxWriteQueryCount
= 0;
3172 $this->trxWriteAffectedRows
= 0;
3173 $this->trxWriteAdjDuration
= 0.0;
3174 $this->trxWriteAdjQueryCount
= 0;
3175 $this->trxWriteCallers
= [];
3176 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3177 // Get an estimate of the replica DB lag before then, treating estimate staleness
3178 // as lag itself just to be safe
3179 $status = $this->getApproximateLagStatus();
3180 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3181 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3182 // caller will think its OK to muck around with the transaction just because startAtomic()
3183 // has not yet completed (e.g. setting trxAtomicLevels).
3184 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3188 * Issues the BEGIN command to the database server.
3190 * @see Database::begin()
3191 * @param string $fname
3193 protected function doBegin( $fname ) {
3194 $this->query( 'BEGIN', $fname );
3195 $this->trxLevel
= 1;
3198 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3199 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3200 // There are still atomic sections open. This cannot be ignored
3201 $levels = implode( ', ', $this->trxAtomicLevels
);
3202 throw new DBUnexpectedError(
3204 "$fname: Got COMMIT while atomic sections $levels are still open."
3208 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3209 if ( !$this->trxLevel
) {
3210 return; // nothing to do
3211 } elseif ( !$this->trxAutomatic
) {
3212 throw new DBUnexpectedError(
3214 "$fname: Flushing an explicit transaction, getting out of sync."
3218 if ( !$this->trxLevel
) {
3219 $this->queryLogger
->error(
3220 "$fname: No transaction to commit, something got out of sync." );
3221 return; // nothing to do
3222 } elseif ( $this->trxAutomatic
) {
3223 // @TODO: make this an exception at some point
3224 $msg = "$fname: Explicit commit of implicit transaction.";
3225 $this->queryLogger
->error( $msg );
3226 return; // wait for the main transaction set commit round
3230 // Avoid fatals if close() was called
3231 $this->assertOpen();
3233 $this->runOnTransactionPreCommitCallbacks();
3234 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3235 $this->doCommit( $fname );
3236 if ( $this->trxDoneWrites
) {
3237 $this->lastWriteTime
= microtime( true );
3238 $this->trxProfiler
->transactionWritingOut(
3243 $this->trxWriteAffectedRows
3247 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3248 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3252 * Issues the COMMIT command to the database server.
3254 * @see Database::commit()
3255 * @param string $fname
3257 protected function doCommit( $fname ) {
3258 if ( $this->trxLevel
) {
3259 $this->query( 'COMMIT', $fname );
3260 $this->trxLevel
= 0;
3264 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3265 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3266 if ( !$this->trxLevel
) {
3267 return; // nothing to do
3270 if ( !$this->trxLevel
) {
3271 $this->queryLogger
->error(
3272 "$fname: No transaction to rollback, something got out of sync." );
3273 return; // nothing to do
3274 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3275 throw new DBUnexpectedError(
3277 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3282 // Avoid fatals if close() was called
3283 $this->assertOpen();
3285 $this->doRollback( $fname );
3286 $this->trxAtomicLevels
= [];
3287 if ( $this->trxDoneWrites
) {
3288 $this->trxProfiler
->transactionWritingOut(
3295 $this->trxIdleCallbacks
= []; // clear
3296 $this->trxPreCommitCallbacks
= []; // clear
3298 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3299 } catch ( Exception
$e ) {
3300 // already logged; finish and let LoadBalancer move on during mass-rollback
3303 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3304 } catch ( Exception
$e ) {
3305 // already logged; let LoadBalancer move on during mass-rollback
3308 $this->affectedRowCount
= 0; // for the sake of consistency
3312 * Issues the ROLLBACK command to the database server.
3314 * @see Database::rollback()
3315 * @param string $fname
3317 protected function doRollback( $fname ) {
3318 if ( $this->trxLevel
) {
3319 # Disconnects cause rollback anyway, so ignore those errors
3320 $ignoreErrors = true;
3321 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3322 $this->trxLevel
= 0;
3326 public function flushSnapshot( $fname = __METHOD__
) {
3327 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3328 // This only flushes transactions to clear snapshots, not to write data
3329 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3330 throw new DBUnexpectedError(
3332 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3336 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3339 public function explicitTrxActive() {
3340 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3343 public function duplicateTableStructure(
3344 $oldName, $newName, $temporary = false, $fname = __METHOD__
3346 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3349 public function listTables( $prefix = null, $fname = __METHOD__
) {
3350 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3353 public function listViews( $prefix = null, $fname = __METHOD__
) {
3354 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3357 public function timestamp( $ts = 0 ) {
3358 $t = new ConvertibleTimestamp( $ts );
3359 // Let errors bubble up to avoid putting garbage in the DB
3360 return $t->getTimestamp( TS_MW
);
3363 public function timestampOrNull( $ts = null ) {
3364 if ( is_null( $ts ) ) {
3367 return $this->timestamp( $ts );
3371 public function affectedRows() {
3372 return ( $this->affectedRowCount
=== null )
3373 ?
$this->fetchAffectedRowCount() // default to driver value
3374 : $this->affectedRowCount
;
3378 * @return int Number of retrieved rows according to the driver
3380 abstract protected function fetchAffectedRowCount();
3383 * Take the result from a query, and wrap it in a ResultWrapper if
3384 * necessary. Boolean values are passed through as is, to indicate success
3385 * of write queries or failure.
3387 * Once upon a time, Database::query() returned a bare MySQL result
3388 * resource, and it was necessary to call this function to convert it to
3389 * a wrapper. Nowadays, raw database objects are never exposed to external
3390 * callers, so this is unnecessary in external code.
3392 * @param bool|ResultWrapper|resource|object $result
3393 * @return bool|ResultWrapper
3395 protected function resultObject( $result ) {
3398 } elseif ( $result instanceof ResultWrapper
) {
3400 } elseif ( $result === true ) {
3401 // Successful write query
3404 return new ResultWrapper( $this, $result );
3408 public function ping( &$rtt = null ) {
3409 // Avoid hitting the server if it was hit recently
3410 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3411 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3412 $rtt = $this->rttEstimate
;
3413 return true; // don't care about $rtt
3417 // This will reconnect if possible or return false if not
3418 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3419 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3420 $this->restoreFlags( self
::RESTORE_PRIOR
);
3423 $rtt = $this->rttEstimate
;
3430 * Close existing database connection and open a new connection
3432 * @return bool True if new connection is opened successfully, false if error
3434 protected function reconnect() {
3435 $this->closeConnection();
3436 $this->opened
= false;
3437 $this->conn
= false;
3439 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3440 $this->lastPing
= microtime( true );
3442 } catch ( DBConnectionError
$e ) {
3449 public function getSessionLagStatus() {
3450 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3454 * Get the replica DB lag when the current transaction started
3456 * This is useful when transactions might use snapshot isolation
3457 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3458 * is this lag plus transaction duration. If they don't, it is still
3459 * safe to be pessimistic. This returns null if there is no transaction.
3461 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3464 protected function getTransactionLagStatus() {
3465 return $this->trxLevel
3466 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3471 * Get a replica DB lag estimate for this server
3473 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3476 protected function getApproximateLagStatus() {
3478 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3479 'since' => microtime( true )
3484 * Merge the result of getSessionLagStatus() for several DBs
3485 * using the most pessimistic values to estimate the lag of
3486 * any data derived from them in combination
3488 * This is information is useful for caching modules
3490 * @see WANObjectCache::set()
3491 * @see WANObjectCache::getWithSetCallback()
3493 * @param IDatabase $db1
3494 * @param IDatabase $db2 [optional]
3495 * @return array Map of values:
3496 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3497 * - since: oldest UNIX timestamp of any of the DB lag estimates
3498 * - pending: whether any of the DBs have uncommitted changes
3502 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3503 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3504 foreach ( func_get_args() as $db ) {
3505 /** @var IDatabase $db */
3506 $status = $db->getSessionLagStatus();
3507 if ( $status['lag'] === false ) {
3508 $res['lag'] = false;
3509 } elseif ( $res['lag'] !== false ) {
3510 $res['lag'] = max( $res['lag'], $status['lag'] );
3512 $res['since'] = min( $res['since'], $status['since'] );
3513 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3519 public function getLag() {
3523 public function maxListLen() {
3527 public function encodeBlob( $b ) {
3531 public function decodeBlob( $b ) {
3532 if ( $b instanceof Blob
) {
3538 public function setSessionOptions( array $options ) {
3541 public function sourceFile(
3543 callable
$lineCallback = null,
3544 callable
$resultCallback = null,
3546 callable
$inputCallback = null
3548 Wikimedia\
suppressWarnings();
3549 $fp = fopen( $filename, 'r' );
3550 Wikimedia\restoreWarnings
();
3552 if ( false === $fp ) {
3553 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3557 $fname = __METHOD__
. "( $filename )";
3561 $error = $this->sourceStream(
3562 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3563 } catch ( Exception
$e ) {
3573 public function setSchemaVars( $vars ) {
3574 $this->schemaVars
= $vars;
3577 public function sourceStream(
3579 callable
$lineCallback = null,
3580 callable
$resultCallback = null,
3581 $fname = __METHOD__
,
3582 callable
$inputCallback = null
3584 $delimiterReset = new ScopedCallback(
3585 function ( $delimiter ) {
3586 $this->delimiter
= $delimiter;
3588 [ $this->delimiter
]
3592 while ( !feof( $fp ) ) {
3593 if ( $lineCallback ) {
3594 call_user_func( $lineCallback );
3597 $line = trim( fgets( $fp ) );
3599 if ( $line == '' ) {
3603 if ( '-' == $line[0] && '-' == $line[1] ) {
3611 $done = $this->streamStatementEnd( $cmd, $line );
3615 if ( $done ||
feof( $fp ) ) {
3616 $cmd = $this->replaceVars( $cmd );
3618 if ( $inputCallback ) {
3619 $callbackResult = call_user_func( $inputCallback, $cmd );
3621 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3622 $cmd = $callbackResult;
3627 $res = $this->query( $cmd, $fname );
3629 if ( $resultCallback ) {
3630 call_user_func( $resultCallback, $res, $this );
3633 if ( false === $res ) {
3634 $err = $this->lastError();
3636 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3643 ScopedCallback
::consume( $delimiterReset );
3648 * Called by sourceStream() to check if we've reached a statement end
3650 * @param string &$sql SQL assembled so far
3651 * @param string &$newLine New line about to be added to $sql
3652 * @return bool Whether $newLine contains end of the statement
3654 public function streamStatementEnd( &$sql, &$newLine ) {
3655 if ( $this->delimiter
) {
3657 $newLine = preg_replace(
3658 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3659 if ( $newLine != $prev ) {
3668 * Database independent variable replacement. Replaces a set of variables
3669 * in an SQL statement with their contents as given by $this->getSchemaVars().
3671 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3673 * - '{$var}' should be used for text and is passed through the database's
3675 * - `{$var}` should be used for identifiers (e.g. table and database names).
3676 * It is passed through the database's addIdentifierQuotes method which
3677 * can be overridden if the database uses something other than backticks.
3678 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3679 * database's tableName method.
3680 * - / *i* / passes the name that follows through the database's indexName method.
3681 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3682 * its use should be avoided. In 1.24 and older, string encoding was applied.
3684 * @param string $ins SQL statement to replace variables in
3685 * @return string The new SQL statement with variables replaced
3687 protected function replaceVars( $ins ) {
3688 $vars = $this->getSchemaVars();
3689 return preg_replace_callback(
3691 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3692 \'\{\$ (\w+) }\' | # 3. addQuotes
3693 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3694 /\*\$ (\w+) \*/ # 5. leave unencoded
3696 function ( $m ) use ( $vars ) {
3697 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3698 // check for both nonexistent keys *and* the empty string.
3699 if ( isset( $m[1] ) && $m[1] !== '' ) {
3700 if ( $m[1] === 'i' ) {
3701 return $this->indexName( $m[2] );
3703 return $this->tableName( $m[2] );
3705 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3706 return $this->addQuotes( $vars[$m[3]] );
3707 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3708 return $this->addIdentifierQuotes( $vars[$m[4]] );
3709 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3710 return $vars[$m[5]];
3720 * Get schema variables. If none have been set via setSchemaVars(), then
3721 * use some defaults from the current object.
3725 protected function getSchemaVars() {
3726 if ( $this->schemaVars
) {
3727 return $this->schemaVars
;
3729 return $this->getDefaultSchemaVars();
3734 * Get schema variables to use if none have been set via setSchemaVars().
3736 * Override this in derived classes to provide variables for tables.sql
3737 * and SQL patch files.
3741 protected function getDefaultSchemaVars() {
3745 public function lockIsFree( $lockName, $method ) {
3746 // RDBMs methods for checking named locks may or may not count this thread itself.
3747 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3748 // the behavior choosen by the interface for this method.
3749 return !isset( $this->namedLocksHeld
[$lockName] );
3752 public function lock( $lockName, $method, $timeout = 5 ) {
3753 $this->namedLocksHeld
[$lockName] = 1;
3758 public function unlock( $lockName, $method ) {
3759 unset( $this->namedLocksHeld
[$lockName] );
3764 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3765 if ( $this->writesOrCallbacksPending() ) {
3766 // This only flushes transactions to clear snapshots, not to write data
3767 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3768 throw new DBUnexpectedError(
3770 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3774 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3778 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3779 if ( $this->trxLevel() ) {
3780 // There is a good chance an exception was thrown, causing any early return
3781 // from the caller. Let any error handler get a chance to issue rollback().
3782 // If there isn't one, let the error bubble up and trigger server-side rollback.
3783 $this->onTransactionResolution(
3784 function () use ( $lockKey, $fname ) {
3785 $this->unlock( $lockKey, $fname );
3790 $this->unlock( $lockKey, $fname );
3794 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3799 public function namedLocksEnqueue() {
3803 public function tableLocksHaveTransactionScope() {
3807 final public function lockTables( array $read, array $write, $method ) {
3808 if ( $this->writesOrCallbacksPending() ) {
3809 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3812 if ( $this->tableLocksHaveTransactionScope() ) {
3813 $this->startAtomic( $method );
3816 return $this->doLockTables( $read, $write, $method );
3820 * Helper function for lockTables() that handles the actual table locking
3822 * @param array $read Array of tables to lock for read access
3823 * @param array $write Array of tables to lock for write access
3824 * @param string $method Name of caller
3827 protected function doLockTables( array $read, array $write, $method ) {
3831 final public function unlockTables( $method ) {
3832 if ( $this->tableLocksHaveTransactionScope() ) {
3833 $this->endAtomic( $method );
3835 return true; // locks released on COMMIT/ROLLBACK
3838 return $this->doUnlockTables( $method );
3842 * Helper function for unlockTables() that handles the actual table unlocking
3844 * @param string $method Name of caller
3847 protected function doUnlockTables( $method ) {
3853 * @param string $tableName
3854 * @param string $fName
3855 * @return bool|ResultWrapper
3858 public function dropTable( $tableName, $fName = __METHOD__
) {
3859 if ( !$this->tableExists( $tableName, $fName ) ) {
3862 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3864 return $this->query( $sql, $fName );
3867 public function getInfinity() {
3871 public function encodeExpiry( $expiry ) {
3872 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3873 ?
$this->getInfinity()
3874 : $this->timestamp( $expiry );
3877 public function decodeExpiry( $expiry, $format = TS_MW
) {
3878 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3882 return ConvertibleTimestamp
::convert( $format, $expiry );
3885 public function setBigSelects( $value = true ) {
3889 public function isReadOnly() {
3890 return ( $this->getReadOnlyReason() !== false );
3894 * @return string|bool Reason this DB is read-only or false if it is not
3896 protected function getReadOnlyReason() {
3897 $reason = $this->getLBInfo( 'readOnlyReason' );
3899 return is_string( $reason ) ?
$reason : false;
3902 public function setTableAliases( array $aliases ) {
3903 $this->tableAliases
= $aliases;
3907 * Get the underlying binding connection handle
3909 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3910 * This catches broken callers than catch and ignore disconnection exceptions.
3911 * Unlike checking isOpen(), this is safe to call inside of open().
3914 * @throws DBUnexpectedError
3917 protected function getBindingHandle() {
3918 if ( !$this->conn
) {
3919 throw new DBUnexpectedError(
3921 'DB connection was already closed or the connection dropped.'
3932 public function __toString() {
3933 return (string)$this->conn
;
3937 * Make sure that copies do not share the same client binding handle
3938 * @throws DBConnectionError
3940 public function __clone() {
3941 $this->connLogger
->warning(
3942 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3943 ( new RuntimeException() )->getTraceAsString()
3946 if ( $this->isOpen() ) {
3947 // Open a new connection resource without messing with the old one
3948 $this->opened
= false;
3949 $this->conn
= false;
3950 $this->trxEndCallbacks
= []; // don't copy
3951 $this->handleSessionLoss(); // no trx or locks anymore
3952 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3953 $this->lastPing
= microtime( true );
3958 * Called by serialize. Throw an exception when DB connection is serialized.
3959 * This causes problems on some database engines because the connection is
3960 * not restored on unserialize.
3962 public function __sleep() {
3963 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3964 'the connection is not restored on wakeup.' );
3968 * Run a few simple sanity checks and close dangling connections
3970 public function __destruct() {
3971 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3972 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3975 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3976 if ( $danglingWriters ) {
3977 $fnames = implode( ', ', $danglingWriters );
3978 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3981 if ( $this->conn
) {
3982 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3983 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3984 Wikimedia\
suppressWarnings();
3985 $this->closeConnection();
3986 Wikimedia\restoreWarnings
();
3987 $this->conn
= false;
3988 $this->opened
= false;
3993 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3994 class_alias( Database
::class, 'Database' ); // b/c global alias