4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX
= 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var BagOStuff APC cache */
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = [];
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = [];
60 protected $mTablePrefix;
64 protected $mLBInfo = [];
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
68 protected $mSessionVars = [];
70 protected $preparedArgs;
72 protected $htmlErrors;
74 protected $delimiter = ';';
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
82 protected $mTrxLevel = 0;
85 * Either a short hexidecimal string if a transaction is active or ""
88 * @see DatabaseBase::mTrxLevel
90 protected $mTrxShortId = '';
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
98 * @see DatabaseBase::mTrxLevel
100 private $mTrxTimestamp = null;
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
135 private $mTrxAtomicLevels = [];
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
145 * Track the write query callers of the current transaction
149 private $mTrxWriteCallers = [];
152 * Track the seconds spent in write queries for the current transaction
156 private $mTrxWriteDuration = 0.0;
158 /** @var array Map of (name => 1) for locks obtained via lock() */
159 private $mNamedLocksHeld = [];
161 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
162 private $lazyMasterHandle;
166 * @var resource File handle for upgrade
168 protected $fileHandle = null;
172 * @var string[] Process cache of VIEWs names in the database
174 protected $allViews = null;
176 /** @var TransactionProfiler */
177 protected $trxProfiler;
179 public function getServerInfo() {
180 return $this->getServerVersion();
184 * @return string Command delimiter used by this database engine
186 public function getDelimiter() {
187 return $this->delimiter
;
191 * Boolean, controls output of large amounts of debug information.
192 * @param bool|null $debug
193 * - true to enable debugging
194 * - false to disable debugging
195 * - omitted or null to do nothing
197 * @return bool|null Previous value of the flag
199 public function debug( $debug = null ) {
200 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
203 public function bufferResults( $buffer = null ) {
204 if ( is_null( $buffer ) ) {
205 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
207 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
212 * Turns on (false) or off (true) the automatic generation and sending
213 * of a "we're sorry, but there has been a database error" page on
214 * database errors. Default is on (false). When turned off, the
215 * code should use lastErrno() and lastError() to handle the
216 * situation as appropriate.
218 * Do not use this function outside of the Database classes.
220 * @param null|bool $ignoreErrors
221 * @return bool The previous value of the flag.
223 protected function ignoreErrors( $ignoreErrors = null ) {
224 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
227 public function trxLevel() {
228 return $this->mTrxLevel
;
231 public function trxTimestamp() {
232 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
235 public function tablePrefix( $prefix = null ) {
236 return wfSetVar( $this->mTablePrefix
, $prefix );
239 public function dbSchema( $schema = null ) {
240 return wfSetVar( $this->mSchema
, $schema );
244 * Set the filehandle to copy write statements to.
246 * @param resource $fh File handle
248 public function setFileHandle( $fh ) {
249 $this->fileHandle
= $fh;
252 public function getLBInfo( $name = null ) {
253 if ( is_null( $name ) ) {
254 return $this->mLBInfo
;
256 if ( array_key_exists( $name, $this->mLBInfo
) ) {
257 return $this->mLBInfo
[$name];
264 public function setLBInfo( $name, $value = null ) {
265 if ( is_null( $value ) ) {
266 $this->mLBInfo
= $name;
268 $this->mLBInfo
[$name] = $value;
273 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
275 * @param IDatabase $conn
278 public function setLazyMasterHandle( IDatabase
$conn ) {
279 $this->lazyMasterHandle
= $conn;
283 * @return IDatabase|null
284 * @see setLazyMasterHandle()
287 public function getLazyMasterHandle() {
288 return $this->lazyMasterHandle
;
292 * @return TransactionProfiler
294 protected function getTransactionProfiler() {
295 if ( !$this->trxProfiler
) {
296 $this->trxProfiler
= new TransactionProfiler();
299 return $this->trxProfiler
;
303 * @param TransactionProfiler $profiler
306 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
307 $this->trxProfiler
= $profiler;
311 * Returns true if this database supports (and uses) cascading deletes
315 public function cascadingDeletes() {
320 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
324 public function cleanupTriggers() {
329 * Returns true if this database is strict about what can be put into an IP field.
330 * Specifically, it uses a NULL value instead of an empty string.
334 public function strictIPs() {
339 * Returns true if this database uses timestamps rather than integers
343 public function realTimestamps() {
347 public function implicitGroupby() {
351 public function implicitOrderby() {
356 * Returns true if this database can do a native search on IP columns
357 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
361 public function searchableIPs() {
366 * Returns true if this database can use functional indexes
370 public function functionalIndexes() {
374 public function lastQuery() {
375 return $this->mLastQuery
;
378 public function doneWrites() {
379 return (bool)$this->mDoneWrites
;
382 public function lastDoneWrites() {
383 return $this->mDoneWrites ?
: false;
386 public function writesPending() {
387 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
390 public function writesOrCallbacksPending() {
391 return $this->mTrxLevel
&& (
392 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
396 public function pendingWriteQueryDuration() {
397 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
400 public function pendingWriteCallers() {
401 return $this->mTrxLevel ?
$this->mTrxWriteCallers
: [];
404 public function isOpen() {
405 return $this->mOpened
;
408 public function setFlag( $flag ) {
409 $this->mFlags |
= $flag;
412 public function clearFlag( $flag ) {
413 $this->mFlags
&= ~
$flag;
416 public function getFlag( $flag ) {
417 return !!( $this->mFlags
& $flag );
420 public function getProperty( $name ) {
424 public function getWikiID() {
425 if ( $this->mTablePrefix
) {
426 return "{$this->mDBname}-{$this->mTablePrefix}";
428 return $this->mDBname
;
433 * Return a path to the DBMS-specific SQL file if it exists,
434 * otherwise default SQL file
436 * @param string $filename
439 private function getSqlFilePath( $filename ) {
441 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
442 if ( file_exists( $dbmsSpecificFilePath ) ) {
443 return $dbmsSpecificFilePath;
445 return "$IP/maintenance/$filename";
450 * Return a path to the DBMS-specific schema file,
451 * otherwise default to tables.sql
455 public function getSchemaPath() {
456 return $this->getSqlFilePath( 'tables.sql' );
460 * Return a path to the DBMS-specific update key file,
461 * otherwise default to update-keys.sql
465 public function getUpdateKeysPath() {
466 return $this->getSqlFilePath( 'update-keys.sql' );
470 * Get information about an index into an object
471 * @param string $table Table name
472 * @param string $index Index name
473 * @param string $fname Calling function name
474 * @return mixed Database-specific index description class or false if the index does not exist
476 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
479 * Wrapper for addslashes()
481 * @param string $s String to be slashed.
482 * @return string Slashed string.
484 abstract function strencode( $s );
489 * FIXME: It is possible to construct a Database object with no associated
490 * connection object, by specifying no parameters to __construct(). This
491 * feature is deprecated and should be removed.
493 * DatabaseBase subclasses should not be constructed directly in external
494 * code. DatabaseBase::factory() should be used instead.
496 * @param array $params Parameters passed from DatabaseBase::factory()
498 function __construct( array $params ) {
499 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
501 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
503 $server = $params['host'];
504 $user = $params['user'];
505 $password = $params['password'];
506 $dbName = $params['dbname'];
507 $flags = $params['flags'];
508 $tablePrefix = $params['tablePrefix'];
509 $schema = $params['schema'];
510 $foreign = $params['foreign'];
512 $this->mFlags
= $flags;
513 if ( $this->mFlags
& DBO_DEFAULT
) {
514 if ( $wgCommandLineMode ) {
515 $this->mFlags
&= ~DBO_TRX
;
517 $this->mFlags |
= DBO_TRX
;
521 $this->mSessionVars
= $params['variables'];
523 /** Get the default table prefix*/
524 if ( $tablePrefix === 'get from global' ) {
525 $this->mTablePrefix
= $wgDBprefix;
527 $this->mTablePrefix
= $tablePrefix;
530 /** Get the database schema*/
531 if ( $schema === 'get from global' ) {
532 $this->mSchema
= $wgDBmwschema;
534 $this->mSchema
= $schema;
537 $this->mForeign
= $foreign;
539 if ( isset( $params['trxProfiler'] ) ) {
540 $this->trxProfiler
= $params['trxProfiler']; // override
544 $this->open( $server, $user, $password, $dbName );
549 * Called by serialize. Throw an exception when DB connection is serialized.
550 * This causes problems on some database engines because the connection is
551 * not restored on unserialize.
553 public function __sleep() {
554 throw new MWException( 'Database serialization may cause problems, since ' .
555 'the connection is not restored on wakeup.' );
559 * Given a DB type, construct the name of the appropriate child class of
560 * DatabaseBase. This is designed to replace all of the manual stuff like:
561 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
562 * as well as validate against the canonical list of DB types we have
564 * This factory function is mostly useful for when you need to connect to a
565 * database other than the MediaWiki default (such as for external auth,
566 * an extension, et cetera). Do not use this to connect to the MediaWiki
567 * database. Example uses in core:
568 * @see LoadBalancer::reallyOpenConnection()
569 * @see ForeignDBRepo::getMasterDB()
570 * @see WebInstallerDBConnect::execute()
574 * @param string $dbType A possible DB type
575 * @param array $p An array of options to pass to the constructor.
576 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
577 * @throws MWException If the database driver or extension cannot be found
578 * @return DatabaseBase|null DatabaseBase subclass or null
580 final public static function factory( $dbType, $p = [] ) {
581 $canonicalDBTypes = [
582 'mysql' => [ 'mysqli', 'mysql' ],
590 $dbType = strtolower( $dbType );
591 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
592 $possibleDrivers = $canonicalDBTypes[$dbType];
593 if ( !empty( $p['driver'] ) ) {
594 if ( in_array( $p['driver'], $possibleDrivers ) ) {
595 $driver = $p['driver'];
597 throw new MWException( __METHOD__
.
598 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
601 foreach ( $possibleDrivers as $posDriver ) {
602 if ( extension_loaded( $posDriver ) ) {
603 $driver = $posDriver;
611 if ( $driver === false ) {
612 throw new MWException( __METHOD__
.
613 " no viable database extension found for type '$dbType'" );
616 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
617 // and everything else doesn't use a schema (e.g. null)
618 // Although postgres and oracle support schemas, we don't use them (yet)
619 // to maintain backwards compatibility
621 'mssql' => 'get from global',
624 $class = 'Database' . ucfirst( $driver );
625 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
626 // Resolve some defaults for b/c
627 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
628 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
629 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
630 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
631 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
632 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : [];
633 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
634 if ( !isset( $p['schema'] ) ) {
635 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
637 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
639 return new $class( $p );
645 protected function installErrorHandler() {
646 $this->mPHPError
= false;
647 $this->htmlErrors
= ini_set( 'html_errors', '0' );
648 set_error_handler( [ $this, 'connectionErrorHandler' ] );
652 * @return bool|string
654 protected function restoreErrorHandler() {
655 restore_error_handler();
656 if ( $this->htmlErrors
!== false ) {
657 ini_set( 'html_errors', $this->htmlErrors
);
659 if ( $this->mPHPError
) {
660 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
661 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
671 * @param string $errstr
673 public function connectionErrorHandler( $errno, $errstr ) {
674 $this->mPHPError
= $errstr;
678 * Create a log context to pass to wfLogDBError or other logging functions.
680 * @param array $extras Additional data to add to context
683 protected function getLogContext( array $extras = [] ) {
686 'db_server' => $this->mServer
,
687 'db_name' => $this->mDBname
,
688 'db_user' => $this->mUser
,
694 public function close() {
695 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
696 throw new MWException( "Transaction idle callbacks still pending." );
698 if ( $this->mConn
) {
699 if ( $this->trxLevel() ) {
700 if ( !$this->mTrxAutomatic
) {
701 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
702 " performing implicit commit before closing connection!" );
705 $this->commit( __METHOD__
, 'flush' );
708 $closed = $this->closeConnection();
709 $this->mConn
= false;
713 $this->mOpened
= false;
719 * Make sure isOpen() returns true as a sanity check
721 * @throws DBUnexpectedError
723 protected function assertOpen() {
724 if ( !$this->isOpen() ) {
725 throw new DBUnexpectedError( $this, "DB connection was already closed." );
730 * Closes underlying database connection
732 * @return bool Whether connection was closed successfully
734 abstract protected function closeConnection();
736 function reportConnectionError( $error = 'Unknown error' ) {
737 $myError = $this->lastError();
743 throw new DBConnectionError( $this, $error );
747 * The DBMS-dependent part of query()
749 * @param string $sql SQL query.
750 * @return ResultWrapper|bool Result object to feed to fetchObject,
751 * fetchRow, ...; or false on failure
753 abstract protected function doQuery( $sql );
756 * Determine whether a query writes to the DB.
757 * Should return true if unsure.
762 protected function isWriteQuery( $sql ) {
763 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
767 * Determine whether a SQL statement is sensitive to isolation level.
768 * A SQL statement is considered transactable if its result could vary
769 * depending on the transaction isolation level. Operational commands
770 * such as 'SET' and 'SHOW' are not considered to be transactable.
775 protected function isTransactableQuery( $sql ) {
776 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
777 return !in_array( $verb, [ 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ] );
780 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
783 $this->mLastQuery
= $sql;
785 $isWriteQuery = $this->isWriteQuery( $sql );
786 if ( $isWriteQuery ) {
787 $reason = $this->getReadOnlyReason();
788 if ( $reason !== false ) {
789 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
791 # Set a flag indicating that writes have been done
792 $this->mDoneWrites
= microtime( true );
795 # Add a comment for easy SHOW PROCESSLIST interpretation
796 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
797 $userName = $wgUser->getName();
798 if ( mb_strlen( $userName ) > 15 ) {
799 $userName = mb_substr( $userName, 0, 15 ) . '...';
801 $userName = str_replace( '/', '', $userName );
806 // Add trace comment to the begin of the sql string, right after the operator.
807 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
808 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
810 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
811 $this->begin( __METHOD__
. " ($fname)" );
812 $this->mTrxAutomatic
= true;
815 # Keep track of whether the transaction has write queries pending
816 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
817 $this->mTrxDoneWrites
= true;
818 $this->getTransactionProfiler()->transactionWritingIn(
819 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
822 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
823 # generalizeSQL will probably cut down the query to reasonable
824 # logging size most of the time. The substr is really just a sanity check.
826 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
827 $totalProf = 'DatabaseBase::query-master';
829 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
830 $totalProf = 'DatabaseBase::query';
832 # Include query transaction state
833 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
835 $profiler = Profiler
::instance();
836 if ( !$profiler instanceof ProfilerStub
) {
837 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
838 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
841 if ( $this->debug() ) {
842 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
845 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
847 # Avoid fatals if close() was called
850 # Do the query and handle errors
851 $startTime = microtime( true );
852 $ret = $this->doQuery( $commentedSql );
853 $queryRuntime = microtime( true ) - $startTime;
854 # Log the query time and feed it into the DB trx profiler
855 $this->getTransactionProfiler()->recordQueryCompletion(
856 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
858 MWDebug
::queryTime( $queryId );
860 # Try reconnecting if the connection was lost
861 if ( false === $ret && $this->wasErrorReissuable() ) {
862 # Transaction is gone, like it or not
863 $hadTrx = $this->mTrxLevel
; // possible lost transaction
864 $this->mTrxLevel
= 0;
865 $this->mTrxIdleCallbacks
= []; // bug 65263
866 $this->mTrxPreCommitCallbacks
= []; // bug 65263
867 wfDebug( "Connection lost, reconnecting...\n" );
868 # Stash the last error values since ping() might clear them
869 $lastError = $this->lastError();
870 $lastErrno = $this->lastErrno();
871 if ( $this->ping() ) {
872 wfDebug( "Reconnected\n" );
873 $server = $this->getServer();
874 $msg = __METHOD__
. ": lost connection to $server; reconnected";
875 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
877 if ( $hadTrx ||
$this->mNamedLocksHeld
) {
878 # Leave $ret as false and let an error be reported.
879 # Callers may catch the exception and continue to use the DB.
880 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
882 # Should be safe to silently retry (no trx and thus no callbacks)
883 $startTime = microtime( true );
884 $ret = $this->doQuery( $commentedSql );
885 $queryRuntime = microtime( true ) - $startTime;
886 # Log the query time and feed it into the DB trx profiler
887 $this->getTransactionProfiler()->recordQueryCompletion(
888 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
891 wfDebug( "Failed\n" );
895 if ( false === $ret ) {
896 $this->reportQueryError(
897 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
900 $res = $this->resultObject( $ret );
902 // Destroy profile sections in the opposite order to their creation
903 ScopedCallback
::consume( $queryProfSection );
904 ScopedCallback
::consume( $totalProfSection );
906 if ( $isWriteQuery && $this->mTrxLevel
) {
907 $this->mTrxWriteDuration +
= $queryRuntime;
908 $this->mTrxWriteCallers
[] = $fname;
914 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
915 if ( $this->ignoreErrors() ||
$tempIgnore ) {
916 wfDebug( "SQL ERROR (ignored): $error\n" );
918 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
920 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
921 $this->getLogContext( [
922 'method' => __METHOD__
,
925 'sql1line' => $sql1line,
929 wfDebug( "SQL ERROR: " . $error . "\n" );
930 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
935 * Intended to be compatible with the PEAR::DB wrapper functions.
936 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
938 * ? = scalar value, quoted as necessary
939 * ! = raw SQL bit (a function for instance)
940 * & = filename; reads the file and inserts as a blob
941 * (we don't use this though...)
944 * @param string $func
948 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
949 /* MySQL doesn't support prepared statements (yet), so just
950 * pack up the query for reference. We'll manually replace
953 return [ 'query' => $sql, 'func' => $func ];
957 * Free a prepared query, generated by prepare().
958 * @param string $prepared
960 protected function freePrepared( $prepared ) {
961 /* No-op by default */
965 * Execute a prepared query with the various arguments
966 * @param string $prepared The prepared sql
967 * @param mixed $args Either an array here, or put scalars as varargs
969 * @return ResultWrapper
971 public function execute( $prepared, $args = null ) {
972 if ( !is_array( $args ) ) {
974 $args = func_get_args();
975 array_shift( $args );
978 $sql = $this->fillPrepared( $prepared['query'], $args );
980 return $this->query( $sql, $prepared['func'] );
984 * For faking prepared SQL statements on DBs that don't support it directly.
986 * @param string $preparedQuery A 'preparable' SQL statement
987 * @param array $args Array of Arguments to fill it with
988 * @return string Executable SQL
990 public function fillPrepared( $preparedQuery, $args ) {
992 $this->preparedArgs
=& $args;
994 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
995 [ &$this, 'fillPreparedArg' ], $preparedQuery );
999 * preg_callback func for fillPrepared()
1000 * The arguments should be in $this->preparedArgs and must not be touched
1001 * while we're doing this.
1003 * @param array $matches
1004 * @throws DBUnexpectedError
1007 protected function fillPreparedArg( $matches ) {
1008 switch ( $matches[1] ) {
1017 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1019 switch ( $matches[1] ) {
1021 return $this->addQuotes( $arg );
1025 # return $this->addQuotes( file_get_contents( $arg ) );
1026 throw new DBUnexpectedError(
1028 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1031 throw new DBUnexpectedError(
1033 'Received invalid match. This should never happen!'
1038 public function freeResult( $res ) {
1041 public function selectField(
1042 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1044 if ( $var === '*' ) { // sanity
1045 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1048 if ( !is_array( $options ) ) {
1049 $options = [ $options ];
1052 $options['LIMIT'] = 1;
1054 $res = $this->select( $table, $var, $cond, $fname, $options );
1055 if ( $res === false ||
!$this->numRows( $res ) ) {
1059 $row = $this->fetchRow( $res );
1061 if ( $row !== false ) {
1062 return reset( $row );
1068 public function selectFieldValues(
1069 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1071 if ( $var === '*' ) { // sanity
1072 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1075 if ( !is_array( $options ) ) {
1076 $options = [ $options ];
1079 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1080 if ( $res === false ) {
1085 foreach ( $res as $row ) {
1086 $values[] = $row->$var;
1093 * Returns an optional USE INDEX clause to go after the table, and a
1094 * string to go at the end of the query.
1096 * @param array $options Associative array of options to be turned into
1097 * an SQL query, valid keys are listed in the function.
1099 * @see DatabaseBase::select()
1101 public function makeSelectOptions( $options ) {
1102 $preLimitTail = $postLimitTail = '';
1107 foreach ( $options as $key => $option ) {
1108 if ( is_numeric( $key ) ) {
1109 $noKeyOptions[$option] = true;
1113 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1115 $preLimitTail .= $this->makeOrderBy( $options );
1117 // if (isset($options['LIMIT'])) {
1118 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1119 // isset($options['OFFSET']) ? $options['OFFSET']
1123 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1124 $postLimitTail .= ' FOR UPDATE';
1127 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1128 $postLimitTail .= ' LOCK IN SHARE MODE';
1131 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1132 $startOpts .= 'DISTINCT';
1135 # Various MySQL extensions
1136 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1137 $startOpts .= ' /*! STRAIGHT_JOIN */';
1140 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1141 $startOpts .= ' HIGH_PRIORITY';
1144 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1145 $startOpts .= ' SQL_BIG_RESULT';
1148 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1149 $startOpts .= ' SQL_BUFFER_RESULT';
1152 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1153 $startOpts .= ' SQL_SMALL_RESULT';
1156 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1157 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1160 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1161 $startOpts .= ' SQL_CACHE';
1164 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1165 $startOpts .= ' SQL_NO_CACHE';
1168 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1169 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1174 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1178 * Returns an optional GROUP BY with an optional HAVING
1180 * @param array $options Associative array of options
1182 * @see DatabaseBase::select()
1185 public function makeGroupByWithHaving( $options ) {
1187 if ( isset( $options['GROUP BY'] ) ) {
1188 $gb = is_array( $options['GROUP BY'] )
1189 ?
implode( ',', $options['GROUP BY'] )
1190 : $options['GROUP BY'];
1191 $sql .= ' GROUP BY ' . $gb;
1193 if ( isset( $options['HAVING'] ) ) {
1194 $having = is_array( $options['HAVING'] )
1195 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1196 : $options['HAVING'];
1197 $sql .= ' HAVING ' . $having;
1204 * Returns an optional ORDER BY
1206 * @param array $options Associative array of options
1208 * @see DatabaseBase::select()
1211 public function makeOrderBy( $options ) {
1212 if ( isset( $options['ORDER BY'] ) ) {
1213 $ob = is_array( $options['ORDER BY'] )
1214 ?
implode( ',', $options['ORDER BY'] )
1215 : $options['ORDER BY'];
1217 return ' ORDER BY ' . $ob;
1223 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1224 $options = [], $join_conds = [] ) {
1225 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1227 return $this->query( $sql, $fname );
1230 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1231 $options = [], $join_conds = []
1233 if ( is_array( $vars ) ) {
1234 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1237 $options = (array)$options;
1238 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1239 ?
$options['USE INDEX']
1242 if ( is_array( $table ) ) {
1244 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1245 } elseif ( $table != '' ) {
1246 if ( $table[0] == ' ' ) {
1247 $from = ' FROM ' . $table;
1250 $this->tableNamesWithUseIndexOrJOIN( [ $table ], $useIndexes, [] );
1256 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1257 $this->makeSelectOptions( $options );
1259 if ( !empty( $conds ) ) {
1260 if ( is_array( $conds ) ) {
1261 $conds = $this->makeList( $conds, LIST_AND
);
1263 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1265 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1268 if ( isset( $options['LIMIT'] ) ) {
1269 $sql = $this->limitResult( $sql, $options['LIMIT'],
1270 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1272 $sql = "$sql $postLimitTail";
1274 if ( isset( $options['EXPLAIN'] ) ) {
1275 $sql = 'EXPLAIN ' . $sql;
1281 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1282 $options = [], $join_conds = []
1284 $options = (array)$options;
1285 $options['LIMIT'] = 1;
1286 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1288 if ( $res === false ) {
1292 if ( !$this->numRows( $res ) ) {
1296 $obj = $this->fetchObject( $res );
1301 public function estimateRowCount(
1302 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1305 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1308 $row = $this->fetchRow( $res );
1309 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1315 public function selectRowCount(
1316 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1319 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1320 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1323 $row = $this->fetchRow( $res );
1324 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1331 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1332 * It's only slightly flawed. Don't use for anything important.
1334 * @param string $sql A SQL Query
1338 protected static function generalizeSQL( $sql ) {
1339 # This does the same as the regexp below would do, but in such a way
1340 # as to avoid crashing php on some large strings.
1341 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1343 $sql = str_replace( "\\\\", '', $sql );
1344 $sql = str_replace( "\\'", '', $sql );
1345 $sql = str_replace( "\\\"", '', $sql );
1346 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1347 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1349 # All newlines, tabs, etc replaced by single space
1350 $sql = preg_replace( '/\s+/', ' ', $sql );
1353 # except the ones surrounded by characters, e.g. l10n
1354 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1355 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1360 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1361 $info = $this->fieldInfo( $table, $field );
1366 public function indexExists( $table, $index, $fname = __METHOD__
) {
1367 if ( !$this->tableExists( $table ) ) {
1371 $info = $this->indexInfo( $table, $index, $fname );
1372 if ( is_null( $info ) ) {
1375 return $info !== false;
1379 public function tableExists( $table, $fname = __METHOD__
) {
1380 $table = $this->tableName( $table );
1381 $old = $this->ignoreErrors( true );
1382 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1383 $this->ignoreErrors( $old );
1388 public function indexUnique( $table, $index ) {
1389 $indexInfo = $this->indexInfo( $table, $index );
1391 if ( !$indexInfo ) {
1395 return !$indexInfo[0]->Non_unique
;
1399 * Helper for DatabaseBase::insert().
1401 * @param array $options
1404 protected function makeInsertOptions( $options ) {
1405 return implode( ' ', $options );
1408 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1409 # No rows to insert, easy just return now
1410 if ( !count( $a ) ) {
1414 $table = $this->tableName( $table );
1416 if ( !is_array( $options ) ) {
1417 $options = [ $options ];
1421 if ( isset( $options['fileHandle'] ) ) {
1422 $fh = $options['fileHandle'];
1424 $options = $this->makeInsertOptions( $options );
1426 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1428 $keys = array_keys( $a[0] );
1431 $keys = array_keys( $a );
1434 $sql = 'INSERT ' . $options .
1435 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1439 foreach ( $a as $row ) {
1445 $sql .= '(' . $this->makeList( $row ) . ')';
1448 $sql .= '(' . $this->makeList( $a ) . ')';
1451 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1453 } elseif ( $fh !== null ) {
1457 return (bool)$this->query( $sql, $fname );
1461 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1463 * @param array $options
1466 protected function makeUpdateOptionsArray( $options ) {
1467 if ( !is_array( $options ) ) {
1468 $options = [ $options ];
1473 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1474 $opts[] = $this->lowPriorityOption();
1477 if ( in_array( 'IGNORE', $options ) ) {
1485 * Make UPDATE options for the DatabaseBase::update function
1487 * @param array $options The options passed to DatabaseBase::update
1490 protected function makeUpdateOptions( $options ) {
1491 $opts = $this->makeUpdateOptionsArray( $options );
1493 return implode( ' ', $opts );
1496 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1497 $table = $this->tableName( $table );
1498 $opts = $this->makeUpdateOptions( $options );
1499 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1501 if ( $conds !== [] && $conds !== '*' ) {
1502 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1505 return $this->query( $sql, $fname );
1508 public function makeList( $a, $mode = LIST_COMMA
) {
1509 if ( !is_array( $a ) ) {
1510 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1516 foreach ( $a as $field => $value ) {
1518 if ( $mode == LIST_AND
) {
1520 } elseif ( $mode == LIST_OR
) {
1529 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1530 $list .= "($value)";
1531 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1533 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1534 // Remove null from array to be handled separately if found
1535 $includeNull = false;
1536 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1537 $includeNull = true;
1538 unset( $value[$nullKey] );
1540 if ( count( $value ) == 0 && !$includeNull ) {
1541 throw new MWException( __METHOD__
. ": empty input for field $field" );
1542 } elseif ( count( $value ) == 0 ) {
1543 // only check if $field is null
1544 $list .= "$field IS NULL";
1546 // IN clause contains at least one valid element
1547 if ( $includeNull ) {
1548 // Group subconditions to ensure correct precedence
1551 if ( count( $value ) == 1 ) {
1552 // Special-case single values, as IN isn't terribly efficient
1553 // Don't necessarily assume the single key is 0; we don't
1554 // enforce linear numeric ordering on other arrays here.
1555 $value = array_values( $value );
1556 $list .= $field . " = " . $this->addQuotes( $value[0] );
1558 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1560 // if null present in array, append IS NULL
1561 if ( $includeNull ) {
1562 $list .= " OR $field IS NULL)";
1565 } elseif ( $value === null ) {
1566 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1567 $list .= "$field IS ";
1568 } elseif ( $mode == LIST_SET
) {
1569 $list .= "$field = ";
1573 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1574 $list .= "$field = ";
1576 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1583 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1586 foreach ( $data as $base => $sub ) {
1587 if ( count( $sub ) ) {
1588 $conds[] = $this->makeList(
1589 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1595 return $this->makeList( $conds, LIST_OR
);
1597 // Nothing to search for...
1603 * Return aggregated value alias
1605 * @param array $valuedata
1606 * @param string $valuename
1610 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1614 public function bitNot( $field ) {
1618 public function bitAnd( $fieldLeft, $fieldRight ) {
1619 return "($fieldLeft & $fieldRight)";
1622 public function bitOr( $fieldLeft, $fieldRight ) {
1623 return "($fieldLeft | $fieldRight)";
1626 public function buildConcat( $stringList ) {
1627 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1630 public function buildGroupConcatField(
1631 $delim, $table, $field, $conds = '', $join_conds = []
1633 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1635 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1638 public function selectDB( $db ) {
1639 # Stub. Shouldn't cause serious problems if it's not overridden, but
1640 # if your database engine supports a concept similar to MySQL's
1641 # databases you may as well.
1642 $this->mDBname
= $db;
1647 public function getDBname() {
1648 return $this->mDBname
;
1651 public function getServer() {
1652 return $this->mServer
;
1656 * Format a table name ready for use in constructing an SQL query
1658 * This does two important things: it quotes the table names to clean them up,
1659 * and it adds a table prefix if only given a table name with no quotes.
1661 * All functions of this object which require a table name call this function
1662 * themselves. Pass the canonical name to such functions. This is only needed
1663 * when calling query() directly.
1665 * @param string $name Database table name
1666 * @param string $format One of:
1667 * quoted - Automatically pass the table name through addIdentifierQuotes()
1668 * so that it can be used in a query.
1669 * raw - Do not add identifier quotes to the table name
1670 * @return string Full database name
1672 public function tableName( $name, $format = 'quoted' ) {
1673 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1674 # Skip the entire process when we have a string quoted on both ends.
1675 # Note that we check the end so that we will still quote any use of
1676 # use of `database`.table. But won't break things if someone wants
1677 # to query a database table with a dot in the name.
1678 if ( $this->isQuotedIdentifier( $name ) ) {
1682 # Lets test for any bits of text that should never show up in a table
1683 # name. Basically anything like JOIN or ON which are actually part of
1684 # SQL queries, but may end up inside of the table value to combine
1685 # sql. Such as how the API is doing.
1686 # Note that we use a whitespace test rather than a \b test to avoid
1687 # any remote case where a word like on may be inside of a table name
1688 # surrounded by symbols which may be considered word breaks.
1689 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1693 # Split database and table into proper variables.
1694 # We reverse the explode so that database.table and table both output
1695 # the correct table.
1696 $dbDetails = explode( '.', $name, 3 );
1697 if ( count( $dbDetails ) == 3 ) {
1698 list( $database, $schema, $table ) = $dbDetails;
1699 # We don't want any prefix added in this case
1701 } elseif ( count( $dbDetails ) == 2 ) {
1702 list( $database, $table ) = $dbDetails;
1703 # We don't want any prefix added in this case
1704 # In dbs that support it, $database may actually be the schema
1705 # but that doesn't affect any of the functionality here
1709 list( $table ) = $dbDetails;
1710 if ( $wgSharedDB !== null # We have a shared database
1711 && $this->mForeign
== false # We're not working on a foreign database
1712 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1713 && in_array( $table, $wgSharedTables ) # A shared table is selected
1715 $database = $wgSharedDB;
1716 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1717 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1720 $schema = $this->mSchema
; # Default schema
1721 $prefix = $this->mTablePrefix
; # Default prefix
1725 # Quote $table and apply the prefix if not quoted.
1726 # $tableName might be empty if this is called from Database::replaceVars()
1727 $tableName = "{$prefix}{$table}";
1728 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1729 $tableName = $this->addIdentifierQuotes( $tableName );
1732 # Quote $schema and merge it with the table name if needed
1733 if ( strlen( $schema ) ) {
1734 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1735 $schema = $this->addIdentifierQuotes( $schema );
1737 $tableName = $schema . '.' . $tableName;
1740 # Quote $database and merge it with the table name if needed
1741 if ( $database !== null ) {
1742 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1743 $database = $this->addIdentifierQuotes( $database );
1745 $tableName = $database . '.' . $tableName;
1752 * Fetch a number of table names into an array
1753 * This is handy when you need to construct SQL for joins
1756 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1757 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1758 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1762 public function tableNames() {
1763 $inArray = func_get_args();
1766 foreach ( $inArray as $name ) {
1767 $retVal[$name] = $this->tableName( $name );
1774 * Fetch a number of table names into an zero-indexed numerical array
1775 * This is handy when you need to construct SQL for joins
1778 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1779 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1780 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1784 public function tableNamesN() {
1785 $inArray = func_get_args();
1788 foreach ( $inArray as $name ) {
1789 $retVal[] = $this->tableName( $name );
1796 * Get an aliased table name
1797 * e.g. tableName AS newTableName
1799 * @param string $name Table name, see tableName()
1800 * @param string|bool $alias Alias (optional)
1801 * @return string SQL name for aliased table. Will not alias a table to its own name
1803 public function tableNameWithAlias( $name, $alias = false ) {
1804 if ( !$alias ||
$alias == $name ) {
1805 return $this->tableName( $name );
1807 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1812 * Gets an array of aliased table names
1814 * @param array $tables Array( [alias] => table )
1815 * @return string[] See tableNameWithAlias()
1817 public function tableNamesWithAlias( $tables ) {
1819 foreach ( $tables as $alias => $table ) {
1820 if ( is_numeric( $alias ) ) {
1823 $retval[] = $this->tableNameWithAlias( $table, $alias );
1830 * Get an aliased field name
1831 * e.g. fieldName AS newFieldName
1833 * @param string $name Field name
1834 * @param string|bool $alias Alias (optional)
1835 * @return string SQL name for aliased field. Will not alias a field to its own name
1837 public function fieldNameWithAlias( $name, $alias = false ) {
1838 if ( !$alias ||
(string)$alias === (string)$name ) {
1841 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1846 * Gets an array of aliased field names
1848 * @param array $fields Array( [alias] => field )
1849 * @return string[] See fieldNameWithAlias()
1851 public function fieldNamesWithAlias( $fields ) {
1853 foreach ( $fields as $alias => $field ) {
1854 if ( is_numeric( $alias ) ) {
1857 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1864 * Get the aliased table name clause for a FROM clause
1865 * which might have a JOIN and/or USE INDEX clause
1867 * @param array $tables ( [alias] => table )
1868 * @param array $use_index Same as for select()
1869 * @param array $join_conds Same as for select()
1872 protected function tableNamesWithUseIndexOrJOIN(
1873 $tables, $use_index = [], $join_conds = []
1877 $use_index = (array)$use_index;
1878 $join_conds = (array)$join_conds;
1880 foreach ( $tables as $alias => $table ) {
1881 if ( !is_string( $alias ) ) {
1882 // No alias? Set it equal to the table name
1885 // Is there a JOIN clause for this table?
1886 if ( isset( $join_conds[$alias] ) ) {
1887 list( $joinType, $conds ) = $join_conds[$alias];
1888 $tableClause = $joinType;
1889 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1890 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1891 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1893 $tableClause .= ' ' . $use;
1896 $on = $this->makeList( (array)$conds, LIST_AND
);
1898 $tableClause .= ' ON (' . $on . ')';
1901 $retJOIN[] = $tableClause;
1902 } elseif ( isset( $use_index[$alias] ) ) {
1903 // Is there an INDEX clause for this table?
1904 $tableClause = $this->tableNameWithAlias( $table, $alias );
1905 $tableClause .= ' ' . $this->useIndexClause(
1906 implode( ',', (array)$use_index[$alias] )
1909 $ret[] = $tableClause;
1911 $tableClause = $this->tableNameWithAlias( $table, $alias );
1913 $ret[] = $tableClause;
1917 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1918 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1919 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1921 // Compile our final table clause
1922 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1926 * Get the name of an index in a given table.
1928 * @param string $index
1931 protected function indexName( $index ) {
1932 // Backwards-compatibility hack
1934 'ar_usertext_timestamp' => 'usertext_timestamp',
1935 'un_user_id' => 'user_id',
1936 'un_user_ip' => 'user_ip',
1939 if ( isset( $renamed[$index] ) ) {
1940 return $renamed[$index];
1946 public function addQuotes( $s ) {
1947 if ( $s instanceof Blob
) {
1950 if ( $s === null ) {
1953 # This will also quote numeric values. This should be harmless,
1954 # and protects against weird problems that occur when they really
1955 # _are_ strings such as article titles and string->number->string
1956 # conversion is not 1:1.
1957 return "'" . $this->strencode( $s ) . "'";
1962 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1963 * MySQL uses `backticks` while basically everything else uses double quotes.
1964 * Since MySQL is the odd one out here the double quotes are our generic
1965 * and we implement backticks in DatabaseMysql.
1970 public function addIdentifierQuotes( $s ) {
1971 return '"' . str_replace( '"', '""', $s ) . '"';
1975 * Returns if the given identifier looks quoted or not according to
1976 * the database convention for quoting identifiers .
1978 * @param string $name
1981 public function isQuotedIdentifier( $name ) {
1982 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1989 protected function escapeLikeInternal( $s ) {
1990 return addcslashes( $s, '\%_' );
1993 public function buildLike() {
1994 $params = func_get_args();
1996 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1997 $params = $params[0];
2002 foreach ( $params as $value ) {
2003 if ( $value instanceof LikeMatch
) {
2004 $s .= $value->toString();
2006 $s .= $this->escapeLikeInternal( $value );
2010 return " LIKE {$this->addQuotes( $s )} ";
2013 public function anyChar() {
2014 return new LikeMatch( '_' );
2017 public function anyString() {
2018 return new LikeMatch( '%' );
2021 public function nextSequenceValue( $seqName ) {
2026 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2027 * is only needed because a) MySQL must be as efficient as possible due to
2028 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2029 * which index to pick. Anyway, other databases might have different
2030 * indexes on a given table. So don't bother overriding this unless you're
2032 * @param string $index
2035 public function useIndexClause( $index ) {
2039 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2040 $quotedTable = $this->tableName( $table );
2042 if ( count( $rows ) == 0 ) {
2047 if ( !is_array( reset( $rows ) ) ) {
2051 // @FXIME: this is not atomic, but a trx would break affectedRows()
2052 foreach ( $rows as $row ) {
2053 # Delete rows which collide
2054 if ( $uniqueIndexes ) {
2055 $sql = "DELETE FROM $quotedTable WHERE ";
2057 foreach ( $uniqueIndexes as $index ) {
2064 if ( is_array( $index ) ) {
2066 foreach ( $index as $col ) {
2072 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2075 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2079 $this->query( $sql, $fname );
2082 # Now insert the row
2083 $this->insert( $table, $row, $fname );
2088 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2091 * @param string $table Table name
2092 * @param array|string $rows Row(s) to insert
2093 * @param string $fname Caller function name
2095 * @return ResultWrapper
2097 protected function nativeReplace( $table, $rows, $fname ) {
2098 $table = $this->tableName( $table );
2101 if ( !is_array( reset( $rows ) ) ) {
2105 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2108 foreach ( $rows as $row ) {
2115 $sql .= '(' . $this->makeList( $row ) . ')';
2118 return $this->query( $sql, $fname );
2121 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2124 if ( !count( $rows ) ) {
2125 return true; // nothing to do
2128 if ( !is_array( reset( $rows ) ) ) {
2132 if ( count( $uniqueIndexes ) ) {
2133 $clauses = []; // list WHERE clauses that each identify a single row
2134 foreach ( $rows as $row ) {
2135 foreach ( $uniqueIndexes as $index ) {
2136 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2137 $rowKey = []; // unique key to this row
2138 foreach ( $index as $column ) {
2139 $rowKey[$column] = $row[$column];
2141 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2144 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2149 $useTrx = !$this->mTrxLevel
;
2151 $this->begin( $fname );
2154 # Update any existing conflicting row(s)
2155 if ( $where !== false ) {
2156 $ok = $this->update( $table, $set, $where, $fname );
2160 # Now insert any non-conflicting row(s)
2161 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2162 } catch ( Exception
$e ) {
2164 $this->rollback( $fname );
2169 $this->commit( $fname );
2175 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2179 throw new DBUnexpectedError( $this,
2180 'DatabaseBase::deleteJoin() called with empty $conds' );
2183 $delTable = $this->tableName( $delTable );
2184 $joinTable = $this->tableName( $joinTable );
2185 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2186 if ( $conds != '*' ) {
2187 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2191 $this->query( $sql, $fname );
2195 * Returns the size of a text field, or -1 for "unlimited"
2197 * @param string $table
2198 * @param string $field
2201 public function textFieldSize( $table, $field ) {
2202 $table = $this->tableName( $table );
2203 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2204 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2205 $row = $this->fetchObject( $res );
2209 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2219 * A string to insert into queries to show that they're low-priority, like
2220 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2221 * string and nothing bad should happen.
2223 * @return string Returns the text of the low priority option if it is
2224 * supported, or a blank string otherwise
2226 public function lowPriorityOption() {
2230 public function delete( $table, $conds, $fname = __METHOD__
) {
2232 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2235 $table = $this->tableName( $table );
2236 $sql = "DELETE FROM $table";
2238 if ( $conds != '*' ) {
2239 if ( is_array( $conds ) ) {
2240 $conds = $this->makeList( $conds, LIST_AND
);
2242 $sql .= ' WHERE ' . $conds;
2245 return $this->query( $sql, $fname );
2248 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2249 $fname = __METHOD__
,
2250 $insertOptions = [], $selectOptions = []
2252 $destTable = $this->tableName( $destTable );
2254 if ( !is_array( $insertOptions ) ) {
2255 $insertOptions = [ $insertOptions ];
2258 $insertOptions = $this->makeInsertOptions( $insertOptions );
2260 if ( !is_array( $selectOptions ) ) {
2261 $selectOptions = [ $selectOptions ];
2264 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2266 if ( is_array( $srcTable ) ) {
2267 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2269 $srcTable = $this->tableName( $srcTable );
2272 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2273 " SELECT $startOpts " . implode( ',', $varMap ) .
2274 " FROM $srcTable $useIndex ";
2276 if ( $conds != '*' ) {
2277 if ( is_array( $conds ) ) {
2278 $conds = $this->makeList( $conds, LIST_AND
);
2280 $sql .= " WHERE $conds";
2283 $sql .= " $tailOpts";
2285 return $this->query( $sql, $fname );
2289 * Construct a LIMIT query with optional offset. This is used for query
2290 * pages. The SQL should be adjusted so that only the first $limit rows
2291 * are returned. If $offset is provided as well, then the first $offset
2292 * rows should be discarded, and the next $limit rows should be returned.
2293 * If the result of the query is not ordered, then the rows to be returned
2294 * are theoretically arbitrary.
2296 * $sql is expected to be a SELECT, if that makes a difference.
2298 * The version provided by default works in MySQL and SQLite. It will very
2299 * likely need to be overridden for most other DBMSes.
2301 * @param string $sql SQL query we will append the limit too
2302 * @param int $limit The SQL limit
2303 * @param int|bool $offset The SQL offset (default false)
2304 * @throws DBUnexpectedError
2307 public function limitResult( $sql, $limit, $offset = false ) {
2308 if ( !is_numeric( $limit ) ) {
2309 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2312 return "$sql LIMIT "
2313 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2317 public function unionSupportsOrderAndLimit() {
2318 return true; // True for almost every DB supported
2321 public function unionQueries( $sqls, $all ) {
2322 $glue = $all ?
') UNION ALL (' : ') UNION (';
2324 return '(' . implode( $glue, $sqls ) . ')';
2327 public function conditional( $cond, $trueVal, $falseVal ) {
2328 if ( is_array( $cond ) ) {
2329 $cond = $this->makeList( $cond, LIST_AND
);
2332 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2335 public function strreplace( $orig, $old, $new ) {
2336 return "REPLACE({$orig}, {$old}, {$new})";
2339 public function getServerUptime() {
2343 public function wasDeadlock() {
2347 public function wasLockTimeout() {
2351 public function wasErrorReissuable() {
2355 public function wasReadOnlyError() {
2360 * Determines if the given query error was a connection drop
2363 * @param integer|string $errno
2366 public function wasConnectionError( $errno ) {
2371 * Perform a deadlock-prone transaction.
2373 * This function invokes a callback function to perform a set of write
2374 * queries. If a deadlock occurs during the processing, the transaction
2375 * will be rolled back and the callback function will be called again.
2378 * $dbw->deadlockLoop( callback, ... );
2380 * Extra arguments are passed through to the specified callback function.
2382 * Returns whatever the callback function returned on its successful,
2383 * iteration, or false on error, for example if the retry limit was
2386 * @throws DBUnexpectedError
2389 public function deadlockLoop() {
2390 $args = func_get_args();
2391 $function = array_shift( $args );
2392 $tries = self
::DEADLOCK_TRIES
;
2394 $this->begin( __METHOD__
);
2397 /** @var Exception $e */
2401 $retVal = call_user_func_array( $function, $args );
2403 } catch ( DBQueryError
$e ) {
2404 if ( $this->wasDeadlock() ) {
2405 // Retry after a randomized delay
2406 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2408 // Throw the error back up
2412 } while ( --$tries > 0 );
2414 if ( $tries <= 0 ) {
2415 // Too many deadlocks; give up
2416 $this->rollback( __METHOD__
);
2419 $this->commit( __METHOD__
);
2425 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2426 # Real waits are implemented in the subclass.
2430 public function getSlavePos() {
2435 public function getMasterPos() {
2440 final public function onTransactionIdle( $callback ) {
2441 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2442 if ( !$this->mTrxLevel
) {
2443 $this->runOnTransactionIdleCallbacks();
2447 final public function onTransactionPreCommitOrIdle( $callback ) {
2448 if ( $this->mTrxLevel
) {
2449 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2451 $this->onTransactionIdle( $callback ); // this will trigger immediately
2456 * Actually any "on transaction idle" callbacks.
2460 protected function runOnTransactionIdleCallbacks() {
2461 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2463 $e = $ePrior = null; // last exception
2464 do { // callbacks may add callbacks :)
2465 $callbacks = $this->mTrxIdleCallbacks
;
2466 $this->mTrxIdleCallbacks
= []; // recursion guard
2467 foreach ( $callbacks as $callback ) {
2469 list( $phpCallback ) = $callback;
2470 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2471 call_user_func( $phpCallback );
2473 $this->setFlag( DBO_TRX
); // restore automatic begin()
2475 $this->clearFlag( DBO_TRX
); // restore auto-commit
2477 } catch ( Exception
$e ) {
2479 MWExceptionHandler
::logException( $ePrior );
2482 // Some callbacks may use startAtomic/endAtomic, so make sure
2483 // their transactions are ended so other callbacks don't fail
2484 if ( $this->trxLevel() ) {
2485 $this->rollback( __METHOD__
);
2489 } while ( count( $this->mTrxIdleCallbacks
) );
2491 if ( $e instanceof Exception
) {
2492 throw $e; // re-throw any last exception
2497 * Actually any "on transaction pre-commit" callbacks.
2501 protected function runOnTransactionPreCommitCallbacks() {
2502 $e = $ePrior = null; // last exception
2503 do { // callbacks may add callbacks :)
2504 $callbacks = $this->mTrxPreCommitCallbacks
;
2505 $this->mTrxPreCommitCallbacks
= []; // recursion guard
2506 foreach ( $callbacks as $callback ) {
2508 list( $phpCallback ) = $callback;
2509 call_user_func( $phpCallback );
2510 } catch ( Exception
$e ) {
2512 MWExceptionHandler
::logException( $ePrior );
2517 } while ( count( $this->mTrxPreCommitCallbacks
) );
2519 if ( $e instanceof Exception
) {
2520 throw $e; // re-throw any last exception
2524 final public function startAtomic( $fname = __METHOD__
) {
2525 if ( !$this->mTrxLevel
) {
2526 $this->begin( $fname );
2527 $this->mTrxAutomatic
= true;
2528 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2529 // in all changes being in one transaction to keep requests transactional.
2530 if ( !$this->getFlag( DBO_TRX
) ) {
2531 $this->mTrxAutomaticAtomic
= true;
2535 $this->mTrxAtomicLevels
[] = $fname;
2538 final public function endAtomic( $fname = __METHOD__
) {
2539 if ( !$this->mTrxLevel
) {
2540 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2542 if ( !$this->mTrxAtomicLevels ||
2543 array_pop( $this->mTrxAtomicLevels
) !== $fname
2545 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2548 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2549 $this->commit( $fname, 'flush' );
2553 final public function doAtomicSection( $fname, $callback ) {
2554 if ( !is_callable( $callback ) ) {
2555 throw new UnexpectedValueException( "Invalid callback." );
2558 $this->startAtomic( $fname );
2560 call_user_func_array( $callback, [ $this, $fname ] );
2561 } catch ( Exception
$e ) {
2562 $this->rollback( $fname );
2565 $this->endAtomic( $fname );
2568 final public function begin( $fname = __METHOD__
) {
2569 if ( $this->mTrxLevel
) { // implicit commit
2570 if ( $this->mTrxAtomicLevels
) {
2571 // If the current transaction was an automatic atomic one, then we definitely have
2572 // a problem. Same if there is any unclosed atomic level.
2573 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2574 throw new DBUnexpectedError(
2576 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2578 } elseif ( !$this->mTrxAutomatic
) {
2579 // We want to warn about inadvertently nested begin/commit pairs, but not about
2580 // auto-committing implicit transactions that were started by query() via DBO_TRX
2581 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2582 " performing implicit commit!";
2585 $this->getLogContext( [
2586 'method' => __METHOD__
,
2591 // if the transaction was automatic and has done write operations
2592 if ( $this->mTrxDoneWrites
) {
2593 wfDebug( "$fname: Automatic transaction with writes in progress" .
2594 " (from {$this->mTrxFname}), performing implicit commit!\n"
2599 $this->runOnTransactionPreCommitCallbacks();
2600 $writeTime = $this->pendingWriteQueryDuration();
2601 $this->doCommit( $fname );
2602 if ( $this->mTrxDoneWrites
) {
2603 $this->mDoneWrites
= microtime( true );
2604 $this->getTransactionProfiler()->transactionWritingOut(
2605 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2607 $this->runOnTransactionIdleCallbacks();
2610 # Avoid fatals if close() was called
2611 $this->assertOpen();
2613 $this->doBegin( $fname );
2614 $this->mTrxTimestamp
= microtime( true );
2615 $this->mTrxFname
= $fname;
2616 $this->mTrxDoneWrites
= false;
2617 $this->mTrxAutomatic
= false;
2618 $this->mTrxAutomaticAtomic
= false;
2619 $this->mTrxAtomicLevels
= [];
2620 $this->mTrxIdleCallbacks
= [];
2621 $this->mTrxPreCommitCallbacks
= [];
2622 $this->mTrxShortId
= wfRandomString( 12 );
2623 $this->mTrxWriteDuration
= 0.0;
2624 $this->mTrxWriteCallers
= [];
2625 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2626 // Get an estimate of the slave lag before then, treating estimate staleness
2627 // as lag itself just to be safe
2628 $status = $this->getApproximateLagStatus();
2629 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2633 * Issues the BEGIN command to the database server.
2635 * @see DatabaseBase::begin()
2636 * @param string $fname
2638 protected function doBegin( $fname ) {
2639 $this->query( 'BEGIN', $fname );
2640 $this->mTrxLevel
= 1;
2643 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2644 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2645 // There are still atomic sections open. This cannot be ignored
2646 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2647 throw new DBUnexpectedError(
2649 "Got COMMIT while atomic sections $levels are still open"
2653 if ( $flush === 'flush' ) {
2654 if ( !$this->mTrxLevel
) {
2655 return; // nothing to do
2656 } elseif ( !$this->mTrxAutomatic
) {
2657 throw new DBUnexpectedError(
2659 "$fname: Flushing an explicit transaction, getting out of sync!"
2663 if ( !$this->mTrxLevel
) {
2664 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2665 return; // nothing to do
2666 } elseif ( $this->mTrxAutomatic
) {
2667 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2671 # Avoid fatals if close() was called
2672 $this->assertOpen();
2674 $this->runOnTransactionPreCommitCallbacks();
2675 $writeTime = $this->pendingWriteQueryDuration();
2676 $this->doCommit( $fname );
2677 if ( $this->mTrxDoneWrites
) {
2678 $this->mDoneWrites
= microtime( true );
2679 $this->getTransactionProfiler()->transactionWritingOut(
2680 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2682 $this->runOnTransactionIdleCallbacks();
2686 * Issues the COMMIT command to the database server.
2688 * @see DatabaseBase::commit()
2689 * @param string $fname
2691 protected function doCommit( $fname ) {
2692 if ( $this->mTrxLevel
) {
2693 $this->query( 'COMMIT', $fname );
2694 $this->mTrxLevel
= 0;
2698 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2699 if ( $flush !== 'flush' ) {
2700 if ( !$this->mTrxLevel
) {
2701 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2702 return; // nothing to do
2705 if ( !$this->mTrxLevel
) {
2706 return; // nothing to do
2710 # Avoid fatals if close() was called
2711 $this->assertOpen();
2713 $this->doRollback( $fname );
2714 $this->mTrxIdleCallbacks
= []; // cancel
2715 $this->mTrxPreCommitCallbacks
= []; // cancel
2716 $this->mTrxAtomicLevels
= [];
2717 if ( $this->mTrxDoneWrites
) {
2718 $this->getTransactionProfiler()->transactionWritingOut(
2719 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2724 * Issues the ROLLBACK command to the database server.
2726 * @see DatabaseBase::rollback()
2727 * @param string $fname
2729 protected function doRollback( $fname ) {
2730 if ( $this->mTrxLevel
) {
2731 $this->query( 'ROLLBACK', $fname, true );
2732 $this->mTrxLevel
= 0;
2737 * Creates a new table with structure copied from existing table
2738 * Note that unlike most database abstraction functions, this function does not
2739 * automatically append database prefix, because it works at a lower
2740 * abstraction level.
2741 * The table names passed to this function shall not be quoted (this
2742 * function calls addIdentifierQuotes when needed).
2744 * @param string $oldName Name of table whose structure should be copied
2745 * @param string $newName Name of table to be created
2746 * @param bool $temporary Whether the new table should be temporary
2747 * @param string $fname Calling function name
2748 * @throws MWException
2749 * @return bool True if operation was successful
2751 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2754 throw new MWException(
2755 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2758 function listTables( $prefix = null, $fname = __METHOD__
) {
2759 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2763 * Reset the views process cache set by listViews()
2766 final public function clearViewsCache() {
2767 $this->allViews
= null;
2771 * Lists all the VIEWs in the database
2773 * For caching purposes the list of all views should be stored in
2774 * $this->allViews. The process cache can be cleared with clearViewsCache()
2776 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2777 * @param string $fname Name of calling function
2778 * @throws MWException
2782 public function listViews( $prefix = null, $fname = __METHOD__
) {
2783 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2787 * Differentiates between a TABLE and a VIEW
2789 * @param string $name Name of the database-structure to test.
2790 * @throws MWException
2794 public function isView( $name ) {
2795 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2798 public function timestamp( $ts = 0 ) {
2799 return wfTimestamp( TS_MW
, $ts );
2802 public function timestampOrNull( $ts = null ) {
2803 if ( is_null( $ts ) ) {
2806 return $this->timestamp( $ts );
2811 * Take the result from a query, and wrap it in a ResultWrapper if
2812 * necessary. Boolean values are passed through as is, to indicate success
2813 * of write queries or failure.
2815 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2816 * resource, and it was necessary to call this function to convert it to
2817 * a wrapper. Nowadays, raw database objects are never exposed to external
2818 * callers, so this is unnecessary in external code.
2820 * @param bool|ResultWrapper|resource|object $result
2821 * @return bool|ResultWrapper
2823 protected function resultObject( $result ) {
2826 } elseif ( $result instanceof ResultWrapper
) {
2828 } elseif ( $result === true ) {
2829 // Successful write query
2832 return new ResultWrapper( $this, $result );
2836 public function ping() {
2837 # Stub. Not essential to override.
2841 public function getSessionLagStatus() {
2842 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2846 * Get the slave lag when the current transaction started
2848 * This is useful when transactions might use snapshot isolation
2849 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2850 * is this lag plus transaction duration. If they don't, it is still
2851 * safe to be pessimistic. This returns null if there is no transaction.
2853 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2856 public function getTransactionLagStatus() {
2857 return $this->mTrxLevel
2858 ?
[ 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() ]
2863 * Get a slave lag estimate for this server
2865 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2868 public function getApproximateLagStatus() {
2870 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
2871 'since' => microtime( true )
2876 * Merge the result of getSessionLagStatus() for several DBs
2877 * using the most pessimistic values to estimate the lag of
2878 * any data derived from them in combination
2880 * This is information is useful for caching modules
2882 * @see WANObjectCache::set()
2883 * @see WANObjectCache::getWithSetCallback()
2885 * @param IDatabase $db1
2886 * @param IDatabase ...
2887 * @return array Map of values:
2888 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2889 * - since: oldest UNIX timestamp of any of the DB lag estimates
2890 * - pending: whether any of the DBs have uncommitted changes
2893 public static function getCacheSetOptions( IDatabase
$db1 ) {
2894 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
2895 foreach ( func_get_args() as $db ) {
2896 /** @var IDatabase $db */
2897 $status = $db->getSessionLagStatus();
2898 if ( $status['lag'] === false ) {
2899 $res['lag'] = false;
2900 } elseif ( $res['lag'] !== false ) {
2901 $res['lag'] = max( $res['lag'], $status['lag'] );
2903 $res['since'] = min( $res['since'], $status['since'] );
2904 $res['pending'] = $res['pending'] ?
: $db->writesPending();
2910 public function getLag() {
2914 function maxListLen() {
2918 public function encodeBlob( $b ) {
2922 public function decodeBlob( $b ) {
2923 if ( $b instanceof Blob
) {
2929 public function setSessionOptions( array $options ) {
2933 * Read and execute SQL commands from a file.
2935 * Returns true on success, error string or exception on failure (depending
2936 * on object's error ignore settings).
2938 * @param string $filename File name to open
2939 * @param bool|callable $lineCallback Optional function called before reading each line
2940 * @param bool|callable $resultCallback Optional function called for each MySQL result
2941 * @param bool|string $fname Calling function name or false if name should be
2942 * generated dynamically using $filename
2943 * @param bool|callable $inputCallback Optional function called for each
2944 * complete line sent
2945 * @throws Exception|MWException
2946 * @return bool|string
2948 public function sourceFile(
2949 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2951 MediaWiki\
suppressWarnings();
2952 $fp = fopen( $filename, 'r' );
2953 MediaWiki\restoreWarnings
();
2955 if ( false === $fp ) {
2956 throw new MWException( "Could not open \"{$filename}\".\n" );
2960 $fname = __METHOD__
. "( $filename )";
2964 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2965 } catch ( Exception
$e ) {
2976 * Get the full path of a patch file. Originally based on archive()
2977 * from updaters.inc. Keep in mind this always returns a patch, as
2978 * it fails back to MySQL if no DB-specific patch can be found
2980 * @param string $patch The name of the patch, like patch-something.sql
2981 * @return string Full path to patch file
2983 public function patchPath( $patch ) {
2986 $dbType = $this->getType();
2987 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2988 return "$IP/maintenance/$dbType/archives/$patch";
2990 return "$IP/maintenance/archives/$patch";
2994 public function setSchemaVars( $vars ) {
2995 $this->mSchemaVars
= $vars;
2999 * Read and execute commands from an open file handle.
3001 * Returns true on success, error string or exception on failure (depending
3002 * on object's error ignore settings).
3004 * @param resource $fp File handle
3005 * @param bool|callable $lineCallback Optional function called before reading each query
3006 * @param bool|callable $resultCallback Optional function called for each MySQL result
3007 * @param string $fname Calling function name
3008 * @param bool|callable $inputCallback Optional function called for each complete query sent
3009 * @return bool|string
3011 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3012 $fname = __METHOD__
, $inputCallback = false
3016 while ( !feof( $fp ) ) {
3017 if ( $lineCallback ) {
3018 call_user_func( $lineCallback );
3021 $line = trim( fgets( $fp ) );
3023 if ( $line == '' ) {
3027 if ( '-' == $line[0] && '-' == $line[1] ) {
3035 $done = $this->streamStatementEnd( $cmd, $line );
3039 if ( $done ||
feof( $fp ) ) {
3040 $cmd = $this->replaceVars( $cmd );
3042 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3043 $res = $this->query( $cmd, $fname );
3045 if ( $resultCallback ) {
3046 call_user_func( $resultCallback, $res, $this );
3049 if ( false === $res ) {
3050 $err = $this->lastError();
3052 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3063 * Called by sourceStream() to check if we've reached a statement end
3065 * @param string $sql SQL assembled so far
3066 * @param string $newLine New line about to be added to $sql
3067 * @return bool Whether $newLine contains end of the statement
3069 public function streamStatementEnd( &$sql, &$newLine ) {
3070 if ( $this->delimiter
) {
3072 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3073 if ( $newLine != $prev ) {
3082 * Database independent variable replacement. Replaces a set of variables
3083 * in an SQL statement with their contents as given by $this->getSchemaVars().
3085 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3087 * - '{$var}' should be used for text and is passed through the database's
3089 * - `{$var}` should be used for identifiers (e.g. table and database names).
3090 * It is passed through the database's addIdentifierQuotes method which
3091 * can be overridden if the database uses something other than backticks.
3092 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3093 * database's tableName method.
3094 * - / *i* / passes the name that follows through the database's indexName method.
3095 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3096 * its use should be avoided. In 1.24 and older, string encoding was applied.
3098 * @param string $ins SQL statement to replace variables in
3099 * @return string The new SQL statement with variables replaced
3101 protected function replaceVars( $ins ) {
3102 $vars = $this->getSchemaVars();
3103 return preg_replace_callback(
3105 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3106 \'\{\$ (\w+) }\' | # 3. addQuotes
3107 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3108 /\*\$ (\w+) \*/ # 5. leave unencoded
3110 function ( $m ) use ( $vars ) {
3111 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3112 // check for both nonexistent keys *and* the empty string.
3113 if ( isset( $m[1] ) && $m[1] !== '' ) {
3114 if ( $m[1] === 'i' ) {
3115 return $this->indexName( $m[2] );
3117 return $this->tableName( $m[2] );
3119 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3120 return $this->addQuotes( $vars[$m[3]] );
3121 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3122 return $this->addIdentifierQuotes( $vars[$m[4]] );
3123 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3124 return $vars[$m[5]];
3134 * Get schema variables. If none have been set via setSchemaVars(), then
3135 * use some defaults from the current object.
3139 protected function getSchemaVars() {
3140 if ( $this->mSchemaVars
) {
3141 return $this->mSchemaVars
;
3143 return $this->getDefaultSchemaVars();
3148 * Get schema variables to use if none have been set via setSchemaVars().
3150 * Override this in derived classes to provide variables for tables.sql
3151 * and SQL patch files.
3155 protected function getDefaultSchemaVars() {
3159 public function lockIsFree( $lockName, $method ) {
3163 public function lock( $lockName, $method, $timeout = 5 ) {
3164 $this->mNamedLocksHeld
[$lockName] = 1;
3169 public function unlock( $lockName, $method ) {
3170 unset( $this->mNamedLocksHeld
[$lockName] );
3175 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3176 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3180 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3181 $this->commit( __METHOD__
, 'flush' );
3182 $this->unlock( $lockKey, $fname );
3185 $this->commit( __METHOD__
, 'flush' );
3190 public function namedLocksEnqueue() {
3195 * Lock specific tables
3197 * @param array $read Array of tables to lock for read access
3198 * @param array $write Array of tables to lock for write access
3199 * @param string $method Name of caller
3200 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3203 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3208 * Unlock specific tables
3210 * @param string $method The caller
3213 public function unlockTables( $method ) {
3219 * @param string $tableName
3220 * @param string $fName
3221 * @return bool|ResultWrapper
3224 public function dropTable( $tableName, $fName = __METHOD__
) {
3225 if ( !$this->tableExists( $tableName, $fName ) ) {
3228 $sql = "DROP TABLE " . $this->tableName( $tableName );
3229 if ( $this->cascadingDeletes() ) {
3233 return $this->query( $sql, $fName );
3237 * Get search engine class. All subclasses of this need to implement this
3238 * if they wish to use searching.
3242 public function getSearchEngine() {
3243 return 'SearchEngineDummy';
3246 public function getInfinity() {
3250 public function encodeExpiry( $expiry ) {
3251 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3252 ?
$this->getInfinity()
3253 : $this->timestamp( $expiry );
3256 public function decodeExpiry( $expiry, $format = TS_MW
) {
3257 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3259 : wfTimestamp( $format, $expiry );
3262 public function setBigSelects( $value = true ) {
3266 public function isReadOnly() {
3267 return ( $this->getReadOnlyReason() !== false );
3271 * @return string|bool Reason this DB is read-only or false if it is not
3273 protected function getReadOnlyReason() {
3274 $reason = $this->getLBInfo( 'readOnlyReason' );
3276 return is_string( $reason ) ?
$reason : false;
3283 public function __toString() {
3284 return (string)$this->mConn
;
3288 * Run a few simple sanity checks
3290 public function __destruct() {
3291 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3292 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3294 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3296 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3297 $callers[] = $callbackInfo[1];
3299 $callers = implode( ', ', $callers );
3300 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3308 abstract class Database
extends DatabaseBase
{
3309 // B/C until nothing type hints for DatabaseBase
3310 // @TODO: finish renaming DatabaseBase => Database