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;
105 /** @var resource|null Database connection */
106 protected $conn = null;
108 protected $opened = false;
110 /** @var array[] List of (callable, method name) */
111 protected $trxIdleCallbacks = [];
112 /** @var array[] List of (callable, method name) */
113 protected $trxPreCommitCallbacks = [];
114 /** @var array[] List of (callable, method name) */
115 protected $trxEndCallbacks = [];
116 /** @var callable[] Map of (name => callable) */
117 protected $trxRecurringCallbacks = [];
118 /** @var bool Whether to suppress triggering of transaction end callbacks */
119 protected $trxEndCallbacksSuppressed = false;
122 protected $tablePrefix = '';
124 protected $schema = '';
128 protected $lbInfo = [];
129 /** @var array|bool */
130 protected $schemaVars = false;
132 protected $sessionVars = [];
133 /** @var array|null */
134 protected $preparedArgs;
135 /** @var string|bool|null Stashed value of html_errors INI setting */
136 protected $htmlErrors;
138 protected $delimiter = ';';
139 /** @var DatabaseDomain */
140 protected $currentDomain;
141 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
142 protected $affectedRowCount;
145 * Either 1 if a transaction is active or 0 otherwise.
146 * The other Trx fields may not be meaningfull if this is 0.
150 protected $trxLevel = 0;
152 * Either a short hexidecimal string if a transaction is active or ""
155 * @see Database::trxLevel
157 protected $trxShortId = '';
159 * The UNIX time that the transaction started. Callers can assume that if
160 * snapshot isolation is used, then the data is *at least* up to date to that
161 * point (possibly more up-to-date since the first SELECT defines the snapshot).
164 * @see Database::trxLevel
166 private $trxTimestamp = null;
167 /** @var float Lag estimate at the time of BEGIN */
168 private $trxReplicaLag = null;
170 * Remembers the function name given for starting the most recent transaction via begin().
171 * Used to provide additional context for error reporting.
174 * @see Database::trxLevel
176 private $trxFname = null;
178 * Record if possible write queries were done in the last transaction started
181 * @see Database::trxLevel
183 private $trxDoneWrites = false;
185 * Record if the current transaction was started implicitly due to DBO_TRX being set.
188 * @see Database::trxLevel
190 private $trxAutomatic = false;
192 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
196 private $trxAtomicCounter = 0;
198 * Array of levels of atomicity within transactions
202 private $trxAtomicLevels = [];
204 * Record if the current transaction was started implicitly by Database::startAtomic
208 private $trxAutomaticAtomic = false;
210 * Track the write query callers of the current transaction
214 private $trxWriteCallers = [];
216 * @var float Seconds spent in write queries for the current transaction
218 private $trxWriteDuration = 0.0;
220 * @var int Number of write queries for the current transaction
222 private $trxWriteQueryCount = 0;
224 * @var int Number of rows affected by write queries for the current transaction
226 private $trxWriteAffectedRows = 0;
228 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
230 private $trxWriteAdjDuration = 0.0;
232 * @var int Number of write queries counted in trxWriteAdjDuration
234 private $trxWriteAdjQueryCount = 0;
236 * @var float RTT time estimate
238 private $rttEstimate = 0.0;
240 /** @var array Map of (name => 1) for locks obtained via lock() */
241 private $namedLocksHeld = [];
242 /** @var array Map of (table name => 1) for TEMPORARY tables */
243 protected $sessionTempTables = [];
245 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
246 private $lazyMasterHandle;
248 /** @var float UNIX timestamp */
249 protected $lastPing = 0.0;
251 /** @var int[] Prior flags member variable values */
252 private $priorFlags = [];
254 /** @var object|string Class name or object With profileIn/profileOut methods */
256 /** @var TransactionProfiler */
257 protected $trxProfiler;
260 protected $nonNativeInsertSelectBatchSize = 10000;
263 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
264 * @param array $params Parameters passed from Database::factory()
266 protected function __construct( array $params ) {
267 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
268 $this->connectionParams
[$name] = $params[$name];
271 $this->schema
= $params['schema'];
272 $this->tablePrefix
= $params['tablePrefix'];
274 $this->cliMode
= $params['cliMode'];
275 // Agent name is added to SQL queries in a comment, so make sure it can't break out
276 $this->agent
= str_replace( '/', '-', $params['agent'] );
278 $this->flags
= $params['flags'];
279 if ( $this->flags
& self
::DBO_DEFAULT
) {
280 if ( $this->cliMode
) {
281 $this->flags
&= ~self
::DBO_TRX
;
283 $this->flags |
= self
::DBO_TRX
;
286 // Disregard deprecated DBO_IGNORE flag (T189999)
287 $this->flags
&= ~self
::DBO_IGNORE
;
289 $this->sessionVars
= $params['variables'];
291 $this->srvCache
= isset( $params['srvCache'] )
292 ?
$params['srvCache']
293 : new HashBagOStuff();
295 $this->profiler
= $params['profiler'];
296 $this->trxProfiler
= $params['trxProfiler'];
297 $this->connLogger
= $params['connLogger'];
298 $this->queryLogger
= $params['queryLogger'];
299 $this->errorLogger
= $params['errorLogger'];
301 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
302 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
305 // Set initial dummy domain until open() sets the final DB/prefix
306 $this->currentDomain
= DatabaseDomain
::newUnspecified();
310 * Initialize the connection to the database over the wire (or to local files)
312 * @throws LogicException
313 * @throws InvalidArgumentException
314 * @throws DBConnectionError
317 final public function initConnection() {
318 if ( $this->isOpen() ) {
319 throw new LogicException( __METHOD__
. ': already connected.' );
321 // Establish the connection
322 $this->doInitConnection();
323 // Set the domain object after open() sets the relevant fields
324 if ( $this->dbName
!= '' ) {
325 // Domains with server scope but a table prefix are not used by IDatabase classes
326 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
331 * Actually connect to the database over the wire (or to local files)
333 * @throws InvalidArgumentException
334 * @throws DBConnectionError
337 protected function doInitConnection() {
338 if ( strlen( $this->connectionParams
['user'] ) ) {
340 $this->connectionParams
['host'],
341 $this->connectionParams
['user'],
342 $this->connectionParams
['password'],
343 $this->connectionParams
['dbname']
346 throw new InvalidArgumentException( "No database user provided." );
351 * Construct a Database subclass instance given a database type and parameters
353 * This also connects to the database immediately upon object construction
355 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
356 * @param array $p Parameter map with keys:
357 * - host : The hostname of the DB server
358 * - user : The name of the database user the client operates under
359 * - password : The password for the database user
360 * - dbname : The name of the database to use where queries do not specify one.
361 * The database must exist or an error might be thrown. Setting this to the empty string
362 * will avoid any such errors and make the handle have no implicit database scope. This is
363 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
364 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
365 * in which user names and such are defined, e.g. users are database-specific in Postgres.
366 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
367 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
368 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
369 * recognized in queries. This can be used in place of schemas for handle site farms.
370 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
371 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
372 * flag in place UNLESS this this database simply acts as a key/value store.
373 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
374 * 'mysqli' driver; the old one 'mysql' has been removed.
375 * - variables: Optional map of session variables to set after connecting. This can be
376 * used to adjust lock timeouts or encoding modes and the like.
377 * - connLogger: Optional PSR-3 logger interface instance.
378 * - queryLogger: Optional PSR-3 logger interface instance.
379 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
380 * These will be called in query(), using a simplified version of the SQL that also
381 * includes the agent as a SQL comment.
382 * - trxProfiler: Optional TransactionProfiler instance.
383 * - errorLogger: Optional callback that takes an Exception and logs it.
384 * - cliMode: Whether to consider the execution context that of a CLI script.
385 * - agent: Optional name used to identify the end-user in query profiling/logging.
386 * - srvCache: Optional BagOStuff instance to an APC-style cache.
387 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
388 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
389 * @return Database|null If the database driver or extension cannot be found
390 * @throws InvalidArgumentException If the database driver or extension cannot be found
393 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
394 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
396 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
397 // Resolve some defaults for b/c
398 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
399 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
400 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
401 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
402 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
403 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
404 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
405 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
406 $p['cliMode'] = isset( $p['cliMode'] )
408 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
409 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
410 if ( !isset( $p['connLogger'] ) ) {
411 $p['connLogger'] = new NullLogger();
413 if ( !isset( $p['queryLogger'] ) ) {
414 $p['queryLogger'] = new NullLogger();
416 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
417 if ( !isset( $p['trxProfiler'] ) ) {
418 $p['trxProfiler'] = new TransactionProfiler();
420 if ( !isset( $p['errorLogger'] ) ) {
421 $p['errorLogger'] = function ( Exception
$e ) {
422 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
426 /** @var Database $conn */
427 $conn = new $class( $p );
428 if ( $connect == self
::NEW_CONNECTED
) {
429 $conn->initConnection();
439 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
440 * @param string|null $driver Optional name of a specific DB client driver
441 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
442 * @throws InvalidArgumentException
445 final public static function attributesFromType( $dbType, $driver = null ) {
446 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
448 $class = self
::getClass( $dbType, $driver );
450 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
454 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
455 * @param string|null $driver Optional name of a specific DB client driver
456 * @return string Database subclass name to use
457 * @throws InvalidArgumentException
459 private static function getClass( $dbType, $driver = null ) {
460 // For database types with built-in support, the below maps type to IDatabase
461 // implementations. For types with multipe driver implementations (PHP extensions),
462 // an array can be used, keyed by extension name. In case of an array, the
463 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
464 // we auto-detect the first available driver. For types without built-in support,
465 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
466 static $builtinTypes = [
467 'mssql' => DatabaseMssql
::class,
468 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
469 'sqlite' => DatabaseSqlite
::class,
470 'postgres' => DatabasePostgres
::class,
473 $dbType = strtolower( $dbType );
476 if ( isset( $builtinTypes[$dbType] ) ) {
477 $possibleDrivers = $builtinTypes[$dbType];
478 if ( is_string( $possibleDrivers ) ) {
479 $class = $possibleDrivers;
481 if ( (string)$driver !== '' ) {
482 if ( !isset( $possibleDrivers[$driver] ) ) {
483 throw new InvalidArgumentException( __METHOD__
.
484 " type '$dbType' does not support driver '{$driver}'" );
486 $class = $possibleDrivers[$driver];
489 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
490 if ( extension_loaded( $posDriver ) ) {
491 $class = $possibleClass;
498 $class = 'Database' . ucfirst( $dbType );
501 if ( $class === false ) {
502 throw new InvalidArgumentException( __METHOD__
.
503 " no viable database extension found for type '$dbType'" );
510 * @return array Map of (Database::ATTRIBUTE_* constant => value
513 protected static function getAttributes() {
518 * Set the PSR-3 logger interface to use for query logging. (The logger
519 * interfaces for connection logging and error logging can be set with the
522 * @param LoggerInterface $logger
524 public function setLogger( LoggerInterface
$logger ) {
525 $this->queryLogger
= $logger;
528 public function getServerInfo() {
529 return $this->getServerVersion();
532 public function bufferResults( $buffer = null ) {
533 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
534 if ( $buffer !== null ) {
536 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
537 : $this->setFlag( self
::DBO_NOBUFFER
);
543 public function trxLevel() {
544 return $this->trxLevel
;
547 public function trxTimestamp() {
548 return $this->trxLevel ?
$this->trxTimestamp
: null;
551 public function tablePrefix( $prefix = null ) {
552 $old = $this->tablePrefix
;
553 if ( $prefix !== null ) {
554 $this->tablePrefix
= $prefix;
555 $this->currentDomain
= ( $this->dbName
!= '' )
556 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
557 : DatabaseDomain
::newUnspecified();
563 public function dbSchema( $schema = null ) {
564 $old = $this->schema
;
565 if ( $schema !== null ) {
566 $this->schema
= $schema;
572 public function getLBInfo( $name = null ) {
573 if ( is_null( $name ) ) {
574 return $this->lbInfo
;
576 if ( array_key_exists( $name, $this->lbInfo
) ) {
577 return $this->lbInfo
[$name];
584 public function setLBInfo( $name, $value = null ) {
585 if ( is_null( $value ) ) {
586 $this->lbInfo
= $name;
588 $this->lbInfo
[$name] = $value;
592 public function setLazyMasterHandle( IDatabase
$conn ) {
593 $this->lazyMasterHandle
= $conn;
597 * @return IDatabase|null
598 * @see setLazyMasterHandle()
601 protected function getLazyMasterHandle() {
602 return $this->lazyMasterHandle
;
605 public function implicitGroupby() {
609 public function implicitOrderby() {
613 public function lastQuery() {
614 return $this->lastQuery
;
617 public function doneWrites() {
618 return (bool)$this->lastWriteTime
;
621 public function lastDoneWrites() {
622 return $this->lastWriteTime ?
: false;
625 public function writesPending() {
626 return $this->trxLevel
&& $this->trxDoneWrites
;
629 public function writesOrCallbacksPending() {
630 return $this->trxLevel
&& (
631 $this->trxDoneWrites ||
632 $this->trxIdleCallbacks ||
633 $this->trxPreCommitCallbacks ||
634 $this->trxEndCallbacks
638 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
639 if ( !$this->trxLevel
) {
641 } elseif ( !$this->trxDoneWrites
) {
646 case self
::ESTIMATE_DB_APPLY
:
648 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
649 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
650 // For omitted queries, make them count as something at least
651 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
652 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
655 default: // everything
656 return $this->trxWriteDuration
;
660 public function pendingWriteCallers() {
661 return $this->trxLevel ?
$this->trxWriteCallers
: [];
664 public function pendingWriteRowsAffected() {
665 return $this->trxWriteAffectedRows
;
669 * Get the list of method names that have pending write queries or callbacks
670 * for this transaction
674 protected function pendingWriteAndCallbackCallers() {
675 if ( !$this->trxLevel
) {
679 $fnames = $this->trxWriteCallers
;
681 $this->trxIdleCallbacks
,
682 $this->trxPreCommitCallbacks
,
683 $this->trxEndCallbacks
685 foreach ( $callbacks as $callback ) {
686 $fnames[] = $callback[1];
693 public function isOpen() {
694 return $this->opened
;
697 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
698 if ( ( $flag & self
::DBO_IGNORE
) ) {
699 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
702 if ( $remember === self
::REMEMBER_PRIOR
) {
703 array_push( $this->priorFlags
, $this->flags
);
705 $this->flags |
= $flag;
708 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
709 if ( ( $flag & self
::DBO_IGNORE
) ) {
710 throw new UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
713 if ( $remember === self
::REMEMBER_PRIOR
) {
714 array_push( $this->priorFlags
, $this->flags
);
716 $this->flags
&= ~
$flag;
719 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
720 if ( !$this->priorFlags
) {
724 if ( $state === self
::RESTORE_INITIAL
) {
725 $this->flags
= reset( $this->priorFlags
);
726 $this->priorFlags
= [];
728 $this->flags
= array_pop( $this->priorFlags
);
732 public function getFlag( $flag ) {
733 return !!( $this->flags
& $flag );
737 * @param string $name Class field name
739 * @deprecated Since 1.28
741 public function getProperty( $name ) {
745 public function getDomainID() {
746 return $this->currentDomain
->getId();
749 final public function getWikiID() {
750 return $this->getDomainID();
754 * Get information about an index into an object
755 * @param string $table Table name
756 * @param string $index Index name
757 * @param string $fname Calling function name
758 * @return mixed Database-specific index description class or false if the index does not exist
760 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
763 * Wrapper for addslashes()
765 * @param string $s String to be slashed.
766 * @return string Slashed string.
768 abstract function strencode( $s );
771 * Set a custom error handler for logging errors during database connection
773 protected function installErrorHandler() {
774 $this->phpError
= false;
775 $this->htmlErrors
= ini_set( 'html_errors', '0' );
776 set_error_handler( [ $this, 'connectionErrorLogger' ] );
780 * Restore the previous error handler and return the last PHP error for this DB
782 * @return bool|string
784 protected function restoreErrorHandler() {
785 restore_error_handler();
786 if ( $this->htmlErrors
!== false ) {
787 ini_set( 'html_errors', $this->htmlErrors
);
790 return $this->getLastPHPError();
794 * @return string|bool Last PHP error for this DB (typically connection errors)
796 protected function getLastPHPError() {
797 if ( $this->phpError
) {
798 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
799 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
808 * Error handler for logging errors during database connection
809 * This method should not be used outside of Database classes
812 * @param string $errstr
814 public function connectionErrorLogger( $errno, $errstr ) {
815 $this->phpError
= $errstr;
819 * Create a log context to pass to PSR-3 logger functions.
821 * @param array $extras Additional data to add to context
824 protected function getLogContext( array $extras = [] ) {
827 'db_server' => $this->server
,
828 'db_name' => $this->dbName
,
829 'db_user' => $this->user
,
835 public function close() {
837 // Resolve any dangling transaction first
838 if ( $this->trxLevel() ) {
839 // Meaningful transactions should ideally have been resolved by now
840 if ( $this->writesOrCallbacksPending() ) {
841 $this->queryLogger
->warning(
842 __METHOD__
. ": writes or callbacks still pending.",
843 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
846 // Check if it is possible to properly commit and trigger callbacks
847 if ( $this->trxEndCallbacksSuppressed
) {
848 throw new DBUnexpectedError(
850 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
853 // Commit the changes and run any callbacks as needed
854 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
856 // Close the actual connection in the binding handle
857 $closed = $this->closeConnection();
859 // Sanity check that no callbacks are dangling
861 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
863 throw new RuntimeException( "Transaction callbacks still pending." );
866 $closed = true; // already closed; nothing to do
869 $this->opened
= false;
875 * Make sure isOpen() returns true as a sanity check
877 * @throws DBUnexpectedError
879 protected function assertOpen() {
880 if ( !$this->isOpen() ) {
881 throw new DBUnexpectedError( $this, "DB connection was already closed." );
886 * Closes underlying database connection
888 * @return bool Whether connection was closed successfully
890 abstract protected function closeConnection();
893 * @param string $error Fallback error message, used if none is given by DB
894 * @throws DBConnectionError
896 public function reportConnectionError( $error = 'Unknown error' ) {
897 $myError = $this->lastError();
903 throw new DBConnectionError( $this, $error );
907 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
909 * This might return things, such as mysqli_result, that do not formally implement
910 * IResultWrapper, but nonetheless implement all of its methods correctly
912 * @param string $sql SQL query.
913 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
915 abstract protected function doQuery( $sql );
918 * Determine whether a query writes to the DB.
919 * Should return true if unsure.
924 protected function isWriteQuery( $sql ) {
926 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
931 * @return string|null
933 protected function getQueryVerb( $sql ) {
934 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
938 * Determine whether a SQL statement is sensitive to isolation level.
939 * A SQL statement is considered transactable if its result could vary
940 * depending on the transaction isolation level. Operational commands
941 * such as 'SET' and 'SHOW' are not considered to be transactable.
946 protected function isTransactableQuery( $sql ) {
948 $this->getQueryVerb( $sql ),
949 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
955 * @param string $sql A SQL query
956 * @return bool Whether $sql is SQL for TEMPORARY table operation
958 protected function registerTempTableOperation( $sql ) {
960 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
964 $this->sessionTempTables
[$matches[1]] = 1;
967 } elseif ( preg_match(
968 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
972 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
973 unset( $this->sessionTempTables
[$matches[1]] );
976 } elseif ( preg_match(
977 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
981 return isset( $this->sessionTempTables
[$matches[1]] );
982 } elseif ( preg_match(
983 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
987 return isset( $this->sessionTempTables
[$matches[1]] );
993 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
994 $priorWritesPending = $this->writesOrCallbacksPending();
995 $this->lastQuery
= $sql;
997 $isWrite = $this->isWriteQuery( $sql );
999 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
1001 $isNonTempWrite = false;
1005 if ( $this->getLBInfo( 'replica' ) === true ) {
1008 'Write operations are not allowed on replica database connections.'
1011 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1012 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1013 $reason = $this->getReadOnlyReason();
1014 if ( $reason !== false ) {
1015 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1017 # Set a flag indicating that writes have been done
1018 $this->lastWriteTime
= microtime( true );
1021 # Add trace comment to the begin of the sql string, right after the operator.
1022 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1023 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1025 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1026 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1027 && $this->isTransactableQuery( $sql )
1029 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1030 $this->trxAutomatic
= true;
1033 # Keep track of whether the transaction has write queries pending
1034 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1035 $this->trxDoneWrites
= true;
1036 $this->trxProfiler
->transactionWritingIn(
1037 $this->server
, $this->dbName
, $this->trxShortId
);
1040 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1041 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1044 # Avoid fatals if close() was called
1045 $this->assertOpen();
1047 # Send the query to the server
1048 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1050 # Try reconnecting if the connection was lost
1051 if ( false === $ret && $this->wasConnectionLoss() ) {
1052 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1053 # Stash the last error values before anything might clear them
1054 $lastError = $this->lastError();
1055 $lastErrno = $this->lastErrno();
1056 # Update state tracking to reflect transaction loss due to disconnection
1057 $this->handleSessionLoss();
1058 if ( $this->reconnect() ) {
1059 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1060 $params = [ 'dbserver' => $this->getServer() ];
1061 $this->connLogger
->warning( $msg, $params );
1062 $this->queryLogger
->warning( $msg, $params +
1063 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1065 if ( $recoverable ) {
1066 # Should be safe to silently retry the query
1067 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1069 # Callers may catch the exception and continue to use the DB
1070 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1073 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1074 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1078 if ( false === $ret ) {
1079 # Deadlocks cause the entire transaction to abort, not just the statement.
1080 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1081 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1082 if ( $this->wasDeadlock() ) {
1083 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1084 $tempIgnore = false; // not recoverable
1086 # Update state tracking to reflect transaction loss
1087 $this->handleSessionLoss();
1090 $this->reportQueryError(
1091 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1094 $res = $this->resultObject( $ret );
1100 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1102 * @param string $sql Original SQL query
1103 * @param string $commentedSql SQL query with debugging/trace comment
1104 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1105 * @param string $fname Name of the calling function
1106 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1107 * object for a successful read query, or false on failure
1109 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1110 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1111 # generalizeSQL() will probably cut down the query to reasonable
1112 # logging size most of the time. The substr is really just a sanity check.
1114 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1116 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1119 # Include query transaction state
1120 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1122 $startTime = microtime( true );
1123 if ( $this->profiler
) {
1124 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1126 $this->affectedRowCount
= null;
1127 $ret = $this->doQuery( $commentedSql );
1128 $this->affectedRowCount
= $this->affectedRows();
1129 if ( $this->profiler
) {
1130 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1132 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1134 unset( $queryProfSection ); // profile out (if set)
1136 if ( $ret !== false ) {
1137 $this->lastPing
= $startTime;
1138 if ( $isWrite && $this->trxLevel
) {
1139 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1140 $this->trxWriteCallers
[] = $fname;
1144 if ( $sql === self
::PING_QUERY
) {
1145 $this->rttEstimate
= $queryRuntime;
1148 $this->trxProfiler
->recordQueryCompletion(
1149 $queryProf, $startTime, $isWrite, $this->affectedRows()
1151 $this->queryLogger
->debug( $sql, [
1153 'master' => $isMaster,
1154 'runtime' => $queryRuntime,
1161 * Update the estimated run-time of a query, not counting large row lock times
1163 * LoadBalancer can be set to rollback transactions that will create huge replication
1164 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1165 * queries, like inserting a row can take a long time due to row locking. This method
1166 * uses some simple heuristics to discount those cases.
1168 * @param string $sql A SQL write query
1169 * @param float $runtime Total runtime, including RTT
1170 * @param int $affected Affected row count
1172 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1173 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1174 $indicativeOfReplicaRuntime = true;
1175 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1176 $verb = $this->getQueryVerb( $sql );
1177 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1178 if ( $verb === 'INSERT' ) {
1179 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1180 } elseif ( $verb === 'REPLACE' ) {
1181 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1185 $this->trxWriteDuration +
= $runtime;
1186 $this->trxWriteQueryCount +
= 1;
1187 $this->trxWriteAffectedRows +
= $affected;
1188 if ( $indicativeOfReplicaRuntime ) {
1189 $this->trxWriteAdjDuration +
= $runtime;
1190 $this->trxWriteAdjQueryCount +
= 1;
1195 * Determine whether or not it is safe to retry queries after a database
1196 * connection is lost
1198 * @param string $sql SQL query
1199 * @param bool $priorWritesPending Whether there is a transaction open with
1200 * possible write queries or transaction pre-commit/idle callbacks
1201 * waiting on it to finish.
1202 * @return bool True if it is safe to retry the query, false otherwise
1204 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1205 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1206 # Dropped connections also mean that named locks are automatically released.
1207 # Only allow error suppression in autocommit mode or when the lost transaction
1208 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1209 if ( $this->namedLocksHeld
) {
1210 return false; // possible critical section violation
1211 } elseif ( $sql === 'COMMIT' ) {
1212 return !$priorWritesPending; // nothing written anyway? (T127428)
1213 } elseif ( $sql === 'ROLLBACK' ) {
1214 return true; // transaction lost...which is also what was requested :)
1215 } elseif ( $this->explicitTrxActive() ) {
1216 return false; // don't drop atomocity
1217 } elseif ( $priorWritesPending ) {
1218 return false; // prior writes lost from implicit transaction
1225 * Clean things up after transaction loss due to disconnection
1227 * @return null|Exception
1229 private function handleSessionLoss() {
1230 $this->trxLevel
= 0;
1231 $this->trxAtomicCounter
= 0;
1232 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1233 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1234 $this->sessionTempTables
= [];
1235 $this->namedLocksHeld
= [];
1237 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1240 // Handle callbacks in trxEndCallbacks
1241 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1242 } catch ( Exception
$ex ) {
1243 // Already logged; move on...
1247 // Handle callbacks in trxRecurringCallbacks
1248 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1249 } catch ( Exception
$ex ) {
1250 // Already logged; move on...
1258 * Checks whether the cause of the error is detected to be a timeout.
1260 * It returns false by default, and not all engines support detecting this yet.
1261 * If this returns false, it will be treated as a generic query error.
1263 * @param string $error Error text
1264 * @param int $errno Error number
1267 protected function wasQueryTimeout( $error, $errno ) {
1272 * Report a query error. Log the error, and if neither the object ignore
1273 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1275 * @param string $error
1277 * @param string $sql
1278 * @param string $fname
1279 * @param bool $tempIgnore
1280 * @throws DBQueryError
1282 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1283 if ( $tempIgnore ) {
1284 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1286 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1287 $this->queryLogger
->error(
1288 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1289 $this->getLogContext( [
1290 'method' => __METHOD__
,
1293 'sql1line' => $sql1line,
1297 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1298 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1299 if ( $wasQueryTimeout ) {
1300 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1302 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1307 public function freeResult( $res ) {
1310 public function selectField(
1311 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1313 if ( $var === '*' ) { // sanity
1314 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1317 if ( !is_array( $options ) ) {
1318 $options = [ $options ];
1321 $options['LIMIT'] = 1;
1323 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1324 if ( $res === false ||
!$this->numRows( $res ) ) {
1328 $row = $this->fetchRow( $res );
1330 if ( $row !== false ) {
1331 return reset( $row );
1337 public function selectFieldValues(
1338 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1340 if ( $var === '*' ) { // sanity
1341 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1342 } elseif ( !is_string( $var ) ) { // sanity
1343 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1346 if ( !is_array( $options ) ) {
1347 $options = [ $options ];
1350 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1351 if ( $res === false ) {
1356 foreach ( $res as $row ) {
1357 $values[] = $row->$var;
1364 * Returns an optional USE INDEX clause to go after the table, and a
1365 * string to go at the end of the query.
1367 * @param array $options Associative array of options to be turned into
1368 * an SQL query, valid keys are listed in the function.
1370 * @see Database::select()
1372 protected function makeSelectOptions( $options ) {
1373 $preLimitTail = $postLimitTail = '';
1378 foreach ( $options as $key => $option ) {
1379 if ( is_numeric( $key ) ) {
1380 $noKeyOptions[$option] = true;
1384 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1386 $preLimitTail .= $this->makeOrderBy( $options );
1388 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1389 $postLimitTail .= ' FOR UPDATE';
1392 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1393 $postLimitTail .= ' LOCK IN SHARE MODE';
1396 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1397 $startOpts .= 'DISTINCT';
1400 # Various MySQL extensions
1401 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1402 $startOpts .= ' /*! STRAIGHT_JOIN */';
1405 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1406 $startOpts .= ' HIGH_PRIORITY';
1409 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1410 $startOpts .= ' SQL_BIG_RESULT';
1413 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1414 $startOpts .= ' SQL_BUFFER_RESULT';
1417 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1418 $startOpts .= ' SQL_SMALL_RESULT';
1421 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1422 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1425 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1426 $startOpts .= ' SQL_CACHE';
1429 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1430 $startOpts .= ' SQL_NO_CACHE';
1433 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1434 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1438 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1439 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1444 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1448 * Returns an optional GROUP BY with an optional HAVING
1450 * @param array $options Associative array of options
1452 * @see Database::select()
1455 protected function makeGroupByWithHaving( $options ) {
1457 if ( isset( $options['GROUP BY'] ) ) {
1458 $gb = is_array( $options['GROUP BY'] )
1459 ?
implode( ',', $options['GROUP BY'] )
1460 : $options['GROUP BY'];
1461 $sql .= ' GROUP BY ' . $gb;
1463 if ( isset( $options['HAVING'] ) ) {
1464 $having = is_array( $options['HAVING'] )
1465 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1466 : $options['HAVING'];
1467 $sql .= ' HAVING ' . $having;
1474 * Returns an optional ORDER BY
1476 * @param array $options Associative array of options
1478 * @see Database::select()
1481 protected function makeOrderBy( $options ) {
1482 if ( isset( $options['ORDER BY'] ) ) {
1483 $ob = is_array( $options['ORDER BY'] )
1484 ?
implode( ',', $options['ORDER BY'] )
1485 : $options['ORDER BY'];
1487 return ' ORDER BY ' . $ob;
1493 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1494 $options = [], $join_conds = [] ) {
1495 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1497 return $this->query( $sql, $fname );
1500 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1501 $options = [], $join_conds = []
1503 if ( is_array( $vars ) ) {
1504 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1507 $options = (array)$options;
1508 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1509 ?
$options['USE INDEX']
1512 isset( $options['IGNORE INDEX'] ) &&
1513 is_array( $options['IGNORE INDEX'] )
1515 ?
$options['IGNORE INDEX']
1518 if ( is_array( $table ) ) {
1520 $this->tableNamesWithIndexClauseOrJOIN(
1521 $table, $useIndexes, $ignoreIndexes, $join_conds );
1522 } elseif ( $table != '' ) {
1524 $this->tableNamesWithIndexClauseOrJOIN(
1525 [ $table ], $useIndexes, $ignoreIndexes, [] );
1530 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1531 $this->makeSelectOptions( $options );
1533 if ( is_array( $conds ) ) {
1534 $conds = $this->makeList( $conds, self
::LIST_AND
);
1537 if ( $conds === null ||
$conds === false ) {
1538 $this->queryLogger
->warning(
1542 . ' with incorrect parameters: $conds must be a string or an array'
1547 if ( $conds === '' ) {
1548 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1549 } elseif ( is_string( $conds ) ) {
1550 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1551 "WHERE $conds $preLimitTail";
1553 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1556 if ( isset( $options['LIMIT'] ) ) {
1557 $sql = $this->limitResult( $sql, $options['LIMIT'],
1558 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1560 $sql = "$sql $postLimitTail";
1562 if ( isset( $options['EXPLAIN'] ) ) {
1563 $sql = 'EXPLAIN ' . $sql;
1569 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1570 $options = [], $join_conds = []
1572 $options = (array)$options;
1573 $options['LIMIT'] = 1;
1574 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1576 if ( $res === false ) {
1580 if ( !$this->numRows( $res ) ) {
1584 $obj = $this->fetchObject( $res );
1589 public function estimateRowCount(
1590 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1592 $conds = $this->normalizeConditions( $conds, $fname );
1593 $column = $this->extractSingleFieldFromList( $var );
1594 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1595 $conds[] = "$column IS NOT NULL";
1598 $res = $this->select(
1599 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1601 $row = $res ?
$this->fetchRow( $res ) : [];
1603 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1606 public function selectRowCount(
1607 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1609 $conds = $this->normalizeConditions( $conds, $fname );
1610 $column = $this->extractSingleFieldFromList( $var );
1611 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1612 $conds[] = "$column IS NOT NULL";
1615 $res = $this->select(
1617 'tmp_count' => $this->buildSelectSubquery(
1626 [ 'rowcount' => 'COUNT(*)' ],
1630 $row = $res ?
$this->fetchRow( $res ) : [];
1632 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1636 * @param array|string $conds
1637 * @param string $fname
1640 final protected function normalizeConditions( $conds, $fname ) {
1641 if ( $conds === null ||
$conds === false ) {
1642 $this->queryLogger
->warning(
1646 . ' with incorrect parameters: $conds must be a string or an array'
1651 if ( !is_array( $conds ) ) {
1652 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1659 * @param array|string $var Field parameter in the style of select()
1660 * @return string|null Column name or null; ignores aliases
1661 * @throws DBUnexpectedError Errors out if multiple columns are given
1663 final protected function extractSingleFieldFromList( $var ) {
1664 if ( is_array( $var ) ) {
1667 } elseif ( count( $var ) == 1 ) {
1668 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1670 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1680 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1681 * It's only slightly flawed. Don't use for anything important.
1683 * @param string $sql A SQL Query
1687 protected static function generalizeSQL( $sql ) {
1688 # This does the same as the regexp below would do, but in such a way
1689 # as to avoid crashing php on some large strings.
1690 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1692 $sql = str_replace( "\\\\", '', $sql );
1693 $sql = str_replace( "\\'", '', $sql );
1694 $sql = str_replace( "\\\"", '', $sql );
1695 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1696 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1698 # All newlines, tabs, etc replaced by single space
1699 $sql = preg_replace( '/\s+/', ' ', $sql );
1702 # except the ones surrounded by characters, e.g. l10n
1703 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1704 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1709 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1710 $info = $this->fieldInfo( $table, $field );
1715 public function indexExists( $table, $index, $fname = __METHOD__
) {
1716 if ( !$this->tableExists( $table ) ) {
1720 $info = $this->indexInfo( $table, $index, $fname );
1721 if ( is_null( $info ) ) {
1724 return $info !== false;
1728 public function tableExists( $table, $fname = __METHOD__
) {
1729 $tableRaw = $this->tableName( $table, 'raw' );
1730 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1731 return true; // already known to exist
1734 $table = $this->tableName( $table );
1735 $ignoreErrors = true;
1736 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1741 public function indexUnique( $table, $index ) {
1742 $indexInfo = $this->indexInfo( $table, $index );
1744 if ( !$indexInfo ) {
1748 return !$indexInfo[0]->Non_unique
;
1752 * Helper for Database::insert().
1754 * @param array $options
1757 protected function makeInsertOptions( $options ) {
1758 return implode( ' ', $options );
1761 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1762 # No rows to insert, easy just return now
1763 if ( !count( $a ) ) {
1767 $table = $this->tableName( $table );
1769 if ( !is_array( $options ) ) {
1770 $options = [ $options ];
1774 if ( isset( $options['fileHandle'] ) ) {
1775 $fh = $options['fileHandle'];
1777 $options = $this->makeInsertOptions( $options );
1779 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1781 $keys = array_keys( $a[0] );
1784 $keys = array_keys( $a );
1787 $sql = 'INSERT ' . $options .
1788 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1792 foreach ( $a as $row ) {
1798 $sql .= '(' . $this->makeList( $row ) . ')';
1801 $sql .= '(' . $this->makeList( $a ) . ')';
1804 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1806 } elseif ( $fh !== null ) {
1810 return (bool)$this->query( $sql, $fname );
1814 * Make UPDATE options array for Database::makeUpdateOptions
1816 * @param array $options
1819 protected function makeUpdateOptionsArray( $options ) {
1820 if ( !is_array( $options ) ) {
1821 $options = [ $options ];
1826 if ( in_array( 'IGNORE', $options ) ) {
1834 * Make UPDATE options for the Database::update function
1836 * @param array $options The options passed to Database::update
1839 protected function makeUpdateOptions( $options ) {
1840 $opts = $this->makeUpdateOptionsArray( $options );
1842 return implode( ' ', $opts );
1845 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1846 $table = $this->tableName( $table );
1847 $opts = $this->makeUpdateOptions( $options );
1848 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1850 if ( $conds !== [] && $conds !== '*' ) {
1851 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1854 return (bool)$this->query( $sql, $fname );
1857 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1858 if ( !is_array( $a ) ) {
1859 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1865 foreach ( $a as $field => $value ) {
1867 if ( $mode == self
::LIST_AND
) {
1869 } elseif ( $mode == self
::LIST_OR
) {
1878 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1879 $list .= "($value)";
1880 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1883 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1885 // Remove null from array to be handled separately if found
1886 $includeNull = false;
1887 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1888 $includeNull = true;
1889 unset( $value[$nullKey] );
1891 if ( count( $value ) == 0 && !$includeNull ) {
1892 throw new InvalidArgumentException(
1893 __METHOD__
. ": empty input for field $field" );
1894 } elseif ( count( $value ) == 0 ) {
1895 // only check if $field is null
1896 $list .= "$field IS NULL";
1898 // IN clause contains at least one valid element
1899 if ( $includeNull ) {
1900 // Group subconditions to ensure correct precedence
1903 if ( count( $value ) == 1 ) {
1904 // Special-case single values, as IN isn't terribly efficient
1905 // Don't necessarily assume the single key is 0; we don't
1906 // enforce linear numeric ordering on other arrays here.
1907 $value = array_values( $value )[0];
1908 $list .= $field . " = " . $this->addQuotes( $value );
1910 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1912 // if null present in array, append IS NULL
1913 if ( $includeNull ) {
1914 $list .= " OR $field IS NULL)";
1917 } elseif ( $value === null ) {
1918 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1919 $list .= "$field IS ";
1920 } elseif ( $mode == self
::LIST_SET
) {
1921 $list .= "$field = ";
1926 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1928 $list .= "$field = ";
1930 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1937 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1940 foreach ( $data as $base => $sub ) {
1941 if ( count( $sub ) ) {
1942 $conds[] = $this->makeList(
1943 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1949 return $this->makeList( $conds, self
::LIST_OR
);
1951 // Nothing to search for...
1956 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1960 public function bitNot( $field ) {
1964 public function bitAnd( $fieldLeft, $fieldRight ) {
1965 return "($fieldLeft & $fieldRight)";
1968 public function bitOr( $fieldLeft, $fieldRight ) {
1969 return "($fieldLeft | $fieldRight)";
1972 public function buildConcat( $stringList ) {
1973 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1976 public function buildGroupConcatField(
1977 $delim, $table, $field, $conds = '', $join_conds = []
1979 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1981 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1984 public function buildSubstring( $input, $startPosition, $length = null ) {
1985 $this->assertBuildSubstringParams( $startPosition, $length );
1986 $functionBody = "$input FROM $startPosition";
1987 if ( $length !== null ) {
1988 $functionBody .= " FOR $length";
1990 return 'SUBSTRING(' . $functionBody . ')';
1994 * Check type and bounds for parameters to self::buildSubstring()
1996 * All supported databases have substring functions that behave the same for
1997 * positive $startPosition and non-negative $length, but behaviors differ when
1998 * given 0 or negative $startPosition or negative $length. The simplest
1999 * solution to that is to just forbid those values.
2001 * @param int $startPosition
2002 * @param int|null $length
2005 protected function assertBuildSubstringParams( $startPosition, $length ) {
2006 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2007 throw new InvalidArgumentException(
2008 '$startPosition must be a positive integer'
2011 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2012 throw new InvalidArgumentException(
2013 '$length must be null or an integer greater than or equal to 0'
2018 public function buildStringCast( $field ) {
2022 public function buildIntegerCast( $field ) {
2023 return 'CAST( ' . $field . ' AS INTEGER )';
2026 public function buildSelectSubquery(
2027 $table, $vars, $conds = '', $fname = __METHOD__
,
2028 $options = [], $join_conds = []
2030 return new Subquery(
2031 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2035 public function databasesAreIndependent() {
2039 public function selectDB( $db ) {
2040 # Stub. Shouldn't cause serious problems if it's not overridden, but
2041 # if your database engine supports a concept similar to MySQL's
2042 # databases you may as well.
2043 $this->dbName
= $db;
2048 public function getDBname() {
2049 return $this->dbName
;
2052 public function getServer() {
2053 return $this->server
;
2056 public function tableName( $name, $format = 'quoted' ) {
2057 if ( $name instanceof Subquery
) {
2058 throw new DBUnexpectedError(
2060 __METHOD__
. ': got Subquery instance when expecting a string.'
2064 # Skip the entire process when we have a string quoted on both ends.
2065 # Note that we check the end so that we will still quote any use of
2066 # use of `database`.table. But won't break things if someone wants
2067 # to query a database table with a dot in the name.
2068 if ( $this->isQuotedIdentifier( $name ) ) {
2072 # Lets test for any bits of text that should never show up in a table
2073 # name. Basically anything like JOIN or ON which are actually part of
2074 # SQL queries, but may end up inside of the table value to combine
2075 # sql. Such as how the API is doing.
2076 # Note that we use a whitespace test rather than a \b test to avoid
2077 # any remote case where a word like on may be inside of a table name
2078 # surrounded by symbols which may be considered word breaks.
2079 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2080 $this->queryLogger
->warning(
2081 __METHOD__
. ": use of subqueries is not supported this way.",
2082 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2088 # Split database and table into proper variables.
2089 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2091 # Quote $table and apply the prefix if not quoted.
2092 # $tableName might be empty if this is called from Database::replaceVars()
2093 $tableName = "{$prefix}{$table}";
2094 if ( $format === 'quoted'
2095 && !$this->isQuotedIdentifier( $tableName )
2096 && $tableName !== ''
2098 $tableName = $this->addIdentifierQuotes( $tableName );
2101 # Quote $schema and $database and merge them with the table name if needed
2102 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2103 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2109 * Get the table components needed for a query given the currently selected database
2111 * @param string $name Table name in the form of db.schema.table, db.table, or table
2112 * @return array (DB name or "" for default, schema name, table prefix, table name)
2114 protected function qualifiedTableComponents( $name ) {
2115 # We reverse the explode so that database.table and table both output the correct table.
2116 $dbDetails = explode( '.', $name, 3 );
2117 if ( count( $dbDetails ) == 3 ) {
2118 list( $database, $schema, $table ) = $dbDetails;
2119 # We don't want any prefix added in this case
2121 } elseif ( count( $dbDetails ) == 2 ) {
2122 list( $database, $table ) = $dbDetails;
2123 # We don't want any prefix added in this case
2125 # In dbs that support it, $database may actually be the schema
2126 # but that doesn't affect any of the functionality here
2129 list( $table ) = $dbDetails;
2130 if ( isset( $this->tableAliases
[$table] ) ) {
2131 $database = $this->tableAliases
[$table]['dbname'];
2132 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2133 ?
$this->tableAliases
[$table]['schema']
2135 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2136 ?
$this->tableAliases
[$table]['prefix']
2137 : $this->tablePrefix
;
2140 $schema = $this->schema
; # Default schema
2141 $prefix = $this->tablePrefix
; # Default prefix
2145 return [ $database, $schema, $prefix, $table ];
2149 * @param string|null $namespace Database or schema
2150 * @param string $relation Name of table, view, sequence, etc...
2151 * @param string $format One of (raw, quoted)
2152 * @return string Relation name with quoted and merged $namespace as needed
2154 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2155 if ( strlen( $namespace ) ) {
2156 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2157 $namespace = $this->addIdentifierQuotes( $namespace );
2159 $relation = $namespace . '.' . $relation;
2165 public function tableNames() {
2166 $inArray = func_get_args();
2169 foreach ( $inArray as $name ) {
2170 $retVal[$name] = $this->tableName( $name );
2176 public function tableNamesN() {
2177 $inArray = func_get_args();
2180 foreach ( $inArray as $name ) {
2181 $retVal[] = $this->tableName( $name );
2188 * Get an aliased table name
2190 * This returns strings like "tableName AS newTableName" for aliased tables
2191 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2193 * @see Database::tableName()
2194 * @param string|Subquery $table Table name or object with a 'sql' field
2195 * @param string|bool $alias Table alias (optional)
2196 * @return string SQL name for aliased table. Will not alias a table to its own name
2198 protected function tableNameWithAlias( $table, $alias = false ) {
2199 if ( is_string( $table ) ) {
2200 $quotedTable = $this->tableName( $table );
2201 } elseif ( $table instanceof Subquery
) {
2202 $quotedTable = (string)$table;
2204 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2207 if ( !strlen( $alias ) ||
$alias === $table ) {
2208 if ( $table instanceof Subquery
) {
2209 throw new InvalidArgumentException( "Subquery table missing alias." );
2212 return $quotedTable;
2214 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2219 * Gets an array of aliased table names
2221 * @param array $tables [ [alias] => table ]
2222 * @return string[] See tableNameWithAlias()
2224 protected function tableNamesWithAlias( $tables ) {
2226 foreach ( $tables as $alias => $table ) {
2227 if ( is_numeric( $alias ) ) {
2230 $retval[] = $this->tableNameWithAlias( $table, $alias );
2237 * Get an aliased field name
2238 * e.g. fieldName AS newFieldName
2240 * @param string $name Field name
2241 * @param string|bool $alias Alias (optional)
2242 * @return string SQL name for aliased field. Will not alias a field to its own name
2244 protected function fieldNameWithAlias( $name, $alias = false ) {
2245 if ( !$alias ||
(string)$alias === (string)$name ) {
2248 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2253 * Gets an array of aliased field names
2255 * @param array $fields [ [alias] => field ]
2256 * @return string[] See fieldNameWithAlias()
2258 protected function fieldNamesWithAlias( $fields ) {
2260 foreach ( $fields as $alias => $field ) {
2261 if ( is_numeric( $alias ) ) {
2264 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2271 * Get the aliased table name clause for a FROM clause
2272 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2274 * @param array $tables ( [alias] => table )
2275 * @param array $use_index Same as for select()
2276 * @param array $ignore_index Same as for select()
2277 * @param array $join_conds Same as for select()
2280 protected function tableNamesWithIndexClauseOrJOIN(
2281 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2285 $use_index = (array)$use_index;
2286 $ignore_index = (array)$ignore_index;
2287 $join_conds = (array)$join_conds;
2289 foreach ( $tables as $alias => $table ) {
2290 if ( !is_string( $alias ) ) {
2291 // No alias? Set it equal to the table name
2295 if ( is_array( $table ) ) {
2296 // A parenthesized group
2297 if ( count( $table ) > 1 ) {
2298 $joinedTable = '(' .
2299 $this->tableNamesWithIndexClauseOrJOIN(
2300 $table, $use_index, $ignore_index, $join_conds ) . ')';
2303 $innerTable = reset( $table );
2304 $innerAlias = key( $table );
2305 $joinedTable = $this->tableNameWithAlias(
2307 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2311 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2314 // Is there a JOIN clause for this table?
2315 if ( isset( $join_conds[$alias] ) ) {
2316 list( $joinType, $conds ) = $join_conds[$alias];
2317 $tableClause = $joinType;
2318 $tableClause .= ' ' . $joinedTable;
2319 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2320 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2322 $tableClause .= ' ' . $use;
2325 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2326 $ignore = $this->ignoreIndexClause(
2327 implode( ',', (array)$ignore_index[$alias] ) );
2328 if ( $ignore != '' ) {
2329 $tableClause .= ' ' . $ignore;
2332 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2334 $tableClause .= ' ON (' . $on . ')';
2337 $retJOIN[] = $tableClause;
2338 } elseif ( isset( $use_index[$alias] ) ) {
2339 // Is there an INDEX clause for this table?
2340 $tableClause = $joinedTable;
2341 $tableClause .= ' ' . $this->useIndexClause(
2342 implode( ',', (array)$use_index[$alias] )
2345 $ret[] = $tableClause;
2346 } elseif ( isset( $ignore_index[$alias] ) ) {
2347 // Is there an INDEX clause for this table?
2348 $tableClause = $joinedTable;
2349 $tableClause .= ' ' . $this->ignoreIndexClause(
2350 implode( ',', (array)$ignore_index[$alias] )
2353 $ret[] = $tableClause;
2355 $tableClause = $joinedTable;
2357 $ret[] = $tableClause;
2361 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2362 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2363 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2365 // Compile our final table clause
2366 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2370 * Allows for index remapping in queries where this is not consistent across DBMS
2372 * @param string $index
2375 protected function indexName( $index ) {
2376 return isset( $this->indexAliases
[$index] )
2377 ?
$this->indexAliases
[$index]
2381 public function addQuotes( $s ) {
2382 if ( $s instanceof Blob
) {
2385 if ( $s === null ) {
2387 } elseif ( is_bool( $s ) ) {
2390 # This will also quote numeric values. This should be harmless,
2391 # and protects against weird problems that occur when they really
2392 # _are_ strings such as article titles and string->number->string
2393 # conversion is not 1:1.
2394 return "'" . $this->strencode( $s ) . "'";
2399 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2400 * MySQL uses `backticks` while basically everything else uses double quotes.
2401 * Since MySQL is the odd one out here the double quotes are our generic
2402 * and we implement backticks in DatabaseMysqlBase.
2407 public function addIdentifierQuotes( $s ) {
2408 return '"' . str_replace( '"', '""', $s ) . '"';
2412 * Returns if the given identifier looks quoted or not according to
2413 * the database convention for quoting identifiers .
2415 * @note Do not use this to determine if untrusted input is safe.
2416 * A malicious user can trick this function.
2417 * @param string $name
2420 public function isQuotedIdentifier( $name ) {
2421 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2426 * @param string $escapeChar
2429 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2430 return str_replace( [ $escapeChar, '%', '_' ],
2431 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2435 public function buildLike() {
2436 $params = func_get_args();
2438 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2439 $params = $params[0];
2444 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2445 // may escape backslashes, creating problems of double escaping. The `
2446 // character has good cross-DBMS compatibility, avoiding special operators
2447 // in MS SQL like ^ and %
2450 foreach ( $params as $value ) {
2451 if ( $value instanceof LikeMatch
) {
2452 $s .= $value->toString();
2454 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2459 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2462 public function anyChar() {
2463 return new LikeMatch( '_' );
2466 public function anyString() {
2467 return new LikeMatch( '%' );
2470 public function nextSequenceValue( $seqName ) {
2475 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2476 * is only needed because a) MySQL must be as efficient as possible due to
2477 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2478 * which index to pick. Anyway, other databases might have different
2479 * indexes on a given table. So don't bother overriding this unless you're
2481 * @param string $index
2484 public function useIndexClause( $index ) {
2489 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2490 * is only needed because a) MySQL must be as efficient as possible due to
2491 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2492 * which index to pick. Anyway, other databases might have different
2493 * indexes on a given table. So don't bother overriding this unless you're
2495 * @param string $index
2498 public function ignoreIndexClause( $index ) {
2502 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2503 if ( count( $rows ) == 0 ) {
2508 if ( !is_array( reset( $rows ) ) ) {
2513 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2514 $affectedRowCount = 0;
2515 foreach ( $rows as $row ) {
2516 // Delete rows which collide with this one
2517 $indexWhereClauses = [];
2518 foreach ( $uniqueIndexes as $index ) {
2519 $indexColumns = (array)$index;
2520 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2521 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2522 throw new DBUnexpectedError(
2524 'New record does not provide all values for unique key (' .
2525 implode( ', ', $indexColumns ) . ')'
2527 } elseif ( in_array( null, $indexRowValues, true ) ) {
2528 throw new DBUnexpectedError(
2530 'New record has a null value for unique key (' .
2531 implode( ', ', $indexColumns ) . ')'
2534 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2537 if ( $indexWhereClauses ) {
2538 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2539 $affectedRowCount +
= $this->affectedRows();
2542 // Now insert the row
2543 $this->insert( $table, $row, $fname );
2544 $affectedRowCount +
= $this->affectedRows();
2546 $this->endAtomic( $fname );
2547 $this->affectedRowCount
= $affectedRowCount;
2548 } catch ( Exception
$e ) {
2549 $this->cancelAtomic( $fname );
2555 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2558 * @param string $table Table name
2559 * @param array|string $rows Row(s) to insert
2560 * @param string $fname Caller function name
2562 * @return ResultWrapper
2564 protected function nativeReplace( $table, $rows, $fname ) {
2565 $table = $this->tableName( $table );
2568 if ( !is_array( reset( $rows ) ) ) {
2572 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2575 foreach ( $rows as $row ) {
2582 $sql .= '(' . $this->makeList( $row ) . ')';
2585 return $this->query( $sql, $fname );
2588 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2591 if ( !count( $rows ) ) {
2592 return true; // nothing to do
2595 if ( !is_array( reset( $rows ) ) ) {
2599 if ( count( $uniqueIndexes ) ) {
2600 $clauses = []; // list WHERE clauses that each identify a single row
2601 foreach ( $rows as $row ) {
2602 foreach ( $uniqueIndexes as $index ) {
2603 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2604 $rowKey = []; // unique key to this row
2605 foreach ( $index as $column ) {
2606 $rowKey[$column] = $row[$column];
2608 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2611 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2616 $affectedRowCount = 0;
2618 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2619 # Update any existing conflicting row(s)
2620 if ( $where !== false ) {
2621 $ok = $this->update( $table, $set, $where, $fname );
2622 $affectedRowCount +
= $this->affectedRows();
2626 # Now insert any non-conflicting row(s)
2627 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2628 $affectedRowCount +
= $this->affectedRows();
2629 $this->endAtomic( $fname );
2630 $this->affectedRowCount
= $affectedRowCount;
2631 } catch ( Exception
$e ) {
2632 $this->cancelAtomic( $fname );
2639 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2643 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2646 $delTable = $this->tableName( $delTable );
2647 $joinTable = $this->tableName( $joinTable );
2648 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2649 if ( $conds != '*' ) {
2650 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2654 $this->query( $sql, $fname );
2657 public function textFieldSize( $table, $field ) {
2658 $table = $this->tableName( $table );
2659 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2660 $res = $this->query( $sql, __METHOD__
);
2661 $row = $this->fetchObject( $res );
2665 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2674 public function delete( $table, $conds, $fname = __METHOD__
) {
2676 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2679 $table = $this->tableName( $table );
2680 $sql = "DELETE FROM $table";
2682 if ( $conds != '*' ) {
2683 if ( is_array( $conds ) ) {
2684 $conds = $this->makeList( $conds, self
::LIST_AND
);
2686 $sql .= ' WHERE ' . $conds;
2689 return $this->query( $sql, $fname );
2692 final public function insertSelect(
2693 $destTable, $srcTable, $varMap, $conds,
2694 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2696 static $hints = [ 'NO_AUTO_COLUMNS' ];
2698 $insertOptions = (array)$insertOptions;
2699 $selectOptions = (array)$selectOptions;
2701 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2702 // For massive migrations with downtime, we don't want to select everything
2703 // into memory and OOM, so do all this native on the server side if possible.
2704 return $this->nativeInsertSelect(
2710 array_diff( $insertOptions, $hints ),
2716 return $this->nonNativeInsertSelect(
2722 array_diff( $insertOptions, $hints ),
2729 * @param array $insertOptions INSERT options
2730 * @param array $selectOptions SELECT options
2731 * @return bool Whether an INSERT SELECT with these options will be replication safe
2734 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2739 * Implementation of insertSelect() based on select() and insert()
2741 * @see IDatabase::insertSelect()
2743 * @param string $destTable
2744 * @param string|array $srcTable
2745 * @param array $varMap
2746 * @param array $conds
2747 * @param string $fname
2748 * @param array $insertOptions
2749 * @param array $selectOptions
2750 * @param array $selectJoinConds
2753 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2754 $fname = __METHOD__
,
2755 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2757 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2758 // on only the master (without needing row-based-replication). It also makes it easy to
2759 // know how big the INSERT is going to be.
2761 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2762 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2764 $selectOptions[] = 'FOR UPDATE';
2765 $res = $this->select(
2766 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2773 $affectedRowCount = 0;
2774 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2777 foreach ( $res as $row ) {
2778 $rows[] = (array)$row;
2780 // Avoid inserts that are too huge
2781 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2782 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2786 $affectedRowCount +
= $this->affectedRows();
2790 if ( $rows && $ok ) {
2791 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2793 $affectedRowCount +
= $this->affectedRows();
2797 $this->endAtomic( $fname );
2798 $this->affectedRowCount
= $affectedRowCount;
2800 $this->cancelAtomic( $fname );
2803 } catch ( Exception
$e ) {
2804 $this->cancelAtomic( $fname );
2810 * Native server-side implementation of insertSelect() for situations where
2811 * we don't want to select everything into memory
2813 * @see IDatabase::insertSelect()
2814 * @param string $destTable
2815 * @param string|array $srcTable
2816 * @param array $varMap
2817 * @param array $conds
2818 * @param string $fname
2819 * @param array $insertOptions
2820 * @param array $selectOptions
2821 * @param array $selectJoinConds
2824 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2825 $fname = __METHOD__
,
2826 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2828 $destTable = $this->tableName( $destTable );
2830 if ( !is_array( $insertOptions ) ) {
2831 $insertOptions = [ $insertOptions ];
2834 $insertOptions = $this->makeInsertOptions( $insertOptions );
2836 $selectSql = $this->selectSQLText(
2838 array_values( $varMap ),
2845 $sql = "INSERT $insertOptions" .
2846 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2849 return $this->query( $sql, $fname );
2853 * Construct a LIMIT query with optional offset. This is used for query
2854 * pages. The SQL should be adjusted so that only the first $limit rows
2855 * are returned. If $offset is provided as well, then the first $offset
2856 * rows should be discarded, and the next $limit rows should be returned.
2857 * If the result of the query is not ordered, then the rows to be returned
2858 * are theoretically arbitrary.
2860 * $sql is expected to be a SELECT, if that makes a difference.
2862 * The version provided by default works in MySQL and SQLite. It will very
2863 * likely need to be overridden for most other DBMSes.
2865 * @param string $sql SQL query we will append the limit too
2866 * @param int $limit The SQL limit
2867 * @param int|bool $offset The SQL offset (default false)
2868 * @throws DBUnexpectedError
2871 public function limitResult( $sql, $limit, $offset = false ) {
2872 if ( !is_numeric( $limit ) ) {
2873 throw new DBUnexpectedError( $this,
2874 "Invalid non-numeric limit passed to limitResult()\n" );
2877 return "$sql LIMIT "
2878 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2882 public function unionSupportsOrderAndLimit() {
2883 return true; // True for almost every DB supported
2886 public function unionQueries( $sqls, $all ) {
2887 $glue = $all ?
') UNION ALL (' : ') UNION (';
2889 return '(' . implode( $glue, $sqls ) . ')';
2892 public function unionConditionPermutations(
2893 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2894 $options = [], $join_conds = []
2896 // First, build the Cartesian product of $permute_conds
2898 foreach ( $permute_conds as $field => $values ) {
2900 // Skip empty $values
2903 $values = array_unique( $values ); // For sanity
2905 foreach ( $conds as $cond ) {
2906 foreach ( $values as $value ) {
2907 $cond[$field] = $value;
2908 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2914 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2916 // If there's just one condition and no subordering, hand off to
2917 // selectSQLText directly.
2918 if ( count( $conds ) === 1 &&
2919 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2921 return $this->selectSQLText(
2922 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2926 // Otherwise, we need to pull out the order and limit to apply after
2927 // the union. Then build the SQL queries for each set of conditions in
2928 // $conds. Then union them together (using UNION ALL, because the
2929 // product *should* already be distinct).
2930 $orderBy = $this->makeOrderBy( $options );
2931 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2932 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2933 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2934 if ( !$this->unionSupportsOrderAndLimit() ) {
2935 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2937 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2938 $options['ORDER BY'] = $options['INNER ORDER BY'];
2940 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2941 // We need to increase the limit by the offset rather than
2942 // using the offset directly, otherwise it'll skip incorrectly
2943 // in the subqueries.
2944 $options['LIMIT'] = $limit +
$offset;
2945 unset( $options['OFFSET'] );
2950 foreach ( $conds as $cond ) {
2951 $sqls[] = $this->selectSQLText(
2952 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2955 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2956 if ( $limit !== null ) {
2957 $sql = $this->limitResult( $sql, $limit, $offset );
2963 public function conditional( $cond, $trueVal, $falseVal ) {
2964 if ( is_array( $cond ) ) {
2965 $cond = $this->makeList( $cond, self
::LIST_AND
);
2968 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2971 public function strreplace( $orig, $old, $new ) {
2972 return "REPLACE({$orig}, {$old}, {$new})";
2975 public function getServerUptime() {
2979 public function wasDeadlock() {
2983 public function wasLockTimeout() {
2987 public function wasConnectionLoss() {
2988 return $this->wasConnectionError( $this->lastErrno() );
2991 public function wasReadOnlyError() {
2995 public function wasErrorReissuable() {
2997 $this->wasDeadlock() ||
2998 $this->wasLockTimeout() ||
2999 $this->wasConnectionLoss()
3004 * Do not use this method outside of Database/DBError classes
3006 * @param int|string $errno
3007 * @return bool Whether the given query error was a connection drop
3009 public function wasConnectionError( $errno ) {
3013 public function deadlockLoop() {
3014 $args = func_get_args();
3015 $function = array_shift( $args );
3016 $tries = self
::DEADLOCK_TRIES
;
3018 $this->begin( __METHOD__
);
3021 /** @var Exception $e */
3025 $retVal = call_user_func_array( $function, $args );
3027 } catch ( DBQueryError
$e ) {
3028 if ( $this->wasDeadlock() ) {
3029 // Retry after a randomized delay
3030 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3032 // Throw the error back up
3036 } while ( --$tries > 0 );
3038 if ( $tries <= 0 ) {
3039 // Too many deadlocks; give up
3040 $this->rollback( __METHOD__
);
3043 $this->commit( __METHOD__
);
3049 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3050 # Real waits are implemented in the subclass.
3054 public function getReplicaPos() {
3059 public function getMasterPos() {
3064 public function serverIsReadOnly() {
3068 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3069 if ( !$this->trxLevel
) {
3070 throw new DBUnexpectedError( $this, "No transaction is active." );
3072 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3075 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3076 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3077 if ( !$this->trxLevel
) {
3078 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3082 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3083 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
3084 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3085 // an implicit commit of all peer databases. This is true even if a transaction has
3086 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3087 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3089 // No transaction is active nor will start implicitly, so make one for this callback
3090 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3092 call_user_func( $callback );
3093 $this->endAtomic( __METHOD__
);
3094 } catch ( Exception
$e ) {
3095 $this->cancelAtomic( __METHOD__
);
3101 final public function setTransactionListener( $name, callable
$callback = null ) {
3103 $this->trxRecurringCallbacks
[$name] = $callback;
3105 unset( $this->trxRecurringCallbacks
[$name] );
3110 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3112 * This method should not be used outside of Database/LoadBalancer
3114 * @param bool $suppress
3117 final public function setTrxEndCallbackSuppression( $suppress ) {
3118 $this->trxEndCallbacksSuppressed
= $suppress;
3122 * Actually run and consume any "on transaction idle/resolution" callbacks.
3124 * This method should not be used outside of Database/LoadBalancer
3126 * @param int $trigger IDatabase::TRIGGER_* constant
3130 public function runOnTransactionIdleCallbacks( $trigger ) {
3131 if ( $this->trxEndCallbacksSuppressed
) {
3135 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3136 /** @var Exception $e */
3137 $e = null; // first exception
3138 do { // callbacks may add callbacks :)
3139 $callbacks = array_merge(
3140 $this->trxIdleCallbacks
,
3141 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3143 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3144 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3145 foreach ( $callbacks as $callback ) {
3147 list( $phpCallback ) = $callback;
3148 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3149 call_user_func_array( $phpCallback, [ $trigger ] );
3151 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3153 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3155 } catch ( Exception
$ex ) {
3156 call_user_func( $this->errorLogger
, $ex );
3158 // Some callbacks may use startAtomic/endAtomic, so make sure
3159 // their transactions are ended so other callbacks don't fail
3160 if ( $this->trxLevel() ) {
3161 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3165 } while ( count( $this->trxIdleCallbacks
) );
3167 if ( $e instanceof Exception
) {
3168 throw $e; // re-throw any first exception
3173 * Actually run and consume any "on transaction pre-commit" callbacks.
3175 * This method should not be used outside of Database/LoadBalancer
3180 public function runOnTransactionPreCommitCallbacks() {
3181 $e = null; // first exception
3182 do { // callbacks may add callbacks :)
3183 $callbacks = $this->trxPreCommitCallbacks
;
3184 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3185 foreach ( $callbacks as $callback ) {
3187 list( $phpCallback ) = $callback;
3188 call_user_func( $phpCallback );
3189 } catch ( Exception
$ex ) {
3190 call_user_func( $this->errorLogger
, $ex );
3194 } while ( count( $this->trxPreCommitCallbacks
) );
3196 if ( $e instanceof Exception
) {
3197 throw $e; // re-throw any first exception
3202 * Actually run any "transaction listener" callbacks.
3204 * This method should not be used outside of Database/LoadBalancer
3206 * @param int $trigger IDatabase::TRIGGER_* constant
3210 public function runTransactionListenerCallbacks( $trigger ) {
3211 if ( $this->trxEndCallbacksSuppressed
) {
3215 /** @var Exception $e */
3216 $e = null; // first exception
3218 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3220 $phpCallback( $trigger, $this );
3221 } catch ( Exception
$ex ) {
3222 call_user_func( $this->errorLogger
, $ex );
3227 if ( $e instanceof Exception
) {
3228 throw $e; // re-throw any first exception
3233 * Create a savepoint
3235 * This is used internally to implement atomic sections. It should not be
3239 * @param string $identifier Identifier for the savepoint
3240 * @param string $fname Calling function name
3242 protected function doSavepoint( $identifier, $fname ) {
3243 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3247 * Release a savepoint
3249 * This is used internally to implement atomic sections. It should not be
3253 * @param string $identifier Identifier for the savepoint
3254 * @param string $fname Calling function name
3256 protected function doReleaseSavepoint( $identifier, $fname ) {
3257 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3261 * Rollback to a savepoint
3263 * This is used internally to implement atomic sections. It should not be
3267 * @param string $identifier Identifier for the savepoint
3268 * @param string $fname Calling function name
3270 protected function doRollbackToSavepoint( $identifier, $fname ) {
3271 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3274 final public function startAtomic(
3275 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3277 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3278 if ( !$this->trxLevel
) {
3279 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3280 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3281 // in all changes being in one transaction to keep requests transactional.
3282 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3283 $this->trxAutomaticAtomic
= true;
3285 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3286 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3287 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3288 $this->queryLogger
->warning(
3289 'There have been an excessively large number of atomic sections in a transaction'
3290 . " started by $this->trxFname, reusing IDs (at $fname)",
3291 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3293 $this->trxAtomicCounter
= 0;
3294 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3296 $this->doSavepoint( $savepointId, $fname );
3299 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3302 final public function endAtomic( $fname = __METHOD__
) {
3303 if ( !$this->trxLevel
) {
3304 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3307 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3308 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3309 if ( $savedFname !== $fname ) {
3310 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3313 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3314 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3315 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3316 $this->doReleaseSavepoint( $savepointId, $fname );
3320 final public function cancelAtomic( $fname = __METHOD__
) {
3321 if ( !$this->trxLevel
) {
3322 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3325 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3326 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3327 if ( $savedFname !== $fname ) {
3328 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3330 if ( !$savepointId ) {
3331 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3334 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3335 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3336 } elseif ( $savepointId !== 'n/a' ) {
3337 $this->doRollbackToSavepoint( $savepointId, $fname );
3340 $this->affectedRowCount
= 0; // for the sake of consistency
3343 final public function doAtomicSection( $fname, callable
$callback ) {
3344 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3346 $res = call_user_func_array( $callback, [ $this, $fname ] );
3347 } catch ( Exception
$e ) {
3348 $this->cancelAtomic( $fname );
3351 $this->endAtomic( $fname );
3356 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3357 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3358 if ( $this->trxLevel
) {
3359 if ( $this->trxAtomicLevels
) {
3360 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3361 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3363 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3364 throw new DBUnexpectedError( $this, $msg );
3365 } elseif ( !$this->trxAutomatic
) {
3366 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3367 throw new DBUnexpectedError( $this, $msg );
3369 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3370 throw new DBUnexpectedError( $this, $msg );
3372 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3373 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3374 throw new DBUnexpectedError( $this, $msg );
3377 // Avoid fatals if close() was called
3378 $this->assertOpen();
3380 $this->doBegin( $fname );
3381 $this->trxAtomicCounter
= 0;
3382 $this->trxTimestamp
= microtime( true );
3383 $this->trxFname
= $fname;
3384 $this->trxDoneWrites
= false;
3385 $this->trxAutomaticAtomic
= false;
3386 $this->trxAtomicLevels
= [];
3387 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3388 $this->trxWriteDuration
= 0.0;
3389 $this->trxWriteQueryCount
= 0;
3390 $this->trxWriteAffectedRows
= 0;
3391 $this->trxWriteAdjDuration
= 0.0;
3392 $this->trxWriteAdjQueryCount
= 0;
3393 $this->trxWriteCallers
= [];
3394 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3395 // Get an estimate of the replication lag before any such queries.
3396 $this->trxReplicaLag
= $this->getApproximateLagStatus()['lag'];
3397 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3398 // caller will think its OK to muck around with the transaction just because startAtomic()
3399 // has not yet completed (e.g. setting trxAtomicLevels).
3400 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3404 * Issues the BEGIN command to the database server.
3406 * @see Database::begin()
3407 * @param string $fname
3409 protected function doBegin( $fname ) {
3410 $this->query( 'BEGIN', $fname );
3411 $this->trxLevel
= 1;
3414 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3415 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3416 // There are still atomic sections open. This cannot be ignored
3417 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3418 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3420 throw new DBUnexpectedError(
3422 "$fname: Got COMMIT while atomic sections $levels are still open."
3426 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3427 if ( !$this->trxLevel
) {
3428 return; // nothing to do
3429 } elseif ( !$this->trxAutomatic
) {
3430 throw new DBUnexpectedError(
3432 "$fname: Flushing an explicit transaction, getting out of sync."
3436 if ( !$this->trxLevel
) {
3437 $this->queryLogger
->error(
3438 "$fname: No transaction to commit, something got out of sync." );
3439 return; // nothing to do
3440 } elseif ( $this->trxAutomatic
) {
3441 throw new DBUnexpectedError(
3443 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3448 // Avoid fatals if close() was called
3449 $this->assertOpen();
3451 $this->runOnTransactionPreCommitCallbacks();
3452 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3453 $this->doCommit( $fname );
3454 if ( $this->trxDoneWrites
) {
3455 $this->lastWriteTime
= microtime( true );
3456 $this->trxProfiler
->transactionWritingOut(
3461 $this->trxWriteAffectedRows
3465 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3466 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3470 * Issues the COMMIT command to the database server.
3472 * @see Database::commit()
3473 * @param string $fname
3475 protected function doCommit( $fname ) {
3476 if ( $this->trxLevel
) {
3477 $this->query( 'COMMIT', $fname );
3478 $this->trxLevel
= 0;
3482 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3483 $trxActive = $this->trxLevel
;
3485 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3486 if ( $this->getFlag( self
::DBO_TRX
) ) {
3487 throw new DBUnexpectedError(
3489 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3495 // Avoid fatals if close() was called
3496 $this->assertOpen();
3498 $this->doRollback( $fname );
3499 $this->trxAtomicLevels
= [];
3500 if ( $this->trxDoneWrites
) {
3501 $this->trxProfiler
->transactionWritingOut(
3509 // Clear any commit-dependant callbacks. They might even be present
3510 // only due to transaction rounds, with no SQL transaction being active
3511 $this->trxIdleCallbacks
= [];
3512 $this->trxPreCommitCallbacks
= [];
3516 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3517 } catch ( Exception
$e ) {
3518 // already logged; finish and let LoadBalancer move on during mass-rollback
3521 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3522 } catch ( Exception
$e ) {
3523 // already logged; let LoadBalancer move on during mass-rollback
3526 $this->affectedRowCount
= 0; // for the sake of consistency
3531 * Issues the ROLLBACK command to the database server.
3533 * @see Database::rollback()
3534 * @param string $fname
3536 protected function doRollback( $fname ) {
3537 if ( $this->trxLevel
) {
3538 # Disconnects cause rollback anyway, so ignore those errors
3539 $ignoreErrors = true;
3540 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3541 $this->trxLevel
= 0;
3545 public function flushSnapshot( $fname = __METHOD__
) {
3546 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3547 // This only flushes transactions to clear snapshots, not to write data
3548 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3549 throw new DBUnexpectedError(
3551 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3555 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3558 public function explicitTrxActive() {
3559 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3562 public function duplicateTableStructure(
3563 $oldName, $newName, $temporary = false, $fname = __METHOD__
3565 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3568 public function listTables( $prefix = null, $fname = __METHOD__
) {
3569 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3572 public function listViews( $prefix = null, $fname = __METHOD__
) {
3573 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3576 public function timestamp( $ts = 0 ) {
3577 $t = new ConvertibleTimestamp( $ts );
3578 // Let errors bubble up to avoid putting garbage in the DB
3579 return $t->getTimestamp( TS_MW
);
3582 public function timestampOrNull( $ts = null ) {
3583 if ( is_null( $ts ) ) {
3586 return $this->timestamp( $ts );
3590 public function affectedRows() {
3591 return ( $this->affectedRowCount
=== null )
3592 ?
$this->fetchAffectedRowCount() // default to driver value
3593 : $this->affectedRowCount
;
3597 * @return int Number of retrieved rows according to the driver
3599 abstract protected function fetchAffectedRowCount();
3602 * Take the result from a query, and wrap it in a ResultWrapper if
3603 * necessary. Boolean values are passed through as is, to indicate success
3604 * of write queries or failure.
3606 * Once upon a time, Database::query() returned a bare MySQL result
3607 * resource, and it was necessary to call this function to convert it to
3608 * a wrapper. Nowadays, raw database objects are never exposed to external
3609 * callers, so this is unnecessary in external code.
3611 * @param bool|ResultWrapper|resource|object $result
3612 * @return bool|ResultWrapper
3614 protected function resultObject( $result ) {
3617 } elseif ( $result instanceof ResultWrapper
) {
3619 } elseif ( $result === true ) {
3620 // Successful write query
3623 return new ResultWrapper( $this, $result );
3627 public function ping( &$rtt = null ) {
3628 // Avoid hitting the server if it was hit recently
3629 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3630 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3631 $rtt = $this->rttEstimate
;
3632 return true; // don't care about $rtt
3636 // This will reconnect if possible or return false if not
3637 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3638 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3639 $this->restoreFlags( self
::RESTORE_PRIOR
);
3642 $rtt = $this->rttEstimate
;
3649 * Close existing database connection and open a new connection
3651 * @return bool True if new connection is opened successfully, false if error
3653 protected function reconnect() {
3654 $this->closeConnection();
3655 $this->opened
= false;
3656 $this->conn
= false;
3658 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3659 $this->lastPing
= microtime( true );
3661 } catch ( DBConnectionError
$e ) {
3668 public function getSessionLagStatus() {
3669 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3673 * Get the replica DB lag when the current transaction started
3675 * This is useful when transactions might use snapshot isolation
3676 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3677 * is this lag plus transaction duration. If they don't, it is still
3678 * safe to be pessimistic. This returns null if there is no transaction.
3680 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3683 final protected function getTransactionLagStatus() {
3684 return $this->trxLevel
3685 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3690 * Get a replica DB lag estimate for this server
3692 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3695 protected function getApproximateLagStatus() {
3697 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3698 'since' => microtime( true )
3703 * Merge the result of getSessionLagStatus() for several DBs
3704 * using the most pessimistic values to estimate the lag of
3705 * any data derived from them in combination
3707 * This is information is useful for caching modules
3709 * @see WANObjectCache::set()
3710 * @see WANObjectCache::getWithSetCallback()
3712 * @param IDatabase $db1
3713 * @param IDatabase $db2 [optional]
3714 * @return array Map of values:
3715 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3716 * - since: oldest UNIX timestamp of any of the DB lag estimates
3717 * - pending: whether any of the DBs have uncommitted changes
3721 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3722 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3723 foreach ( func_get_args() as $db ) {
3724 /** @var IDatabase $db */
3725 $status = $db->getSessionLagStatus();
3726 if ( $status['lag'] === false ) {
3727 $res['lag'] = false;
3728 } elseif ( $res['lag'] !== false ) {
3729 $res['lag'] = max( $res['lag'], $status['lag'] );
3731 $res['since'] = min( $res['since'], $status['since'] );
3732 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3738 public function getLag() {
3742 public function maxListLen() {
3746 public function encodeBlob( $b ) {
3750 public function decodeBlob( $b ) {
3751 if ( $b instanceof Blob
) {
3757 public function setSessionOptions( array $options ) {
3760 public function sourceFile(
3762 callable
$lineCallback = null,
3763 callable
$resultCallback = null,
3765 callable
$inputCallback = null
3767 Wikimedia\
suppressWarnings();
3768 $fp = fopen( $filename, 'r' );
3769 Wikimedia\restoreWarnings
();
3771 if ( false === $fp ) {
3772 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3776 $fname = __METHOD__
. "( $filename )";
3780 $error = $this->sourceStream(
3781 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3782 } catch ( Exception
$e ) {
3792 public function setSchemaVars( $vars ) {
3793 $this->schemaVars
= $vars;
3796 public function sourceStream(
3798 callable
$lineCallback = null,
3799 callable
$resultCallback = null,
3800 $fname = __METHOD__
,
3801 callable
$inputCallback = null
3803 $delimiterReset = new ScopedCallback(
3804 function ( $delimiter ) {
3805 $this->delimiter
= $delimiter;
3807 [ $this->delimiter
]
3811 while ( !feof( $fp ) ) {
3812 if ( $lineCallback ) {
3813 call_user_func( $lineCallback );
3816 $line = trim( fgets( $fp ) );
3818 if ( $line == '' ) {
3822 if ( '-' == $line[0] && '-' == $line[1] ) {
3830 $done = $this->streamStatementEnd( $cmd, $line );
3834 if ( $done ||
feof( $fp ) ) {
3835 $cmd = $this->replaceVars( $cmd );
3837 if ( $inputCallback ) {
3838 $callbackResult = call_user_func( $inputCallback, $cmd );
3840 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3841 $cmd = $callbackResult;
3846 $res = $this->query( $cmd, $fname );
3848 if ( $resultCallback ) {
3849 call_user_func( $resultCallback, $res, $this );
3852 if ( false === $res ) {
3853 $err = $this->lastError();
3855 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3862 ScopedCallback
::consume( $delimiterReset );
3867 * Called by sourceStream() to check if we've reached a statement end
3869 * @param string &$sql SQL assembled so far
3870 * @param string &$newLine New line about to be added to $sql
3871 * @return bool Whether $newLine contains end of the statement
3873 public function streamStatementEnd( &$sql, &$newLine ) {
3874 if ( $this->delimiter
) {
3876 $newLine = preg_replace(
3877 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3878 if ( $newLine != $prev ) {
3887 * Database independent variable replacement. Replaces a set of variables
3888 * in an SQL statement with their contents as given by $this->getSchemaVars().
3890 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3892 * - '{$var}' should be used for text and is passed through the database's
3894 * - `{$var}` should be used for identifiers (e.g. table and database names).
3895 * It is passed through the database's addIdentifierQuotes method which
3896 * can be overridden if the database uses something other than backticks.
3897 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3898 * database's tableName method.
3899 * - / *i* / passes the name that follows through the database's indexName method.
3900 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3901 * its use should be avoided. In 1.24 and older, string encoding was applied.
3903 * @param string $ins SQL statement to replace variables in
3904 * @return string The new SQL statement with variables replaced
3906 protected function replaceVars( $ins ) {
3907 $vars = $this->getSchemaVars();
3908 return preg_replace_callback(
3910 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3911 \'\{\$ (\w+) }\' | # 3. addQuotes
3912 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3913 /\*\$ (\w+) \*/ # 5. leave unencoded
3915 function ( $m ) use ( $vars ) {
3916 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3917 // check for both nonexistent keys *and* the empty string.
3918 if ( isset( $m[1] ) && $m[1] !== '' ) {
3919 if ( $m[1] === 'i' ) {
3920 return $this->indexName( $m[2] );
3922 return $this->tableName( $m[2] );
3924 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3925 return $this->addQuotes( $vars[$m[3]] );
3926 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3927 return $this->addIdentifierQuotes( $vars[$m[4]] );
3928 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3929 return $vars[$m[5]];
3939 * Get schema variables. If none have been set via setSchemaVars(), then
3940 * use some defaults from the current object.
3944 protected function getSchemaVars() {
3945 if ( $this->schemaVars
) {
3946 return $this->schemaVars
;
3948 return $this->getDefaultSchemaVars();
3953 * Get schema variables to use if none have been set via setSchemaVars().
3955 * Override this in derived classes to provide variables for tables.sql
3956 * and SQL patch files.
3960 protected function getDefaultSchemaVars() {
3964 public function lockIsFree( $lockName, $method ) {
3965 // RDBMs methods for checking named locks may or may not count this thread itself.
3966 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3967 // the behavior choosen by the interface for this method.
3968 return !isset( $this->namedLocksHeld
[$lockName] );
3971 public function lock( $lockName, $method, $timeout = 5 ) {
3972 $this->namedLocksHeld
[$lockName] = 1;
3977 public function unlock( $lockName, $method ) {
3978 unset( $this->namedLocksHeld
[$lockName] );
3983 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3984 if ( $this->writesOrCallbacksPending() ) {
3985 // This only flushes transactions to clear snapshots, not to write data
3986 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3987 throw new DBUnexpectedError(
3989 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3993 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3997 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3998 if ( $this->trxLevel() ) {
3999 // There is a good chance an exception was thrown, causing any early return
4000 // from the caller. Let any error handler get a chance to issue rollback().
4001 // If there isn't one, let the error bubble up and trigger server-side rollback.
4002 $this->onTransactionResolution(
4003 function () use ( $lockKey, $fname ) {
4004 $this->unlock( $lockKey, $fname );
4009 $this->unlock( $lockKey, $fname );
4013 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4018 public function namedLocksEnqueue() {
4022 public function tableLocksHaveTransactionScope() {
4026 final public function lockTables( array $read, array $write, $method ) {
4027 if ( $this->writesOrCallbacksPending() ) {
4028 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4031 if ( $this->tableLocksHaveTransactionScope() ) {
4032 $this->startAtomic( $method );
4035 return $this->doLockTables( $read, $write, $method );
4039 * Helper function for lockTables() that handles the actual table locking
4041 * @param array $read Array of tables to lock for read access
4042 * @param array $write Array of tables to lock for write access
4043 * @param string $method Name of caller
4046 protected function doLockTables( array $read, array $write, $method ) {
4050 final public function unlockTables( $method ) {
4051 if ( $this->tableLocksHaveTransactionScope() ) {
4052 $this->endAtomic( $method );
4054 return true; // locks released on COMMIT/ROLLBACK
4057 return $this->doUnlockTables( $method );
4061 * Helper function for unlockTables() that handles the actual table unlocking
4063 * @param string $method Name of caller
4066 protected function doUnlockTables( $method ) {
4072 * @param string $tableName
4073 * @param string $fName
4074 * @return bool|ResultWrapper
4077 public function dropTable( $tableName, $fName = __METHOD__
) {
4078 if ( !$this->tableExists( $tableName, $fName ) ) {
4081 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4083 return $this->query( $sql, $fName );
4086 public function getInfinity() {
4090 public function encodeExpiry( $expiry ) {
4091 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4092 ?
$this->getInfinity()
4093 : $this->timestamp( $expiry );
4096 public function decodeExpiry( $expiry, $format = TS_MW
) {
4097 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4101 return ConvertibleTimestamp
::convert( $format, $expiry );
4104 public function setBigSelects( $value = true ) {
4108 public function isReadOnly() {
4109 return ( $this->getReadOnlyReason() !== false );
4113 * @return string|bool Reason this DB is read-only or false if it is not
4115 protected function getReadOnlyReason() {
4116 $reason = $this->getLBInfo( 'readOnlyReason' );
4118 return is_string( $reason ) ?
$reason : false;
4121 public function setTableAliases( array $aliases ) {
4122 $this->tableAliases
= $aliases;
4125 public function setIndexAliases( array $aliases ) {
4126 $this->indexAliases
= $aliases;
4130 * Get the underlying binding connection handle
4132 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4133 * This catches broken callers than catch and ignore disconnection exceptions.
4134 * Unlike checking isOpen(), this is safe to call inside of open().
4137 * @throws DBUnexpectedError
4140 protected function getBindingHandle() {
4141 if ( !$this->conn
) {
4142 throw new DBUnexpectedError(
4144 'DB connection was already closed or the connection dropped.'
4155 public function __toString() {
4156 return (string)$this->conn
;
4160 * Make sure that copies do not share the same client binding handle
4161 * @throws DBConnectionError
4163 public function __clone() {
4164 $this->connLogger
->warning(
4165 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4166 ( new RuntimeException() )->getTraceAsString()
4169 if ( $this->isOpen() ) {
4170 // Open a new connection resource without messing with the old one
4171 $this->opened
= false;
4172 $this->conn
= false;
4173 $this->trxEndCallbacks
= []; // don't copy
4174 $this->handleSessionLoss(); // no trx or locks anymore
4175 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4176 $this->lastPing
= microtime( true );
4181 * Called by serialize. Throw an exception when DB connection is serialized.
4182 * This causes problems on some database engines because the connection is
4183 * not restored on unserialize.
4185 public function __sleep() {
4186 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4187 'the connection is not restored on wakeup.' );
4191 * Run a few simple sanity checks and close dangling connections
4193 public function __destruct() {
4194 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4195 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4198 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4199 if ( $danglingWriters ) {
4200 $fnames = implode( ', ', $danglingWriters );
4201 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4204 if ( $this->conn
) {
4205 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4206 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4207 Wikimedia\
suppressWarnings();
4208 $this->closeConnection();
4209 Wikimedia\restoreWarnings
();
4210 $this->conn
= false;
4211 $this->opened
= false;
4216 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4217 class_alias( Database
::class, 'Database' ); // b/c global alias