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 Wikimedia\ScopedCallback
;
31 use Wikimedia\Timestamp\ConvertibleTimestamp
;
35 use InvalidArgumentException
;
40 * Relational database abstraction object
45 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
46 /** Number of times to re-try an operation in case of deadlock */
47 const DEADLOCK_TRIES
= 4;
48 /** Minimum time to wait before retry, in microseconds */
49 const DEADLOCK_DELAY_MIN
= 500000;
50 /** Maximum time to wait before retry */
51 const DEADLOCK_DELAY_MAX
= 1500000;
53 /** How long before it is worth doing a dummy query to test the connection */
55 const PING_QUERY
= 'SELECT 1 AS ping';
57 const TINY_WRITE_SEC
= 0.010;
58 const SLOW_WRITE_SEC
= 0.500;
59 const SMALL_WRITE_ROWS
= 100;
61 /** @var string SQL query */
62 protected $lastQuery = '';
63 /** @var float|bool UNIX timestamp of last write query */
64 protected $lastWriteTime = false;
65 /** @var string|bool */
66 protected $phpError = false;
75 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
76 protected $tableAliases = [];
77 /** @var bool Whether this PHP instance is for a CLI script */
79 /** @var string Agent name for query profiling */
82 /** @var BagOStuff APC cache */
84 /** @var LoggerInterface */
85 protected $connLogger;
86 /** @var LoggerInterface */
87 protected $queryLogger;
88 /** @var callback Error logging callback */
89 protected $errorLogger;
91 /** @var resource|null Database connection */
92 protected $conn = null;
94 protected $opened = false;
96 /** @var array[] List of (callable, method name) */
97 protected $trxIdleCallbacks = [];
98 /** @var array[] List of (callable, method name) */
99 protected $trxPreCommitCallbacks = [];
100 /** @var array[] List of (callable, method name) */
101 protected $trxEndCallbacks = [];
102 /** @var callable[] Map of (name => callable) */
103 protected $trxRecurringCallbacks = [];
104 /** @var bool Whether to suppress triggering of transaction end callbacks */
105 protected $trxEndCallbacksSuppressed = false;
108 protected $tablePrefix = '';
110 protected $schema = '';
114 protected $lbInfo = [];
115 /** @var array|bool */
116 protected $schemaVars = false;
118 protected $sessionVars = [];
119 /** @var array|null */
120 protected $preparedArgs;
121 /** @var string|bool|null Stashed value of html_errors INI setting */
122 protected $htmlErrors;
124 protected $delimiter = ';';
125 /** @var DatabaseDomain */
126 protected $currentDomain;
127 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
128 protected $affectedRowCount;
131 * Either 1 if a transaction is active or 0 otherwise.
132 * The other Trx fields may not be meaningfull if this is 0.
136 protected $trxLevel = 0;
138 * Either a short hexidecimal string if a transaction is active or ""
141 * @see Database::trxLevel
143 protected $trxShortId = '';
145 * The UNIX time that the transaction started. Callers can assume that if
146 * snapshot isolation is used, then the data is *at least* up to date to that
147 * point (possibly more up-to-date since the first SELECT defines the snapshot).
150 * @see Database::trxLevel
152 private $trxTimestamp = null;
153 /** @var float Lag estimate at the time of BEGIN */
154 private $trxReplicaLag = null;
156 * Remembers the function name given for starting the most recent transaction via begin().
157 * Used to provide additional context for error reporting.
160 * @see Database::trxLevel
162 private $trxFname = null;
164 * Record if possible write queries were done in the last transaction started
167 * @see Database::trxLevel
169 private $trxDoneWrites = false;
171 * Record if the current transaction was started implicitly due to DBO_TRX being set.
174 * @see Database::trxLevel
176 private $trxAutomatic = false;
178 * Array of levels of atomicity within transactions
182 private $trxAtomicLevels = [];
184 * Record if the current transaction was started implicitly by Database::startAtomic
188 private $trxAutomaticAtomic = false;
190 * Track the write query callers of the current transaction
194 private $trxWriteCallers = [];
196 * @var float Seconds spent in write queries for the current transaction
198 private $trxWriteDuration = 0.0;
200 * @var int Number of write queries for the current transaction
202 private $trxWriteQueryCount = 0;
204 * @var int Number of rows affected by write queries for the current transaction
206 private $trxWriteAffectedRows = 0;
208 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
210 private $trxWriteAdjDuration = 0.0;
212 * @var int Number of write queries counted in trxWriteAdjDuration
214 private $trxWriteAdjQueryCount = 0;
216 * @var float RTT time estimate
218 private $rttEstimate = 0.0;
220 /** @var array Map of (name => 1) for locks obtained via lock() */
221 private $namedLocksHeld = [];
222 /** @var array Map of (table name => 1) for TEMPORARY tables */
223 protected $sessionTempTables = [];
225 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
226 private $lazyMasterHandle;
228 /** @var float UNIX timestamp */
229 protected $lastPing = 0.0;
231 /** @var int[] Prior flags member variable values */
232 private $priorFlags = [];
234 /** @var object|string Class name or object With profileIn/profileOut methods */
236 /** @var TransactionProfiler */
237 protected $trxProfiler;
240 protected $nonNativeInsertSelectBatchSize = 10000;
243 * Constructor and database handle and attempt to connect to the DB server
245 * IDatabase classes should not be constructed directly in external
246 * code. Database::factory() should be used instead.
248 * @param array $params Parameters passed from Database::factory()
250 function __construct( array $params ) {
251 $server = $params['host'];
252 $user = $params['user'];
253 $password = $params['password'];
254 $dbName = $params['dbname'];
256 $this->schema
= $params['schema'];
257 $this->tablePrefix
= $params['tablePrefix'];
259 $this->cliMode
= $params['cliMode'];
260 // Agent name is added to SQL queries in a comment, so make sure it can't break out
261 $this->agent
= str_replace( '/', '-', $params['agent'] );
263 $this->flags
= $params['flags'];
264 if ( $this->flags
& self
::DBO_DEFAULT
) {
265 if ( $this->cliMode
) {
266 $this->flags
&= ~self
::DBO_TRX
;
268 $this->flags |
= self
::DBO_TRX
;
272 $this->sessionVars
= $params['variables'];
274 $this->srvCache
= isset( $params['srvCache'] )
275 ?
$params['srvCache']
276 : new HashBagOStuff();
278 $this->profiler
= $params['profiler'];
279 $this->trxProfiler
= $params['trxProfiler'];
280 $this->connLogger
= $params['connLogger'];
281 $this->queryLogger
= $params['queryLogger'];
282 $this->errorLogger
= $params['errorLogger'];
284 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
285 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
288 // Set initial dummy domain until open() sets the final DB/prefix
289 $this->currentDomain
= DatabaseDomain
::newUnspecified();
292 $this->open( $server, $user, $password, $dbName );
293 } elseif ( $this->requiresDatabaseUser() ) {
294 throw new InvalidArgumentException( "No database user provided." );
297 // Set the domain object after open() sets the relevant fields
298 if ( $this->dbName
!= '' ) {
299 // Domains with server scope but a table prefix are not used by IDatabase classes
300 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
305 * Construct a Database subclass instance given a database type and parameters
307 * This also connects to the database immediately upon object construction
309 * @param string $dbType A possible DB type (sqlite, mysql, postgres)
310 * @param array $p Parameter map with keys:
311 * - host : The hostname of the DB server
312 * - user : The name of the database user the client operates under
313 * - password : The password for the database user
314 * - dbname : The name of the database to use where queries do not specify one.
315 * The database must exist or an error might be thrown. Setting this to the empty string
316 * will avoid any such errors and make the handle have no implicit database scope. This is
317 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
318 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
319 * in which user names and such are defined, e.g. users are database-specific in Postgres.
320 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
321 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
322 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
323 * recognized in queries. This can be used in place of schemas for handle site farms.
324 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
325 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
326 * flag in place UNLESS this this database simply acts as a key/value store.
327 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
328 * 'mysqli' driver; the old one 'mysql' has been removed.
329 * - variables: Optional map of session variables to set after connecting. This can be
330 * used to adjust lock timeouts or encoding modes and the like.
331 * - connLogger: Optional PSR-3 logger interface instance.
332 * - queryLogger: Optional PSR-3 logger interface instance.
333 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
334 * These will be called in query(), using a simplified version of the SQL that also
335 * includes the agent as a SQL comment.
336 * - trxProfiler: Optional TransactionProfiler instance.
337 * - errorLogger: Optional callback that takes an Exception and logs it.
338 * - cliMode: Whether to consider the execution context that of a CLI script.
339 * - agent: Optional name used to identify the end-user in query profiling/logging.
340 * - srvCache: Optional BagOStuff instance to an APC-style cache.
341 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
342 * @return Database|null If the database driver or extension cannot be found
343 * @throws InvalidArgumentException If the database driver or extension cannot be found
346 final public static function factory( $dbType, $p = [] ) {
347 // For database types with built-in support, the below maps type to IDatabase
348 // implementations. For types with multipe driver implementations (PHP extensions),
349 // an array can be used, keyed by extension name. In case of an array, the
350 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
351 // we auto-detect the first available driver. For types without built-in support,
352 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
353 static $builtinTypes = [
354 'mssql' => DatabaseMssql
::class,
355 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
356 'sqlite' => DatabaseSqlite
::class,
357 'postgres' => DatabasePostgres
::class,
360 $dbType = strtolower( $dbType );
362 if ( isset( $builtinTypes[$dbType] ) ) {
363 $possibleDrivers = $builtinTypes[$dbType];
364 if ( is_string( $possibleDrivers ) ) {
365 $class = $possibleDrivers;
367 if ( !empty( $p['driver'] ) ) {
368 if ( !isset( $possibleDrivers[$p['driver']] ) ) {
369 throw new InvalidArgumentException( __METHOD__
.
370 " type '$dbType' does not support driver '{$p['driver']}'" );
372 $class = $possibleDrivers[$p['driver']];
375 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
376 if ( extension_loaded( $posDriver ) ) {
377 $class = $possibleClass;
384 $class = 'Database' . ucfirst( $dbType );
387 if ( $class === false ) {
388 throw new InvalidArgumentException( __METHOD__
.
389 " no viable database extension found for type '$dbType'" );
392 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
393 // Resolve some defaults for b/c
394 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
395 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
396 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
397 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
398 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
399 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
400 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
401 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
402 $p['cliMode'] = isset( $p['cliMode'] )
404 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
405 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
406 if ( !isset( $p['connLogger'] ) ) {
407 $p['connLogger'] = new \Psr\Log\
NullLogger();
409 if ( !isset( $p['queryLogger'] ) ) {
410 $p['queryLogger'] = new \Psr\Log\
NullLogger();
412 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
413 if ( !isset( $p['trxProfiler'] ) ) {
414 $p['trxProfiler'] = new TransactionProfiler();
416 if ( !isset( $p['errorLogger'] ) ) {
417 $p['errorLogger'] = function ( Exception
$e ) {
418 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
422 $conn = new $class( $p );
431 * Set the PSR-3 logger interface to use for query logging. (The logger
432 * interfaces for connection logging and error logging can be set with the
435 * @param LoggerInterface $logger
437 public function setLogger( LoggerInterface
$logger ) {
438 $this->queryLogger
= $logger;
441 public function getServerInfo() {
442 return $this->getServerVersion();
445 public function bufferResults( $buffer = null ) {
446 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
447 if ( $buffer !== null ) {
449 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
450 : $this->setFlag( self
::DBO_NOBUFFER
);
457 * Turns on (false) or off (true) the automatic generation and sending
458 * of a "we're sorry, but there has been a database error" page on
459 * database errors. Default is on (false). When turned off, the
460 * code should use lastErrno() and lastError() to handle the
461 * situation as appropriate.
463 * Do not use this function outside of the Database classes.
465 * @param null|bool $ignoreErrors
466 * @return bool The previous value of the flag.
468 protected function ignoreErrors( $ignoreErrors = null ) {
469 $res = $this->getFlag( self
::DBO_IGNORE
);
470 if ( $ignoreErrors !== null ) {
471 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
472 if ( $ignoreErrors ) {
473 $this->flags |
= self
::DBO_IGNORE
;
475 $this->flags
&= ~self
::DBO_IGNORE
;
482 public function trxLevel() {
483 return $this->trxLevel
;
486 public function trxTimestamp() {
487 return $this->trxLevel ?
$this->trxTimestamp
: null;
490 public function tablePrefix( $prefix = null ) {
491 $old = $this->tablePrefix
;
492 if ( $prefix !== null ) {
493 $this->tablePrefix
= $prefix;
494 $this->currentDomain
= ( $this->dbName
!= '' )
495 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
496 : DatabaseDomain
::newUnspecified();
502 public function dbSchema( $schema = null ) {
503 $old = $this->schema
;
504 if ( $schema !== null ) {
505 $this->schema
= $schema;
511 public function getLBInfo( $name = null ) {
512 if ( is_null( $name ) ) {
513 return $this->lbInfo
;
515 if ( array_key_exists( $name, $this->lbInfo
) ) {
516 return $this->lbInfo
[$name];
523 public function setLBInfo( $name, $value = null ) {
524 if ( is_null( $value ) ) {
525 $this->lbInfo
= $name;
527 $this->lbInfo
[$name] = $value;
531 public function setLazyMasterHandle( IDatabase
$conn ) {
532 $this->lazyMasterHandle
= $conn;
536 * @return IDatabase|null
537 * @see setLazyMasterHandle()
540 protected function getLazyMasterHandle() {
541 return $this->lazyMasterHandle
;
544 public function implicitGroupby() {
548 public function implicitOrderby() {
552 public function lastQuery() {
553 return $this->lastQuery
;
556 public function doneWrites() {
557 return (bool)$this->lastWriteTime
;
560 public function lastDoneWrites() {
561 return $this->lastWriteTime ?
: false;
564 public function writesPending() {
565 return $this->trxLevel
&& $this->trxDoneWrites
;
568 public function writesOrCallbacksPending() {
569 return $this->trxLevel
&& (
570 $this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks
574 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
575 if ( !$this->trxLevel
) {
577 } elseif ( !$this->trxDoneWrites
) {
582 case self
::ESTIMATE_DB_APPLY
:
584 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
585 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
586 // For omitted queries, make them count as something at least
587 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
588 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
591 default: // everything
592 return $this->trxWriteDuration
;
596 public function pendingWriteCallers() {
597 return $this->trxLevel ?
$this->trxWriteCallers
: [];
600 public function pendingWriteRowsAffected() {
601 return $this->trxWriteAffectedRows
;
605 * Get the list of method names that have pending write queries or callbacks
606 * for this transaction
610 protected function pendingWriteAndCallbackCallers() {
611 if ( !$this->trxLevel
) {
615 $fnames = $this->trxWriteCallers
;
617 $this->trxIdleCallbacks
,
618 $this->trxPreCommitCallbacks
,
619 $this->trxEndCallbacks
621 foreach ( $callbacks as $callback ) {
622 $fnames[] = $callback[1];
629 public function isOpen() {
630 return $this->opened
;
633 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
634 if ( ( $flag & self
::DBO_IGNORE
) ) {
635 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
638 if ( $remember === self
::REMEMBER_PRIOR
) {
639 array_push( $this->priorFlags
, $this->flags
);
641 $this->flags |
= $flag;
644 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
645 if ( ( $flag & self
::DBO_IGNORE
) ) {
646 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
649 if ( $remember === self
::REMEMBER_PRIOR
) {
650 array_push( $this->priorFlags
, $this->flags
);
652 $this->flags
&= ~
$flag;
655 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
656 if ( !$this->priorFlags
) {
660 if ( $state === self
::RESTORE_INITIAL
) {
661 $this->flags
= reset( $this->priorFlags
);
662 $this->priorFlags
= [];
664 $this->flags
= array_pop( $this->priorFlags
);
668 public function getFlag( $flag ) {
669 return !!( $this->flags
& $flag );
673 * @param string $name Class field name
675 * @deprecated Since 1.28
677 public function getProperty( $name ) {
681 public function getDomainID() {
682 return $this->currentDomain
->getId();
685 final public function getWikiID() {
686 return $this->getDomainID();
690 * Get information about an index into an object
691 * @param string $table Table name
692 * @param string $index Index name
693 * @param string $fname Calling function name
694 * @return mixed Database-specific index description class or false if the index does not exist
696 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
699 * Wrapper for addslashes()
701 * @param string $s String to be slashed.
702 * @return string Slashed string.
704 abstract function strencode( $s );
707 * Set a custom error handler for logging errors during database connection
709 protected function installErrorHandler() {
710 $this->phpError
= false;
711 $this->htmlErrors
= ini_set( 'html_errors', '0' );
712 set_error_handler( [ $this, 'connectionErrorLogger' ] );
716 * Restore the previous error handler and return the last PHP error for this DB
718 * @return bool|string
720 protected function restoreErrorHandler() {
721 restore_error_handler();
722 if ( $this->htmlErrors
!== false ) {
723 ini_set( 'html_errors', $this->htmlErrors
);
726 return $this->getLastPHPError();
730 * @return string|bool Last PHP error for this DB (typically connection errors)
732 protected function getLastPHPError() {
733 if ( $this->phpError
) {
734 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
735 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
744 * Error handler for logging errors during database connection
745 * This method should not be used outside of Database classes
748 * @param string $errstr
750 public function connectionErrorLogger( $errno, $errstr ) {
751 $this->phpError
= $errstr;
755 * Create a log context to pass to PSR-3 logger functions.
757 * @param array $extras Additional data to add to context
760 protected function getLogContext( array $extras = [] ) {
763 'db_server' => $this->server
,
764 'db_name' => $this->dbName
,
765 'db_user' => $this->user
,
771 public function close() {
773 if ( $this->trxLevel() ) {
774 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
777 $closed = $this->closeConnection();
780 $this->trxIdleCallbacks ||
781 $this->trxPreCommitCallbacks ||
782 $this->trxEndCallbacks
784 throw new RuntimeException( "Transaction callbacks still pending." );
788 $this->opened
= false;
794 * Make sure isOpen() returns true as a sanity check
796 * @throws DBUnexpectedError
798 protected function assertOpen() {
799 if ( !$this->isOpen() ) {
800 throw new DBUnexpectedError( $this, "DB connection was already closed." );
805 * Closes underlying database connection
807 * @return bool Whether connection was closed successfully
809 abstract protected function closeConnection();
811 public function reportConnectionError( $error = 'Unknown error' ) {
812 $myError = $this->lastError();
818 throw new DBConnectionError( $this, $error );
822 * The DBMS-dependent part of query()
824 * @param string $sql SQL query.
825 * @return ResultWrapper|bool Result object to feed to fetchObject,
826 * fetchRow, ...; or false on failure
828 abstract protected function doQuery( $sql );
831 * Determine whether a query writes to the DB.
832 * Should return true if unsure.
837 protected function isWriteQuery( $sql ) {
839 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
844 * @return string|null
846 protected function getQueryVerb( $sql ) {
847 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
851 * Determine whether a SQL statement is sensitive to isolation level.
852 * A SQL statement is considered transactable if its result could vary
853 * depending on the transaction isolation level. Operational commands
854 * such as 'SET' and 'SHOW' are not considered to be transactable.
859 protected function isTransactableQuery( $sql ) {
861 $this->getQueryVerb( $sql ),
862 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
868 * @param string $sql A SQL query
869 * @return bool Whether $sql is SQL for TEMPORARY table operation
871 protected function registerTempTableOperation( $sql ) {
873 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
877 $this->sessionTempTables
[$matches[1]] = 1;
880 } elseif ( preg_match(
881 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
885 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
886 unset( $this->sessionTempTables
[$matches[1]] );
889 } elseif ( preg_match(
890 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
894 return isset( $this->sessionTempTables
[$matches[1]] );
895 } elseif ( preg_match(
896 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
900 return isset( $this->sessionTempTables
[$matches[1]] );
906 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
907 $priorWritesPending = $this->writesOrCallbacksPending();
908 $this->lastQuery
= $sql;
910 $isWrite = $this->isWriteQuery( $sql );
912 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
914 $isNonTempWrite = false;
918 if ( $this->getLBInfo( 'replica' ) === true ) {
921 'Write operations are not allowed on replica database connections.'
924 # In theory, non-persistent writes are allowed in read-only mode, but due to things
925 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
926 $reason = $this->getReadOnlyReason();
927 if ( $reason !== false ) {
928 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
930 # Set a flag indicating that writes have been done
931 $this->lastWriteTime
= microtime( true );
934 # Add trace comment to the begin of the sql string, right after the operator.
935 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
936 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
938 # Start implicit transactions that wrap the request if DBO_TRX is enabled
939 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
940 && $this->isTransactableQuery( $sql )
942 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
943 $this->trxAutomatic
= true;
946 # Keep track of whether the transaction has write queries pending
947 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
948 $this->trxDoneWrites
= true;
949 $this->trxProfiler
->transactionWritingIn(
950 $this->server
, $this->dbName
, $this->trxShortId
);
953 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
954 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
957 # Avoid fatals if close() was called
960 # Send the query to the server
961 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
963 # Try reconnecting if the connection was lost
964 if ( false === $ret && $this->wasErrorReissuable() ) {
965 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
966 # Stash the last error values before anything might clear them
967 $lastError = $this->lastError();
968 $lastErrno = $this->lastErrno();
969 # Update state tracking to reflect transaction loss due to disconnection
970 $this->handleSessionLoss();
971 if ( $this->reconnect() ) {
972 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
973 $params = [ 'dbserver' => $this->getServer() ];
974 $this->connLogger
->warning( $msg, $params );
975 $this->queryLogger
->warning( $msg, $params +
976 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
978 if ( !$recoverable ) {
979 # Callers may catch the exception and continue to use the DB
980 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
982 # Should be safe to silently retry the query
983 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
986 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
987 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
991 if ( false === $ret ) {
992 # Deadlocks cause the entire transaction to abort, not just the statement.
993 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
994 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
995 if ( $this->wasDeadlock() ) {
996 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
997 $tempIgnore = false; // not recoverable
999 # Update state tracking to reflect transaction loss
1000 $this->handleSessionLoss();
1003 $this->reportQueryError(
1004 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1007 $res = $this->resultObject( $ret );
1013 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1015 * @param string $sql Original SQL query
1016 * @param string $commentedSql SQL query with debugging/trace comment
1017 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1018 * @param string $fname Name of the calling function
1019 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1020 * object for a successful read query, or false on failure
1022 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1023 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1024 # generalizeSQL() will probably cut down the query to reasonable
1025 # logging size most of the time. The substr is really just a sanity check.
1027 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1029 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1032 # Include query transaction state
1033 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1035 $startTime = microtime( true );
1036 if ( $this->profiler
) {
1037 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1039 $this->affectedRowCount
= null;
1040 $ret = $this->doQuery( $commentedSql );
1041 $this->affectedRowCount
= $this->affectedRows();
1042 if ( $this->profiler
) {
1043 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1045 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1047 unset( $queryProfSection ); // profile out (if set)
1049 if ( $ret !== false ) {
1050 $this->lastPing
= $startTime;
1051 if ( $isWrite && $this->trxLevel
) {
1052 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1053 $this->trxWriteCallers
[] = $fname;
1057 if ( $sql === self
::PING_QUERY
) {
1058 $this->rttEstimate
= $queryRuntime;
1061 $this->trxProfiler
->recordQueryCompletion(
1062 $queryProf, $startTime, $isWrite, $this->affectedRows()
1064 $this->queryLogger
->debug( $sql, [
1066 'master' => $isMaster,
1067 'runtime' => $queryRuntime,
1074 * Update the estimated run-time of a query, not counting large row lock times
1076 * LoadBalancer can be set to rollback transactions that will create huge replication
1077 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1078 * queries, like inserting a row can take a long time due to row locking. This method
1079 * uses some simple heuristics to discount those cases.
1081 * @param string $sql A SQL write query
1082 * @param float $runtime Total runtime, including RTT
1083 * @param int $affected Affected row count
1085 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1086 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1087 $indicativeOfReplicaRuntime = true;
1088 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1089 $verb = $this->getQueryVerb( $sql );
1090 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1091 if ( $verb === 'INSERT' ) {
1092 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1093 } elseif ( $verb === 'REPLACE' ) {
1094 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1098 $this->trxWriteDuration +
= $runtime;
1099 $this->trxWriteQueryCount +
= 1;
1100 $this->trxWriteAffectedRows +
= $affected;
1101 if ( $indicativeOfReplicaRuntime ) {
1102 $this->trxWriteAdjDuration +
= $runtime;
1103 $this->trxWriteAdjQueryCount +
= 1;
1108 * Determine whether or not it is safe to retry queries after a database
1109 * connection is lost
1111 * @param string $sql SQL query
1112 * @param bool $priorWritesPending Whether there is a transaction open with
1113 * possible write queries or transaction pre-commit/idle callbacks
1114 * waiting on it to finish.
1115 * @return bool True if it is safe to retry the query, false otherwise
1117 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1118 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1119 # Dropped connections also mean that named locks are automatically released.
1120 # Only allow error suppression in autocommit mode or when the lost transaction
1121 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1122 if ( $this->namedLocksHeld
) {
1123 return false; // possible critical section violation
1124 } elseif ( $sql === 'COMMIT' ) {
1125 return !$priorWritesPending; // nothing written anyway? (T127428)
1126 } elseif ( $sql === 'ROLLBACK' ) {
1127 return true; // transaction lost...which is also what was requested :)
1128 } elseif ( $this->explicitTrxActive() ) {
1129 return false; // don't drop atomocity
1130 } elseif ( $priorWritesPending ) {
1131 return false; // prior writes lost from implicit transaction
1138 * Clean things up after transaction loss due to disconnection
1140 * @return null|Exception
1142 private function handleSessionLoss() {
1143 $this->trxLevel
= 0;
1144 $this->trxIdleCallbacks
= []; // T67263
1145 $this->trxPreCommitCallbacks
= []; // T67263
1146 $this->sessionTempTables
= [];
1147 $this->namedLocksHeld
= [];
1149 // Handle callbacks in trxEndCallbacks
1150 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1151 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1153 } catch ( Exception
$e ) {
1154 // Already logged; move on...
1160 * Checks whether the cause of the error is detected to be a timeout.
1162 * It returns false by default, and not all engines support detecting this yet.
1163 * If this returns false, it will be treated as a generic query error.
1165 * @param string $error Error text
1166 * @param int $errno Error number
1169 protected function wasQueryTimeout( $error, $errno ) {
1173 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1174 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1175 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1177 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1178 $this->queryLogger
->error(
1179 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1180 $this->getLogContext( [
1181 'method' => __METHOD__
,
1184 'sql1line' => $sql1line,
1188 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1189 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1190 if ( $wasQueryTimeout ) {
1191 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1193 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1198 public function freeResult( $res ) {
1201 public function selectField(
1202 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1204 if ( $var === '*' ) { // sanity
1205 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1208 if ( !is_array( $options ) ) {
1209 $options = [ $options ];
1212 $options['LIMIT'] = 1;
1214 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1215 if ( $res === false ||
!$this->numRows( $res ) ) {
1219 $row = $this->fetchRow( $res );
1221 if ( $row !== false ) {
1222 return reset( $row );
1228 public function selectFieldValues(
1229 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1231 if ( $var === '*' ) { // sanity
1232 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1233 } elseif ( !is_string( $var ) ) { // sanity
1234 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1237 if ( !is_array( $options ) ) {
1238 $options = [ $options ];
1241 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1242 if ( $res === false ) {
1247 foreach ( $res as $row ) {
1248 $values[] = $row->$var;
1255 * Returns an optional USE INDEX clause to go after the table, and a
1256 * string to go at the end of the query.
1258 * @param array $options Associative array of options to be turned into
1259 * an SQL query, valid keys are listed in the function.
1261 * @see Database::select()
1263 protected function makeSelectOptions( $options ) {
1264 $preLimitTail = $postLimitTail = '';
1269 foreach ( $options as $key => $option ) {
1270 if ( is_numeric( $key ) ) {
1271 $noKeyOptions[$option] = true;
1275 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1277 $preLimitTail .= $this->makeOrderBy( $options );
1279 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1280 $postLimitTail .= ' FOR UPDATE';
1283 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1284 $postLimitTail .= ' LOCK IN SHARE MODE';
1287 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1288 $startOpts .= 'DISTINCT';
1291 # Various MySQL extensions
1292 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1293 $startOpts .= ' /*! STRAIGHT_JOIN */';
1296 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1297 $startOpts .= ' HIGH_PRIORITY';
1300 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1301 $startOpts .= ' SQL_BIG_RESULT';
1304 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1305 $startOpts .= ' SQL_BUFFER_RESULT';
1308 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1309 $startOpts .= ' SQL_SMALL_RESULT';
1312 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1313 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1316 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1317 $startOpts .= ' SQL_CACHE';
1320 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1321 $startOpts .= ' SQL_NO_CACHE';
1324 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1325 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1329 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1330 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1335 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1339 * Returns an optional GROUP BY with an optional HAVING
1341 * @param array $options Associative array of options
1343 * @see Database::select()
1346 protected function makeGroupByWithHaving( $options ) {
1348 if ( isset( $options['GROUP BY'] ) ) {
1349 $gb = is_array( $options['GROUP BY'] )
1350 ?
implode( ',', $options['GROUP BY'] )
1351 : $options['GROUP BY'];
1352 $sql .= ' GROUP BY ' . $gb;
1354 if ( isset( $options['HAVING'] ) ) {
1355 $having = is_array( $options['HAVING'] )
1356 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1357 : $options['HAVING'];
1358 $sql .= ' HAVING ' . $having;
1365 * Returns an optional ORDER BY
1367 * @param array $options Associative array of options
1369 * @see Database::select()
1372 protected function makeOrderBy( $options ) {
1373 if ( isset( $options['ORDER BY'] ) ) {
1374 $ob = is_array( $options['ORDER BY'] )
1375 ?
implode( ',', $options['ORDER BY'] )
1376 : $options['ORDER BY'];
1378 return ' ORDER BY ' . $ob;
1384 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1385 $options = [], $join_conds = [] ) {
1386 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1388 return $this->query( $sql, $fname );
1391 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1392 $options = [], $join_conds = []
1394 if ( is_array( $vars ) ) {
1395 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1398 $options = (array)$options;
1399 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1400 ?
$options['USE INDEX']
1403 isset( $options['IGNORE INDEX'] ) &&
1404 is_array( $options['IGNORE INDEX'] )
1406 ?
$options['IGNORE INDEX']
1409 if ( is_array( $table ) ) {
1411 $this->tableNamesWithIndexClauseOrJOIN(
1412 $table, $useIndexes, $ignoreIndexes, $join_conds );
1413 } elseif ( $table != '' ) {
1415 $this->tableNamesWithIndexClauseOrJOIN(
1416 [ $table ], $useIndexes, $ignoreIndexes, [] );
1421 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1422 $this->makeSelectOptions( $options );
1424 if ( !empty( $conds ) ) {
1425 if ( is_array( $conds ) ) {
1426 $conds = $this->makeList( $conds, self
::LIST_AND
);
1428 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1429 "WHERE $conds $preLimitTail";
1431 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1434 if ( isset( $options['LIMIT'] ) ) {
1435 $sql = $this->limitResult( $sql, $options['LIMIT'],
1436 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1438 $sql = "$sql $postLimitTail";
1440 if ( isset( $options['EXPLAIN'] ) ) {
1441 $sql = 'EXPLAIN ' . $sql;
1447 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1448 $options = [], $join_conds = []
1450 $options = (array)$options;
1451 $options['LIMIT'] = 1;
1452 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1454 if ( $res === false ) {
1458 if ( !$this->numRows( $res ) ) {
1462 $obj = $this->fetchObject( $res );
1467 public function estimateRowCount(
1468 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1471 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1474 $row = $this->fetchRow( $res );
1475 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1481 public function selectRowCount(
1482 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1485 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1486 // The identifier quotes is primarily for MSSQL.
1487 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1488 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1489 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1492 $row = $this->fetchRow( $res );
1493 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1500 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1501 * It's only slightly flawed. Don't use for anything important.
1503 * @param string $sql A SQL Query
1507 protected static function generalizeSQL( $sql ) {
1508 # This does the same as the regexp below would do, but in such a way
1509 # as to avoid crashing php on some large strings.
1510 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1512 $sql = str_replace( "\\\\", '', $sql );
1513 $sql = str_replace( "\\'", '', $sql );
1514 $sql = str_replace( "\\\"", '', $sql );
1515 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1516 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1518 # All newlines, tabs, etc replaced by single space
1519 $sql = preg_replace( '/\s+/', ' ', $sql );
1522 # except the ones surrounded by characters, e.g. l10n
1523 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1524 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1529 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1530 $info = $this->fieldInfo( $table, $field );
1535 public function indexExists( $table, $index, $fname = __METHOD__
) {
1536 if ( !$this->tableExists( $table ) ) {
1540 $info = $this->indexInfo( $table, $index, $fname );
1541 if ( is_null( $info ) ) {
1544 return $info !== false;
1548 public function tableExists( $table, $fname = __METHOD__
) {
1549 $tableRaw = $this->tableName( $table, 'raw' );
1550 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1551 return true; // already known to exist
1554 $table = $this->tableName( $table );
1555 $ignoreErrors = true;
1556 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1561 public function indexUnique( $table, $index ) {
1562 $indexInfo = $this->indexInfo( $table, $index );
1564 if ( !$indexInfo ) {
1568 return !$indexInfo[0]->Non_unique
;
1572 * Helper for Database::insert().
1574 * @param array $options
1577 protected function makeInsertOptions( $options ) {
1578 return implode( ' ', $options );
1581 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1582 # No rows to insert, easy just return now
1583 if ( !count( $a ) ) {
1587 $table = $this->tableName( $table );
1589 if ( !is_array( $options ) ) {
1590 $options = [ $options ];
1594 if ( isset( $options['fileHandle'] ) ) {
1595 $fh = $options['fileHandle'];
1597 $options = $this->makeInsertOptions( $options );
1599 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1601 $keys = array_keys( $a[0] );
1604 $keys = array_keys( $a );
1607 $sql = 'INSERT ' . $options .
1608 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1612 foreach ( $a as $row ) {
1618 $sql .= '(' . $this->makeList( $row ) . ')';
1621 $sql .= '(' . $this->makeList( $a ) . ')';
1624 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1626 } elseif ( $fh !== null ) {
1630 return (bool)$this->query( $sql, $fname );
1634 * Make UPDATE options array for Database::makeUpdateOptions
1636 * @param array $options
1639 protected function makeUpdateOptionsArray( $options ) {
1640 if ( !is_array( $options ) ) {
1641 $options = [ $options ];
1646 if ( in_array( 'IGNORE', $options ) ) {
1654 * Make UPDATE options for the Database::update function
1656 * @param array $options The options passed to Database::update
1659 protected function makeUpdateOptions( $options ) {
1660 $opts = $this->makeUpdateOptionsArray( $options );
1662 return implode( ' ', $opts );
1665 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1666 $table = $this->tableName( $table );
1667 $opts = $this->makeUpdateOptions( $options );
1668 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1670 if ( $conds !== [] && $conds !== '*' ) {
1671 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1674 return (bool)$this->query( $sql, $fname );
1677 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1678 if ( !is_array( $a ) ) {
1679 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1685 foreach ( $a as $field => $value ) {
1687 if ( $mode == self
::LIST_AND
) {
1689 } elseif ( $mode == self
::LIST_OR
) {
1698 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1699 $list .= "($value)";
1700 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1703 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1705 // Remove null from array to be handled separately if found
1706 $includeNull = false;
1707 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1708 $includeNull = true;
1709 unset( $value[$nullKey] );
1711 if ( count( $value ) == 0 && !$includeNull ) {
1712 throw new InvalidArgumentException(
1713 __METHOD__
. ": empty input for field $field" );
1714 } elseif ( count( $value ) == 0 ) {
1715 // only check if $field is null
1716 $list .= "$field IS NULL";
1718 // IN clause contains at least one valid element
1719 if ( $includeNull ) {
1720 // Group subconditions to ensure correct precedence
1723 if ( count( $value ) == 1 ) {
1724 // Special-case single values, as IN isn't terribly efficient
1725 // Don't necessarily assume the single key is 0; we don't
1726 // enforce linear numeric ordering on other arrays here.
1727 $value = array_values( $value )[0];
1728 $list .= $field . " = " . $this->addQuotes( $value );
1730 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1732 // if null present in array, append IS NULL
1733 if ( $includeNull ) {
1734 $list .= " OR $field IS NULL)";
1737 } elseif ( $value === null ) {
1738 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1739 $list .= "$field IS ";
1740 } elseif ( $mode == self
::LIST_SET
) {
1741 $list .= "$field = ";
1746 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1748 $list .= "$field = ";
1750 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1757 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1760 foreach ( $data as $base => $sub ) {
1761 if ( count( $sub ) ) {
1762 $conds[] = $this->makeList(
1763 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1769 return $this->makeList( $conds, self
::LIST_OR
);
1771 // Nothing to search for...
1776 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1780 public function bitNot( $field ) {
1784 public function bitAnd( $fieldLeft, $fieldRight ) {
1785 return "($fieldLeft & $fieldRight)";
1788 public function bitOr( $fieldLeft, $fieldRight ) {
1789 return "($fieldLeft | $fieldRight)";
1792 public function buildConcat( $stringList ) {
1793 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1796 public function buildGroupConcatField(
1797 $delim, $table, $field, $conds = '', $join_conds = []
1799 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1801 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1804 public function buildStringCast( $field ) {
1808 public function databasesAreIndependent() {
1812 public function selectDB( $db ) {
1813 # Stub. Shouldn't cause serious problems if it's not overridden, but
1814 # if your database engine supports a concept similar to MySQL's
1815 # databases you may as well.
1816 $this->dbName
= $db;
1821 public function getDBname() {
1822 return $this->dbName
;
1825 public function getServer() {
1826 return $this->server
;
1829 public function tableName( $name, $format = 'quoted' ) {
1830 # Skip the entire process when we have a string quoted on both ends.
1831 # Note that we check the end so that we will still quote any use of
1832 # use of `database`.table. But won't break things if someone wants
1833 # to query a database table with a dot in the name.
1834 if ( $this->isQuotedIdentifier( $name ) ) {
1838 # Lets test for any bits of text that should never show up in a table
1839 # name. Basically anything like JOIN or ON which are actually part of
1840 # SQL queries, but may end up inside of the table value to combine
1841 # sql. Such as how the API is doing.
1842 # Note that we use a whitespace test rather than a \b test to avoid
1843 # any remote case where a word like on may be inside of a table name
1844 # surrounded by symbols which may be considered word breaks.
1845 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1849 # Split database and table into proper variables.
1850 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1852 # Quote $table and apply the prefix if not quoted.
1853 # $tableName might be empty if this is called from Database::replaceVars()
1854 $tableName = "{$prefix}{$table}";
1855 if ( $format === 'quoted'
1856 && !$this->isQuotedIdentifier( $tableName )
1857 && $tableName !== ''
1859 $tableName = $this->addIdentifierQuotes( $tableName );
1862 # Quote $schema and $database and merge them with the table name if needed
1863 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1864 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1870 * Get the table components needed for a query given the currently selected database
1872 * @param string $name Table name in the form of db.schema.table, db.table, or table
1873 * @return array (DB name or "" for default, schema name, table prefix, table name)
1875 protected function qualifiedTableComponents( $name ) {
1876 # We reverse the explode so that database.table and table both output the correct table.
1877 $dbDetails = explode( '.', $name, 3 );
1878 if ( count( $dbDetails ) == 3 ) {
1879 list( $database, $schema, $table ) = $dbDetails;
1880 # We don't want any prefix added in this case
1882 } elseif ( count( $dbDetails ) == 2 ) {
1883 list( $database, $table ) = $dbDetails;
1884 # We don't want any prefix added in this case
1886 # In dbs that support it, $database may actually be the schema
1887 # but that doesn't affect any of the functionality here
1890 list( $table ) = $dbDetails;
1891 if ( isset( $this->tableAliases
[$table] ) ) {
1892 $database = $this->tableAliases
[$table]['dbname'];
1893 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1894 ?
$this->tableAliases
[$table]['schema']
1896 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1897 ?
$this->tableAliases
[$table]['prefix']
1898 : $this->tablePrefix
;
1901 $schema = $this->schema
; # Default schema
1902 $prefix = $this->tablePrefix
; # Default prefix
1906 return [ $database, $schema, $prefix, $table ];
1910 * @param string|null $namespace Database or schema
1911 * @param string $relation Name of table, view, sequence, etc...
1912 * @param string $format One of (raw, quoted)
1913 * @return string Relation name with quoted and merged $namespace as needed
1915 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1916 if ( strlen( $namespace ) ) {
1917 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1918 $namespace = $this->addIdentifierQuotes( $namespace );
1920 $relation = $namespace . '.' . $relation;
1926 public function tableNames() {
1927 $inArray = func_get_args();
1930 foreach ( $inArray as $name ) {
1931 $retVal[$name] = $this->tableName( $name );
1937 public function tableNamesN() {
1938 $inArray = func_get_args();
1941 foreach ( $inArray as $name ) {
1942 $retVal[] = $this->tableName( $name );
1949 * Get an aliased table name
1950 * e.g. tableName AS newTableName
1952 * @param string $name Table name, see tableName()
1953 * @param string|bool $alias Alias (optional)
1954 * @return string SQL name for aliased table. Will not alias a table to its own name
1956 protected function tableNameWithAlias( $name, $alias = false ) {
1957 if ( !$alias ||
$alias == $name ) {
1958 return $this->tableName( $name );
1960 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1965 * Gets an array of aliased table names
1967 * @param array $tables [ [alias] => table ]
1968 * @return string[] See tableNameWithAlias()
1970 protected function tableNamesWithAlias( $tables ) {
1972 foreach ( $tables as $alias => $table ) {
1973 if ( is_numeric( $alias ) ) {
1976 $retval[] = $this->tableNameWithAlias( $table, $alias );
1983 * Get an aliased field name
1984 * e.g. fieldName AS newFieldName
1986 * @param string $name Field name
1987 * @param string|bool $alias Alias (optional)
1988 * @return string SQL name for aliased field. Will not alias a field to its own name
1990 protected function fieldNameWithAlias( $name, $alias = false ) {
1991 if ( !$alias ||
(string)$alias === (string)$name ) {
1994 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
1999 * Gets an array of aliased field names
2001 * @param array $fields [ [alias] => field ]
2002 * @return string[] See fieldNameWithAlias()
2004 protected function fieldNamesWithAlias( $fields ) {
2006 foreach ( $fields as $alias => $field ) {
2007 if ( is_numeric( $alias ) ) {
2010 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2017 * Get the aliased table name clause for a FROM clause
2018 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2020 * @param array $tables ( [alias] => table )
2021 * @param array $use_index Same as for select()
2022 * @param array $ignore_index Same as for select()
2023 * @param array $join_conds Same as for select()
2026 protected function tableNamesWithIndexClauseOrJOIN(
2027 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2031 $use_index = (array)$use_index;
2032 $ignore_index = (array)$ignore_index;
2033 $join_conds = (array)$join_conds;
2035 foreach ( $tables as $alias => $table ) {
2036 if ( !is_string( $alias ) ) {
2037 // No alias? Set it equal to the table name
2041 if ( is_array( $table ) ) {
2042 // A parenthesized group
2043 if ( count( $table ) > 1 ) {
2045 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2049 $innerTable = reset( $table );
2050 $innerAlias = key( $table );
2051 $joinedTable = $this->tableNameWithAlias(
2053 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2057 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2060 // Is there a JOIN clause for this table?
2061 if ( isset( $join_conds[$alias] ) ) {
2062 list( $joinType, $conds ) = $join_conds[$alias];
2063 $tableClause = $joinType;
2064 $tableClause .= ' ' . $joinedTable;
2065 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2066 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2068 $tableClause .= ' ' . $use;
2071 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2072 $ignore = $this->ignoreIndexClause(
2073 implode( ',', (array)$ignore_index[$alias] ) );
2074 if ( $ignore != '' ) {
2075 $tableClause .= ' ' . $ignore;
2078 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2080 $tableClause .= ' ON (' . $on . ')';
2083 $retJOIN[] = $tableClause;
2084 } elseif ( isset( $use_index[$alias] ) ) {
2085 // Is there an INDEX clause for this table?
2086 $tableClause = $joinedTable;
2087 $tableClause .= ' ' . $this->useIndexClause(
2088 implode( ',', (array)$use_index[$alias] )
2091 $ret[] = $tableClause;
2092 } elseif ( isset( $ignore_index[$alias] ) ) {
2093 // Is there an INDEX clause for this table?
2094 $tableClause = $joinedTable;
2095 $tableClause .= ' ' . $this->ignoreIndexClause(
2096 implode( ',', (array)$ignore_index[$alias] )
2099 $ret[] = $tableClause;
2101 $tableClause = $joinedTable;
2103 $ret[] = $tableClause;
2107 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2108 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2109 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2111 // Compile our final table clause
2112 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2116 * Allows for index remapping in queries where this is not consistent across DBMS
2118 * @param string $index
2121 protected function indexName( $index ) {
2125 public function addQuotes( $s ) {
2126 if ( $s instanceof Blob
) {
2129 if ( $s === null ) {
2131 } elseif ( is_bool( $s ) ) {
2134 # This will also quote numeric values. This should be harmless,
2135 # and protects against weird problems that occur when they really
2136 # _are_ strings such as article titles and string->number->string
2137 # conversion is not 1:1.
2138 return "'" . $this->strencode( $s ) . "'";
2143 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2144 * MySQL uses `backticks` while basically everything else uses double quotes.
2145 * Since MySQL is the odd one out here the double quotes are our generic
2146 * and we implement backticks in DatabaseMysqlBase.
2151 public function addIdentifierQuotes( $s ) {
2152 return '"' . str_replace( '"', '""', $s ) . '"';
2156 * Returns if the given identifier looks quoted or not according to
2157 * the database convention for quoting identifiers .
2159 * @note Do not use this to determine if untrusted input is safe.
2160 * A malicious user can trick this function.
2161 * @param string $name
2164 public function isQuotedIdentifier( $name ) {
2165 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2170 * @param string $escapeChar
2173 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2174 return str_replace( [ $escapeChar, '%', '_' ],
2175 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2179 public function buildLike() {
2180 $params = func_get_args();
2182 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2183 $params = $params[0];
2188 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2189 // may escape backslashes, creating problems of double escaping. The `
2190 // character has good cross-DBMS compatibility, avoiding special operators
2191 // in MS SQL like ^ and %
2194 foreach ( $params as $value ) {
2195 if ( $value instanceof LikeMatch
) {
2196 $s .= $value->toString();
2198 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2202 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2205 public function anyChar() {
2206 return new LikeMatch( '_' );
2209 public function anyString() {
2210 return new LikeMatch( '%' );
2213 public function nextSequenceValue( $seqName ) {
2218 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2219 * is only needed because a) MySQL must be as efficient as possible due to
2220 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2221 * which index to pick. Anyway, other databases might have different
2222 * indexes on a given table. So don't bother overriding this unless you're
2224 * @param string $index
2227 public function useIndexClause( $index ) {
2232 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2233 * is only needed because a) MySQL must be as efficient as possible due to
2234 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2235 * which index to pick. Anyway, other databases might have different
2236 * indexes on a given table. So don't bother overriding this unless you're
2238 * @param string $index
2241 public function ignoreIndexClause( $index ) {
2245 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2246 if ( count( $rows ) == 0 ) {
2251 if ( !is_array( reset( $rows ) ) ) {
2255 $useTrx = !$this->trxLevel
;
2257 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2260 $affectedRowCount = 0;
2261 foreach ( $rows as $row ) {
2262 // Delete rows which collide with this one
2263 $indexWhereClauses = [];
2264 foreach ( $uniqueIndexes as $index ) {
2265 $indexColumns = (array)$index;
2266 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2267 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2268 throw new DBUnexpectedError(
2270 'New record does not provide all values for unique key (' .
2271 implode( ', ', $indexColumns ) . ')'
2273 } elseif ( in_array( null, $indexRowValues, true ) ) {
2274 throw new DBUnexpectedError(
2276 'New record has a null value for unique key (' .
2277 implode( ', ', $indexColumns ) . ')'
2280 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2283 if ( $indexWhereClauses ) {
2284 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2285 $affectedRowCount +
= $this->affectedRows();
2288 // Now insert the row
2289 $this->insert( $table, $row, $fname );
2290 $affectedRowCount +
= $this->affectedRows();
2292 } catch ( Exception
$e ) {
2294 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2299 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2302 $this->affectedRowCount
= $affectedRowCount;
2306 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2309 * @param string $table Table name
2310 * @param array|string $rows Row(s) to insert
2311 * @param string $fname Caller function name
2313 * @return ResultWrapper
2315 protected function nativeReplace( $table, $rows, $fname ) {
2316 $table = $this->tableName( $table );
2319 if ( !is_array( reset( $rows ) ) ) {
2323 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2326 foreach ( $rows as $row ) {
2333 $sql .= '(' . $this->makeList( $row ) . ')';
2336 return $this->query( $sql, $fname );
2339 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2342 if ( !count( $rows ) ) {
2343 return true; // nothing to do
2346 if ( !is_array( reset( $rows ) ) ) {
2350 if ( count( $uniqueIndexes ) ) {
2351 $clauses = []; // list WHERE clauses that each identify a single row
2352 foreach ( $rows as $row ) {
2353 foreach ( $uniqueIndexes as $index ) {
2354 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2355 $rowKey = []; // unique key to this row
2356 foreach ( $index as $column ) {
2357 $rowKey[$column] = $row[$column];
2359 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2362 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2367 $affectedRowCount = 0;
2368 $useTrx = !$this->trxLevel
;
2370 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2373 # Update any existing conflicting row(s)
2374 if ( $where !== false ) {
2375 $ok = $this->update( $table, $set, $where, $fname );
2376 $affectedRowCount +
= $this->affectedRows();
2380 # Now insert any non-conflicting row(s)
2381 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2382 $affectedRowCount +
= $this->affectedRows();
2383 } catch ( Exception
$e ) {
2385 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2390 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2392 $this->affectedRowCount
= $affectedRowCount;
2397 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2401 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2404 $delTable = $this->tableName( $delTable );
2405 $joinTable = $this->tableName( $joinTable );
2406 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2407 if ( $conds != '*' ) {
2408 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2412 $this->query( $sql, $fname );
2415 public function textFieldSize( $table, $field ) {
2416 $table = $this->tableName( $table );
2417 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2418 $res = $this->query( $sql, __METHOD__
);
2419 $row = $this->fetchObject( $res );
2423 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2432 public function delete( $table, $conds, $fname = __METHOD__
) {
2434 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2437 $table = $this->tableName( $table );
2438 $sql = "DELETE FROM $table";
2440 if ( $conds != '*' ) {
2441 if ( is_array( $conds ) ) {
2442 $conds = $this->makeList( $conds, self
::LIST_AND
);
2444 $sql .= ' WHERE ' . $conds;
2447 return $this->query( $sql, $fname );
2450 public function insertSelect(
2451 $destTable, $srcTable, $varMap, $conds,
2452 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2454 if ( $this->cliMode
) {
2455 // For massive migrations with downtime, we don't want to select everything
2456 // into memory and OOM, so do all this native on the server side if possible.
2457 return $this->nativeInsertSelect(
2469 return $this->nonNativeInsertSelect(
2482 * Implementation of insertSelect() based on select() and insert()
2484 * @see IDatabase::insertSelect()
2486 * @param string $destTable
2487 * @param string|array $srcTable
2488 * @param array $varMap
2489 * @param array $conds
2490 * @param string $fname
2491 * @param array $insertOptions
2492 * @param array $selectOptions
2493 * @param array $selectJoinConds
2496 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2497 $fname = __METHOD__
,
2498 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2500 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2501 // on only the master (without needing row-based-replication). It also makes it easy to
2502 // know how big the INSERT is going to be.
2504 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2505 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2507 $selectOptions[] = 'FOR UPDATE';
2508 $res = $this->select(
2509 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2516 $affectedRowCount = 0;
2517 $this->startAtomic( $fname );
2520 foreach ( $res as $row ) {
2521 $rows[] = (array)$row;
2523 // Avoid inserts that are too huge
2524 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2525 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2529 $affectedRowCount +
= $this->affectedRows();
2533 if ( $rows && $ok ) {
2534 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2536 $affectedRowCount +
= $this->affectedRows();
2540 $this->endAtomic( $fname );
2541 $this->affectedRowCount
= $affectedRowCount;
2543 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2544 $this->affectedRowCount
= 0;
2547 } catch ( Exception
$e ) {
2548 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2549 $this->affectedRowCount
= 0;
2555 * Native server-side implementation of insertSelect() for situations where
2556 * we don't want to select everything into memory
2558 * @see IDatabase::insertSelect()
2559 * @param string $destTable
2560 * @param string|array $srcTable
2561 * @param array $varMap
2562 * @param array $conds
2563 * @param string $fname
2564 * @param array $insertOptions
2565 * @param array $selectOptions
2566 * @param array $selectJoinConds
2569 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2570 $fname = __METHOD__
,
2571 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2573 $destTable = $this->tableName( $destTable );
2575 if ( !is_array( $insertOptions ) ) {
2576 $insertOptions = [ $insertOptions ];
2579 $insertOptions = $this->makeInsertOptions( $insertOptions );
2581 $selectSql = $this->selectSQLText(
2583 array_values( $varMap ),
2590 $sql = "INSERT $insertOptions" .
2591 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2594 return $this->query( $sql, $fname );
2598 * Construct a LIMIT query with optional offset. This is used for query
2599 * pages. The SQL should be adjusted so that only the first $limit rows
2600 * are returned. If $offset is provided as well, then the first $offset
2601 * rows should be discarded, and the next $limit rows should be returned.
2602 * If the result of the query is not ordered, then the rows to be returned
2603 * are theoretically arbitrary.
2605 * $sql is expected to be a SELECT, if that makes a difference.
2607 * The version provided by default works in MySQL and SQLite. It will very
2608 * likely need to be overridden for most other DBMSes.
2610 * @param string $sql SQL query we will append the limit too
2611 * @param int $limit The SQL limit
2612 * @param int|bool $offset The SQL offset (default false)
2613 * @throws DBUnexpectedError
2616 public function limitResult( $sql, $limit, $offset = false ) {
2617 if ( !is_numeric( $limit ) ) {
2618 throw new DBUnexpectedError( $this,
2619 "Invalid non-numeric limit passed to limitResult()\n" );
2622 return "$sql LIMIT "
2623 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2627 public function unionSupportsOrderAndLimit() {
2628 return true; // True for almost every DB supported
2631 public function unionQueries( $sqls, $all ) {
2632 $glue = $all ?
') UNION ALL (' : ') UNION (';
2634 return '(' . implode( $glue, $sqls ) . ')';
2637 public function unionConditionPermutations(
2638 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2639 $options = [], $join_conds = []
2641 // First, build the Cartesian product of $permute_conds
2643 foreach ( $permute_conds as $field => $values ) {
2645 // Skip empty $values
2648 $values = array_unique( $values ); // For sanity
2650 foreach ( $conds as $cond ) {
2651 foreach ( $values as $value ) {
2652 $cond[$field] = $value;
2653 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2659 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2661 // If there's just one condition and no subordering, hand off to
2662 // selectSQLText directly.
2663 if ( count( $conds ) === 1 &&
2664 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2666 return $this->selectSQLText(
2667 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2671 // Otherwise, we need to pull out the order and limit to apply after
2672 // the union. Then build the SQL queries for each set of conditions in
2673 // $conds. Then union them together (using UNION ALL, because the
2674 // product *should* already be distinct).
2675 $orderBy = $this->makeOrderBy( $options );
2676 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2677 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2678 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2679 if ( !$this->unionSupportsOrderAndLimit() ) {
2680 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2682 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2683 $options['ORDER BY'] = $options['INNER ORDER BY'];
2685 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2686 // We need to increase the limit by the offset rather than
2687 // using the offset directly, otherwise it'll skip incorrectly
2688 // in the subqueries.
2689 $options['LIMIT'] = $limit +
$offset;
2690 unset( $options['OFFSET'] );
2695 foreach ( $conds as $cond ) {
2696 $sqls[] = $this->selectSQLText(
2697 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2700 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2701 if ( $limit !== null ) {
2702 $sql = $this->limitResult( $sql, $limit, $offset );
2708 public function conditional( $cond, $trueVal, $falseVal ) {
2709 if ( is_array( $cond ) ) {
2710 $cond = $this->makeList( $cond, self
::LIST_AND
);
2713 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2716 public function strreplace( $orig, $old, $new ) {
2717 return "REPLACE({$orig}, {$old}, {$new})";
2720 public function getServerUptime() {
2724 public function wasDeadlock() {
2728 public function wasLockTimeout() {
2732 public function wasErrorReissuable() {
2736 public function wasReadOnlyError() {
2741 * Do not use this method outside of Database/DBError classes
2743 * @param int|string $errno
2744 * @return bool Whether the given query error was a connection drop
2746 public function wasConnectionError( $errno ) {
2750 public function deadlockLoop() {
2751 $args = func_get_args();
2752 $function = array_shift( $args );
2753 $tries = self
::DEADLOCK_TRIES
;
2755 $this->begin( __METHOD__
);
2758 /** @var Exception $e */
2762 $retVal = call_user_func_array( $function, $args );
2764 } catch ( DBQueryError
$e ) {
2765 if ( $this->wasDeadlock() ) {
2766 // Retry after a randomized delay
2767 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2769 // Throw the error back up
2773 } while ( --$tries > 0 );
2775 if ( $tries <= 0 ) {
2776 // Too many deadlocks; give up
2777 $this->rollback( __METHOD__
);
2780 $this->commit( __METHOD__
);
2786 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2787 # Real waits are implemented in the subclass.
2791 public function getReplicaPos() {
2796 public function getMasterPos() {
2801 public function serverIsReadOnly() {
2805 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2806 if ( !$this->trxLevel
) {
2807 throw new DBUnexpectedError( $this, "No transaction is active." );
2809 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2812 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2813 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2814 if ( !$this->trxLevel
) {
2815 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2819 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2820 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2821 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2822 // an implicit commit of all peer databases. This is true even if a transaction has
2823 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2824 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2826 // No transaction is active nor will start implicitly, so make one for this callback
2827 $this->startAtomic( __METHOD__
);
2829 call_user_func( $callback );
2830 $this->endAtomic( __METHOD__
);
2831 } catch ( Exception
$e ) {
2832 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2838 final public function setTransactionListener( $name, callable
$callback = null ) {
2840 $this->trxRecurringCallbacks
[$name] = $callback;
2842 unset( $this->trxRecurringCallbacks
[$name] );
2847 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2849 * This method should not be used outside of Database/LoadBalancer
2851 * @param bool $suppress
2854 final public function setTrxEndCallbackSuppression( $suppress ) {
2855 $this->trxEndCallbacksSuppressed
= $suppress;
2859 * Actually run and consume any "on transaction idle/resolution" callbacks.
2861 * This method should not be used outside of Database/LoadBalancer
2863 * @param int $trigger IDatabase::TRIGGER_* constant
2867 public function runOnTransactionIdleCallbacks( $trigger ) {
2868 if ( $this->trxEndCallbacksSuppressed
) {
2872 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2873 /** @var Exception $e */
2874 $e = null; // first exception
2875 do { // callbacks may add callbacks :)
2876 $callbacks = array_merge(
2877 $this->trxIdleCallbacks
,
2878 $this->trxEndCallbacks
// include "transaction resolution" callbacks
2880 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
2881 $this->trxEndCallbacks
= []; // consumed (recursion guard)
2882 foreach ( $callbacks as $callback ) {
2884 list( $phpCallback ) = $callback;
2885 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2886 call_user_func_array( $phpCallback, [ $trigger ] );
2888 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2890 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2892 } catch ( Exception
$ex ) {
2893 call_user_func( $this->errorLogger
, $ex );
2895 // Some callbacks may use startAtomic/endAtomic, so make sure
2896 // their transactions are ended so other callbacks don't fail
2897 if ( $this->trxLevel() ) {
2898 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2902 } while ( count( $this->trxIdleCallbacks
) );
2904 if ( $e instanceof Exception
) {
2905 throw $e; // re-throw any first exception
2910 * Actually run and consume any "on transaction pre-commit" callbacks.
2912 * This method should not be used outside of Database/LoadBalancer
2917 public function runOnTransactionPreCommitCallbacks() {
2918 $e = null; // first exception
2919 do { // callbacks may add callbacks :)
2920 $callbacks = $this->trxPreCommitCallbacks
;
2921 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
2922 foreach ( $callbacks as $callback ) {
2924 list( $phpCallback ) = $callback;
2925 call_user_func( $phpCallback );
2926 } catch ( Exception
$ex ) {
2927 call_user_func( $this->errorLogger
, $ex );
2931 } while ( count( $this->trxPreCommitCallbacks
) );
2933 if ( $e instanceof Exception
) {
2934 throw $e; // re-throw any first exception
2939 * Actually run any "transaction listener" callbacks.
2941 * This method should not be used outside of Database/LoadBalancer
2943 * @param int $trigger IDatabase::TRIGGER_* constant
2947 public function runTransactionListenerCallbacks( $trigger ) {
2948 if ( $this->trxEndCallbacksSuppressed
) {
2952 /** @var Exception $e */
2953 $e = null; // first exception
2955 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
2957 $phpCallback( $trigger, $this );
2958 } catch ( Exception
$ex ) {
2959 call_user_func( $this->errorLogger
, $ex );
2964 if ( $e instanceof Exception
) {
2965 throw $e; // re-throw any first exception
2969 final public function startAtomic( $fname = __METHOD__
) {
2970 if ( !$this->trxLevel
) {
2971 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2972 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2973 // in all changes being in one transaction to keep requests transactional.
2974 if ( !$this->getFlag( self
::DBO_TRX
) ) {
2975 $this->trxAutomaticAtomic
= true;
2979 $this->trxAtomicLevels
[] = $fname;
2982 final public function endAtomic( $fname = __METHOD__
) {
2983 if ( !$this->trxLevel
) {
2984 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
2986 if ( !$this->trxAtomicLevels ||
2987 array_pop( $this->trxAtomicLevels
) !== $fname
2989 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
2992 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
2993 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
2997 final public function doAtomicSection( $fname, callable
$callback ) {
2998 $this->startAtomic( $fname );
3000 $res = call_user_func_array( $callback, [ $this, $fname ] );
3001 } catch ( Exception
$e ) {
3002 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3005 $this->endAtomic( $fname );
3010 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3011 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3012 if ( $this->trxLevel
) {
3013 if ( $this->trxAtomicLevels
) {
3014 $levels = implode( ', ', $this->trxAtomicLevels
);
3015 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3016 throw new DBUnexpectedError( $this, $msg );
3017 } elseif ( !$this->trxAutomatic
) {
3018 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3019 throw new DBUnexpectedError( $this, $msg );
3021 // @TODO: make this an exception at some point
3022 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3023 $this->queryLogger
->error( $msg );
3024 return; // join the main transaction set
3026 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3027 // @TODO: make this an exception at some point
3028 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3029 $this->queryLogger
->error( $msg );
3030 return; // let any writes be in the main transaction
3033 // Avoid fatals if close() was called
3034 $this->assertOpen();
3036 $this->doBegin( $fname );
3037 $this->trxTimestamp
= microtime( true );
3038 $this->trxFname
= $fname;
3039 $this->trxDoneWrites
= false;
3040 $this->trxAutomaticAtomic
= false;
3041 $this->trxAtomicLevels
= [];
3042 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3043 $this->trxWriteDuration
= 0.0;
3044 $this->trxWriteQueryCount
= 0;
3045 $this->trxWriteAffectedRows
= 0;
3046 $this->trxWriteAdjDuration
= 0.0;
3047 $this->trxWriteAdjQueryCount
= 0;
3048 $this->trxWriteCallers
= [];
3049 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3050 // Get an estimate of the replica DB lag before then, treating estimate staleness
3051 // as lag itself just to be safe
3052 $status = $this->getApproximateLagStatus();
3053 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3054 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3055 // caller will think its OK to muck around with the transaction just because startAtomic()
3056 // has not yet completed (e.g. setting trxAtomicLevels).
3057 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3061 * Issues the BEGIN command to the database server.
3063 * @see Database::begin()
3064 * @param string $fname
3066 protected function doBegin( $fname ) {
3067 $this->query( 'BEGIN', $fname );
3068 $this->trxLevel
= 1;
3071 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3072 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3073 // There are still atomic sections open. This cannot be ignored
3074 $levels = implode( ', ', $this->trxAtomicLevels
);
3075 throw new DBUnexpectedError(
3077 "$fname: Got COMMIT while atomic sections $levels are still open."
3081 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3082 if ( !$this->trxLevel
) {
3083 return; // nothing to do
3084 } elseif ( !$this->trxAutomatic
) {
3085 throw new DBUnexpectedError(
3087 "$fname: Flushing an explicit transaction, getting out of sync."
3091 if ( !$this->trxLevel
) {
3092 $this->queryLogger
->error(
3093 "$fname: No transaction to commit, something got out of sync." );
3094 return; // nothing to do
3095 } elseif ( $this->trxAutomatic
) {
3096 // @TODO: make this an exception at some point
3097 $msg = "$fname: Explicit commit of implicit transaction.";
3098 $this->queryLogger
->error( $msg );
3099 return; // wait for the main transaction set commit round
3103 // Avoid fatals if close() was called
3104 $this->assertOpen();
3106 $this->runOnTransactionPreCommitCallbacks();
3107 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3108 $this->doCommit( $fname );
3109 if ( $this->trxDoneWrites
) {
3110 $this->lastWriteTime
= microtime( true );
3111 $this->trxProfiler
->transactionWritingOut(
3116 $this->trxWriteAffectedRows
3120 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3121 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3125 * Issues the COMMIT command to the database server.
3127 * @see Database::commit()
3128 * @param string $fname
3130 protected function doCommit( $fname ) {
3131 if ( $this->trxLevel
) {
3132 $this->query( 'COMMIT', $fname );
3133 $this->trxLevel
= 0;
3137 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3138 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3139 if ( !$this->trxLevel
) {
3140 return; // nothing to do
3143 if ( !$this->trxLevel
) {
3144 $this->queryLogger
->error(
3145 "$fname: No transaction to rollback, something got out of sync." );
3146 return; // nothing to do
3147 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3148 throw new DBUnexpectedError(
3150 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3155 // Avoid fatals if close() was called
3156 $this->assertOpen();
3158 $this->doRollback( $fname );
3159 $this->trxAtomicLevels
= [];
3160 if ( $this->trxDoneWrites
) {
3161 $this->trxProfiler
->transactionWritingOut(
3168 $this->trxIdleCallbacks
= []; // clear
3169 $this->trxPreCommitCallbacks
= []; // clear
3171 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3172 } catch ( Exception
$e ) {
3173 // already logged; finish and let LoadBalancer move on during mass-rollback
3176 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3177 } catch ( Exception
$e ) {
3178 // already logged; let LoadBalancer move on during mass-rollback
3183 * Issues the ROLLBACK command to the database server.
3185 * @see Database::rollback()
3186 * @param string $fname
3188 protected function doRollback( $fname ) {
3189 if ( $this->trxLevel
) {
3190 # Disconnects cause rollback anyway, so ignore those errors
3191 $ignoreErrors = true;
3192 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3193 $this->trxLevel
= 0;
3197 public function flushSnapshot( $fname = __METHOD__
) {
3198 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3199 // This only flushes transactions to clear snapshots, not to write data
3200 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3201 throw new DBUnexpectedError(
3203 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3207 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3210 public function explicitTrxActive() {
3211 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3214 public function duplicateTableStructure(
3215 $oldName, $newName, $temporary = false, $fname = __METHOD__
3217 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3220 public function listTables( $prefix = null, $fname = __METHOD__
) {
3221 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3224 public function listViews( $prefix = null, $fname = __METHOD__
) {
3225 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3228 public function timestamp( $ts = 0 ) {
3229 $t = new ConvertibleTimestamp( $ts );
3230 // Let errors bubble up to avoid putting garbage in the DB
3231 return $t->getTimestamp( TS_MW
);
3234 public function timestampOrNull( $ts = null ) {
3235 if ( is_null( $ts ) ) {
3238 return $this->timestamp( $ts );
3242 public function affectedRows() {
3243 return ( $this->affectedRowCount
=== null )
3244 ?
$this->fetchAffectedRowCount() // default to driver value
3245 : $this->affectedRowCount
;
3249 * @return int Number of retrieved rows according to the driver
3251 abstract protected function fetchAffectedRowCount();
3254 * Take the result from a query, and wrap it in a ResultWrapper if
3255 * necessary. Boolean values are passed through as is, to indicate success
3256 * of write queries or failure.
3258 * Once upon a time, Database::query() returned a bare MySQL result
3259 * resource, and it was necessary to call this function to convert it to
3260 * a wrapper. Nowadays, raw database objects are never exposed to external
3261 * callers, so this is unnecessary in external code.
3263 * @param bool|ResultWrapper|resource|object $result
3264 * @return bool|ResultWrapper
3266 protected function resultObject( $result ) {
3269 } elseif ( $result instanceof ResultWrapper
) {
3271 } elseif ( $result === true ) {
3272 // Successful write query
3275 return new ResultWrapper( $this, $result );
3279 public function ping( &$rtt = null ) {
3280 // Avoid hitting the server if it was hit recently
3281 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3282 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3283 $rtt = $this->rttEstimate
;
3284 return true; // don't care about $rtt
3288 // This will reconnect if possible or return false if not
3289 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3290 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3291 $this->restoreFlags( self
::RESTORE_PRIOR
);
3294 $rtt = $this->rttEstimate
;
3301 * Close existing database connection and open a new connection
3303 * @return bool True if new connection is opened successfully, false if error
3305 protected function reconnect() {
3306 $this->closeConnection();
3307 $this->opened
= false;
3308 $this->conn
= false;
3310 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3311 $this->lastPing
= microtime( true );
3313 } catch ( DBConnectionError
$e ) {
3320 public function getSessionLagStatus() {
3321 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3325 * Get the replica DB lag when the current transaction started
3327 * This is useful when transactions might use snapshot isolation
3328 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3329 * is this lag plus transaction duration. If they don't, it is still
3330 * safe to be pessimistic. This returns null if there is no transaction.
3332 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3335 protected function getTransactionLagStatus() {
3336 return $this->trxLevel
3337 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3342 * Get a replica DB lag estimate for this server
3344 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3347 protected function getApproximateLagStatus() {
3349 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3350 'since' => microtime( true )
3355 * Merge the result of getSessionLagStatus() for several DBs
3356 * using the most pessimistic values to estimate the lag of
3357 * any data derived from them in combination
3359 * This is information is useful for caching modules
3361 * @see WANObjectCache::set()
3362 * @see WANObjectCache::getWithSetCallback()
3364 * @param IDatabase $db1
3365 * @param IDatabase $db2 [optional]
3366 * @return array Map of values:
3367 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3368 * - since: oldest UNIX timestamp of any of the DB lag estimates
3369 * - pending: whether any of the DBs have uncommitted changes
3373 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3374 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3375 foreach ( func_get_args() as $db ) {
3376 /** @var IDatabase $db */
3377 $status = $db->getSessionLagStatus();
3378 if ( $status['lag'] === false ) {
3379 $res['lag'] = false;
3380 } elseif ( $res['lag'] !== false ) {
3381 $res['lag'] = max( $res['lag'], $status['lag'] );
3383 $res['since'] = min( $res['since'], $status['since'] );
3384 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3390 public function getLag() {
3394 public function maxListLen() {
3398 public function encodeBlob( $b ) {
3402 public function decodeBlob( $b ) {
3403 if ( $b instanceof Blob
) {
3409 public function setSessionOptions( array $options ) {
3412 public function sourceFile(
3414 callable
$lineCallback = null,
3415 callable
$resultCallback = null,
3417 callable
$inputCallback = null
3419 Wikimedia\
suppressWarnings();
3420 $fp = fopen( $filename, 'r' );
3421 Wikimedia\restoreWarnings
();
3423 if ( false === $fp ) {
3424 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3428 $fname = __METHOD__
. "( $filename )";
3432 $error = $this->sourceStream(
3433 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3434 } catch ( Exception
$e ) {
3444 public function setSchemaVars( $vars ) {
3445 $this->schemaVars
= $vars;
3448 public function sourceStream(
3450 callable
$lineCallback = null,
3451 callable
$resultCallback = null,
3452 $fname = __METHOD__
,
3453 callable
$inputCallback = null
3455 $delimiterReset = new ScopedCallback(
3456 function ( $delimiter ) {
3457 $this->delimiter
= $delimiter;
3459 [ $this->delimiter
]
3463 while ( !feof( $fp ) ) {
3464 if ( $lineCallback ) {
3465 call_user_func( $lineCallback );
3468 $line = trim( fgets( $fp ) );
3470 if ( $line == '' ) {
3474 if ( '-' == $line[0] && '-' == $line[1] ) {
3482 $done = $this->streamStatementEnd( $cmd, $line );
3486 if ( $done ||
feof( $fp ) ) {
3487 $cmd = $this->replaceVars( $cmd );
3489 if ( $inputCallback ) {
3490 $callbackResult = call_user_func( $inputCallback, $cmd );
3492 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3493 $cmd = $callbackResult;
3498 $res = $this->query( $cmd, $fname );
3500 if ( $resultCallback ) {
3501 call_user_func( $resultCallback, $res, $this );
3504 if ( false === $res ) {
3505 $err = $this->lastError();
3507 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3514 ScopedCallback
::consume( $delimiterReset );
3519 * Called by sourceStream() to check if we've reached a statement end
3521 * @param string &$sql SQL assembled so far
3522 * @param string &$newLine New line about to be added to $sql
3523 * @return bool Whether $newLine contains end of the statement
3525 public function streamStatementEnd( &$sql, &$newLine ) {
3526 if ( $this->delimiter
) {
3528 $newLine = preg_replace(
3529 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3530 if ( $newLine != $prev ) {
3539 * Database independent variable replacement. Replaces a set of variables
3540 * in an SQL statement with their contents as given by $this->getSchemaVars().
3542 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3544 * - '{$var}' should be used for text and is passed through the database's
3546 * - `{$var}` should be used for identifiers (e.g. table and database names).
3547 * It is passed through the database's addIdentifierQuotes method which
3548 * can be overridden if the database uses something other than backticks.
3549 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3550 * database's tableName method.
3551 * - / *i* / passes the name that follows through the database's indexName method.
3552 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3553 * its use should be avoided. In 1.24 and older, string encoding was applied.
3555 * @param string $ins SQL statement to replace variables in
3556 * @return string The new SQL statement with variables replaced
3558 protected function replaceVars( $ins ) {
3559 $vars = $this->getSchemaVars();
3560 return preg_replace_callback(
3562 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3563 \'\{\$ (\w+) }\' | # 3. addQuotes
3564 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3565 /\*\$ (\w+) \*/ # 5. leave unencoded
3567 function ( $m ) use ( $vars ) {
3568 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3569 // check for both nonexistent keys *and* the empty string.
3570 if ( isset( $m[1] ) && $m[1] !== '' ) {
3571 if ( $m[1] === 'i' ) {
3572 return $this->indexName( $m[2] );
3574 return $this->tableName( $m[2] );
3576 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3577 return $this->addQuotes( $vars[$m[3]] );
3578 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3579 return $this->addIdentifierQuotes( $vars[$m[4]] );
3580 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3581 return $vars[$m[5]];
3591 * Get schema variables. If none have been set via setSchemaVars(), then
3592 * use some defaults from the current object.
3596 protected function getSchemaVars() {
3597 if ( $this->schemaVars
) {
3598 return $this->schemaVars
;
3600 return $this->getDefaultSchemaVars();
3605 * Get schema variables to use if none have been set via setSchemaVars().
3607 * Override this in derived classes to provide variables for tables.sql
3608 * and SQL patch files.
3612 protected function getDefaultSchemaVars() {
3616 public function lockIsFree( $lockName, $method ) {
3617 // RDBMs methods for checking named locks may or may not count this thread itself.
3618 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3619 // the behavior choosen by the interface for this method.
3620 return !isset( $this->namedLocksHeld
[$lockName] );
3623 public function lock( $lockName, $method, $timeout = 5 ) {
3624 $this->namedLocksHeld
[$lockName] = 1;
3629 public function unlock( $lockName, $method ) {
3630 unset( $this->namedLocksHeld
[$lockName] );
3635 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3636 if ( $this->writesOrCallbacksPending() ) {
3637 // This only flushes transactions to clear snapshots, not to write data
3638 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3639 throw new DBUnexpectedError(
3641 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3645 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3649 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3650 if ( $this->trxLevel() ) {
3651 // There is a good chance an exception was thrown, causing any early return
3652 // from the caller. Let any error handler get a chance to issue rollback().
3653 // If there isn't one, let the error bubble up and trigger server-side rollback.
3654 $this->onTransactionResolution(
3655 function () use ( $lockKey, $fname ) {
3656 $this->unlock( $lockKey, $fname );
3661 $this->unlock( $lockKey, $fname );
3665 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3670 public function namedLocksEnqueue() {
3674 public function tableLocksHaveTransactionScope() {
3678 final public function lockTables( array $read, array $write, $method ) {
3679 if ( $this->writesOrCallbacksPending() ) {
3680 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3683 if ( $this->tableLocksHaveTransactionScope() ) {
3684 $this->startAtomic( $method );
3687 return $this->doLockTables( $read, $write, $method );
3691 * Helper function for lockTables() that handles the actual table locking
3693 * @param array $read Array of tables to lock for read access
3694 * @param array $write Array of tables to lock for write access
3695 * @param string $method Name of caller
3698 protected function doLockTables( array $read, array $write, $method ) {
3702 final public function unlockTables( $method ) {
3703 if ( $this->tableLocksHaveTransactionScope() ) {
3704 $this->endAtomic( $method );
3706 return true; // locks released on COMMIT/ROLLBACK
3709 return $this->doUnlockTables( $method );
3713 * Helper function for unlockTables() that handles the actual table unlocking
3715 * @param string $method Name of caller
3718 protected function doUnlockTables( $method ) {
3724 * @param string $tableName
3725 * @param string $fName
3726 * @return bool|ResultWrapper
3729 public function dropTable( $tableName, $fName = __METHOD__
) {
3730 if ( !$this->tableExists( $tableName, $fName ) ) {
3733 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3735 return $this->query( $sql, $fName );
3738 public function getInfinity() {
3742 public function encodeExpiry( $expiry ) {
3743 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3744 ?
$this->getInfinity()
3745 : $this->timestamp( $expiry );
3748 public function decodeExpiry( $expiry, $format = TS_MW
) {
3749 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3753 return ConvertibleTimestamp
::convert( $format, $expiry );
3756 public function setBigSelects( $value = true ) {
3760 public function isReadOnly() {
3761 return ( $this->getReadOnlyReason() !== false );
3765 * @return string|bool Reason this DB is read-only or false if it is not
3767 protected function getReadOnlyReason() {
3768 $reason = $this->getLBInfo( 'readOnlyReason' );
3770 return is_string( $reason ) ?
$reason : false;
3773 public function setTableAliases( array $aliases ) {
3774 $this->tableAliases
= $aliases;
3778 * @return bool Whether a DB user is required to access the DB
3781 protected function requiresDatabaseUser() {
3786 * Get the underlying binding connection handle
3788 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3789 * This catches broken callers than catch and ignore disconnection exceptions.
3790 * Unlike checking isOpen(), this is safe to call inside of open().
3792 * @return resource|object
3793 * @throws DBUnexpectedError
3796 protected function getBindingHandle() {
3797 if ( !$this->conn
) {
3798 throw new DBUnexpectedError(
3800 'DB connection was already closed or the connection dropped.'
3811 public function __toString() {
3812 return (string)$this->conn
;
3816 * Make sure that copies do not share the same client binding handle
3817 * @throws DBConnectionError
3819 public function __clone() {
3820 $this->connLogger
->warning(
3821 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3822 ( new RuntimeException() )->getTraceAsString()
3825 if ( $this->isOpen() ) {
3826 // Open a new connection resource without messing with the old one
3827 $this->opened
= false;
3828 $this->conn
= false;
3829 $this->trxEndCallbacks
= []; // don't copy
3830 $this->handleSessionLoss(); // no trx or locks anymore
3831 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3832 $this->lastPing
= microtime( true );
3837 * Called by serialize. Throw an exception when DB connection is serialized.
3838 * This causes problems on some database engines because the connection is
3839 * not restored on unserialize.
3841 public function __sleep() {
3842 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3843 'the connection is not restored on wakeup.' );
3847 * Run a few simple sanity checks and close dangling connections
3849 public function __destruct() {
3850 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3851 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3854 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3855 if ( $danglingWriters ) {
3856 $fnames = implode( ', ', $danglingWriters );
3857 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3860 if ( $this->conn
) {
3861 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3862 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3863 Wikimedia\
suppressWarnings();
3864 $this->closeConnection();
3865 Wikimedia\restoreWarnings
();
3866 $this->conn
= false;
3867 $this->opened
= false;
3872 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3873 class_alias( Database
::class, 'Database' ); // b/c global alias