3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
42 * Relational database abstraction object
47 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
48 /** Number of times to re-try an operation in case of deadlock */
49 const DEADLOCK_TRIES
= 4;
50 /** Minimum time to wait before retry, in microseconds */
51 const DEADLOCK_DELAY_MIN
= 500000;
52 /** Maximum time to wait before retry */
53 const DEADLOCK_DELAY_MAX
= 1500000;
55 /** How long before it is worth doing a dummy query to test the connection */
57 const PING_QUERY
= 'SELECT 1 AS ping';
59 const TINY_WRITE_SEC
= 0.010;
60 const SLOW_WRITE_SEC
= 0.500;
61 const SMALL_WRITE_ROWS
= 100;
63 /** @var string Whether lock granularity is on the level of the entire database */
64 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
66 /** @var int New Database instance will not be connected yet when returned */
67 const NEW_UNCONNECTED
= 0;
68 /** @var int New Database instance will already be connected when returned */
69 const NEW_CONNECTED
= 1;
71 /** @var string SQL query */
72 protected $lastQuery = '';
73 /** @var float|bool UNIX timestamp of last write query */
74 protected $lastWriteTime = false;
75 /** @var string|bool */
76 protected $phpError = false;
77 /** @var string Server that this instance is currently connected to */
79 /** @var string User that this instance is currently connected under the name of */
81 /** @var string Password used to establish the current connection */
83 /** @var string Database that this instance is currently connected to */
85 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
86 protected $tableAliases = [];
87 /** @var string[] Map of (index alias => index) */
88 protected $indexAliases = [];
89 /** @var bool Whether this PHP instance is for a CLI script */
91 /** @var string Agent name for query profiling */
93 /** @var array Parameters used by initConnection() to establish a connection */
94 protected $connectionParams = [];
95 /** @var BagOStuff APC cache */
97 /** @var LoggerInterface */
98 protected $connLogger;
99 /** @var LoggerInterface */
100 protected $queryLogger;
101 /** @var callback Error logging callback */
102 protected $errorLogger;
104 /** @var resource|null Database connection */
105 protected $conn = null;
107 protected $opened = false;
109 /** @var array[] List of (callable, method name) */
110 protected $trxIdleCallbacks = [];
111 /** @var array[] List of (callable, method name) */
112 protected $trxPreCommitCallbacks = [];
113 /** @var array[] List of (callable, method name) */
114 protected $trxEndCallbacks = [];
115 /** @var callable[] Map of (name => callable) */
116 protected $trxRecurringCallbacks = [];
117 /** @var bool Whether to suppress triggering of transaction end callbacks */
118 protected $trxEndCallbacksSuppressed = false;
121 protected $tablePrefix = '';
123 protected $schema = '';
127 protected $lbInfo = [];
128 /** @var array|bool */
129 protected $schemaVars = false;
131 protected $sessionVars = [];
132 /** @var array|null */
133 protected $preparedArgs;
134 /** @var string|bool|null Stashed value of html_errors INI setting */
135 protected $htmlErrors;
137 protected $delimiter = ';';
138 /** @var DatabaseDomain */
139 protected $currentDomain;
140 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
141 protected $affectedRowCount;
144 * Either 1 if a transaction is active or 0 otherwise.
145 * The other Trx fields may not be meaningfull if this is 0.
149 protected $trxLevel = 0;
151 * Either a short hexidecimal string if a transaction is active or ""
154 * @see Database::trxLevel
156 protected $trxShortId = '';
158 * The UNIX time that the transaction started. Callers can assume that if
159 * snapshot isolation is used, then the data is *at least* up to date to that
160 * point (possibly more up-to-date since the first SELECT defines the snapshot).
163 * @see Database::trxLevel
165 private $trxTimestamp = null;
166 /** @var float Lag estimate at the time of BEGIN */
167 private $trxReplicaLag = null;
169 * Remembers the function name given for starting the most recent transaction via begin().
170 * Used to provide additional context for error reporting.
173 * @see Database::trxLevel
175 private $trxFname = null;
177 * Record if possible write queries were done in the last transaction started
180 * @see Database::trxLevel
182 private $trxDoneWrites = false;
184 * Record if the current transaction was started implicitly due to DBO_TRX being set.
187 * @see Database::trxLevel
189 private $trxAutomatic = false;
191 * Array of levels of atomicity within transactions
195 private $trxAtomicLevels = [];
197 * Record if the current transaction was started implicitly by Database::startAtomic
201 private $trxAutomaticAtomic = false;
203 * Track the write query callers of the current transaction
207 private $trxWriteCallers = [];
209 * @var float Seconds spent in write queries for the current transaction
211 private $trxWriteDuration = 0.0;
213 * @var int Number of write queries for the current transaction
215 private $trxWriteQueryCount = 0;
217 * @var int Number of rows affected by write queries for the current transaction
219 private $trxWriteAffectedRows = 0;
221 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
223 private $trxWriteAdjDuration = 0.0;
225 * @var int Number of write queries counted in trxWriteAdjDuration
227 private $trxWriteAdjQueryCount = 0;
229 * @var float RTT time estimate
231 private $rttEstimate = 0.0;
233 /** @var array Map of (name => 1) for locks obtained via lock() */
234 private $namedLocksHeld = [];
235 /** @var array Map of (table name => 1) for TEMPORARY tables */
236 protected $sessionTempTables = [];
238 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
239 private $lazyMasterHandle;
241 /** @var float UNIX timestamp */
242 protected $lastPing = 0.0;
244 /** @var int[] Prior flags member variable values */
245 private $priorFlags = [];
247 /** @var object|string Class name or object With profileIn/profileOut methods */
249 /** @var TransactionProfiler */
250 protected $trxProfiler;
253 protected $nonNativeInsertSelectBatchSize = 10000;
256 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
257 * @param array $params Parameters passed from Database::factory()
259 protected function __construct( array $params ) {
260 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
261 $this->connectionParams
[$name] = $params[$name];
264 $this->schema
= $params['schema'];
265 $this->tablePrefix
= $params['tablePrefix'];
267 $this->cliMode
= $params['cliMode'];
268 // Agent name is added to SQL queries in a comment, so make sure it can't break out
269 $this->agent
= str_replace( '/', '-', $params['agent'] );
271 $this->flags
= $params['flags'];
272 if ( $this->flags
& self
::DBO_DEFAULT
) {
273 if ( $this->cliMode
) {
274 $this->flags
&= ~self
::DBO_TRX
;
276 $this->flags |
= self
::DBO_TRX
;
280 $this->sessionVars
= $params['variables'];
282 $this->srvCache
= isset( $params['srvCache'] )
283 ?
$params['srvCache']
284 : new HashBagOStuff();
286 $this->profiler
= $params['profiler'];
287 $this->trxProfiler
= $params['trxProfiler'];
288 $this->connLogger
= $params['connLogger'];
289 $this->queryLogger
= $params['queryLogger'];
290 $this->errorLogger
= $params['errorLogger'];
292 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
293 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
296 // Set initial dummy domain until open() sets the final DB/prefix
297 $this->currentDomain
= DatabaseDomain
::newUnspecified();
301 * Initialize the connection to the database over the wire (or to local files)
303 * @throws LogicException
304 * @throws InvalidArgumentException
305 * @throws DBConnectionError
308 final public function initConnection() {
309 if ( $this->isOpen() ) {
310 throw new LogicException( __METHOD__
. ': already connected.' );
312 // Establish the connection
313 $this->doInitConnection();
314 // Set the domain object after open() sets the relevant fields
315 if ( $this->dbName
!= '' ) {
316 // Domains with server scope but a table prefix are not used by IDatabase classes
317 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
322 * Actually connect to the database over the wire (or to local files)
324 * @throws InvalidArgumentException
325 * @throws DBConnectionError
328 protected function doInitConnection() {
329 if ( strlen( $this->connectionParams
['user'] ) ) {
331 $this->connectionParams
['host'],
332 $this->connectionParams
['user'],
333 $this->connectionParams
['password'],
334 $this->connectionParams
['dbname']
337 throw new InvalidArgumentException( "No database user provided." );
342 * Construct a Database subclass instance given a database type and parameters
344 * This also connects to the database immediately upon object construction
346 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
347 * @param array $p Parameter map with keys:
348 * - host : The hostname of the DB server
349 * - user : The name of the database user the client operates under
350 * - password : The password for the database user
351 * - dbname : The name of the database to use where queries do not specify one.
352 * The database must exist or an error might be thrown. Setting this to the empty string
353 * will avoid any such errors and make the handle have no implicit database scope. This is
354 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
355 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
356 * in which user names and such are defined, e.g. users are database-specific in Postgres.
357 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
358 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
359 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
360 * recognized in queries. This can be used in place of schemas for handle site farms.
361 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
362 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
363 * flag in place UNLESS this this database simply acts as a key/value store.
364 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
365 * 'mysqli' driver; the old one 'mysql' has been removed.
366 * - variables: Optional map of session variables to set after connecting. This can be
367 * used to adjust lock timeouts or encoding modes and the like.
368 * - connLogger: Optional PSR-3 logger interface instance.
369 * - queryLogger: Optional PSR-3 logger interface instance.
370 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
371 * These will be called in query(), using a simplified version of the SQL that also
372 * includes the agent as a SQL comment.
373 * - trxProfiler: Optional TransactionProfiler instance.
374 * - errorLogger: Optional callback that takes an Exception and logs it.
375 * - cliMode: Whether to consider the execution context that of a CLI script.
376 * - agent: Optional name used to identify the end-user in query profiling/logging.
377 * - srvCache: Optional BagOStuff instance to an APC-style cache.
378 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
379 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
380 * @return Database|null If the database driver or extension cannot be found
381 * @throws InvalidArgumentException If the database driver or extension cannot be found
384 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
385 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
387 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
388 // Resolve some defaults for b/c
389 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
390 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
391 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
392 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
393 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
394 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
395 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
396 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
397 $p['cliMode'] = isset( $p['cliMode'] )
399 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
400 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
401 if ( !isset( $p['connLogger'] ) ) {
402 $p['connLogger'] = new NullLogger();
404 if ( !isset( $p['queryLogger'] ) ) {
405 $p['queryLogger'] = new NullLogger();
407 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
408 if ( !isset( $p['trxProfiler'] ) ) {
409 $p['trxProfiler'] = new TransactionProfiler();
411 if ( !isset( $p['errorLogger'] ) ) {
412 $p['errorLogger'] = function ( Exception
$e ) {
413 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
417 /** @var Database $conn */
418 $conn = new $class( $p );
419 if ( $connect == self
::NEW_CONNECTED
) {
420 $conn->initConnection();
430 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
431 * @param string|null $driver Optional name of a specific DB client driver
432 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
433 * @throws InvalidArgumentException
436 final public static function attributesFromType( $dbType, $driver = null ) {
437 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
439 $class = self
::getClass( $dbType, $driver );
441 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
445 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
446 * @param string|null $driver Optional name of a specific DB client driver
447 * @return string Database subclass name to use
448 * @throws InvalidArgumentException
450 private static function getClass( $dbType, $driver = null ) {
451 // For database types with built-in support, the below maps type to IDatabase
452 // implementations. For types with multipe driver implementations (PHP extensions),
453 // an array can be used, keyed by extension name. In case of an array, the
454 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
455 // we auto-detect the first available driver. For types without built-in support,
456 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
457 static $builtinTypes = [
458 'mssql' => DatabaseMssql
::class,
459 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
460 'sqlite' => DatabaseSqlite
::class,
461 'postgres' => DatabasePostgres
::class,
464 $dbType = strtolower( $dbType );
467 if ( isset( $builtinTypes[$dbType] ) ) {
468 $possibleDrivers = $builtinTypes[$dbType];
469 if ( is_string( $possibleDrivers ) ) {
470 $class = $possibleDrivers;
472 if ( (string)$driver !== '' ) {
473 if ( !isset( $possibleDrivers[$driver] ) ) {
474 throw new InvalidArgumentException( __METHOD__
.
475 " type '$dbType' does not support driver '{$driver}'" );
477 $class = $possibleDrivers[$driver];
480 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
481 if ( extension_loaded( $posDriver ) ) {
482 $class = $possibleClass;
489 $class = 'Database' . ucfirst( $dbType );
492 if ( $class === false ) {
493 throw new InvalidArgumentException( __METHOD__
.
494 " no viable database extension found for type '$dbType'" );
501 * @return array Map of (Database::ATTRIBUTE_* constant => value
504 protected static function getAttributes() {
509 * Set the PSR-3 logger interface to use for query logging. (The logger
510 * interfaces for connection logging and error logging can be set with the
513 * @param LoggerInterface $logger
515 public function setLogger( LoggerInterface
$logger ) {
516 $this->queryLogger
= $logger;
519 public function getServerInfo() {
520 return $this->getServerVersion();
523 public function bufferResults( $buffer = null ) {
524 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
525 if ( $buffer !== null ) {
527 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
528 : $this->setFlag( self
::DBO_NOBUFFER
);
535 * Turns on (false) or off (true) the automatic generation and sending
536 * of a "we're sorry, but there has been a database error" page on
537 * database errors. Default is on (false). When turned off, the
538 * code should use lastErrno() and lastError() to handle the
539 * situation as appropriate.
541 * Do not use this function outside of the Database classes.
543 * @param null|bool $ignoreErrors
544 * @return bool The previous value of the flag.
546 protected function ignoreErrors( $ignoreErrors = null ) {
547 $res = $this->getFlag( self
::DBO_IGNORE
);
548 if ( $ignoreErrors !== null ) {
549 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
550 if ( $ignoreErrors ) {
551 $this->flags |
= self
::DBO_IGNORE
;
553 $this->flags
&= ~self
::DBO_IGNORE
;
560 public function trxLevel() {
561 return $this->trxLevel
;
564 public function trxTimestamp() {
565 return $this->trxLevel ?
$this->trxTimestamp
: null;
568 public function tablePrefix( $prefix = null ) {
569 $old = $this->tablePrefix
;
570 if ( $prefix !== null ) {
571 $this->tablePrefix
= $prefix;
572 $this->currentDomain
= ( $this->dbName
!= '' )
573 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
574 : DatabaseDomain
::newUnspecified();
580 public function dbSchema( $schema = null ) {
581 $old = $this->schema
;
582 if ( $schema !== null ) {
583 $this->schema
= $schema;
589 public function getLBInfo( $name = null ) {
590 if ( is_null( $name ) ) {
591 return $this->lbInfo
;
593 if ( array_key_exists( $name, $this->lbInfo
) ) {
594 return $this->lbInfo
[$name];
601 public function setLBInfo( $name, $value = null ) {
602 if ( is_null( $value ) ) {
603 $this->lbInfo
= $name;
605 $this->lbInfo
[$name] = $value;
609 public function setLazyMasterHandle( IDatabase
$conn ) {
610 $this->lazyMasterHandle
= $conn;
614 * @return IDatabase|null
615 * @see setLazyMasterHandle()
618 protected function getLazyMasterHandle() {
619 return $this->lazyMasterHandle
;
622 public function implicitGroupby() {
626 public function implicitOrderby() {
630 public function lastQuery() {
631 return $this->lastQuery
;
634 public function doneWrites() {
635 return (bool)$this->lastWriteTime
;
638 public function lastDoneWrites() {
639 return $this->lastWriteTime ?
: false;
642 public function writesPending() {
643 return $this->trxLevel
&& $this->trxDoneWrites
;
646 public function writesOrCallbacksPending() {
647 return $this->trxLevel
&& (
648 $this->trxDoneWrites ||
649 $this->trxIdleCallbacks ||
650 $this->trxPreCommitCallbacks ||
651 $this->trxEndCallbacks
655 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
656 if ( !$this->trxLevel
) {
658 } elseif ( !$this->trxDoneWrites
) {
663 case self
::ESTIMATE_DB_APPLY
:
665 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
666 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
667 // For omitted queries, make them count as something at least
668 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
669 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
672 default: // everything
673 return $this->trxWriteDuration
;
677 public function pendingWriteCallers() {
678 return $this->trxLevel ?
$this->trxWriteCallers
: [];
681 public function pendingWriteRowsAffected() {
682 return $this->trxWriteAffectedRows
;
686 * Get the list of method names that have pending write queries or callbacks
687 * for this transaction
691 protected function pendingWriteAndCallbackCallers() {
692 if ( !$this->trxLevel
) {
696 $fnames = $this->trxWriteCallers
;
698 $this->trxIdleCallbacks
,
699 $this->trxPreCommitCallbacks
,
700 $this->trxEndCallbacks
702 foreach ( $callbacks as $callback ) {
703 $fnames[] = $callback[1];
710 public function isOpen() {
711 return $this->opened
;
714 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
715 if ( ( $flag & self
::DBO_IGNORE
) ) {
716 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
719 if ( $remember === self
::REMEMBER_PRIOR
) {
720 array_push( $this->priorFlags
, $this->flags
);
722 $this->flags |
= $flag;
725 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
726 if ( ( $flag & self
::DBO_IGNORE
) ) {
727 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
730 if ( $remember === self
::REMEMBER_PRIOR
) {
731 array_push( $this->priorFlags
, $this->flags
);
733 $this->flags
&= ~
$flag;
736 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
737 if ( !$this->priorFlags
) {
741 if ( $state === self
::RESTORE_INITIAL
) {
742 $this->flags
= reset( $this->priorFlags
);
743 $this->priorFlags
= [];
745 $this->flags
= array_pop( $this->priorFlags
);
749 public function getFlag( $flag ) {
750 return !!( $this->flags
& $flag );
754 * @param string $name Class field name
756 * @deprecated Since 1.28
758 public function getProperty( $name ) {
762 public function getDomainID() {
763 return $this->currentDomain
->getId();
766 final public function getWikiID() {
767 return $this->getDomainID();
771 * Get information about an index into an object
772 * @param string $table Table name
773 * @param string $index Index name
774 * @param string $fname Calling function name
775 * @return mixed Database-specific index description class or false if the index does not exist
777 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
780 * Wrapper for addslashes()
782 * @param string $s String to be slashed.
783 * @return string Slashed string.
785 abstract function strencode( $s );
788 * Set a custom error handler for logging errors during database connection
790 protected function installErrorHandler() {
791 $this->phpError
= false;
792 $this->htmlErrors
= ini_set( 'html_errors', '0' );
793 set_error_handler( [ $this, 'connectionErrorLogger' ] );
797 * Restore the previous error handler and return the last PHP error for this DB
799 * @return bool|string
801 protected function restoreErrorHandler() {
802 restore_error_handler();
803 if ( $this->htmlErrors
!== false ) {
804 ini_set( 'html_errors', $this->htmlErrors
);
807 return $this->getLastPHPError();
811 * @return string|bool Last PHP error for this DB (typically connection errors)
813 protected function getLastPHPError() {
814 if ( $this->phpError
) {
815 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
816 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
825 * Error handler for logging errors during database connection
826 * This method should not be used outside of Database classes
829 * @param string $errstr
831 public function connectionErrorLogger( $errno, $errstr ) {
832 $this->phpError
= $errstr;
836 * Create a log context to pass to PSR-3 logger functions.
838 * @param array $extras Additional data to add to context
841 protected function getLogContext( array $extras = [] ) {
844 'db_server' => $this->server
,
845 'db_name' => $this->dbName
,
846 'db_user' => $this->user
,
852 public function close() {
854 // Resolve any dangling transaction first
855 if ( $this->trxLevel() ) {
856 // Meaningful transactions should ideally have been resolved by now
857 if ( $this->writesOrCallbacksPending() ) {
858 $this->queryLogger
->warning(
859 __METHOD__
. ": writes or callbacks still pending.",
860 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
863 // Check if it is possible to properly commit and trigger callbacks
864 if ( $this->trxEndCallbacksSuppressed
) {
865 throw new DBUnexpectedError(
867 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
870 // Commit the changes and run any callbacks as needed
871 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
873 // Close the actual connection in the binding handle
874 $closed = $this->closeConnection();
876 // Sanity check that no callbacks are dangling
878 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
880 throw new RuntimeException( "Transaction callbacks still pending." );
883 $closed = true; // already closed; nothing to do
886 $this->opened
= false;
892 * Make sure isOpen() returns true as a sanity check
894 * @throws DBUnexpectedError
896 protected function assertOpen() {
897 if ( !$this->isOpen() ) {
898 throw new DBUnexpectedError( $this, "DB connection was already closed." );
903 * Closes underlying database connection
905 * @return bool Whether connection was closed successfully
907 abstract protected function closeConnection();
909 public function reportConnectionError( $error = 'Unknown error' ) {
910 $myError = $this->lastError();
916 throw new DBConnectionError( $this, $error );
920 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
922 * This might return things, such as mysqli_result, that do not formally implement
923 * IResultWrapper, but nonetheless implement all of its methods correctly
925 * @param string $sql SQL query.
926 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
928 abstract protected function doQuery( $sql );
931 * Determine whether a query writes to the DB.
932 * Should return true if unsure.
937 protected function isWriteQuery( $sql ) {
939 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
944 * @return string|null
946 protected function getQueryVerb( $sql ) {
947 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
951 * Determine whether a SQL statement is sensitive to isolation level.
952 * A SQL statement is considered transactable if its result could vary
953 * depending on the transaction isolation level. Operational commands
954 * such as 'SET' and 'SHOW' are not considered to be transactable.
959 protected function isTransactableQuery( $sql ) {
961 $this->getQueryVerb( $sql ),
962 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
968 * @param string $sql A SQL query
969 * @return bool Whether $sql is SQL for TEMPORARY table operation
971 protected function registerTempTableOperation( $sql ) {
973 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
977 $this->sessionTempTables
[$matches[1]] = 1;
980 } elseif ( preg_match(
981 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
985 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
986 unset( $this->sessionTempTables
[$matches[1]] );
989 } elseif ( preg_match(
990 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
994 return isset( $this->sessionTempTables
[$matches[1]] );
995 } elseif ( preg_match(
996 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1000 return isset( $this->sessionTempTables
[$matches[1]] );
1006 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1007 $priorWritesPending = $this->writesOrCallbacksPending();
1008 $this->lastQuery
= $sql;
1010 $isWrite = $this->isWriteQuery( $sql );
1012 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1014 $isNonTempWrite = false;
1018 if ( $this->getLBInfo( 'replica' ) === true ) {
1021 'Write operations are not allowed on replica database connections.'
1024 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1025 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1026 $reason = $this->getReadOnlyReason();
1027 if ( $reason !== false ) {
1028 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1030 # Set a flag indicating that writes have been done
1031 $this->lastWriteTime
= microtime( true );
1034 # Add trace comment to the begin of the sql string, right after the operator.
1035 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1036 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1038 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1039 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1040 && $this->isTransactableQuery( $sql )
1042 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1043 $this->trxAutomatic
= true;
1046 # Keep track of whether the transaction has write queries pending
1047 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1048 $this->trxDoneWrites
= true;
1049 $this->trxProfiler
->transactionWritingIn(
1050 $this->server
, $this->dbName
, $this->trxShortId
);
1053 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1054 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1057 # Avoid fatals if close() was called
1058 $this->assertOpen();
1060 # Send the query to the server
1061 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1063 # Try reconnecting if the connection was lost
1064 if ( false === $ret && $this->wasConnectionLoss() ) {
1065 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1066 # Stash the last error values before anything might clear them
1067 $lastError = $this->lastError();
1068 $lastErrno = $this->lastErrno();
1069 # Update state tracking to reflect transaction loss due to disconnection
1070 $this->handleSessionLoss();
1071 if ( $this->reconnect() ) {
1072 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1073 $params = [ 'dbserver' => $this->getServer() ];
1074 $this->connLogger
->warning( $msg, $params );
1075 $this->queryLogger
->warning( $msg, $params +
1076 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1078 if ( $recoverable ) {
1079 # Should be safe to silently retry the query
1080 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1082 # Callers may catch the exception and continue to use the DB
1083 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1086 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1087 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1091 if ( false === $ret ) {
1092 # Deadlocks cause the entire transaction to abort, not just the statement.
1093 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1094 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1095 if ( $this->wasDeadlock() ) {
1096 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1097 $tempIgnore = false; // not recoverable
1099 # Update state tracking to reflect transaction loss
1100 $this->handleSessionLoss();
1103 $this->reportQueryError(
1104 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1107 $res = $this->resultObject( $ret );
1113 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1115 * @param string $sql Original SQL query
1116 * @param string $commentedSql SQL query with debugging/trace comment
1117 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1118 * @param string $fname Name of the calling function
1119 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1120 * object for a successful read query, or false on failure
1122 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1123 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1124 # generalizeSQL() will probably cut down the query to reasonable
1125 # logging size most of the time. The substr is really just a sanity check.
1127 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1129 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1132 # Include query transaction state
1133 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1135 $startTime = microtime( true );
1136 if ( $this->profiler
) {
1137 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1139 $this->affectedRowCount
= null;
1140 $ret = $this->doQuery( $commentedSql );
1141 $this->affectedRowCount
= $this->affectedRows();
1142 if ( $this->profiler
) {
1143 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1145 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1147 unset( $queryProfSection ); // profile out (if set)
1149 if ( $ret !== false ) {
1150 $this->lastPing
= $startTime;
1151 if ( $isWrite && $this->trxLevel
) {
1152 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1153 $this->trxWriteCallers
[] = $fname;
1157 if ( $sql === self
::PING_QUERY
) {
1158 $this->rttEstimate
= $queryRuntime;
1161 $this->trxProfiler
->recordQueryCompletion(
1162 $queryProf, $startTime, $isWrite, $this->affectedRows()
1164 $this->queryLogger
->debug( $sql, [
1166 'master' => $isMaster,
1167 'runtime' => $queryRuntime,
1174 * Update the estimated run-time of a query, not counting large row lock times
1176 * LoadBalancer can be set to rollback transactions that will create huge replication
1177 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1178 * queries, like inserting a row can take a long time due to row locking. This method
1179 * uses some simple heuristics to discount those cases.
1181 * @param string $sql A SQL write query
1182 * @param float $runtime Total runtime, including RTT
1183 * @param int $affected Affected row count
1185 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1186 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1187 $indicativeOfReplicaRuntime = true;
1188 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1189 $verb = $this->getQueryVerb( $sql );
1190 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1191 if ( $verb === 'INSERT' ) {
1192 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1193 } elseif ( $verb === 'REPLACE' ) {
1194 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1198 $this->trxWriteDuration +
= $runtime;
1199 $this->trxWriteQueryCount +
= 1;
1200 $this->trxWriteAffectedRows +
= $affected;
1201 if ( $indicativeOfReplicaRuntime ) {
1202 $this->trxWriteAdjDuration +
= $runtime;
1203 $this->trxWriteAdjQueryCount +
= 1;
1208 * Determine whether or not it is safe to retry queries after a database
1209 * connection is lost
1211 * @param string $sql SQL query
1212 * @param bool $priorWritesPending Whether there is a transaction open with
1213 * possible write queries or transaction pre-commit/idle callbacks
1214 * waiting on it to finish.
1215 * @return bool True if it is safe to retry the query, false otherwise
1217 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1218 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1219 # Dropped connections also mean that named locks are automatically released.
1220 # Only allow error suppression in autocommit mode or when the lost transaction
1221 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1222 if ( $this->namedLocksHeld
) {
1223 return false; // possible critical section violation
1224 } elseif ( $sql === 'COMMIT' ) {
1225 return !$priorWritesPending; // nothing written anyway? (T127428)
1226 } elseif ( $sql === 'ROLLBACK' ) {
1227 return true; // transaction lost...which is also what was requested :)
1228 } elseif ( $this->explicitTrxActive() ) {
1229 return false; // don't drop atomocity
1230 } elseif ( $priorWritesPending ) {
1231 return false; // prior writes lost from implicit transaction
1238 * Clean things up after transaction loss due to disconnection
1240 * @return null|Exception
1242 private function handleSessionLoss() {
1243 $this->trxLevel
= 0;
1244 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1245 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1246 $this->sessionTempTables
= [];
1247 $this->namedLocksHeld
= [];
1249 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1252 // Handle callbacks in trxEndCallbacks
1253 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1254 } catch ( Exception
$ex ) {
1255 // Already logged; move on...
1259 // Handle callbacks in trxRecurringCallbacks
1260 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1261 } catch ( Exception
$ex ) {
1262 // Already logged; move on...
1270 * Checks whether the cause of the error is detected to be a timeout.
1272 * It returns false by default, and not all engines support detecting this yet.
1273 * If this returns false, it will be treated as a generic query error.
1275 * @param string $error Error text
1276 * @param int $errno Error number
1279 protected function wasQueryTimeout( $error, $errno ) {
1283 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1284 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1285 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1287 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1288 $this->queryLogger
->error(
1289 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1290 $this->getLogContext( [
1291 'method' => __METHOD__
,
1294 'sql1line' => $sql1line,
1298 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1299 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1300 if ( $wasQueryTimeout ) {
1301 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1303 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1308 public function freeResult( $res ) {
1311 public function selectField(
1312 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1314 if ( $var === '*' ) { // sanity
1315 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1318 if ( !is_array( $options ) ) {
1319 $options = [ $options ];
1322 $options['LIMIT'] = 1;
1324 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1325 if ( $res === false ||
!$this->numRows( $res ) ) {
1329 $row = $this->fetchRow( $res );
1331 if ( $row !== false ) {
1332 return reset( $row );
1338 public function selectFieldValues(
1339 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1341 if ( $var === '*' ) { // sanity
1342 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1343 } elseif ( !is_string( $var ) ) { // sanity
1344 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1347 if ( !is_array( $options ) ) {
1348 $options = [ $options ];
1351 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1352 if ( $res === false ) {
1357 foreach ( $res as $row ) {
1358 $values[] = $row->$var;
1365 * Returns an optional USE INDEX clause to go after the table, and a
1366 * string to go at the end of the query.
1368 * @param array $options Associative array of options to be turned into
1369 * an SQL query, valid keys are listed in the function.
1371 * @see Database::select()
1373 protected function makeSelectOptions( $options ) {
1374 $preLimitTail = $postLimitTail = '';
1379 foreach ( $options as $key => $option ) {
1380 if ( is_numeric( $key ) ) {
1381 $noKeyOptions[$option] = true;
1385 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1387 $preLimitTail .= $this->makeOrderBy( $options );
1389 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1390 $postLimitTail .= ' FOR UPDATE';
1393 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1394 $postLimitTail .= ' LOCK IN SHARE MODE';
1397 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1398 $startOpts .= 'DISTINCT';
1401 # Various MySQL extensions
1402 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1403 $startOpts .= ' /*! STRAIGHT_JOIN */';
1406 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1407 $startOpts .= ' HIGH_PRIORITY';
1410 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1411 $startOpts .= ' SQL_BIG_RESULT';
1414 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1415 $startOpts .= ' SQL_BUFFER_RESULT';
1418 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1419 $startOpts .= ' SQL_SMALL_RESULT';
1422 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1423 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1426 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1427 $startOpts .= ' SQL_CACHE';
1430 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1431 $startOpts .= ' SQL_NO_CACHE';
1434 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1435 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1439 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1440 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1445 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1449 * Returns an optional GROUP BY with an optional HAVING
1451 * @param array $options Associative array of options
1453 * @see Database::select()
1456 protected function makeGroupByWithHaving( $options ) {
1458 if ( isset( $options['GROUP BY'] ) ) {
1459 $gb = is_array( $options['GROUP BY'] )
1460 ?
implode( ',', $options['GROUP BY'] )
1461 : $options['GROUP BY'];
1462 $sql .= ' GROUP BY ' . $gb;
1464 if ( isset( $options['HAVING'] ) ) {
1465 $having = is_array( $options['HAVING'] )
1466 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1467 : $options['HAVING'];
1468 $sql .= ' HAVING ' . $having;
1475 * Returns an optional ORDER BY
1477 * @param array $options Associative array of options
1479 * @see Database::select()
1482 protected function makeOrderBy( $options ) {
1483 if ( isset( $options['ORDER BY'] ) ) {
1484 $ob = is_array( $options['ORDER BY'] )
1485 ?
implode( ',', $options['ORDER BY'] )
1486 : $options['ORDER BY'];
1488 return ' ORDER BY ' . $ob;
1494 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1495 $options = [], $join_conds = [] ) {
1496 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1498 return $this->query( $sql, $fname );
1501 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1502 $options = [], $join_conds = []
1504 if ( is_array( $vars ) ) {
1505 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1508 $options = (array)$options;
1509 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1510 ?
$options['USE INDEX']
1513 isset( $options['IGNORE INDEX'] ) &&
1514 is_array( $options['IGNORE INDEX'] )
1516 ?
$options['IGNORE INDEX']
1519 if ( is_array( $table ) ) {
1521 $this->tableNamesWithIndexClauseOrJOIN(
1522 $table, $useIndexes, $ignoreIndexes, $join_conds );
1523 } elseif ( $table != '' ) {
1525 $this->tableNamesWithIndexClauseOrJOIN(
1526 [ $table ], $useIndexes, $ignoreIndexes, [] );
1531 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1532 $this->makeSelectOptions( $options );
1534 if ( is_array( $conds ) ) {
1535 $conds = $this->makeList( $conds, self
::LIST_AND
);
1538 if ( $conds === null ||
$conds === false ) {
1539 $this->queryLogger
->warning(
1543 . ' with incorrect parameters: $conds must be a string or an array'
1548 if ( $conds === '' ) {
1549 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1550 } elseif ( is_string( $conds ) ) {
1551 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1552 "WHERE $conds $preLimitTail";
1554 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1557 if ( isset( $options['LIMIT'] ) ) {
1558 $sql = $this->limitResult( $sql, $options['LIMIT'],
1559 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1561 $sql = "$sql $postLimitTail";
1563 if ( isset( $options['EXPLAIN'] ) ) {
1564 $sql = 'EXPLAIN ' . $sql;
1570 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1571 $options = [], $join_conds = []
1573 $options = (array)$options;
1574 $options['LIMIT'] = 1;
1575 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1577 if ( $res === false ) {
1581 if ( !$this->numRows( $res ) ) {
1585 $obj = $this->fetchObject( $res );
1590 public function estimateRowCount(
1591 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1593 $conds = $this->normalizeConditions( $conds, $fname );
1594 $column = $this->extractSingleFieldFromList( $var );
1595 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1596 $conds[] = "$column IS NOT NULL";
1599 $res = $this->select(
1600 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1602 $row = $res ?
$this->fetchRow( $res ) : [];
1604 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1607 public function selectRowCount(
1608 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1610 $conds = $this->normalizeConditions( $conds, $fname );
1611 $column = $this->extractSingleFieldFromList( $var );
1612 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1613 $conds[] = "$column IS NOT NULL";
1616 $res = $this->select(
1618 'tmp_count' => $this->buildSelectSubquery(
1627 [ 'rowcount' => 'COUNT(*)' ],
1631 $row = $res ?
$this->fetchRow( $res ) : [];
1633 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1637 * @param array|string $conds
1638 * @param string $fname
1641 final protected function normalizeConditions( $conds, $fname ) {
1642 if ( $conds === null ||
$conds === false ) {
1643 $this->queryLogger
->warning(
1647 . ' with incorrect parameters: $conds must be a string or an array'
1652 if ( !is_array( $conds ) ) {
1653 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1660 * @param array|string $var Field parameter in the style of select()
1661 * @return string|null Column name or null; ignores aliases
1662 * @throws DBUnexpectedError Errors out if multiple columns are given
1664 final protected function extractSingleFieldFromList( $var ) {
1665 if ( is_array( $var ) ) {
1668 } elseif ( count( $var ) == 1 ) {
1669 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1671 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1681 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1682 * It's only slightly flawed. Don't use for anything important.
1684 * @param string $sql A SQL Query
1688 protected static function generalizeSQL( $sql ) {
1689 # This does the same as the regexp below would do, but in such a way
1690 # as to avoid crashing php on some large strings.
1691 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1693 $sql = str_replace( "\\\\", '', $sql );
1694 $sql = str_replace( "\\'", '', $sql );
1695 $sql = str_replace( "\\\"", '', $sql );
1696 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1697 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1699 # All newlines, tabs, etc replaced by single space
1700 $sql = preg_replace( '/\s+/', ' ', $sql );
1703 # except the ones surrounded by characters, e.g. l10n
1704 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1705 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1710 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1711 $info = $this->fieldInfo( $table, $field );
1716 public function indexExists( $table, $index, $fname = __METHOD__
) {
1717 if ( !$this->tableExists( $table ) ) {
1721 $info = $this->indexInfo( $table, $index, $fname );
1722 if ( is_null( $info ) ) {
1725 return $info !== false;
1729 public function tableExists( $table, $fname = __METHOD__
) {
1730 $tableRaw = $this->tableName( $table, 'raw' );
1731 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1732 return true; // already known to exist
1735 $table = $this->tableName( $table );
1736 $ignoreErrors = true;
1737 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1742 public function indexUnique( $table, $index ) {
1743 $indexInfo = $this->indexInfo( $table, $index );
1745 if ( !$indexInfo ) {
1749 return !$indexInfo[0]->Non_unique
;
1753 * Helper for Database::insert().
1755 * @param array $options
1758 protected function makeInsertOptions( $options ) {
1759 return implode( ' ', $options );
1762 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1763 # No rows to insert, easy just return now
1764 if ( !count( $a ) ) {
1768 $table = $this->tableName( $table );
1770 if ( !is_array( $options ) ) {
1771 $options = [ $options ];
1775 if ( isset( $options['fileHandle'] ) ) {
1776 $fh = $options['fileHandle'];
1778 $options = $this->makeInsertOptions( $options );
1780 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1782 $keys = array_keys( $a[0] );
1785 $keys = array_keys( $a );
1788 $sql = 'INSERT ' . $options .
1789 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1793 foreach ( $a as $row ) {
1799 $sql .= '(' . $this->makeList( $row ) . ')';
1802 $sql .= '(' . $this->makeList( $a ) . ')';
1805 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1807 } elseif ( $fh !== null ) {
1811 return (bool)$this->query( $sql, $fname );
1815 * Make UPDATE options array for Database::makeUpdateOptions
1817 * @param array $options
1820 protected function makeUpdateOptionsArray( $options ) {
1821 if ( !is_array( $options ) ) {
1822 $options = [ $options ];
1827 if ( in_array( 'IGNORE', $options ) ) {
1835 * Make UPDATE options for the Database::update function
1837 * @param array $options The options passed to Database::update
1840 protected function makeUpdateOptions( $options ) {
1841 $opts = $this->makeUpdateOptionsArray( $options );
1843 return implode( ' ', $opts );
1846 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1847 $table = $this->tableName( $table );
1848 $opts = $this->makeUpdateOptions( $options );
1849 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1851 if ( $conds !== [] && $conds !== '*' ) {
1852 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1855 return (bool)$this->query( $sql, $fname );
1858 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1859 if ( !is_array( $a ) ) {
1860 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1866 foreach ( $a as $field => $value ) {
1868 if ( $mode == self
::LIST_AND
) {
1870 } elseif ( $mode == self
::LIST_OR
) {
1879 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1880 $list .= "($value)";
1881 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1884 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1886 // Remove null from array to be handled separately if found
1887 $includeNull = false;
1888 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1889 $includeNull = true;
1890 unset( $value[$nullKey] );
1892 if ( count( $value ) == 0 && !$includeNull ) {
1893 throw new InvalidArgumentException(
1894 __METHOD__
. ": empty input for field $field" );
1895 } elseif ( count( $value ) == 0 ) {
1896 // only check if $field is null
1897 $list .= "$field IS NULL";
1899 // IN clause contains at least one valid element
1900 if ( $includeNull ) {
1901 // Group subconditions to ensure correct precedence
1904 if ( count( $value ) == 1 ) {
1905 // Special-case single values, as IN isn't terribly efficient
1906 // Don't necessarily assume the single key is 0; we don't
1907 // enforce linear numeric ordering on other arrays here.
1908 $value = array_values( $value )[0];
1909 $list .= $field . " = " . $this->addQuotes( $value );
1911 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1913 // if null present in array, append IS NULL
1914 if ( $includeNull ) {
1915 $list .= " OR $field IS NULL)";
1918 } elseif ( $value === null ) {
1919 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1920 $list .= "$field IS ";
1921 } elseif ( $mode == self
::LIST_SET
) {
1922 $list .= "$field = ";
1927 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1929 $list .= "$field = ";
1931 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1938 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1941 foreach ( $data as $base => $sub ) {
1942 if ( count( $sub ) ) {
1943 $conds[] = $this->makeList(
1944 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1950 return $this->makeList( $conds, self
::LIST_OR
);
1952 // Nothing to search for...
1957 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1961 public function bitNot( $field ) {
1965 public function bitAnd( $fieldLeft, $fieldRight ) {
1966 return "($fieldLeft & $fieldRight)";
1969 public function bitOr( $fieldLeft, $fieldRight ) {
1970 return "($fieldLeft | $fieldRight)";
1973 public function buildConcat( $stringList ) {
1974 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1977 public function buildGroupConcatField(
1978 $delim, $table, $field, $conds = '', $join_conds = []
1980 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1982 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1985 public function buildSubstring( $input, $startPosition, $length = null ) {
1986 $this->assertBuildSubstringParams( $startPosition, $length );
1987 $functionBody = "$input FROM $startPosition";
1988 if ( $length !== null ) {
1989 $functionBody .= " FOR $length";
1991 return 'SUBSTRING(' . $functionBody . ')';
1995 * Check type and bounds for parameters to self::buildSubstring()
1997 * All supported databases have substring functions that behave the same for
1998 * positive $startPosition and non-negative $length, but behaviors differ when
1999 * given 0 or negative $startPosition or negative $length. The simplest
2000 * solution to that is to just forbid those values.
2002 * @param int $startPosition
2003 * @param int|null $length
2006 protected function assertBuildSubstringParams( $startPosition, $length ) {
2007 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2008 throw new InvalidArgumentException(
2009 '$startPosition must be a positive integer'
2012 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2013 throw new InvalidArgumentException(
2014 '$length must be null or an integer greater than or equal to 0'
2019 public function buildStringCast( $field ) {
2023 public function buildIntegerCast( $field ) {
2024 return 'CAST( ' . $field . ' AS INTEGER )';
2027 public function buildSelectSubquery(
2028 $table, $vars, $conds = '', $fname = __METHOD__
,
2029 $options = [], $join_conds = []
2031 return new Subquery(
2032 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2036 public function databasesAreIndependent() {
2040 public function selectDB( $db ) {
2041 # Stub. Shouldn't cause serious problems if it's not overridden, but
2042 # if your database engine supports a concept similar to MySQL's
2043 # databases you may as well.
2044 $this->dbName
= $db;
2049 public function getDBname() {
2050 return $this->dbName
;
2053 public function getServer() {
2054 return $this->server
;
2057 public function tableName( $name, $format = 'quoted' ) {
2058 if ( $name instanceof Subquery
) {
2059 throw new DBUnexpectedError(
2061 __METHOD__
. ': got Subquery instance when expecting a string.'
2065 # Skip the entire process when we have a string quoted on both ends.
2066 # Note that we check the end so that we will still quote any use of
2067 # use of `database`.table. But won't break things if someone wants
2068 # to query a database table with a dot in the name.
2069 if ( $this->isQuotedIdentifier( $name ) ) {
2073 # Lets test for any bits of text that should never show up in a table
2074 # name. Basically anything like JOIN or ON which are actually part of
2075 # SQL queries, but may end up inside of the table value to combine
2076 # sql. Such as how the API is doing.
2077 # Note that we use a whitespace test rather than a \b test to avoid
2078 # any remote case where a word like on may be inside of a table name
2079 # surrounded by symbols which may be considered word breaks.
2080 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2081 $this->queryLogger
->warning(
2082 __METHOD__
. ": use of subqueries is not supported this way.",
2083 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2089 # Split database and table into proper variables.
2090 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2092 # Quote $table and apply the prefix if not quoted.
2093 # $tableName might be empty if this is called from Database::replaceVars()
2094 $tableName = "{$prefix}{$table}";
2095 if ( $format === 'quoted'
2096 && !$this->isQuotedIdentifier( $tableName )
2097 && $tableName !== ''
2099 $tableName = $this->addIdentifierQuotes( $tableName );
2102 # Quote $schema and $database and merge them with the table name if needed
2103 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2104 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2110 * Get the table components needed for a query given the currently selected database
2112 * @param string $name Table name in the form of db.schema.table, db.table, or table
2113 * @return array (DB name or "" for default, schema name, table prefix, table name)
2115 protected function qualifiedTableComponents( $name ) {
2116 # We reverse the explode so that database.table and table both output the correct table.
2117 $dbDetails = explode( '.', $name, 3 );
2118 if ( count( $dbDetails ) == 3 ) {
2119 list( $database, $schema, $table ) = $dbDetails;
2120 # We don't want any prefix added in this case
2122 } elseif ( count( $dbDetails ) == 2 ) {
2123 list( $database, $table ) = $dbDetails;
2124 # We don't want any prefix added in this case
2126 # In dbs that support it, $database may actually be the schema
2127 # but that doesn't affect any of the functionality here
2130 list( $table ) = $dbDetails;
2131 if ( isset( $this->tableAliases
[$table] ) ) {
2132 $database = $this->tableAliases
[$table]['dbname'];
2133 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2134 ?
$this->tableAliases
[$table]['schema']
2136 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2137 ?
$this->tableAliases
[$table]['prefix']
2138 : $this->tablePrefix
;
2141 $schema = $this->schema
; # Default schema
2142 $prefix = $this->tablePrefix
; # Default prefix
2146 return [ $database, $schema, $prefix, $table ];
2150 * @param string|null $namespace Database or schema
2151 * @param string $relation Name of table, view, sequence, etc...
2152 * @param string $format One of (raw, quoted)
2153 * @return string Relation name with quoted and merged $namespace as needed
2155 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2156 if ( strlen( $namespace ) ) {
2157 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2158 $namespace = $this->addIdentifierQuotes( $namespace );
2160 $relation = $namespace . '.' . $relation;
2166 public function tableNames() {
2167 $inArray = func_get_args();
2170 foreach ( $inArray as $name ) {
2171 $retVal[$name] = $this->tableName( $name );
2177 public function tableNamesN() {
2178 $inArray = func_get_args();
2181 foreach ( $inArray as $name ) {
2182 $retVal[] = $this->tableName( $name );
2189 * Get an aliased table name
2191 * This returns strings like "tableName AS newTableName" for aliased tables
2192 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2194 * @see Database::tableName()
2195 * @param string|Subquery $table Table name or object with a 'sql' field
2196 * @param string|bool $alias Table alias (optional)
2197 * @return string SQL name for aliased table. Will not alias a table to its own name
2199 protected function tableNameWithAlias( $table, $alias = false ) {
2200 if ( is_string( $table ) ) {
2201 $quotedTable = $this->tableName( $table );
2202 } elseif ( $table instanceof Subquery
) {
2203 $quotedTable = (string)$table;
2205 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2208 if ( !strlen( $alias ) ||
$alias === $table ) {
2209 if ( $table instanceof Subquery
) {
2210 throw new InvalidArgumentException( "Subquery table missing alias." );
2213 return $quotedTable;
2215 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2220 * Gets an array of aliased table names
2222 * @param array $tables [ [alias] => table ]
2223 * @return string[] See tableNameWithAlias()
2225 protected function tableNamesWithAlias( $tables ) {
2227 foreach ( $tables as $alias => $table ) {
2228 if ( is_numeric( $alias ) ) {
2231 $retval[] = $this->tableNameWithAlias( $table, $alias );
2238 * Get an aliased field name
2239 * e.g. fieldName AS newFieldName
2241 * @param string $name Field name
2242 * @param string|bool $alias Alias (optional)
2243 * @return string SQL name for aliased field. Will not alias a field to its own name
2245 protected function fieldNameWithAlias( $name, $alias = false ) {
2246 if ( !$alias ||
(string)$alias === (string)$name ) {
2249 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2254 * Gets an array of aliased field names
2256 * @param array $fields [ [alias] => field ]
2257 * @return string[] See fieldNameWithAlias()
2259 protected function fieldNamesWithAlias( $fields ) {
2261 foreach ( $fields as $alias => $field ) {
2262 if ( is_numeric( $alias ) ) {
2265 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2272 * Get the aliased table name clause for a FROM clause
2273 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2275 * @param array $tables ( [alias] => table )
2276 * @param array $use_index Same as for select()
2277 * @param array $ignore_index Same as for select()
2278 * @param array $join_conds Same as for select()
2281 protected function tableNamesWithIndexClauseOrJOIN(
2282 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2286 $use_index = (array)$use_index;
2287 $ignore_index = (array)$ignore_index;
2288 $join_conds = (array)$join_conds;
2290 foreach ( $tables as $alias => $table ) {
2291 if ( !is_string( $alias ) ) {
2292 // No alias? Set it equal to the table name
2296 if ( is_array( $table ) ) {
2297 // A parenthesized group
2298 if ( count( $table ) > 1 ) {
2299 $joinedTable = '(' .
2300 $this->tableNamesWithIndexClauseOrJOIN(
2301 $table, $use_index, $ignore_index, $join_conds ) . ')';
2304 $innerTable = reset( $table );
2305 $innerAlias = key( $table );
2306 $joinedTable = $this->tableNameWithAlias(
2308 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2312 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2315 // Is there a JOIN clause for this table?
2316 if ( isset( $join_conds[$alias] ) ) {
2317 list( $joinType, $conds ) = $join_conds[$alias];
2318 $tableClause = $joinType;
2319 $tableClause .= ' ' . $joinedTable;
2320 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2321 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2323 $tableClause .= ' ' . $use;
2326 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2327 $ignore = $this->ignoreIndexClause(
2328 implode( ',', (array)$ignore_index[$alias] ) );
2329 if ( $ignore != '' ) {
2330 $tableClause .= ' ' . $ignore;
2333 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2335 $tableClause .= ' ON (' . $on . ')';
2338 $retJOIN[] = $tableClause;
2339 } elseif ( isset( $use_index[$alias] ) ) {
2340 // Is there an INDEX clause for this table?
2341 $tableClause = $joinedTable;
2342 $tableClause .= ' ' . $this->useIndexClause(
2343 implode( ',', (array)$use_index[$alias] )
2346 $ret[] = $tableClause;
2347 } elseif ( isset( $ignore_index[$alias] ) ) {
2348 // Is there an INDEX clause for this table?
2349 $tableClause = $joinedTable;
2350 $tableClause .= ' ' . $this->ignoreIndexClause(
2351 implode( ',', (array)$ignore_index[$alias] )
2354 $ret[] = $tableClause;
2356 $tableClause = $joinedTable;
2358 $ret[] = $tableClause;
2362 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2363 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2364 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2366 // Compile our final table clause
2367 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2371 * Allows for index remapping in queries where this is not consistent across DBMS
2373 * @param string $index
2376 protected function indexName( $index ) {
2377 return isset( $this->indexAliases
[$index] )
2378 ?
$this->indexAliases
[$index]
2382 public function addQuotes( $s ) {
2383 if ( $s instanceof Blob
) {
2386 if ( $s === null ) {
2388 } elseif ( is_bool( $s ) ) {
2391 # This will also quote numeric values. This should be harmless,
2392 # and protects against weird problems that occur when they really
2393 # _are_ strings such as article titles and string->number->string
2394 # conversion is not 1:1.
2395 return "'" . $this->strencode( $s ) . "'";
2400 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2401 * MySQL uses `backticks` while basically everything else uses double quotes.
2402 * Since MySQL is the odd one out here the double quotes are our generic
2403 * and we implement backticks in DatabaseMysqlBase.
2408 public function addIdentifierQuotes( $s ) {
2409 return '"' . str_replace( '"', '""', $s ) . '"';
2413 * Returns if the given identifier looks quoted or not according to
2414 * the database convention for quoting identifiers .
2416 * @note Do not use this to determine if untrusted input is safe.
2417 * A malicious user can trick this function.
2418 * @param string $name
2421 public function isQuotedIdentifier( $name ) {
2422 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2427 * @param string $escapeChar
2430 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2431 return str_replace( [ $escapeChar, '%', '_' ],
2432 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2436 public function buildLike() {
2437 $params = func_get_args();
2439 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2440 $params = $params[0];
2445 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2446 // may escape backslashes, creating problems of double escaping. The `
2447 // character has good cross-DBMS compatibility, avoiding special operators
2448 // in MS SQL like ^ and %
2451 foreach ( $params as $value ) {
2452 if ( $value instanceof LikeMatch
) {
2453 $s .= $value->toString();
2455 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2460 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2463 public function anyChar() {
2464 return new LikeMatch( '_' );
2467 public function anyString() {
2468 return new LikeMatch( '%' );
2471 public function nextSequenceValue( $seqName ) {
2476 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2477 * is only needed because a) MySQL must be as efficient as possible due to
2478 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2479 * which index to pick. Anyway, other databases might have different
2480 * indexes on a given table. So don't bother overriding this unless you're
2482 * @param string $index
2485 public function useIndexClause( $index ) {
2490 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2491 * is only needed because a) MySQL must be as efficient as possible due to
2492 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2493 * which index to pick. Anyway, other databases might have different
2494 * indexes on a given table. So don't bother overriding this unless you're
2496 * @param string $index
2499 public function ignoreIndexClause( $index ) {
2503 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2504 if ( count( $rows ) == 0 ) {
2509 if ( !is_array( reset( $rows ) ) ) {
2514 $this->startAtomic( $fname );
2515 $affectedRowCount = 0;
2516 foreach ( $rows as $row ) {
2517 // Delete rows which collide with this one
2518 $indexWhereClauses = [];
2519 foreach ( $uniqueIndexes as $index ) {
2520 $indexColumns = (array)$index;
2521 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2522 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2523 throw new DBUnexpectedError(
2525 'New record does not provide all values for unique key (' .
2526 implode( ', ', $indexColumns ) . ')'
2528 } elseif ( in_array( null, $indexRowValues, true ) ) {
2529 throw new DBUnexpectedError(
2531 'New record has a null value for unique key (' .
2532 implode( ', ', $indexColumns ) . ')'
2535 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2538 if ( $indexWhereClauses ) {
2539 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2540 $affectedRowCount +
= $this->affectedRows();
2543 // Now insert the row
2544 $this->insert( $table, $row, $fname );
2545 $affectedRowCount +
= $this->affectedRows();
2547 $this->endAtomic( $fname );
2548 $this->affectedRowCount
= $affectedRowCount;
2549 } catch ( Exception
$e ) {
2550 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2556 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2559 * @param string $table Table name
2560 * @param array|string $rows Row(s) to insert
2561 * @param string $fname Caller function name
2563 * @return ResultWrapper
2565 protected function nativeReplace( $table, $rows, $fname ) {
2566 $table = $this->tableName( $table );
2569 if ( !is_array( reset( $rows ) ) ) {
2573 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2576 foreach ( $rows as $row ) {
2583 $sql .= '(' . $this->makeList( $row ) . ')';
2586 return $this->query( $sql, $fname );
2589 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2592 if ( !count( $rows ) ) {
2593 return true; // nothing to do
2596 if ( !is_array( reset( $rows ) ) ) {
2600 if ( count( $uniqueIndexes ) ) {
2601 $clauses = []; // list WHERE clauses that each identify a single row
2602 foreach ( $rows as $row ) {
2603 foreach ( $uniqueIndexes as $index ) {
2604 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2605 $rowKey = []; // unique key to this row
2606 foreach ( $index as $column ) {
2607 $rowKey[$column] = $row[$column];
2609 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2612 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2617 $affectedRowCount = 0;
2619 $this->startAtomic( $fname );
2620 # Update any existing conflicting row(s)
2621 if ( $where !== false ) {
2622 $ok = $this->update( $table, $set, $where, $fname );
2623 $affectedRowCount +
= $this->affectedRows();
2627 # Now insert any non-conflicting row(s)
2628 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2629 $affectedRowCount +
= $this->affectedRows();
2630 $this->endAtomic( $fname );
2631 $this->affectedRowCount
= $affectedRowCount;
2632 } catch ( Exception
$e ) {
2633 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2640 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2644 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2647 $delTable = $this->tableName( $delTable );
2648 $joinTable = $this->tableName( $joinTable );
2649 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2650 if ( $conds != '*' ) {
2651 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2655 $this->query( $sql, $fname );
2658 public function textFieldSize( $table, $field ) {
2659 $table = $this->tableName( $table );
2660 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2661 $res = $this->query( $sql, __METHOD__
);
2662 $row = $this->fetchObject( $res );
2666 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2675 public function delete( $table, $conds, $fname = __METHOD__
) {
2677 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2680 $table = $this->tableName( $table );
2681 $sql = "DELETE FROM $table";
2683 if ( $conds != '*' ) {
2684 if ( is_array( $conds ) ) {
2685 $conds = $this->makeList( $conds, self
::LIST_AND
);
2687 $sql .= ' WHERE ' . $conds;
2690 return $this->query( $sql, $fname );
2693 final public function insertSelect(
2694 $destTable, $srcTable, $varMap, $conds,
2695 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2697 static $hints = [ 'NO_AUTO_COLUMNS' ];
2699 $insertOptions = (array)$insertOptions;
2700 $selectOptions = (array)$selectOptions;
2702 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2703 // For massive migrations with downtime, we don't want to select everything
2704 // into memory and OOM, so do all this native on the server side if possible.
2705 return $this->nativeInsertSelect(
2711 array_diff( $insertOptions, $hints ),
2717 return $this->nonNativeInsertSelect(
2723 array_diff( $insertOptions, $hints ),
2730 * @param array $insertOptions INSERT options
2731 * @param array $selectOptions SELECT options
2732 * @return bool Whether an INSERT SELECT with these options will be replication safe
2735 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2740 * Implementation of insertSelect() based on select() and insert()
2742 * @see IDatabase::insertSelect()
2744 * @param string $destTable
2745 * @param string|array $srcTable
2746 * @param array $varMap
2747 * @param array $conds
2748 * @param string $fname
2749 * @param array $insertOptions
2750 * @param array $selectOptions
2751 * @param array $selectJoinConds
2754 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2755 $fname = __METHOD__
,
2756 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2758 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2759 // on only the master (without needing row-based-replication). It also makes it easy to
2760 // know how big the INSERT is going to be.
2762 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2763 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2765 $selectOptions[] = 'FOR UPDATE';
2766 $res = $this->select(
2767 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2774 $affectedRowCount = 0;
2775 $this->startAtomic( $fname );
2778 foreach ( $res as $row ) {
2779 $rows[] = (array)$row;
2781 // Avoid inserts that are too huge
2782 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2783 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2787 $affectedRowCount +
= $this->affectedRows();
2791 if ( $rows && $ok ) {
2792 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2794 $affectedRowCount +
= $this->affectedRows();
2798 $this->endAtomic( $fname );
2799 $this->affectedRowCount
= $affectedRowCount;
2801 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2804 } catch ( Exception
$e ) {
2805 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2811 * Native server-side implementation of insertSelect() for situations where
2812 * we don't want to select everything into memory
2814 * @see IDatabase::insertSelect()
2815 * @param string $destTable
2816 * @param string|array $srcTable
2817 * @param array $varMap
2818 * @param array $conds
2819 * @param string $fname
2820 * @param array $insertOptions
2821 * @param array $selectOptions
2822 * @param array $selectJoinConds
2825 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2826 $fname = __METHOD__
,
2827 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2829 $destTable = $this->tableName( $destTable );
2831 if ( !is_array( $insertOptions ) ) {
2832 $insertOptions = [ $insertOptions ];
2835 $insertOptions = $this->makeInsertOptions( $insertOptions );
2837 $selectSql = $this->selectSQLText(
2839 array_values( $varMap ),
2846 $sql = "INSERT $insertOptions" .
2847 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2850 return $this->query( $sql, $fname );
2854 * Construct a LIMIT query with optional offset. This is used for query
2855 * pages. The SQL should be adjusted so that only the first $limit rows
2856 * are returned. If $offset is provided as well, then the first $offset
2857 * rows should be discarded, and the next $limit rows should be returned.
2858 * If the result of the query is not ordered, then the rows to be returned
2859 * are theoretically arbitrary.
2861 * $sql is expected to be a SELECT, if that makes a difference.
2863 * The version provided by default works in MySQL and SQLite. It will very
2864 * likely need to be overridden for most other DBMSes.
2866 * @param string $sql SQL query we will append the limit too
2867 * @param int $limit The SQL limit
2868 * @param int|bool $offset The SQL offset (default false)
2869 * @throws DBUnexpectedError
2872 public function limitResult( $sql, $limit, $offset = false ) {
2873 if ( !is_numeric( $limit ) ) {
2874 throw new DBUnexpectedError( $this,
2875 "Invalid non-numeric limit passed to limitResult()\n" );
2878 return "$sql LIMIT "
2879 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2883 public function unionSupportsOrderAndLimit() {
2884 return true; // True for almost every DB supported
2887 public function unionQueries( $sqls, $all ) {
2888 $glue = $all ?
') UNION ALL (' : ') UNION (';
2890 return '(' . implode( $glue, $sqls ) . ')';
2893 public function unionConditionPermutations(
2894 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2895 $options = [], $join_conds = []
2897 // First, build the Cartesian product of $permute_conds
2899 foreach ( $permute_conds as $field => $values ) {
2901 // Skip empty $values
2904 $values = array_unique( $values ); // For sanity
2906 foreach ( $conds as $cond ) {
2907 foreach ( $values as $value ) {
2908 $cond[$field] = $value;
2909 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2915 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2917 // If there's just one condition and no subordering, hand off to
2918 // selectSQLText directly.
2919 if ( count( $conds ) === 1 &&
2920 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2922 return $this->selectSQLText(
2923 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2927 // Otherwise, we need to pull out the order and limit to apply after
2928 // the union. Then build the SQL queries for each set of conditions in
2929 // $conds. Then union them together (using UNION ALL, because the
2930 // product *should* already be distinct).
2931 $orderBy = $this->makeOrderBy( $options );
2932 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2933 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2934 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2935 if ( !$this->unionSupportsOrderAndLimit() ) {
2936 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2938 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2939 $options['ORDER BY'] = $options['INNER ORDER BY'];
2941 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2942 // We need to increase the limit by the offset rather than
2943 // using the offset directly, otherwise it'll skip incorrectly
2944 // in the subqueries.
2945 $options['LIMIT'] = $limit +
$offset;
2946 unset( $options['OFFSET'] );
2951 foreach ( $conds as $cond ) {
2952 $sqls[] = $this->selectSQLText(
2953 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2956 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2957 if ( $limit !== null ) {
2958 $sql = $this->limitResult( $sql, $limit, $offset );
2964 public function conditional( $cond, $trueVal, $falseVal ) {
2965 if ( is_array( $cond ) ) {
2966 $cond = $this->makeList( $cond, self
::LIST_AND
);
2969 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2972 public function strreplace( $orig, $old, $new ) {
2973 return "REPLACE({$orig}, {$old}, {$new})";
2976 public function getServerUptime() {
2980 public function wasDeadlock() {
2984 public function wasLockTimeout() {
2988 public function wasConnectionLoss() {
2989 return $this->wasConnectionError( $this->lastErrno() );
2992 public function wasReadOnlyError() {
2996 public function wasErrorReissuable() {
2998 $this->wasDeadlock() ||
2999 $this->wasLockTimeout() ||
3000 $this->wasConnectionLoss()
3005 * Do not use this method outside of Database/DBError classes
3007 * @param int|string $errno
3008 * @return bool Whether the given query error was a connection drop
3010 public function wasConnectionError( $errno ) {
3014 public function deadlockLoop() {
3015 $args = func_get_args();
3016 $function = array_shift( $args );
3017 $tries = self
::DEADLOCK_TRIES
;
3019 $this->begin( __METHOD__
);
3022 /** @var Exception $e */
3026 $retVal = call_user_func_array( $function, $args );
3028 } catch ( DBQueryError
$e ) {
3029 if ( $this->wasDeadlock() ) {
3030 // Retry after a randomized delay
3031 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3033 // Throw the error back up
3037 } while ( --$tries > 0 );
3039 if ( $tries <= 0 ) {
3040 // Too many deadlocks; give up
3041 $this->rollback( __METHOD__
);
3044 $this->commit( __METHOD__
);
3050 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3051 # Real waits are implemented in the subclass.
3055 public function getReplicaPos() {
3060 public function getMasterPos() {
3065 public function serverIsReadOnly() {
3069 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3070 if ( !$this->trxLevel
) {
3071 throw new DBUnexpectedError( $this, "No transaction is active." );
3073 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3076 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3077 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3078 if ( !$this->trxLevel
) {
3079 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3083 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3084 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
3085 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3086 // an implicit commit of all peer databases. This is true even if a transaction has
3087 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3088 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3090 // No transaction is active nor will start implicitly, so make one for this callback
3091 $this->startAtomic( __METHOD__
);
3093 call_user_func( $callback );
3094 $this->endAtomic( __METHOD__
);
3095 } catch ( Exception
$e ) {
3096 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3102 final public function setTransactionListener( $name, callable
$callback = null ) {
3104 $this->trxRecurringCallbacks
[$name] = $callback;
3106 unset( $this->trxRecurringCallbacks
[$name] );
3111 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3113 * This method should not be used outside of Database/LoadBalancer
3115 * @param bool $suppress
3118 final public function setTrxEndCallbackSuppression( $suppress ) {
3119 $this->trxEndCallbacksSuppressed
= $suppress;
3123 * Actually run and consume any "on transaction idle/resolution" callbacks.
3125 * This method should not be used outside of Database/LoadBalancer
3127 * @param int $trigger IDatabase::TRIGGER_* constant
3131 public function runOnTransactionIdleCallbacks( $trigger ) {
3132 if ( $this->trxEndCallbacksSuppressed
) {
3136 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3137 /** @var Exception $e */
3138 $e = null; // first exception
3139 do { // callbacks may add callbacks :)
3140 $callbacks = array_merge(
3141 $this->trxIdleCallbacks
,
3142 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3144 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3145 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3146 foreach ( $callbacks as $callback ) {
3148 list( $phpCallback ) = $callback;
3149 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3150 call_user_func_array( $phpCallback, [ $trigger ] );
3152 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3154 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3156 } catch ( Exception
$ex ) {
3157 call_user_func( $this->errorLogger
, $ex );
3159 // Some callbacks may use startAtomic/endAtomic, so make sure
3160 // their transactions are ended so other callbacks don't fail
3161 if ( $this->trxLevel() ) {
3162 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3166 } while ( count( $this->trxIdleCallbacks
) );
3168 if ( $e instanceof Exception
) {
3169 throw $e; // re-throw any first exception
3174 * Actually run and consume any "on transaction pre-commit" callbacks.
3176 * This method should not be used outside of Database/LoadBalancer
3181 public function runOnTransactionPreCommitCallbacks() {
3182 $e = null; // first exception
3183 do { // callbacks may add callbacks :)
3184 $callbacks = $this->trxPreCommitCallbacks
;
3185 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3186 foreach ( $callbacks as $callback ) {
3188 list( $phpCallback ) = $callback;
3189 call_user_func( $phpCallback );
3190 } catch ( Exception
$ex ) {
3191 call_user_func( $this->errorLogger
, $ex );
3195 } while ( count( $this->trxPreCommitCallbacks
) );
3197 if ( $e instanceof Exception
) {
3198 throw $e; // re-throw any first exception
3203 * Actually run any "transaction listener" callbacks.
3205 * This method should not be used outside of Database/LoadBalancer
3207 * @param int $trigger IDatabase::TRIGGER_* constant
3211 public function runTransactionListenerCallbacks( $trigger ) {
3212 if ( $this->trxEndCallbacksSuppressed
) {
3216 /** @var Exception $e */
3217 $e = null; // first exception
3219 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3221 $phpCallback( $trigger, $this );
3222 } catch ( Exception
$ex ) {
3223 call_user_func( $this->errorLogger
, $ex );
3228 if ( $e instanceof Exception
) {
3229 throw $e; // re-throw any first exception
3233 final public function startAtomic( $fname = __METHOD__
) {
3234 if ( !$this->trxLevel
) {
3235 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3236 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3237 // in all changes being in one transaction to keep requests transactional.
3238 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3239 $this->trxAutomaticAtomic
= true;
3243 $this->trxAtomicLevels
[] = $fname;
3246 final public function endAtomic( $fname = __METHOD__
) {
3247 if ( !$this->trxLevel
) {
3248 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3250 if ( !$this->trxAtomicLevels ||
3251 array_pop( $this->trxAtomicLevels
) !== $fname
3253 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3256 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3257 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3261 final public function doAtomicSection( $fname, callable
$callback ) {
3262 $this->startAtomic( $fname );
3264 $res = call_user_func_array( $callback, [ $this, $fname ] );
3265 } catch ( Exception
$e ) {
3266 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3269 $this->endAtomic( $fname );
3274 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3275 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3276 if ( $this->trxLevel
) {
3277 if ( $this->trxAtomicLevels
) {
3278 $levels = implode( ', ', $this->trxAtomicLevels
);
3279 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3280 throw new DBUnexpectedError( $this, $msg );
3281 } elseif ( !$this->trxAutomatic
) {
3282 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3283 throw new DBUnexpectedError( $this, $msg );
3285 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3286 throw new DBUnexpectedError( $this, $msg );
3288 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3289 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3290 throw new DBUnexpectedError( $this, $msg );
3293 // Avoid fatals if close() was called
3294 $this->assertOpen();
3296 $this->doBegin( $fname );
3297 $this->trxTimestamp
= microtime( true );
3298 $this->trxFname
= $fname;
3299 $this->trxDoneWrites
= false;
3300 $this->trxAutomaticAtomic
= false;
3301 $this->trxAtomicLevels
= [];
3302 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3303 $this->trxWriteDuration
= 0.0;
3304 $this->trxWriteQueryCount
= 0;
3305 $this->trxWriteAffectedRows
= 0;
3306 $this->trxWriteAdjDuration
= 0.0;
3307 $this->trxWriteAdjQueryCount
= 0;
3308 $this->trxWriteCallers
= [];
3309 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3310 // Get an estimate of the replica DB lag before then, treating estimate staleness
3311 // as lag itself just to be safe
3312 $status = $this->getApproximateLagStatus();
3313 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3314 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3315 // caller will think its OK to muck around with the transaction just because startAtomic()
3316 // has not yet completed (e.g. setting trxAtomicLevels).
3317 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3321 * Issues the BEGIN command to the database server.
3323 * @see Database::begin()
3324 * @param string $fname
3326 protected function doBegin( $fname ) {
3327 $this->query( 'BEGIN', $fname );
3328 $this->trxLevel
= 1;
3331 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3332 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3333 // There are still atomic sections open. This cannot be ignored
3334 $levels = implode( ', ', $this->trxAtomicLevels
);
3335 throw new DBUnexpectedError(
3337 "$fname: Got COMMIT while atomic sections $levels are still open."
3341 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3342 if ( !$this->trxLevel
) {
3343 return; // nothing to do
3344 } elseif ( !$this->trxAutomatic
) {
3345 throw new DBUnexpectedError(
3347 "$fname: Flushing an explicit transaction, getting out of sync."
3351 if ( !$this->trxLevel
) {
3352 $this->queryLogger
->error(
3353 "$fname: No transaction to commit, something got out of sync." );
3354 return; // nothing to do
3355 } elseif ( $this->trxAutomatic
) {
3356 throw new DBUnexpectedError(
3358 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3363 // Avoid fatals if close() was called
3364 $this->assertOpen();
3366 $this->runOnTransactionPreCommitCallbacks();
3367 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3368 $this->doCommit( $fname );
3369 if ( $this->trxDoneWrites
) {
3370 $this->lastWriteTime
= microtime( true );
3371 $this->trxProfiler
->transactionWritingOut(
3376 $this->trxWriteAffectedRows
3380 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3381 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3385 * Issues the COMMIT command to the database server.
3387 * @see Database::commit()
3388 * @param string $fname
3390 protected function doCommit( $fname ) {
3391 if ( $this->trxLevel
) {
3392 $this->query( 'COMMIT', $fname );
3393 $this->trxLevel
= 0;
3397 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3398 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3399 if ( !$this->trxLevel
) {
3400 return; // nothing to do
3403 if ( !$this->trxLevel
) {
3404 $this->queryLogger
->error(
3405 "$fname: No transaction to rollback, something got out of sync." );
3406 return; // nothing to do
3407 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3408 throw new DBUnexpectedError(
3410 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3415 // Avoid fatals if close() was called
3416 $this->assertOpen();
3418 $this->doRollback( $fname );
3419 $this->trxAtomicLevels
= [];
3420 if ( $this->trxDoneWrites
) {
3421 $this->trxProfiler
->transactionWritingOut(
3428 $this->trxIdleCallbacks
= []; // clear
3429 $this->trxPreCommitCallbacks
= []; // clear
3431 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3432 } catch ( Exception
$e ) {
3433 // already logged; finish and let LoadBalancer move on during mass-rollback
3436 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3437 } catch ( Exception
$e ) {
3438 // already logged; let LoadBalancer move on during mass-rollback
3441 $this->affectedRowCount
= 0; // for the sake of consistency
3445 * Issues the ROLLBACK command to the database server.
3447 * @see Database::rollback()
3448 * @param string $fname
3450 protected function doRollback( $fname ) {
3451 if ( $this->trxLevel
) {
3452 # Disconnects cause rollback anyway, so ignore those errors
3453 $ignoreErrors = true;
3454 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3455 $this->trxLevel
= 0;
3459 public function flushSnapshot( $fname = __METHOD__
) {
3460 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3461 // This only flushes transactions to clear snapshots, not to write data
3462 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3463 throw new DBUnexpectedError(
3465 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3469 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3472 public function explicitTrxActive() {
3473 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3476 public function duplicateTableStructure(
3477 $oldName, $newName, $temporary = false, $fname = __METHOD__
3479 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3482 public function listTables( $prefix = null, $fname = __METHOD__
) {
3483 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3486 public function listViews( $prefix = null, $fname = __METHOD__
) {
3487 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3490 public function timestamp( $ts = 0 ) {
3491 $t = new ConvertibleTimestamp( $ts );
3492 // Let errors bubble up to avoid putting garbage in the DB
3493 return $t->getTimestamp( TS_MW
);
3496 public function timestampOrNull( $ts = null ) {
3497 if ( is_null( $ts ) ) {
3500 return $this->timestamp( $ts );
3504 public function affectedRows() {
3505 return ( $this->affectedRowCount
=== null )
3506 ?
$this->fetchAffectedRowCount() // default to driver value
3507 : $this->affectedRowCount
;
3511 * @return int Number of retrieved rows according to the driver
3513 abstract protected function fetchAffectedRowCount();
3516 * Take the result from a query, and wrap it in a ResultWrapper if
3517 * necessary. Boolean values are passed through as is, to indicate success
3518 * of write queries or failure.
3520 * Once upon a time, Database::query() returned a bare MySQL result
3521 * resource, and it was necessary to call this function to convert it to
3522 * a wrapper. Nowadays, raw database objects are never exposed to external
3523 * callers, so this is unnecessary in external code.
3525 * @param bool|ResultWrapper|resource|object $result
3526 * @return bool|ResultWrapper
3528 protected function resultObject( $result ) {
3531 } elseif ( $result instanceof ResultWrapper
) {
3533 } elseif ( $result === true ) {
3534 // Successful write query
3537 return new ResultWrapper( $this, $result );
3541 public function ping( &$rtt = null ) {
3542 // Avoid hitting the server if it was hit recently
3543 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3544 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3545 $rtt = $this->rttEstimate
;
3546 return true; // don't care about $rtt
3550 // This will reconnect if possible or return false if not
3551 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3552 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3553 $this->restoreFlags( self
::RESTORE_PRIOR
);
3556 $rtt = $this->rttEstimate
;
3563 * Close existing database connection and open a new connection
3565 * @return bool True if new connection is opened successfully, false if error
3567 protected function reconnect() {
3568 $this->closeConnection();
3569 $this->opened
= false;
3570 $this->conn
= false;
3572 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3573 $this->lastPing
= microtime( true );
3575 } catch ( DBConnectionError
$e ) {
3582 public function getSessionLagStatus() {
3583 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3587 * Get the replica DB lag when the current transaction started
3589 * This is useful when transactions might use snapshot isolation
3590 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3591 * is this lag plus transaction duration. If they don't, it is still
3592 * safe to be pessimistic. This returns null if there is no transaction.
3594 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3597 protected function getTransactionLagStatus() {
3598 return $this->trxLevel
3599 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3604 * Get a replica DB lag estimate for this server
3606 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3609 protected function getApproximateLagStatus() {
3611 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3612 'since' => microtime( true )
3617 * Merge the result of getSessionLagStatus() for several DBs
3618 * using the most pessimistic values to estimate the lag of
3619 * any data derived from them in combination
3621 * This is information is useful for caching modules
3623 * @see WANObjectCache::set()
3624 * @see WANObjectCache::getWithSetCallback()
3626 * @param IDatabase $db1
3627 * @param IDatabase $db2 [optional]
3628 * @return array Map of values:
3629 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3630 * - since: oldest UNIX timestamp of any of the DB lag estimates
3631 * - pending: whether any of the DBs have uncommitted changes
3635 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3636 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3637 foreach ( func_get_args() as $db ) {
3638 /** @var IDatabase $db */
3639 $status = $db->getSessionLagStatus();
3640 if ( $status['lag'] === false ) {
3641 $res['lag'] = false;
3642 } elseif ( $res['lag'] !== false ) {
3643 $res['lag'] = max( $res['lag'], $status['lag'] );
3645 $res['since'] = min( $res['since'], $status['since'] );
3646 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3652 public function getLag() {
3656 public function maxListLen() {
3660 public function encodeBlob( $b ) {
3664 public function decodeBlob( $b ) {
3665 if ( $b instanceof Blob
) {
3671 public function setSessionOptions( array $options ) {
3674 public function sourceFile(
3676 callable
$lineCallback = null,
3677 callable
$resultCallback = null,
3679 callable
$inputCallback = null
3681 Wikimedia\
suppressWarnings();
3682 $fp = fopen( $filename, 'r' );
3683 Wikimedia\restoreWarnings
();
3685 if ( false === $fp ) {
3686 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3690 $fname = __METHOD__
. "( $filename )";
3694 $error = $this->sourceStream(
3695 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3696 } catch ( Exception
$e ) {
3706 public function setSchemaVars( $vars ) {
3707 $this->schemaVars
= $vars;
3710 public function sourceStream(
3712 callable
$lineCallback = null,
3713 callable
$resultCallback = null,
3714 $fname = __METHOD__
,
3715 callable
$inputCallback = null
3717 $delimiterReset = new ScopedCallback(
3718 function ( $delimiter ) {
3719 $this->delimiter
= $delimiter;
3721 [ $this->delimiter
]
3725 while ( !feof( $fp ) ) {
3726 if ( $lineCallback ) {
3727 call_user_func( $lineCallback );
3730 $line = trim( fgets( $fp ) );
3732 if ( $line == '' ) {
3736 if ( '-' == $line[0] && '-' == $line[1] ) {
3744 $done = $this->streamStatementEnd( $cmd, $line );
3748 if ( $done ||
feof( $fp ) ) {
3749 $cmd = $this->replaceVars( $cmd );
3751 if ( $inputCallback ) {
3752 $callbackResult = call_user_func( $inputCallback, $cmd );
3754 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3755 $cmd = $callbackResult;
3760 $res = $this->query( $cmd, $fname );
3762 if ( $resultCallback ) {
3763 call_user_func( $resultCallback, $res, $this );
3766 if ( false === $res ) {
3767 $err = $this->lastError();
3769 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3776 ScopedCallback
::consume( $delimiterReset );
3781 * Called by sourceStream() to check if we've reached a statement end
3783 * @param string &$sql SQL assembled so far
3784 * @param string &$newLine New line about to be added to $sql
3785 * @return bool Whether $newLine contains end of the statement
3787 public function streamStatementEnd( &$sql, &$newLine ) {
3788 if ( $this->delimiter
) {
3790 $newLine = preg_replace(
3791 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3792 if ( $newLine != $prev ) {
3801 * Database independent variable replacement. Replaces a set of variables
3802 * in an SQL statement with their contents as given by $this->getSchemaVars().
3804 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3806 * - '{$var}' should be used for text and is passed through the database's
3808 * - `{$var}` should be used for identifiers (e.g. table and database names).
3809 * It is passed through the database's addIdentifierQuotes method which
3810 * can be overridden if the database uses something other than backticks.
3811 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3812 * database's tableName method.
3813 * - / *i* / passes the name that follows through the database's indexName method.
3814 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3815 * its use should be avoided. In 1.24 and older, string encoding was applied.
3817 * @param string $ins SQL statement to replace variables in
3818 * @return string The new SQL statement with variables replaced
3820 protected function replaceVars( $ins ) {
3821 $vars = $this->getSchemaVars();
3822 return preg_replace_callback(
3824 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3825 \'\{\$ (\w+) }\' | # 3. addQuotes
3826 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3827 /\*\$ (\w+) \*/ # 5. leave unencoded
3829 function ( $m ) use ( $vars ) {
3830 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3831 // check for both nonexistent keys *and* the empty string.
3832 if ( isset( $m[1] ) && $m[1] !== '' ) {
3833 if ( $m[1] === 'i' ) {
3834 return $this->indexName( $m[2] );
3836 return $this->tableName( $m[2] );
3838 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3839 return $this->addQuotes( $vars[$m[3]] );
3840 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3841 return $this->addIdentifierQuotes( $vars[$m[4]] );
3842 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3843 return $vars[$m[5]];
3853 * Get schema variables. If none have been set via setSchemaVars(), then
3854 * use some defaults from the current object.
3858 protected function getSchemaVars() {
3859 if ( $this->schemaVars
) {
3860 return $this->schemaVars
;
3862 return $this->getDefaultSchemaVars();
3867 * Get schema variables to use if none have been set via setSchemaVars().
3869 * Override this in derived classes to provide variables for tables.sql
3870 * and SQL patch files.
3874 protected function getDefaultSchemaVars() {
3878 public function lockIsFree( $lockName, $method ) {
3879 // RDBMs methods for checking named locks may or may not count this thread itself.
3880 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3881 // the behavior choosen by the interface for this method.
3882 return !isset( $this->namedLocksHeld
[$lockName] );
3885 public function lock( $lockName, $method, $timeout = 5 ) {
3886 $this->namedLocksHeld
[$lockName] = 1;
3891 public function unlock( $lockName, $method ) {
3892 unset( $this->namedLocksHeld
[$lockName] );
3897 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3898 if ( $this->writesOrCallbacksPending() ) {
3899 // This only flushes transactions to clear snapshots, not to write data
3900 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3901 throw new DBUnexpectedError(
3903 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3907 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3911 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3912 if ( $this->trxLevel() ) {
3913 // There is a good chance an exception was thrown, causing any early return
3914 // from the caller. Let any error handler get a chance to issue rollback().
3915 // If there isn't one, let the error bubble up and trigger server-side rollback.
3916 $this->onTransactionResolution(
3917 function () use ( $lockKey, $fname ) {
3918 $this->unlock( $lockKey, $fname );
3923 $this->unlock( $lockKey, $fname );
3927 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3932 public function namedLocksEnqueue() {
3936 public function tableLocksHaveTransactionScope() {
3940 final public function lockTables( array $read, array $write, $method ) {
3941 if ( $this->writesOrCallbacksPending() ) {
3942 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3945 if ( $this->tableLocksHaveTransactionScope() ) {
3946 $this->startAtomic( $method );
3949 return $this->doLockTables( $read, $write, $method );
3953 * Helper function for lockTables() that handles the actual table locking
3955 * @param array $read Array of tables to lock for read access
3956 * @param array $write Array of tables to lock for write access
3957 * @param string $method Name of caller
3960 protected function doLockTables( array $read, array $write, $method ) {
3964 final public function unlockTables( $method ) {
3965 if ( $this->tableLocksHaveTransactionScope() ) {
3966 $this->endAtomic( $method );
3968 return true; // locks released on COMMIT/ROLLBACK
3971 return $this->doUnlockTables( $method );
3975 * Helper function for unlockTables() that handles the actual table unlocking
3977 * @param string $method Name of caller
3980 protected function doUnlockTables( $method ) {
3986 * @param string $tableName
3987 * @param string $fName
3988 * @return bool|ResultWrapper
3991 public function dropTable( $tableName, $fName = __METHOD__
) {
3992 if ( !$this->tableExists( $tableName, $fName ) ) {
3995 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3997 return $this->query( $sql, $fName );
4000 public function getInfinity() {
4004 public function encodeExpiry( $expiry ) {
4005 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4006 ?
$this->getInfinity()
4007 : $this->timestamp( $expiry );
4010 public function decodeExpiry( $expiry, $format = TS_MW
) {
4011 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4015 return ConvertibleTimestamp
::convert( $format, $expiry );
4018 public function setBigSelects( $value = true ) {
4022 public function isReadOnly() {
4023 return ( $this->getReadOnlyReason() !== false );
4027 * @return string|bool Reason this DB is read-only or false if it is not
4029 protected function getReadOnlyReason() {
4030 $reason = $this->getLBInfo( 'readOnlyReason' );
4032 return is_string( $reason ) ?
$reason : false;
4035 public function setTableAliases( array $aliases ) {
4036 $this->tableAliases
= $aliases;
4039 public function setIndexAliases( array $aliases ) {
4040 $this->indexAliases
= $aliases;
4044 * Get the underlying binding connection handle
4046 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4047 * This catches broken callers than catch and ignore disconnection exceptions.
4048 * Unlike checking isOpen(), this is safe to call inside of open().
4051 * @throws DBUnexpectedError
4054 protected function getBindingHandle() {
4055 if ( !$this->conn
) {
4056 throw new DBUnexpectedError(
4058 'DB connection was already closed or the connection dropped.'
4069 public function __toString() {
4070 return (string)$this->conn
;
4074 * Make sure that copies do not share the same client binding handle
4075 * @throws DBConnectionError
4077 public function __clone() {
4078 $this->connLogger
->warning(
4079 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4080 ( new RuntimeException() )->getTraceAsString()
4083 if ( $this->isOpen() ) {
4084 // Open a new connection resource without messing with the old one
4085 $this->opened
= false;
4086 $this->conn
= false;
4087 $this->trxEndCallbacks
= []; // don't copy
4088 $this->handleSessionLoss(); // no trx or locks anymore
4089 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4090 $this->lastPing
= microtime( true );
4095 * Called by serialize. Throw an exception when DB connection is serialized.
4096 * This causes problems on some database engines because the connection is
4097 * not restored on unserialize.
4099 public function __sleep() {
4100 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4101 'the connection is not restored on wakeup.' );
4105 * Run a few simple sanity checks and close dangling connections
4107 public function __destruct() {
4108 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4109 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4112 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4113 if ( $danglingWriters ) {
4114 $fnames = implode( ', ', $danglingWriters );
4115 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4118 if ( $this->conn
) {
4119 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4120 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4121 Wikimedia\
suppressWarnings();
4122 $this->closeConnection();
4123 Wikimedia\restoreWarnings
();
4124 $this->conn
= false;
4125 $this->opened
= false;
4130 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4131 class_alias( Database
::class, 'Database' ); // b/c global alias