3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
26 namespace Wikimedia\Rdbms
;
28 use Psr\Log\LoggerAwareInterface
;
29 use Psr\Log\LoggerInterface
;
30 use Psr\Log\NullLogger
;
31 use Wikimedia\ScopedCallback
;
32 use Wikimedia\Timestamp\ConvertibleTimestamp
;
36 use InvalidArgumentException
;
41 * Relational database abstraction object
46 abstract class Database
implements IDatabase
, IMaintainableDatabase
, LoggerAwareInterface
{
47 /** Number of times to re-try an operation in case of deadlock */
48 const DEADLOCK_TRIES
= 4;
49 /** Minimum time to wait before retry, in microseconds */
50 const DEADLOCK_DELAY_MIN
= 500000;
51 /** Maximum time to wait before retry */
52 const DEADLOCK_DELAY_MAX
= 1500000;
54 /** How long before it is worth doing a dummy query to test the connection */
56 const PING_QUERY
= 'SELECT 1 AS ping';
58 const TINY_WRITE_SEC
= 0.010;
59 const SLOW_WRITE_SEC
= 0.500;
60 const SMALL_WRITE_ROWS
= 100;
62 /** @var string SQL query */
63 protected $lastQuery = '';
64 /** @var float|bool UNIX timestamp of last write query */
65 protected $lastWriteTime = false;
66 /** @var string|bool */
67 protected $phpError = false;
76 /** @var array[] $aliases Map of (table => (dbname, schema, prefix) map) */
77 protected $tableAliases = [];
78 /** @var bool Whether this PHP instance is for a CLI script */
80 /** @var string Agent name for query profiling */
83 /** @var BagOStuff APC cache */
85 /** @var LoggerInterface */
86 protected $connLogger;
87 /** @var LoggerInterface */
88 protected $queryLogger;
89 /** @var callback Error logging callback */
90 protected $errorLogger;
92 /** @var resource|null Database connection */
93 protected $conn = null;
95 protected $opened = false;
97 /** @var array[] List of (callable, method name) */
98 protected $trxIdleCallbacks = [];
99 /** @var array[] List of (callable, method name) */
100 protected $trxPreCommitCallbacks = [];
101 /** @var array[] List of (callable, method name) */
102 protected $trxEndCallbacks = [];
103 /** @var callable[] Map of (name => callable) */
104 protected $trxRecurringCallbacks = [];
105 /** @var bool Whether to suppress triggering of transaction end callbacks */
106 protected $trxEndCallbacksSuppressed = false;
109 protected $tablePrefix = '';
111 protected $schema = '';
115 protected $lbInfo = [];
116 /** @var array|bool */
117 protected $schemaVars = false;
119 protected $sessionVars = [];
120 /** @var array|null */
121 protected $preparedArgs;
122 /** @var string|bool|null Stashed value of html_errors INI setting */
123 protected $htmlErrors;
125 protected $delimiter = ';';
126 /** @var DatabaseDomain */
127 protected $currentDomain;
128 /** @var integer|null Rows affected by the last query to query() or its CRUD wrappers */
129 protected $affectedRowCount;
132 * Either 1 if a transaction is active or 0 otherwise.
133 * The other Trx fields may not be meaningfull if this is 0.
137 protected $trxLevel = 0;
139 * Either a short hexidecimal string if a transaction is active or ""
142 * @see Database::trxLevel
144 protected $trxShortId = '';
146 * The UNIX time that the transaction started. Callers can assume that if
147 * snapshot isolation is used, then the data is *at least* up to date to that
148 * point (possibly more up-to-date since the first SELECT defines the snapshot).
151 * @see Database::trxLevel
153 private $trxTimestamp = null;
154 /** @var float Lag estimate at the time of BEGIN */
155 private $trxReplicaLag = null;
157 * Remembers the function name given for starting the most recent transaction via begin().
158 * Used to provide additional context for error reporting.
161 * @see Database::trxLevel
163 private $trxFname = null;
165 * Record if possible write queries were done in the last transaction started
168 * @see Database::trxLevel
170 private $trxDoneWrites = false;
172 * Record if the current transaction was started implicitly due to DBO_TRX being set.
175 * @see Database::trxLevel
177 private $trxAutomatic = false;
179 * Array of levels of atomicity within transactions
183 private $trxAtomicLevels = [];
185 * Record if the current transaction was started implicitly by Database::startAtomic
189 private $trxAutomaticAtomic = false;
191 * Track the write query callers of the current transaction
195 private $trxWriteCallers = [];
197 * @var float Seconds spent in write queries for the current transaction
199 private $trxWriteDuration = 0.0;
201 * @var int Number of write queries for the current transaction
203 private $trxWriteQueryCount = 0;
205 * @var int Number of rows affected by write queries for the current transaction
207 private $trxWriteAffectedRows = 0;
209 * @var float Like trxWriteQueryCount but excludes lock-bound, easy to replicate, queries
211 private $trxWriteAdjDuration = 0.0;
213 * @var int Number of write queries counted in trxWriteAdjDuration
215 private $trxWriteAdjQueryCount = 0;
217 * @var float RTT time estimate
219 private $rttEstimate = 0.0;
221 /** @var array Map of (name => 1) for locks obtained via lock() */
222 private $namedLocksHeld = [];
223 /** @var array Map of (table name => 1) for TEMPORARY tables */
224 protected $sessionTempTables = [];
226 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
227 private $lazyMasterHandle;
229 /** @var float UNIX timestamp */
230 protected $lastPing = 0.0;
232 /** @var int[] Prior flags member variable values */
233 private $priorFlags = [];
235 /** @var object|string Class name or object With profileIn/profileOut methods */
237 /** @var TransactionProfiler */
238 protected $trxProfiler;
241 protected $nonNativeInsertSelectBatchSize = 10000;
244 * Constructor and database handle and attempt to connect to the DB server
246 * IDatabase classes should not be constructed directly in external
247 * code. Database::factory() should be used instead.
249 * @param array $params Parameters passed from Database::factory()
251 function __construct( array $params ) {
252 $server = $params['host'];
253 $user = $params['user'];
254 $password = $params['password'];
255 $dbName = $params['dbname'];
257 $this->schema
= $params['schema'];
258 $this->tablePrefix
= $params['tablePrefix'];
260 $this->cliMode
= $params['cliMode'];
261 // Agent name is added to SQL queries in a comment, so make sure it can't break out
262 $this->agent
= str_replace( '/', '-', $params['agent'] );
264 $this->flags
= $params['flags'];
265 if ( $this->flags
& self
::DBO_DEFAULT
) {
266 if ( $this->cliMode
) {
267 $this->flags
&= ~self
::DBO_TRX
;
269 $this->flags |
= self
::DBO_TRX
;
273 $this->sessionVars
= $params['variables'];
275 $this->srvCache
= isset( $params['srvCache'] )
276 ?
$params['srvCache']
277 : new HashBagOStuff();
279 $this->profiler
= $params['profiler'];
280 $this->trxProfiler
= $params['trxProfiler'];
281 $this->connLogger
= $params['connLogger'];
282 $this->queryLogger
= $params['queryLogger'];
283 $this->errorLogger
= $params['errorLogger'];
285 if ( isset( $params['nonNativeInsertSelectBatchSize'] ) ) {
286 $this->nonNativeInsertSelectBatchSize
= $params['nonNativeInsertSelectBatchSize'];
289 // Set initial dummy domain until open() sets the final DB/prefix
290 $this->currentDomain
= DatabaseDomain
::newUnspecified();
293 $this->open( $server, $user, $password, $dbName );
294 } elseif ( $this->requiresDatabaseUser() ) {
295 throw new InvalidArgumentException( "No database user provided." );
298 // Set the domain object after open() sets the relevant fields
299 if ( $this->dbName
!= '' ) {
300 // Domains with server scope but a table prefix are not used by IDatabase classes
301 $this->currentDomain
= new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
);
306 * Construct a Database subclass instance given a database type and parameters
308 * This also connects to the database immediately upon object construction
310 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
311 * @param array $p Parameter map with keys:
312 * - host : The hostname of the DB server
313 * - user : The name of the database user the client operates under
314 * - password : The password for the database user
315 * - dbname : The name of the database to use where queries do not specify one.
316 * The database must exist or an error might be thrown. Setting this to the empty string
317 * will avoid any such errors and make the handle have no implicit database scope. This is
318 * useful for queries like SHOW STATUS, CREATE DATABASE, or DROP DATABASE. Note that a
319 * "database" in Postgres is rougly equivalent to an entire MySQL server. This the domain
320 * in which user names and such are defined, e.g. users are database-specific in Postgres.
321 * - schema : The database schema to use (if supported). A "schema" in Postgres is roughly
322 * equivalent to a "database" in MySQL. Note that MySQL and SQLite do not use schemas.
323 * - tablePrefix : Optional table prefix that is implicitly added on to all table names
324 * recognized in queries. This can be used in place of schemas for handle site farms.
325 * - flags : Optional bitfield of DBO_* constants that define connection, protocol,
326 * buffering, and transaction behavior. It is STRONGLY adviced to leave the DBO_DEFAULT
327 * flag in place UNLESS this this database simply acts as a key/value store.
328 * - driver: Optional name of a specific DB client driver. For MySQL, there is only the
329 * 'mysqli' driver; the old one 'mysql' has been removed.
330 * - variables: Optional map of session variables to set after connecting. This can be
331 * used to adjust lock timeouts or encoding modes and the like.
332 * - connLogger: Optional PSR-3 logger interface instance.
333 * - queryLogger: Optional PSR-3 logger interface instance.
334 * - profiler: Optional class name or object with profileIn()/profileOut() methods.
335 * These will be called in query(), using a simplified version of the SQL that also
336 * includes the agent as a SQL comment.
337 * - trxProfiler: Optional TransactionProfiler instance.
338 * - errorLogger: Optional callback that takes an Exception and logs it.
339 * - cliMode: Whether to consider the execution context that of a CLI script.
340 * - agent: Optional name used to identify the end-user in query profiling/logging.
341 * - srvCache: Optional BagOStuff instance to an APC-style cache.
342 * - nonNativeInsertSelectBatchSize: Optional batch size for non-native INSERT SELECT emulation.
343 * @return Database|null If the database driver or extension cannot be found
344 * @throws InvalidArgumentException If the database driver or extension cannot be found
347 final public static function factory( $dbType, $p = [] ) {
348 $class = self
::getClass( $dbType, isset( $p['driver'] ) ?
$p['driver'] : null );
350 if ( class_exists( $class ) && is_subclass_of( $class, IDatabase
::class ) ) {
351 // Resolve some defaults for b/c
352 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
353 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
354 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
355 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
356 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
357 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
358 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : '';
359 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : '';
360 $p['cliMode'] = isset( $p['cliMode'] )
362 : ( PHP_SAPI
=== 'cli' || PHP_SAPI
=== 'phpdbg' );
363 $p['agent'] = isset( $p['agent'] ) ?
$p['agent'] : '';
364 if ( !isset( $p['connLogger'] ) ) {
365 $p['connLogger'] = new NullLogger();
367 if ( !isset( $p['queryLogger'] ) ) {
368 $p['queryLogger'] = new NullLogger();
370 $p['profiler'] = isset( $p['profiler'] ) ?
$p['profiler'] : null;
371 if ( !isset( $p['trxProfiler'] ) ) {
372 $p['trxProfiler'] = new TransactionProfiler();
374 if ( !isset( $p['errorLogger'] ) ) {
375 $p['errorLogger'] = function ( Exception
$e ) {
376 trigger_error( get_class( $e ) . ': ' . $e->getMessage(), E_USER_WARNING
);
380 $conn = new $class( $p );
389 * @param string $dbType A possible DB type (sqlite, mysql, postgres,...)
390 * @param string|null $driver Optional name of a specific DB client driver
391 * @return string Database subclass name to use
392 * @throws InvalidArgumentException
394 private static function getClass( $dbType, $driver = null ) {
395 // For database types with built-in support, the below maps type to IDatabase
396 // implementations. For types with multipe driver implementations (PHP extensions),
397 // an array can be used, keyed by extension name. In case of an array, the
398 // optional 'driver' parameter can be used to force a specific driver. Otherwise,
399 // we auto-detect the first available driver. For types without built-in support,
400 // an class named "Database<Type>" us used, eg. DatabaseFoo for type 'foo'.
401 static $builtinTypes = [
402 'mssql' => DatabaseMssql
::class,
403 'mysql' => [ 'mysqli' => DatabaseMysqli
::class ],
404 'sqlite' => DatabaseSqlite
::class,
405 'postgres' => DatabasePostgres
::class,
408 $dbType = strtolower( $dbType );
411 if ( isset( $builtinTypes[$dbType] ) ) {
412 $possibleDrivers = $builtinTypes[$dbType];
413 if ( is_string( $possibleDrivers ) ) {
414 $class = $possibleDrivers;
416 if ( (string)$driver !== '' ) {
417 if ( !isset( $possibleDrivers[$driver] ) ) {
418 throw new InvalidArgumentException( __METHOD__
.
419 " type '$dbType' does not support driver '{$driver}'" );
421 $class = $possibleDrivers[$driver];
424 foreach ( $possibleDrivers as $posDriver => $possibleClass ) {
425 if ( extension_loaded( $posDriver ) ) {
426 $class = $possibleClass;
433 $class = 'Database' . ucfirst( $dbType );
436 if ( $class === false ) {
437 throw new InvalidArgumentException( __METHOD__
.
438 " no viable database extension found for type '$dbType'" );
445 * Set the PSR-3 logger interface to use for query logging. (The logger
446 * interfaces for connection logging and error logging can be set with the
449 * @param LoggerInterface $logger
451 public function setLogger( LoggerInterface
$logger ) {
452 $this->queryLogger
= $logger;
455 public function getServerInfo() {
456 return $this->getServerVersion();
459 public function bufferResults( $buffer = null ) {
460 $res = !$this->getFlag( self
::DBO_NOBUFFER
);
461 if ( $buffer !== null ) {
463 ?
$this->clearFlag( self
::DBO_NOBUFFER
)
464 : $this->setFlag( self
::DBO_NOBUFFER
);
471 * Turns on (false) or off (true) the automatic generation and sending
472 * of a "we're sorry, but there has been a database error" page on
473 * database errors. Default is on (false). When turned off, the
474 * code should use lastErrno() and lastError() to handle the
475 * situation as appropriate.
477 * Do not use this function outside of the Database classes.
479 * @param null|bool $ignoreErrors
480 * @return bool The previous value of the flag.
482 protected function ignoreErrors( $ignoreErrors = null ) {
483 $res = $this->getFlag( self
::DBO_IGNORE
);
484 if ( $ignoreErrors !== null ) {
485 // setFlag()/clearFlag() do not allow DBO_IGNORE changes for sanity
486 if ( $ignoreErrors ) {
487 $this->flags |
= self
::DBO_IGNORE
;
489 $this->flags
&= ~self
::DBO_IGNORE
;
496 public function trxLevel() {
497 return $this->trxLevel
;
500 public function trxTimestamp() {
501 return $this->trxLevel ?
$this->trxTimestamp
: null;
504 public function tablePrefix( $prefix = null ) {
505 $old = $this->tablePrefix
;
506 if ( $prefix !== null ) {
507 $this->tablePrefix
= $prefix;
508 $this->currentDomain
= ( $this->dbName
!= '' )
509 ?
new DatabaseDomain( $this->dbName
, null, $this->tablePrefix
)
510 : DatabaseDomain
::newUnspecified();
516 public function dbSchema( $schema = null ) {
517 $old = $this->schema
;
518 if ( $schema !== null ) {
519 $this->schema
= $schema;
525 public function getLBInfo( $name = null ) {
526 if ( is_null( $name ) ) {
527 return $this->lbInfo
;
529 if ( array_key_exists( $name, $this->lbInfo
) ) {
530 return $this->lbInfo
[$name];
537 public function setLBInfo( $name, $value = null ) {
538 if ( is_null( $value ) ) {
539 $this->lbInfo
= $name;
541 $this->lbInfo
[$name] = $value;
545 public function setLazyMasterHandle( IDatabase
$conn ) {
546 $this->lazyMasterHandle
= $conn;
550 * @return IDatabase|null
551 * @see setLazyMasterHandle()
554 protected function getLazyMasterHandle() {
555 return $this->lazyMasterHandle
;
558 public function implicitGroupby() {
562 public function implicitOrderby() {
566 public function lastQuery() {
567 return $this->lastQuery
;
570 public function doneWrites() {
571 return (bool)$this->lastWriteTime
;
574 public function lastDoneWrites() {
575 return $this->lastWriteTime ?
: false;
578 public function writesPending() {
579 return $this->trxLevel
&& $this->trxDoneWrites
;
582 public function writesOrCallbacksPending() {
583 return $this->trxLevel
&& (
584 $this->trxDoneWrites ||
$this->trxIdleCallbacks ||
$this->trxPreCommitCallbacks
588 public function pendingWriteQueryDuration( $type = self
::ESTIMATE_TOTAL
) {
589 if ( !$this->trxLevel
) {
591 } elseif ( !$this->trxDoneWrites
) {
596 case self
::ESTIMATE_DB_APPLY
:
598 $rttAdjTotal = $this->trxWriteAdjQueryCount
* $rtt;
599 $applyTime = max( $this->trxWriteAdjDuration
- $rttAdjTotal, 0 );
600 // For omitted queries, make them count as something at least
601 $omitted = $this->trxWriteQueryCount
- $this->trxWriteAdjQueryCount
;
602 $applyTime +
= self
::TINY_WRITE_SEC
* $omitted;
605 default: // everything
606 return $this->trxWriteDuration
;
610 public function pendingWriteCallers() {
611 return $this->trxLevel ?
$this->trxWriteCallers
: [];
614 public function pendingWriteRowsAffected() {
615 return $this->trxWriteAffectedRows
;
619 * Get the list of method names that have pending write queries or callbacks
620 * for this transaction
624 protected function pendingWriteAndCallbackCallers() {
625 if ( !$this->trxLevel
) {
629 $fnames = $this->trxWriteCallers
;
631 $this->trxIdleCallbacks
,
632 $this->trxPreCommitCallbacks
,
633 $this->trxEndCallbacks
635 foreach ( $callbacks as $callback ) {
636 $fnames[] = $callback[1];
643 public function isOpen() {
644 return $this->opened
;
647 public function setFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
648 if ( ( $flag & self
::DBO_IGNORE
) ) {
649 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
652 if ( $remember === self
::REMEMBER_PRIOR
) {
653 array_push( $this->priorFlags
, $this->flags
);
655 $this->flags |
= $flag;
658 public function clearFlag( $flag, $remember = self
::REMEMBER_NOTHING
) {
659 if ( ( $flag & self
::DBO_IGNORE
) ) {
660 throw new \
UnexpectedValueException( "Modifying DBO_IGNORE is not allowed." );
663 if ( $remember === self
::REMEMBER_PRIOR
) {
664 array_push( $this->priorFlags
, $this->flags
);
666 $this->flags
&= ~
$flag;
669 public function restoreFlags( $state = self
::RESTORE_PRIOR
) {
670 if ( !$this->priorFlags
) {
674 if ( $state === self
::RESTORE_INITIAL
) {
675 $this->flags
= reset( $this->priorFlags
);
676 $this->priorFlags
= [];
678 $this->flags
= array_pop( $this->priorFlags
);
682 public function getFlag( $flag ) {
683 return !!( $this->flags
& $flag );
687 * @param string $name Class field name
689 * @deprecated Since 1.28
691 public function getProperty( $name ) {
695 public function getDomainID() {
696 return $this->currentDomain
->getId();
699 final public function getWikiID() {
700 return $this->getDomainID();
704 * Get information about an index into an object
705 * @param string $table Table name
706 * @param string $index Index name
707 * @param string $fname Calling function name
708 * @return mixed Database-specific index description class or false if the index does not exist
710 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
713 * Wrapper for addslashes()
715 * @param string $s String to be slashed.
716 * @return string Slashed string.
718 abstract function strencode( $s );
721 * Set a custom error handler for logging errors during database connection
723 protected function installErrorHandler() {
724 $this->phpError
= false;
725 $this->htmlErrors
= ini_set( 'html_errors', '0' );
726 set_error_handler( [ $this, 'connectionErrorLogger' ] );
730 * Restore the previous error handler and return the last PHP error for this DB
732 * @return bool|string
734 protected function restoreErrorHandler() {
735 restore_error_handler();
736 if ( $this->htmlErrors
!== false ) {
737 ini_set( 'html_errors', $this->htmlErrors
);
740 return $this->getLastPHPError();
744 * @return string|bool Last PHP error for this DB (typically connection errors)
746 protected function getLastPHPError() {
747 if ( $this->phpError
) {
748 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->phpError
);
749 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
758 * Error handler for logging errors during database connection
759 * This method should not be used outside of Database classes
762 * @param string $errstr
764 public function connectionErrorLogger( $errno, $errstr ) {
765 $this->phpError
= $errstr;
769 * Create a log context to pass to PSR-3 logger functions.
771 * @param array $extras Additional data to add to context
774 protected function getLogContext( array $extras = [] ) {
777 'db_server' => $this->server
,
778 'db_name' => $this->dbName
,
779 'db_user' => $this->user
,
785 public function close() {
787 if ( $this->trxLevel() ) {
788 $this->commit( __METHOD__
, self
::FLUSHING_INTERNAL
);
791 $closed = $this->closeConnection();
794 $this->trxIdleCallbacks ||
795 $this->trxPreCommitCallbacks ||
796 $this->trxEndCallbacks
798 throw new RuntimeException( "Transaction callbacks still pending." );
802 $this->opened
= false;
808 * Make sure isOpen() returns true as a sanity check
810 * @throws DBUnexpectedError
812 protected function assertOpen() {
813 if ( !$this->isOpen() ) {
814 throw new DBUnexpectedError( $this, "DB connection was already closed." );
819 * Closes underlying database connection
821 * @return bool Whether connection was closed successfully
823 abstract protected function closeConnection();
825 public function reportConnectionError( $error = 'Unknown error' ) {
826 $myError = $this->lastError();
832 throw new DBConnectionError( $this, $error );
836 * The DBMS-dependent part of query()
838 * @param string $sql SQL query.
839 * @return ResultWrapper|bool Result object to feed to fetchObject,
840 * fetchRow, ...; or false on failure
842 abstract protected function doQuery( $sql );
845 * Determine whether a query writes to the DB.
846 * Should return true if unsure.
851 protected function isWriteQuery( $sql ) {
853 '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
858 * @return string|null
860 protected function getQueryVerb( $sql ) {
861 return preg_match( '/^\s*([a-z]+)/i', $sql, $m ) ?
strtoupper( $m[1] ) : null;
865 * Determine whether a SQL statement is sensitive to isolation level.
866 * A SQL statement is considered transactable if its result could vary
867 * depending on the transaction isolation level. Operational commands
868 * such as 'SET' and 'SHOW' are not considered to be transactable.
873 protected function isTransactableQuery( $sql ) {
875 $this->getQueryVerb( $sql ),
876 [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET', 'CREATE', 'ALTER' ],
882 * @param string $sql A SQL query
883 * @return bool Whether $sql is SQL for TEMPORARY table operation
885 protected function registerTempTableOperation( $sql ) {
887 '/^CREATE\s+TEMPORARY\s+TABLE\s+(?:IF\s+NOT\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
891 $this->sessionTempTables
[$matches[1]] = 1;
894 } elseif ( preg_match(
895 '/^DROP\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
899 $isTemp = isset( $this->sessionTempTables
[$matches[1]] );
900 unset( $this->sessionTempTables
[$matches[1]] );
903 } elseif ( preg_match(
904 '/^TRUNCATE\s+(?:TEMPORARY\s+)?TABLE\s+(?:IF\s+EXISTS\s+)?[`"\']?(\w+)[`"\']?/i',
908 return isset( $this->sessionTempTables
[$matches[1]] );
909 } elseif ( preg_match(
910 '/^(?:INSERT\s+(?:\w+\s+)?INTO|UPDATE|DELETE\s+FROM)\s+[`"\']?(\w+)[`"\']?/i',
914 return isset( $this->sessionTempTables
[$matches[1]] );
920 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
921 $priorWritesPending = $this->writesOrCallbacksPending();
922 $this->lastQuery
= $sql;
924 $isWrite = $this->isWriteQuery( $sql );
926 $isNonTempWrite = !$this->registerTempTableOperation( $sql );
928 $isNonTempWrite = false;
932 if ( $this->getLBInfo( 'replica' ) === true ) {
935 'Write operations are not allowed on replica database connections.'
938 # In theory, non-persistent writes are allowed in read-only mode, but due to things
939 # like https://bugs.mysql.com/bug.php?id=33669 that might not work anyway...
940 $reason = $this->getReadOnlyReason();
941 if ( $reason !== false ) {
942 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
944 # Set a flag indicating that writes have been done
945 $this->lastWriteTime
= microtime( true );
948 # Add trace comment to the begin of the sql string, right after the operator.
949 # Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (T44598)
950 $commentedSql = preg_replace( '/\s|$/', " /* $fname {$this->agent} */ ", $sql, 1 );
952 # Start implicit transactions that wrap the request if DBO_TRX is enabled
953 if ( !$this->trxLevel
&& $this->getFlag( self
::DBO_TRX
)
954 && $this->isTransactableQuery( $sql )
956 $this->begin( __METHOD__
. " ($fname)", self
::TRANSACTION_INTERNAL
);
957 $this->trxAutomatic
= true;
960 # Keep track of whether the transaction has write queries pending
961 if ( $this->trxLevel
&& !$this->trxDoneWrites
&& $isWrite ) {
962 $this->trxDoneWrites
= true;
963 $this->trxProfiler
->transactionWritingIn(
964 $this->server
, $this->dbName
, $this->trxShortId
);
967 if ( $this->getFlag( self
::DBO_DEBUG
) ) {
968 $this->queryLogger
->debug( "{$this->dbName} {$commentedSql}" );
971 # Avoid fatals if close() was called
974 # Send the query to the server
975 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
977 # Try reconnecting if the connection was lost
978 if ( false === $ret && $this->wasErrorReissuable() ) {
979 $recoverable = $this->canRecoverFromDisconnect( $sql, $priorWritesPending );
980 # Stash the last error values before anything might clear them
981 $lastError = $this->lastError();
982 $lastErrno = $this->lastErrno();
983 # Update state tracking to reflect transaction loss due to disconnection
984 $this->handleSessionLoss();
985 if ( $this->reconnect() ) {
986 $msg = __METHOD__
. ': lost connection to {dbserver}; reconnected';
987 $params = [ 'dbserver' => $this->getServer() ];
988 $this->connLogger
->warning( $msg, $params );
989 $this->queryLogger
->warning( $msg, $params +
990 [ 'trace' => ( new RuntimeException() )->getTraceAsString() ] );
992 if ( !$recoverable ) {
993 # Callers may catch the exception and continue to use the DB
994 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname );
996 # Should be safe to silently retry the query
997 $ret = $this->doProfiledQuery( $sql, $commentedSql, $isNonTempWrite, $fname );
1000 $msg = __METHOD__
. ': lost connection to {dbserver} permanently';
1001 $this->connLogger
->error( $msg, [ 'dbserver' => $this->getServer() ] );
1005 if ( false === $ret ) {
1006 # Deadlocks cause the entire transaction to abort, not just the statement.
1007 # https://dev.mysql.com/doc/refman/5.7/en/innodb-error-handling.html
1008 # https://www.postgresql.org/docs/9.1/static/explicit-locking.html
1009 if ( $this->wasDeadlock() ) {
1010 if ( $this->explicitTrxActive() ||
$priorWritesPending ) {
1011 $tempIgnore = false; // not recoverable
1013 # Update state tracking to reflect transaction loss
1014 $this->handleSessionLoss();
1017 $this->reportQueryError(
1018 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1021 $res = $this->resultObject( $ret );
1027 * Wrapper for query() that also handles profiling, logging, and affected row count updates
1029 * @param string $sql Original SQL query
1030 * @param string $commentedSql SQL query with debugging/trace comment
1031 * @param bool $isWrite Whether the query is a (non-temporary) write operation
1032 * @param string $fname Name of the calling function
1033 * @return bool|ResultWrapper True for a successful write query, ResultWrapper
1034 * object for a successful read query, or false on failure
1036 private function doProfiledQuery( $sql, $commentedSql, $isWrite, $fname ) {
1037 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1038 # generalizeSQL() will probably cut down the query to reasonable
1039 # logging size most of the time. The substr is really just a sanity check.
1041 $queryProf = 'query-m: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1043 $queryProf = 'query: ' . substr( self
::generalizeSQL( $sql ), 0, 255 );
1046 # Include query transaction state
1047 $queryProf .= $this->trxShortId ?
" [TRX#{$this->trxShortId}]" : "";
1049 $startTime = microtime( true );
1050 if ( $this->profiler
) {
1051 call_user_func( [ $this->profiler
, 'profileIn' ], $queryProf );
1053 $this->affectedRowCount
= null;
1054 $ret = $this->doQuery( $commentedSql );
1055 $this->affectedRowCount
= $this->affectedRows();
1056 if ( $this->profiler
) {
1057 call_user_func( [ $this->profiler
, 'profileOut' ], $queryProf );
1059 $queryRuntime = max( microtime( true ) - $startTime, 0.0 );
1061 unset( $queryProfSection ); // profile out (if set)
1063 if ( $ret !== false ) {
1064 $this->lastPing
= $startTime;
1065 if ( $isWrite && $this->trxLevel
) {
1066 $this->updateTrxWriteQueryTime( $sql, $queryRuntime, $this->affectedRows() );
1067 $this->trxWriteCallers
[] = $fname;
1071 if ( $sql === self
::PING_QUERY
) {
1072 $this->rttEstimate
= $queryRuntime;
1075 $this->trxProfiler
->recordQueryCompletion(
1076 $queryProf, $startTime, $isWrite, $this->affectedRows()
1078 $this->queryLogger
->debug( $sql, [
1080 'master' => $isMaster,
1081 'runtime' => $queryRuntime,
1088 * Update the estimated run-time of a query, not counting large row lock times
1090 * LoadBalancer can be set to rollback transactions that will create huge replication
1091 * lag. It bases this estimate off of pendingWriteQueryDuration(). Certain simple
1092 * queries, like inserting a row can take a long time due to row locking. This method
1093 * uses some simple heuristics to discount those cases.
1095 * @param string $sql A SQL write query
1096 * @param float $runtime Total runtime, including RTT
1097 * @param int $affected Affected row count
1099 private function updateTrxWriteQueryTime( $sql, $runtime, $affected ) {
1100 // Whether this is indicative of replica DB runtime (except for RBR or ws_repl)
1101 $indicativeOfReplicaRuntime = true;
1102 if ( $runtime > self
::SLOW_WRITE_SEC
) {
1103 $verb = $this->getQueryVerb( $sql );
1104 // insert(), upsert(), replace() are fast unless bulky in size or blocked on locks
1105 if ( $verb === 'INSERT' ) {
1106 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
;
1107 } elseif ( $verb === 'REPLACE' ) {
1108 $indicativeOfReplicaRuntime = $this->affectedRows() > self
::SMALL_WRITE_ROWS
/ 2;
1112 $this->trxWriteDuration +
= $runtime;
1113 $this->trxWriteQueryCount +
= 1;
1114 $this->trxWriteAffectedRows +
= $affected;
1115 if ( $indicativeOfReplicaRuntime ) {
1116 $this->trxWriteAdjDuration +
= $runtime;
1117 $this->trxWriteAdjQueryCount +
= 1;
1122 * Determine whether or not it is safe to retry queries after a database
1123 * connection is lost
1125 * @param string $sql SQL query
1126 * @param bool $priorWritesPending Whether there is a transaction open with
1127 * possible write queries or transaction pre-commit/idle callbacks
1128 * waiting on it to finish.
1129 * @return bool True if it is safe to retry the query, false otherwise
1131 private function canRecoverFromDisconnect( $sql, $priorWritesPending ) {
1132 # Transaction dropped; this can mean lost writes, or REPEATABLE-READ snapshots.
1133 # Dropped connections also mean that named locks are automatically released.
1134 # Only allow error suppression in autocommit mode or when the lost transaction
1135 # didn't matter anyway (aside from DBO_TRX snapshot loss).
1136 if ( $this->namedLocksHeld
) {
1137 return false; // possible critical section violation
1138 } elseif ( $sql === 'COMMIT' ) {
1139 return !$priorWritesPending; // nothing written anyway? (T127428)
1140 } elseif ( $sql === 'ROLLBACK' ) {
1141 return true; // transaction lost...which is also what was requested :)
1142 } elseif ( $this->explicitTrxActive() ) {
1143 return false; // don't drop atomocity
1144 } elseif ( $priorWritesPending ) {
1145 return false; // prior writes lost from implicit transaction
1152 * Clean things up after transaction loss due to disconnection
1154 * @return null|Exception
1156 private function handleSessionLoss() {
1157 $this->trxLevel
= 0;
1158 $this->trxIdleCallbacks
= []; // T67263
1159 $this->trxPreCommitCallbacks
= []; // T67263
1160 $this->sessionTempTables
= [];
1161 $this->namedLocksHeld
= [];
1163 // Handle callbacks in trxEndCallbacks
1164 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
1165 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
1167 } catch ( Exception
$e ) {
1168 // Already logged; move on...
1174 * Checks whether the cause of the error is detected to be a timeout.
1176 * It returns false by default, and not all engines support detecting this yet.
1177 * If this returns false, it will be treated as a generic query error.
1179 * @param string $error Error text
1180 * @param int $errno Error number
1183 protected function wasQueryTimeout( $error, $errno ) {
1187 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1188 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1189 $this->queryLogger
->debug( "SQL ERROR (ignored): $error\n" );
1191 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1192 $this->queryLogger
->error(
1193 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1194 $this->getLogContext( [
1195 'method' => __METHOD__
,
1198 'sql1line' => $sql1line,
1202 $this->queryLogger
->debug( "SQL ERROR: " . $error . "\n" );
1203 $wasQueryTimeout = $this->wasQueryTimeout( $error, $errno );
1204 if ( $wasQueryTimeout ) {
1205 throw new DBQueryTimeoutError( $this, $error, $errno, $sql, $fname );
1207 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1212 public function freeResult( $res ) {
1215 public function selectField(
1216 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1218 if ( $var === '*' ) { // sanity
1219 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1222 if ( !is_array( $options ) ) {
1223 $options = [ $options ];
1226 $options['LIMIT'] = 1;
1228 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1229 if ( $res === false ||
!$this->numRows( $res ) ) {
1233 $row = $this->fetchRow( $res );
1235 if ( $row !== false ) {
1236 return reset( $row );
1242 public function selectFieldValues(
1243 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1245 if ( $var === '*' ) { // sanity
1246 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1247 } elseif ( !is_string( $var ) ) { // sanity
1248 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1251 if ( !is_array( $options ) ) {
1252 $options = [ $options ];
1255 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1256 if ( $res === false ) {
1261 foreach ( $res as $row ) {
1262 $values[] = $row->$var;
1269 * Returns an optional USE INDEX clause to go after the table, and a
1270 * string to go at the end of the query.
1272 * @param array $options Associative array of options to be turned into
1273 * an SQL query, valid keys are listed in the function.
1275 * @see Database::select()
1277 protected function makeSelectOptions( $options ) {
1278 $preLimitTail = $postLimitTail = '';
1283 foreach ( $options as $key => $option ) {
1284 if ( is_numeric( $key ) ) {
1285 $noKeyOptions[$option] = true;
1289 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1291 $preLimitTail .= $this->makeOrderBy( $options );
1293 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1294 $postLimitTail .= ' FOR UPDATE';
1297 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1298 $postLimitTail .= ' LOCK IN SHARE MODE';
1301 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1302 $startOpts .= 'DISTINCT';
1305 # Various MySQL extensions
1306 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1307 $startOpts .= ' /*! STRAIGHT_JOIN */';
1310 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1311 $startOpts .= ' HIGH_PRIORITY';
1314 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1315 $startOpts .= ' SQL_BIG_RESULT';
1318 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1319 $startOpts .= ' SQL_BUFFER_RESULT';
1322 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1323 $startOpts .= ' SQL_SMALL_RESULT';
1326 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1327 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1330 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1331 $startOpts .= ' SQL_CACHE';
1334 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1335 $startOpts .= ' SQL_NO_CACHE';
1338 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1339 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1343 if ( isset( $options['IGNORE INDEX'] ) && is_string( $options['IGNORE INDEX'] ) ) {
1344 $ignoreIndex = $this->ignoreIndexClause( $options['IGNORE INDEX'] );
1349 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ];
1353 * Returns an optional GROUP BY with an optional HAVING
1355 * @param array $options Associative array of options
1357 * @see Database::select()
1360 protected function makeGroupByWithHaving( $options ) {
1362 if ( isset( $options['GROUP BY'] ) ) {
1363 $gb = is_array( $options['GROUP BY'] )
1364 ?
implode( ',', $options['GROUP BY'] )
1365 : $options['GROUP BY'];
1366 $sql .= ' GROUP BY ' . $gb;
1368 if ( isset( $options['HAVING'] ) ) {
1369 $having = is_array( $options['HAVING'] )
1370 ?
$this->makeList( $options['HAVING'], self
::LIST_AND
)
1371 : $options['HAVING'];
1372 $sql .= ' HAVING ' . $having;
1379 * Returns an optional ORDER BY
1381 * @param array $options Associative array of options
1383 * @see Database::select()
1386 protected function makeOrderBy( $options ) {
1387 if ( isset( $options['ORDER BY'] ) ) {
1388 $ob = is_array( $options['ORDER BY'] )
1389 ?
implode( ',', $options['ORDER BY'] )
1390 : $options['ORDER BY'];
1392 return ' ORDER BY ' . $ob;
1398 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1399 $options = [], $join_conds = [] ) {
1400 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1402 return $this->query( $sql, $fname );
1405 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1406 $options = [], $join_conds = []
1408 if ( is_array( $vars ) ) {
1409 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1412 $options = (array)$options;
1413 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1414 ?
$options['USE INDEX']
1417 isset( $options['IGNORE INDEX'] ) &&
1418 is_array( $options['IGNORE INDEX'] )
1420 ?
$options['IGNORE INDEX']
1423 if ( is_array( $table ) ) {
1425 $this->tableNamesWithIndexClauseOrJOIN(
1426 $table, $useIndexes, $ignoreIndexes, $join_conds );
1427 } elseif ( $table != '' ) {
1429 $this->tableNamesWithIndexClauseOrJOIN(
1430 [ $table ], $useIndexes, $ignoreIndexes, [] );
1435 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail, $ignoreIndex ) =
1436 $this->makeSelectOptions( $options );
1438 if ( is_array( $conds ) ) {
1439 $conds = $this->makeList( $conds, self
::LIST_AND
);
1442 if ( $conds === null ||
$conds === false ) {
1443 $this->queryLogger
->warning(
1447 . ' with incorrect parameters: $conds must be a string or an array'
1452 if ( $conds === '' ) {
1453 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex $preLimitTail";
1454 } elseif ( is_string( $conds ) ) {
1455 $sql = "SELECT $startOpts $vars $from $useIndex $ignoreIndex " .
1456 "WHERE $conds $preLimitTail";
1458 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1461 if ( isset( $options['LIMIT'] ) ) {
1462 $sql = $this->limitResult( $sql, $options['LIMIT'],
1463 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1465 $sql = "$sql $postLimitTail";
1467 if ( isset( $options['EXPLAIN'] ) ) {
1468 $sql = 'EXPLAIN ' . $sql;
1474 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1475 $options = [], $join_conds = []
1477 $options = (array)$options;
1478 $options['LIMIT'] = 1;
1479 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1481 if ( $res === false ) {
1485 if ( !$this->numRows( $res ) ) {
1489 $obj = $this->fetchObject( $res );
1494 public function estimateRowCount(
1495 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1498 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1501 $row = $this->fetchRow( $res );
1502 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1508 public function selectRowCount(
1509 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1512 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1513 // The identifier quotes is primarily for MSSQL.
1514 $rowCountCol = $this->addIdentifierQuotes( "rowcount" );
1515 $tableName = $this->addIdentifierQuotes( "tmp_count" );
1516 $res = $this->query( "SELECT COUNT(*) AS $rowCountCol FROM ($sql) $tableName", $fname );
1519 $row = $this->fetchRow( $res );
1520 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1527 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1528 * It's only slightly flawed. Don't use for anything important.
1530 * @param string $sql A SQL Query
1534 protected static function generalizeSQL( $sql ) {
1535 # This does the same as the regexp below would do, but in such a way
1536 # as to avoid crashing php on some large strings.
1537 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1539 $sql = str_replace( "\\\\", '', $sql );
1540 $sql = str_replace( "\\'", '', $sql );
1541 $sql = str_replace( "\\\"", '', $sql );
1542 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1543 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1545 # All newlines, tabs, etc replaced by single space
1546 $sql = preg_replace( '/\s+/', ' ', $sql );
1549 # except the ones surrounded by characters, e.g. l10n
1550 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1551 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1556 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1557 $info = $this->fieldInfo( $table, $field );
1562 public function indexExists( $table, $index, $fname = __METHOD__
) {
1563 if ( !$this->tableExists( $table ) ) {
1567 $info = $this->indexInfo( $table, $index, $fname );
1568 if ( is_null( $info ) ) {
1571 return $info !== false;
1575 public function tableExists( $table, $fname = __METHOD__
) {
1576 $tableRaw = $this->tableName( $table, 'raw' );
1577 if ( isset( $this->sessionTempTables
[$tableRaw] ) ) {
1578 return true; // already known to exist
1581 $table = $this->tableName( $table );
1582 $ignoreErrors = true;
1583 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname, $ignoreErrors );
1588 public function indexUnique( $table, $index ) {
1589 $indexInfo = $this->indexInfo( $table, $index );
1591 if ( !$indexInfo ) {
1595 return !$indexInfo[0]->Non_unique
;
1599 * Helper for Database::insert().
1601 * @param array $options
1604 protected function makeInsertOptions( $options ) {
1605 return implode( ' ', $options );
1608 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1609 # No rows to insert, easy just return now
1610 if ( !count( $a ) ) {
1614 $table = $this->tableName( $table );
1616 if ( !is_array( $options ) ) {
1617 $options = [ $options ];
1621 if ( isset( $options['fileHandle'] ) ) {
1622 $fh = $options['fileHandle'];
1624 $options = $this->makeInsertOptions( $options );
1626 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1628 $keys = array_keys( $a[0] );
1631 $keys = array_keys( $a );
1634 $sql = 'INSERT ' . $options .
1635 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1639 foreach ( $a as $row ) {
1645 $sql .= '(' . $this->makeList( $row ) . ')';
1648 $sql .= '(' . $this->makeList( $a ) . ')';
1651 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1653 } elseif ( $fh !== null ) {
1657 return (bool)$this->query( $sql, $fname );
1661 * Make UPDATE options array for Database::makeUpdateOptions
1663 * @param array $options
1666 protected function makeUpdateOptionsArray( $options ) {
1667 if ( !is_array( $options ) ) {
1668 $options = [ $options ];
1673 if ( in_array( 'IGNORE', $options ) ) {
1681 * Make UPDATE options for the Database::update function
1683 * @param array $options The options passed to Database::update
1686 protected function makeUpdateOptions( $options ) {
1687 $opts = $this->makeUpdateOptionsArray( $options );
1689 return implode( ' ', $opts );
1692 public function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1693 $table = $this->tableName( $table );
1694 $opts = $this->makeUpdateOptions( $options );
1695 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, self
::LIST_SET
);
1697 if ( $conds !== [] && $conds !== '*' ) {
1698 $sql .= " WHERE " . $this->makeList( $conds, self
::LIST_AND
);
1701 return (bool)$this->query( $sql, $fname );
1704 public function makeList( $a, $mode = self
::LIST_COMMA
) {
1705 if ( !is_array( $a ) ) {
1706 throw new DBUnexpectedError( $this, __METHOD__
. ' called with incorrect parameters' );
1712 foreach ( $a as $field => $value ) {
1714 if ( $mode == self
::LIST_AND
) {
1716 } elseif ( $mode == self
::LIST_OR
) {
1725 if ( ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_numeric( $field ) ) {
1726 $list .= "($value)";
1727 } elseif ( $mode == self
::LIST_SET
&& is_numeric( $field ) ) {
1730 ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) && is_array( $value )
1732 // Remove null from array to be handled separately if found
1733 $includeNull = false;
1734 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1735 $includeNull = true;
1736 unset( $value[$nullKey] );
1738 if ( count( $value ) == 0 && !$includeNull ) {
1739 throw new InvalidArgumentException(
1740 __METHOD__
. ": empty input for field $field" );
1741 } elseif ( count( $value ) == 0 ) {
1742 // only check if $field is null
1743 $list .= "$field IS NULL";
1745 // IN clause contains at least one valid element
1746 if ( $includeNull ) {
1747 // Group subconditions to ensure correct precedence
1750 if ( count( $value ) == 1 ) {
1751 // Special-case single values, as IN isn't terribly efficient
1752 // Don't necessarily assume the single key is 0; we don't
1753 // enforce linear numeric ordering on other arrays here.
1754 $value = array_values( $value )[0];
1755 $list .= $field . " = " . $this->addQuotes( $value );
1757 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1759 // if null present in array, append IS NULL
1760 if ( $includeNull ) {
1761 $list .= " OR $field IS NULL)";
1764 } elseif ( $value === null ) {
1765 if ( $mode == self
::LIST_AND ||
$mode == self
::LIST_OR
) {
1766 $list .= "$field IS ";
1767 } elseif ( $mode == self
::LIST_SET
) {
1768 $list .= "$field = ";
1773 $mode == self
::LIST_AND ||
$mode == self
::LIST_OR ||
$mode == self
::LIST_SET
1775 $list .= "$field = ";
1777 $list .= $mode == self
::LIST_NAMES ?
$value : $this->addQuotes( $value );
1784 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1787 foreach ( $data as $base => $sub ) {
1788 if ( count( $sub ) ) {
1789 $conds[] = $this->makeList(
1790 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1796 return $this->makeList( $conds, self
::LIST_OR
);
1798 // Nothing to search for...
1803 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1807 public function bitNot( $field ) {
1811 public function bitAnd( $fieldLeft, $fieldRight ) {
1812 return "($fieldLeft & $fieldRight)";
1815 public function bitOr( $fieldLeft, $fieldRight ) {
1816 return "($fieldLeft | $fieldRight)";
1819 public function buildConcat( $stringList ) {
1820 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1823 public function buildGroupConcatField(
1824 $delim, $table, $field, $conds = '', $join_conds = []
1826 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1828 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1831 public function buildStringCast( $field ) {
1835 public function databasesAreIndependent() {
1839 public function selectDB( $db ) {
1840 # Stub. Shouldn't cause serious problems if it's not overridden, but
1841 # if your database engine supports a concept similar to MySQL's
1842 # databases you may as well.
1843 $this->dbName
= $db;
1848 public function getDBname() {
1849 return $this->dbName
;
1852 public function getServer() {
1853 return $this->server
;
1856 public function tableName( $name, $format = 'quoted' ) {
1857 # Skip the entire process when we have a string quoted on both ends.
1858 # Note that we check the end so that we will still quote any use of
1859 # use of `database`.table. But won't break things if someone wants
1860 # to query a database table with a dot in the name.
1861 if ( $this->isQuotedIdentifier( $name ) ) {
1865 # Lets test for any bits of text that should never show up in a table
1866 # name. Basically anything like JOIN or ON which are actually part of
1867 # SQL queries, but may end up inside of the table value to combine
1868 # sql. Such as how the API is doing.
1869 # Note that we use a whitespace test rather than a \b test to avoid
1870 # any remote case where a word like on may be inside of a table name
1871 # surrounded by symbols which may be considered word breaks.
1872 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1876 # Split database and table into proper variables.
1877 list( $database, $schema, $prefix, $table ) = $this->qualifiedTableComponents( $name );
1879 # Quote $table and apply the prefix if not quoted.
1880 # $tableName might be empty if this is called from Database::replaceVars()
1881 $tableName = "{$prefix}{$table}";
1882 if ( $format === 'quoted'
1883 && !$this->isQuotedIdentifier( $tableName )
1884 && $tableName !== ''
1886 $tableName = $this->addIdentifierQuotes( $tableName );
1889 # Quote $schema and $database and merge them with the table name if needed
1890 $tableName = $this->prependDatabaseOrSchema( $schema, $tableName, $format );
1891 $tableName = $this->prependDatabaseOrSchema( $database, $tableName, $format );
1897 * Get the table components needed for a query given the currently selected database
1899 * @param string $name Table name in the form of db.schema.table, db.table, or table
1900 * @return array (DB name or "" for default, schema name, table prefix, table name)
1902 protected function qualifiedTableComponents( $name ) {
1903 # We reverse the explode so that database.table and table both output the correct table.
1904 $dbDetails = explode( '.', $name, 3 );
1905 if ( count( $dbDetails ) == 3 ) {
1906 list( $database, $schema, $table ) = $dbDetails;
1907 # We don't want any prefix added in this case
1909 } elseif ( count( $dbDetails ) == 2 ) {
1910 list( $database, $table ) = $dbDetails;
1911 # We don't want any prefix added in this case
1913 # In dbs that support it, $database may actually be the schema
1914 # but that doesn't affect any of the functionality here
1917 list( $table ) = $dbDetails;
1918 if ( isset( $this->tableAliases
[$table] ) ) {
1919 $database = $this->tableAliases
[$table]['dbname'];
1920 $schema = is_string( $this->tableAliases
[$table]['schema'] )
1921 ?
$this->tableAliases
[$table]['schema']
1923 $prefix = is_string( $this->tableAliases
[$table]['prefix'] )
1924 ?
$this->tableAliases
[$table]['prefix']
1925 : $this->tablePrefix
;
1928 $schema = $this->schema
; # Default schema
1929 $prefix = $this->tablePrefix
; # Default prefix
1933 return [ $database, $schema, $prefix, $table ];
1937 * @param string|null $namespace Database or schema
1938 * @param string $relation Name of table, view, sequence, etc...
1939 * @param string $format One of (raw, quoted)
1940 * @return string Relation name with quoted and merged $namespace as needed
1942 private function prependDatabaseOrSchema( $namespace, $relation, $format ) {
1943 if ( strlen( $namespace ) ) {
1944 if ( $format === 'quoted' && !$this->isQuotedIdentifier( $namespace ) ) {
1945 $namespace = $this->addIdentifierQuotes( $namespace );
1947 $relation = $namespace . '.' . $relation;
1953 public function tableNames() {
1954 $inArray = func_get_args();
1957 foreach ( $inArray as $name ) {
1958 $retVal[$name] = $this->tableName( $name );
1964 public function tableNamesN() {
1965 $inArray = func_get_args();
1968 foreach ( $inArray as $name ) {
1969 $retVal[] = $this->tableName( $name );
1976 * Get an aliased table name
1977 * e.g. tableName AS newTableName
1979 * @param string $name Table name, see tableName()
1980 * @param string|bool $alias Alias (optional)
1981 * @return string SQL name for aliased table. Will not alias a table to its own name
1983 protected function tableNameWithAlias( $name, $alias = false ) {
1984 if ( !$alias ||
$alias == $name ) {
1985 return $this->tableName( $name );
1987 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1992 * Gets an array of aliased table names
1994 * @param array $tables [ [alias] => table ]
1995 * @return string[] See tableNameWithAlias()
1997 protected function tableNamesWithAlias( $tables ) {
1999 foreach ( $tables as $alias => $table ) {
2000 if ( is_numeric( $alias ) ) {
2003 $retval[] = $this->tableNameWithAlias( $table, $alias );
2010 * Get an aliased field name
2011 * e.g. fieldName AS newFieldName
2013 * @param string $name Field name
2014 * @param string|bool $alias Alias (optional)
2015 * @return string SQL name for aliased field. Will not alias a field to its own name
2017 protected function fieldNameWithAlias( $name, $alias = false ) {
2018 if ( !$alias ||
(string)$alias === (string)$name ) {
2021 return $name . ' AS ' . $this->addIdentifierQuotes( $alias ); // PostgreSQL needs AS
2026 * Gets an array of aliased field names
2028 * @param array $fields [ [alias] => field ]
2029 * @return string[] See fieldNameWithAlias()
2031 protected function fieldNamesWithAlias( $fields ) {
2033 foreach ( $fields as $alias => $field ) {
2034 if ( is_numeric( $alias ) ) {
2037 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2044 * Get the aliased table name clause for a FROM clause
2045 * which might have a JOIN and/or USE INDEX or IGNORE INDEX clause
2047 * @param array $tables ( [alias] => table )
2048 * @param array $use_index Same as for select()
2049 * @param array $ignore_index Same as for select()
2050 * @param array $join_conds Same as for select()
2053 protected function tableNamesWithIndexClauseOrJOIN(
2054 $tables, $use_index = [], $ignore_index = [], $join_conds = []
2058 $use_index = (array)$use_index;
2059 $ignore_index = (array)$ignore_index;
2060 $join_conds = (array)$join_conds;
2062 foreach ( $tables as $alias => $table ) {
2063 if ( !is_string( $alias ) ) {
2064 // No alias? Set it equal to the table name
2068 if ( is_array( $table ) ) {
2069 // A parenthesized group
2070 if ( count( $table ) > 1 ) {
2072 . $this->tableNamesWithIndexClauseOrJOIN( $table, $use_index, $ignore_index, $join_conds )
2076 $innerTable = reset( $table );
2077 $innerAlias = key( $table );
2078 $joinedTable = $this->tableNameWithAlias(
2080 is_string( $innerAlias ) ?
$innerAlias : $innerTable
2084 $joinedTable = $this->tableNameWithAlias( $table, $alias );
2087 // Is there a JOIN clause for this table?
2088 if ( isset( $join_conds[$alias] ) ) {
2089 list( $joinType, $conds ) = $join_conds[$alias];
2090 $tableClause = $joinType;
2091 $tableClause .= ' ' . $joinedTable;
2092 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2093 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2095 $tableClause .= ' ' . $use;
2098 if ( isset( $ignore_index[$alias] ) ) { // has IGNORE INDEX?
2099 $ignore = $this->ignoreIndexClause(
2100 implode( ',', (array)$ignore_index[$alias] ) );
2101 if ( $ignore != '' ) {
2102 $tableClause .= ' ' . $ignore;
2105 $on = $this->makeList( (array)$conds, self
::LIST_AND
);
2107 $tableClause .= ' ON (' . $on . ')';
2110 $retJOIN[] = $tableClause;
2111 } elseif ( isset( $use_index[$alias] ) ) {
2112 // Is there an INDEX clause for this table?
2113 $tableClause = $joinedTable;
2114 $tableClause .= ' ' . $this->useIndexClause(
2115 implode( ',', (array)$use_index[$alias] )
2118 $ret[] = $tableClause;
2119 } elseif ( isset( $ignore_index[$alias] ) ) {
2120 // Is there an INDEX clause for this table?
2121 $tableClause = $joinedTable;
2122 $tableClause .= ' ' . $this->ignoreIndexClause(
2123 implode( ',', (array)$ignore_index[$alias] )
2126 $ret[] = $tableClause;
2128 $tableClause = $joinedTable;
2130 $ret[] = $tableClause;
2134 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2135 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2136 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2138 // Compile our final table clause
2139 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
2143 * Allows for index remapping in queries where this is not consistent across DBMS
2145 * @param string $index
2148 protected function indexName( $index ) {
2152 public function addQuotes( $s ) {
2153 if ( $s instanceof Blob
) {
2156 if ( $s === null ) {
2158 } elseif ( is_bool( $s ) ) {
2161 # This will also quote numeric values. This should be harmless,
2162 # and protects against weird problems that occur when they really
2163 # _are_ strings such as article titles and string->number->string
2164 # conversion is not 1:1.
2165 return "'" . $this->strencode( $s ) . "'";
2170 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2171 * MySQL uses `backticks` while basically everything else uses double quotes.
2172 * Since MySQL is the odd one out here the double quotes are our generic
2173 * and we implement backticks in DatabaseMysqlBase.
2178 public function addIdentifierQuotes( $s ) {
2179 return '"' . str_replace( '"', '""', $s ) . '"';
2183 * Returns if the given identifier looks quoted or not according to
2184 * the database convention for quoting identifiers .
2186 * @note Do not use this to determine if untrusted input is safe.
2187 * A malicious user can trick this function.
2188 * @param string $name
2191 public function isQuotedIdentifier( $name ) {
2192 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2197 * @param string $escapeChar
2200 protected function escapeLikeInternal( $s, $escapeChar = '`' ) {
2201 return str_replace( [ $escapeChar, '%', '_' ],
2202 [ "{$escapeChar}{$escapeChar}", "{$escapeChar}%", "{$escapeChar}_" ],
2206 public function buildLike() {
2207 $params = func_get_args();
2209 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2210 $params = $params[0];
2215 // We use ` instead of \ as the default LIKE escape character, since addQuotes()
2216 // may escape backslashes, creating problems of double escaping. The `
2217 // character has good cross-DBMS compatibility, avoiding special operators
2218 // in MS SQL like ^ and %
2221 foreach ( $params as $value ) {
2222 if ( $value instanceof LikeMatch
) {
2223 $s .= $value->toString();
2225 $s .= $this->escapeLikeInternal( $value, $escapeChar );
2229 return ' LIKE ' . $this->addQuotes( $s ) . ' ESCAPE ' . $this->addQuotes( $escapeChar ) . ' ';
2232 public function anyChar() {
2233 return new LikeMatch( '_' );
2236 public function anyString() {
2237 return new LikeMatch( '%' );
2240 public function nextSequenceValue( $seqName ) {
2245 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2246 * is only needed because a) MySQL must be as efficient as possible due to
2247 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2248 * which index to pick. Anyway, other databases might have different
2249 * indexes on a given table. So don't bother overriding this unless you're
2251 * @param string $index
2254 public function useIndexClause( $index ) {
2259 * IGNORE INDEX clause. Unlikely to be useful for anything but MySQL. This
2260 * is only needed because a) MySQL must be as efficient as possible due to
2261 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2262 * which index to pick. Anyway, other databases might have different
2263 * indexes on a given table. So don't bother overriding this unless you're
2265 * @param string $index
2268 public function ignoreIndexClause( $index ) {
2272 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2273 if ( count( $rows ) == 0 ) {
2278 if ( !is_array( reset( $rows ) ) ) {
2283 $this->startAtomic( $fname );
2284 $affectedRowCount = 0;
2285 foreach ( $rows as $row ) {
2286 // Delete rows which collide with this one
2287 $indexWhereClauses = [];
2288 foreach ( $uniqueIndexes as $index ) {
2289 $indexColumns = (array)$index;
2290 $indexRowValues = array_intersect_key( $row, array_flip( $indexColumns ) );
2291 if ( count( $indexRowValues ) != count( $indexColumns ) ) {
2292 throw new DBUnexpectedError(
2294 'New record does not provide all values for unique key (' .
2295 implode( ', ', $indexColumns ) . ')'
2297 } elseif ( in_array( null, $indexRowValues, true ) ) {
2298 throw new DBUnexpectedError(
2300 'New record has a null value for unique key (' .
2301 implode( ', ', $indexColumns ) . ')'
2304 $indexWhereClauses[] = $this->makeList( $indexRowValues, LIST_AND
);
2307 if ( $indexWhereClauses ) {
2308 $this->delete( $table, $this->makeList( $indexWhereClauses, LIST_OR
), $fname );
2309 $affectedRowCount +
= $this->affectedRows();
2312 // Now insert the row
2313 $this->insert( $table, $row, $fname );
2314 $affectedRowCount +
= $this->affectedRows();
2316 $this->endAtomic( $fname );
2317 $this->affectedRowCount
= $affectedRowCount;
2318 } catch ( Exception
$e ) {
2319 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2325 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2328 * @param string $table Table name
2329 * @param array|string $rows Row(s) to insert
2330 * @param string $fname Caller function name
2332 * @return ResultWrapper
2334 protected function nativeReplace( $table, $rows, $fname ) {
2335 $table = $this->tableName( $table );
2338 if ( !is_array( reset( $rows ) ) ) {
2342 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2345 foreach ( $rows as $row ) {
2352 $sql .= '(' . $this->makeList( $row ) . ')';
2355 return $this->query( $sql, $fname );
2358 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2361 if ( !count( $rows ) ) {
2362 return true; // nothing to do
2365 if ( !is_array( reset( $rows ) ) ) {
2369 if ( count( $uniqueIndexes ) ) {
2370 $clauses = []; // list WHERE clauses that each identify a single row
2371 foreach ( $rows as $row ) {
2372 foreach ( $uniqueIndexes as $index ) {
2373 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2374 $rowKey = []; // unique key to this row
2375 foreach ( $index as $column ) {
2376 $rowKey[$column] = $row[$column];
2378 $clauses[] = $this->makeList( $rowKey, self
::LIST_AND
);
2381 $where = [ $this->makeList( $clauses, self
::LIST_OR
) ];
2386 $affectedRowCount = 0;
2388 $this->startAtomic( $fname );
2389 # Update any existing conflicting row(s)
2390 if ( $where !== false ) {
2391 $ok = $this->update( $table, $set, $where, $fname );
2392 $affectedRowCount +
= $this->affectedRows();
2396 # Now insert any non-conflicting row(s)
2397 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2398 $affectedRowCount +
= $this->affectedRows();
2399 $this->endAtomic( $fname );
2400 $this->affectedRowCount
= $affectedRowCount;
2401 } catch ( Exception
$e ) {
2402 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2409 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2413 throw new DBUnexpectedError( $this, __METHOD__
. ' called with empty $conds' );
2416 $delTable = $this->tableName( $delTable );
2417 $joinTable = $this->tableName( $joinTable );
2418 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2419 if ( $conds != '*' ) {
2420 $sql .= 'WHERE ' . $this->makeList( $conds, self
::LIST_AND
);
2424 $this->query( $sql, $fname );
2427 public function textFieldSize( $table, $field ) {
2428 $table = $this->tableName( $table );
2429 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2430 $res = $this->query( $sql, __METHOD__
);
2431 $row = $this->fetchObject( $res );
2435 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2444 public function delete( $table, $conds, $fname = __METHOD__
) {
2446 throw new DBUnexpectedError( $this, __METHOD__
. ' called with no conditions' );
2449 $table = $this->tableName( $table );
2450 $sql = "DELETE FROM $table";
2452 if ( $conds != '*' ) {
2453 if ( is_array( $conds ) ) {
2454 $conds = $this->makeList( $conds, self
::LIST_AND
);
2456 $sql .= ' WHERE ' . $conds;
2459 return $this->query( $sql, $fname );
2462 final public function insertSelect(
2463 $destTable, $srcTable, $varMap, $conds,
2464 $fname = __METHOD__
, $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2466 static $hints = [ 'NO_AUTO_COLUMNS' ];
2468 $insertOptions = (array)$insertOptions;
2469 $selectOptions = (array)$selectOptions;
2471 if ( $this->cliMode
&& $this->isInsertSelectSafe( $insertOptions, $selectOptions ) ) {
2472 // For massive migrations with downtime, we don't want to select everything
2473 // into memory and OOM, so do all this native on the server side if possible.
2474 return $this->nativeInsertSelect(
2480 array_diff( $insertOptions, $hints ),
2486 return $this->nonNativeInsertSelect(
2492 array_diff( $insertOptions, $hints ),
2499 * @param array $insertOptions INSERT options
2500 * @param array $selectOptions SELECT options
2501 * @return bool Whether an INSERT SELECT with these options will be replication safe
2504 protected function isInsertSelectSafe( array $insertOptions, array $selectOptions ) {
2509 * Implementation of insertSelect() based on select() and insert()
2511 * @see IDatabase::insertSelect()
2513 * @param string $destTable
2514 * @param string|array $srcTable
2515 * @param array $varMap
2516 * @param array $conds
2517 * @param string $fname
2518 * @param array $insertOptions
2519 * @param array $selectOptions
2520 * @param array $selectJoinConds
2523 protected function nonNativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2524 $fname = __METHOD__
,
2525 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2527 // For web requests, do a locking SELECT and then INSERT. This puts the SELECT burden
2528 // on only the master (without needing row-based-replication). It also makes it easy to
2529 // know how big the INSERT is going to be.
2531 foreach ( $varMap as $dstColumn => $sourceColumnOrSql ) {
2532 $fields[] = $this->fieldNameWithAlias( $sourceColumnOrSql, $dstColumn );
2534 $selectOptions[] = 'FOR UPDATE';
2535 $res = $this->select(
2536 $srcTable, implode( ',', $fields ), $conds, $fname, $selectOptions, $selectJoinConds
2543 $affectedRowCount = 0;
2544 $this->startAtomic( $fname );
2547 foreach ( $res as $row ) {
2548 $rows[] = (array)$row;
2550 // Avoid inserts that are too huge
2551 if ( count( $rows ) >= $this->nonNativeInsertSelectBatchSize
) {
2552 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2556 $affectedRowCount +
= $this->affectedRows();
2560 if ( $rows && $ok ) {
2561 $ok = $this->insert( $destTable, $rows, $fname, $insertOptions );
2563 $affectedRowCount +
= $this->affectedRows();
2567 $this->endAtomic( $fname );
2568 $this->affectedRowCount
= $affectedRowCount;
2570 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2573 } catch ( Exception
$e ) {
2574 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
2580 * Native server-side implementation of insertSelect() for situations where
2581 * we don't want to select everything into memory
2583 * @see IDatabase::insertSelect()
2584 * @param string $destTable
2585 * @param string|array $srcTable
2586 * @param array $varMap
2587 * @param array $conds
2588 * @param string $fname
2589 * @param array $insertOptions
2590 * @param array $selectOptions
2591 * @param array $selectJoinConds
2594 protected function nativeInsertSelect( $destTable, $srcTable, $varMap, $conds,
2595 $fname = __METHOD__
,
2596 $insertOptions = [], $selectOptions = [], $selectJoinConds = []
2598 $destTable = $this->tableName( $destTable );
2600 if ( !is_array( $insertOptions ) ) {
2601 $insertOptions = [ $insertOptions ];
2604 $insertOptions = $this->makeInsertOptions( $insertOptions );
2606 $selectSql = $this->selectSQLText(
2608 array_values( $varMap ),
2615 $sql = "INSERT $insertOptions" .
2616 " INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ') ' .
2619 return $this->query( $sql, $fname );
2623 * Construct a LIMIT query with optional offset. This is used for query
2624 * pages. The SQL should be adjusted so that only the first $limit rows
2625 * are returned. If $offset is provided as well, then the first $offset
2626 * rows should be discarded, and the next $limit rows should be returned.
2627 * If the result of the query is not ordered, then the rows to be returned
2628 * are theoretically arbitrary.
2630 * $sql is expected to be a SELECT, if that makes a difference.
2632 * The version provided by default works in MySQL and SQLite. It will very
2633 * likely need to be overridden for most other DBMSes.
2635 * @param string $sql SQL query we will append the limit too
2636 * @param int $limit The SQL limit
2637 * @param int|bool $offset The SQL offset (default false)
2638 * @throws DBUnexpectedError
2641 public function limitResult( $sql, $limit, $offset = false ) {
2642 if ( !is_numeric( $limit ) ) {
2643 throw new DBUnexpectedError( $this,
2644 "Invalid non-numeric limit passed to limitResult()\n" );
2647 return "$sql LIMIT "
2648 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2652 public function unionSupportsOrderAndLimit() {
2653 return true; // True for almost every DB supported
2656 public function unionQueries( $sqls, $all ) {
2657 $glue = $all ?
') UNION ALL (' : ') UNION (';
2659 return '(' . implode( $glue, $sqls ) . ')';
2662 public function unionConditionPermutations(
2663 $table, $vars, array $permute_conds, $extra_conds = '', $fname = __METHOD__
,
2664 $options = [], $join_conds = []
2666 // First, build the Cartesian product of $permute_conds
2668 foreach ( $permute_conds as $field => $values ) {
2670 // Skip empty $values
2673 $values = array_unique( $values ); // For sanity
2675 foreach ( $conds as $cond ) {
2676 foreach ( $values as $value ) {
2677 $cond[$field] = $value;
2678 $newConds[] = $cond; // Arrays are by-value, not by-reference, so this works
2684 $extra_conds = $extra_conds === '' ?
[] : (array)$extra_conds;
2686 // If there's just one condition and no subordering, hand off to
2687 // selectSQLText directly.
2688 if ( count( $conds ) === 1 &&
2689 ( !isset( $options['INNER ORDER BY'] ) ||
!$this->unionSupportsOrderAndLimit() )
2691 return $this->selectSQLText(
2692 $table, $vars, $conds[0] +
$extra_conds, $fname, $options, $join_conds
2696 // Otherwise, we need to pull out the order and limit to apply after
2697 // the union. Then build the SQL queries for each set of conditions in
2698 // $conds. Then union them together (using UNION ALL, because the
2699 // product *should* already be distinct).
2700 $orderBy = $this->makeOrderBy( $options );
2701 $limit = isset( $options['LIMIT'] ) ?
$options['LIMIT'] : null;
2702 $offset = isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false;
2703 $all = empty( $options['NOTALL'] ) && !in_array( 'NOTALL', $options );
2704 if ( !$this->unionSupportsOrderAndLimit() ) {
2705 unset( $options['ORDER BY'], $options['LIMIT'], $options['OFFSET'] );
2707 if ( array_key_exists( 'INNER ORDER BY', $options ) ) {
2708 $options['ORDER BY'] = $options['INNER ORDER BY'];
2710 if ( $limit !== null && is_numeric( $offset ) && $offset != 0 ) {
2711 // We need to increase the limit by the offset rather than
2712 // using the offset directly, otherwise it'll skip incorrectly
2713 // in the subqueries.
2714 $options['LIMIT'] = $limit +
$offset;
2715 unset( $options['OFFSET'] );
2720 foreach ( $conds as $cond ) {
2721 $sqls[] = $this->selectSQLText(
2722 $table, $vars, $cond +
$extra_conds, $fname, $options, $join_conds
2725 $sql = $this->unionQueries( $sqls, $all ) . $orderBy;
2726 if ( $limit !== null ) {
2727 $sql = $this->limitResult( $sql, $limit, $offset );
2733 public function conditional( $cond, $trueVal, $falseVal ) {
2734 if ( is_array( $cond ) ) {
2735 $cond = $this->makeList( $cond, self
::LIST_AND
);
2738 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2741 public function strreplace( $orig, $old, $new ) {
2742 return "REPLACE({$orig}, {$old}, {$new})";
2745 public function getServerUptime() {
2749 public function wasDeadlock() {
2753 public function wasLockTimeout() {
2757 public function wasErrorReissuable() {
2761 public function wasReadOnlyError() {
2766 * Do not use this method outside of Database/DBError classes
2768 * @param int|string $errno
2769 * @return bool Whether the given query error was a connection drop
2771 public function wasConnectionError( $errno ) {
2775 public function deadlockLoop() {
2776 $args = func_get_args();
2777 $function = array_shift( $args );
2778 $tries = self
::DEADLOCK_TRIES
;
2780 $this->begin( __METHOD__
);
2783 /** @var Exception $e */
2787 $retVal = call_user_func_array( $function, $args );
2789 } catch ( DBQueryError
$e ) {
2790 if ( $this->wasDeadlock() ) {
2791 // Retry after a randomized delay
2792 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2794 // Throw the error back up
2798 } while ( --$tries > 0 );
2800 if ( $tries <= 0 ) {
2801 // Too many deadlocks; give up
2802 $this->rollback( __METHOD__
);
2805 $this->commit( __METHOD__
);
2811 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2812 # Real waits are implemented in the subclass.
2816 public function getReplicaPos() {
2821 public function getMasterPos() {
2826 public function serverIsReadOnly() {
2830 final public function onTransactionResolution( callable
$callback, $fname = __METHOD__
) {
2831 if ( !$this->trxLevel
) {
2832 throw new DBUnexpectedError( $this, "No transaction is active." );
2834 $this->trxEndCallbacks
[] = [ $callback, $fname ];
2837 final public function onTransactionIdle( callable
$callback, $fname = __METHOD__
) {
2838 $this->trxIdleCallbacks
[] = [ $callback, $fname ];
2839 if ( !$this->trxLevel
) {
2840 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_IDLE
);
2844 final public function onTransactionPreCommitOrIdle( callable
$callback, $fname = __METHOD__
) {
2845 if ( $this->trxLevel ||
$this->getFlag( self
::DBO_TRX
) ) {
2846 // As long as DBO_TRX is set, writes will accumulate until the load balancer issues
2847 // an implicit commit of all peer databases. This is true even if a transaction has
2848 // not yet been triggered by writes; make sure $callback runs *after* any such writes.
2849 $this->trxPreCommitCallbacks
[] = [ $callback, $fname ];
2851 // No transaction is active nor will start implicitly, so make one for this callback
2852 $this->startAtomic( __METHOD__
);
2854 call_user_func( $callback );
2855 $this->endAtomic( __METHOD__
);
2856 } catch ( Exception
$e ) {
2857 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2863 final public function setTransactionListener( $name, callable
$callback = null ) {
2865 $this->trxRecurringCallbacks
[$name] = $callback;
2867 unset( $this->trxRecurringCallbacks
[$name] );
2872 * Whether to disable running of post-COMMIT/ROLLBACK callbacks
2874 * This method should not be used outside of Database/LoadBalancer
2876 * @param bool $suppress
2879 final public function setTrxEndCallbackSuppression( $suppress ) {
2880 $this->trxEndCallbacksSuppressed
= $suppress;
2884 * Actually run and consume any "on transaction idle/resolution" callbacks.
2886 * This method should not be used outside of Database/LoadBalancer
2888 * @param int $trigger IDatabase::TRIGGER_* constant
2892 public function runOnTransactionIdleCallbacks( $trigger ) {
2893 if ( $this->trxEndCallbacksSuppressed
) {
2897 $autoTrx = $this->getFlag( self
::DBO_TRX
); // automatic begin() enabled?
2898 /** @var Exception $e */
2899 $e = null; // first exception
2900 do { // callbacks may add callbacks :)
2901 $callbacks = array_merge(
2902 $this->trxIdleCallbacks
,
2903 $this->trxEndCallbacks
// include "transaction resolution" callbacks
2905 $this->trxIdleCallbacks
= []; // consumed (and recursion guard)
2906 $this->trxEndCallbacks
= []; // consumed (recursion guard)
2907 foreach ( $callbacks as $callback ) {
2909 list( $phpCallback ) = $callback;
2910 $this->clearFlag( self
::DBO_TRX
); // make each query its own transaction
2911 call_user_func_array( $phpCallback, [ $trigger ] );
2913 $this->setFlag( self
::DBO_TRX
); // restore automatic begin()
2915 $this->clearFlag( self
::DBO_TRX
); // restore auto-commit
2917 } catch ( Exception
$ex ) {
2918 call_user_func( $this->errorLogger
, $ex );
2920 // Some callbacks may use startAtomic/endAtomic, so make sure
2921 // their transactions are ended so other callbacks don't fail
2922 if ( $this->trxLevel() ) {
2923 $this->rollback( __METHOD__
, self
::FLUSHING_INTERNAL
);
2927 } while ( count( $this->trxIdleCallbacks
) );
2929 if ( $e instanceof Exception
) {
2930 throw $e; // re-throw any first exception
2935 * Actually run and consume any "on transaction pre-commit" callbacks.
2937 * This method should not be used outside of Database/LoadBalancer
2942 public function runOnTransactionPreCommitCallbacks() {
2943 $e = null; // first exception
2944 do { // callbacks may add callbacks :)
2945 $callbacks = $this->trxPreCommitCallbacks
;
2946 $this->trxPreCommitCallbacks
= []; // consumed (and recursion guard)
2947 foreach ( $callbacks as $callback ) {
2949 list( $phpCallback ) = $callback;
2950 call_user_func( $phpCallback );
2951 } catch ( Exception
$ex ) {
2952 call_user_func( $this->errorLogger
, $ex );
2956 } while ( count( $this->trxPreCommitCallbacks
) );
2958 if ( $e instanceof Exception
) {
2959 throw $e; // re-throw any first exception
2964 * Actually run any "transaction listener" callbacks.
2966 * This method should not be used outside of Database/LoadBalancer
2968 * @param int $trigger IDatabase::TRIGGER_* constant
2972 public function runTransactionListenerCallbacks( $trigger ) {
2973 if ( $this->trxEndCallbacksSuppressed
) {
2977 /** @var Exception $e */
2978 $e = null; // first exception
2980 foreach ( $this->trxRecurringCallbacks
as $phpCallback ) {
2982 $phpCallback( $trigger, $this );
2983 } catch ( Exception
$ex ) {
2984 call_user_func( $this->errorLogger
, $ex );
2989 if ( $e instanceof Exception
) {
2990 throw $e; // re-throw any first exception
2994 final public function startAtomic( $fname = __METHOD__
) {
2995 if ( !$this->trxLevel
) {
2996 $this->begin( $fname, self
::TRANSACTION_INTERNAL
);
2997 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2998 // in all changes being in one transaction to keep requests transactional.
2999 if ( !$this->getFlag( self
::DBO_TRX
) ) {
3000 $this->trxAutomaticAtomic
= true;
3004 $this->trxAtomicLevels
[] = $fname;
3007 final public function endAtomic( $fname = __METHOD__
) {
3008 if ( !$this->trxLevel
) {
3009 throw new DBUnexpectedError( $this, "No atomic transaction is open (got $fname)." );
3011 if ( !$this->trxAtomicLevels ||
3012 array_pop( $this->trxAtomicLevels
) !== $fname
3014 throw new DBUnexpectedError( $this, "Invalid atomic section ended (got $fname)." );
3017 if ( !$this->trxAtomicLevels
&& $this->trxAutomaticAtomic
) {
3018 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3022 final public function doAtomicSection( $fname, callable
$callback ) {
3023 $this->startAtomic( $fname );
3025 $res = call_user_func_array( $callback, [ $this, $fname ] );
3026 } catch ( Exception
$e ) {
3027 $this->rollback( $fname, self
::FLUSHING_INTERNAL
);
3030 $this->endAtomic( $fname );
3035 final public function begin( $fname = __METHOD__
, $mode = self
::TRANSACTION_EXPLICIT
) {
3036 // Protect against mismatched atomic section, transaction nesting, and snapshot loss
3037 if ( $this->trxLevel
) {
3038 if ( $this->trxAtomicLevels
) {
3039 $levels = implode( ', ', $this->trxAtomicLevels
);
3040 $msg = "$fname: Got explicit BEGIN while atomic section(s) $levels are open.";
3041 throw new DBUnexpectedError( $this, $msg );
3042 } elseif ( !$this->trxAutomatic
) {
3043 $msg = "$fname: Explicit transaction already active (from {$this->trxFname}).";
3044 throw new DBUnexpectedError( $this, $msg );
3046 // @TODO: make this an exception at some point
3047 $msg = "$fname: Implicit transaction already active (from {$this->trxFname}).";
3048 $this->queryLogger
->error( $msg );
3049 return; // join the main transaction set
3051 } elseif ( $this->getFlag( self
::DBO_TRX
) && $mode !== self
::TRANSACTION_INTERNAL
) {
3052 // @TODO: make this an exception at some point
3053 $msg = "$fname: Implicit transaction expected (DBO_TRX set).";
3054 $this->queryLogger
->error( $msg );
3055 return; // let any writes be in the main transaction
3058 // Avoid fatals if close() was called
3059 $this->assertOpen();
3061 $this->doBegin( $fname );
3062 $this->trxTimestamp
= microtime( true );
3063 $this->trxFname
= $fname;
3064 $this->trxDoneWrites
= false;
3065 $this->trxAutomaticAtomic
= false;
3066 $this->trxAtomicLevels
= [];
3067 $this->trxShortId
= sprintf( '%06x', mt_rand( 0, 0xffffff ) );
3068 $this->trxWriteDuration
= 0.0;
3069 $this->trxWriteQueryCount
= 0;
3070 $this->trxWriteAffectedRows
= 0;
3071 $this->trxWriteAdjDuration
= 0.0;
3072 $this->trxWriteAdjQueryCount
= 0;
3073 $this->trxWriteCallers
= [];
3074 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3075 // Get an estimate of the replica DB lag before then, treating estimate staleness
3076 // as lag itself just to be safe
3077 $status = $this->getApproximateLagStatus();
3078 $this->trxReplicaLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3079 // T147697: make explicitTrxActive() return true until begin() finishes. This way, no
3080 // caller will think its OK to muck around with the transaction just because startAtomic()
3081 // has not yet completed (e.g. setting trxAtomicLevels).
3082 $this->trxAutomatic
= ( $mode === self
::TRANSACTION_INTERNAL
);
3086 * Issues the BEGIN command to the database server.
3088 * @see Database::begin()
3089 * @param string $fname
3091 protected function doBegin( $fname ) {
3092 $this->query( 'BEGIN', $fname );
3093 $this->trxLevel
= 1;
3096 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3097 if ( $this->trxLevel
&& $this->trxAtomicLevels
) {
3098 // There are still atomic sections open. This cannot be ignored
3099 $levels = implode( ', ', $this->trxAtomicLevels
);
3100 throw new DBUnexpectedError(
3102 "$fname: Got COMMIT while atomic sections $levels are still open."
3106 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3107 if ( !$this->trxLevel
) {
3108 return; // nothing to do
3109 } elseif ( !$this->trxAutomatic
) {
3110 throw new DBUnexpectedError(
3112 "$fname: Flushing an explicit transaction, getting out of sync."
3116 if ( !$this->trxLevel
) {
3117 $this->queryLogger
->error(
3118 "$fname: No transaction to commit, something got out of sync." );
3119 return; // nothing to do
3120 } elseif ( $this->trxAutomatic
) {
3121 // @TODO: make this an exception at some point
3122 $msg = "$fname: Explicit commit of implicit transaction.";
3123 $this->queryLogger
->error( $msg );
3124 return; // wait for the main transaction set commit round
3128 // Avoid fatals if close() was called
3129 $this->assertOpen();
3131 $this->runOnTransactionPreCommitCallbacks();
3132 $writeTime = $this->pendingWriteQueryDuration( self
::ESTIMATE_DB_APPLY
);
3133 $this->doCommit( $fname );
3134 if ( $this->trxDoneWrites
) {
3135 $this->lastWriteTime
= microtime( true );
3136 $this->trxProfiler
->transactionWritingOut(
3141 $this->trxWriteAffectedRows
3145 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_COMMIT
);
3146 $this->runTransactionListenerCallbacks( self
::TRIGGER_COMMIT
);
3150 * Issues the COMMIT command to the database server.
3152 * @see Database::commit()
3153 * @param string $fname
3155 protected function doCommit( $fname ) {
3156 if ( $this->trxLevel
) {
3157 $this->query( 'COMMIT', $fname );
3158 $this->trxLevel
= 0;
3162 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3163 if ( $flush === self
::FLUSHING_INTERNAL ||
$flush === self
::FLUSHING_ALL_PEERS
) {
3164 if ( !$this->trxLevel
) {
3165 return; // nothing to do
3168 if ( !$this->trxLevel
) {
3169 $this->queryLogger
->error(
3170 "$fname: No transaction to rollback, something got out of sync." );
3171 return; // nothing to do
3172 } elseif ( $this->getFlag( self
::DBO_TRX
) ) {
3173 throw new DBUnexpectedError(
3175 "$fname: Expected mass rollback of all peer databases (DBO_TRX set)."
3180 // Avoid fatals if close() was called
3181 $this->assertOpen();
3183 $this->doRollback( $fname );
3184 $this->trxAtomicLevels
= [];
3185 if ( $this->trxDoneWrites
) {
3186 $this->trxProfiler
->transactionWritingOut(
3193 $this->trxIdleCallbacks
= []; // clear
3194 $this->trxPreCommitCallbacks
= []; // clear
3196 $this->runOnTransactionIdleCallbacks( self
::TRIGGER_ROLLBACK
);
3197 } catch ( Exception
$e ) {
3198 // already logged; finish and let LoadBalancer move on during mass-rollback
3201 $this->runTransactionListenerCallbacks( self
::TRIGGER_ROLLBACK
);
3202 } catch ( Exception
$e ) {
3203 // already logged; let LoadBalancer move on during mass-rollback
3206 $this->affectedRowCount
= 0; // for the sake of consistency
3210 * Issues the ROLLBACK command to the database server.
3212 * @see Database::rollback()
3213 * @param string $fname
3215 protected function doRollback( $fname ) {
3216 if ( $this->trxLevel
) {
3217 # Disconnects cause rollback anyway, so ignore those errors
3218 $ignoreErrors = true;
3219 $this->query( 'ROLLBACK', $fname, $ignoreErrors );
3220 $this->trxLevel
= 0;
3224 public function flushSnapshot( $fname = __METHOD__
) {
3225 if ( $this->writesOrCallbacksPending() ||
$this->explicitTrxActive() ) {
3226 // This only flushes transactions to clear snapshots, not to write data
3227 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3228 throw new DBUnexpectedError(
3230 "$fname: Cannot flush snapshot because writes are pending ($fnames)."
3234 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3237 public function explicitTrxActive() {
3238 return $this->trxLevel
&& ( $this->trxAtomicLevels ||
!$this->trxAutomatic
);
3241 public function duplicateTableStructure(
3242 $oldName, $newName, $temporary = false, $fname = __METHOD__
3244 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3247 public function listTables( $prefix = null, $fname = __METHOD__
) {
3248 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3251 public function listViews( $prefix = null, $fname = __METHOD__
) {
3252 throw new RuntimeException( __METHOD__
. ' is not implemented in descendant class' );
3255 public function timestamp( $ts = 0 ) {
3256 $t = new ConvertibleTimestamp( $ts );
3257 // Let errors bubble up to avoid putting garbage in the DB
3258 return $t->getTimestamp( TS_MW
);
3261 public function timestampOrNull( $ts = null ) {
3262 if ( is_null( $ts ) ) {
3265 return $this->timestamp( $ts );
3269 public function affectedRows() {
3270 return ( $this->affectedRowCount
=== null )
3271 ?
$this->fetchAffectedRowCount() // default to driver value
3272 : $this->affectedRowCount
;
3276 * @return int Number of retrieved rows according to the driver
3278 abstract protected function fetchAffectedRowCount();
3281 * Take the result from a query, and wrap it in a ResultWrapper if
3282 * necessary. Boolean values are passed through as is, to indicate success
3283 * of write queries or failure.
3285 * Once upon a time, Database::query() returned a bare MySQL result
3286 * resource, and it was necessary to call this function to convert it to
3287 * a wrapper. Nowadays, raw database objects are never exposed to external
3288 * callers, so this is unnecessary in external code.
3290 * @param bool|ResultWrapper|resource|object $result
3291 * @return bool|ResultWrapper
3293 protected function resultObject( $result ) {
3296 } elseif ( $result instanceof ResultWrapper
) {
3298 } elseif ( $result === true ) {
3299 // Successful write query
3302 return new ResultWrapper( $this, $result );
3306 public function ping( &$rtt = null ) {
3307 // Avoid hitting the server if it was hit recently
3308 if ( $this->isOpen() && ( microtime( true ) - $this->lastPing
) < self
::PING_TTL
) {
3309 if ( !func_num_args() ||
$this->rttEstimate
> 0 ) {
3310 $rtt = $this->rttEstimate
;
3311 return true; // don't care about $rtt
3315 // This will reconnect if possible or return false if not
3316 $this->clearFlag( self
::DBO_TRX
, self
::REMEMBER_PRIOR
);
3317 $ok = ( $this->query( self
::PING_QUERY
, __METHOD__
, true ) !== false );
3318 $this->restoreFlags( self
::RESTORE_PRIOR
);
3321 $rtt = $this->rttEstimate
;
3328 * Close existing database connection and open a new connection
3330 * @return bool True if new connection is opened successfully, false if error
3332 protected function reconnect() {
3333 $this->closeConnection();
3334 $this->opened
= false;
3335 $this->conn
= false;
3337 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3338 $this->lastPing
= microtime( true );
3340 } catch ( DBConnectionError
$e ) {
3347 public function getSessionLagStatus() {
3348 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3352 * Get the replica DB lag when the current transaction started
3354 * This is useful when transactions might use snapshot isolation
3355 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3356 * is this lag plus transaction duration. If they don't, it is still
3357 * safe to be pessimistic. This returns null if there is no transaction.
3359 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3362 protected function getTransactionLagStatus() {
3363 return $this->trxLevel
3364 ?
[ 'lag' => $this->trxReplicaLag
, 'since' => $this->trxTimestamp() ]
3369 * Get a replica DB lag estimate for this server
3371 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3374 protected function getApproximateLagStatus() {
3376 'lag' => $this->getLBInfo( 'replica' ) ?
$this->getLag() : 0,
3377 'since' => microtime( true )
3382 * Merge the result of getSessionLagStatus() for several DBs
3383 * using the most pessimistic values to estimate the lag of
3384 * any data derived from them in combination
3386 * This is information is useful for caching modules
3388 * @see WANObjectCache::set()
3389 * @see WANObjectCache::getWithSetCallback()
3391 * @param IDatabase $db1
3392 * @param IDatabase $db2 [optional]
3393 * @return array Map of values:
3394 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3395 * - since: oldest UNIX timestamp of any of the DB lag estimates
3396 * - pending: whether any of the DBs have uncommitted changes
3400 public static function getCacheSetOptions( IDatabase
$db1, IDatabase
$db2 = null ) {
3401 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
3402 foreach ( func_get_args() as $db ) {
3403 /** @var IDatabase $db */
3404 $status = $db->getSessionLagStatus();
3405 if ( $status['lag'] === false ) {
3406 $res['lag'] = false;
3407 } elseif ( $res['lag'] !== false ) {
3408 $res['lag'] = max( $res['lag'], $status['lag'] );
3410 $res['since'] = min( $res['since'], $status['since'] );
3411 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3417 public function getLag() {
3421 public function maxListLen() {
3425 public function encodeBlob( $b ) {
3429 public function decodeBlob( $b ) {
3430 if ( $b instanceof Blob
) {
3436 public function setSessionOptions( array $options ) {
3439 public function sourceFile(
3441 callable
$lineCallback = null,
3442 callable
$resultCallback = null,
3444 callable
$inputCallback = null
3446 Wikimedia\
suppressWarnings();
3447 $fp = fopen( $filename, 'r' );
3448 Wikimedia\restoreWarnings
();
3450 if ( false === $fp ) {
3451 throw new RuntimeException( "Could not open \"{$filename}\".\n" );
3455 $fname = __METHOD__
. "( $filename )";
3459 $error = $this->sourceStream(
3460 $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3461 } catch ( Exception
$e ) {
3471 public function setSchemaVars( $vars ) {
3472 $this->schemaVars
= $vars;
3475 public function sourceStream(
3477 callable
$lineCallback = null,
3478 callable
$resultCallback = null,
3479 $fname = __METHOD__
,
3480 callable
$inputCallback = null
3482 $delimiterReset = new ScopedCallback(
3483 function ( $delimiter ) {
3484 $this->delimiter
= $delimiter;
3486 [ $this->delimiter
]
3490 while ( !feof( $fp ) ) {
3491 if ( $lineCallback ) {
3492 call_user_func( $lineCallback );
3495 $line = trim( fgets( $fp ) );
3497 if ( $line == '' ) {
3501 if ( '-' == $line[0] && '-' == $line[1] ) {
3509 $done = $this->streamStatementEnd( $cmd, $line );
3513 if ( $done ||
feof( $fp ) ) {
3514 $cmd = $this->replaceVars( $cmd );
3516 if ( $inputCallback ) {
3517 $callbackResult = call_user_func( $inputCallback, $cmd );
3519 if ( is_string( $callbackResult ) ||
!$callbackResult ) {
3520 $cmd = $callbackResult;
3525 $res = $this->query( $cmd, $fname );
3527 if ( $resultCallback ) {
3528 call_user_func( $resultCallback, $res, $this );
3531 if ( false === $res ) {
3532 $err = $this->lastError();
3534 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3541 ScopedCallback
::consume( $delimiterReset );
3546 * Called by sourceStream() to check if we've reached a statement end
3548 * @param string &$sql SQL assembled so far
3549 * @param string &$newLine New line about to be added to $sql
3550 * @return bool Whether $newLine contains end of the statement
3552 public function streamStatementEnd( &$sql, &$newLine ) {
3553 if ( $this->delimiter
) {
3555 $newLine = preg_replace(
3556 '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3557 if ( $newLine != $prev ) {
3566 * Database independent variable replacement. Replaces a set of variables
3567 * in an SQL statement with their contents as given by $this->getSchemaVars().
3569 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3571 * - '{$var}' should be used for text and is passed through the database's
3573 * - `{$var}` should be used for identifiers (e.g. table and database names).
3574 * It is passed through the database's addIdentifierQuotes method which
3575 * can be overridden if the database uses something other than backticks.
3576 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3577 * database's tableName method.
3578 * - / *i* / passes the name that follows through the database's indexName method.
3579 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3580 * its use should be avoided. In 1.24 and older, string encoding was applied.
3582 * @param string $ins SQL statement to replace variables in
3583 * @return string The new SQL statement with variables replaced
3585 protected function replaceVars( $ins ) {
3586 $vars = $this->getSchemaVars();
3587 return preg_replace_callback(
3589 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3590 \'\{\$ (\w+) }\' | # 3. addQuotes
3591 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3592 /\*\$ (\w+) \*/ # 5. leave unencoded
3594 function ( $m ) use ( $vars ) {
3595 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3596 // check for both nonexistent keys *and* the empty string.
3597 if ( isset( $m[1] ) && $m[1] !== '' ) {
3598 if ( $m[1] === 'i' ) {
3599 return $this->indexName( $m[2] );
3601 return $this->tableName( $m[2] );
3603 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3604 return $this->addQuotes( $vars[$m[3]] );
3605 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3606 return $this->addIdentifierQuotes( $vars[$m[4]] );
3607 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3608 return $vars[$m[5]];
3618 * Get schema variables. If none have been set via setSchemaVars(), then
3619 * use some defaults from the current object.
3623 protected function getSchemaVars() {
3624 if ( $this->schemaVars
) {
3625 return $this->schemaVars
;
3627 return $this->getDefaultSchemaVars();
3632 * Get schema variables to use if none have been set via setSchemaVars().
3634 * Override this in derived classes to provide variables for tables.sql
3635 * and SQL patch files.
3639 protected function getDefaultSchemaVars() {
3643 public function lockIsFree( $lockName, $method ) {
3644 // RDBMs methods for checking named locks may or may not count this thread itself.
3645 // In MySQL, IS_FREE_LOCK() returns 0 if the thread already has the lock. This is
3646 // the behavior choosen by the interface for this method.
3647 return !isset( $this->namedLocksHeld
[$lockName] );
3650 public function lock( $lockName, $method, $timeout = 5 ) {
3651 $this->namedLocksHeld
[$lockName] = 1;
3656 public function unlock( $lockName, $method ) {
3657 unset( $this->namedLocksHeld
[$lockName] );
3662 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3663 if ( $this->writesOrCallbacksPending() ) {
3664 // This only flushes transactions to clear snapshots, not to write data
3665 $fnames = implode( ', ', $this->pendingWriteAndCallbackCallers() );
3666 throw new DBUnexpectedError(
3668 "$fname: Cannot flush pre-lock snapshot because writes are pending ($fnames)."
3672 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3676 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3677 if ( $this->trxLevel() ) {
3678 // There is a good chance an exception was thrown, causing any early return
3679 // from the caller. Let any error handler get a chance to issue rollback().
3680 // If there isn't one, let the error bubble up and trigger server-side rollback.
3681 $this->onTransactionResolution(
3682 function () use ( $lockKey, $fname ) {
3683 $this->unlock( $lockKey, $fname );
3688 $this->unlock( $lockKey, $fname );
3692 $this->commit( $fname, self
::FLUSHING_INTERNAL
);
3697 public function namedLocksEnqueue() {
3701 public function tableLocksHaveTransactionScope() {
3705 final public function lockTables( array $read, array $write, $method ) {
3706 if ( $this->writesOrCallbacksPending() ) {
3707 throw new DBUnexpectedError( $this, "Transaction writes or callbacks still pending." );
3710 if ( $this->tableLocksHaveTransactionScope() ) {
3711 $this->startAtomic( $method );
3714 return $this->doLockTables( $read, $write, $method );
3718 * Helper function for lockTables() that handles the actual table locking
3720 * @param array $read Array of tables to lock for read access
3721 * @param array $write Array of tables to lock for write access
3722 * @param string $method Name of caller
3725 protected function doLockTables( array $read, array $write, $method ) {
3729 final public function unlockTables( $method ) {
3730 if ( $this->tableLocksHaveTransactionScope() ) {
3731 $this->endAtomic( $method );
3733 return true; // locks released on COMMIT/ROLLBACK
3736 return $this->doUnlockTables( $method );
3740 * Helper function for unlockTables() that handles the actual table unlocking
3742 * @param string $method Name of caller
3745 protected function doUnlockTables( $method ) {
3751 * @param string $tableName
3752 * @param string $fName
3753 * @return bool|ResultWrapper
3756 public function dropTable( $tableName, $fName = __METHOD__
) {
3757 if ( !$this->tableExists( $tableName, $fName ) ) {
3760 $sql = "DROP TABLE " . $this->tableName( $tableName ) . " CASCADE";
3762 return $this->query( $sql, $fName );
3765 public function getInfinity() {
3769 public function encodeExpiry( $expiry ) {
3770 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3771 ?
$this->getInfinity()
3772 : $this->timestamp( $expiry );
3775 public function decodeExpiry( $expiry, $format = TS_MW
) {
3776 if ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() ) {
3780 return ConvertibleTimestamp
::convert( $format, $expiry );
3783 public function setBigSelects( $value = true ) {
3787 public function isReadOnly() {
3788 return ( $this->getReadOnlyReason() !== false );
3792 * @return string|bool Reason this DB is read-only or false if it is not
3794 protected function getReadOnlyReason() {
3795 $reason = $this->getLBInfo( 'readOnlyReason' );
3797 return is_string( $reason ) ?
$reason : false;
3800 public function setTableAliases( array $aliases ) {
3801 $this->tableAliases
= $aliases;
3805 * @return bool Whether a DB user is required to access the DB
3808 protected function requiresDatabaseUser() {
3813 * Get the underlying binding connection handle
3815 * Makes sure the connection resource is set (disconnects and ping() failure can unset it).
3816 * This catches broken callers than catch and ignore disconnection exceptions.
3817 * Unlike checking isOpen(), this is safe to call inside of open().
3819 * @return resource|object
3820 * @throws DBUnexpectedError
3823 protected function getBindingHandle() {
3824 if ( !$this->conn
) {
3825 throw new DBUnexpectedError(
3827 'DB connection was already closed or the connection dropped.'
3838 public function __toString() {
3839 return (string)$this->conn
;
3843 * Make sure that copies do not share the same client binding handle
3844 * @throws DBConnectionError
3846 public function __clone() {
3847 $this->connLogger
->warning(
3848 "Cloning " . static::class . " is not recomended; forking connection:\n" .
3849 ( new RuntimeException() )->getTraceAsString()
3852 if ( $this->isOpen() ) {
3853 // Open a new connection resource without messing with the old one
3854 $this->opened
= false;
3855 $this->conn
= false;
3856 $this->trxEndCallbacks
= []; // don't copy
3857 $this->handleSessionLoss(); // no trx or locks anymore
3858 $this->open( $this->server
, $this->user
, $this->password
, $this->dbName
);
3859 $this->lastPing
= microtime( true );
3864 * Called by serialize. Throw an exception when DB connection is serialized.
3865 * This causes problems on some database engines because the connection is
3866 * not restored on unserialize.
3868 public function __sleep() {
3869 throw new RuntimeException( 'Database serialization may cause problems, since ' .
3870 'the connection is not restored on wakeup.' );
3874 * Run a few simple sanity checks and close dangling connections
3876 public function __destruct() {
3877 if ( $this->trxLevel
&& $this->trxDoneWrites
) {
3878 trigger_error( "Uncommitted DB writes (transaction from {$this->trxFname})." );
3881 $danglingWriters = $this->pendingWriteAndCallbackCallers();
3882 if ( $danglingWriters ) {
3883 $fnames = implode( ', ', $danglingWriters );
3884 trigger_error( "DB transaction writes or callbacks still pending ($fnames)." );
3887 if ( $this->conn
) {
3888 // Avoid connection leaks for sanity. Normally, resources close at script completion.
3889 // The connection might already be closed in zend/hhvm by now, so suppress warnings.
3890 Wikimedia\
suppressWarnings();
3891 $this->closeConnection();
3892 Wikimedia\restoreWarnings
();
3893 $this->conn
= false;
3894 $this->opened
= false;
3899 class_alias( Database
::class, 'DatabaseBase' ); // b/c for old name
3900 class_alias( Database
::class, 'Database' ); // b/c global alias