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
;
38 use UnexpectedValueException
;
43 * Relational database abstraction object
48 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
49 /** Number of times to re-try an operation in case of deadlock */
50 const DEADLOCK_TRIES
= 4;
51 /** Minimum time to wait before retry, in microseconds */
52 const DEADLOCK_DELAY_MIN
= 500000;
53 /** Maximum time to wait before retry */
54 const DEADLOCK_DELAY_MAX
= 1500000;
56 /** How long before it is worth doing a dummy query to test the connection */
58 const PING_QUERY
= 'SELECT 1 AS ping';
60 const TINY_WRITE_SEC
= 0.010;
61 const SLOW_WRITE_SEC
= 0.500;
62 const SMALL_WRITE_ROWS
= 100;
64 /** @var string Whether lock granularity is on the level of the entire database */
65 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
67 /** @var int New Database instance will not be connected yet when returned */
68 const NEW_UNCONNECTED
= 0;
69 /** @var int New Database instance will already be connected when returned */
70 const NEW_CONNECTED
= 1;
72 /** @var string SQL query */
73 protected $lastQuery = '';
74 /** @var float|bool UNIX timestamp of last write query */
75 protected $lastWriteTime = false;
76 /** @var string|bool */
77 protected $phpError = false;
78 /** @var string Server that this instance is currently connected to */
80 /** @var string User that this instance is currently connected under the name of */
82 /** @var string Password used to establish the current connection */
84 /** @var string Database that this instance is currently connected to */
86 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
87 protected $tableAliases = [];
88 /** @var string[] Map of (index alias => index) */
89 protected $indexAliases = [];
90 /** @var bool Whether this PHP instance is for a CLI script */
92 /** @var string Agent name for query profiling */
94 /** @var array Parameters used by initConnection() to establish a connection */
95 protected $connectionParams = [];
96 /** @var BagOStuff APC cache */
98 /** @var LoggerInterface */
99 protected $connLogger;
100 /** @var LoggerInterface */
101 protected $queryLogger;
102 /** @var callback Error logging callback */
103 protected $errorLogger;
104 /** @var callback Deprecation logging callback */
105 protected $deprecationLogger;
107 /** @var resource|null Database connection */
108 protected $conn = null;
110 protected $opened = false;
112 /** @var array[] List of (callable, method name) */
113 protected $trxIdleCallbacks = [];
114 /** @var array[] List of (callable, method name) */
115 protected $trxPreCommitCallbacks = [];
116 /** @var array[] List of (callable, method name) */
117 protected $trxEndCallbacks = [];
118 /** @var callable[] Map of (name => callable) */
119 protected $trxRecurringCallbacks = [];
120 /** @var bool Whether to suppress triggering of transaction end callbacks */
121 protected $trxEndCallbacksSuppressed = false;
124 protected $tablePrefix = '';
126 protected $schema = '';
130 protected $lbInfo = [];
131 /** @var array|bool */
132 protected $schemaVars = false;
134 protected $sessionVars = [];
135 /** @var array|null */
136 protected $preparedArgs;
137 /** @var string|bool|null Stashed value of html_errors INI setting */
138 protected $htmlErrors;
140 protected $delimiter = ';';
141 /** @var DatabaseDomain */
142 protected $currentDomain;
143 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
144 protected $affectedRowCount;
147 * @var int Transaction status
149 protected $trxStatus = self
::STATUS_TRX_NONE
;
151 * @var Exception|null The last error that caused the status to become STATUS_TRX_ERROR
153 protected $trxStatusCause;
155 * @var array|null If wasKnownStatementRollbackError() prevented trxStatus from being set,
156 * the relevant details are stored here.
158 protected $trxStatusIgnoredCause;
160 * Either 1 if a transaction is active or 0 otherwise.
161 * The other Trx fields may not be meaningfull if this is 0.
165 protected $trxLevel = 0;
167 * Either a short hexidecimal string if a transaction is active or ""
170 * @see Database::trxLevel
172 protected $trxShortId = '';
174 * The UNIX time that the transaction started. Callers can assume that if
175 * snapshot isolation is used, then the data is *at least* up to date to that
176 * point (possibly more up-to-date since the first SELECT defines the snapshot).
179 * @see Database::trxLevel
181 private $trxTimestamp = null;
182 /** @var float Lag estimate at the time of BEGIN */
183 private $trxReplicaLag = null;
185 * Remembers the function name given for starting the most recent transaction via begin().
186 * Used to provide additional context for error reporting.
189 * @see Database::trxLevel
191 private $trxFname = null;
193 * Record if possible write queries were done in the last transaction started
196 * @see Database::trxLevel
198 private $trxDoneWrites = false;
200 * Record if the current transaction was started implicitly due to DBO_TRX being set.
203 * @see Database::trxLevel
205 private $trxAutomatic = false;
207 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
211 private $trxAtomicCounter = 0;
213 * Array of levels of atomicity within transactions
215 * @var array List of (name, unique ID, savepoint ID)
217 private $trxAtomicLevels = [];
219 * Record if the current transaction was started implicitly by Database::startAtomic
223 private $trxAutomaticAtomic = false;
225 * Track the write query callers of the current transaction
229 private $trxWriteCallers = [];
231 * @var float Seconds spent in write queries for the current transaction
233 private $trxWriteDuration = 0.0;
235 * @var int Number of write queries for the current transaction
237 private $trxWriteQueryCount = 0;
239 * @var int Number of rows affected by write queries for the current transaction
241 private $trxWriteAffectedRows = 0;
243 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
245 private $trxWriteAdjDuration = 0.0;
247 * @var int Number of write queries counted in trxWriteAdjDuration
249 private $trxWriteAdjQueryCount = 0;
251 * @var float RTT time estimate
253 private $rttEstimate = 0.0;
255 /** @var array Map of (name => 1) for locks obtained via lock() */
256 private $namedLocksHeld = [];
257 /** @var array Map of (table name => 1) for TEMPORARY tables */
258 protected $sessionTempTables = [];
260 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
261 private $lazyMasterHandle;
263 /** @var float UNIX timestamp */
264 protected $lastPing = 0.0;
266 /** @var int[] Prior flags member variable values */
267 private $priorFlags = [];
269 /** @var object|string Class name or object With profileIn/profileOut methods */
271 /** @var TransactionProfiler */
272 protected $trxProfiler;
275 protected $nonNativeInsertSelectBatchSize = 10000;
277 /** @var int Transaction is in a error state requiring a full or savepoint rollback */
278 const STATUS_TRX_ERROR
= 1;
279 /** @var int Transaction is active and in a normal state */
280 const STATUS_TRX_OK
= 2;
281 /** @var int No transaction is active */
282 const STATUS_TRX_NONE
= 3;
285 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
286 * @param array $params Parameters passed from Database::factory()
288 protected function __construct( array $params ) {
289 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
290 $this->connectionParams
[$name] = $params[$name];
293 $this->schema
= $params['schema'];
294 $this->tablePrefix
= $params['tablePrefix'];
296 $this->cliMode
= $params['cliMode'];
297 // Agent name is added to SQL queries in a comment, so make sure it can't break out
298 $this->agent
= str_replace( '/', '-', $params['agent'] );
300 $this->flags
= $params['flags'];
301 if ( $this->flags
& self
::DBO_DEFAULT
) {
302 if ( $this->cliMode
) {
303 $this->flags
&= ~self
::DBO_TRX
;
305 $this->flags |
= self
::DBO_TRX
;
308 // Disregard deprecated DBO_IGNORE flag (T189999)
309 $this->flags
&= ~self
::DBO_IGNORE
;
311 $this->sessionVars
= $params['variables'];
313 $this->srvCache
= isset( $params['srvCache'] )
314 ?
$params['srvCache']
315 : new HashBagOStuff();
317 $this->profiler
= $params['profiler'];
318 $this->trxProfiler
= $params['trxProfiler'];
319 $this->connLogger
= $params['connLogger'];
320 $this->queryLogger
= $params['queryLogger'];
321 $this->errorLogger
= $params['errorLogger'];
322 $this->deprecationLogger
= $params['deprecationLogger'];
324 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
325 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
328 // Set initial dummy domain until open() sets the final DB/prefix
329 $this->currentDomain
= DatabaseDomain
::newUnspecified();
333 * Initialize the connection to the database over the wire (or to local files)
335 * @throws LogicException
336 * @throws InvalidArgumentException
337 * @throws DBConnectionError
340 final public function initConnection() {
341 if ( $this->isOpen() ) {
342 throw new LogicException( __METHOD__
. ': already connected.' );
344 // Establish the connection
345 $this->doInitConnection();
346 // Set the domain object after open() sets the relevant fields
347 if ( $this->dbName
!= '' ) {
348 // Domains with server scope but a table prefix are not used by IDatabase classes
349 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
354 * Actually connect to the database over the wire (or to local files)
356 * @throws InvalidArgumentException
357 * @throws DBConnectionError
360 protected function doInitConnection() {
361 if ( strlen( $this->connectionParams
['user'] ) ) {
363 $this->connectionParams
['host'],
364 $this->connectionParams
['user'],
365 $this->connectionParams
['password'],
366 $this->connectionParams
['dbname']
369 throw new InvalidArgumentException( "No database user provided." );
374 * Construct a Database subclass instance given a database type and parameters
376 * This also connects to the database immediately upon object construction
378 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
379 * @param array $p Parameter map with keys:
380 * - host : The hostname of the DB server
381 * - user : The name of the database user the client operates under
382 * - password : The password for the database user
383 * - dbname : The name of the database to use where queries do not specify one.
384 * The database must exist or an error might be thrown. Setting this to the empty string
385 * will avoid any such errors and make the handle have no implicit database scope. This is
386 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
387 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
388 * in which user names and such are defined, e.g. users are database-specific in Postgres.
389 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
390 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
391 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
392 * recognized in queries. This can be used in place of schemas for handle site farms.
393 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
394 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
395 * flag in place UNLESS this this database simply acts as a key/value store.
396 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
397 * 'mysqli' driver; the old one 'mysql' has been removed.
398 * - variables: Optional map of session variables to set after connecting. This can be
399 * used to adjust lock timeouts or encoding modes and the like.
400 * - connLogger: Optional PSR-3 logger interface instance.
401 * - queryLogger: Optional PSR-3 logger interface instance.
402 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
403 * These will be called in query(), using a simplified version of the SQL that also
404 * includes the agent as a SQL comment.
405 * - trxProfiler: Optional TransactionProfiler instance.
406 * - errorLogger: Optional callback that takes an Exception and logs it.
407 * - deprecationLogger: Optional callback that takes a string and logs it.
408 * - cliMode: Whether to consider the execution context that of a CLI script.
409 * - agent: Optional name used to identify the end-user in query profiling/logging.
410 * - srvCache: Optional BagOStuff instance to an APC-style cache.
411 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
412 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
413 * @return Database|null If the database driver or extension cannot be found
414 * @throws InvalidArgumentException If the database driver or extension cannot be found
417 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
418 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
420 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
421 // Resolve some defaults for b/c
422 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
423 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
424 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
425 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
426 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
427 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
428 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
429 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
430 $p['cliMode'] = isset( $p['cliMode'] )
432 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
433 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
434 if ( !isset( $p['connLogger'] ) ) {
435 $p['connLogger'] = new NullLogger();
437 if ( !isset( $p['queryLogger'] ) ) {
438 $p['queryLogger'] = new NullLogger();
440 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
441 if ( !isset( $p['trxProfiler'] ) ) {
442 $p['trxProfiler'] = new TransactionProfiler();
444 if ( !isset( $p['errorLogger'] ) ) {
445 $p['errorLogger'] = function ( Exception
$e ) {
446 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
449 if ( !isset( $p['deprecationLogger'] ) ) {
450 $p['deprecationLogger'] = function ( $msg ) {
451 trigger_error( $msg, E_USER_DEPRECATED
);
455 /** @var Database $conn */
456 $conn = new $class( $p );
457 if ( $connect == self
::NEW_CONNECTED
) {
458 $conn->initConnection();
468 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
469 * @param string|null $driver Optional name of a specific DB client driver
470 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
471 * @throws InvalidArgumentException
474 final public static function attributesFromType( $dbType, $driver = null ) {
475 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
477 $class = self
::getClass( $dbType, $driver );
479 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
483 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
484 * @param string|null $driver Optional name of a specific DB client driver
485 * @return string Database subclass name to use
486 * @throws InvalidArgumentException
488 private static function getClass( $dbType, $driver = null ) {
489 // For database types with built-in support, the below maps type to IDatabase
490 // implementations. For types with multipe driver implementations (PHP extensions),
491 // an array can be used, keyed by extension name. In case of an array, the
492 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
493 // we auto-detect the first available driver. For types without built-in support,
494 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
495 static $builtinTypes = [
496 'mssql' => DatabaseMssql
::class,
497 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
498 'sqlite' => DatabaseSqlite
::class,
499 'postgres' => DatabasePostgres
::class,
502 $dbType = strtolower( $dbType );
505 if ( isset( $builtinTypes[$dbType] ) ) {
506 $possibleDrivers = $builtinTypes[$dbType];
507 if ( is_string( $possibleDrivers ) ) {
508 $class = $possibleDrivers;
510 if ( (string)$driver !== '' ) {
511 if ( !isset( $possibleDrivers[$driver] ) ) {
512 throw new InvalidArgumentException( __METHOD__
.
513 " type '$dbType' does not support driver '{$driver}'" );
515 $class = $possibleDrivers[$driver];
518 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
519 if ( extension_loaded( $posDriver ) ) {
520 $class = $possibleClass;
527 $class = 'Database' . ucfirst( $dbType );
530 if ( $class === false ) {
531 throw new InvalidArgumentException( __METHOD__
.
532 " no viable database extension found for type '$dbType'" );
539 * @return array Map of (Database::ATTRIBUTE_* constant => value
542 protected static function getAttributes() {
547 * Set the PSR-3 logger interface to use for query logging. (The logger
548 * interfaces for connection logging and error logging can be set with the
551 * @param LoggerInterface $logger
553 public function setLogger( LoggerInterface
$logger ) {
554 $this->queryLogger
= $logger;
557 public function getServerInfo() {
558 return $this->getServerVersion();
561 public function bufferResults( $buffer = null ) {
562 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
563 if ( $buffer !== null ) {
565 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
566 : $this->setFlag( self
::DBO_NOBUFFER
);
572 public function trxLevel() {
573 return $this->trxLevel
;
576 public function trxTimestamp() {
577 return $this->trxLevel ?
$this->trxTimestamp
: null;
581 * @return int One of the STATUS_TRX_* class constants
584 public function trxStatus() {
585 return $this->trxStatus
;
588 public function tablePrefix( $prefix = null ) {
589 $old = $this->tablePrefix
;
590 if ( $prefix !== null ) {
591 $this->tablePrefix
= $prefix;
592 $this->currentDomain
= ( $this->dbName
!= '' )
593 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
594 : DatabaseDomain
::newUnspecified();
600 public function dbSchema( $schema = null ) {
601 $old = $this->schema
;
602 if ( $schema !== null ) {
603 $this->schema
= $schema;
609 public function getLBInfo( $name = null ) {
610 if ( is_null( $name ) ) {
611 return $this->lbInfo
;
613 if ( array_key_exists( $name, $this->lbInfo
) ) {
614 return $this->lbInfo
[$name];
621 public function setLBInfo( $name, $value = null ) {
622 if ( is_null( $value ) ) {
623 $this->lbInfo
= $name;
625 $this->lbInfo
[$name] = $value;
629 public function setLazyMasterHandle( IDatabase
$conn ) {
630 $this->lazyMasterHandle
= $conn;
634 * @return IDatabase|null
635 * @see setLazyMasterHandle()
638 protected function getLazyMasterHandle() {
639 return $this->lazyMasterHandle
;
642 public function implicitGroupby() {
646 public function implicitOrderby() {
650 public function lastQuery() {
651 return $this->lastQuery
;
654 public function doneWrites() {
655 return (bool)$this->lastWriteTime
;
658 public function lastDoneWrites() {
659 return $this->lastWriteTime ?
: false;
662 public function writesPending() {
663 return $this->trxLevel
&& $this->trxDoneWrites
;
666 public function writesOrCallbacksPending() {
667 return $this->trxLevel
&& (
668 $this->trxDoneWrites ||
669 $this->trxIdleCallbacks ||
670 $this->trxPreCommitCallbacks ||
671 $this->trxEndCallbacks
676 * @return string|null
678 final protected function getTransactionRoundId() {
679 // If transaction round participation is enabled, see if one is active
680 if ( $this->getFlag( self
::DBO_TRX
) ) {
681 $id = $this->getLBInfo( 'trxRoundId' );
683 return is_string( $id ) ?
$id : null;
689 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
690 if ( !$this->trxLevel
) {
692 } elseif ( !$this->trxDoneWrites
) {
697 case self
::ESTIMATE_DB_APPLY
:
699 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
700 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
701 // For omitted queries, make them count as something at least
702 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
703 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
706 default: // everything
707 return $this->trxWriteDuration
;
711 public function pendingWriteCallers() {
712 return $this->trxLevel ?
$this->trxWriteCallers
: [];
715 public function pendingWriteRowsAffected() {
716 return $this->trxWriteAffectedRows
;
720 * Get the list of method names that have pending write queries or callbacks
721 * for this transaction
725 protected function pendingWriteAndCallbackCallers() {
726 if ( !$this->trxLevel
) {
730 $fnames = $this->trxWriteCallers
;
732 $this->trxIdleCallbacks
,
733 $this->trxPreCommitCallbacks
,
734 $this->trxEndCallbacks
736 foreach ( $callbacks as $callback ) {
737 $fnames[] = $callback[1];
747 private function flatAtomicSectionList() {
748 return array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
749 return $accum === null ?
$v[0] : "$accum, " . $v[0];
753 public function isOpen() {
754 return $this->opened
;
757 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
758 if ( ( $flag & self
::DBO_IGNORE
) ) {
759 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
762 if ( $remember === self
::REMEMBER_PRIOR
) {
763 array_push( $this->priorFlags
, $this->flags
);
765 $this->flags |
= $flag;
768 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
769 if ( ( $flag & self
::DBO_IGNORE
) ) {
770 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
773 if ( $remember === self
::REMEMBER_PRIOR
) {
774 array_push( $this->priorFlags
, $this->flags
);
776 $this->flags
&= ~
$flag;
779 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
780 if ( !$this->priorFlags
) {
784 if ( $state === self
::RESTORE_INITIAL
) {
785 $this->flags
= reset( $this->priorFlags
);
786 $this->priorFlags
= [];
788 $this->flags
= array_pop( $this->priorFlags
);
792 public function getFlag( $flag ) {
793 return !!( $this->flags
& $flag );
797 * @param string $name Class field name
799 * @deprecated Since 1.28
801 public function getProperty( $name ) {
805 public function getDomainID() {
806 return $this->currentDomain
->getId();
809 final public function getWikiID() {
810 return $this->getDomainID();
814 * Get information about an index into an object
815 * @param string $table Table name
816 * @param string $index Index name
817 * @param string $fname Calling function name
818 * @return mixed Database-specific index description class or false if the index does not exist
820 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
823 * Wrapper for addslashes()
825 * @param string $s String to be slashed.
826 * @return string Slashed string.
828 abstract function strencode( $s );
831 * Set a custom error handler for logging errors during database connection
833 protected function installErrorHandler() {
834 $this->phpError
= false;
835 $this->htmlErrors
= ini_set( 'html_errors', '0' );
836 set_error_handler( [ $this, 'connectionErrorLogger' ] );
840 * Restore the previous error handler and return the last PHP error for this DB
842 * @return bool|string
844 protected function restoreErrorHandler() {
845 restore_error_handler();
846 if ( $this->htmlErrors
!== false ) {
847 ini_set( 'html_errors', $this->htmlErrors
);
850 return $this->getLastPHPError();
854 * @return string|bool Last PHP error for this DB (typically connection errors)
856 protected function getLastPHPError() {
857 if ( $this->phpError
) {
858 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
859 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
868 * Error handler for logging errors during database connection
869 * This method should not be used outside of Database classes
872 * @param string $errstr
874 public function connectionErrorLogger( $errno, $errstr ) {
875 $this->phpError
= $errstr;
879 * Create a log context to pass to PSR-3 logger functions.
881 * @param array $extras Additional data to add to context
884 protected function getLogContext( array $extras = [] ) {
887 'db_server' => $this->server
,
888 'db_name' => $this->dbName
,
889 'db_user' => $this->user
,
895 final public function close() {
896 $exception = null; // error to throw after disconnecting
899 // Resolve any dangling transaction first
900 if ( $this->trxLevel
) {
901 if ( $this->trxAtomicLevels
) {
902 // Cannot let incomplete atomic sections be committed
903 $levels = $this->flatAtomicSectionList();
904 $exception = new DBUnexpectedError(
906 __METHOD__
. ": atomic sections $levels are still open."
908 } elseif ( $this->trxAutomatic
) {
909 // Only the connection manager can commit non-empty DBO_TRX transactions
910 if ( $this->writesOrCallbacksPending() ) {
911 $exception = new DBUnexpectedError(
914 ": mass commit/rollback of peer transaction required (DBO_TRX set)."
917 } elseif ( $this->trxLevel
) {
918 // Commit explicit transactions as if this was commit()
919 $this->queryLogger
->warning(
920 __METHOD__
. ": writes or callbacks still pending.",
921 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
925 if ( $this->trxEndCallbacksSuppressed
) {
926 $exception = $exception ?
: new DBUnexpectedError(
928 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
932 // Commit or rollback the changes and run any callbacks as needed
933 if ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& !$exception ) {
936 $this->trxAutomatic ? self
::FLUSHING_INTERNAL
: self
::FLUSHING_ONE
939 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
943 // Close the actual connection in the binding handle
944 $closed = $this->closeConnection();
947 $closed = true; // already closed; nothing to do
950 $this->opened
= false;
952 // Throw any unexpected errors after having disconnected
953 if ( $exception instanceof Exception
) {
957 // Sanity check that no callbacks are dangling
959 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
961 throw new RuntimeException(
962 "Transaction callbacks are still pending:\n" .
963 implode( ', ', $this->pendingWriteAndCallbackCallers() )
971 * Make sure isOpen() returns true as a sanity check
973 * @throws DBUnexpectedError
975 protected function assertOpen() {
976 if ( !$this->isOpen() ) {
977 throw new DBUnexpectedError( $this, "DB connection was already closed." );
982 * Closes underlying database connection
984 * @return bool Whether connection was closed successfully
986 abstract protected function closeConnection();
989 * @param string $error Fallback error message, used if none is given by DB
990 * @throws DBConnectionError
992 public function reportConnectionError( $error = 'Unknown error' ) {
993 $myError = $this->lastError();
999 throw new DBConnectionError( $this, $error );
1003 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
1005 * This might return things, such as mysqli_result, that do not formally implement
1006 * IResultWrapper, but nonetheless implement all of its methods correctly
1008 * @param string $sql SQL query.
1009 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
1011 abstract protected function doQuery( $sql );
1014 * Determine whether a query writes to the DB.
1015 * Should return true if unsure.
1017 * @param string $sql
1020 protected function isWriteQuery( $sql ) {
1022 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1026 * @param string $sql
1027 * @return string|null
1029 protected function getQueryVerb( $sql ) {
1030 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
1034 * Determine whether a SQL statement is sensitive to isolation level.
1035 * A SQL statement is considered transactable if its result could vary
1036 * depending on the transaction isolation level. Operational commands
1037 * such as 'SET' and 'SHOW' are not considered to be transactable.
1039 * @param string $sql
1042 protected function isTransactableQuery( $sql ) {
1044 $this->getQueryVerb( $sql ),
1045 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
1051 * @param string $sql A SQL query
1052 * @return bool Whether $sql is SQL for TEMPORARY table operation
1054 protected function registerTempTableOperation( $sql ) {
1056 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1060 $this->sessionTempTables
[$matches[1]] = 1;
1063 } elseif ( preg_match(
1064 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1068 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
1069 unset( $this->sessionTempTables
[$matches[1]] );
1072 } elseif ( preg_match(
1073 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
1077 return isset( $this->sessionTempTables
[$matches[1]] );
1078 } elseif ( preg_match(
1079 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
1083 return isset( $this->sessionTempTables
[$matches[1]] );
1089 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1090 $this->assertTransactionStatus( $sql, $fname );
1092 # Avoid fatals if close() was called
1093 $this->assertOpen();
1095 $priorWritesPending = $this->writesOrCallbacksPending();
1096 $this->lastQuery
= $sql;
1098 $isWrite = $this->isWriteQuery( $sql );
1100 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1102 $isNonTempWrite = false;
1106 if ( $this->getLBInfo( 'replica' ) === true ) {
1109 'Write operations are not allowed on replica database connections.'
1112 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1113 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1114 $reason = $this->getReadOnlyReason();
1115 if ( $reason !== false ) {
1116 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1118 # Set a flag indicating that writes have been done
1119 $this->lastWriteTime
= microtime( true );
1122 # Add trace comment to the begin of the sql string, right after the operator.
1123 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1124 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1126 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1127 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1128 && $this->isTransactableQuery( $sql )
1130 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1131 $this->trxAutomatic
= true;
1134 # Keep track of whether the transaction has write queries pending
1135 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1136 $this->trxDoneWrites
= true;
1137 $this->trxProfiler
->transactionWritingIn(
1138 $this->server
, $this->dbName
, $this->trxShortId
);
1141 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1142 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1145 # Send the query to the server and fetch any corresponding errors
1146 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1147 $lastError = $this->lastError();
1148 $lastErrno = $this->lastErrno();
1150 # Try reconnecting if the connection was lost
1151 if ( $ret === false && $this->wasConnectionLoss() ) {
1152 # Check if any meaningful session state was lost
1153 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1154 # Update session state tracking and try to restore the connection
1155 $reconnected = $this->replaceLostConnection( __METHOD__
);
1156 # Silently resend the query to the server if it is safe and possible
1157 if ( $reconnected && $recoverable ) {
1158 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1159 $lastError = $this->lastError();
1160 $lastErrno = $this->lastErrno();
1162 if ( $ret === false && $this->wasConnectionLoss() ) {
1163 # Query probably causes disconnects; reconnect and do not re-run it
1164 $this->replaceLostConnection( __METHOD__
);
1169 if ( $ret === false ) {
1170 if ( $this->trxLevel
) {
1171 if ( !$this->wasKnownStatementRollbackError() ) {
1172 # Either the query was aborted or all queries after BEGIN where aborted.
1173 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1174 # In the first case, the only options going forward are (a) ROLLBACK, or
1175 # (b) ROLLBACK TO SAVEPOINT (if one was set). If the later case, the only
1176 # option is ROLLBACK, since the snapshots would have been released.
1177 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
1178 $this->trxStatusCause
=
1179 $this->makeQueryException( $lastError, $lastErrno, $sql, $fname );
1180 $tempIgnore = false; // cannot recover
1182 # Nothing prior was there to lose from the transaction,
1183 # so just roll it back.
1184 $this->doRollback( __METHOD__
. " ($fname)" );
1185 $this->trxStatus
= self
::STATUS_TRX_OK
;
1187 $this->trxStatusIgnoredCause
= null;
1189 # We're ignoring an error that caused just the current query to be aborted.
1190 # But log the cause so we can log a deprecation notice if a
1191 # caller actually does ignore it.
1192 $this->trxStatusIgnoredCause
= [ $lastError, $lastErrno, $fname ];
1196 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1199 return $this->resultObject( $ret );
1203 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1205 * @param string $sql Original SQL query
1206 * @param string $commentedSql SQL query with debugging/trace comment
1207 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1208 * @param string $fname Name of the calling function
1209 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1210 * object for a successful read query, or false on failure
1212 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1213 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1214 # generalizeSQL() will probably cut down the query to reasonable
1215 # logging size most of the time. The substr is really just a sanity check.
1217 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1219 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1222 # Include query transaction state
1223 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1225 $startTime = microtime( true );
1226 if ( $this->profiler
) {
1227 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1229 $this->affectedRowCount
= null;
1230 $ret = $this->doQuery( $commentedSql );
1231 $this->affectedRowCount
= $this->affectedRows();
1232 if ( $this->profiler
) {
1233 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1235 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1237 unset( $queryProfSection ); // profile out (if set)
1239 if ( $ret !== false ) {
1240 $this->lastPing
= $startTime;
1241 if ( $isWrite && $this->trxLevel
) {
1242 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1243 $this->trxWriteCallers
[] = $fname;
1247 if ( $sql === self
::PING_QUERY
) {
1248 $this->rttEstimate
= $queryRuntime;
1251 $this->trxProfiler
->recordQueryCompletion(
1252 $queryProf, $startTime, $isWrite, $this->affectedRows()
1254 $this->queryLogger
->debug( $sql, [
1256 'master' => $isMaster,
1257 'runtime' => $queryRuntime,
1264 * Update the estimated run-time of a query, not counting large row lock times
1266 * LoadBalancer can be set to rollback transactions that will create huge replication
1267 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1268 * queries, like inserting a row can take a long time due to row locking. This method
1269 * uses some simple heuristics to discount those cases.
1271 * @param string $sql A SQL write query
1272 * @param float $runtime Total runtime, including RTT
1273 * @param int $affected Affected row count
1275 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1276 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1277 $indicativeOfReplicaRuntime = true;
1278 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1279 $verb = $this->getQueryVerb( $sql );
1280 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1281 if ( $verb === 'INSERT' ) {
1282 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1283 } elseif ( $verb === 'REPLACE' ) {
1284 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1288 $this->trxWriteDuration +
= $runtime;
1289 $this->trxWriteQueryCount +
= 1;
1290 $this->trxWriteAffectedRows +
= $affected;
1291 if ( $indicativeOfReplicaRuntime ) {
1292 $this->trxWriteAdjDuration +
= $runtime;
1293 $this->trxWriteAdjQueryCount +
= 1;
1298 * @param string $sql
1299 * @param string $fname
1300 * @throws DBTransactionStateError
1302 private function assertTransactionStatus( $sql, $fname ) {
1303 if ( $this->getQueryVerb( $sql ) === 'ROLLBACK' ) { // transaction/savepoint
1307 if ( $this->trxStatus
< self
::STATUS_TRX_OK
) {
1308 throw new DBTransactionStateError(
1310 "Cannot execute query from $fname while transaction status is ERROR.",
1312 $this->trxStatusCause
1314 } elseif ( $this->trxStatus
=== self
::STATUS_TRX_OK
&& $this->trxStatusIgnoredCause
) {
1315 list( $iLastError, $iLastErrno, $iFname ) = $this->trxStatusIgnoredCause
;
1316 call_user_func( $this->deprecationLogger
,
1317 "Caller from $fname ignored an error originally raised from $iFname: " .
1318 "[$iLastErrno] $iLastError"
1320 $this->trxStatusIgnoredCause
= null;
1325 * Determine whether or not it is safe to retry queries after a database
1326 * connection is lost
1328 * @param string $sql SQL query
1329 * @param bool $priorWritesPending Whether there is a transaction open with
1330 * possible write queries or transaction pre-commit/idle callbacks
1331 * waiting on it to finish.
1332 * @return bool True if it is safe to retry the query, false otherwise
1334 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1335 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1336 # Dropped connections also mean that named locks are automatically released.
1337 # Only allow error suppression in autocommit mode or when the lost transaction
1338 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1339 if ( $this->namedLocksHeld
) {
1340 return false; // possible critical section violation
1341 } elseif ( $this->sessionTempTables
) {
1342 return false; // tables might be queried latter
1343 } elseif ( $sql === 'COMMIT' ) {
1344 return !$priorWritesPending; // nothing written anyway? (T127428)
1345 } elseif ( $sql === 'ROLLBACK' ) {
1346 return true; // transaction lost...which is also what was requested :)
1347 } elseif ( $this->explicitTrxActive() ) {
1348 return false; // don't drop atomocity and explicit snapshots
1349 } elseif ( $priorWritesPending ) {
1350 return false; // prior writes lost from implicit transaction
1357 * Clean things up after session (and thus transaction) loss
1359 private function handleSessionLoss() {
1360 // Clean up tracking of session-level things...
1361 // https://dev.mysql.com/doc/refman/5.7/en/implicit-commit.html
1362 // https://www.postgresql.org/docs/9.2/static/sql-createtable.html (ignoring ON COMMIT)
1363 $this->sessionTempTables
= [];
1364 // https://dev.mysql.com/doc/refman/5.7/en/miscellaneous-functions.html#function_get-lock
1365 // https://www.postgresql.org/docs/9.4/static/functions-admin.html#FUNCTIONS-ADVISORY-LOCKS
1366 $this->namedLocksHeld
= [];
1367 // Session loss implies transaction loss
1368 $this->handleTransactionLoss();
1372 * Clean things up after transaction loss
1374 private function handleTransactionLoss() {
1375 $this->trxLevel
= 0;
1376 $this->trxAtomicCounter
= 0;
1377 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1378 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1380 // Handle callbacks in trxEndCallbacks, e.g. onTransactionResolution().
1381 // If callback suppression is set then the array will remain unhandled.
1382 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1383 } catch ( Exception
$ex ) {
1384 // Already logged; move on...
1387 // Handle callbacks in trxRecurringCallbacks, e.g. setTransactionListener()
1388 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1389 } catch ( Exception
$ex ) {
1390 // Already logged; move on...
1395 * Checks whether the cause of the error is detected to be a timeout.
1397 * It returns false by default, and not all engines support detecting this yet.
1398 * If this returns false, it will be treated as a generic query error.
1400 * @param string $error Error text
1401 * @param int $errno Error number
1404 protected function wasQueryTimeout( $error, $errno ) {
1409 * Report a query error. Log the error, and if neither the object ignore
1410 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1412 * @param string $error
1414 * @param string $sql
1415 * @param string $fname
1416 * @param bool $tempIgnore
1417 * @throws DBQueryError
1419 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1420 if ( $tempIgnore ) {
1421 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1423 $exception = $this->makeQueryException( $error, $errno, $sql, $fname );
1430 * @param string $error
1431 * @param string|int $errno
1432 * @param string $sql
1433 * @param string $fname
1436 private function makeQueryException( $error, $errno, $sql, $fname ) {
1437 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1438 $this->queryLogger
->error(
1439 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1440 $this->getLogContext( [
1441 'method' => __METHOD__
,
1444 'sql1line' => $sql1line,
1448 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1449 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1450 if ( $wasQueryTimeout ) {
1451 $e = new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1453 $e = new DBQueryError( $this, $error, $errno, $sql, $fname );
1459 public function freeResult( $res ) {
1462 public function selectField(
1463 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1465 if ( $var === '*' ) { // sanity
1466 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1469 if ( !is_array( $options ) ) {
1470 $options = [ $options ];
1473 $options['LIMIT'] = 1;
1475 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1476 if ( $res === false ||
!$this->numRows( $res ) ) {
1480 $row = $this->fetchRow( $res );
1482 if ( $row !== false ) {
1483 return reset( $row );
1489 public function selectFieldValues(
1490 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1492 if ( $var === '*' ) { // sanity
1493 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1494 } elseif ( !is_string( $var ) ) { // sanity
1495 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1498 if ( !is_array( $options ) ) {
1499 $options = [ $options ];
1502 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1503 if ( $res === false ) {
1508 foreach ( $res as $row ) {
1509 $values[] = $row->$var;
1516 * Returns an optional USE INDEX clause to go after the table, and a
1517 * string to go at the end of the query.
1519 * @param array $options Associative array of options to be turned into
1520 * an SQL query, valid keys are listed in the function.
1522 * @see Database::select()
1524 protected function makeSelectOptions( $options ) {
1525 $preLimitTail = $postLimitTail = '';
1530 foreach ( $options as $key => $option ) {
1531 if ( is_numeric( $key ) ) {
1532 $noKeyOptions[$option] = true;
1536 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1538 $preLimitTail .= $this->makeOrderBy( $options );
1540 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1541 $postLimitTail .= ' FOR UPDATE';
1544 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1545 $postLimitTail .= ' LOCK IN SHARE MODE';
1548 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1549 $startOpts .= 'DISTINCT';
1552 # Various MySQL extensions
1553 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1554 $startOpts .= ' /*! STRAIGHT_JOIN */';
1557 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1558 $startOpts .= ' HIGH_PRIORITY';
1561 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1562 $startOpts .= ' SQL_BIG_RESULT';
1565 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1566 $startOpts .= ' SQL_BUFFER_RESULT';
1569 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1570 $startOpts .= ' SQL_SMALL_RESULT';
1573 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1574 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1577 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1578 $startOpts .= ' SQL_CACHE';
1581 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1582 $startOpts .= ' SQL_NO_CACHE';
1585 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1586 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1590 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1591 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1596 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1600 * Returns an optional GROUP BY with an optional HAVING
1602 * @param array $options Associative array of options
1604 * @see Database::select()
1607 protected function makeGroupByWithHaving( $options ) {
1609 if ( isset( $options['GROUP BY'] ) ) {
1610 $gb = is_array( $options['GROUP BY'] )
1611 ?
implode( ',', $options['GROUP BY'] )
1612 : $options['GROUP BY'];
1613 $sql .= ' GROUP BY ' . $gb;
1615 if ( isset( $options['HAVING'] ) ) {
1616 $having = is_array( $options['HAVING'] )
1617 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1618 : $options['HAVING'];
1619 $sql .= ' HAVING ' . $having;
1626 * Returns an optional ORDER BY
1628 * @param array $options Associative array of options
1630 * @see Database::select()
1633 protected function makeOrderBy( $options ) {
1634 if ( isset( $options['ORDER BY'] ) ) {
1635 $ob = is_array( $options['ORDER BY'] )
1636 ?
implode( ',', $options['ORDER BY'] )
1637 : $options['ORDER BY'];
1639 return ' ORDER BY ' . $ob;
1645 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1646 $options = [], $join_conds = [] ) {
1647 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1649 return $this->query( $sql, $fname );
1652 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1653 $options = [], $join_conds = []
1655 if ( is_array( $vars ) ) {
1656 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1659 $options = (array)$options;
1660 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1661 ?
$options['USE INDEX']
1664 isset( $options['IGNORE INDEX'] ) &&
1665 is_array( $options['IGNORE INDEX'] )
1667 ?
$options['IGNORE INDEX']
1670 if ( is_array( $table ) ) {
1672 $this->tableNamesWithIndexClauseOrJOIN(
1673 $table, $useIndexes, $ignoreIndexes, $join_conds );
1674 } elseif ( $table != '' ) {
1676 $this->tableNamesWithIndexClauseOrJOIN(
1677 [ $table ], $useIndexes, $ignoreIndexes, [] );
1682 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1683 $this->makeSelectOptions( $options );
1685 if ( is_array( $conds ) ) {
1686 $conds = $this->makeList( $conds, self
::LIST_AND
);
1689 if ( $conds === null ||
$conds === false ) {
1690 $this->queryLogger
->warning(
1694 . ' with incorrect parameters: $conds must be a string or an array'
1699 if ( $conds === '' ) {
1700 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1701 } elseif ( is_string( $conds ) ) {
1702 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1703 "WHERE $conds $preLimitTail";
1705 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1708 if ( isset( $options['LIMIT'] ) ) {
1709 $sql = $this->limitResult( $sql, $options['LIMIT'],
1710 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1712 $sql = "$sql $postLimitTail";
1714 if ( isset( $options['EXPLAIN'] ) ) {
1715 $sql = 'EXPLAIN ' . $sql;
1721 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1722 $options = [], $join_conds = []
1724 $options = (array)$options;
1725 $options['LIMIT'] = 1;
1726 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1728 if ( $res === false ) {
1732 if ( !$this->numRows( $res ) ) {
1736 $obj = $this->fetchObject( $res );
1741 public function estimateRowCount(
1742 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1744 $conds = $this->normalizeConditions( $conds, $fname );
1745 $column = $this->extractSingleFieldFromList( $var );
1746 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1747 $conds[] = "$column IS NOT NULL";
1750 $res = $this->select(
1751 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1753 $row = $res ?
$this->fetchRow( $res ) : [];
1755 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1758 public function selectRowCount(
1759 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1761 $conds = $this->normalizeConditions( $conds, $fname );
1762 $column = $this->extractSingleFieldFromList( $var );
1763 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1764 $conds[] = "$column IS NOT NULL";
1767 $res = $this->select(
1769 'tmp_count' => $this->buildSelectSubquery(
1778 [ 'rowcount' => 'COUNT(*)' ],
1782 $row = $res ?
$this->fetchRow( $res ) : [];
1784 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1788 * @param array|string $conds
1789 * @param string $fname
1792 final protected function normalizeConditions( $conds, $fname ) {
1793 if ( $conds === null ||
$conds === false ) {
1794 $this->queryLogger
->warning(
1798 . ' with incorrect parameters: $conds must be a string or an array'
1803 if ( !is_array( $conds ) ) {
1804 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1811 * @param array|string $var Field parameter in the style of select()
1812 * @return string|null Column name or null; ignores aliases
1813 * @throws DBUnexpectedError Errors out if multiple columns are given
1815 final protected function extractSingleFieldFromList( $var ) {
1816 if ( is_array( $var ) ) {
1819 } elseif ( count( $var ) == 1 ) {
1820 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1822 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1832 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1833 * It's only slightly flawed. Don't use for anything important.
1835 * @param string $sql A SQL Query
1839 protected static function generalizeSQL( $sql ) {
1840 # This does the same as the regexp below would do, but in such a way
1841 # as to avoid crashing php on some large strings.
1842 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1844 $sql = str_replace( "\\\\", '', $sql );
1845 $sql = str_replace( "\\'", '', $sql );
1846 $sql = str_replace( "\\\"", '', $sql );
1847 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1848 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1850 # All newlines, tabs, etc replaced by single space
1851 $sql = preg_replace( '/\s+/', ' ', $sql );
1854 # except the ones surrounded by characters, e.g. l10n
1855 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1856 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1861 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1862 $info = $this->fieldInfo( $table, $field );
1867 public function indexExists( $table, $index, $fname = __METHOD__
) {
1868 if ( !$this->tableExists( $table ) ) {
1872 $info = $this->indexInfo( $table, $index, $fname );
1873 if ( is_null( $info ) ) {
1876 return $info !== false;
1880 public function tableExists( $table, $fname = __METHOD__
) {
1881 $tableRaw = $this->tableName( $table, 'raw' );
1882 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1883 return true; // already known to exist
1886 $table = $this->tableName( $table );
1887 $ignoreErrors = true;
1888 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1893 public function indexUnique( $table, $index ) {
1894 $indexInfo = $this->indexInfo( $table, $index );
1896 if ( !$indexInfo ) {
1900 return !$indexInfo[0]->Non_unique
;
1904 * Helper for Database::insert().
1906 * @param array $options
1909 protected function makeInsertOptions( $options ) {
1910 return implode( ' ', $options );
1913 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1914 # No rows to insert, easy just return now
1915 if ( !count( $a ) ) {
1919 $table = $this->tableName( $table );
1921 if ( !is_array( $options ) ) {
1922 $options = [ $options ];
1926 if ( isset( $options['fileHandle'] ) ) {
1927 $fh = $options['fileHandle'];
1929 $options = $this->makeInsertOptions( $options );
1931 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1933 $keys = array_keys( $a[0] );
1936 $keys = array_keys( $a );
1939 $sql = 'INSERT ' . $options .
1940 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1944 foreach ( $a as $row ) {
1950 $sql .= '(' . $this->makeList( $row ) . ')';
1953 $sql .= '(' . $this->makeList( $a ) . ')';
1956 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1958 } elseif ( $fh !== null ) {
1962 return (bool)$this->query( $sql, $fname );
1966 * Make UPDATE options array for Database::makeUpdateOptions
1968 * @param array $options
1971 protected function makeUpdateOptionsArray( $options ) {
1972 if ( !is_array( $options ) ) {
1973 $options = [ $options ];
1978 if ( in_array( 'IGNORE', $options ) ) {
1986 * Make UPDATE options for the Database::update function
1988 * @param array $options The options passed to Database::update
1991 protected function makeUpdateOptions( $options ) {
1992 $opts = $this->makeUpdateOptionsArray( $options );
1994 return implode( ' ', $opts );
1997 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1998 $table = $this->tableName( $table );
1999 $opts = $this->makeUpdateOptions( $options );
2000 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
2002 if ( $conds !== [] && $conds !== '*' ) {
2003 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
2006 return (bool)$this->query( $sql, $fname );
2009 public function makeList( $a, $mode = self
::LIST_COMMA
) {
2010 if ( !is_array( $a ) ) {
2011 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
2017 foreach ( $a as $field => $value ) {
2019 if ( $mode == self
::LIST_AND
) {
2021 } elseif ( $mode == self
::LIST_OR
) {
2030 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
2031 $list .= "($value)";
2032 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
2035 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
2037 // Remove null from array to be handled separately if found
2038 $includeNull = false;
2039 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2040 $includeNull = true;
2041 unset( $value[$nullKey] );
2043 if ( count( $value ) == 0 && !$includeNull ) {
2044 throw new InvalidArgumentException(
2045 __METHOD__
. ": empty input for field $field" );
2046 } elseif ( count( $value ) == 0 ) {
2047 // only check if $field is null
2048 $list .= "$field IS NULL";
2050 // IN clause contains at least one valid element
2051 if ( $includeNull ) {
2052 // Group subconditions to ensure correct precedence
2055 if ( count( $value ) == 1 ) {
2056 // Special-case single values, as IN isn't terribly efficient
2057 // Don't necessarily assume the single key is 0; we don't
2058 // enforce linear numeric ordering on other arrays here.
2059 $value = array_values( $value )[0];
2060 $list .= $field . " = " . $this->addQuotes( $value );
2062 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2064 // if null present in array, append IS NULL
2065 if ( $includeNull ) {
2066 $list .= " OR $field IS NULL)";
2069 } elseif ( $value === null ) {
2070 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
2071 $list .= "$field IS ";
2072 } elseif ( $mode == self
::LIST_SET
) {
2073 $list .= "$field = ";
2078 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
2080 $list .= "$field = ";
2082 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
2089 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2092 foreach ( $data as $base => $sub ) {
2093 if ( count( $sub ) ) {
2094 $conds[] = $this->makeList(
2095 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
2101 return $this->makeList( $conds, self
::LIST_OR
);
2103 // Nothing to search for...
2108 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2112 public function bitNot( $field ) {
2116 public function bitAnd( $fieldLeft, $fieldRight ) {
2117 return "($fieldLeft & $fieldRight)";
2120 public function bitOr( $fieldLeft, $fieldRight ) {
2121 return "($fieldLeft | $fieldRight)";
2124 public function buildConcat( $stringList ) {
2125 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2128 public function buildGroupConcatField(
2129 $delim, $table, $field, $conds = '', $join_conds = []
2131 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2133 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
2136 public function buildSubstring( $input, $startPosition, $length = null ) {
2137 $this->assertBuildSubstringParams( $startPosition, $length );
2138 $functionBody = "$input FROM $startPosition";
2139 if ( $length !== null ) {
2140 $functionBody .= " FOR $length";
2142 return 'SUBSTRING(' . $functionBody . ')';
2146 * Check type and bounds for parameters to self::buildSubstring()
2148 * All supported databases have substring functions that behave the same for
2149 * positive $startPosition and non-negative $length, but behaviors differ when
2150 * given 0 or negative $startPosition or negative $length. The simplest
2151 * solution to that is to just forbid those values.
2153 * @param int $startPosition
2154 * @param int|null $length
2157 protected function assertBuildSubstringParams( $startPosition, $length ) {
2158 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2159 throw new InvalidArgumentException(
2160 '$startPosition must be a positive integer'
2163 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2164 throw new InvalidArgumentException(
2165 '$length must be null or an integer greater than or equal to 0'
2170 public function buildStringCast( $field ) {
2174 public function buildIntegerCast( $field ) {
2175 return 'CAST( ' . $field . ' AS INTEGER )';
2178 public function buildSelectSubquery(
2179 $table, $vars, $conds = '', $fname = __METHOD__
,
2180 $options = [], $join_conds = []
2182 return new Subquery(
2183 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2187 public function databasesAreIndependent() {
2191 public function selectDB( $db ) {
2192 # Stub. Shouldn't cause serious problems if it's not overridden, but
2193 # if your database engine supports a concept similar to MySQL's
2194 # databases you may as well.
2195 $this->dbName
= $db;
2200 public function getDBname() {
2201 return $this->dbName
;
2204 public function getServer() {
2205 return $this->server
;
2208 public function tableName( $name, $format = 'quoted' ) {
2209 if ( $name instanceof Subquery
) {
2210 throw new DBUnexpectedError(
2212 __METHOD__
. ': got Subquery instance when expecting a string.'
2216 # Skip the entire process when we have a string quoted on both ends.
2217 # Note that we check the end so that we will still quote any use of
2218 # use of `database`.table. But won't break things if someone wants
2219 # to query a database table with a dot in the name.
2220 if ( $this->isQuotedIdentifier( $name ) ) {
2224 # Lets test for any bits of text that should never show up in a table
2225 # name. Basically anything like JOIN or ON which are actually part of
2226 # SQL queries, but may end up inside of the table value to combine
2227 # sql. Such as how the API is doing.
2228 # Note that we use a whitespace test rather than a \b test to avoid
2229 # any remote case where a word like on may be inside of a table name
2230 # surrounded by symbols which may be considered word breaks.
2231 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2232 $this->queryLogger
->warning(
2233 __METHOD__
. ": use of subqueries is not supported this way.",
2234 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2240 # Split database and table into proper variables.
2241 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2243 # Quote $table and apply the prefix if not quoted.
2244 # $tableName might be empty if this is called from Database::replaceVars()
2245 $tableName = "{$prefix}{$table}";
2246 if ( $format === 'quoted'
2247 && !$this->isQuotedIdentifier( $tableName )
2248 && $tableName !== ''
2250 $tableName = $this->addIdentifierQuotes( $tableName );
2253 # Quote $schema and $database and merge them with the table name if needed
2254 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2255 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2261 * Get the table components needed for a query given the currently selected database
2263 * @param string $name Table name in the form of db.schema.table, db.table, or table
2264 * @return array (DB name or "" for default, schema name, table prefix, table name)
2266 protected function qualifiedTableComponents( $name ) {
2267 # We reverse the explode so that database.table and table both output the correct table.
2268 $dbDetails = explode( '.', $name, 3 );
2269 if ( count( $dbDetails ) == 3 ) {
2270 list( $database, $schema, $table ) = $dbDetails;
2271 # We don't want any prefix added in this case
2273 } elseif ( count( $dbDetails ) == 2 ) {
2274 list( $database, $table ) = $dbDetails;
2275 # We don't want any prefix added in this case
2277 # In dbs that support it, $database may actually be the schema
2278 # but that doesn't affect any of the functionality here
2281 list( $table ) = $dbDetails;
2282 if ( isset( $this->tableAliases
[$table] ) ) {
2283 $database = $this->tableAliases
[$table]['dbname'];
2284 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2285 ?
$this->tableAliases
[$table]['schema']
2287 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2288 ?
$this->tableAliases
[$table]['prefix']
2289 : $this->tablePrefix
;
2292 $schema = $this->schema
; # Default schema
2293 $prefix = $this->tablePrefix
; # Default prefix
2297 return [ $database, $schema, $prefix, $table ];
2301 * @param string|null $namespace Database or schema
2302 * @param string $relation Name of table, view, sequence, etc...
2303 * @param string $format One of (raw, quoted)
2304 * @return string Relation name with quoted and merged $namespace as needed
2306 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2307 if ( strlen( $namespace ) ) {
2308 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2309 $namespace = $this->addIdentifierQuotes( $namespace );
2311 $relation = $namespace . '.' . $relation;
2317 public function tableNames() {
2318 $inArray = func_get_args();
2321 foreach ( $inArray as $name ) {
2322 $retVal[$name] = $this->tableName( $name );
2328 public function tableNamesN() {
2329 $inArray = func_get_args();
2332 foreach ( $inArray as $name ) {
2333 $retVal[] = $this->tableName( $name );
2340 * Get an aliased table name
2342 * This returns strings like "tableName AS newTableName" for aliased tables
2343 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2345 * @see Database::tableName()
2346 * @param string|Subquery $table Table name or object with a 'sql' field
2347 * @param string|bool $alias Table alias (optional)
2348 * @return string SQL name for aliased table. Will not alias a table to its own name
2350 protected function tableNameWithAlias( $table, $alias = false ) {
2351 if ( is_string( $table ) ) {
2352 $quotedTable = $this->tableName( $table );
2353 } elseif ( $table instanceof Subquery
) {
2354 $quotedTable = (string)$table;
2356 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2359 if ( !strlen( $alias ) ||
$alias === $table ) {
2360 if ( $table instanceof Subquery
) {
2361 throw new InvalidArgumentException( "Subquery table missing alias." );
2364 return $quotedTable;
2366 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2371 * Gets an array of aliased table names
2373 * @param array $tables [ [alias] => table ]
2374 * @return string[] See tableNameWithAlias()
2376 protected function tableNamesWithAlias( $tables ) {
2378 foreach ( $tables as $alias => $table ) {
2379 if ( is_numeric( $alias ) ) {
2382 $retval[] = $this->tableNameWithAlias( $table, $alias );
2389 * Get an aliased field name
2390 * e.g. fieldName AS newFieldName
2392 * @param string $name Field name
2393 * @param string|bool $alias Alias (optional)
2394 * @return string SQL name for aliased field. Will not alias a field to its own name
2396 protected function fieldNameWithAlias( $name, $alias = false ) {
2397 if ( !$alias ||
(string)$alias === (string)$name ) {
2400 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2405 * Gets an array of aliased field names
2407 * @param array $fields [ [alias] => field ]
2408 * @return string[] See fieldNameWithAlias()
2410 protected function fieldNamesWithAlias( $fields ) {
2412 foreach ( $fields as $alias => $field ) {
2413 if ( is_numeric( $alias ) ) {
2416 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2423 * Get the aliased table name clause for a FROM clause
2424 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2426 * @param array $tables ( [alias] => table )
2427 * @param array $use_index Same as for select()
2428 * @param array $ignore_index Same as for select()
2429 * @param array $join_conds Same as for select()
2432 protected function tableNamesWithIndexClauseOrJOIN(
2433 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2437 $use_index = (array)$use_index;
2438 $ignore_index = (array)$ignore_index;
2439 $join_conds = (array)$join_conds;
2441 foreach ( $tables as $alias => $table ) {
2442 if ( !is_string( $alias ) ) {
2443 // No alias? Set it equal to the table name
2447 if ( is_array( $table ) ) {
2448 // A parenthesized group
2449 if ( count( $table ) > 1 ) {
2450 $joinedTable = '(' .
2451 $this->tableNamesWithIndexClauseOrJOIN(
2452 $table, $use_index, $ignore_index, $join_conds ) . ')';
2455 $innerTable = reset( $table );
2456 $innerAlias = key( $table );
2457 $joinedTable = $this->tableNameWithAlias(
2459 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2463 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2466 // Is there a JOIN clause for this table?
2467 if ( isset( $join_conds[$alias] ) ) {
2468 list( $joinType, $conds ) = $join_conds[$alias];
2469 $tableClause = $joinType;
2470 $tableClause .= ' ' . $joinedTable;
2471 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2472 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2474 $tableClause .= ' ' . $use;
2477 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2478 $ignore = $this->ignoreIndexClause(
2479 implode( ',', (array)$ignore_index[$alias] ) );
2480 if ( $ignore != '' ) {
2481 $tableClause .= ' ' . $ignore;
2484 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2486 $tableClause .= ' ON (' . $on . ')';
2489 $retJOIN[] = $tableClause;
2490 } elseif ( isset( $use_index[$alias] ) ) {
2491 // Is there an INDEX clause for this table?
2492 $tableClause = $joinedTable;
2493 $tableClause .= ' ' . $this->useIndexClause(
2494 implode( ',', (array)$use_index[$alias] )
2497 $ret[] = $tableClause;
2498 } elseif ( isset( $ignore_index[$alias] ) ) {
2499 // Is there an INDEX clause for this table?
2500 $tableClause = $joinedTable;
2501 $tableClause .= ' ' . $this->ignoreIndexClause(
2502 implode( ',', (array)$ignore_index[$alias] )
2505 $ret[] = $tableClause;
2507 $tableClause = $joinedTable;
2509 $ret[] = $tableClause;
2513 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2514 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2515 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2517 // Compile our final table clause
2518 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2522 * Allows for index remapping in queries where this is not consistent across DBMS
2524 * @param string $index
2527 protected function indexName( $index ) {
2528 return isset( $this->indexAliases
[$index] )
2529 ?
$this->indexAliases
[$index]
2533 public function addQuotes( $s ) {
2534 if ( $s instanceof Blob
) {
2537 if ( $s === null ) {
2539 } elseif ( is_bool( $s ) ) {
2542 # This will also quote numeric values. This should be harmless,
2543 # and protects against weird problems that occur when they really
2544 # _are_ strings such as article titles and string->number->string
2545 # conversion is not 1:1.
2546 return "'" . $this->strencode( $s ) . "'";
2551 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2552 * MySQL uses `backticks` while basically everything else uses double quotes.
2553 * Since MySQL is the odd one out here the double quotes are our generic
2554 * and we implement backticks in DatabaseMysqlBase.
2559 public function addIdentifierQuotes( $s ) {
2560 return '"' . str_replace( '"', '""', $s ) . '"';
2564 * Returns if the given identifier looks quoted or not according to
2565 * the database convention for quoting identifiers .
2567 * @note Do not use this to determine if untrusted input is safe.
2568 * A malicious user can trick this function.
2569 * @param string $name
2572 public function isQuotedIdentifier( $name ) {
2573 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2578 * @param string $escapeChar
2581 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2582 return str_replace( [ $escapeChar, '%', '_' ],
2583 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2587 public function buildLike() {
2588 $params = func_get_args();
2590 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2591 $params = $params[0];
2596 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2597 // may escape backslashes, creating problems of double escaping. The `
2598 // character has good cross-DBMS compatibility, avoiding special operators
2599 // in MS SQL like ^ and %
2602 foreach ( $params as $value ) {
2603 if ( $value instanceof LikeMatch
) {
2604 $s .= $value->toString();
2606 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2611 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2614 public function anyChar() {
2615 return new LikeMatch( '_' );
2618 public function anyString() {
2619 return new LikeMatch( '%' );
2622 public function nextSequenceValue( $seqName ) {
2627 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2628 * is only needed because a) MySQL must be as efficient as possible due to
2629 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2630 * which index to pick. Anyway, other databases might have different
2631 * indexes on a given table. So don't bother overriding this unless you're
2633 * @param string $index
2636 public function useIndexClause( $index ) {
2641 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2642 * is only needed because a) MySQL must be as efficient as possible due to
2643 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2644 * which index to pick. Anyway, other databases might have different
2645 * indexes on a given table. So don't bother overriding this unless you're
2647 * @param string $index
2650 public function ignoreIndexClause( $index ) {
2654 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2655 if ( count( $rows ) == 0 ) {
2660 if ( !is_array( reset( $rows ) ) ) {
2665 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2666 $affectedRowCount = 0;
2667 foreach ( $rows as $row ) {
2668 // Delete rows which collide with this one
2669 $indexWhereClauses = [];
2670 foreach ( $uniqueIndexes as $index ) {
2671 $indexColumns = (array)$index;
2672 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2673 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2674 throw new DBUnexpectedError(
2676 'New record does not provide all values for unique key (' .
2677 implode( ', ', $indexColumns ) . ')'
2679 } elseif ( in_array( null, $indexRowValues, true ) ) {
2680 throw new DBUnexpectedError(
2682 'New record has a null value for unique key (' .
2683 implode( ', ', $indexColumns ) . ')'
2686 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2689 if ( $indexWhereClauses ) {
2690 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2691 $affectedRowCount +
= $this->affectedRows();
2694 // Now insert the row
2695 $this->insert( $table, $row, $fname );
2696 $affectedRowCount +
= $this->affectedRows();
2698 $this->endAtomic( $fname );
2699 $this->affectedRowCount
= $affectedRowCount;
2700 } catch ( Exception
$e ) {
2701 $this->cancelAtomic( $fname );
2707 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2710 * @param string $table Table name
2711 * @param array|string $rows Row(s) to insert
2712 * @param string $fname Caller function name
2714 * @return ResultWrapper
2716 protected function nativeReplace( $table, $rows, $fname ) {
2717 $table = $this->tableName( $table );
2720 if ( !is_array( reset( $rows ) ) ) {
2724 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2727 foreach ( $rows as $row ) {
2734 $sql .= '(' . $this->makeList( $row ) . ')';
2737 return $this->query( $sql, $fname );
2740 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2743 if ( !count( $rows ) ) {
2744 return true; // nothing to do
2747 if ( !is_array( reset( $rows ) ) ) {
2751 if ( count( $uniqueIndexes ) ) {
2752 $clauses = []; // list WHERE clauses that each identify a single row
2753 foreach ( $rows as $row ) {
2754 foreach ( $uniqueIndexes as $index ) {
2755 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2756 $rowKey = []; // unique key to this row
2757 foreach ( $index as $column ) {
2758 $rowKey[$column] = $row[$column];
2760 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2763 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2768 $affectedRowCount = 0;
2770 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2771 # Update any existing conflicting row(s)
2772 if ( $where !== false ) {
2773 $ok = $this->update( $table, $set, $where, $fname );
2774 $affectedRowCount +
= $this->affectedRows();
2778 # Now insert any non-conflicting row(s)
2779 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2780 $affectedRowCount +
= $this->affectedRows();
2781 $this->endAtomic( $fname );
2782 $this->affectedRowCount
= $affectedRowCount;
2783 } catch ( Exception
$e ) {
2784 $this->cancelAtomic( $fname );
2791 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2795 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2798 $delTable = $this->tableName( $delTable );
2799 $joinTable = $this->tableName( $joinTable );
2800 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2801 if ( $conds != '*' ) {
2802 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2806 $this->query( $sql, $fname );
2809 public function textFieldSize( $table, $field ) {
2810 $table = $this->tableName( $table );
2811 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2812 $res = $this->query( $sql, __METHOD__
);
2813 $row = $this->fetchObject( $res );
2817 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2826 public function delete( $table, $conds, $fname = __METHOD__
) {
2828 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2831 $table = $this->tableName( $table );
2832 $sql = "DELETE FROM $table";
2834 if ( $conds != '*' ) {
2835 if ( is_array( $conds ) ) {
2836 $conds = $this->makeList( $conds, self
::LIST_AND
);
2838 $sql .= ' WHERE ' . $conds;
2841 return $this->query( $sql, $fname );
2844 final public function insertSelect(
2845 $destTable, $srcTable, $varMap, $conds,
2846 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2848 static $hints = [ 'NO_AUTO_COLUMNS' ];
2850 $insertOptions = (array)$insertOptions;
2851 $selectOptions = (array)$selectOptions;
2853 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2854 // For massive migrations with downtime, we don't want to select everything
2855 // into memory and OOM, so do all this native on the server side if possible.
2856 return $this->nativeInsertSelect(
2862 array_diff( $insertOptions, $hints ),
2868 return $this->nonNativeInsertSelect(
2874 array_diff( $insertOptions, $hints ),
2881 * @param array $insertOptions INSERT options
2882 * @param array $selectOptions SELECT options
2883 * @return bool Whether an INSERT SELECT with these options will be replication safe
2886 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2891 * Implementation of insertSelect() based on select() and insert()
2893 * @see IDatabase::insertSelect()
2895 * @param string $destTable
2896 * @param string|array $srcTable
2897 * @param array $varMap
2898 * @param array $conds
2899 * @param string $fname
2900 * @param array $insertOptions
2901 * @param array $selectOptions
2902 * @param array $selectJoinConds
2905 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2906 $fname = __METHOD__
,
2907 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2909 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2910 // on only the master (without needing row-based-replication). It also makes it easy to
2911 // know how big the INSERT is going to be.
2913 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2914 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2916 $selectOptions[] = 'FOR UPDATE';
2917 $res = $this->select(
2918 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2925 $affectedRowCount = 0;
2926 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2929 foreach ( $res as $row ) {
2930 $rows[] = (array)$row;
2932 // Avoid inserts that are too huge
2933 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2934 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2938 $affectedRowCount +
= $this->affectedRows();
2942 if ( $rows && $ok ) {
2943 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2945 $affectedRowCount +
= $this->affectedRows();
2949 $this->endAtomic( $fname );
2950 $this->affectedRowCount
= $affectedRowCount;
2952 $this->cancelAtomic( $fname );
2955 } catch ( Exception
$e ) {
2956 $this->cancelAtomic( $fname );
2962 * Native server-side implementation of insertSelect() for situations where
2963 * we don't want to select everything into memory
2965 * @see IDatabase::insertSelect()
2966 * @param string $destTable
2967 * @param string|array $srcTable
2968 * @param array $varMap
2969 * @param array $conds
2970 * @param string $fname
2971 * @param array $insertOptions
2972 * @param array $selectOptions
2973 * @param array $selectJoinConds
2976 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2977 $fname = __METHOD__
,
2978 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2980 $destTable = $this->tableName( $destTable );
2982 if ( !is_array( $insertOptions ) ) {
2983 $insertOptions = [ $insertOptions ];
2986 $insertOptions = $this->makeInsertOptions( $insertOptions );
2988 $selectSql = $this->selectSQLText(
2990 array_values( $varMap ),
2997 $sql = "INSERT $insertOptions" .
2998 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
3001 return $this->query( $sql, $fname );
3005 * Construct a LIMIT query with optional offset. This is used for query
3006 * pages. The SQL should be adjusted so that only the first $limit rows
3007 * are returned. If $offset is provided as well, then the first $offset
3008 * rows should be discarded, and the next $limit rows should be returned.
3009 * If the result of the query is not ordered, then the rows to be returned
3010 * are theoretically arbitrary.
3012 * $sql is expected to be a SELECT, if that makes a difference.
3014 * The version provided by default works in MySQL and SQLite. It will very
3015 * likely need to be overridden for most other DBMSes.
3017 * @param string $sql SQL query we will append the limit too
3018 * @param int $limit The SQL limit
3019 * @param int|bool $offset The SQL offset (default false)
3020 * @throws DBUnexpectedError
3023 public function limitResult( $sql, $limit, $offset = false ) {
3024 if ( !is_numeric( $limit ) ) {
3025 throw new DBUnexpectedError( $this,
3026 "Invalid non-numeric limit passed to limitResult()\n" );
3029 return "$sql LIMIT "
3030 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3034 public function unionSupportsOrderAndLimit() {
3035 return true; // True for almost every DB supported
3038 public function unionQueries( $sqls, $all ) {
3039 $glue = $all ?
') UNION ALL (' : ') UNION (';
3041 return '(' . implode( $glue, $sqls ) . ')';
3044 public function unionConditionPermutations(
3045 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
3046 $options = [], $join_conds = []
3048 // First, build the Cartesian product of $permute_conds
3050 foreach ( $permute_conds as $field => $values ) {
3052 // Skip empty $values
3055 $values = array_unique( $values ); // For sanity
3057 foreach ( $conds as $cond ) {
3058 foreach ( $values as $value ) {
3059 $cond[$field] = $value;
3060 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
3066 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
3068 // If there's just one condition and no subordering, hand off to
3069 // selectSQLText directly.
3070 if ( count( $conds ) === 1 &&
3071 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
3073 return $this->selectSQLText(
3074 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
3078 // Otherwise, we need to pull out the order and limit to apply after
3079 // the union. Then build the SQL queries for each set of conditions in
3080 // $conds. Then union them together (using UNION ALL, because the
3081 // product *should* already be distinct).
3082 $orderBy = $this->makeOrderBy( $options );
3083 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
3084 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
3085 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
3086 if ( !$this->unionSupportsOrderAndLimit() ) {
3087 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
3089 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
3090 $options['ORDER BY'] = $options['INNER ORDER BY'];
3092 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
3093 // We need to increase the limit by the offset rather than
3094 // using the offset directly, otherwise it'll skip incorrectly
3095 // in the subqueries.
3096 $options['LIMIT'] = $limit +
$offset;
3097 unset( $options['OFFSET'] );
3102 foreach ( $conds as $cond ) {
3103 $sqls[] = $this->selectSQLText(
3104 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
3107 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
3108 if ( $limit !== null ) {
3109 $sql = $this->limitResult( $sql, $limit, $offset );
3115 public function conditional( $cond, $trueVal, $falseVal ) {
3116 if ( is_array( $cond ) ) {
3117 $cond = $this->makeList( $cond, self
::LIST_AND
);
3120 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3123 public function strreplace( $orig, $old, $new ) {
3124 return "REPLACE({$orig}, {$old}, {$new})";
3127 public function getServerUptime() {
3131 public function wasDeadlock() {
3135 public function wasLockTimeout() {
3139 public function wasConnectionLoss() {
3140 return $this->wasConnectionError( $this->lastErrno() );
3143 public function wasReadOnlyError() {
3147 public function wasErrorReissuable() {
3149 $this->wasDeadlock() ||
3150 $this->wasLockTimeout() ||
3151 $this->wasConnectionLoss()
3156 * Do not use this method outside of Database/DBError classes
3158 * @param int|string $errno
3159 * @return bool Whether the given query error was a connection drop
3161 public function wasConnectionError( $errno ) {
3166 * @return bool Whether it is safe to assume the given error only caused statement rollback
3167 * @note This is for backwards compatibility for callers catching DBError exceptions in
3168 * order to ignore problems like duplicate key errors or foriegn key violations
3171 protected function wasKnownStatementRollbackError() {
3172 return false; // don't know; it could have caused a transaction rollback
3175 public function deadlockLoop() {
3176 $args = func_get_args();
3177 $function = array_shift( $args );
3178 $tries = self
::DEADLOCK_TRIES
;
3180 $this->begin( __METHOD__
);
3183 /** @var Exception $e */
3187 $retVal = call_user_func_array( $function, $args );
3189 } catch ( DBQueryError
$e ) {
3190 if ( $this->wasDeadlock() ) {
3191 // Retry after a randomized delay
3192 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3194 // Throw the error back up
3198 } while ( --$tries > 0 );
3200 if ( $tries <= 0 ) {
3201 // Too many deadlocks; give up
3202 $this->rollback( __METHOD__
);
3205 $this->commit( __METHOD__
);
3211 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3212 # Real waits are implemented in the subclass.
3216 public function getReplicaPos() {
3221 public function getMasterPos() {
3226 public function serverIsReadOnly() {
3230 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3231 if ( !$this->trxLevel
) {
3232 throw new DBUnexpectedError( $this, "No transaction is active." );
3234 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3237 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3238 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3239 // Start an implicit transaction similar to how query() does
3240 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3241 $this->trxAutomatic
= true;
3244 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3245 if ( !$this->trxLevel
) {
3246 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3250 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3251 if ( !$this->trxLevel
&& $this->getTransactionRoundId() ) {
3252 // Start an implicit transaction similar to how query() does
3253 $this->begin( __METHOD__
, self
::TRANSACTION_INTERNAL
);
3254 $this->trxAutomatic
= true;
3257 if ( $this->trxLevel
) {
3258 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3260 // No transaction is active nor will start implicitly, so make one for this callback
3261 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3263 call_user_func( $callback );
3264 $this->endAtomic( __METHOD__
);
3265 } catch ( Exception
$e ) {
3266 $this->cancelAtomic( __METHOD__
);
3272 final public function setTransactionListener( $name, callable
$callback = null ) {
3274 $this->trxRecurringCallbacks
[$name] = $callback;
3276 unset( $this->trxRecurringCallbacks
[$name] );
3281 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3283 * This method should not be used outside of Database/LoadBalancer
3285 * @param bool $suppress
3288 final public function setTrxEndCallbackSuppression( $suppress ) {
3289 $this->trxEndCallbacksSuppressed
= $suppress;
3293 * Actually run and consume any "on transaction idle/resolution" callbacks.
3295 * This method should not be used outside of Database/LoadBalancer
3297 * @param int $trigger IDatabase::TRIGGER_* constant
3301 public function runOnTransactionIdleCallbacks( $trigger ) {
3302 if ( $this->trxEndCallbacksSuppressed
) {
3306 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3307 /** @var Exception $e */
3308 $e = null; // first exception
3309 do { // callbacks may add callbacks :)
3310 $callbacks = array_merge(
3311 $this->trxIdleCallbacks
,
3312 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3314 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3315 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3316 foreach ( $callbacks as $callback ) {
3318 list( $phpCallback ) = $callback;
3319 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3320 call_user_func_array( $phpCallback, [ $trigger ] );
3322 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3324 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3326 } catch ( Exception
$ex ) {
3327 call_user_func( $this->errorLogger
, $ex );
3329 // Some callbacks may use startAtomic/endAtomic, so make sure
3330 // their transactions are ended so other callbacks don't fail
3331 if ( $this->trxLevel() ) {
3332 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3336 } while ( count( $this->trxIdleCallbacks
) );
3338 if ( $e instanceof Exception
) {
3339 throw $e; // re-throw any first exception
3344 * Actually run and consume any "on transaction pre-commit" callbacks.
3346 * This method should not be used outside of Database/LoadBalancer
3351 public function runOnTransactionPreCommitCallbacks() {
3352 $e = null; // first exception
3353 do { // callbacks may add callbacks :)
3354 $callbacks = $this->trxPreCommitCallbacks
;
3355 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3356 foreach ( $callbacks as $callback ) {
3358 list( $phpCallback ) = $callback;
3359 call_user_func( $phpCallback );
3360 } catch ( Exception
$ex ) {
3361 call_user_func( $this->errorLogger
, $ex );
3365 } while ( count( $this->trxPreCommitCallbacks
) );
3367 if ( $e instanceof Exception
) {
3368 throw $e; // re-throw any first exception
3373 * Actually run any "transaction listener" callbacks.
3375 * This method should not be used outside of Database/LoadBalancer
3377 * @param int $trigger IDatabase::TRIGGER_* constant
3381 public function runTransactionListenerCallbacks( $trigger ) {
3382 if ( $this->trxEndCallbacksSuppressed
) {
3386 /** @var Exception $e */
3387 $e = null; // first exception
3389 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3391 $phpCallback( $trigger, $this );
3392 } catch ( Exception
$ex ) {
3393 call_user_func( $this->errorLogger
, $ex );
3398 if ( $e instanceof Exception
) {
3399 throw $e; // re-throw any first exception
3404 * Create a savepoint
3406 * This is used internally to implement atomic sections. It should not be
3410 * @param string $identifier Identifier for the savepoint
3411 * @param string $fname Calling function name
3413 protected function doSavepoint( $identifier, $fname ) {
3414 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3418 * Release a savepoint
3420 * This is used internally to implement atomic sections. It should not be
3424 * @param string $identifier Identifier for the savepoint
3425 * @param string $fname Calling function name
3427 protected function doReleaseSavepoint( $identifier, $fname ) {
3428 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3432 * Rollback to a savepoint
3434 * This is used internally to implement atomic sections. It should not be
3438 * @param string $identifier Identifier for the savepoint
3439 * @param string $fname Calling function name
3441 protected function doRollbackToSavepoint( $identifier, $fname ) {
3442 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3445 final public function startAtomic(
3446 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3448 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3449 if ( !$this->trxLevel
) {
3450 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3451 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3452 // in all changes being in one transaction to keep requests transactional.
3453 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3454 $this->trxAutomaticAtomic
= true;
3456 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3457 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3458 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3459 $this->queryLogger
->warning(
3460 'There have been an excessively large number of atomic sections in a transaction'
3461 . " started by $this->trxFname, reusing IDs (at $fname)",
3462 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3464 $this->trxAtomicCounter
= 0;
3465 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3467 $this->doSavepoint( $savepointId, $fname );
3470 $sectionId = new AtomicSectionIdentifier
;
3471 $this->trxAtomicLevels
[] = [ $fname, $sectionId, $savepointId ];
3476 final public function endAtomic( $fname = __METHOD__
) {
3477 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3478 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3481 // Check if the current section matches $fname
3482 $pos = count( $this->trxAtomicLevels
) - 1;
3483 list( $savedFname, , $savepointId ) = $this->trxAtomicLevels
[$pos];
3485 if ( $savedFname !== $fname ) {
3486 throw new DBUnexpectedError(
3488 "Invalid atomic section ended (got $fname but expected $savedFname)."
3492 // Remove the last section and re-index the array
3493 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos );
3495 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3496 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3497 } elseif ( $savepointId !== null && $savepointId !== 'n/a' ) {
3498 $this->doReleaseSavepoint( $savepointId, $fname );
3502 final public function cancelAtomic(
3503 $fname = __METHOD__
, AtomicSectionIdentifier
$sectionId = null
3505 if ( !$this->trxLevel ||
!$this->trxAtomicLevels
) {
3506 throw new DBUnexpectedError( $this, "No atomic section is open (got $fname)." );
3509 if ( $sectionId !== null ) {
3510 // Find the (last) section with the given $sectionId
3512 foreach ( $this->trxAtomicLevels
as $i => list( $asFname, $asId, $spId ) ) {
3513 if ( $asId === $sectionId ) {
3518 throw new DBUnexpectedError( "Atomic section not found (for $fname)" );
3520 // Remove all descendant sections and re-index the array
3521 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos +
1 );
3524 // Check if the current section matches $fname
3525 $pos = count( $this->trxAtomicLevels
) - 1;
3526 list( $savedFname, , $savepointId ) = $this->trxAtomicLevels
[$pos];
3528 if ( $savedFname !== $fname ) {
3529 throw new DBUnexpectedError(
3531 "Invalid atomic section ended (got $fname but expected $savedFname)."
3535 // Remove the last section and re-index the array
3536 $this->trxAtomicLevels
= array_slice( $this->trxAtomicLevels
, 0, $pos );
3538 if ( $savepointId !== null ) {
3539 // Rollback the transaction to the state just before this atomic section
3540 if ( $savepointId === 'n/a' ) {
3541 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3543 $this->doRollbackToSavepoint( $savepointId, $fname );
3544 $this->trxStatus
= self
::STATUS_TRX_OK
; // no exception; recovered
3545 $this->trxStatusIgnoredCause
= null;
3547 } elseif ( $this->trxStatus
> self
::STATUS_TRX_ERROR
) {
3548 // Put the transaction into an error state if it's not already in one
3549 $this->trxStatus
= self
::STATUS_TRX_ERROR
;
3550 $this->trxStatusCause
= new DBUnexpectedError(
3552 "Uncancelable atomic section canceled (got $fname)."
3556 $this->affectedRowCount
= 0; // for the sake of consistency
3559 final public function doAtomicSection(
3560 $fname, callable
$callback, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3562 $sectionId = $this->startAtomic( $fname, $cancelable );
3564 $res = call_user_func_array( $callback, [ $this, $fname ] );
3565 } catch ( Exception
$e ) {
3566 $this->cancelAtomic( $fname, $sectionId );
3570 $this->endAtomic( $fname );
3575 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3576 static $modes = [ self
::TRANSACTION_EXPLICIT
, self
::TRANSACTION_INTERNAL
];
3577 if ( !in_array( $mode, $modes, true ) ) {
3578 throw new DBUnexpectedError( $this, "$fname: invalid mode parameter '$mode'." );
3581 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3582 if ( $this->trxLevel
) {
3583 if ( $this->trxAtomicLevels
) {
3584 $levels = $this->flatAtomicSectionList();
3585 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3586 throw new DBUnexpectedError( $this, $msg );
3587 } elseif ( !$this->trxAutomatic
) {
3588 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3589 throw new DBUnexpectedError( $this, $msg );
3591 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3592 throw new DBUnexpectedError( $this, $msg );
3594 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3595 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3596 throw new DBUnexpectedError( $this, $msg );
3599 // Avoid fatals if close() was called
3600 $this->assertOpen();
3602 $this->doBegin( $fname );
3603 $this->trxStatus
= self
::STATUS_TRX_OK
;
3604 $this->trxStatusIgnoredCause
= null;
3605 $this->trxAtomicCounter
= 0;
3606 $this->trxTimestamp
= microtime( true );
3607 $this->trxFname
= $fname;
3608 $this->trxDoneWrites
= false;
3609 $this->trxAutomaticAtomic
= false;
3610 $this->trxAtomicLevels
= [];
3611 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3612 $this->trxWriteDuration
= 0.0;
3613 $this->trxWriteQueryCount
= 0;
3614 $this->trxWriteAffectedRows
= 0;
3615 $this->trxWriteAdjDuration
= 0.0;
3616 $this->trxWriteAdjQueryCount
= 0;
3617 $this->trxWriteCallers
= [];
3618 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3619 // Get an estimate of the replication lag before any such queries.
3620 $this->trxReplicaLag
= null; // clear cached value first
3621 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3622 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3623 // caller will think its OK to muck around with the transaction just because startAtomic()
3624 // has not yet completed (e.g. setting trxAtomicLevels).
3625 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3629 * Issues the BEGIN command to the database server.
3631 * @see Database::begin()
3632 * @param string $fname
3634 protected function doBegin( $fname ) {
3635 $this->query( 'BEGIN', $fname );
3636 $this->trxLevel
= 1;
3639 final public function commit( $fname = __METHOD__
, $flush = self
::FLUSHING_ONE
) {
3640 static $modes = [ self
::FLUSHING_ONE
, self
::FLUSHING_ALL_PEERS
, self
::FLUSHING_INTERNAL
];
3641 if ( !in_array( $flush, $modes, true ) ) {
3642 throw new DBUnexpectedError( $this, "$fname: invalid flush parameter '$flush'." );
3645 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3646 // There are still atomic sections open; this cannot be ignored
3647 $levels = $this->flatAtomicSectionList();
3648 throw new DBUnexpectedError(
3650 "$fname: Got COMMIT while atomic sections $levels are still open."
3654 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3655 if ( !$this->trxLevel
) {
3656 return; // nothing to do
3657 } elseif ( !$this->trxAutomatic
) {
3658 throw new DBUnexpectedError(
3660 "$fname: Flushing an explicit transaction, getting out of sync."
3664 if ( !$this->trxLevel
) {
3665 $this->queryLogger
->error(
3666 "$fname: No transaction to commit, something got out of sync." );
3667 return; // nothing to do
3668 } elseif ( $this->trxAutomatic
) {
3669 throw new DBUnexpectedError(
3671 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3676 // Avoid fatals if close() was called
3677 $this->assertOpen();
3679 $this->runOnTransactionPreCommitCallbacks();
3680 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3681 $this->doCommit( $fname );
3682 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3683 if ( $this->trxDoneWrites
) {
3684 $this->lastWriteTime
= microtime( true );
3685 $this->trxProfiler
->transactionWritingOut(
3690 $this->trxWriteAffectedRows
3694 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3695 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3699 * Issues the COMMIT command to the database server.
3701 * @see Database::commit()
3702 * @param string $fname
3704 protected function doCommit( $fname ) {
3705 if ( $this->trxLevel
) {
3706 $this->query( 'COMMIT', $fname );
3707 $this->trxLevel
= 0;
3711 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3712 $trxActive = $this->trxLevel
;
3714 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3715 if ( $this->getFlag( self
::DBO_TRX
) ) {
3716 throw new DBUnexpectedError(
3718 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3724 // Avoid fatals if close() was called
3725 $this->assertOpen();
3727 $this->doRollback( $fname );
3728 $this->trxStatus
= self
::STATUS_TRX_NONE
;
3729 $this->trxAtomicLevels
= [];
3730 if ( $this->trxDoneWrites
) {
3731 $this->trxProfiler
->transactionWritingOut(
3739 // Clear any commit-dependant callbacks. They might even be present
3740 // only due to transaction rounds, with no SQL transaction being active
3741 $this->trxIdleCallbacks
= [];
3742 $this->trxPreCommitCallbacks
= [];
3746 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3747 } catch ( Exception
$e ) {
3748 // already logged; finish and let LoadBalancer move on during mass-rollback
3751 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3752 } catch ( Exception
$e ) {
3753 // already logged; let LoadBalancer move on during mass-rollback
3756 $this->affectedRowCount
= 0; // for the sake of consistency
3761 * Issues the ROLLBACK command to the database server.
3763 * @see Database::rollback()
3764 * @param string $fname
3766 protected function doRollback( $fname ) {
3767 if ( $this->trxLevel
) {
3768 # Disconnects cause rollback anyway, so ignore those errors
3769 $ignoreErrors = true;
3770 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3771 $this->trxLevel
= 0;
3775 public function flushSnapshot( $fname = __METHOD__
) {
3776 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3777 // This only flushes transactions to clear snapshots, not to write data
3778 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3779 throw new DBUnexpectedError(
3781 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3785 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3788 public function explicitTrxActive() {
3789 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3792 public function duplicateTableStructure(
3793 $oldName, $newName, $temporary = false, $fname = __METHOD__
3795 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3798 public function listTables( $prefix = null, $fname = __METHOD__
) {
3799 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3802 public function listViews( $prefix = null, $fname = __METHOD__
) {
3803 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3806 public function timestamp( $ts = 0 ) {
3807 $t = new ConvertibleTimestamp( $ts );
3808 // Let errors bubble up to avoid putting garbage in the DB
3809 return $t->getTimestamp( TS_MW
);
3812 public function timestampOrNull( $ts = null ) {
3813 if ( is_null( $ts ) ) {
3816 return $this->timestamp( $ts );
3820 public function affectedRows() {
3821 return ( $this->affectedRowCount
=== null )
3822 ?
$this->fetchAffectedRowCount() // default to driver value
3823 : $this->affectedRowCount
;
3827 * @return int Number of retrieved rows according to the driver
3829 abstract protected function fetchAffectedRowCount();
3832 * Take the result from a query, and wrap it in a ResultWrapper if
3833 * necessary. Boolean values are passed through as is, to indicate success
3834 * of write queries or failure.
3836 * Once upon a time, Database::query() returned a bare MySQL result
3837 * resource, and it was necessary to call this function to convert it to
3838 * a wrapper. Nowadays, raw database objects are never exposed to external
3839 * callers, so this is unnecessary in external code.
3841 * @param bool|ResultWrapper|resource|object $result
3842 * @return bool|ResultWrapper
3844 protected function resultObject( $result ) {
3847 } elseif ( $result instanceof ResultWrapper
) {
3849 } elseif ( $result === true ) {
3850 // Successful write query
3853 return new ResultWrapper( $this, $result );
3857 public function ping( &$rtt = null ) {
3858 // Avoid hitting the server if it was hit recently
3859 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3860 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3861 $rtt = $this->rttEstimate
;
3862 return true; // don't care about $rtt
3866 // This will reconnect if possible or return false if not
3867 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3868 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3869 $this->restoreFlags( self
::RESTORE_PRIOR
);
3872 $rtt = $this->rttEstimate
;
3879 * Close any existing (dead) database connection and open a new connection
3881 * @param string $fname
3882 * @return bool True if new connection is opened successfully, false if error
3884 protected function replaceLostConnection( $fname ) {
3885 $this->closeConnection();
3886 $this->opened
= false;
3887 $this->conn
= false;
3889 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3890 $this->lastPing
= microtime( true );
3893 $this->connLogger
->warning(
3894 $fname . ': lost connection to {dbserver}; reconnected',
3896 'dbserver' => $this->getServer(),
3897 'trace' => ( new RuntimeException() )->getTraceAsString()
3900 } catch ( DBConnectionError
$e ) {
3903 $this->connLogger
->error(
3904 $fname . ': lost connection to {dbserver} permanently',
3905 [ 'dbserver' => $this->getServer() ]
3909 $this->handleSessionLoss();
3914 public function getSessionLagStatus() {
3915 return $this->getRecordedTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3919 * Get the replica DB lag when the current transaction started
3921 * This is useful when transactions might use snapshot isolation
3922 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3923 * is this lag plus transaction duration. If they don't, it is still
3924 * safe to be pessimistic. This returns null if there is no transaction.
3926 * This returns null if the lag status for this transaction was not yet recorded.
3928 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3931 final protected function getRecordedTransactionLagStatus() {
3932 return ( $this->trxLevel
&& $this->trxReplicaLag
!== null )
3933 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3938 * Get a replica DB lag estimate for this server
3940 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3943 protected function getApproximateLagStatus() {
3945 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3946 'since' => microtime( true )
3951 * Merge the result of getSessionLagStatus() for several DBs
3952 * using the most pessimistic values to estimate the lag of
3953 * any data derived from them in combination
3955 * This is information is useful for caching modules
3957 * @see WANObjectCache::set()
3958 * @see WANObjectCache::getWithSetCallback()
3960 * @param IDatabase $db1
3961 * @param IDatabase $db2 [optional]
3962 * @return array Map of values:
3963 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3964 * - since: oldest UNIX timestamp of any of the DB lag estimates
3965 * - pending: whether any of the DBs have uncommitted changes
3969 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3970 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3971 foreach ( func_get_args() as $db ) {
3972 /** @var IDatabase $db */
3973 $status = $db->getSessionLagStatus();
3974 if ( $status['lag'] === false ) {
3975 $res['lag'] = false;
3976 } elseif ( $res['lag'] !== false ) {
3977 $res['lag'] = max( $res['lag'], $status['lag'] );
3979 $res['since'] = min( $res['since'], $status['since'] );
3980 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3986 public function getLag() {
3990 public function maxListLen() {
3994 public function encodeBlob( $b ) {
3998 public function decodeBlob( $b ) {
3999 if ( $b instanceof Blob
) {
4005 public function setSessionOptions( array $options ) {
4008 public function sourceFile(
4010 callable
$lineCallback = null,
4011 callable
$resultCallback = null,
4013 callable
$inputCallback = null
4015 Wikimedia\
suppressWarnings();
4016 $fp = fopen( $filename, 'r' );
4017 Wikimedia\restoreWarnings
();
4019 if ( false === $fp ) {
4020 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
4024 $fname = __METHOD__
. "( $filename )";
4028 $error = $this->sourceStream(
4029 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4030 } catch ( Exception
$e ) {
4040 public function setSchemaVars( $vars ) {
4041 $this->schemaVars
= $vars;
4044 public function sourceStream(
4046 callable
$lineCallback = null,
4047 callable
$resultCallback = null,
4048 $fname = __METHOD__
,
4049 callable
$inputCallback = null
4051 $delimiterReset = new ScopedCallback(
4052 function ( $delimiter ) {
4053 $this->delimiter
= $delimiter;
4055 [ $this->delimiter
]
4059 while ( !feof( $fp ) ) {
4060 if ( $lineCallback ) {
4061 call_user_func( $lineCallback );
4064 $line = trim( fgets( $fp ) );
4066 if ( $line == '' ) {
4070 if ( '-' == $line[0] && '-' == $line[1] ) {
4078 $done = $this->streamStatementEnd( $cmd, $line );
4082 if ( $done ||
feof( $fp ) ) {
4083 $cmd = $this->replaceVars( $cmd );
4085 if ( $inputCallback ) {
4086 $callbackResult = call_user_func( $inputCallback, $cmd );
4088 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
4089 $cmd = $callbackResult;
4094 $res = $this->query( $cmd, $fname );
4096 if ( $resultCallback ) {
4097 call_user_func( $resultCallback, $res, $this );
4100 if ( false === $res ) {
4101 $err = $this->lastError();
4103 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4110 ScopedCallback
::consume( $delimiterReset );
4115 * Called by sourceStream() to check if we've reached a statement end
4117 * @param string &$sql SQL assembled so far
4118 * @param string &$newLine New line about to be added to $sql
4119 * @return bool Whether $newLine contains end of the statement
4121 public function streamStatementEnd( &$sql, &$newLine ) {
4122 if ( $this->delimiter
) {
4124 $newLine = preg_replace(
4125 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4126 if ( $newLine != $prev ) {
4135 * Database independent variable replacement. Replaces a set of variables
4136 * in an SQL statement with their contents as given by $this->getSchemaVars().
4138 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4140 * - '{$var}' should be used for text and is passed through the database's
4142 * - `{$var}` should be used for identifiers (e.g. table and database names).
4143 * It is passed through the database's addIdentifierQuotes method which
4144 * can be overridden if the database uses something other than backticks.
4145 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4146 * database's tableName method.
4147 * - / *i* / passes the name that follows through the database's indexName method.
4148 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4149 * its use should be avoided. In 1.24 and older, string encoding was applied.
4151 * @param string $ins SQL statement to replace variables in
4152 * @return string The new SQL statement with variables replaced
4154 protected function replaceVars( $ins ) {
4155 $vars = $this->getSchemaVars();
4156 return preg_replace_callback(
4158 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4159 \'\{\$ (\w+) }\' | # 3. addQuotes
4160 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4161 /\*\$ (\w+) \*/ # 5. leave unencoded
4163 function ( $m ) use ( $vars ) {
4164 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4165 // check for both nonexistent keys *and* the empty string.
4166 if ( isset( $m[1] ) && $m[1] !== '' ) {
4167 if ( $m[1] === 'i' ) {
4168 return $this->indexName( $m[2] );
4170 return $this->tableName( $m[2] );
4172 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4173 return $this->addQuotes( $vars[$m[3]] );
4174 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4175 return $this->addIdentifierQuotes( $vars[$m[4]] );
4176 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4177 return $vars[$m[5]];
4187 * Get schema variables. If none have been set via setSchemaVars(), then
4188 * use some defaults from the current object.
4192 protected function getSchemaVars() {
4193 if ( $this->schemaVars
) {
4194 return $this->schemaVars
;
4196 return $this->getDefaultSchemaVars();
4201 * Get schema variables to use if none have been set via setSchemaVars().
4203 * Override this in derived classes to provide variables for tables.sql
4204 * and SQL patch files.
4208 protected function getDefaultSchemaVars() {
4212 public function lockIsFree( $lockName, $method ) {
4213 // RDBMs methods for checking named locks may or may not count this thread itself.
4214 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
4215 // the behavior choosen by the interface for this method.
4216 return !isset( $this->namedLocksHeld
[$lockName] );
4219 public function lock( $lockName, $method, $timeout = 5 ) {
4220 $this->namedLocksHeld
[$lockName] = 1;
4225 public function unlock( $lockName, $method ) {
4226 unset( $this->namedLocksHeld
[$lockName] );
4231 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
4232 if ( $this->writesOrCallbacksPending() ) {
4233 // This only flushes transactions to clear snapshots, not to write data
4234 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
4235 throw new DBUnexpectedError(
4237 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
4241 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
4245 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
4246 if ( $this->trxLevel() ) {
4247 // There is a good chance an exception was thrown, causing any early return
4248 // from the caller. Let any error handler get a chance to issue rollback().
4249 // If there isn't one, let the error bubble up and trigger server-side rollback.
4250 $this->onTransactionResolution(
4251 function () use ( $lockKey, $fname ) {
4252 $this->unlock( $lockKey, $fname );
4257 $this->unlock( $lockKey, $fname );
4261 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4266 public function namedLocksEnqueue() {
4270 public function tableLocksHaveTransactionScope() {
4274 final public function lockTables( array $read, array $write, $method ) {
4275 if ( $this->writesOrCallbacksPending() ) {
4276 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4279 if ( $this->tableLocksHaveTransactionScope() ) {
4280 $this->startAtomic( $method );
4283 return $this->doLockTables( $read, $write, $method );
4287 * Helper function for lockTables() that handles the actual table locking
4289 * @param array $read Array of tables to lock for read access
4290 * @param array $write Array of tables to lock for write access
4291 * @param string $method Name of caller
4294 protected function doLockTables( array $read, array $write, $method ) {
4298 final public function unlockTables( $method ) {
4299 if ( $this->tableLocksHaveTransactionScope() ) {
4300 $this->endAtomic( $method );
4302 return true; // locks released on COMMIT/ROLLBACK
4305 return $this->doUnlockTables( $method );
4309 * Helper function for unlockTables() that handles the actual table unlocking
4311 * @param string $method Name of caller
4314 protected function doUnlockTables( $method ) {
4320 * @param string $tableName
4321 * @param string $fName
4322 * @return bool|ResultWrapper
4325 public function dropTable( $tableName, $fName = __METHOD__
) {
4326 if ( !$this->tableExists( $tableName, $fName ) ) {
4329 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4331 return $this->query( $sql, $fName );
4334 public function getInfinity() {
4338 public function encodeExpiry( $expiry ) {
4339 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4340 ?
$this->getInfinity()
4341 : $this->timestamp( $expiry );
4344 public function decodeExpiry( $expiry, $format = TS_MW
) {
4345 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4349 return ConvertibleTimestamp
::convert( $format, $expiry );
4352 public function setBigSelects( $value = true ) {
4356 public function isReadOnly() {
4357 return ( $this->getReadOnlyReason() !== false );
4361 * @return string|bool Reason this DB is read-only or false if it is not
4363 protected function getReadOnlyReason() {
4364 $reason = $this->getLBInfo( 'readOnlyReason' );
4366 return is_string( $reason ) ?
$reason : false;
4369 public function setTableAliases( array $aliases ) {
4370 $this->tableAliases
= $aliases;
4373 public function setIndexAliases( array $aliases ) {
4374 $this->indexAliases
= $aliases;
4378 * Get the underlying binding connection handle
4380 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4381 * This catches broken callers than catch and ignore disconnection exceptions.
4382 * Unlike checking isOpen(), this is safe to call inside of open().
4385 * @throws DBUnexpectedError
4388 protected function getBindingHandle() {
4389 if ( !$this->conn
) {
4390 throw new DBUnexpectedError(
4392 'DB connection was already closed or the connection dropped.'
4403 public function __toString() {
4404 return (string)$this->conn
;
4408 * Make sure that copies do not share the same client binding handle
4409 * @throws DBConnectionError
4411 public function __clone() {
4412 $this->connLogger
->warning(
4413 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4414 ( new RuntimeException() )->getTraceAsString()
4417 if ( $this->isOpen() ) {
4418 // Open a new connection resource without messing with the old one
4419 $this->opened
= false;
4420 $this->conn
= false;
4421 $this->trxEndCallbacks
= []; // don't copy
4422 $this->handleSessionLoss(); // no trx or locks anymore
4423 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4424 $this->lastPing
= microtime( true );
4429 * Called by serialize. Throw an exception when DB connection is serialized.
4430 * This causes problems on some database engines because the connection is
4431 * not restored on unserialize.
4433 public function __sleep() {
4434 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4435 'the connection is not restored on wakeup.' );
4439 * Run a few simple sanity checks and close dangling connections
4441 public function __destruct() {
4442 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4443 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4446 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4447 if ( $danglingWriters ) {
4448 $fnames = implode( ', ', $danglingWriters );
4449 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4452 if ( $this->conn
) {
4453 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4454 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4455 Wikimedia\
suppressWarnings();
4456 $this->closeConnection();
4457 Wikimedia\restoreWarnings
();
4458 $this->conn
= false;
4459 $this->opened
= false;
4464 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4465 class_alias( Database
::class, 'Database' ); // b/c global alias