3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
37 use InvalidArgumentException
;
42 * Relational database abstraction object
47 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
48 /** Number of times to re-try an operation in case of deadlock */
49 const DEADLOCK_TRIES
= 4;
50 /** Minimum time to wait before retry, in microseconds */
51 const DEADLOCK_DELAY_MIN
= 500000;
52 /** Maximum time to wait before retry */
53 const DEADLOCK_DELAY_MAX
= 1500000;
55 /** How long before it is worth doing a dummy query to test the connection */
57 const PING_QUERY
= 'SELECT 1 AS ping';
59 const TINY_WRITE_SEC
= 0.010;
60 const SLOW_WRITE_SEC
= 0.500;
61 const SMALL_WRITE_ROWS
= 100;
63 /** @var string Whether lock granularity is on the level of the entire database */
64 const ATTR_DB_LEVEL_LOCKING
= 'db-level-locking';
66 /** @var int New Database instance will not be connected yet when returned */
67 const NEW_UNCONNECTED
= 0;
68 /** @var int New Database instance will already be connected when returned */
69 const NEW_CONNECTED
= 1;
71 /** @var string SQL query */
72 protected $lastQuery = '';
73 /** @var float|bool UNIX timestamp of last write query */
74 protected $lastWriteTime = false;
75 /** @var string|bool */
76 protected $phpError = false;
77 /** @var string Server that this instance is currently connected to */
79 /** @var string User that this instance is currently connected under the name of */
81 /** @var string Password used to establish the current connection */
83 /** @var string Database that this instance is currently connected to */
85 /** @var array[] Map of (table => (dbname, schema, prefix) map) */
86 protected $tableAliases = [];
87 /** @var string[] Map of (index alias => index) */
88 protected $indexAliases = [];
89 /** @var bool Whether this PHP instance is for a CLI script */
91 /** @var string Agent name for query profiling */
93 /** @var array Parameters used by initConnection() to establish a connection */
94 protected $connectionParams = [];
95 /** @var BagOStuff APC cache */
97 /** @var LoggerInterface */
98 protected $connLogger;
99 /** @var LoggerInterface */
100 protected $queryLogger;
101 /** @var callback Error logging callback */
102 protected $errorLogger;
104 /** @var resource|null Database connection */
105 protected $conn = null;
107 protected $opened = false;
109 /** @var array[] List of (callable, method name) */
110 protected $trxIdleCallbacks = [];
111 /** @var array[] List of (callable, method name) */
112 protected $trxPreCommitCallbacks = [];
113 /** @var array[] List of (callable, method name) */
114 protected $trxEndCallbacks = [];
115 /** @var callable[] Map of (name => callable) */
116 protected $trxRecurringCallbacks = [];
117 /** @var bool Whether to suppress triggering of transaction end callbacks */
118 protected $trxEndCallbacksSuppressed = false;
121 protected $tablePrefix = '';
123 protected $schema = '';
127 protected $lbInfo = [];
128 /** @var array|bool */
129 protected $schemaVars = false;
131 protected $sessionVars = [];
132 /** @var array|null */
133 protected $preparedArgs;
134 /** @var string|bool|null Stashed value of html_errors INI setting */
135 protected $htmlErrors;
137 protected $delimiter = ';';
138 /** @var DatabaseDomain */
139 protected $currentDomain;
140 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
141 protected $affectedRowCount;
144 * Either 1 if a transaction is active or 0 otherwise.
145 * The other Trx fields may not be meaningfull if this is 0.
149 protected $trxLevel = 0;
151 * Either a short hexidecimal string if a transaction is active or ""
154 * @see Database::trxLevel
156 protected $trxShortId = '';
158 * The UNIX time that the transaction started. Callers can assume that if
159 * snapshot isolation is used, then the data is *at least* up to date to that
160 * point (possibly more up-to-date since the first SELECT defines the snapshot).
163 * @see Database::trxLevel
165 private $trxTimestamp = null;
166 /** @var float Lag estimate at the time of BEGIN */
167 private $trxReplicaLag = null;
169 * Remembers the function name given for starting the most recent transaction via begin().
170 * Used to provide additional context for error reporting.
173 * @see Database::trxLevel
175 private $trxFname = null;
177 * Record if possible write queries were done in the last transaction started
180 * @see Database::trxLevel
182 private $trxDoneWrites = false;
184 * Record if the current transaction was started implicitly due to DBO_TRX being set.
187 * @see Database::trxLevel
189 private $trxAutomatic = false;
191 * Counter for atomic savepoint identifiers. Reset when a new transaction begins.
195 private $trxAtomicCounter = 0;
197 * Array of levels of atomicity within transactions
201 private $trxAtomicLevels = [];
203 * Record if the current transaction was started implicitly by Database::startAtomic
207 private $trxAutomaticAtomic = false;
209 * Track the write query callers of the current transaction
213 private $trxWriteCallers = [];
215 * @var float Seconds spent in write queries for the current transaction
217 private $trxWriteDuration = 0.0;
219 * @var int Number of write queries for the current transaction
221 private $trxWriteQueryCount = 0;
223 * @var int Number of rows affected by write queries for the current transaction
225 private $trxWriteAffectedRows = 0;
227 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
229 private $trxWriteAdjDuration = 0.0;
231 * @var int Number of write queries counted in trxWriteAdjDuration
233 private $trxWriteAdjQueryCount = 0;
235 * @var float RTT time estimate
237 private $rttEstimate = 0.0;
239 /** @var array Map of (name => 1) for locks obtained via lock() */
240 private $namedLocksHeld = [];
241 /** @var array Map of (table name => 1) for TEMPORARY tables */
242 protected $sessionTempTables = [];
244 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
245 private $lazyMasterHandle;
247 /** @var float UNIX timestamp */
248 protected $lastPing = 0.0;
250 /** @var int[] Prior flags member variable values */
251 private $priorFlags = [];
253 /** @var object|string Class name or object With profileIn/profileOut methods */
255 /** @var TransactionProfiler */
256 protected $trxProfiler;
259 protected $nonNativeInsertSelectBatchSize = 10000;
262 * @note: exceptions for missing libraries/drivers should be thrown in initConnection()
263 * @param array $params Parameters passed from Database::factory()
265 protected function __construct( array $params ) {
266 foreach ( [ 'host', 'user', 'password', 'dbname' ] as $name ) {
267 $this->connectionParams
[$name] = $params[$name];
270 $this->schema
= $params['schema'];
271 $this->tablePrefix
= $params['tablePrefix'];
273 $this->cliMode
= $params['cliMode'];
274 // Agent name is added to SQL queries in a comment, so make sure it can't break out
275 $this->agent
= str_replace( '/', '-', $params['agent'] );
277 $this->flags
= $params['flags'];
278 if ( $this->flags
& self
::DBO_DEFAULT
) {
279 if ( $this->cliMode
) {
280 $this->flags
&= ~self
::DBO_TRX
;
282 $this->flags |
= self
::DBO_TRX
;
286 $this->sessionVars
= $params['variables'];
288 $this->srvCache
= isset( $params['srvCache'] )
289 ?
$params['srvCache']
290 : new HashBagOStuff();
292 $this->profiler
= $params['profiler'];
293 $this->trxProfiler
= $params['trxProfiler'];
294 $this->connLogger
= $params['connLogger'];
295 $this->queryLogger
= $params['queryLogger'];
296 $this->errorLogger
= $params['errorLogger'];
298 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
299 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
302 // Set initial dummy domain until open() sets the final DB/prefix
303 $this->currentDomain
= DatabaseDomain
::newUnspecified();
307 * Initialize the connection to the database over the wire (or to local files)
309 * @throws LogicException
310 * @throws InvalidArgumentException
311 * @throws DBConnectionError
314 final public function initConnection() {
315 if ( $this->isOpen() ) {
316 throw new LogicException( __METHOD__
. ': already connected.' );
318 // Establish the connection
319 $this->doInitConnection();
320 // Set the domain object after open() sets the relevant fields
321 if ( $this->dbName
!= '' ) {
322 // Domains with server scope but a table prefix are not used by IDatabase classes
323 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
328 * Actually connect to the database over the wire (or to local files)
330 * @throws InvalidArgumentException
331 * @throws DBConnectionError
334 protected function doInitConnection() {
335 if ( strlen( $this->connectionParams
['user'] ) ) {
337 $this->connectionParams
['host'],
338 $this->connectionParams
['user'],
339 $this->connectionParams
['password'],
340 $this->connectionParams
['dbname']
343 throw new InvalidArgumentException( "No database user provided." );
348 * Construct a Database subclass instance given a database type and parameters
350 * This also connects to the database immediately upon object construction
352 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
353 * @param array $p Parameter map with keys:
354 * - host : The hostname of the DB server
355 * - user : The name of the database user the client operates under
356 * - password : The password for the database user
357 * - dbname : The name of the database to use where queries do not specify one.
358 * The database must exist or an error might be thrown. Setting this to the empty string
359 * will avoid any such errors and make the handle have no implicit database scope. This is
360 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
361 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
362 * in which user names and such are defined, e.g. users are database-specific in Postgres.
363 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
364 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
365 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
366 * recognized in queries. This can be used in place of schemas for handle site farms.
367 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
368 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
369 * flag in place UNLESS this this database simply acts as a key/value store.
370 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
371 * 'mysqli' driver; the old one 'mysql' has been removed.
372 * - variables: Optional map of session variables to set after connecting. This can be
373 * used to adjust lock timeouts or encoding modes and the like.
374 * - connLogger: Optional PSR-3 logger interface instance.
375 * - queryLogger: Optional PSR-3 logger interface instance.
376 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
377 * These will be called in query(), using a simplified version of the SQL that also
378 * includes the agent as a SQL comment.
379 * - trxProfiler: Optional TransactionProfiler instance.
380 * - errorLogger: Optional callback that takes an Exception and logs it.
381 * - cliMode: Whether to consider the execution context that of a CLI script.
382 * - agent: Optional name used to identify the end-user in query profiling/logging.
383 * - srvCache: Optional BagOStuff instance to an APC-style cache.
384 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
385 * @param int $connect One of the class constants (NEW_CONNECTED, NEW_UNCONNECTED) [optional]
386 * @return Database|null If the database driver or extension cannot be found
387 * @throws InvalidArgumentException If the database driver or extension cannot be found
390 final public static function factory( $dbType, $p = [], $connect = self
::NEW_CONNECTED
) {
391 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
393 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
394 // Resolve some defaults for b/c
395 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
396 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
397 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
398 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
399 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
400 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
401 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
402 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
403 $p['cliMode'] = isset( $p['cliMode'] )
405 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
406 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
407 if ( !isset( $p['connLogger'] ) ) {
408 $p['connLogger'] = new NullLogger();
410 if ( !isset( $p['queryLogger'] ) ) {
411 $p['queryLogger'] = new NullLogger();
413 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
414 if ( !isset( $p['trxProfiler'] ) ) {
415 $p['trxProfiler'] = new TransactionProfiler();
417 if ( !isset( $p['errorLogger'] ) ) {
418 $p['errorLogger'] = function ( Exception
$e ) {
419 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
423 /** @var Database $conn */
424 $conn = new $class( $p );
425 if ( $connect == self
::NEW_CONNECTED
) {
426 $conn->initConnection();
436 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
437 * @param string|null $driver Optional name of a specific DB client driver
438 * @return array Map of (Database::ATTRIBUTE_* constant => value) for all such constants
439 * @throws InvalidArgumentException
442 final public static function attributesFromType( $dbType, $driver = null ) {
443 static $defaults = [ self
::ATTR_DB_LEVEL_LOCKING
=> false ];
445 $class = self
::getClass( $dbType, $driver );
447 return call_user_func( [ $class, 'getAttributes' ] ) +
$defaults;
451 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
452 * @param string|null $driver Optional name of a specific DB client driver
453 * @return string Database subclass name to use
454 * @throws InvalidArgumentException
456 private static function getClass( $dbType, $driver = null ) {
457 // For database types with built-in support, the below maps type to IDatabase
458 // implementations. For types with multipe driver implementations (PHP extensions),
459 // an array can be used, keyed by extension name. In case of an array, the
460 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
461 // we auto-detect the first available driver. For types without built-in support,
462 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
463 static $builtinTypes = [
464 'mssql' => DatabaseMssql
::class,
465 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
466 'sqlite' => DatabaseSqlite
::class,
467 'postgres' => DatabasePostgres
::class,
470 $dbType = strtolower( $dbType );
473 if ( isset( $builtinTypes[$dbType] ) ) {
474 $possibleDrivers = $builtinTypes[$dbType];
475 if ( is_string( $possibleDrivers ) ) {
476 $class = $possibleDrivers;
478 if ( (string)$driver !== '' ) {
479 if ( !isset( $possibleDrivers[$driver] ) ) {
480 throw new InvalidArgumentException( __METHOD__
.
481 " type '$dbType' does not support driver '{$driver}'" );
483 $class = $possibleDrivers[$driver];
486 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
487 if ( extension_loaded( $posDriver ) ) {
488 $class = $possibleClass;
495 $class = 'Database' . ucfirst( $dbType );
498 if ( $class === false ) {
499 throw new InvalidArgumentException( __METHOD__
.
500 " no viable database extension found for type '$dbType'" );
507 * @return array Map of (Database::ATTRIBUTE_* constant => value
510 protected static function getAttributes() {
515 * Set the PSR-3 logger interface to use for query logging. (The logger
516 * interfaces for connection logging and error logging can be set with the
519 * @param LoggerInterface $logger
521 public function setLogger( LoggerInterface
$logger ) {
522 $this->queryLogger
= $logger;
525 public function getServerInfo() {
526 return $this->getServerVersion();
529 public function bufferResults( $buffer = null ) {
530 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
531 if ( $buffer !== null ) {
533 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
534 : $this->setFlag( self
::DBO_NOBUFFER
);
540 public function trxLevel() {
541 return $this->trxLevel
;
544 public function trxTimestamp() {
545 return $this->trxLevel ?
$this->trxTimestamp
: null;
548 public function tablePrefix( $prefix = null ) {
549 $old = $this->tablePrefix
;
550 if ( $prefix !== null ) {
551 $this->tablePrefix
= $prefix;
552 $this->currentDomain
= ( $this->dbName
!= '' )
553 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
554 : DatabaseDomain
::newUnspecified();
560 public function dbSchema( $schema = null ) {
561 $old = $this->schema
;
562 if ( $schema !== null ) {
563 $this->schema
= $schema;
569 public function getLBInfo( $name = null ) {
570 if ( is_null( $name ) ) {
571 return $this->lbInfo
;
573 if ( array_key_exists( $name, $this->lbInfo
) ) {
574 return $this->lbInfo
[$name];
581 public function setLBInfo( $name, $value = null ) {
582 if ( is_null( $value ) ) {
583 $this->lbInfo
= $name;
585 $this->lbInfo
[$name] = $value;
589 public function setLazyMasterHandle( IDatabase
$conn ) {
590 $this->lazyMasterHandle
= $conn;
594 * @return IDatabase|null
595 * @see setLazyMasterHandle()
598 protected function getLazyMasterHandle() {
599 return $this->lazyMasterHandle
;
602 public function implicitGroupby() {
606 public function implicitOrderby() {
610 public function lastQuery() {
611 return $this->lastQuery
;
614 public function doneWrites() {
615 return (bool)$this->lastWriteTime
;
618 public function lastDoneWrites() {
619 return $this->lastWriteTime ?
: false;
622 public function writesPending() {
623 return $this->trxLevel
&& $this->trxDoneWrites
;
626 public function writesOrCallbacksPending() {
627 return $this->trxLevel
&& (
628 $this->trxDoneWrites ||
629 $this->trxIdleCallbacks ||
630 $this->trxPreCommitCallbacks ||
631 $this->trxEndCallbacks
635 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
636 if ( !$this->trxLevel
) {
638 } elseif ( !$this->trxDoneWrites
) {
643 case self
::ESTIMATE_DB_APPLY
:
645 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
646 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
647 // For omitted queries, make them count as something at least
648 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
649 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
652 default: // everything
653 return $this->trxWriteDuration
;
657 public function pendingWriteCallers() {
658 return $this->trxLevel ?
$this->trxWriteCallers
: [];
661 public function pendingWriteRowsAffected() {
662 return $this->trxWriteAffectedRows
;
666 * Get the list of method names that have pending write queries or callbacks
667 * for this transaction
671 protected function pendingWriteAndCallbackCallers() {
672 if ( !$this->trxLevel
) {
676 $fnames = $this->trxWriteCallers
;
678 $this->trxIdleCallbacks
,
679 $this->trxPreCommitCallbacks
,
680 $this->trxEndCallbacks
682 foreach ( $callbacks as $callback ) {
683 $fnames[] = $callback[1];
690 public function isOpen() {
691 return $this->opened
;
694 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
695 if ( ( $flag & self
::DBO_IGNORE
) ) {
696 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
699 if ( $remember === self
::REMEMBER_PRIOR
) {
700 array_push( $this->priorFlags
, $this->flags
);
702 $this->flags |
= $flag;
705 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
706 if ( ( $flag & self
::DBO_IGNORE
) ) {
707 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
710 if ( $remember === self
::REMEMBER_PRIOR
) {
711 array_push( $this->priorFlags
, $this->flags
);
713 $this->flags
&= ~
$flag;
716 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
717 if ( !$this->priorFlags
) {
721 if ( $state === self
::RESTORE_INITIAL
) {
722 $this->flags
= reset( $this->priorFlags
);
723 $this->priorFlags
= [];
725 $this->flags
= array_pop( $this->priorFlags
);
729 public function getFlag( $flag ) {
730 return !!( $this->flags
& $flag );
734 * @param string $name Class field name
736 * @deprecated Since 1.28
738 public function getProperty( $name ) {
742 public function getDomainID() {
743 return $this->currentDomain
->getId();
746 final public function getWikiID() {
747 return $this->getDomainID();
751 * Get information about an index into an object
752 * @param string $table Table name
753 * @param string $index Index name
754 * @param string $fname Calling function name
755 * @return mixed Database-specific index description class or false if the index does not exist
757 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
760 * Wrapper for addslashes()
762 * @param string $s String to be slashed.
763 * @return string Slashed string.
765 abstract function strencode( $s );
768 * Set a custom error handler for logging errors during database connection
770 protected function installErrorHandler() {
771 $this->phpError
= false;
772 $this->htmlErrors
= ini_set( 'html_errors', '0' );
773 set_error_handler( [ $this, 'connectionErrorLogger' ] );
777 * Restore the previous error handler and return the last PHP error for this DB
779 * @return bool|string
781 protected function restoreErrorHandler() {
782 restore_error_handler();
783 if ( $this->htmlErrors
!== false ) {
784 ini_set( 'html_errors', $this->htmlErrors
);
787 return $this->getLastPHPError();
791 * @return string|bool Last PHP error for this DB (typically connection errors)
793 protected function getLastPHPError() {
794 if ( $this->phpError
) {
795 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
796 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
805 * Error handler for logging errors during database connection
806 * This method should not be used outside of Database classes
809 * @param string $errstr
811 public function connectionErrorLogger( $errno, $errstr ) {
812 $this->phpError
= $errstr;
816 * Create a log context to pass to PSR-3 logger functions.
818 * @param array $extras Additional data to add to context
821 protected function getLogContext( array $extras = [] ) {
824 'db_server' => $this->server
,
825 'db_name' => $this->dbName
,
826 'db_user' => $this->user
,
832 public function close() {
834 // Resolve any dangling transaction first
835 if ( $this->trxLevel() ) {
836 // Meaningful transactions should ideally have been resolved by now
837 if ( $this->writesOrCallbacksPending() ) {
838 $this->queryLogger
->warning(
839 __METHOD__
. ": writes or callbacks still pending.",
840 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
843 // Check if it is possible to properly commit and trigger callbacks
844 if ( $this->trxEndCallbacksSuppressed
) {
845 throw new DBUnexpectedError(
847 __METHOD__
. ': callbacks are suppressed; cannot properly commit.'
850 // Commit the changes and run any callbacks as needed
851 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
853 // Close the actual connection in the binding handle
854 $closed = $this->closeConnection();
856 // Sanity check that no callbacks are dangling
858 $this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks ||
$this->trxEndCallbacks
860 throw new RuntimeException( "Transaction callbacks still pending." );
863 $closed = true; // already closed; nothing to do
866 $this->opened
= false;
872 * Make sure isOpen() returns true as a sanity check
874 * @throws DBUnexpectedError
876 protected function assertOpen() {
877 if ( !$this->isOpen() ) {
878 throw new DBUnexpectedError( $this, "DB connection was already closed." );
883 * Closes underlying database connection
885 * @return bool Whether connection was closed successfully
887 abstract protected function closeConnection();
890 * @param string $error Fallback error message, used if none is given by DB
891 * @throws DBConnectionError
893 public function reportConnectionError( $error = 'Unknown error' ) {
894 $myError = $this->lastError();
900 throw new DBConnectionError( $this, $error );
904 * Run a query and return a DBMS-dependent wrapper (that has all IResultWrapper methods)
906 * This might return things, such as mysqli_result, that do not formally implement
907 * IResultWrapper, but nonetheless implement all of its methods correctly
909 * @param string $sql SQL query.
910 * @return IResultWrapper|bool Iterator to feed to fetchObject/fetchRow; false on failure
912 abstract protected function doQuery( $sql );
915 * Determine whether a query writes to the DB.
916 * Should return true if unsure.
921 protected function isWriteQuery( $sql ) {
923 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
928 * @return string|null
930 protected function getQueryVerb( $sql ) {
931 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
935 * Determine whether a SQL statement is sensitive to isolation level.
936 * A SQL statement is considered transactable if its result could vary
937 * depending on the transaction isolation level. Operational commands
938 * such as 'SET' and 'SHOW' are not considered to be transactable.
943 protected function isTransactableQuery( $sql ) {
945 $this->getQueryVerb( $sql ),
946 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
952 * @param string $sql A SQL query
953 * @return bool Whether $sql is SQL for TEMPORARY table operation
955 protected function registerTempTableOperation( $sql ) {
957 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
961 $this->sessionTempTables
[$matches[1]] = 1;
964 } elseif ( preg_match(
965 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
969 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
970 unset( $this->sessionTempTables
[$matches[1]] );
973 } elseif ( preg_match(
974 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
978 return isset( $this->sessionTempTables
[$matches[1]] );
979 } elseif ( preg_match(
980 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
984 return isset( $this->sessionTempTables
[$matches[1]] );
990 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
991 $priorWritesPending = $this->writesOrCallbacksPending();
992 $this->lastQuery
= $sql;
994 $isWrite = $this->isWriteQuery( $sql );
996 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
998 $isNonTempWrite = false;
1002 if ( $this->getLBInfo( 'replica' ) === true ) {
1005 'Write operations are not allowed on replica database connections.'
1008 # In theory, non-persistent writes are allowed in read-only mode, but due to things
1009 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
1010 $reason = $this->getReadOnlyReason();
1011 if ( $reason !== false ) {
1012 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
1014 # Set a flag indicating that writes have been done
1015 $this->lastWriteTime
= microtime( true );
1018 # Add trace comment to the begin of the sql string, right after the operator.
1019 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
1020 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
1022 # Start implicit transactions that wrap the request if DBO_TRX is enabled
1023 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
1024 && $this->isTransactableQuery( $sql )
1026 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
1027 $this->trxAutomatic
= true;
1030 # Keep track of whether the transaction has write queries pending
1031 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
1032 $this->trxDoneWrites
= true;
1033 $this->trxProfiler
->transactionWritingIn(
1034 $this->server
, $this->dbName
, $this->trxShortId
);
1037 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
1038 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
1041 # Avoid fatals if close() was called
1042 $this->assertOpen();
1044 # Send the query to the server
1045 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1047 # Try reconnecting if the connection was lost
1048 if ( false === $ret && $this->wasConnectionLoss() ) {
1049 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
1050 # Stash the last error values before anything might clear them
1051 $lastError = $this->lastError();
1052 $lastErrno = $this->lastErrno();
1053 # Update state tracking to reflect transaction loss due to disconnection
1054 $this->handleSessionLoss();
1055 if ( $this->reconnect() ) {
1056 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
1057 $params = [ 'dbserver' => $this->getServer() ];
1058 $this->connLogger
->warning( $msg, $params );
1059 $this->queryLogger
->warning( $msg, $params +
1060 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
1062 if ( $recoverable ) {
1063 # Should be safe to silently retry the query
1064 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1066 # Callers may catch the exception and continue to use the DB
1067 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
1070 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1071 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1075 if ( false === $ret ) {
1076 # Deadlocks cause the entire transaction to abort, not just the statement.
1077 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1078 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1079 if ( $this->wasDeadlock() ) {
1080 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1081 $tempIgnore = false; // not recoverable
1083 # Update state tracking to reflect transaction loss
1084 $this->handleSessionLoss();
1087 $this->reportQueryError(
1088 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1091 $res = $this->resultObject( $ret );
1097 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1099 * @param string $sql Original SQL query
1100 * @param string $commentedSql SQL query with debugging/trace comment
1101 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1102 * @param string $fname Name of the calling function
1103 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1104 * object for a successful read query, or false on failure
1106 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1107 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1108 # generalizeSQL() will probably cut down the query to reasonable
1109 # logging size most of the time. The substr is really just a sanity check.
1111 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1113 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1116 # Include query transaction state
1117 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1119 $startTime = microtime( true );
1120 if ( $this->profiler
) {
1121 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1123 $this->affectedRowCount
= null;
1124 $ret = $this->doQuery( $commentedSql );
1125 $this->affectedRowCount
= $this->affectedRows();
1126 if ( $this->profiler
) {
1127 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1129 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1131 unset( $queryProfSection ); // profile out (if set)
1133 if ( $ret !== false ) {
1134 $this->lastPing
= $startTime;
1135 if ( $isWrite && $this->trxLevel
) {
1136 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1137 $this->trxWriteCallers
[] = $fname;
1141 if ( $sql === self
::PING_QUERY
) {
1142 $this->rttEstimate
= $queryRuntime;
1145 $this->trxProfiler
->recordQueryCompletion(
1146 $queryProf, $startTime, $isWrite, $this->affectedRows()
1148 $this->queryLogger
->debug( $sql, [
1150 'master' => $isMaster,
1151 'runtime' => $queryRuntime,
1158 * Update the estimated run-time of a query, not counting large row lock times
1160 * LoadBalancer can be set to rollback transactions that will create huge replication
1161 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1162 * queries, like inserting a row can take a long time due to row locking. This method
1163 * uses some simple heuristics to discount those cases.
1165 * @param string $sql A SQL write query
1166 * @param float $runtime Total runtime, including RTT
1167 * @param int $affected Affected row count
1169 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1170 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1171 $indicativeOfReplicaRuntime = true;
1172 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1173 $verb = $this->getQueryVerb( $sql );
1174 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1175 if ( $verb === 'INSERT' ) {
1176 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1177 } elseif ( $verb === 'REPLACE' ) {
1178 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1182 $this->trxWriteDuration +
= $runtime;
1183 $this->trxWriteQueryCount +
= 1;
1184 $this->trxWriteAffectedRows +
= $affected;
1185 if ( $indicativeOfReplicaRuntime ) {
1186 $this->trxWriteAdjDuration +
= $runtime;
1187 $this->trxWriteAdjQueryCount +
= 1;
1192 * Determine whether or not it is safe to retry queries after a database
1193 * connection is lost
1195 * @param string $sql SQL query
1196 * @param bool $priorWritesPending Whether there is a transaction open with
1197 * possible write queries or transaction pre-commit/idle callbacks
1198 * waiting on it to finish.
1199 * @return bool True if it is safe to retry the query, false otherwise
1201 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1202 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1203 # Dropped connections also mean that named locks are automatically released.
1204 # Only allow error suppression in autocommit mode or when the lost transaction
1205 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1206 if ( $this->namedLocksHeld
) {
1207 return false; // possible critical section violation
1208 } elseif ( $sql === 'COMMIT' ) {
1209 return !$priorWritesPending; // nothing written anyway? (T127428)
1210 } elseif ( $sql === 'ROLLBACK' ) {
1211 return true; // transaction lost...which is also what was requested :)
1212 } elseif ( $this->explicitTrxActive() ) {
1213 return false; // don't drop atomocity
1214 } elseif ( $priorWritesPending ) {
1215 return false; // prior writes lost from implicit transaction
1222 * Clean things up after transaction loss due to disconnection
1224 * @return null|Exception
1226 private function handleSessionLoss() {
1227 $this->trxLevel
= 0;
1228 $this->trxAtomicCounter
= 0;
1229 $this->trxIdleCallbacks
= []; // T67263; transaction already lost
1230 $this->trxPreCommitCallbacks
= []; // T67263; transaction already lost
1231 $this->sessionTempTables
= [];
1232 $this->namedLocksHeld
= [];
1234 // Note: if callback suppression is set then some *Callbacks arrays are not cleared here
1237 // Handle callbacks in trxEndCallbacks
1238 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1239 } catch ( Exception
$ex ) {
1240 // Already logged; move on...
1244 // Handle callbacks in trxRecurringCallbacks
1245 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1246 } catch ( Exception
$ex ) {
1247 // Already logged; move on...
1255 * Checks whether the cause of the error is detected to be a timeout.
1257 * It returns false by default, and not all engines support detecting this yet.
1258 * If this returns false, it will be treated as a generic query error.
1260 * @param string $error Error text
1261 * @param int $errno Error number
1264 protected function wasQueryTimeout( $error, $errno ) {
1269 * Report a query error. Log the error, and if neither the object ignore
1270 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1272 * @param string $error
1274 * @param string $sql
1275 * @param string $fname
1276 * @param bool $tempIgnore
1277 * @throws DBQueryError
1279 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1280 if ( $this->getFlag( self
::DBO_IGNORE
) ||
$tempIgnore ) {
1281 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1283 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1284 $this->queryLogger
->error(
1285 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1286 $this->getLogContext( [
1287 'method' => __METHOD__
,
1290 'sql1line' => $sql1line,
1294 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1295 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1296 if ( $wasQueryTimeout ) {
1297 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1299 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1304 public function freeResult( $res ) {
1307 public function selectField(
1308 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1310 if ( $var === '*' ) { // sanity
1311 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1314 if ( !is_array( $options ) ) {
1315 $options = [ $options ];
1318 $options['LIMIT'] = 1;
1320 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1321 if ( $res === false ||
!$this->numRows( $res ) ) {
1325 $row = $this->fetchRow( $res );
1327 if ( $row !== false ) {
1328 return reset( $row );
1334 public function selectFieldValues(
1335 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1337 if ( $var === '*' ) { // sanity
1338 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1339 } elseif ( !is_string( $var ) ) { // sanity
1340 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1343 if ( !is_array( $options ) ) {
1344 $options = [ $options ];
1347 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1348 if ( $res === false ) {
1353 foreach ( $res as $row ) {
1354 $values[] = $row->$var;
1361 * Returns an optional USE INDEX clause to go after the table, and a
1362 * string to go at the end of the query.
1364 * @param array $options Associative array of options to be turned into
1365 * an SQL query, valid keys are listed in the function.
1367 * @see Database::select()
1369 protected function makeSelectOptions( $options ) {
1370 $preLimitTail = $postLimitTail = '';
1375 foreach ( $options as $key => $option ) {
1376 if ( is_numeric( $key ) ) {
1377 $noKeyOptions[$option] = true;
1381 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1383 $preLimitTail .= $this->makeOrderBy( $options );
1385 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1386 $postLimitTail .= ' FOR UPDATE';
1389 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1390 $postLimitTail .= ' LOCK IN SHARE MODE';
1393 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1394 $startOpts .= 'DISTINCT';
1397 # Various MySQL extensions
1398 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1399 $startOpts .= ' /*! STRAIGHT_JOIN */';
1402 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1403 $startOpts .= ' HIGH_PRIORITY';
1406 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1407 $startOpts .= ' SQL_BIG_RESULT';
1410 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1411 $startOpts .= ' SQL_BUFFER_RESULT';
1414 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1415 $startOpts .= ' SQL_SMALL_RESULT';
1418 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1419 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1422 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1423 $startOpts .= ' SQL_CACHE';
1426 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1427 $startOpts .= ' SQL_NO_CACHE';
1430 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1431 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1435 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1436 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1441 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1445 * Returns an optional GROUP BY with an optional HAVING
1447 * @param array $options Associative array of options
1449 * @see Database::select()
1452 protected function makeGroupByWithHaving( $options ) {
1454 if ( isset( $options['GROUP BY'] ) ) {
1455 $gb = is_array( $options['GROUP BY'] )
1456 ?
implode( ',', $options['GROUP BY'] )
1457 : $options['GROUP BY'];
1458 $sql .= ' GROUP BY ' . $gb;
1460 if ( isset( $options['HAVING'] ) ) {
1461 $having = is_array( $options['HAVING'] )
1462 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1463 : $options['HAVING'];
1464 $sql .= ' HAVING ' . $having;
1471 * Returns an optional ORDER BY
1473 * @param array $options Associative array of options
1475 * @see Database::select()
1478 protected function makeOrderBy( $options ) {
1479 if ( isset( $options['ORDER BY'] ) ) {
1480 $ob = is_array( $options['ORDER BY'] )
1481 ?
implode( ',', $options['ORDER BY'] )
1482 : $options['ORDER BY'];
1484 return ' ORDER BY ' . $ob;
1490 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1491 $options = [], $join_conds = [] ) {
1492 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1494 return $this->query( $sql, $fname );
1497 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1498 $options = [], $join_conds = []
1500 if ( is_array( $vars ) ) {
1501 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1504 $options = (array)$options;
1505 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1506 ?
$options['USE INDEX']
1509 isset( $options['IGNORE INDEX'] ) &&
1510 is_array( $options['IGNORE INDEX'] )
1512 ?
$options['IGNORE INDEX']
1515 if ( is_array( $table ) ) {
1517 $this->tableNamesWithIndexClauseOrJOIN(
1518 $table, $useIndexes, $ignoreIndexes, $join_conds );
1519 } elseif ( $table != '' ) {
1521 $this->tableNamesWithIndexClauseOrJOIN(
1522 [ $table ], $useIndexes, $ignoreIndexes, [] );
1527 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1528 $this->makeSelectOptions( $options );
1530 if ( is_array( $conds ) ) {
1531 $conds = $this->makeList( $conds, self
::LIST_AND
);
1534 if ( $conds === null ||
$conds === false ) {
1535 $this->queryLogger
->warning(
1539 . ' with incorrect parameters: $conds must be a string or an array'
1544 if ( $conds === '' ) {
1545 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1546 } elseif ( is_string( $conds ) ) {
1547 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1548 "WHERE $conds $preLimitTail";
1550 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1553 if ( isset( $options['LIMIT'] ) ) {
1554 $sql = $this->limitResult( $sql, $options['LIMIT'],
1555 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1557 $sql = "$sql $postLimitTail";
1559 if ( isset( $options['EXPLAIN'] ) ) {
1560 $sql = 'EXPLAIN ' . $sql;
1566 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1567 $options = [], $join_conds = []
1569 $options = (array)$options;
1570 $options['LIMIT'] = 1;
1571 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1573 if ( $res === false ) {
1577 if ( !$this->numRows( $res ) ) {
1581 $obj = $this->fetchObject( $res );
1586 public function estimateRowCount(
1587 $table, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1589 $conds = $this->normalizeConditions( $conds, $fname );
1590 $column = $this->extractSingleFieldFromList( $var );
1591 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1592 $conds[] = "$column IS NOT NULL";
1595 $res = $this->select(
1596 $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options, $join_conds
1598 $row = $res ?
$this->fetchRow( $res ) : [];
1600 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1603 public function selectRowCount(
1604 $tables, $var = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1606 $conds = $this->normalizeConditions( $conds, $fname );
1607 $column = $this->extractSingleFieldFromList( $var );
1608 if ( is_string( $column ) && !in_array( $column, [ '*', '1' ] ) ) {
1609 $conds[] = "$column IS NOT NULL";
1612 $res = $this->select(
1614 'tmp_count' => $this->buildSelectSubquery(
1623 [ 'rowcount' => 'COUNT(*)' ],
1627 $row = $res ?
$this->fetchRow( $res ) : [];
1629 return isset( $row['rowcount'] ) ?
(int)$row['rowcount'] : 0;
1633 * @param array|string $conds
1634 * @param string $fname
1637 final protected function normalizeConditions( $conds, $fname ) {
1638 if ( $conds === null ||
$conds === false ) {
1639 $this->queryLogger
->warning(
1643 . ' with incorrect parameters: $conds must be a string or an array'
1648 if ( !is_array( $conds ) ) {
1649 $conds = ( $conds === '' ) ?
[] : [ $conds ];
1656 * @param array|string $var Field parameter in the style of select()
1657 * @return string|null Column name or null; ignores aliases
1658 * @throws DBUnexpectedError Errors out if multiple columns are given
1660 final protected function extractSingleFieldFromList( $var ) {
1661 if ( is_array( $var ) ) {
1664 } elseif ( count( $var ) == 1 ) {
1665 $column = isset( $var[0] ) ?
$var[0] : reset( $var );
1667 throw new DBUnexpectedError( $this, __METHOD__
. ': got multiple columns.' );
1677 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1678 * It's only slightly flawed. Don't use for anything important.
1680 * @param string $sql A SQL Query
1684 protected static function generalizeSQL( $sql ) {
1685 # This does the same as the regexp below would do, but in such a way
1686 # as to avoid crashing php on some large strings.
1687 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1689 $sql = str_replace( "\\\\", '', $sql );
1690 $sql = str_replace( "\\'", '', $sql );
1691 $sql = str_replace( "\\\"", '', $sql );
1692 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1693 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1695 # All newlines, tabs, etc replaced by single space
1696 $sql = preg_replace( '/\s+/', ' ', $sql );
1699 # except the ones surrounded by characters, e.g. l10n
1700 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1701 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1706 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1707 $info = $this->fieldInfo( $table, $field );
1712 public function indexExists( $table, $index, $fname = __METHOD__
) {
1713 if ( !$this->tableExists( $table ) ) {
1717 $info = $this->indexInfo( $table, $index, $fname );
1718 if ( is_null( $info ) ) {
1721 return $info !== false;
1725 public function tableExists( $table, $fname = __METHOD__
) {
1726 $tableRaw = $this->tableName( $table, 'raw' );
1727 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1728 return true; // already known to exist
1731 $table = $this->tableName( $table );
1732 $ignoreErrors = true;
1733 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1738 public function indexUnique( $table, $index ) {
1739 $indexInfo = $this->indexInfo( $table, $index );
1741 if ( !$indexInfo ) {
1745 return !$indexInfo[0]->Non_unique
;
1749 * Helper for Database::insert().
1751 * @param array $options
1754 protected function makeInsertOptions( $options ) {
1755 return implode( ' ', $options );
1758 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1759 # No rows to insert, easy just return now
1760 if ( !count( $a ) ) {
1764 $table = $this->tableName( $table );
1766 if ( !is_array( $options ) ) {
1767 $options = [ $options ];
1771 if ( isset( $options['fileHandle'] ) ) {
1772 $fh = $options['fileHandle'];
1774 $options = $this->makeInsertOptions( $options );
1776 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1778 $keys = array_keys( $a[0] );
1781 $keys = array_keys( $a );
1784 $sql = 'INSERT ' . $options .
1785 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1789 foreach ( $a as $row ) {
1795 $sql .= '(' . $this->makeList( $row ) . ')';
1798 $sql .= '(' . $this->makeList( $a ) . ')';
1801 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1803 } elseif ( $fh !== null ) {
1807 return (bool)$this->query( $sql, $fname );
1811 * Make UPDATE options array for Database::makeUpdateOptions
1813 * @param array $options
1816 protected function makeUpdateOptionsArray( $options ) {
1817 if ( !is_array( $options ) ) {
1818 $options = [ $options ];
1823 if ( in_array( 'IGNORE', $options ) ) {
1831 * Make UPDATE options for the Database::update function
1833 * @param array $options The options passed to Database::update
1836 protected function makeUpdateOptions( $options ) {
1837 $opts = $this->makeUpdateOptionsArray( $options );
1839 return implode( ' ', $opts );
1842 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1843 $table = $this->tableName( $table );
1844 $opts = $this->makeUpdateOptions( $options );
1845 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1847 if ( $conds !== [] && $conds !== '*' ) {
1848 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1851 return (bool)$this->query( $sql, $fname );
1854 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1855 if ( !is_array( $a ) ) {
1856 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1862 foreach ( $a as $field => $value ) {
1864 if ( $mode == self
::LIST_AND
) {
1866 } elseif ( $mode == self
::LIST_OR
) {
1875 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1876 $list .= "($value)";
1877 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1880 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1882 // Remove null from array to be handled separately if found
1883 $includeNull = false;
1884 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1885 $includeNull = true;
1886 unset( $value[$nullKey] );
1888 if ( count( $value ) == 0 && !$includeNull ) {
1889 throw new InvalidArgumentException(
1890 __METHOD__
. ": empty input for field $field" );
1891 } elseif ( count( $value ) == 0 ) {
1892 // only check if $field is null
1893 $list .= "$field IS NULL";
1895 // IN clause contains at least one valid element
1896 if ( $includeNull ) {
1897 // Group subconditions to ensure correct precedence
1900 if ( count( $value ) == 1 ) {
1901 // Special-case single values, as IN isn't terribly efficient
1902 // Don't necessarily assume the single key is 0; we don't
1903 // enforce linear numeric ordering on other arrays here.
1904 $value = array_values( $value )[0];
1905 $list .= $field . " = " . $this->addQuotes( $value );
1907 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1909 // if null present in array, append IS NULL
1910 if ( $includeNull ) {
1911 $list .= " OR $field IS NULL)";
1914 } elseif ( $value === null ) {
1915 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1916 $list .= "$field IS ";
1917 } elseif ( $mode == self
::LIST_SET
) {
1918 $list .= "$field = ";
1923 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1925 $list .= "$field = ";
1927 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1934 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1937 foreach ( $data as $base => $sub ) {
1938 if ( count( $sub ) ) {
1939 $conds[] = $this->makeList(
1940 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1946 return $this->makeList( $conds, self
::LIST_OR
);
1948 // Nothing to search for...
1953 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1957 public function bitNot( $field ) {
1961 public function bitAnd( $fieldLeft, $fieldRight ) {
1962 return "($fieldLeft & $fieldRight)";
1965 public function bitOr( $fieldLeft, $fieldRight ) {
1966 return "($fieldLeft | $fieldRight)";
1969 public function buildConcat( $stringList ) {
1970 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1973 public function buildGroupConcatField(
1974 $delim, $table, $field, $conds = '', $join_conds = []
1976 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1978 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1981 public function buildSubstring( $input, $startPosition, $length = null ) {
1982 $this->assertBuildSubstringParams( $startPosition, $length );
1983 $functionBody = "$input FROM $startPosition";
1984 if ( $length !== null ) {
1985 $functionBody .= " FOR $length";
1987 return 'SUBSTRING(' . $functionBody . ')';
1991 * Check type and bounds for parameters to self::buildSubstring()
1993 * All supported databases have substring functions that behave the same for
1994 * positive $startPosition and non-negative $length, but behaviors differ when
1995 * given 0 or negative $startPosition or negative $length. The simplest
1996 * solution to that is to just forbid those values.
1998 * @param int $startPosition
1999 * @param int|null $length
2002 protected function assertBuildSubstringParams( $startPosition, $length ) {
2003 if ( !is_int( $startPosition ) ||
$startPosition <= 0 ) {
2004 throw new InvalidArgumentException(
2005 '$startPosition must be a positive integer'
2008 if ( !( is_int( $length ) && $length >= 0 ||
$length === null ) ) {
2009 throw new InvalidArgumentException(
2010 '$length must be null or an integer greater than or equal to 0'
2015 public function buildStringCast( $field ) {
2019 public function buildIntegerCast( $field ) {
2020 return 'CAST( ' . $field . ' AS INTEGER )';
2023 public function buildSelectSubquery(
2024 $table, $vars, $conds = '', $fname = __METHOD__
,
2025 $options = [], $join_conds = []
2027 return new Subquery(
2028 $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds )
2032 public function databasesAreIndependent() {
2036 public function selectDB( $db ) {
2037 # Stub. Shouldn't cause serious problems if it's not overridden, but
2038 # if your database engine supports a concept similar to MySQL's
2039 # databases you may as well.
2040 $this->dbName
= $db;
2045 public function getDBname() {
2046 return $this->dbName
;
2049 public function getServer() {
2050 return $this->server
;
2053 public function tableName( $name, $format = 'quoted' ) {
2054 if ( $name instanceof Subquery
) {
2055 throw new DBUnexpectedError(
2057 __METHOD__
. ': got Subquery instance when expecting a string.'
2061 # Skip the entire process when we have a string quoted on both ends.
2062 # Note that we check the end so that we will still quote any use of
2063 # use of `database`.table. But won't break things if someone wants
2064 # to query a database table with a dot in the name.
2065 if ( $this->isQuotedIdentifier( $name ) ) {
2069 # Lets test for any bits of text that should never show up in a table
2070 # name. Basically anything like JOIN or ON which are actually part of
2071 # SQL queries, but may end up inside of the table value to combine
2072 # sql. Such as how the API is doing.
2073 # Note that we use a whitespace test rather than a \b test to avoid
2074 # any remote case where a word like on may be inside of a table name
2075 # surrounded by symbols which may be considered word breaks.
2076 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2077 $this->queryLogger
->warning(
2078 __METHOD__
. ": use of subqueries is not supported this way.",
2079 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
2085 # Split database and table into proper variables.
2086 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
2088 # Quote $table and apply the prefix if not quoted.
2089 # $tableName might be empty if this is called from Database::replaceVars()
2090 $tableName = "{$prefix}{$table}";
2091 if ( $format === 'quoted'
2092 && !$this->isQuotedIdentifier( $tableName )
2093 && $tableName !== ''
2095 $tableName = $this->addIdentifierQuotes( $tableName );
2098 # Quote $schema and $database and merge them with the table name if needed
2099 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
2100 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
2106 * Get the table components needed for a query given the currently selected database
2108 * @param string $name Table name in the form of db.schema.table, db.table, or table
2109 * @return array (DB name or "" for default, schema name, table prefix, table name)
2111 protected function qualifiedTableComponents( $name ) {
2112 # We reverse the explode so that database.table and table both output the correct table.
2113 $dbDetails = explode( '.', $name, 3 );
2114 if ( count( $dbDetails ) == 3 ) {
2115 list( $database, $schema, $table ) = $dbDetails;
2116 # We don't want any prefix added in this case
2118 } elseif ( count( $dbDetails ) == 2 ) {
2119 list( $database, $table ) = $dbDetails;
2120 # We don't want any prefix added in this case
2122 # In dbs that support it, $database may actually be the schema
2123 # but that doesn't affect any of the functionality here
2126 list( $table ) = $dbDetails;
2127 if ( isset( $this->tableAliases
[$table] ) ) {
2128 $database = $this->tableAliases
[$table]['dbname'];
2129 $schema = is_string( $this->tableAliases
[$table]['schema'] )
2130 ?
$this->tableAliases
[$table]['schema']
2132 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
2133 ?
$this->tableAliases
[$table]['prefix']
2134 : $this->tablePrefix
;
2137 $schema = $this->schema
; # Default schema
2138 $prefix = $this->tablePrefix
; # Default prefix
2142 return [ $database, $schema, $prefix, $table ];
2146 * @param string|null $namespace Database or schema
2147 * @param string $relation Name of table, view, sequence, etc...
2148 * @param string $format One of (raw, quoted)
2149 * @return string Relation name with quoted and merged $namespace as needed
2151 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
2152 if ( strlen( $namespace ) ) {
2153 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
2154 $namespace = $this->addIdentifierQuotes( $namespace );
2156 $relation = $namespace . '.' . $relation;
2162 public function tableNames() {
2163 $inArray = func_get_args();
2166 foreach ( $inArray as $name ) {
2167 $retVal[$name] = $this->tableName( $name );
2173 public function tableNamesN() {
2174 $inArray = func_get_args();
2177 foreach ( $inArray as $name ) {
2178 $retVal[] = $this->tableName( $name );
2185 * Get an aliased table name
2187 * This returns strings like "tableName AS newTableName" for aliased tables
2188 * and "(SELECT * from tableA) newTablename" for subqueries (e.g. derived tables)
2190 * @see Database::tableName()
2191 * @param string|Subquery $table Table name or object with a 'sql' field
2192 * @param string|bool $alias Table alias (optional)
2193 * @return string SQL name for aliased table. Will not alias a table to its own name
2195 protected function tableNameWithAlias( $table, $alias = false ) {
2196 if ( is_string( $table ) ) {
2197 $quotedTable = $this->tableName( $table );
2198 } elseif ( $table instanceof Subquery
) {
2199 $quotedTable = (string)$table;
2201 throw new InvalidArgumentException( "Table must be a string or Subquery." );
2204 if ( !strlen( $alias ) ||
$alias === $table ) {
2205 if ( $table instanceof Subquery
) {
2206 throw new InvalidArgumentException( "Subquery table missing alias." );
2209 return $quotedTable;
2211 return $quotedTable . ' ' . $this->addIdentifierQuotes( $alias );
2216 * Gets an array of aliased table names
2218 * @param array $tables [ [alias] => table ]
2219 * @return string[] See tableNameWithAlias()
2221 protected function tableNamesWithAlias( $tables ) {
2223 foreach ( $tables as $alias => $table ) {
2224 if ( is_numeric( $alias ) ) {
2227 $retval[] = $this->tableNameWithAlias( $table, $alias );
2234 * Get an aliased field name
2235 * e.g. fieldName AS newFieldName
2237 * @param string $name Field name
2238 * @param string|bool $alias Alias (optional)
2239 * @return string SQL name for aliased field. Will not alias a field to its own name
2241 protected function fieldNameWithAlias( $name, $alias = false ) {
2242 if ( !$alias ||
(string)$alias === (string)$name ) {
2245 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2250 * Gets an array of aliased field names
2252 * @param array $fields [ [alias] => field ]
2253 * @return string[] See fieldNameWithAlias()
2255 protected function fieldNamesWithAlias( $fields ) {
2257 foreach ( $fields as $alias => $field ) {
2258 if ( is_numeric( $alias ) ) {
2261 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2268 * Get the aliased table name clause for a FROM clause
2269 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2271 * @param array $tables ( [alias] => table )
2272 * @param array $use_index Same as for select()
2273 * @param array $ignore_index Same as for select()
2274 * @param array $join_conds Same as for select()
2277 protected function tableNamesWithIndexClauseOrJOIN(
2278 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2282 $use_index = (array)$use_index;
2283 $ignore_index = (array)$ignore_index;
2284 $join_conds = (array)$join_conds;
2286 foreach ( $tables as $alias => $table ) {
2287 if ( !is_string( $alias ) ) {
2288 // No alias? Set it equal to the table name
2292 if ( is_array( $table ) ) {
2293 // A parenthesized group
2294 if ( count( $table ) > 1 ) {
2295 $joinedTable = '(' .
2296 $this->tableNamesWithIndexClauseOrJOIN(
2297 $table, $use_index, $ignore_index, $join_conds ) . ')';
2300 $innerTable = reset( $table );
2301 $innerAlias = key( $table );
2302 $joinedTable = $this->tableNameWithAlias(
2304 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2308 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2311 // Is there a JOIN clause for this table?
2312 if ( isset( $join_conds[$alias] ) ) {
2313 list( $joinType, $conds ) = $join_conds[$alias];
2314 $tableClause = $joinType;
2315 $tableClause .= ' ' . $joinedTable;
2316 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2317 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2319 $tableClause .= ' ' . $use;
2322 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2323 $ignore = $this->ignoreIndexClause(
2324 implode( ',', (array)$ignore_index[$alias] ) );
2325 if ( $ignore != '' ) {
2326 $tableClause .= ' ' . $ignore;
2329 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2331 $tableClause .= ' ON (' . $on . ')';
2334 $retJOIN[] = $tableClause;
2335 } elseif ( isset( $use_index[$alias] ) ) {
2336 // Is there an INDEX clause for this table?
2337 $tableClause = $joinedTable;
2338 $tableClause .= ' ' . $this->useIndexClause(
2339 implode( ',', (array)$use_index[$alias] )
2342 $ret[] = $tableClause;
2343 } elseif ( isset( $ignore_index[$alias] ) ) {
2344 // Is there an INDEX clause for this table?
2345 $tableClause = $joinedTable;
2346 $tableClause .= ' ' . $this->ignoreIndexClause(
2347 implode( ',', (array)$ignore_index[$alias] )
2350 $ret[] = $tableClause;
2352 $tableClause = $joinedTable;
2354 $ret[] = $tableClause;
2358 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2359 $implicitJoins = $ret ?
implode( ',', $ret ) : "";
2360 $explicitJoins = $retJOIN ?
implode( ' ', $retJOIN ) : "";
2362 // Compile our final table clause
2363 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2367 * Allows for index remapping in queries where this is not consistent across DBMS
2369 * @param string $index
2372 protected function indexName( $index ) {
2373 return isset( $this->indexAliases
[$index] )
2374 ?
$this->indexAliases
[$index]
2378 public function addQuotes( $s ) {
2379 if ( $s instanceof Blob
) {
2382 if ( $s === null ) {
2384 } elseif ( is_bool( $s ) ) {
2387 # This will also quote numeric values. This should be harmless,
2388 # and protects against weird problems that occur when they really
2389 # _are_ strings such as article titles and string->number->string
2390 # conversion is not 1:1.
2391 return "'" . $this->strencode( $s ) . "'";
2396 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2397 * MySQL uses `backticks` while basically everything else uses double quotes.
2398 * Since MySQL is the odd one out here the double quotes are our generic
2399 * and we implement backticks in DatabaseMysqlBase.
2404 public function addIdentifierQuotes( $s ) {
2405 return '"' . str_replace( '"', '""', $s ) . '"';
2409 * Returns if the given identifier looks quoted or not according to
2410 * the database convention for quoting identifiers .
2412 * @note Do not use this to determine if untrusted input is safe.
2413 * A malicious user can trick this function.
2414 * @param string $name
2417 public function isQuotedIdentifier( $name ) {
2418 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2423 * @param string $escapeChar
2426 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2427 return str_replace( [ $escapeChar, '%', '_' ],
2428 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2432 public function buildLike() {
2433 $params = func_get_args();
2435 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2436 $params = $params[0];
2441 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2442 // may escape backslashes, creating problems of double escaping. The `
2443 // character has good cross-DBMS compatibility, avoiding special operators
2444 // in MS SQL like ^ and %
2447 foreach ( $params as $value ) {
2448 if ( $value instanceof LikeMatch
) {
2449 $s .= $value->toString();
2451 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2456 $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2459 public function anyChar() {
2460 return new LikeMatch( '_' );
2463 public function anyString() {
2464 return new LikeMatch( '%' );
2467 public function nextSequenceValue( $seqName ) {
2472 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2473 * is only needed because a) MySQL must be as efficient as possible due to
2474 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2475 * which index to pick. Anyway, other databases might have different
2476 * indexes on a given table. So don't bother overriding this unless you're
2478 * @param string $index
2481 public function useIndexClause( $index ) {
2486 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2487 * is only needed because a) MySQL must be as efficient as possible due to
2488 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2489 * which index to pick. Anyway, other databases might have different
2490 * indexes on a given table. So don't bother overriding this unless you're
2492 * @param string $index
2495 public function ignoreIndexClause( $index ) {
2499 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2500 if ( count( $rows ) == 0 ) {
2505 if ( !is_array( reset( $rows ) ) ) {
2510 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2511 $affectedRowCount = 0;
2512 foreach ( $rows as $row ) {
2513 // Delete rows which collide with this one
2514 $indexWhereClauses = [];
2515 foreach ( $uniqueIndexes as $index ) {
2516 $indexColumns = (array)$index;
2517 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2518 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2519 throw new DBUnexpectedError(
2521 'New record does not provide all values for unique key (' .
2522 implode( ', ', $indexColumns ) . ')'
2524 } elseif ( in_array( null, $indexRowValues, true ) ) {
2525 throw new DBUnexpectedError(
2527 'New record has a null value for unique key (' .
2528 implode( ', ', $indexColumns ) . ')'
2531 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2534 if ( $indexWhereClauses ) {
2535 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2536 $affectedRowCount +
= $this->affectedRows();
2539 // Now insert the row
2540 $this->insert( $table, $row, $fname );
2541 $affectedRowCount +
= $this->affectedRows();
2543 $this->endAtomic( $fname );
2544 $this->affectedRowCount
= $affectedRowCount;
2545 } catch ( Exception
$e ) {
2546 $this->cancelAtomic( $fname );
2552 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2555 * @param string $table Table name
2556 * @param array|string $rows Row(s) to insert
2557 * @param string $fname Caller function name
2559 * @return ResultWrapper
2561 protected function nativeReplace( $table, $rows, $fname ) {
2562 $table = $this->tableName( $table );
2565 if ( !is_array( reset( $rows ) ) ) {
2569 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2572 foreach ( $rows as $row ) {
2579 $sql .= '(' . $this->makeList( $row ) . ')';
2582 return $this->query( $sql, $fname );
2585 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2588 if ( !count( $rows ) ) {
2589 return true; // nothing to do
2592 if ( !is_array( reset( $rows ) ) ) {
2596 if ( count( $uniqueIndexes ) ) {
2597 $clauses = []; // list WHERE clauses that each identify a single row
2598 foreach ( $rows as $row ) {
2599 foreach ( $uniqueIndexes as $index ) {
2600 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2601 $rowKey = []; // unique key to this row
2602 foreach ( $index as $column ) {
2603 $rowKey[$column] = $row[$column];
2605 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2608 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2613 $affectedRowCount = 0;
2615 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2616 # Update any existing conflicting row(s)
2617 if ( $where !== false ) {
2618 $ok = $this->update( $table, $set, $where, $fname );
2619 $affectedRowCount +
= $this->affectedRows();
2623 # Now insert any non-conflicting row(s)
2624 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2625 $affectedRowCount +
= $this->affectedRows();
2626 $this->endAtomic( $fname );
2627 $this->affectedRowCount
= $affectedRowCount;
2628 } catch ( Exception
$e ) {
2629 $this->cancelAtomic( $fname );
2636 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2640 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2643 $delTable = $this->tableName( $delTable );
2644 $joinTable = $this->tableName( $joinTable );
2645 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2646 if ( $conds != '*' ) {
2647 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2651 $this->query( $sql, $fname );
2654 public function textFieldSize( $table, $field ) {
2655 $table = $this->tableName( $table );
2656 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2657 $res = $this->query( $sql, __METHOD__
);
2658 $row = $this->fetchObject( $res );
2662 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2671 public function delete( $table, $conds, $fname = __METHOD__
) {
2673 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2676 $table = $this->tableName( $table );
2677 $sql = "DELETE FROM $table";
2679 if ( $conds != '*' ) {
2680 if ( is_array( $conds ) ) {
2681 $conds = $this->makeList( $conds, self
::LIST_AND
);
2683 $sql .= ' WHERE ' . $conds;
2686 return $this->query( $sql, $fname );
2689 final public function insertSelect(
2690 $destTable, $srcTable, $varMap, $conds,
2691 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2693 static $hints = [ 'NO_AUTO_COLUMNS' ];
2695 $insertOptions = (array)$insertOptions;
2696 $selectOptions = (array)$selectOptions;
2698 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2699 // For massive migrations with downtime, we don't want to select everything
2700 // into memory and OOM, so do all this native on the server side if possible.
2701 return $this->nativeInsertSelect(
2707 array_diff( $insertOptions, $hints ),
2713 return $this->nonNativeInsertSelect(
2719 array_diff( $insertOptions, $hints ),
2726 * @param array $insertOptions INSERT options
2727 * @param array $selectOptions SELECT options
2728 * @return bool Whether an INSERT SELECT with these options will be replication safe
2731 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2736 * Implementation of insertSelect() based on select() and insert()
2738 * @see IDatabase::insertSelect()
2740 * @param string $destTable
2741 * @param string|array $srcTable
2742 * @param array $varMap
2743 * @param array $conds
2744 * @param string $fname
2745 * @param array $insertOptions
2746 * @param array $selectOptions
2747 * @param array $selectJoinConds
2750 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2751 $fname = __METHOD__
,
2752 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2754 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2755 // on only the master (without needing row-based-replication). It also makes it easy to
2756 // know how big the INSERT is going to be.
2758 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2759 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2761 $selectOptions[] = 'FOR UPDATE';
2762 $res = $this->select(
2763 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2770 $affectedRowCount = 0;
2771 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
2774 foreach ( $res as $row ) {
2775 $rows[] = (array)$row;
2777 // Avoid inserts that are too huge
2778 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2779 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2783 $affectedRowCount +
= $this->affectedRows();
2787 if ( $rows && $ok ) {
2788 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2790 $affectedRowCount +
= $this->affectedRows();
2794 $this->endAtomic( $fname );
2795 $this->affectedRowCount
= $affectedRowCount;
2797 $this->cancelAtomic( $fname );
2800 } catch ( Exception
$e ) {
2801 $this->cancelAtomic( $fname );
2807 * Native server-side implementation of insertSelect() for situations where
2808 * we don't want to select everything into memory
2810 * @see IDatabase::insertSelect()
2811 * @param string $destTable
2812 * @param string|array $srcTable
2813 * @param array $varMap
2814 * @param array $conds
2815 * @param string $fname
2816 * @param array $insertOptions
2817 * @param array $selectOptions
2818 * @param array $selectJoinConds
2821 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2822 $fname = __METHOD__
,
2823 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2825 $destTable = $this->tableName( $destTable );
2827 if ( !is_array( $insertOptions ) ) {
2828 $insertOptions = [ $insertOptions ];
2831 $insertOptions = $this->makeInsertOptions( $insertOptions );
2833 $selectSql = $this->selectSQLText(
2835 array_values( $varMap ),
2842 $sql = "INSERT $insertOptions" .
2843 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2846 return $this->query( $sql, $fname );
2850 * Construct a LIMIT query with optional offset. This is used for query
2851 * pages. The SQL should be adjusted so that only the first $limit rows
2852 * are returned. If $offset is provided as well, then the first $offset
2853 * rows should be discarded, and the next $limit rows should be returned.
2854 * If the result of the query is not ordered, then the rows to be returned
2855 * are theoretically arbitrary.
2857 * $sql is expected to be a SELECT, if that makes a difference.
2859 * The version provided by default works in MySQL and SQLite. It will very
2860 * likely need to be overridden for most other DBMSes.
2862 * @param string $sql SQL query we will append the limit too
2863 * @param int $limit The SQL limit
2864 * @param int|bool $offset The SQL offset (default false)
2865 * @throws DBUnexpectedError
2868 public function limitResult( $sql, $limit, $offset = false ) {
2869 if ( !is_numeric( $limit ) ) {
2870 throw new DBUnexpectedError( $this,
2871 "Invalid non-numeric limit passed to limitResult()\n" );
2874 return "$sql LIMIT "
2875 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2879 public function unionSupportsOrderAndLimit() {
2880 return true; // True for almost every DB supported
2883 public function unionQueries( $sqls, $all ) {
2884 $glue = $all ?
') UNION ALL (' : ') UNION (';
2886 return '(' . implode( $glue, $sqls ) . ')';
2889 public function unionConditionPermutations(
2890 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2891 $options = [], $join_conds = []
2893 // First, build the Cartesian product of $permute_conds
2895 foreach ( $permute_conds as $field => $values ) {
2897 // Skip empty $values
2900 $values = array_unique( $values ); // For sanity
2902 foreach ( $conds as $cond ) {
2903 foreach ( $values as $value ) {
2904 $cond[$field] = $value;
2905 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2911 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2913 // If there's just one condition and no subordering, hand off to
2914 // selectSQLText directly.
2915 if ( count( $conds ) === 1 &&
2916 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2918 return $this->selectSQLText(
2919 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2923 // Otherwise, we need to pull out the order and limit to apply after
2924 // the union. Then build the SQL queries for each set of conditions in
2925 // $conds. Then union them together (using UNION ALL, because the
2926 // product *should* already be distinct).
2927 $orderBy = $this->makeOrderBy( $options );
2928 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2929 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2930 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2931 if ( !$this->unionSupportsOrderAndLimit() ) {
2932 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2934 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2935 $options['ORDER BY'] = $options['INNER ORDER BY'];
2937 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2938 // We need to increase the limit by the offset rather than
2939 // using the offset directly, otherwise it'll skip incorrectly
2940 // in the subqueries.
2941 $options['LIMIT'] = $limit +
$offset;
2942 unset( $options['OFFSET'] );
2947 foreach ( $conds as $cond ) {
2948 $sqls[] = $this->selectSQLText(
2949 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2952 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2953 if ( $limit !== null ) {
2954 $sql = $this->limitResult( $sql, $limit, $offset );
2960 public function conditional( $cond, $trueVal, $falseVal ) {
2961 if ( is_array( $cond ) ) {
2962 $cond = $this->makeList( $cond, self
::LIST_AND
);
2965 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2968 public function strreplace( $orig, $old, $new ) {
2969 return "REPLACE({$orig}, {$old}, {$new})";
2972 public function getServerUptime() {
2976 public function wasDeadlock() {
2980 public function wasLockTimeout() {
2984 public function wasConnectionLoss() {
2985 return $this->wasConnectionError( $this->lastErrno() );
2988 public function wasReadOnlyError() {
2992 public function wasErrorReissuable() {
2994 $this->wasDeadlock() ||
2995 $this->wasLockTimeout() ||
2996 $this->wasConnectionLoss()
3001 * Do not use this method outside of Database/DBError classes
3003 * @param int|string $errno
3004 * @return bool Whether the given query error was a connection drop
3006 public function wasConnectionError( $errno ) {
3010 public function deadlockLoop() {
3011 $args = func_get_args();
3012 $function = array_shift( $args );
3013 $tries = self
::DEADLOCK_TRIES
;
3015 $this->begin( __METHOD__
);
3018 /** @var Exception $e */
3022 $retVal = call_user_func_array( $function, $args );
3024 } catch ( DBQueryError
$e ) {
3025 if ( $this->wasDeadlock() ) {
3026 // Retry after a randomized delay
3027 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3029 // Throw the error back up
3033 } while ( --$tries > 0 );
3035 if ( $tries <= 0 ) {
3036 // Too many deadlocks; give up
3037 $this->rollback( __METHOD__
);
3040 $this->commit( __METHOD__
);
3046 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3047 # Real waits are implemented in the subclass.
3051 public function getReplicaPos() {
3056 public function getMasterPos() {
3061 public function serverIsReadOnly() {
3065 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
3066 if ( !$this->trxLevel
) {
3067 throw new DBUnexpectedError( $this, "No transaction is active." );
3069 $this->trxEndCallbacks
[] = [ $callback, $fname ];
3072 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
3073 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
3074 if ( !$this->trxLevel
) {
3075 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
3079 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
3080 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
3081 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
3082 // an implicit commit of all peer databases. This is true even if a transaction has
3083 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
3084 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
3086 // No transaction is active nor will start implicitly, so make one for this callback
3087 $this->startAtomic( __METHOD__
, self
::ATOMIC_CANCELABLE
);
3089 call_user_func( $callback );
3090 $this->endAtomic( __METHOD__
);
3091 } catch ( Exception
$e ) {
3092 $this->cancelAtomic( __METHOD__
);
3098 final public function setTransactionListener( $name, callable
$callback = null ) {
3100 $this->trxRecurringCallbacks
[$name] = $callback;
3102 unset( $this->trxRecurringCallbacks
[$name] );
3107 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
3109 * This method should not be used outside of Database/LoadBalancer
3111 * @param bool $suppress
3114 final public function setTrxEndCallbackSuppression( $suppress ) {
3115 $this->trxEndCallbacksSuppressed
= $suppress;
3119 * Actually run and consume any "on transaction idle/resolution" callbacks.
3121 * This method should not be used outside of Database/LoadBalancer
3123 * @param int $trigger IDatabase::TRIGGER_* constant
3127 public function runOnTransactionIdleCallbacks( $trigger ) {
3128 if ( $this->trxEndCallbacksSuppressed
) {
3132 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
3133 /** @var Exception $e */
3134 $e = null; // first exception
3135 do { // callbacks may add callbacks :)
3136 $callbacks = array_merge(
3137 $this->trxIdleCallbacks
,
3138 $this->trxEndCallbacks
// include "transaction resolution" callbacks
3140 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
3141 $this->trxEndCallbacks
= []; // consumed (recursion guard)
3142 foreach ( $callbacks as $callback ) {
3144 list( $phpCallback ) = $callback;
3145 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
3146 call_user_func_array( $phpCallback, [ $trigger ] );
3148 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
3150 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
3152 } catch ( Exception
$ex ) {
3153 call_user_func( $this->errorLogger
, $ex );
3155 // Some callbacks may use startAtomic/endAtomic, so make sure
3156 // their transactions are ended so other callbacks don't fail
3157 if ( $this->trxLevel() ) {
3158 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
3162 } while ( count( $this->trxIdleCallbacks
) );
3164 if ( $e instanceof Exception
) {
3165 throw $e; // re-throw any first exception
3170 * Actually run and consume any "on transaction pre-commit" callbacks.
3172 * This method should not be used outside of Database/LoadBalancer
3177 public function runOnTransactionPreCommitCallbacks() {
3178 $e = null; // first exception
3179 do { // callbacks may add callbacks :)
3180 $callbacks = $this->trxPreCommitCallbacks
;
3181 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
3182 foreach ( $callbacks as $callback ) {
3184 list( $phpCallback ) = $callback;
3185 call_user_func( $phpCallback );
3186 } catch ( Exception
$ex ) {
3187 call_user_func( $this->errorLogger
, $ex );
3191 } while ( count( $this->trxPreCommitCallbacks
) );
3193 if ( $e instanceof Exception
) {
3194 throw $e; // re-throw any first exception
3199 * Actually run any "transaction listener" callbacks.
3201 * This method should not be used outside of Database/LoadBalancer
3203 * @param int $trigger IDatabase::TRIGGER_* constant
3207 public function runTransactionListenerCallbacks( $trigger ) {
3208 if ( $this->trxEndCallbacksSuppressed
) {
3212 /** @var Exception $e */
3213 $e = null; // first exception
3215 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
3217 $phpCallback( $trigger, $this );
3218 } catch ( Exception
$ex ) {
3219 call_user_func( $this->errorLogger
, $ex );
3224 if ( $e instanceof Exception
) {
3225 throw $e; // re-throw any first exception
3230 * Create a savepoint
3232 * This is used internally to implement atomic sections. It should not be
3236 * @param string $identifier Identifier for the savepoint
3237 * @param string $fname Calling function name
3239 protected function doSavepoint( $identifier, $fname ) {
3240 $this->query( 'SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3244 * Release a savepoint
3246 * This is used internally to implement atomic sections. It should not be
3250 * @param string $identifier Identifier for the savepoint
3251 * @param string $fname Calling function name
3253 protected function doReleaseSavepoint( $identifier, $fname ) {
3254 $this->query( 'RELEASE SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3258 * Rollback to a savepoint
3260 * This is used internally to implement atomic sections. It should not be
3264 * @param string $identifier Identifier for the savepoint
3265 * @param string $fname Calling function name
3267 protected function doRollbackToSavepoint( $identifier, $fname ) {
3268 $this->query( 'ROLLBACK TO SAVEPOINT ' . $this->addIdentifierQuotes( $identifier ), $fname );
3271 final public function startAtomic(
3272 $fname = __METHOD__
, $cancelable = self
::ATOMIC_NOT_CANCELABLE
3274 $savepointId = $cancelable === self
::ATOMIC_CANCELABLE ?
'n/a' : null;
3275 if ( !$this->trxLevel
) {
3276 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
3277 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3278 // in all changes being in one transaction to keep requests transactional.
3279 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3280 $this->trxAutomaticAtomic
= true;
3282 } elseif ( $cancelable === self
::ATOMIC_CANCELABLE
) {
3283 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3284 if ( strlen( $savepointId ) > 30 ) { // 30 == Oracle's identifier length limit (pre 12c)
3285 $this->queryLogger
->warning(
3286 'There have been an excessively large number of atomic sections in a transaction'
3287 . " started by $this->trxFname, reusing IDs (at $fname)",
3288 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ]
3290 $this->trxAtomicCounter
= 0;
3291 $savepointId = 'wikimedia_rdbms_atomic' . ++
$this->trxAtomicCounter
;
3293 $this->doSavepoint( $savepointId, $fname );
3296 $this->trxAtomicLevels
[] = [ $fname, $savepointId ];
3299 final public function endAtomic( $fname = __METHOD__
) {
3300 if ( !$this->trxLevel
) {
3301 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3304 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3305 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3306 if ( $savedFname !== $fname ) {
3307 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3310 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3311 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3312 } elseif ( $savepointId && $savepointId !== 'n/a' ) {
3313 $this->doReleaseSavepoint( $savepointId, $fname );
3317 final public function cancelAtomic( $fname = __METHOD__
) {
3318 if ( !$this->trxLevel
) {
3319 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3322 list( $savedFname, $savepointId ) = $this->trxAtomicLevels
3323 ?
array_pop( $this->trxAtomicLevels
) : [ null, null ];
3324 if ( $savedFname !== $fname ) {
3325 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3327 if ( !$savepointId ) {
3328 throw new DBUnexpectedError( $this, "Uncancelable atomic section canceled (got $fname)." );
3331 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3332 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3333 } elseif ( $savepointId !== 'n/a' ) {
3334 $this->doRollbackToSavepoint( $savepointId, $fname );
3337 $this->affectedRowCount
= 0; // for the sake of consistency
3340 final public function doAtomicSection( $fname, callable
$callback ) {
3341 $this->startAtomic( $fname, self
::ATOMIC_CANCELABLE
);
3343 $res = call_user_func_array( $callback, [ $this, $fname ] );
3344 } catch ( Exception
$e ) {
3345 $this->cancelAtomic( $fname );
3348 $this->endAtomic( $fname );
3353 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3354 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3355 if ( $this->trxLevel
) {
3356 if ( $this->trxAtomicLevels
) {
3357 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3358 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3360 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3361 throw new DBUnexpectedError( $this, $msg );
3362 } elseif ( !$this->trxAutomatic
) {
3363 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3364 throw new DBUnexpectedError( $this, $msg );
3366 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3367 throw new DBUnexpectedError( $this, $msg );
3369 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3370 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3371 throw new DBUnexpectedError( $this, $msg );
3374 // Avoid fatals if close() was called
3375 $this->assertOpen();
3377 $this->doBegin( $fname );
3378 $this->trxAtomicCounter
= 0;
3379 $this->trxTimestamp
= microtime( true );
3380 $this->trxFname
= $fname;
3381 $this->trxDoneWrites
= false;
3382 $this->trxAutomaticAtomic
= false;
3383 $this->trxAtomicLevels
= [];
3384 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3385 $this->trxWriteDuration
= 0.0;
3386 $this->trxWriteQueryCount
= 0;
3387 $this->trxWriteAffectedRows
= 0;
3388 $this->trxWriteAdjDuration
= 0.0;
3389 $this->trxWriteAdjQueryCount
= 0;
3390 $this->trxWriteCallers
= [];
3391 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3392 // Get an estimate of the replica DB lag before then, treating estimate staleness
3393 // as lag itself just to be safe
3394 $status = $this->getApproximateLagStatus();
3395 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3396 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3397 // caller will think its OK to muck around with the transaction just because startAtomic()
3398 // has not yet completed (e.g. setting trxAtomicLevels).
3399 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3403 * Issues the BEGIN command to the database server.
3405 * @see Database::begin()
3406 * @param string $fname
3408 protected function doBegin( $fname ) {
3409 $this->query( 'BEGIN', $fname );
3410 $this->trxLevel
= 1;
3413 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3414 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3415 // There are still atomic sections open. This cannot be ignored
3416 $levels = array_reduce( $this->trxAtomicLevels
, function ( $accum, $v ) {
3417 return $accum === null ?
$v[0] : "$accum, " . $v[0];
3419 throw new DBUnexpectedError(
3421 "$fname: Got COMMIT while atomic sections $levels are still open."
3425 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3426 if ( !$this->trxLevel
) {
3427 return; // nothing to do
3428 } elseif ( !$this->trxAutomatic
) {
3429 throw new DBUnexpectedError(
3431 "$fname: Flushing an explicit transaction, getting out of sync."
3435 if ( !$this->trxLevel
) {
3436 $this->queryLogger
->error(
3437 "$fname: No transaction to commit, something got out of sync." );
3438 return; // nothing to do
3439 } elseif ( $this->trxAutomatic
) {
3440 throw new DBUnexpectedError(
3442 "$fname: Expected mass commit of all peer transactions (DBO_TRX set)."
3447 // Avoid fatals if close() was called
3448 $this->assertOpen();
3450 $this->runOnTransactionPreCommitCallbacks();
3451 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3452 $this->doCommit( $fname );
3453 if ( $this->trxDoneWrites
) {
3454 $this->lastWriteTime
= microtime( true );
3455 $this->trxProfiler
->transactionWritingOut(
3460 $this->trxWriteAffectedRows
3464 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3465 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3469 * Issues the COMMIT command to the database server.
3471 * @see Database::commit()
3472 * @param string $fname
3474 protected function doCommit( $fname ) {
3475 if ( $this->trxLevel
) {
3476 $this->query( 'COMMIT', $fname );
3477 $this->trxLevel
= 0;
3481 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3482 $trxActive = $this->trxLevel
;
3484 if ( $flush !== self
::FLUSHING_INTERNAL
&& $flush !== self
::FLUSHING_ALL_PEERS
) {
3485 if ( $this->getFlag( self
::DBO_TRX
) ) {
3486 throw new DBUnexpectedError(
3488 "$fname: Expected mass rollback of all peer transactions (DBO_TRX set)."
3494 // Avoid fatals if close() was called
3495 $this->assertOpen();
3497 $this->doRollback( $fname );
3498 $this->trxAtomicLevels
= [];
3499 if ( $this->trxDoneWrites
) {
3500 $this->trxProfiler
->transactionWritingOut(
3508 // Clear any commit-dependant callbacks. They might even be present
3509 // only due to transaction rounds, with no SQL transaction being active
3510 $this->trxIdleCallbacks
= [];
3511 $this->trxPreCommitCallbacks
= [];
3515 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3516 } catch ( Exception
$e ) {
3517 // already logged; finish and let LoadBalancer move on during mass-rollback
3520 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3521 } catch ( Exception
$e ) {
3522 // already logged; let LoadBalancer move on during mass-rollback
3525 $this->affectedRowCount
= 0; // for the sake of consistency
3530 * Issues the ROLLBACK command to the database server.
3532 * @see Database::rollback()
3533 * @param string $fname
3535 protected function doRollback( $fname ) {
3536 if ( $this->trxLevel
) {
3537 # Disconnects cause rollback anyway, so ignore those errors
3538 $ignoreErrors = true;
3539 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3540 $this->trxLevel
= 0;
3544 public function flushSnapshot( $fname = __METHOD__
) {
3545 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3546 // This only flushes transactions to clear snapshots, not to write data
3547 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3548 throw new DBUnexpectedError(
3550 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3554 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3557 public function explicitTrxActive() {
3558 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3561 public function duplicateTableStructure(
3562 $oldName, $newName, $temporary = false, $fname = __METHOD__
3564 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3567 public function listTables( $prefix = null, $fname = __METHOD__
) {
3568 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3571 public function listViews( $prefix = null, $fname = __METHOD__
) {
3572 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3575 public function timestamp( $ts = 0 ) {
3576 $t = new ConvertibleTimestamp( $ts );
3577 // Let errors bubble up to avoid putting garbage in the DB
3578 return $t->getTimestamp( TS_MW
);
3581 public function timestampOrNull( $ts = null ) {
3582 if ( is_null( $ts ) ) {
3585 return $this->timestamp( $ts );
3589 public function affectedRows() {
3590 return ( $this->affectedRowCount
=== null )
3591 ?
$this->fetchAffectedRowCount() // default to driver value
3592 : $this->affectedRowCount
;
3596 * @return int Number of retrieved rows according to the driver
3598 abstract protected function fetchAffectedRowCount();
3601 * Take the result from a query, and wrap it in a ResultWrapper if
3602 * necessary. Boolean values are passed through as is, to indicate success
3603 * of write queries or failure.
3605 * Once upon a time, Database::query() returned a bare MySQL result
3606 * resource, and it was necessary to call this function to convert it to
3607 * a wrapper. Nowadays, raw database objects are never exposed to external
3608 * callers, so this is unnecessary in external code.
3610 * @param bool|ResultWrapper|resource|object $result
3611 * @return bool|ResultWrapper
3613 protected function resultObject( $result ) {
3616 } elseif ( $result instanceof ResultWrapper
) {
3618 } elseif ( $result === true ) {
3619 // Successful write query
3622 return new ResultWrapper( $this, $result );
3626 public function ping( &$rtt = null ) {
3627 // Avoid hitting the server if it was hit recently
3628 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3629 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3630 $rtt = $this->rttEstimate
;
3631 return true; // don't care about $rtt
3635 // This will reconnect if possible or return false if not
3636 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3637 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3638 $this->restoreFlags( self
::RESTORE_PRIOR
);
3641 $rtt = $this->rttEstimate
;
3648 * Close existing database connection and open a new connection
3650 * @return bool True if new connection is opened successfully, false if error
3652 protected function reconnect() {
3653 $this->closeConnection();
3654 $this->opened
= false;
3655 $this->conn
= false;
3657 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3658 $this->lastPing
= microtime( true );
3660 } catch ( DBConnectionError
$e ) {
3667 public function getSessionLagStatus() {
3668 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3672 * Get the replica DB lag when the current transaction started
3674 * This is useful when transactions might use snapshot isolation
3675 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3676 * is this lag plus transaction duration. If they don't, it is still
3677 * safe to be pessimistic. This returns null if there is no transaction.
3679 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3682 protected function getTransactionLagStatus() {
3683 return $this->trxLevel
3684 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3689 * Get a replica DB lag estimate for this server
3691 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3694 protected function getApproximateLagStatus() {
3696 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3697 'since' => microtime( true )
3702 * Merge the result of getSessionLagStatus() for several DBs
3703 * using the most pessimistic values to estimate the lag of
3704 * any data derived from them in combination
3706 * This is information is useful for caching modules
3708 * @see WANObjectCache::set()
3709 * @see WANObjectCache::getWithSetCallback()
3711 * @param IDatabase $db1
3712 * @param IDatabase $db2 [optional]
3713 * @return array Map of values:
3714 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3715 * - since: oldest UNIX timestamp of any of the DB lag estimates
3716 * - pending: whether any of the DBs have uncommitted changes
3720 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3721 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3722 foreach ( func_get_args() as $db ) {
3723 /** @var IDatabase $db */
3724 $status = $db->getSessionLagStatus();
3725 if ( $status['lag'] === false ) {
3726 $res['lag'] = false;
3727 } elseif ( $res['lag'] !== false ) {
3728 $res['lag'] = max( $res['lag'], $status['lag'] );
3730 $res['since'] = min( $res['since'], $status['since'] );
3731 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3737 public function getLag() {
3741 public function maxListLen() {
3745 public function encodeBlob( $b ) {
3749 public function decodeBlob( $b ) {
3750 if ( $b instanceof Blob
) {
3756 public function setSessionOptions( array $options ) {
3759 public function sourceFile(
3761 callable
$lineCallback = null,
3762 callable
$resultCallback = null,
3764 callable
$inputCallback = null
3766 Wikimedia\
suppressWarnings();
3767 $fp = fopen( $filename, 'r' );
3768 Wikimedia\restoreWarnings
();
3770 if ( false === $fp ) {
3771 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3775 $fname = __METHOD__
. "( $filename )";
3779 $error = $this->sourceStream(
3780 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3781 } catch ( Exception
$e ) {
3791 public function setSchemaVars( $vars ) {
3792 $this->schemaVars
= $vars;
3795 public function sourceStream(
3797 callable
$lineCallback = null,
3798 callable
$resultCallback = null,
3799 $fname = __METHOD__
,
3800 callable
$inputCallback = null
3802 $delimiterReset = new ScopedCallback(
3803 function ( $delimiter ) {
3804 $this->delimiter
= $delimiter;
3806 [ $this->delimiter
]
3810 while ( !feof( $fp ) ) {
3811 if ( $lineCallback ) {
3812 call_user_func( $lineCallback );
3815 $line = trim( fgets( $fp ) );
3817 if ( $line == '' ) {
3821 if ( '-' == $line[0] && '-' == $line[1] ) {
3829 $done = $this->streamStatementEnd( $cmd, $line );
3833 if ( $done ||
feof( $fp ) ) {
3834 $cmd = $this->replaceVars( $cmd );
3836 if ( $inputCallback ) {
3837 $callbackResult = call_user_func( $inputCallback, $cmd );
3839 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3840 $cmd = $callbackResult;
3845 $res = $this->query( $cmd, $fname );
3847 if ( $resultCallback ) {
3848 call_user_func( $resultCallback, $res, $this );
3851 if ( false === $res ) {
3852 $err = $this->lastError();
3854 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3861 ScopedCallback
::consume( $delimiterReset );
3866 * Called by sourceStream() to check if we've reached a statement end
3868 * @param string &$sql SQL assembled so far
3869 * @param string &$newLine New line about to be added to $sql
3870 * @return bool Whether $newLine contains end of the statement
3872 public function streamStatementEnd( &$sql, &$newLine ) {
3873 if ( $this->delimiter
) {
3875 $newLine = preg_replace(
3876 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3877 if ( $newLine != $prev ) {
3886 * Database independent variable replacement. Replaces a set of variables
3887 * in an SQL statement with their contents as given by $this->getSchemaVars().
3889 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3891 * - '{$var}' should be used for text and is passed through the database's
3893 * - `{$var}` should be used for identifiers (e.g. table and database names).
3894 * It is passed through the database's addIdentifierQuotes method which
3895 * can be overridden if the database uses something other than backticks.
3896 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3897 * database's tableName method.
3898 * - / *i* / passes the name that follows through the database's indexName method.
3899 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3900 * its use should be avoided. In 1.24 and older, string encoding was applied.
3902 * @param string $ins SQL statement to replace variables in
3903 * @return string The new SQL statement with variables replaced
3905 protected function replaceVars( $ins ) {
3906 $vars = $this->getSchemaVars();
3907 return preg_replace_callback(
3909 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3910 \'\{\$ (\w+) }\' | # 3. addQuotes
3911 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3912 /\*\$ (\w+) \*/ # 5. leave unencoded
3914 function ( $m ) use ( $vars ) {
3915 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3916 // check for both nonexistent keys *and* the empty string.
3917 if ( isset( $m[1] ) && $m[1] !== '' ) {
3918 if ( $m[1] === 'i' ) {
3919 return $this->indexName( $m[2] );
3921 return $this->tableName( $m[2] );
3923 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3924 return $this->addQuotes( $vars[$m[3]] );
3925 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3926 return $this->addIdentifierQuotes( $vars[$m[4]] );
3927 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3928 return $vars[$m[5]];
3938 * Get schema variables. If none have been set via setSchemaVars(), then
3939 * use some defaults from the current object.
3943 protected function getSchemaVars() {
3944 if ( $this->schemaVars
) {
3945 return $this->schemaVars
;
3947 return $this->getDefaultSchemaVars();
3952 * Get schema variables to use if none have been set via setSchemaVars().
3954 * Override this in derived classes to provide variables for tables.sql
3955 * and SQL patch files.
3959 protected function getDefaultSchemaVars() {
3963 public function lockIsFree( $lockName, $method ) {
3964 // RDBMs methods for checking named locks may or may not count this thread itself.
3965 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3966 // the behavior choosen by the interface for this method.
3967 return !isset( $this->namedLocksHeld
[$lockName] );
3970 public function lock( $lockName, $method, $timeout = 5 ) {
3971 $this->namedLocksHeld
[$lockName] = 1;
3976 public function unlock( $lockName, $method ) {
3977 unset( $this->namedLocksHeld
[$lockName] );
3982 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3983 if ( $this->writesOrCallbacksPending() ) {
3984 // This only flushes transactions to clear snapshots, not to write data
3985 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3986 throw new DBUnexpectedError(
3988 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3992 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3996 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3997 if ( $this->trxLevel() ) {
3998 // There is a good chance an exception was thrown, causing any early return
3999 // from the caller. Let any error handler get a chance to issue rollback().
4000 // If there isn't one, let the error bubble up and trigger server-side rollback.
4001 $this->onTransactionResolution(
4002 function () use ( $lockKey, $fname ) {
4003 $this->unlock( $lockKey, $fname );
4008 $this->unlock( $lockKey, $fname );
4012 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
4017 public function namedLocksEnqueue() {
4021 public function tableLocksHaveTransactionScope() {
4025 final public function lockTables( array $read, array $write, $method ) {
4026 if ( $this->writesOrCallbacksPending() ) {
4027 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
4030 if ( $this->tableLocksHaveTransactionScope() ) {
4031 $this->startAtomic( $method );
4034 return $this->doLockTables( $read, $write, $method );
4038 * Helper function for lockTables() that handles the actual table locking
4040 * @param array $read Array of tables to lock for read access
4041 * @param array $write Array of tables to lock for write access
4042 * @param string $method Name of caller
4045 protected function doLockTables( array $read, array $write, $method ) {
4049 final public function unlockTables( $method ) {
4050 if ( $this->tableLocksHaveTransactionScope() ) {
4051 $this->endAtomic( $method );
4053 return true; // locks released on COMMIT/ROLLBACK
4056 return $this->doUnlockTables( $method );
4060 * Helper function for unlockTables() that handles the actual table unlocking
4062 * @param string $method Name of caller
4065 protected function doUnlockTables( $method ) {
4071 * @param string $tableName
4072 * @param string $fName
4073 * @return bool|ResultWrapper
4076 public function dropTable( $tableName, $fName = __METHOD__
) {
4077 if ( !$this->tableExists( $tableName, $fName ) ) {
4080 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
4082 return $this->query( $sql, $fName );
4085 public function getInfinity() {
4089 public function encodeExpiry( $expiry ) {
4090 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4091 ?
$this->getInfinity()
4092 : $this->timestamp( $expiry );
4095 public function decodeExpiry( $expiry, $format = TS_MW
) {
4096 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
4100 return ConvertibleTimestamp
::convert( $format, $expiry );
4103 public function setBigSelects( $value = true ) {
4107 public function isReadOnly() {
4108 return ( $this->getReadOnlyReason() !== false );
4112 * @return string|bool Reason this DB is read-only or false if it is not
4114 protected function getReadOnlyReason() {
4115 $reason = $this->getLBInfo( 'readOnlyReason' );
4117 return is_string( $reason ) ?
$reason : false;
4120 public function setTableAliases( array $aliases ) {
4121 $this->tableAliases
= $aliases;
4124 public function setIndexAliases( array $aliases ) {
4125 $this->indexAliases
= $aliases;
4129 * Get the underlying binding connection handle
4131 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
4132 * This catches broken callers than catch and ignore disconnection exceptions.
4133 * Unlike checking isOpen(), this is safe to call inside of open().
4136 * @throws DBUnexpectedError
4139 protected function getBindingHandle() {
4140 if ( !$this->conn
) {
4141 throw new DBUnexpectedError(
4143 'DB connection was already closed or the connection dropped.'
4154 public function __toString() {
4155 return (string)$this->conn
;
4159 * Make sure that copies do not share the same client binding handle
4160 * @throws DBConnectionError
4162 public function __clone() {
4163 $this->connLogger
->warning(
4164 "Cloning " . static::class . " is not recomended; forking connection:\n" .
4165 ( new RuntimeException() )->getTraceAsString()
4168 if ( $this->isOpen() ) {
4169 // Open a new connection resource without messing with the old one
4170 $this->opened
= false;
4171 $this->conn
= false;
4172 $this->trxEndCallbacks
= []; // don't copy
4173 $this->handleSessionLoss(); // no trx or locks anymore
4174 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
4175 $this->lastPing
= microtime( true );
4180 * Called by serialize. Throw an exception when DB connection is serialized.
4181 * This causes problems on some database engines because the connection is
4182 * not restored on unserialize.
4184 public function __sleep() {
4185 throw new RuntimeException( 'Database serialization may cause problems, since ' .
4186 'the connection is not restored on wakeup.' );
4190 * Run a few simple sanity checks and close dangling connections
4192 public function __destruct() {
4193 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
4194 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
4197 $danglingWriters = $this->pendingWriteAndCallbackCallers();
4198 if ( $danglingWriters ) {
4199 $fnames = implode( ', ', $danglingWriters );
4200 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
4203 if ( $this->conn
) {
4204 // Avoid connection leaks for sanity. Normally, resources close at script completion.
4205 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
4206 Wikimedia\
suppressWarnings();
4207 $this->closeConnection();
4208 Wikimedia\restoreWarnings
();
4209 $this->conn
= false;
4210 $this->opened
= false;
4215 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
4216 class_alias( Database
::class, 'Database' ); // b/c global alias