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; this can mean lost writes or REPEATABLE-READ snapshots
863 $hadTrx = $this->mTrxLevel
;
864 # T127428: for non-write transactions, a disconnect and a COMMIT are similar:
865 # neither changed data and in both cases any read snapshots are reset anyway.
866 $isNoopCommit = ( !$this->writesOrCallbacksPending() && $sql === 'COMMIT' );
867 # Update state tracking to reflect transaction loss
868 $this->mTrxLevel
= 0;
869 $this->mTrxIdleCallbacks
= []; // bug 65263
870 $this->mTrxPreCommitCallbacks
= []; // bug 65263
871 wfDebug( "Connection lost, reconnecting...\n" );
872 # Stash the last error values since ping() might clear them
873 $lastError = $this->lastError();
874 $lastErrno = $this->lastErrno();
875 if ( $this->ping() ) {
876 wfDebug( "Reconnected\n" );
877 $server = $this->getServer();
878 $msg = __METHOD__
. ": lost connection to $server; reconnected";
879 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
881 if ( ( $hadTrx && !$isNoopCommit ) ||
$this->mNamedLocksHeld
) {
882 # Leave $ret as false and let an error be reported.
883 # Callers may catch the exception and continue to use the DB.
884 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
886 # Should be safe to silently retry (no trx/callbacks/locks)
887 $startTime = microtime( true );
888 $ret = $this->doQuery( $commentedSql );
889 $queryRuntime = microtime( true ) - $startTime;
890 # Log the query time and feed it into the DB trx profiler
891 $this->getTransactionProfiler()->recordQueryCompletion(
892 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
895 wfDebug( "Failed\n" );
899 if ( false === $ret ) {
900 $this->reportQueryError(
901 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
904 $res = $this->resultObject( $ret );
906 // Destroy profile sections in the opposite order to their creation
907 ScopedCallback
::consume( $queryProfSection );
908 ScopedCallback
::consume( $totalProfSection );
910 if ( $isWriteQuery && $this->mTrxLevel
) {
911 $this->mTrxWriteDuration +
= $queryRuntime;
912 $this->mTrxWriteCallers
[] = $fname;
918 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
919 if ( $this->ignoreErrors() ||
$tempIgnore ) {
920 wfDebug( "SQL ERROR (ignored): $error\n" );
922 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
924 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
925 $this->getLogContext( [
926 'method' => __METHOD__
,
929 'sql1line' => $sql1line,
933 wfDebug( "SQL ERROR: " . $error . "\n" );
934 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
939 * Intended to be compatible with the PEAR::DB wrapper functions.
940 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
942 * ? = scalar value, quoted as necessary
943 * ! = raw SQL bit (a function for instance)
944 * & = filename; reads the file and inserts as a blob
945 * (we don't use this though...)
948 * @param string $func
952 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
953 /* MySQL doesn't support prepared statements (yet), so just
954 * pack up the query for reference. We'll manually replace
957 return [ 'query' => $sql, 'func' => $func ];
961 * Free a prepared query, generated by prepare().
962 * @param string $prepared
964 protected function freePrepared( $prepared ) {
965 /* No-op by default */
969 * Execute a prepared query with the various arguments
970 * @param string $prepared The prepared sql
971 * @param mixed $args Either an array here, or put scalars as varargs
973 * @return ResultWrapper
975 public function execute( $prepared, $args = null ) {
976 if ( !is_array( $args ) ) {
978 $args = func_get_args();
979 array_shift( $args );
982 $sql = $this->fillPrepared( $prepared['query'], $args );
984 return $this->query( $sql, $prepared['func'] );
988 * For faking prepared SQL statements on DBs that don't support it directly.
990 * @param string $preparedQuery A 'preparable' SQL statement
991 * @param array $args Array of Arguments to fill it with
992 * @return string Executable SQL
994 public function fillPrepared( $preparedQuery, $args ) {
996 $this->preparedArgs
=& $args;
998 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
999 [ &$this, 'fillPreparedArg' ], $preparedQuery );
1003 * preg_callback func for fillPrepared()
1004 * The arguments should be in $this->preparedArgs and must not be touched
1005 * while we're doing this.
1007 * @param array $matches
1008 * @throws DBUnexpectedError
1011 protected function fillPreparedArg( $matches ) {
1012 switch ( $matches[1] ) {
1021 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1023 switch ( $matches[1] ) {
1025 return $this->addQuotes( $arg );
1029 # return $this->addQuotes( file_get_contents( $arg ) );
1030 throw new DBUnexpectedError(
1032 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1035 throw new DBUnexpectedError(
1037 'Received invalid match. This should never happen!'
1042 public function freeResult( $res ) {
1045 public function selectField(
1046 $table, $var, $cond = '', $fname = __METHOD__
, $options = []
1048 if ( $var === '*' ) { // sanity
1049 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1052 if ( !is_array( $options ) ) {
1053 $options = [ $options ];
1056 $options['LIMIT'] = 1;
1058 $res = $this->select( $table, $var, $cond, $fname, $options );
1059 if ( $res === false ||
!$this->numRows( $res ) ) {
1063 $row = $this->fetchRow( $res );
1065 if ( $row !== false ) {
1066 return reset( $row );
1072 public function selectFieldValues(
1073 $table, $var, $cond = '', $fname = __METHOD__
, $options = [], $join_conds = []
1075 if ( $var === '*' ) { // sanity
1076 throw new DBUnexpectedError( $this, "Cannot use a * field" );
1077 } elseif ( !is_string( $var ) ) { // sanity
1078 throw new DBUnexpectedError( $this, "Cannot use an array of fields" );
1081 if ( !is_array( $options ) ) {
1082 $options = [ $options ];
1085 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1086 if ( $res === false ) {
1091 foreach ( $res as $row ) {
1092 $values[] = $row->$var;
1099 * Returns an optional USE INDEX clause to go after the table, and a
1100 * string to go at the end of the query.
1102 * @param array $options Associative array of options to be turned into
1103 * an SQL query, valid keys are listed in the function.
1105 * @see DatabaseBase::select()
1107 public function makeSelectOptions( $options ) {
1108 $preLimitTail = $postLimitTail = '';
1113 foreach ( $options as $key => $option ) {
1114 if ( is_numeric( $key ) ) {
1115 $noKeyOptions[$option] = true;
1119 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1121 $preLimitTail .= $this->makeOrderBy( $options );
1123 // if (isset($options['LIMIT'])) {
1124 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1125 // isset($options['OFFSET']) ? $options['OFFSET']
1129 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1130 $postLimitTail .= ' FOR UPDATE';
1133 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1134 $postLimitTail .= ' LOCK IN SHARE MODE';
1137 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1138 $startOpts .= 'DISTINCT';
1141 # Various MySQL extensions
1142 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1143 $startOpts .= ' /*! STRAIGHT_JOIN */';
1146 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1147 $startOpts .= ' HIGH_PRIORITY';
1150 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1151 $startOpts .= ' SQL_BIG_RESULT';
1154 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1155 $startOpts .= ' SQL_BUFFER_RESULT';
1158 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1159 $startOpts .= ' SQL_SMALL_RESULT';
1162 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1163 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1166 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1167 $startOpts .= ' SQL_CACHE';
1170 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1171 $startOpts .= ' SQL_NO_CACHE';
1174 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1175 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1180 return [ $startOpts, $useIndex, $preLimitTail, $postLimitTail ];
1184 * Returns an optional GROUP BY with an optional HAVING
1186 * @param array $options Associative array of options
1188 * @see DatabaseBase::select()
1191 public function makeGroupByWithHaving( $options ) {
1193 if ( isset( $options['GROUP BY'] ) ) {
1194 $gb = is_array( $options['GROUP BY'] )
1195 ?
implode( ',', $options['GROUP BY'] )
1196 : $options['GROUP BY'];
1197 $sql .= ' GROUP BY ' . $gb;
1199 if ( isset( $options['HAVING'] ) ) {
1200 $having = is_array( $options['HAVING'] )
1201 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1202 : $options['HAVING'];
1203 $sql .= ' HAVING ' . $having;
1210 * Returns an optional ORDER BY
1212 * @param array $options Associative array of options
1214 * @see DatabaseBase::select()
1217 public function makeOrderBy( $options ) {
1218 if ( isset( $options['ORDER BY'] ) ) {
1219 $ob = is_array( $options['ORDER BY'] )
1220 ?
implode( ',', $options['ORDER BY'] )
1221 : $options['ORDER BY'];
1223 return ' ORDER BY ' . $ob;
1229 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1230 $options = [], $join_conds = [] ) {
1231 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1233 return $this->query( $sql, $fname );
1236 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1237 $options = [], $join_conds = []
1239 if ( is_array( $vars ) ) {
1240 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1243 $options = (array)$options;
1244 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1245 ?
$options['USE INDEX']
1248 if ( is_array( $table ) ) {
1250 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1251 } elseif ( $table != '' ) {
1252 if ( $table[0] == ' ' ) {
1253 $from = ' FROM ' . $table;
1256 $this->tableNamesWithUseIndexOrJOIN( [ $table ], $useIndexes, [] );
1262 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1263 $this->makeSelectOptions( $options );
1265 if ( !empty( $conds ) ) {
1266 if ( is_array( $conds ) ) {
1267 $conds = $this->makeList( $conds, LIST_AND
);
1269 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1271 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1274 if ( isset( $options['LIMIT'] ) ) {
1275 $sql = $this->limitResult( $sql, $options['LIMIT'],
1276 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1278 $sql = "$sql $postLimitTail";
1280 if ( isset( $options['EXPLAIN'] ) ) {
1281 $sql = 'EXPLAIN ' . $sql;
1287 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1288 $options = [], $join_conds = []
1290 $options = (array)$options;
1291 $options['LIMIT'] = 1;
1292 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1294 if ( $res === false ) {
1298 if ( !$this->numRows( $res ) ) {
1302 $obj = $this->fetchObject( $res );
1307 public function estimateRowCount(
1308 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = []
1311 $res = $this->select( $table, [ 'rowcount' => 'COUNT(*)' ], $conds, $fname, $options );
1314 $row = $this->fetchRow( $res );
1315 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1321 public function selectRowCount(
1322 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = [], $join_conds = []
1325 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1326 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1329 $row = $this->fetchRow( $res );
1330 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1337 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1338 * It's only slightly flawed. Don't use for anything important.
1340 * @param string $sql A SQL Query
1344 protected static function generalizeSQL( $sql ) {
1345 # This does the same as the regexp below would do, but in such a way
1346 # as to avoid crashing php on some large strings.
1347 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1349 $sql = str_replace( "\\\\", '', $sql );
1350 $sql = str_replace( "\\'", '', $sql );
1351 $sql = str_replace( "\\\"", '', $sql );
1352 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1353 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1355 # All newlines, tabs, etc replaced by single space
1356 $sql = preg_replace( '/\s+/', ' ', $sql );
1359 # except the ones surrounded by characters, e.g. l10n
1360 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1361 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1366 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1367 $info = $this->fieldInfo( $table, $field );
1372 public function indexExists( $table, $index, $fname = __METHOD__
) {
1373 if ( !$this->tableExists( $table ) ) {
1377 $info = $this->indexInfo( $table, $index, $fname );
1378 if ( is_null( $info ) ) {
1381 return $info !== false;
1385 public function tableExists( $table, $fname = __METHOD__
) {
1386 $table = $this->tableName( $table );
1387 $old = $this->ignoreErrors( true );
1388 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1389 $this->ignoreErrors( $old );
1394 public function indexUnique( $table, $index ) {
1395 $indexInfo = $this->indexInfo( $table, $index );
1397 if ( !$indexInfo ) {
1401 return !$indexInfo[0]->Non_unique
;
1405 * Helper for DatabaseBase::insert().
1407 * @param array $options
1410 protected function makeInsertOptions( $options ) {
1411 return implode( ' ', $options );
1414 public function insert( $table, $a, $fname = __METHOD__
, $options = [] ) {
1415 # No rows to insert, easy just return now
1416 if ( !count( $a ) ) {
1420 $table = $this->tableName( $table );
1422 if ( !is_array( $options ) ) {
1423 $options = [ $options ];
1427 if ( isset( $options['fileHandle'] ) ) {
1428 $fh = $options['fileHandle'];
1430 $options = $this->makeInsertOptions( $options );
1432 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1434 $keys = array_keys( $a[0] );
1437 $keys = array_keys( $a );
1440 $sql = 'INSERT ' . $options .
1441 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1445 foreach ( $a as $row ) {
1451 $sql .= '(' . $this->makeList( $row ) . ')';
1454 $sql .= '(' . $this->makeList( $a ) . ')';
1457 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1459 } elseif ( $fh !== null ) {
1463 return (bool)$this->query( $sql, $fname );
1467 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1469 * @param array $options
1472 protected function makeUpdateOptionsArray( $options ) {
1473 if ( !is_array( $options ) ) {
1474 $options = [ $options ];
1479 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1480 $opts[] = $this->lowPriorityOption();
1483 if ( in_array( 'IGNORE', $options ) ) {
1491 * Make UPDATE options for the DatabaseBase::update function
1493 * @param array $options The options passed to DatabaseBase::update
1496 protected function makeUpdateOptions( $options ) {
1497 $opts = $this->makeUpdateOptionsArray( $options );
1499 return implode( ' ', $opts );
1502 function update( $table, $values, $conds, $fname = __METHOD__
, $options = [] ) {
1503 $table = $this->tableName( $table );
1504 $opts = $this->makeUpdateOptions( $options );
1505 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1507 if ( $conds !== [] && $conds !== '*' ) {
1508 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1511 return $this->query( $sql, $fname );
1514 public function makeList( $a, $mode = LIST_COMMA
) {
1515 if ( !is_array( $a ) ) {
1516 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1522 foreach ( $a as $field => $value ) {
1524 if ( $mode == LIST_AND
) {
1526 } elseif ( $mode == LIST_OR
) {
1535 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1536 $list .= "($value)";
1537 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1539 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1540 // Remove null from array to be handled separately if found
1541 $includeNull = false;
1542 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1543 $includeNull = true;
1544 unset( $value[$nullKey] );
1546 if ( count( $value ) == 0 && !$includeNull ) {
1547 throw new MWException( __METHOD__
. ": empty input for field $field" );
1548 } elseif ( count( $value ) == 0 ) {
1549 // only check if $field is null
1550 $list .= "$field IS NULL";
1552 // IN clause contains at least one valid element
1553 if ( $includeNull ) {
1554 // Group subconditions to ensure correct precedence
1557 if ( count( $value ) == 1 ) {
1558 // Special-case single values, as IN isn't terribly efficient
1559 // Don't necessarily assume the single key is 0; we don't
1560 // enforce linear numeric ordering on other arrays here.
1561 $value = array_values( $value )[0];
1562 $list .= $field . " = " . $this->addQuotes( $value );
1564 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1566 // if null present in array, append IS NULL
1567 if ( $includeNull ) {
1568 $list .= " OR $field IS NULL)";
1571 } elseif ( $value === null ) {
1572 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1573 $list .= "$field IS ";
1574 } elseif ( $mode == LIST_SET
) {
1575 $list .= "$field = ";
1579 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1580 $list .= "$field = ";
1582 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1589 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1592 foreach ( $data as $base => $sub ) {
1593 if ( count( $sub ) ) {
1594 $conds[] = $this->makeList(
1595 [ $baseKey => $base, $subKey => array_keys( $sub ) ],
1601 return $this->makeList( $conds, LIST_OR
);
1603 // Nothing to search for...
1609 * Return aggregated value alias
1611 * @param array $valuedata
1612 * @param string $valuename
1616 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1620 public function bitNot( $field ) {
1624 public function bitAnd( $fieldLeft, $fieldRight ) {
1625 return "($fieldLeft & $fieldRight)";
1628 public function bitOr( $fieldLeft, $fieldRight ) {
1629 return "($fieldLeft | $fieldRight)";
1632 public function buildConcat( $stringList ) {
1633 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1636 public function buildGroupConcatField(
1637 $delim, $table, $field, $conds = '', $join_conds = []
1639 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1641 return '(' . $this->selectSQLText( $table, $fld, $conds, null, [], $join_conds ) . ')';
1644 public function selectDB( $db ) {
1645 # Stub. Shouldn't cause serious problems if it's not overridden, but
1646 # if your database engine supports a concept similar to MySQL's
1647 # databases you may as well.
1648 $this->mDBname
= $db;
1653 public function getDBname() {
1654 return $this->mDBname
;
1657 public function getServer() {
1658 return $this->mServer
;
1662 * Format a table name ready for use in constructing an SQL query
1664 * This does two important things: it quotes the table names to clean them up,
1665 * and it adds a table prefix if only given a table name with no quotes.
1667 * All functions of this object which require a table name call this function
1668 * themselves. Pass the canonical name to such functions. This is only needed
1669 * when calling query() directly.
1671 * @param string $name Database table name
1672 * @param string $format One of:
1673 * quoted - Automatically pass the table name through addIdentifierQuotes()
1674 * so that it can be used in a query.
1675 * raw - Do not add identifier quotes to the table name
1676 * @return string Full database name
1678 public function tableName( $name, $format = 'quoted' ) {
1679 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1680 # Skip the entire process when we have a string quoted on both ends.
1681 # Note that we check the end so that we will still quote any use of
1682 # use of `database`.table. But won't break things if someone wants
1683 # to query a database table with a dot in the name.
1684 if ( $this->isQuotedIdentifier( $name ) ) {
1688 # Lets test for any bits of text that should never show up in a table
1689 # name. Basically anything like JOIN or ON which are actually part of
1690 # SQL queries, but may end up inside of the table value to combine
1691 # sql. Such as how the API is doing.
1692 # Note that we use a whitespace test rather than a \b test to avoid
1693 # any remote case where a word like on may be inside of a table name
1694 # surrounded by symbols which may be considered word breaks.
1695 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1699 # Split database and table into proper variables.
1700 # We reverse the explode so that database.table and table both output
1701 # the correct table.
1702 $dbDetails = explode( '.', $name, 3 );
1703 if ( count( $dbDetails ) == 3 ) {
1704 list( $database, $schema, $table ) = $dbDetails;
1705 # We don't want any prefix added in this case
1707 } elseif ( count( $dbDetails ) == 2 ) {
1708 list( $database, $table ) = $dbDetails;
1709 # We don't want any prefix added in this case
1710 # In dbs that support it, $database may actually be the schema
1711 # but that doesn't affect any of the functionality here
1715 list( $table ) = $dbDetails;
1716 if ( $wgSharedDB !== null # We have a shared database
1717 && $this->mForeign
== false # We're not working on a foreign database
1718 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1719 && in_array( $table, $wgSharedTables ) # A shared table is selected
1721 $database = $wgSharedDB;
1722 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1723 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1726 $schema = $this->mSchema
; # Default schema
1727 $prefix = $this->mTablePrefix
; # Default prefix
1731 # Quote $table and apply the prefix if not quoted.
1732 # $tableName might be empty if this is called from Database::replaceVars()
1733 $tableName = "{$prefix}{$table}";
1734 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1735 $tableName = $this->addIdentifierQuotes( $tableName );
1738 # Quote $schema and merge it with the table name if needed
1739 if ( strlen( $schema ) ) {
1740 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1741 $schema = $this->addIdentifierQuotes( $schema );
1743 $tableName = $schema . '.' . $tableName;
1746 # Quote $database and merge it with the table name if needed
1747 if ( $database !== null ) {
1748 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1749 $database = $this->addIdentifierQuotes( $database );
1751 $tableName = $database . '.' . $tableName;
1758 * Fetch a number of table names into an array
1759 * This is handy when you need to construct SQL for joins
1762 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1763 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1764 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1768 public function tableNames() {
1769 $inArray = func_get_args();
1772 foreach ( $inArray as $name ) {
1773 $retVal[$name] = $this->tableName( $name );
1780 * Fetch a number of table names into an zero-indexed numerical array
1781 * This is handy when you need to construct SQL for joins
1784 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1785 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1786 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1790 public function tableNamesN() {
1791 $inArray = func_get_args();
1794 foreach ( $inArray as $name ) {
1795 $retVal[] = $this->tableName( $name );
1802 * Get an aliased table name
1803 * e.g. tableName AS newTableName
1805 * @param string $name Table name, see tableName()
1806 * @param string|bool $alias Alias (optional)
1807 * @return string SQL name for aliased table. Will not alias a table to its own name
1809 public function tableNameWithAlias( $name, $alias = false ) {
1810 if ( !$alias ||
$alias == $name ) {
1811 return $this->tableName( $name );
1813 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1818 * Gets an array of aliased table names
1820 * @param array $tables Array( [alias] => table )
1821 * @return string[] See tableNameWithAlias()
1823 public function tableNamesWithAlias( $tables ) {
1825 foreach ( $tables as $alias => $table ) {
1826 if ( is_numeric( $alias ) ) {
1829 $retval[] = $this->tableNameWithAlias( $table, $alias );
1836 * Get an aliased field name
1837 * e.g. fieldName AS newFieldName
1839 * @param string $name Field name
1840 * @param string|bool $alias Alias (optional)
1841 * @return string SQL name for aliased field. Will not alias a field to its own name
1843 public function fieldNameWithAlias( $name, $alias = false ) {
1844 if ( !$alias ||
(string)$alias === (string)$name ) {
1847 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1852 * Gets an array of aliased field names
1854 * @param array $fields Array( [alias] => field )
1855 * @return string[] See fieldNameWithAlias()
1857 public function fieldNamesWithAlias( $fields ) {
1859 foreach ( $fields as $alias => $field ) {
1860 if ( is_numeric( $alias ) ) {
1863 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1870 * Get the aliased table name clause for a FROM clause
1871 * which might have a JOIN and/or USE INDEX clause
1873 * @param array $tables ( [alias] => table )
1874 * @param array $use_index Same as for select()
1875 * @param array $join_conds Same as for select()
1878 protected function tableNamesWithUseIndexOrJOIN(
1879 $tables, $use_index = [], $join_conds = []
1883 $use_index = (array)$use_index;
1884 $join_conds = (array)$join_conds;
1886 foreach ( $tables as $alias => $table ) {
1887 if ( !is_string( $alias ) ) {
1888 // No alias? Set it equal to the table name
1891 // Is there a JOIN clause for this table?
1892 if ( isset( $join_conds[$alias] ) ) {
1893 list( $joinType, $conds ) = $join_conds[$alias];
1894 $tableClause = $joinType;
1895 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1896 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1897 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1899 $tableClause .= ' ' . $use;
1902 $on = $this->makeList( (array)$conds, LIST_AND
);
1904 $tableClause .= ' ON (' . $on . ')';
1907 $retJOIN[] = $tableClause;
1908 } elseif ( isset( $use_index[$alias] ) ) {
1909 // Is there an INDEX clause for this table?
1910 $tableClause = $this->tableNameWithAlias( $table, $alias );
1911 $tableClause .= ' ' . $this->useIndexClause(
1912 implode( ',', (array)$use_index[$alias] )
1915 $ret[] = $tableClause;
1917 $tableClause = $this->tableNameWithAlias( $table, $alias );
1919 $ret[] = $tableClause;
1923 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1924 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1925 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1927 // Compile our final table clause
1928 return implode( ' ', [ $implicitJoins, $explicitJoins ] );
1932 * Get the name of an index in a given table.
1934 * @param string $index
1937 protected function indexName( $index ) {
1938 // Backwards-compatibility hack
1940 'ar_usertext_timestamp' => 'usertext_timestamp',
1941 'un_user_id' => 'user_id',
1942 'un_user_ip' => 'user_ip',
1945 if ( isset( $renamed[$index] ) ) {
1946 return $renamed[$index];
1952 public function addQuotes( $s ) {
1953 if ( $s instanceof Blob
) {
1956 if ( $s === null ) {
1959 # This will also quote numeric values. This should be harmless,
1960 # and protects against weird problems that occur when they really
1961 # _are_ strings such as article titles and string->number->string
1962 # conversion is not 1:1.
1963 return "'" . $this->strencode( $s ) . "'";
1968 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1969 * MySQL uses `backticks` while basically everything else uses double quotes.
1970 * Since MySQL is the odd one out here the double quotes are our generic
1971 * and we implement backticks in DatabaseMysql.
1976 public function addIdentifierQuotes( $s ) {
1977 return '"' . str_replace( '"', '""', $s ) . '"';
1981 * Returns if the given identifier looks quoted or not according to
1982 * the database convention for quoting identifiers .
1984 * @param string $name
1987 public function isQuotedIdentifier( $name ) {
1988 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1995 protected function escapeLikeInternal( $s ) {
1996 return addcslashes( $s, '\%_' );
1999 public function buildLike() {
2000 $params = func_get_args();
2002 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2003 $params = $params[0];
2008 foreach ( $params as $value ) {
2009 if ( $value instanceof LikeMatch
) {
2010 $s .= $value->toString();
2012 $s .= $this->escapeLikeInternal( $value );
2016 return " LIKE {$this->addQuotes( $s )} ";
2019 public function anyChar() {
2020 return new LikeMatch( '_' );
2023 public function anyString() {
2024 return new LikeMatch( '%' );
2027 public function nextSequenceValue( $seqName ) {
2032 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2033 * is only needed because a) MySQL must be as efficient as possible due to
2034 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2035 * which index to pick. Anyway, other databases might have different
2036 * indexes on a given table. So don't bother overriding this unless you're
2038 * @param string $index
2041 public function useIndexClause( $index ) {
2045 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2046 $quotedTable = $this->tableName( $table );
2048 if ( count( $rows ) == 0 ) {
2053 if ( !is_array( reset( $rows ) ) ) {
2057 // @FXIME: this is not atomic, but a trx would break affectedRows()
2058 foreach ( $rows as $row ) {
2059 # Delete rows which collide
2060 if ( $uniqueIndexes ) {
2061 $sql = "DELETE FROM $quotedTable WHERE ";
2063 foreach ( $uniqueIndexes as $index ) {
2070 if ( is_array( $index ) ) {
2072 foreach ( $index as $col ) {
2078 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2081 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2085 $this->query( $sql, $fname );
2088 # Now insert the row
2089 $this->insert( $table, $row, $fname );
2094 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2097 * @param string $table Table name
2098 * @param array|string $rows Row(s) to insert
2099 * @param string $fname Caller function name
2101 * @return ResultWrapper
2103 protected function nativeReplace( $table, $rows, $fname ) {
2104 $table = $this->tableName( $table );
2107 if ( !is_array( reset( $rows ) ) ) {
2111 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2114 foreach ( $rows as $row ) {
2121 $sql .= '(' . $this->makeList( $row ) . ')';
2124 return $this->query( $sql, $fname );
2127 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2130 if ( !count( $rows ) ) {
2131 return true; // nothing to do
2134 if ( !is_array( reset( $rows ) ) ) {
2138 if ( count( $uniqueIndexes ) ) {
2139 $clauses = []; // list WHERE clauses that each identify a single row
2140 foreach ( $rows as $row ) {
2141 foreach ( $uniqueIndexes as $index ) {
2142 $index = is_array( $index ) ?
$index : [ $index ]; // columns
2143 $rowKey = []; // unique key to this row
2144 foreach ( $index as $column ) {
2145 $rowKey[$column] = $row[$column];
2147 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2150 $where = [ $this->makeList( $clauses, LIST_OR
) ];
2155 $useTrx = !$this->mTrxLevel
;
2157 $this->begin( $fname );
2160 # Update any existing conflicting row(s)
2161 if ( $where !== false ) {
2162 $ok = $this->update( $table, $set, $where, $fname );
2166 # Now insert any non-conflicting row(s)
2167 $ok = $this->insert( $table, $rows, $fname, [ 'IGNORE' ] ) && $ok;
2168 } catch ( Exception
$e ) {
2170 $this->rollback( $fname );
2175 $this->commit( $fname );
2181 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2185 throw new DBUnexpectedError( $this,
2186 'DatabaseBase::deleteJoin() called with empty $conds' );
2189 $delTable = $this->tableName( $delTable );
2190 $joinTable = $this->tableName( $joinTable );
2191 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2192 if ( $conds != '*' ) {
2193 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2197 $this->query( $sql, $fname );
2201 * Returns the size of a text field, or -1 for "unlimited"
2203 * @param string $table
2204 * @param string $field
2207 public function textFieldSize( $table, $field ) {
2208 $table = $this->tableName( $table );
2209 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2210 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2211 $row = $this->fetchObject( $res );
2215 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2225 * A string to insert into queries to show that they're low-priority, like
2226 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2227 * string and nothing bad should happen.
2229 * @return string Returns the text of the low priority option if it is
2230 * supported, or a blank string otherwise
2232 public function lowPriorityOption() {
2236 public function delete( $table, $conds, $fname = __METHOD__
) {
2238 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2241 $table = $this->tableName( $table );
2242 $sql = "DELETE FROM $table";
2244 if ( $conds != '*' ) {
2245 if ( is_array( $conds ) ) {
2246 $conds = $this->makeList( $conds, LIST_AND
);
2248 $sql .= ' WHERE ' . $conds;
2251 return $this->query( $sql, $fname );
2254 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2255 $fname = __METHOD__
,
2256 $insertOptions = [], $selectOptions = []
2258 $destTable = $this->tableName( $destTable );
2260 if ( !is_array( $insertOptions ) ) {
2261 $insertOptions = [ $insertOptions ];
2264 $insertOptions = $this->makeInsertOptions( $insertOptions );
2266 if ( !is_array( $selectOptions ) ) {
2267 $selectOptions = [ $selectOptions ];
2270 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2272 if ( is_array( $srcTable ) ) {
2273 $srcTable = implode( ',', array_map( [ &$this, 'tableName' ], $srcTable ) );
2275 $srcTable = $this->tableName( $srcTable );
2278 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2279 " SELECT $startOpts " . implode( ',', $varMap ) .
2280 " FROM $srcTable $useIndex ";
2282 if ( $conds != '*' ) {
2283 if ( is_array( $conds ) ) {
2284 $conds = $this->makeList( $conds, LIST_AND
);
2286 $sql .= " WHERE $conds";
2289 $sql .= " $tailOpts";
2291 return $this->query( $sql, $fname );
2295 * Construct a LIMIT query with optional offset. This is used for query
2296 * pages. The SQL should be adjusted so that only the first $limit rows
2297 * are returned. If $offset is provided as well, then the first $offset
2298 * rows should be discarded, and the next $limit rows should be returned.
2299 * If the result of the query is not ordered, then the rows to be returned
2300 * are theoretically arbitrary.
2302 * $sql is expected to be a SELECT, if that makes a difference.
2304 * The version provided by default works in MySQL and SQLite. It will very
2305 * likely need to be overridden for most other DBMSes.
2307 * @param string $sql SQL query we will append the limit too
2308 * @param int $limit The SQL limit
2309 * @param int|bool $offset The SQL offset (default false)
2310 * @throws DBUnexpectedError
2313 public function limitResult( $sql, $limit, $offset = false ) {
2314 if ( !is_numeric( $limit ) ) {
2315 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2318 return "$sql LIMIT "
2319 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2323 public function unionSupportsOrderAndLimit() {
2324 return true; // True for almost every DB supported
2327 public function unionQueries( $sqls, $all ) {
2328 $glue = $all ?
') UNION ALL (' : ') UNION (';
2330 return '(' . implode( $glue, $sqls ) . ')';
2333 public function conditional( $cond, $trueVal, $falseVal ) {
2334 if ( is_array( $cond ) ) {
2335 $cond = $this->makeList( $cond, LIST_AND
);
2338 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2341 public function strreplace( $orig, $old, $new ) {
2342 return "REPLACE({$orig}, {$old}, {$new})";
2345 public function getServerUptime() {
2349 public function wasDeadlock() {
2353 public function wasLockTimeout() {
2357 public function wasErrorReissuable() {
2361 public function wasReadOnlyError() {
2366 * Determines if the given query error was a connection drop
2369 * @param integer|string $errno
2372 public function wasConnectionError( $errno ) {
2377 * Perform a deadlock-prone transaction.
2379 * This function invokes a callback function to perform a set of write
2380 * queries. If a deadlock occurs during the processing, the transaction
2381 * will be rolled back and the callback function will be called again.
2384 * $dbw->deadlockLoop( callback, ... );
2386 * Extra arguments are passed through to the specified callback function.
2388 * Returns whatever the callback function returned on its successful,
2389 * iteration, or false on error, for example if the retry limit was
2392 * @throws DBUnexpectedError
2395 public function deadlockLoop() {
2396 $args = func_get_args();
2397 $function = array_shift( $args );
2398 $tries = self
::DEADLOCK_TRIES
;
2400 $this->begin( __METHOD__
);
2403 /** @var Exception $e */
2407 $retVal = call_user_func_array( $function, $args );
2409 } catch ( DBQueryError
$e ) {
2410 if ( $this->wasDeadlock() ) {
2411 // Retry after a randomized delay
2412 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2414 // Throw the error back up
2418 } while ( --$tries > 0 );
2420 if ( $tries <= 0 ) {
2421 // Too many deadlocks; give up
2422 $this->rollback( __METHOD__
);
2425 $this->commit( __METHOD__
);
2431 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2432 # Real waits are implemented in the subclass.
2436 public function getSlavePos() {
2441 public function getMasterPos() {
2446 final public function onTransactionIdle( $callback ) {
2447 $this->mTrxIdleCallbacks
[] = [ $callback, wfGetCaller() ];
2448 if ( !$this->mTrxLevel
) {
2449 $this->runOnTransactionIdleCallbacks();
2453 final public function onTransactionPreCommitOrIdle( $callback ) {
2454 if ( $this->mTrxLevel
) {
2455 $this->mTrxPreCommitCallbacks
[] = [ $callback, wfGetCaller() ];
2457 $this->onTransactionIdle( $callback ); // this will trigger immediately
2462 * Actually any "on transaction idle" callbacks.
2466 protected function runOnTransactionIdleCallbacks() {
2467 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2469 $e = $ePrior = null; // last exception
2470 do { // callbacks may add callbacks :)
2471 $callbacks = $this->mTrxIdleCallbacks
;
2472 $this->mTrxIdleCallbacks
= []; // recursion guard
2473 foreach ( $callbacks as $callback ) {
2475 list( $phpCallback ) = $callback;
2476 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2477 call_user_func( $phpCallback );
2479 $this->setFlag( DBO_TRX
); // restore automatic begin()
2481 $this->clearFlag( DBO_TRX
); // restore auto-commit
2483 } catch ( Exception
$e ) {
2485 MWExceptionHandler
::logException( $ePrior );
2488 // Some callbacks may use startAtomic/endAtomic, so make sure
2489 // their transactions are ended so other callbacks don't fail
2490 if ( $this->trxLevel() ) {
2491 $this->rollback( __METHOD__
);
2495 } while ( count( $this->mTrxIdleCallbacks
) );
2497 if ( $e instanceof Exception
) {
2498 throw $e; // re-throw any last exception
2503 * Actually any "on transaction pre-commit" callbacks.
2507 protected function runOnTransactionPreCommitCallbacks() {
2508 $e = $ePrior = null; // last exception
2509 do { // callbacks may add callbacks :)
2510 $callbacks = $this->mTrxPreCommitCallbacks
;
2511 $this->mTrxPreCommitCallbacks
= []; // recursion guard
2512 foreach ( $callbacks as $callback ) {
2514 list( $phpCallback ) = $callback;
2515 call_user_func( $phpCallback );
2516 } catch ( Exception
$e ) {
2518 MWExceptionHandler
::logException( $ePrior );
2523 } while ( count( $this->mTrxPreCommitCallbacks
) );
2525 if ( $e instanceof Exception
) {
2526 throw $e; // re-throw any last exception
2530 final public function startAtomic( $fname = __METHOD__
) {
2531 if ( !$this->mTrxLevel
) {
2532 $this->begin( $fname );
2533 $this->mTrxAutomatic
= true;
2534 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2535 // in all changes being in one transaction to keep requests transactional.
2536 if ( !$this->getFlag( DBO_TRX
) ) {
2537 $this->mTrxAutomaticAtomic
= true;
2541 $this->mTrxAtomicLevels
[] = $fname;
2544 final public function endAtomic( $fname = __METHOD__
) {
2545 if ( !$this->mTrxLevel
) {
2546 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2548 if ( !$this->mTrxAtomicLevels ||
2549 array_pop( $this->mTrxAtomicLevels
) !== $fname
2551 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2554 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2555 $this->commit( $fname, 'flush' );
2559 final public function doAtomicSection( $fname, $callback ) {
2560 if ( !is_callable( $callback ) ) {
2561 throw new UnexpectedValueException( "Invalid callback." );
2564 $this->startAtomic( $fname );
2566 call_user_func_array( $callback, [ $this, $fname ] );
2567 } catch ( Exception
$e ) {
2568 $this->rollback( $fname );
2571 $this->endAtomic( $fname );
2574 final public function begin( $fname = __METHOD__
) {
2575 if ( $this->mTrxLevel
) { // implicit commit
2576 if ( $this->mTrxAtomicLevels
) {
2577 // If the current transaction was an automatic atomic one, then we definitely have
2578 // a problem. Same if there is any unclosed atomic level.
2579 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2580 throw new DBUnexpectedError(
2582 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2584 } elseif ( !$this->mTrxAutomatic
) {
2585 // We want to warn about inadvertently nested begin/commit pairs, but not about
2586 // auto-committing implicit transactions that were started by query() via DBO_TRX
2587 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2588 " performing implicit commit!";
2591 $this->getLogContext( [
2592 'method' => __METHOD__
,
2597 // if the transaction was automatic and has done write operations
2598 if ( $this->mTrxDoneWrites
) {
2599 wfDebug( "$fname: Automatic transaction with writes in progress" .
2600 " (from {$this->mTrxFname}), performing implicit commit!\n"
2605 $this->runOnTransactionPreCommitCallbacks();
2606 $writeTime = $this->pendingWriteQueryDuration();
2607 $this->doCommit( $fname );
2608 if ( $this->mTrxDoneWrites
) {
2609 $this->mDoneWrites
= microtime( true );
2610 $this->getTransactionProfiler()->transactionWritingOut(
2611 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2613 $this->runOnTransactionIdleCallbacks();
2616 # Avoid fatals if close() was called
2617 $this->assertOpen();
2619 $this->doBegin( $fname );
2620 $this->mTrxTimestamp
= microtime( true );
2621 $this->mTrxFname
= $fname;
2622 $this->mTrxDoneWrites
= false;
2623 $this->mTrxAutomatic
= false;
2624 $this->mTrxAutomaticAtomic
= false;
2625 $this->mTrxAtomicLevels
= [];
2626 $this->mTrxIdleCallbacks
= [];
2627 $this->mTrxPreCommitCallbacks
= [];
2628 $this->mTrxShortId
= wfRandomString( 12 );
2629 $this->mTrxWriteDuration
= 0.0;
2630 $this->mTrxWriteCallers
= [];
2631 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2632 // Get an estimate of the slave lag before then, treating estimate staleness
2633 // as lag itself just to be safe
2634 $status = $this->getApproximateLagStatus();
2635 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2639 * Issues the BEGIN command to the database server.
2641 * @see DatabaseBase::begin()
2642 * @param string $fname
2644 protected function doBegin( $fname ) {
2645 $this->query( 'BEGIN', $fname );
2646 $this->mTrxLevel
= 1;
2649 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2650 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2651 // There are still atomic sections open. This cannot be ignored
2652 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2653 throw new DBUnexpectedError(
2655 "Got COMMIT while atomic sections $levels are still open"
2659 if ( $flush === 'flush' ) {
2660 if ( !$this->mTrxLevel
) {
2661 return; // nothing to do
2662 } elseif ( !$this->mTrxAutomatic
) {
2663 throw new DBUnexpectedError(
2665 "$fname: Flushing an explicit transaction, getting out of sync!"
2669 if ( !$this->mTrxLevel
) {
2670 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2671 return; // nothing to do
2672 } elseif ( $this->mTrxAutomatic
) {
2673 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2677 # Avoid fatals if close() was called
2678 $this->assertOpen();
2680 $this->runOnTransactionPreCommitCallbacks();
2681 $writeTime = $this->pendingWriteQueryDuration();
2682 $this->doCommit( $fname );
2683 if ( $this->mTrxDoneWrites
) {
2684 $this->mDoneWrites
= microtime( true );
2685 $this->getTransactionProfiler()->transactionWritingOut(
2686 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2688 $this->runOnTransactionIdleCallbacks();
2692 * Issues the COMMIT command to the database server.
2694 * @see DatabaseBase::commit()
2695 * @param string $fname
2697 protected function doCommit( $fname ) {
2698 if ( $this->mTrxLevel
) {
2699 $this->query( 'COMMIT', $fname );
2700 $this->mTrxLevel
= 0;
2704 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2705 if ( $flush !== 'flush' ) {
2706 if ( !$this->mTrxLevel
) {
2707 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2708 return; // nothing to do
2711 if ( !$this->mTrxLevel
) {
2712 return; // nothing to do
2716 # Avoid fatals if close() was called
2717 $this->assertOpen();
2719 $this->doRollback( $fname );
2720 $this->mTrxIdleCallbacks
= []; // cancel
2721 $this->mTrxPreCommitCallbacks
= []; // cancel
2722 $this->mTrxAtomicLevels
= [];
2723 if ( $this->mTrxDoneWrites
) {
2724 $this->getTransactionProfiler()->transactionWritingOut(
2725 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2730 * Issues the ROLLBACK command to the database server.
2732 * @see DatabaseBase::rollback()
2733 * @param string $fname
2735 protected function doRollback( $fname ) {
2736 if ( $this->mTrxLevel
) {
2737 $this->query( 'ROLLBACK', $fname, true );
2738 $this->mTrxLevel
= 0;
2743 * Creates a new table with structure copied from existing table
2744 * Note that unlike most database abstraction functions, this function does not
2745 * automatically append database prefix, because it works at a lower
2746 * abstraction level.
2747 * The table names passed to this function shall not be quoted (this
2748 * function calls addIdentifierQuotes when needed).
2750 * @param string $oldName Name of table whose structure should be copied
2751 * @param string $newName Name of table to be created
2752 * @param bool $temporary Whether the new table should be temporary
2753 * @param string $fname Calling function name
2754 * @throws MWException
2755 * @return bool True if operation was successful
2757 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2760 throw new MWException(
2761 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2764 function listTables( $prefix = null, $fname = __METHOD__
) {
2765 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2769 * Reset the views process cache set by listViews()
2772 final public function clearViewsCache() {
2773 $this->allViews
= null;
2777 * Lists all the VIEWs in the database
2779 * For caching purposes the list of all views should be stored in
2780 * $this->allViews. The process cache can be cleared with clearViewsCache()
2782 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2783 * @param string $fname Name of calling function
2784 * @throws MWException
2788 public function listViews( $prefix = null, $fname = __METHOD__
) {
2789 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2793 * Differentiates between a TABLE and a VIEW
2795 * @param string $name Name of the database-structure to test.
2796 * @throws MWException
2800 public function isView( $name ) {
2801 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2804 public function timestamp( $ts = 0 ) {
2805 return wfTimestamp( TS_MW
, $ts );
2808 public function timestampOrNull( $ts = null ) {
2809 if ( is_null( $ts ) ) {
2812 return $this->timestamp( $ts );
2817 * Take the result from a query, and wrap it in a ResultWrapper if
2818 * necessary. Boolean values are passed through as is, to indicate success
2819 * of write queries or failure.
2821 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2822 * resource, and it was necessary to call this function to convert it to
2823 * a wrapper. Nowadays, raw database objects are never exposed to external
2824 * callers, so this is unnecessary in external code.
2826 * @param bool|ResultWrapper|resource|object $result
2827 * @return bool|ResultWrapper
2829 protected function resultObject( $result ) {
2832 } elseif ( $result instanceof ResultWrapper
) {
2834 } elseif ( $result === true ) {
2835 // Successful write query
2838 return new ResultWrapper( $this, $result );
2842 public function ping() {
2843 # Stub. Not essential to override.
2847 public function getSessionLagStatus() {
2848 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2852 * Get the slave lag when the current transaction started
2854 * This is useful when transactions might use snapshot isolation
2855 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2856 * is this lag plus transaction duration. If they don't, it is still
2857 * safe to be pessimistic. This returns null if there is no transaction.
2859 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2862 public function getTransactionLagStatus() {
2863 return $this->mTrxLevel
2864 ?
[ 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() ]
2869 * Get a slave lag estimate for this server
2871 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2874 public function getApproximateLagStatus() {
2876 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
2877 'since' => microtime( true )
2882 * Merge the result of getSessionLagStatus() for several DBs
2883 * using the most pessimistic values to estimate the lag of
2884 * any data derived from them in combination
2886 * This is information is useful for caching modules
2888 * @see WANObjectCache::set()
2889 * @see WANObjectCache::getWithSetCallback()
2891 * @param IDatabase $db1
2892 * @param IDatabase ...
2893 * @return array Map of values:
2894 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2895 * - since: oldest UNIX timestamp of any of the DB lag estimates
2896 * - pending: whether any of the DBs have uncommitted changes
2899 public static function getCacheSetOptions( IDatabase
$db1 ) {
2900 $res = [ 'lag' => 0, 'since' => INF
, 'pending' => false ];
2901 foreach ( func_get_args() as $db ) {
2902 /** @var IDatabase $db */
2903 $status = $db->getSessionLagStatus();
2904 if ( $status['lag'] === false ) {
2905 $res['lag'] = false;
2906 } elseif ( $res['lag'] !== false ) {
2907 $res['lag'] = max( $res['lag'], $status['lag'] );
2909 $res['since'] = min( $res['since'], $status['since'] );
2910 $res['pending'] = $res['pending'] ?
: $db->writesPending();
2916 public function getLag() {
2920 function maxListLen() {
2924 public function encodeBlob( $b ) {
2928 public function decodeBlob( $b ) {
2929 if ( $b instanceof Blob
) {
2935 public function setSessionOptions( array $options ) {
2939 * Read and execute SQL commands from a file.
2941 * Returns true on success, error string or exception on failure (depending
2942 * on object's error ignore settings).
2944 * @param string $filename File name to open
2945 * @param bool|callable $lineCallback Optional function called before reading each line
2946 * @param bool|callable $resultCallback Optional function called for each MySQL result
2947 * @param bool|string $fname Calling function name or false if name should be
2948 * generated dynamically using $filename
2949 * @param bool|callable $inputCallback Optional function called for each
2950 * complete line sent
2951 * @throws Exception|MWException
2952 * @return bool|string
2954 public function sourceFile(
2955 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2957 MediaWiki\
suppressWarnings();
2958 $fp = fopen( $filename, 'r' );
2959 MediaWiki\restoreWarnings
();
2961 if ( false === $fp ) {
2962 throw new MWException( "Could not open \"{$filename}\".\n" );
2966 $fname = __METHOD__
. "( $filename )";
2970 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2971 } catch ( Exception
$e ) {
2982 * Get the full path of a patch file. Originally based on archive()
2983 * from updaters.inc. Keep in mind this always returns a patch, as
2984 * it fails back to MySQL if no DB-specific patch can be found
2986 * @param string $patch The name of the patch, like patch-something.sql
2987 * @return string Full path to patch file
2989 public function patchPath( $patch ) {
2992 $dbType = $this->getType();
2993 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2994 return "$IP/maintenance/$dbType/archives/$patch";
2996 return "$IP/maintenance/archives/$patch";
3000 public function setSchemaVars( $vars ) {
3001 $this->mSchemaVars
= $vars;
3005 * Read and execute commands from an open file handle.
3007 * Returns true on success, error string or exception on failure (depending
3008 * on object's error ignore settings).
3010 * @param resource $fp File handle
3011 * @param bool|callable $lineCallback Optional function called before reading each query
3012 * @param bool|callable $resultCallback Optional function called for each MySQL result
3013 * @param string $fname Calling function name
3014 * @param bool|callable $inputCallback Optional function called for each complete query sent
3015 * @return bool|string
3017 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3018 $fname = __METHOD__
, $inputCallback = false
3022 while ( !feof( $fp ) ) {
3023 if ( $lineCallback ) {
3024 call_user_func( $lineCallback );
3027 $line = trim( fgets( $fp ) );
3029 if ( $line == '' ) {
3033 if ( '-' == $line[0] && '-' == $line[1] ) {
3041 $done = $this->streamStatementEnd( $cmd, $line );
3045 if ( $done ||
feof( $fp ) ) {
3046 $cmd = $this->replaceVars( $cmd );
3048 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3049 $res = $this->query( $cmd, $fname );
3051 if ( $resultCallback ) {
3052 call_user_func( $resultCallback, $res, $this );
3055 if ( false === $res ) {
3056 $err = $this->lastError();
3058 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3069 * Called by sourceStream() to check if we've reached a statement end
3071 * @param string $sql SQL assembled so far
3072 * @param string $newLine New line about to be added to $sql
3073 * @return bool Whether $newLine contains end of the statement
3075 public function streamStatementEnd( &$sql, &$newLine ) {
3076 if ( $this->delimiter
) {
3078 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3079 if ( $newLine != $prev ) {
3088 * Database independent variable replacement. Replaces a set of variables
3089 * in an SQL statement with their contents as given by $this->getSchemaVars().
3091 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3093 * - '{$var}' should be used for text and is passed through the database's
3095 * - `{$var}` should be used for identifiers (e.g. table and database names).
3096 * It is passed through the database's addIdentifierQuotes method which
3097 * can be overridden if the database uses something other than backticks.
3098 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3099 * database's tableName method.
3100 * - / *i* / passes the name that follows through the database's indexName method.
3101 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3102 * its use should be avoided. In 1.24 and older, string encoding was applied.
3104 * @param string $ins SQL statement to replace variables in
3105 * @return string The new SQL statement with variables replaced
3107 protected function replaceVars( $ins ) {
3108 $vars = $this->getSchemaVars();
3109 return preg_replace_callback(
3111 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3112 \'\{\$ (\w+) }\' | # 3. addQuotes
3113 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3114 /\*\$ (\w+) \*/ # 5. leave unencoded
3116 function ( $m ) use ( $vars ) {
3117 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3118 // check for both nonexistent keys *and* the empty string.
3119 if ( isset( $m[1] ) && $m[1] !== '' ) {
3120 if ( $m[1] === 'i' ) {
3121 return $this->indexName( $m[2] );
3123 return $this->tableName( $m[2] );
3125 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3126 return $this->addQuotes( $vars[$m[3]] );
3127 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3128 return $this->addIdentifierQuotes( $vars[$m[4]] );
3129 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3130 return $vars[$m[5]];
3140 * Get schema variables. If none have been set via setSchemaVars(), then
3141 * use some defaults from the current object.
3145 protected function getSchemaVars() {
3146 if ( $this->mSchemaVars
) {
3147 return $this->mSchemaVars
;
3149 return $this->getDefaultSchemaVars();
3154 * Get schema variables to use if none have been set via setSchemaVars().
3156 * Override this in derived classes to provide variables for tables.sql
3157 * and SQL patch files.
3161 protected function getDefaultSchemaVars() {
3165 public function lockIsFree( $lockName, $method ) {
3169 public function lock( $lockName, $method, $timeout = 5 ) {
3170 $this->mNamedLocksHeld
[$lockName] = 1;
3175 public function unlock( $lockName, $method ) {
3176 unset( $this->mNamedLocksHeld
[$lockName] );
3181 public function getScopedLockAndFlush( $lockKey, $fname, $timeout ) {
3182 if ( !$this->lock( $lockKey, $fname, $timeout ) ) {
3186 $unlocker = new ScopedCallback( function () use ( $lockKey, $fname ) {
3187 $this->commit( __METHOD__
, 'flush' );
3188 $this->unlock( $lockKey, $fname );
3191 $this->commit( __METHOD__
, 'flush' );
3196 public function namedLocksEnqueue() {
3201 * Lock specific tables
3203 * @param array $read Array of tables to lock for read access
3204 * @param array $write Array of tables to lock for write access
3205 * @param string $method Name of caller
3206 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3209 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3214 * Unlock specific tables
3216 * @param string $method The caller
3219 public function unlockTables( $method ) {
3225 * @param string $tableName
3226 * @param string $fName
3227 * @return bool|ResultWrapper
3230 public function dropTable( $tableName, $fName = __METHOD__
) {
3231 if ( !$this->tableExists( $tableName, $fName ) ) {
3234 $sql = "DROP TABLE " . $this->tableName( $tableName );
3235 if ( $this->cascadingDeletes() ) {
3239 return $this->query( $sql, $fName );
3243 * Get search engine class. All subclasses of this need to implement this
3244 * if they wish to use searching.
3248 public function getSearchEngine() {
3249 return 'SearchEngineDummy';
3252 public function getInfinity() {
3256 public function encodeExpiry( $expiry ) {
3257 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3258 ?
$this->getInfinity()
3259 : $this->timestamp( $expiry );
3262 public function decodeExpiry( $expiry, $format = TS_MW
) {
3263 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3265 : wfTimestamp( $format, $expiry );
3268 public function setBigSelects( $value = true ) {
3272 public function isReadOnly() {
3273 return ( $this->getReadOnlyReason() !== false );
3277 * @return string|bool Reason this DB is read-only or false if it is not
3279 protected function getReadOnlyReason() {
3280 $reason = $this->getLBInfo( 'readOnlyReason' );
3282 return is_string( $reason ) ?
$reason : false;
3289 public function __toString() {
3290 return (string)$this->mConn
;
3294 * Run a few simple sanity checks
3296 public function __destruct() {
3297 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3298 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3300 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3302 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3303 $callers[] = $callbackInfo[1];
3305 $callers = implode( ', ', $callers );
3306 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3314 abstract class Database
extends DatabaseBase
{
3315 // B/C until nothing type hints for DatabaseBase
3316 // @TODO: finish renaming DatabaseBase => Database