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 = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
60 protected $mTablePrefix;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
68 protected $mSessionVars = array();
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 = array();
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
145 * Track the seconds spent in write queries for the current transaction
149 private $mTrxWriteDuration = 0.0;
151 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
152 private $lazyMasterHandle;
156 * @var resource File handle for upgrade
158 protected $fileHandle = null;
162 * @var string[] Process cache of VIEWs names in the database
164 protected $allViews = null;
166 /** @var TransactionProfiler */
167 protected $trxProfiler;
169 public function getServerInfo() {
170 return $this->getServerVersion();
174 * @return string Command delimiter used by this database engine
176 public function getDelimiter() {
177 return $this->delimiter
;
181 * Boolean, controls output of large amounts of debug information.
182 * @param bool|null $debug
183 * - true to enable debugging
184 * - false to disable debugging
185 * - omitted or null to do nothing
187 * @return bool|null Previous value of the flag
189 public function debug( $debug = null ) {
190 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
193 public function bufferResults( $buffer = null ) {
194 if ( is_null( $buffer ) ) {
195 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
197 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
202 * Turns on (false) or off (true) the automatic generation and sending
203 * of a "we're sorry, but there has been a database error" page on
204 * database errors. Default is on (false). When turned off, the
205 * code should use lastErrno() and lastError() to handle the
206 * situation as appropriate.
208 * Do not use this function outside of the Database classes.
210 * @param null|bool $ignoreErrors
211 * @return bool The previous value of the flag.
213 protected function ignoreErrors( $ignoreErrors = null ) {
214 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
217 public function trxLevel() {
218 return $this->mTrxLevel
;
221 public function trxTimestamp() {
222 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
225 public function tablePrefix( $prefix = null ) {
226 return wfSetVar( $this->mTablePrefix
, $prefix );
229 public function dbSchema( $schema = null ) {
230 return wfSetVar( $this->mSchema
, $schema );
234 * Set the filehandle to copy write statements to.
236 * @param resource $fh File handle
238 public function setFileHandle( $fh ) {
239 $this->fileHandle
= $fh;
242 public function getLBInfo( $name = null ) {
243 if ( is_null( $name ) ) {
244 return $this->mLBInfo
;
246 if ( array_key_exists( $name, $this->mLBInfo
) ) {
247 return $this->mLBInfo
[$name];
254 public function setLBInfo( $name, $value = null ) {
255 if ( is_null( $value ) ) {
256 $this->mLBInfo
= $name;
258 $this->mLBInfo
[$name] = $value;
263 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
265 * @param IDatabase $conn
268 public function setLazyMasterHandle( IDatabase
$conn ) {
269 $this->lazyMasterHandle
= $conn;
273 * @return IDatabase|null
274 * @see setLazyMasterHandle()
277 public function getLazyMasterHandle() {
278 return $this->lazyMasterHandle
;
282 * @return TransactionProfiler
284 protected function getTransactionProfiler() {
285 return $this->trxProfiler
287 : Profiler
::instance()->getTransactionProfiler();
291 * Returns true if this database supports (and uses) cascading deletes
295 public function cascadingDeletes() {
300 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
304 public function cleanupTriggers() {
309 * Returns true if this database is strict about what can be put into an IP field.
310 * Specifically, it uses a NULL value instead of an empty string.
314 public function strictIPs() {
319 * Returns true if this database uses timestamps rather than integers
323 public function realTimestamps() {
327 public function implicitGroupby() {
331 public function implicitOrderby() {
336 * Returns true if this database can do a native search on IP columns
337 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
341 public function searchableIPs() {
346 * Returns true if this database can use functional indexes
350 public function functionalIndexes() {
354 public function lastQuery() {
355 return $this->mLastQuery
;
358 public function doneWrites() {
359 return (bool)$this->mDoneWrites
;
362 public function lastDoneWrites() {
363 return $this->mDoneWrites ?
: false;
366 public function writesPending() {
367 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
370 public function writesOrCallbacksPending() {
371 return $this->mTrxLevel
&& (
372 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
376 public function pendingWriteQueryDuration() {
377 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
380 public function isOpen() {
381 return $this->mOpened
;
384 public function setFlag( $flag ) {
385 $this->mFlags |
= $flag;
388 public function clearFlag( $flag ) {
389 $this->mFlags
&= ~
$flag;
392 public function getFlag( $flag ) {
393 return !!( $this->mFlags
& $flag );
396 public function getProperty( $name ) {
400 public function getWikiID() {
401 if ( $this->mTablePrefix
) {
402 return "{$this->mDBname}-{$this->mTablePrefix}";
404 return $this->mDBname
;
409 * Return a path to the DBMS-specific SQL file if it exists,
410 * otherwise default SQL file
412 * @param string $filename
415 private function getSqlFilePath( $filename ) {
417 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
418 if ( file_exists( $dbmsSpecificFilePath ) ) {
419 return $dbmsSpecificFilePath;
421 return "$IP/maintenance/$filename";
426 * Return a path to the DBMS-specific schema file,
427 * otherwise default to tables.sql
431 public function getSchemaPath() {
432 return $this->getSqlFilePath( 'tables.sql' );
436 * Return a path to the DBMS-specific update key file,
437 * otherwise default to update-keys.sql
441 public function getUpdateKeysPath() {
442 return $this->getSqlFilePath( 'update-keys.sql' );
446 * Get information about an index into an object
447 * @param string $table Table name
448 * @param string $index Index name
449 * @param string $fname Calling function name
450 * @return mixed Database-specific index description class or false if the index does not exist
452 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
455 * Wrapper for addslashes()
457 * @param string $s String to be slashed.
458 * @return string Slashed string.
460 abstract function strencode( $s );
465 * FIXME: It is possible to construct a Database object with no associated
466 * connection object, by specifying no parameters to __construct(). This
467 * feature is deprecated and should be removed.
469 * DatabaseBase subclasses should not be constructed directly in external
470 * code. DatabaseBase::factory() should be used instead.
472 * @param array $params Parameters passed from DatabaseBase::factory()
474 function __construct( array $params ) {
475 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
477 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
479 $server = $params['host'];
480 $user = $params['user'];
481 $password = $params['password'];
482 $dbName = $params['dbname'];
483 $flags = $params['flags'];
484 $tablePrefix = $params['tablePrefix'];
485 $schema = $params['schema'];
486 $foreign = $params['foreign'];
488 $this->mFlags
= $flags;
489 if ( $this->mFlags
& DBO_DEFAULT
) {
490 if ( $wgCommandLineMode ) {
491 $this->mFlags
&= ~DBO_TRX
;
493 $this->mFlags |
= DBO_TRX
;
497 $this->mSessionVars
= $params['variables'];
499 /** Get the default table prefix*/
500 if ( $tablePrefix === 'get from global' ) {
501 $this->mTablePrefix
= $wgDBprefix;
503 $this->mTablePrefix
= $tablePrefix;
506 /** Get the database schema*/
507 if ( $schema === 'get from global' ) {
508 $this->mSchema
= $wgDBmwschema;
510 $this->mSchema
= $schema;
513 $this->mForeign
= $foreign;
515 if ( isset( $params['trxProfiler'] ) ) {
516 $this->trxProfiler
= $params['trxProfiler']; // override
520 $this->open( $server, $user, $password, $dbName );
525 * Called by serialize. Throw an exception when DB connection is serialized.
526 * This causes problems on some database engines because the connection is
527 * not restored on unserialize.
529 public function __sleep() {
530 throw new MWException( 'Database serialization may cause problems, since ' .
531 'the connection is not restored on wakeup.' );
535 * Given a DB type, construct the name of the appropriate child class of
536 * DatabaseBase. This is designed to replace all of the manual stuff like:
537 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
538 * as well as validate against the canonical list of DB types we have
540 * This factory function is mostly useful for when you need to connect to a
541 * database other than the MediaWiki default (such as for external auth,
542 * an extension, et cetera). Do not use this to connect to the MediaWiki
543 * database. Example uses in core:
544 * @see LoadBalancer::reallyOpenConnection()
545 * @see ForeignDBRepo::getMasterDB()
546 * @see WebInstallerDBConnect::execute()
550 * @param string $dbType A possible DB type
551 * @param array $p An array of options to pass to the constructor.
552 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
553 * @throws MWException If the database driver or extension cannot be found
554 * @return DatabaseBase|null DatabaseBase subclass or null
556 final public static function factory( $dbType, $p = array() ) {
557 $canonicalDBTypes = array(
558 'mysql' => array( 'mysqli', 'mysql' ),
559 'postgres' => array(),
566 $dbType = strtolower( $dbType );
567 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
568 $possibleDrivers = $canonicalDBTypes[$dbType];
569 if ( !empty( $p['driver'] ) ) {
570 if ( in_array( $p['driver'], $possibleDrivers ) ) {
571 $driver = $p['driver'];
573 throw new MWException( __METHOD__
.
574 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
577 foreach ( $possibleDrivers as $posDriver ) {
578 if ( extension_loaded( $posDriver ) ) {
579 $driver = $posDriver;
587 if ( $driver === false ) {
588 throw new MWException( __METHOD__
.
589 " no viable database extension found for type '$dbType'" );
592 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
593 // and everything else doesn't use a schema (e.g. null)
594 // Although postgres and oracle support schemas, we don't use them (yet)
595 // to maintain backwards compatibility
596 $defaultSchemas = array(
597 'mssql' => 'get from global',
600 $class = 'Database' . ucfirst( $driver );
601 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
602 // Resolve some defaults for b/c
603 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
604 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
605 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
606 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
607 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
608 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
609 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
610 if ( !isset( $p['schema'] ) ) {
611 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
613 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
615 return new $class( $p );
621 protected function installErrorHandler() {
622 $this->mPHPError
= false;
623 $this->htmlErrors
= ini_set( 'html_errors', '0' );
624 set_error_handler( array( $this, 'connectionErrorHandler' ) );
628 * @return bool|string
630 protected function restoreErrorHandler() {
631 restore_error_handler();
632 if ( $this->htmlErrors
!== false ) {
633 ini_set( 'html_errors', $this->htmlErrors
);
635 if ( $this->mPHPError
) {
636 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
637 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
647 * @param string $errstr
649 public function connectionErrorHandler( $errno, $errstr ) {
650 $this->mPHPError
= $errstr;
654 * Create a log context to pass to wfLogDBError or other logging functions.
656 * @param array $extras Additional data to add to context
659 protected function getLogContext( array $extras = array() ) {
662 'db_server' => $this->mServer
,
663 'db_name' => $this->mDBname
,
664 'db_user' => $this->mUser
,
670 public function close() {
671 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
672 throw new MWException( "Transaction idle callbacks still pending." );
674 if ( $this->mConn
) {
675 if ( $this->trxLevel() ) {
676 if ( !$this->mTrxAutomatic
) {
677 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
678 " performing implicit commit before closing connection!" );
681 $this->commit( __METHOD__
, 'flush' );
684 $closed = $this->closeConnection();
685 $this->mConn
= false;
689 $this->mOpened
= false;
695 * Make sure isOpen() returns true as a sanity check
697 * @throws DBUnexpectedError
699 protected function assertOpen() {
700 if ( !$this->isOpen() ) {
701 throw new DBUnexpectedError( $this, "DB connection was already closed." );
706 * Closes underlying database connection
708 * @return bool Whether connection was closed successfully
710 abstract protected function closeConnection();
712 function reportConnectionError( $error = 'Unknown error' ) {
713 $myError = $this->lastError();
719 throw new DBConnectionError( $this, $error );
723 * The DBMS-dependent part of query()
725 * @param string $sql SQL query.
726 * @return ResultWrapper|bool Result object to feed to fetchObject,
727 * fetchRow, ...; or false on failure
729 abstract protected function doQuery( $sql );
732 * Determine whether a query writes to the DB.
733 * Should return true if unsure.
738 protected function isWriteQuery( $sql ) {
739 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
743 * Determine whether a SQL statement is sensitive to isolation level.
744 * A SQL statement is considered transactable if its result could vary
745 * depending on the transaction isolation level. Operational commands
746 * such as 'SET' and 'SHOW' are not considered to be transactable.
751 protected function isTransactableQuery( $sql ) {
752 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
753 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
756 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
759 $this->mLastQuery
= $sql;
761 $isWriteQuery = $this->isWriteQuery( $sql );
762 if ( $isWriteQuery ) {
763 $reason = $this->getReadOnlyReason();
764 if ( $reason !== false ) {
765 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
767 # Set a flag indicating that writes have been done
768 $this->mDoneWrites
= microtime( true );
771 # Add a comment for easy SHOW PROCESSLIST interpretation
772 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
773 $userName = $wgUser->getName();
774 if ( mb_strlen( $userName ) > 15 ) {
775 $userName = mb_substr( $userName, 0, 15 ) . '...';
777 $userName = str_replace( '/', '', $userName );
782 // Add trace comment to the begin of the sql string, right after the operator.
783 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
784 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
786 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
787 $this->begin( __METHOD__
. " ($fname)" );
788 $this->mTrxAutomatic
= true;
791 # Keep track of whether the transaction has write queries pending
792 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
793 $this->mTrxDoneWrites
= true;
794 $this->getTransactionProfiler()->transactionWritingIn(
795 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
798 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
799 # generalizeSQL will probably cut down the query to reasonable
800 # logging size most of the time. The substr is really just a sanity check.
802 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
803 $totalProf = 'DatabaseBase::query-master';
805 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
806 $totalProf = 'DatabaseBase::query';
808 # Include query transaction state
809 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
811 $profiler = Profiler
::instance();
812 if ( !$profiler instanceof ProfilerStub
) {
813 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
814 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
817 if ( $this->debug() ) {
818 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
821 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
823 # Avoid fatals if close() was called
826 # Do the query and handle errors
827 $startTime = microtime( true );
828 $ret = $this->doQuery( $commentedSql );
829 $queryRuntime = microtime( true ) - $startTime;
830 # Log the query time and feed it into the DB trx profiler
831 $this->getTransactionProfiler()->recordQueryCompletion(
832 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
834 MWDebug
::queryTime( $queryId );
836 # Try reconnecting if the connection was lost
837 if ( false === $ret && $this->wasErrorReissuable() ) {
838 # Transaction is gone, like it or not
839 $hadTrx = $this->mTrxLevel
; // possible lost transaction
840 $this->mTrxLevel
= 0;
841 $this->mTrxIdleCallbacks
= array(); // bug 65263
842 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
843 wfDebug( "Connection lost, reconnecting...\n" );
844 # Stash the last error values since ping() might clear them
845 $lastError = $this->lastError();
846 $lastErrno = $this->lastErrno();
847 if ( $this->ping() ) {
848 wfDebug( "Reconnected\n" );
849 $server = $this->getServer();
850 $msg = __METHOD__
. ": lost connection to $server; reconnected";
851 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
854 # Leave $ret as false and let an error be reported.
855 # Callers may catch the exception and continue to use the DB.
856 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
858 # Should be safe to silently retry (no trx and thus no callbacks)
859 $startTime = microtime( true );
860 $ret = $this->doQuery( $commentedSql );
861 $queryRuntime = microtime( true ) - $startTime;
862 # Log the query time and feed it into the DB trx profiler
863 $this->getTransactionProfiler()->recordQueryCompletion(
864 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
867 wfDebug( "Failed\n" );
871 if ( false === $ret ) {
872 $this->reportQueryError(
873 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
876 $res = $this->resultObject( $ret );
878 // Destroy profile sections in the opposite order to their creation
879 ScopedCallback
::consume( $queryProfSection );
880 ScopedCallback
::consume( $totalProfSection );
882 if ( $isWriteQuery && $this->mTrxLevel
) {
883 $this->mTrxWriteDuration +
= $queryRuntime;
889 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
890 if ( $this->ignoreErrors() ||
$tempIgnore ) {
891 wfDebug( "SQL ERROR (ignored): $error\n" );
893 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
895 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
896 $this->getLogContext( array(
897 'method' => __METHOD__
,
900 'sql1line' => $sql1line,
904 wfDebug( "SQL ERROR: " . $error . "\n" );
905 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
910 * Intended to be compatible with the PEAR::DB wrapper functions.
911 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
913 * ? = scalar value, quoted as necessary
914 * ! = raw SQL bit (a function for instance)
915 * & = filename; reads the file and inserts as a blob
916 * (we don't use this though...)
919 * @param string $func
923 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
924 /* MySQL doesn't support prepared statements (yet), so just
925 * pack up the query for reference. We'll manually replace
928 return array( 'query' => $sql, 'func' => $func );
932 * Free a prepared query, generated by prepare().
933 * @param string $prepared
935 protected function freePrepared( $prepared ) {
936 /* No-op by default */
940 * Execute a prepared query with the various arguments
941 * @param string $prepared The prepared sql
942 * @param mixed $args Either an array here, or put scalars as varargs
944 * @return ResultWrapper
946 public function execute( $prepared, $args = null ) {
947 if ( !is_array( $args ) ) {
949 $args = func_get_args();
950 array_shift( $args );
953 $sql = $this->fillPrepared( $prepared['query'], $args );
955 return $this->query( $sql, $prepared['func'] );
959 * For faking prepared SQL statements on DBs that don't support it directly.
961 * @param string $preparedQuery A 'preparable' SQL statement
962 * @param array $args Array of Arguments to fill it with
963 * @return string Executable SQL
965 public function fillPrepared( $preparedQuery, $args ) {
967 $this->preparedArgs
=& $args;
969 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
970 array( &$this, 'fillPreparedArg' ), $preparedQuery );
974 * preg_callback func for fillPrepared()
975 * The arguments should be in $this->preparedArgs and must not be touched
976 * while we're doing this.
978 * @param array $matches
979 * @throws DBUnexpectedError
982 protected function fillPreparedArg( $matches ) {
983 switch ( $matches[1] ) {
992 list( /* $n */, $arg ) = each( $this->preparedArgs
);
994 switch ( $matches[1] ) {
996 return $this->addQuotes( $arg );
1000 # return $this->addQuotes( file_get_contents( $arg ) );
1001 throw new DBUnexpectedError(
1003 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1006 throw new DBUnexpectedError(
1008 'Received invalid match. This should never happen!'
1013 public function freeResult( $res ) {
1016 public function selectField(
1017 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1019 if ( $var === '*' ) { // sanity
1020 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1023 if ( !is_array( $options ) ) {
1024 $options = array( $options );
1027 $options['LIMIT'] = 1;
1029 $res = $this->select( $table, $var, $cond, $fname, $options );
1030 if ( $res === false ||
!$this->numRows( $res ) ) {
1034 $row = $this->fetchRow( $res );
1036 if ( $row !== false ) {
1037 return reset( $row );
1043 public function selectFieldValues(
1044 $table, $var, $cond = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1046 if ( $var === '*' ) { // sanity
1047 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1050 if ( !is_array( $options ) ) {
1051 $options = array( $options );
1054 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1055 if ( $res === false ) {
1060 foreach ( $res as $row ) {
1061 $values[] = $row->$var;
1068 * Returns an optional USE INDEX clause to go after the table, and a
1069 * string to go at the end of the query.
1071 * @param array $options Associative array of options to be turned into
1072 * an SQL query, valid keys are listed in the function.
1074 * @see DatabaseBase::select()
1076 public function makeSelectOptions( $options ) {
1077 $preLimitTail = $postLimitTail = '';
1080 $noKeyOptions = array();
1082 foreach ( $options as $key => $option ) {
1083 if ( is_numeric( $key ) ) {
1084 $noKeyOptions[$option] = true;
1088 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1090 $preLimitTail .= $this->makeOrderBy( $options );
1092 // if (isset($options['LIMIT'])) {
1093 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1094 // isset($options['OFFSET']) ? $options['OFFSET']
1098 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1099 $postLimitTail .= ' FOR UPDATE';
1102 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1103 $postLimitTail .= ' LOCK IN SHARE MODE';
1106 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1107 $startOpts .= 'DISTINCT';
1110 # Various MySQL extensions
1111 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1112 $startOpts .= ' /*! STRAIGHT_JOIN */';
1115 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1116 $startOpts .= ' HIGH_PRIORITY';
1119 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1120 $startOpts .= ' SQL_BIG_RESULT';
1123 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1124 $startOpts .= ' SQL_BUFFER_RESULT';
1127 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1128 $startOpts .= ' SQL_SMALL_RESULT';
1131 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1132 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1135 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1136 $startOpts .= ' SQL_CACHE';
1139 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1140 $startOpts .= ' SQL_NO_CACHE';
1143 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1144 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1149 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1153 * Returns an optional GROUP BY with an optional HAVING
1155 * @param array $options Associative array of options
1157 * @see DatabaseBase::select()
1160 public function makeGroupByWithHaving( $options ) {
1162 if ( isset( $options['GROUP BY'] ) ) {
1163 $gb = is_array( $options['GROUP BY'] )
1164 ?
implode( ',', $options['GROUP BY'] )
1165 : $options['GROUP BY'];
1166 $sql .= ' GROUP BY ' . $gb;
1168 if ( isset( $options['HAVING'] ) ) {
1169 $having = is_array( $options['HAVING'] )
1170 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1171 : $options['HAVING'];
1172 $sql .= ' HAVING ' . $having;
1179 * Returns an optional ORDER BY
1181 * @param array $options Associative array of options
1183 * @see DatabaseBase::select()
1186 public function makeOrderBy( $options ) {
1187 if ( isset( $options['ORDER BY'] ) ) {
1188 $ob = is_array( $options['ORDER BY'] )
1189 ?
implode( ',', $options['ORDER BY'] )
1190 : $options['ORDER BY'];
1192 return ' ORDER BY ' . $ob;
1198 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1199 $options = array(), $join_conds = array() ) {
1200 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1202 return $this->query( $sql, $fname );
1205 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1206 $options = array(), $join_conds = array()
1208 if ( is_array( $vars ) ) {
1209 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1212 $options = (array)$options;
1213 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1214 ?
$options['USE INDEX']
1217 if ( is_array( $table ) ) {
1219 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1220 } elseif ( $table != '' ) {
1221 if ( $table[0] == ' ' ) {
1222 $from = ' FROM ' . $table;
1225 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1231 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1232 $this->makeSelectOptions( $options );
1234 if ( !empty( $conds ) ) {
1235 if ( is_array( $conds ) ) {
1236 $conds = $this->makeList( $conds, LIST_AND
);
1238 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1240 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1243 if ( isset( $options['LIMIT'] ) ) {
1244 $sql = $this->limitResult( $sql, $options['LIMIT'],
1245 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1247 $sql = "$sql $postLimitTail";
1249 if ( isset( $options['EXPLAIN'] ) ) {
1250 $sql = 'EXPLAIN ' . $sql;
1256 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1257 $options = array(), $join_conds = array()
1259 $options = (array)$options;
1260 $options['LIMIT'] = 1;
1261 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1263 if ( $res === false ) {
1267 if ( !$this->numRows( $res ) ) {
1271 $obj = $this->fetchObject( $res );
1276 public function estimateRowCount(
1277 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1280 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1283 $row = $this->fetchRow( $res );
1284 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1290 public function selectRowCount(
1291 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1294 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1295 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1298 $row = $this->fetchRow( $res );
1299 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1306 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1307 * It's only slightly flawed. Don't use for anything important.
1309 * @param string $sql A SQL Query
1313 protected static function generalizeSQL( $sql ) {
1314 # This does the same as the regexp below would do, but in such a way
1315 # as to avoid crashing php on some large strings.
1316 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1318 $sql = str_replace( "\\\\", '', $sql );
1319 $sql = str_replace( "\\'", '', $sql );
1320 $sql = str_replace( "\\\"", '', $sql );
1321 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1322 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1324 # All newlines, tabs, etc replaced by single space
1325 $sql = preg_replace( '/\s+/', ' ', $sql );
1328 # except the ones surrounded by characters, e.g. l10n
1329 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1330 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1335 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1336 $info = $this->fieldInfo( $table, $field );
1341 public function indexExists( $table, $index, $fname = __METHOD__
) {
1342 if ( !$this->tableExists( $table ) ) {
1346 $info = $this->indexInfo( $table, $index, $fname );
1347 if ( is_null( $info ) ) {
1350 return $info !== false;
1354 public function tableExists( $table, $fname = __METHOD__
) {
1355 $table = $this->tableName( $table );
1356 $old = $this->ignoreErrors( true );
1357 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1358 $this->ignoreErrors( $old );
1363 public function indexUnique( $table, $index ) {
1364 $indexInfo = $this->indexInfo( $table, $index );
1366 if ( !$indexInfo ) {
1370 return !$indexInfo[0]->Non_unique
;
1374 * Helper for DatabaseBase::insert().
1376 * @param array $options
1379 protected function makeInsertOptions( $options ) {
1380 return implode( ' ', $options );
1383 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1384 # No rows to insert, easy just return now
1385 if ( !count( $a ) ) {
1389 $table = $this->tableName( $table );
1391 if ( !is_array( $options ) ) {
1392 $options = array( $options );
1396 if ( isset( $options['fileHandle'] ) ) {
1397 $fh = $options['fileHandle'];
1399 $options = $this->makeInsertOptions( $options );
1401 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1403 $keys = array_keys( $a[0] );
1406 $keys = array_keys( $a );
1409 $sql = 'INSERT ' . $options .
1410 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1414 foreach ( $a as $row ) {
1420 $sql .= '(' . $this->makeList( $row ) . ')';
1423 $sql .= '(' . $this->makeList( $a ) . ')';
1426 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1428 } elseif ( $fh !== null ) {
1432 return (bool)$this->query( $sql, $fname );
1436 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1438 * @param array $options
1441 protected function makeUpdateOptionsArray( $options ) {
1442 if ( !is_array( $options ) ) {
1443 $options = array( $options );
1448 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1449 $opts[] = $this->lowPriorityOption();
1452 if ( in_array( 'IGNORE', $options ) ) {
1460 * Make UPDATE options for the DatabaseBase::update function
1462 * @param array $options The options passed to DatabaseBase::update
1465 protected function makeUpdateOptions( $options ) {
1466 $opts = $this->makeUpdateOptionsArray( $options );
1468 return implode( ' ', $opts );
1471 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1472 $table = $this->tableName( $table );
1473 $opts = $this->makeUpdateOptions( $options );
1474 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1476 if ( $conds !== array() && $conds !== '*' ) {
1477 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1480 return $this->query( $sql, $fname );
1483 public function makeList( $a, $mode = LIST_COMMA
) {
1484 if ( !is_array( $a ) ) {
1485 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1491 foreach ( $a as $field => $value ) {
1493 if ( $mode == LIST_AND
) {
1495 } elseif ( $mode == LIST_OR
) {
1504 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1505 $list .= "($value)";
1506 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1508 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1509 // Remove null from array to be handled separately if found
1510 $includeNull = false;
1511 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1512 $includeNull = true;
1513 unset( $value[$nullKey] );
1515 if ( count( $value ) == 0 && !$includeNull ) {
1516 throw new MWException( __METHOD__
. ": empty input for field $field" );
1517 } elseif ( count( $value ) == 0 ) {
1518 // only check if $field is null
1519 $list .= "$field IS NULL";
1521 // IN clause contains at least one valid element
1522 if ( $includeNull ) {
1523 // Group subconditions to ensure correct precedence
1526 if ( count( $value ) == 1 ) {
1527 // Special-case single values, as IN isn't terribly efficient
1528 // Don't necessarily assume the single key is 0; we don't
1529 // enforce linear numeric ordering on other arrays here.
1530 $value = array_values( $value );
1531 $list .= $field . " = " . $this->addQuotes( $value[0] );
1533 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1535 // if null present in array, append IS NULL
1536 if ( $includeNull ) {
1537 $list .= " OR $field IS NULL)";
1540 } elseif ( $value === null ) {
1541 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1542 $list .= "$field IS ";
1543 } elseif ( $mode == LIST_SET
) {
1544 $list .= "$field = ";
1548 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1549 $list .= "$field = ";
1551 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1558 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1561 foreach ( $data as $base => $sub ) {
1562 if ( count( $sub ) ) {
1563 $conds[] = $this->makeList(
1564 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1570 return $this->makeList( $conds, LIST_OR
);
1572 // Nothing to search for...
1578 * Return aggregated value alias
1580 * @param array $valuedata
1581 * @param string $valuename
1585 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1589 public function bitNot( $field ) {
1593 public function bitAnd( $fieldLeft, $fieldRight ) {
1594 return "($fieldLeft & $fieldRight)";
1597 public function bitOr( $fieldLeft, $fieldRight ) {
1598 return "($fieldLeft | $fieldRight)";
1601 public function buildConcat( $stringList ) {
1602 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1605 public function buildGroupConcatField(
1606 $delim, $table, $field, $conds = '', $join_conds = array()
1608 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1610 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1613 public function selectDB( $db ) {
1614 # Stub. Shouldn't cause serious problems if it's not overridden, but
1615 # if your database engine supports a concept similar to MySQL's
1616 # databases you may as well.
1617 $this->mDBname
= $db;
1622 public function getDBname() {
1623 return $this->mDBname
;
1626 public function getServer() {
1627 return $this->mServer
;
1631 * Format a table name ready for use in constructing an SQL query
1633 * This does two important things: it quotes the table names to clean them up,
1634 * and it adds a table prefix if only given a table name with no quotes.
1636 * All functions of this object which require a table name call this function
1637 * themselves. Pass the canonical name to such functions. This is only needed
1638 * when calling query() directly.
1640 * @param string $name Database table name
1641 * @param string $format One of:
1642 * quoted - Automatically pass the table name through addIdentifierQuotes()
1643 * so that it can be used in a query.
1644 * raw - Do not add identifier quotes to the table name
1645 * @return string Full database name
1647 public function tableName( $name, $format = 'quoted' ) {
1648 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1649 # Skip the entire process when we have a string quoted on both ends.
1650 # Note that we check the end so that we will still quote any use of
1651 # use of `database`.table. But won't break things if someone wants
1652 # to query a database table with a dot in the name.
1653 if ( $this->isQuotedIdentifier( $name ) ) {
1657 # Lets test for any bits of text that should never show up in a table
1658 # name. Basically anything like JOIN or ON which are actually part of
1659 # SQL queries, but may end up inside of the table value to combine
1660 # sql. Such as how the API is doing.
1661 # Note that we use a whitespace test rather than a \b test to avoid
1662 # any remote case where a word like on may be inside of a table name
1663 # surrounded by symbols which may be considered word breaks.
1664 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1668 # Split database and table into proper variables.
1669 # We reverse the explode so that database.table and table both output
1670 # the correct table.
1671 $dbDetails = explode( '.', $name, 3 );
1672 if ( count( $dbDetails ) == 3 ) {
1673 list( $database, $schema, $table ) = $dbDetails;
1674 # We don't want any prefix added in this case
1676 } elseif ( count( $dbDetails ) == 2 ) {
1677 list( $database, $table ) = $dbDetails;
1678 # We don't want any prefix added in this case
1679 # In dbs that support it, $database may actually be the schema
1680 # but that doesn't affect any of the functionality here
1684 list( $table ) = $dbDetails;
1685 if ( $wgSharedDB !== null # We have a shared database
1686 && $this->mForeign
== false # We're not working on a foreign database
1687 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1688 && in_array( $table, $wgSharedTables ) # A shared table is selected
1690 $database = $wgSharedDB;
1691 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1692 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1695 $schema = $this->mSchema
; # Default schema
1696 $prefix = $this->mTablePrefix
; # Default prefix
1700 # Quote $table and apply the prefix if not quoted.
1701 # $tableName might be empty if this is called from Database::replaceVars()
1702 $tableName = "{$prefix}{$table}";
1703 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1704 $tableName = $this->addIdentifierQuotes( $tableName );
1707 # Quote $schema and merge it with the table name if needed
1708 if ( strlen( $schema ) ) {
1709 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1710 $schema = $this->addIdentifierQuotes( $schema );
1712 $tableName = $schema . '.' . $tableName;
1715 # Quote $database and merge it with the table name if needed
1716 if ( $database !== null ) {
1717 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1718 $database = $this->addIdentifierQuotes( $database );
1720 $tableName = $database . '.' . $tableName;
1727 * Fetch a number of table names into an array
1728 * This is handy when you need to construct SQL for joins
1731 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1732 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1733 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1737 public function tableNames() {
1738 $inArray = func_get_args();
1741 foreach ( $inArray as $name ) {
1742 $retVal[$name] = $this->tableName( $name );
1749 * Fetch a number of table names into an zero-indexed numerical array
1750 * This is handy when you need to construct SQL for joins
1753 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1754 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1755 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1759 public function tableNamesN() {
1760 $inArray = func_get_args();
1763 foreach ( $inArray as $name ) {
1764 $retVal[] = $this->tableName( $name );
1771 * Get an aliased table name
1772 * e.g. tableName AS newTableName
1774 * @param string $name Table name, see tableName()
1775 * @param string|bool $alias Alias (optional)
1776 * @return string SQL name for aliased table. Will not alias a table to its own name
1778 public function tableNameWithAlias( $name, $alias = false ) {
1779 if ( !$alias ||
$alias == $name ) {
1780 return $this->tableName( $name );
1782 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1787 * Gets an array of aliased table names
1789 * @param array $tables Array( [alias] => table )
1790 * @return string[] See tableNameWithAlias()
1792 public function tableNamesWithAlias( $tables ) {
1794 foreach ( $tables as $alias => $table ) {
1795 if ( is_numeric( $alias ) ) {
1798 $retval[] = $this->tableNameWithAlias( $table, $alias );
1805 * Get an aliased field name
1806 * e.g. fieldName AS newFieldName
1808 * @param string $name Field name
1809 * @param string|bool $alias Alias (optional)
1810 * @return string SQL name for aliased field. Will not alias a field to its own name
1812 public function fieldNameWithAlias( $name, $alias = false ) {
1813 if ( !$alias ||
(string)$alias === (string)$name ) {
1816 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1821 * Gets an array of aliased field names
1823 * @param array $fields Array( [alias] => field )
1824 * @return string[] See fieldNameWithAlias()
1826 public function fieldNamesWithAlias( $fields ) {
1828 foreach ( $fields as $alias => $field ) {
1829 if ( is_numeric( $alias ) ) {
1832 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1839 * Get the aliased table name clause for a FROM clause
1840 * which might have a JOIN and/or USE INDEX clause
1842 * @param array $tables ( [alias] => table )
1843 * @param array $use_index Same as for select()
1844 * @param array $join_conds Same as for select()
1847 protected function tableNamesWithUseIndexOrJOIN(
1848 $tables, $use_index = array(), $join_conds = array()
1852 $use_index = (array)$use_index;
1853 $join_conds = (array)$join_conds;
1855 foreach ( $tables as $alias => $table ) {
1856 if ( !is_string( $alias ) ) {
1857 // No alias? Set it equal to the table name
1860 // Is there a JOIN clause for this table?
1861 if ( isset( $join_conds[$alias] ) ) {
1862 list( $joinType, $conds ) = $join_conds[$alias];
1863 $tableClause = $joinType;
1864 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1865 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1866 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1868 $tableClause .= ' ' . $use;
1871 $on = $this->makeList( (array)$conds, LIST_AND
);
1873 $tableClause .= ' ON (' . $on . ')';
1876 $retJOIN[] = $tableClause;
1877 } elseif ( isset( $use_index[$alias] ) ) {
1878 // Is there an INDEX clause for this table?
1879 $tableClause = $this->tableNameWithAlias( $table, $alias );
1880 $tableClause .= ' ' . $this->useIndexClause(
1881 implode( ',', (array)$use_index[$alias] )
1884 $ret[] = $tableClause;
1886 $tableClause = $this->tableNameWithAlias( $table, $alias );
1888 $ret[] = $tableClause;
1892 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1893 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1894 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1896 // Compile our final table clause
1897 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1901 * Get the name of an index in a given table.
1903 * @protected Don't use outside of DatabaseBase and childs
1904 * @param string $index
1907 public function indexName( $index ) {
1908 // @FIXME: Make this protected once we move away from PHP 5.3
1909 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
1911 // Backwards-compatibility hack
1913 'ar_usertext_timestamp' => 'usertext_timestamp',
1914 'un_user_id' => 'user_id',
1915 'un_user_ip' => 'user_ip',
1918 if ( isset( $renamed[$index] ) ) {
1919 return $renamed[$index];
1925 public function addQuotes( $s ) {
1926 if ( $s instanceof Blob
) {
1929 if ( $s === null ) {
1932 # This will also quote numeric values. This should be harmless,
1933 # and protects against weird problems that occur when they really
1934 # _are_ strings such as article titles and string->number->string
1935 # conversion is not 1:1.
1936 return "'" . $this->strencode( $s ) . "'";
1941 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1942 * MySQL uses `backticks` while basically everything else uses double quotes.
1943 * Since MySQL is the odd one out here the double quotes are our generic
1944 * and we implement backticks in DatabaseMysql.
1949 public function addIdentifierQuotes( $s ) {
1950 return '"' . str_replace( '"', '""', $s ) . '"';
1954 * Returns if the given identifier looks quoted or not according to
1955 * the database convention for quoting identifiers .
1957 * @param string $name
1960 public function isQuotedIdentifier( $name ) {
1961 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1968 protected function escapeLikeInternal( $s ) {
1969 return addcslashes( $s, '\%_' );
1972 public function buildLike() {
1973 $params = func_get_args();
1975 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1976 $params = $params[0];
1981 foreach ( $params as $value ) {
1982 if ( $value instanceof LikeMatch
) {
1983 $s .= $value->toString();
1985 $s .= $this->escapeLikeInternal( $value );
1989 return " LIKE {$this->addQuotes( $s )} ";
1992 public function anyChar() {
1993 return new LikeMatch( '_' );
1996 public function anyString() {
1997 return new LikeMatch( '%' );
2000 public function nextSequenceValue( $seqName ) {
2005 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2006 * is only needed because a) MySQL must be as efficient as possible due to
2007 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2008 * which index to pick. Anyway, other databases might have different
2009 * indexes on a given table. So don't bother overriding this unless you're
2011 * @param string $index
2014 public function useIndexClause( $index ) {
2018 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2019 $quotedTable = $this->tableName( $table );
2021 if ( count( $rows ) == 0 ) {
2026 if ( !is_array( reset( $rows ) ) ) {
2027 $rows = array( $rows );
2030 // @FXIME: this is not atomic, but a trx would break affectedRows()
2031 foreach ( $rows as $row ) {
2032 # Delete rows which collide
2033 if ( $uniqueIndexes ) {
2034 $sql = "DELETE FROM $quotedTable WHERE ";
2036 foreach ( $uniqueIndexes as $index ) {
2043 if ( is_array( $index ) ) {
2045 foreach ( $index as $col ) {
2051 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2054 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2058 $this->query( $sql, $fname );
2061 # Now insert the row
2062 $this->insert( $table, $row, $fname );
2067 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2070 * @param string $table Table name
2071 * @param array|string $rows Row(s) to insert
2072 * @param string $fname Caller function name
2074 * @return ResultWrapper
2076 protected function nativeReplace( $table, $rows, $fname ) {
2077 $table = $this->tableName( $table );
2080 if ( !is_array( reset( $rows ) ) ) {
2081 $rows = array( $rows );
2084 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2087 foreach ( $rows as $row ) {
2094 $sql .= '(' . $this->makeList( $row ) . ')';
2097 return $this->query( $sql, $fname );
2100 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2103 if ( !count( $rows ) ) {
2104 return true; // nothing to do
2107 if ( !is_array( reset( $rows ) ) ) {
2108 $rows = array( $rows );
2111 if ( count( $uniqueIndexes ) ) {
2112 $clauses = array(); // list WHERE clauses that each identify a single row
2113 foreach ( $rows as $row ) {
2114 foreach ( $uniqueIndexes as $index ) {
2115 $index = is_array( $index ) ?
$index : array( $index ); // columns
2116 $rowKey = array(); // unique key to this row
2117 foreach ( $index as $column ) {
2118 $rowKey[$column] = $row[$column];
2120 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2123 $where = array( $this->makeList( $clauses, LIST_OR
) );
2128 $useTrx = !$this->mTrxLevel
;
2130 $this->begin( $fname );
2133 # Update any existing conflicting row(s)
2134 if ( $where !== false ) {
2135 $ok = $this->update( $table, $set, $where, $fname );
2139 # Now insert any non-conflicting row(s)
2140 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2141 } catch ( Exception
$e ) {
2143 $this->rollback( $fname );
2148 $this->commit( $fname );
2154 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2158 throw new DBUnexpectedError( $this,
2159 'DatabaseBase::deleteJoin() called with empty $conds' );
2162 $delTable = $this->tableName( $delTable );
2163 $joinTable = $this->tableName( $joinTable );
2164 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2165 if ( $conds != '*' ) {
2166 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2170 $this->query( $sql, $fname );
2174 * Returns the size of a text field, or -1 for "unlimited"
2176 * @param string $table
2177 * @param string $field
2180 public function textFieldSize( $table, $field ) {
2181 $table = $this->tableName( $table );
2182 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2183 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2184 $row = $this->fetchObject( $res );
2188 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2198 * A string to insert into queries to show that they're low-priority, like
2199 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2200 * string and nothing bad should happen.
2202 * @return string Returns the text of the low priority option if it is
2203 * supported, or a blank string otherwise
2205 public function lowPriorityOption() {
2209 public function delete( $table, $conds, $fname = __METHOD__
) {
2211 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2214 $table = $this->tableName( $table );
2215 $sql = "DELETE FROM $table";
2217 if ( $conds != '*' ) {
2218 if ( is_array( $conds ) ) {
2219 $conds = $this->makeList( $conds, LIST_AND
);
2221 $sql .= ' WHERE ' . $conds;
2224 return $this->query( $sql, $fname );
2227 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2228 $fname = __METHOD__
,
2229 $insertOptions = array(), $selectOptions = array()
2231 $destTable = $this->tableName( $destTable );
2233 if ( !is_array( $insertOptions ) ) {
2234 $insertOptions = array( $insertOptions );
2237 $insertOptions = $this->makeInsertOptions( $insertOptions );
2239 if ( !is_array( $selectOptions ) ) {
2240 $selectOptions = array( $selectOptions );
2243 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2245 if ( is_array( $srcTable ) ) {
2246 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2248 $srcTable = $this->tableName( $srcTable );
2251 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2252 " SELECT $startOpts " . implode( ',', $varMap ) .
2253 " FROM $srcTable $useIndex ";
2255 if ( $conds != '*' ) {
2256 if ( is_array( $conds ) ) {
2257 $conds = $this->makeList( $conds, LIST_AND
);
2259 $sql .= " WHERE $conds";
2262 $sql .= " $tailOpts";
2264 return $this->query( $sql, $fname );
2268 * Construct a LIMIT query with optional offset. This is used for query
2269 * pages. The SQL should be adjusted so that only the first $limit rows
2270 * are returned. If $offset is provided as well, then the first $offset
2271 * rows should be discarded, and the next $limit rows should be returned.
2272 * If the result of the query is not ordered, then the rows to be returned
2273 * are theoretically arbitrary.
2275 * $sql is expected to be a SELECT, if that makes a difference.
2277 * The version provided by default works in MySQL and SQLite. It will very
2278 * likely need to be overridden for most other DBMSes.
2280 * @param string $sql SQL query we will append the limit too
2281 * @param int $limit The SQL limit
2282 * @param int|bool $offset The SQL offset (default false)
2283 * @throws DBUnexpectedError
2286 public function limitResult( $sql, $limit, $offset = false ) {
2287 if ( !is_numeric( $limit ) ) {
2288 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2291 return "$sql LIMIT "
2292 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2296 public function unionSupportsOrderAndLimit() {
2297 return true; // True for almost every DB supported
2300 public function unionQueries( $sqls, $all ) {
2301 $glue = $all ?
') UNION ALL (' : ') UNION (';
2303 return '(' . implode( $glue, $sqls ) . ')';
2306 public function conditional( $cond, $trueVal, $falseVal ) {
2307 if ( is_array( $cond ) ) {
2308 $cond = $this->makeList( $cond, LIST_AND
);
2311 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2314 public function strreplace( $orig, $old, $new ) {
2315 return "REPLACE({$orig}, {$old}, {$new})";
2318 public function getServerUptime() {
2322 public function wasDeadlock() {
2326 public function wasLockTimeout() {
2330 public function wasErrorReissuable() {
2334 public function wasReadOnlyError() {
2339 * Determines if the given query error was a connection drop
2342 * @param integer|string $errno
2345 public function wasConnectionError( $errno ) {
2350 * Perform a deadlock-prone transaction.
2352 * This function invokes a callback function to perform a set of write
2353 * queries. If a deadlock occurs during the processing, the transaction
2354 * will be rolled back and the callback function will be called again.
2357 * $dbw->deadlockLoop( callback, ... );
2359 * Extra arguments are passed through to the specified callback function.
2361 * Returns whatever the callback function returned on its successful,
2362 * iteration, or false on error, for example if the retry limit was
2365 * @throws DBUnexpectedError
2368 public function deadlockLoop() {
2369 $args = func_get_args();
2370 $function = array_shift( $args );
2371 $tries = self
::DEADLOCK_TRIES
;
2373 $this->begin( __METHOD__
);
2376 /** @var Exception $e */
2380 $retVal = call_user_func_array( $function, $args );
2382 } catch ( DBQueryError
$e ) {
2383 if ( $this->wasDeadlock() ) {
2384 // Retry after a randomized delay
2385 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2387 // Throw the error back up
2391 } while ( --$tries > 0 );
2393 if ( $tries <= 0 ) {
2394 // Too many deadlocks; give up
2395 $this->rollback( __METHOD__
);
2398 $this->commit( __METHOD__
);
2404 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2405 # Real waits are implemented in the subclass.
2409 public function getSlavePos() {
2414 public function getMasterPos() {
2419 final public function onTransactionIdle( $callback ) {
2420 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
2421 if ( !$this->mTrxLevel
) {
2422 $this->runOnTransactionIdleCallbacks();
2426 final public function onTransactionPreCommitOrIdle( $callback ) {
2427 if ( $this->mTrxLevel
) {
2428 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
2430 $this->onTransactionIdle( $callback ); // this will trigger immediately
2435 * Actually any "on transaction idle" callbacks.
2439 protected function runOnTransactionIdleCallbacks() {
2440 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2442 $e = $ePrior = null; // last exception
2443 do { // callbacks may add callbacks :)
2444 $callbacks = $this->mTrxIdleCallbacks
;
2445 $this->mTrxIdleCallbacks
= array(); // recursion guard
2446 foreach ( $callbacks as $callback ) {
2448 list( $phpCallback ) = $callback;
2449 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2450 call_user_func( $phpCallback );
2452 $this->setFlag( DBO_TRX
); // restore automatic begin()
2454 $this->clearFlag( DBO_TRX
); // restore auto-commit
2456 } catch ( Exception
$e ) {
2458 MWExceptionHandler
::logException( $ePrior );
2461 // Some callbacks may use startAtomic/endAtomic, so make sure
2462 // their transactions are ended so other callbacks don't fail
2463 if ( $this->trxLevel() ) {
2464 $this->rollback( __METHOD__
);
2468 } while ( count( $this->mTrxIdleCallbacks
) );
2470 if ( $e instanceof Exception
) {
2471 throw $e; // re-throw any last exception
2476 * Actually any "on transaction pre-commit" callbacks.
2480 protected function runOnTransactionPreCommitCallbacks() {
2481 $e = $ePrior = null; // last exception
2482 do { // callbacks may add callbacks :)
2483 $callbacks = $this->mTrxPreCommitCallbacks
;
2484 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
2485 foreach ( $callbacks as $callback ) {
2487 list( $phpCallback ) = $callback;
2488 call_user_func( $phpCallback );
2489 } catch ( Exception
$e ) {
2491 MWExceptionHandler
::logException( $ePrior );
2496 } while ( count( $this->mTrxPreCommitCallbacks
) );
2498 if ( $e instanceof Exception
) {
2499 throw $e; // re-throw any last exception
2503 final public function startAtomic( $fname = __METHOD__
) {
2504 if ( !$this->mTrxLevel
) {
2505 $this->begin( $fname );
2506 $this->mTrxAutomatic
= true;
2507 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2508 // in all changes being in one transaction to keep requests transactional.
2509 if ( !$this->getFlag( DBO_TRX
) ) {
2510 $this->mTrxAutomaticAtomic
= true;
2514 $this->mTrxAtomicLevels
[] = $fname;
2517 final public function endAtomic( $fname = __METHOD__
) {
2518 if ( !$this->mTrxLevel
) {
2519 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2521 if ( !$this->mTrxAtomicLevels ||
2522 array_pop( $this->mTrxAtomicLevels
) !== $fname
2524 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2527 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2528 $this->commit( $fname, 'flush' );
2532 final public function doAtomicSection( $fname, $callback ) {
2533 if ( !is_callable( $callback ) ) {
2534 throw new UnexpectedValueException( "Invalid callback." );
2537 $this->startAtomic( $fname );
2539 call_user_func_array( $callback, array( $this, $fname ) );
2540 } catch ( Exception
$e ) {
2541 $this->rollback( $fname );
2544 $this->endAtomic( $fname );
2547 final public function begin( $fname = __METHOD__
) {
2548 if ( $this->mTrxLevel
) { // implicit commit
2549 if ( $this->mTrxAtomicLevels
) {
2550 // If the current transaction was an automatic atomic one, then we definitely have
2551 // a problem. Same if there is any unclosed atomic level.
2552 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2553 throw new DBUnexpectedError(
2555 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2557 } elseif ( !$this->mTrxAutomatic
) {
2558 // We want to warn about inadvertently nested begin/commit pairs, but not about
2559 // auto-committing implicit transactions that were started by query() via DBO_TRX
2560 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2561 " performing implicit commit!";
2564 $this->getLogContext( array(
2565 'method' => __METHOD__
,
2570 // if the transaction was automatic and has done write operations
2571 if ( $this->mTrxDoneWrites
) {
2572 wfDebug( "$fname: Automatic transaction with writes in progress" .
2573 " (from {$this->mTrxFname}), performing implicit commit!\n"
2578 $this->runOnTransactionPreCommitCallbacks();
2579 $writeTime = $this->pendingWriteQueryDuration();
2580 $this->doCommit( $fname );
2581 if ( $this->mTrxDoneWrites
) {
2582 $this->mDoneWrites
= microtime( true );
2583 $this->getTransactionProfiler()->transactionWritingOut(
2584 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2586 $this->runOnTransactionIdleCallbacks();
2589 # Avoid fatals if close() was called
2590 $this->assertOpen();
2592 $this->doBegin( $fname );
2593 $this->mTrxTimestamp
= microtime( true );
2594 $this->mTrxFname
= $fname;
2595 $this->mTrxDoneWrites
= false;
2596 $this->mTrxAutomatic
= false;
2597 $this->mTrxAutomaticAtomic
= false;
2598 $this->mTrxAtomicLevels
= array();
2599 $this->mTrxIdleCallbacks
= array();
2600 $this->mTrxPreCommitCallbacks
= array();
2601 $this->mTrxShortId
= wfRandomString( 12 );
2602 $this->mTrxWriteDuration
= 0.0;
2603 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2604 // Get an estimate of the slave lag before then, treating estimate staleness
2605 // as lag itself just to be safe
2606 $status = $this->getApproximateLagStatus();
2607 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2611 * Issues the BEGIN command to the database server.
2613 * @see DatabaseBase::begin()
2614 * @param string $fname
2616 protected function doBegin( $fname ) {
2617 $this->query( 'BEGIN', $fname );
2618 $this->mTrxLevel
= 1;
2621 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2622 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2623 // There are still atomic sections open. This cannot be ignored
2624 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2625 throw new DBUnexpectedError(
2627 "Got COMMIT while atomic sections $levels are still open"
2631 if ( $flush === 'flush' ) {
2632 if ( !$this->mTrxLevel
) {
2633 return; // nothing to do
2634 } elseif ( !$this->mTrxAutomatic
) {
2635 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
2638 if ( !$this->mTrxLevel
) {
2639 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2640 return; // nothing to do
2641 } elseif ( $this->mTrxAutomatic
) {
2642 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2646 # Avoid fatals if close() was called
2647 $this->assertOpen();
2649 $this->runOnTransactionPreCommitCallbacks();
2650 $writeTime = $this->pendingWriteQueryDuration();
2651 $this->doCommit( $fname );
2652 if ( $this->mTrxDoneWrites
) {
2653 $this->mDoneWrites
= microtime( true );
2654 $this->getTransactionProfiler()->transactionWritingOut(
2655 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2657 $this->runOnTransactionIdleCallbacks();
2661 * Issues the COMMIT command to the database server.
2663 * @see DatabaseBase::commit()
2664 * @param string $fname
2666 protected function doCommit( $fname ) {
2667 if ( $this->mTrxLevel
) {
2668 $this->query( 'COMMIT', $fname );
2669 $this->mTrxLevel
= 0;
2673 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2674 if ( $flush !== 'flush' ) {
2675 if ( !$this->mTrxLevel
) {
2676 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2677 return; // nothing to do
2678 } elseif ( $this->mTrxAutomatic
) {
2679 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
2682 if ( !$this->mTrxLevel
) {
2683 return; // nothing to do
2684 } elseif ( !$this->mTrxAutomatic
) {
2685 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
2689 # Avoid fatals if close() was called
2690 $this->assertOpen();
2692 $this->doRollback( $fname );
2693 $this->mTrxIdleCallbacks
= array(); // cancel
2694 $this->mTrxPreCommitCallbacks
= array(); // cancel
2695 $this->mTrxAtomicLevels
= array();
2696 if ( $this->mTrxDoneWrites
) {
2697 $this->getTransactionProfiler()->transactionWritingOut(
2698 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2703 * Issues the ROLLBACK command to the database server.
2705 * @see DatabaseBase::rollback()
2706 * @param string $fname
2708 protected function doRollback( $fname ) {
2709 if ( $this->mTrxLevel
) {
2710 $this->query( 'ROLLBACK', $fname, true );
2711 $this->mTrxLevel
= 0;
2716 * Creates a new table with structure copied from existing table
2717 * Note that unlike most database abstraction functions, this function does not
2718 * automatically append database prefix, because it works at a lower
2719 * abstraction level.
2720 * The table names passed to this function shall not be quoted (this
2721 * function calls addIdentifierQuotes when needed).
2723 * @param string $oldName Name of table whose structure should be copied
2724 * @param string $newName Name of table to be created
2725 * @param bool $temporary Whether the new table should be temporary
2726 * @param string $fname Calling function name
2727 * @throws MWException
2728 * @return bool True if operation was successful
2730 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2733 throw new MWException(
2734 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2737 function listTables( $prefix = null, $fname = __METHOD__
) {
2738 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2742 * Reset the views process cache set by listViews()
2745 final public function clearViewsCache() {
2746 $this->allViews
= null;
2750 * Lists all the VIEWs in the database
2752 * For caching purposes the list of all views should be stored in
2753 * $this->allViews. The process cache can be cleared with clearViewsCache()
2755 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2756 * @param string $fname Name of calling function
2757 * @throws MWException
2761 public function listViews( $prefix = null, $fname = __METHOD__
) {
2762 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2766 * Differentiates between a TABLE and a VIEW
2768 * @param string $name Name of the database-structure to test.
2769 * @throws MWException
2773 public function isView( $name ) {
2774 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2777 public function timestamp( $ts = 0 ) {
2778 return wfTimestamp( TS_MW
, $ts );
2781 public function timestampOrNull( $ts = null ) {
2782 if ( is_null( $ts ) ) {
2785 return $this->timestamp( $ts );
2790 * Take the result from a query, and wrap it in a ResultWrapper if
2791 * necessary. Boolean values are passed through as is, to indicate success
2792 * of write queries or failure.
2794 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2795 * resource, and it was necessary to call this function to convert it to
2796 * a wrapper. Nowadays, raw database objects are never exposed to external
2797 * callers, so this is unnecessary in external code.
2799 * @param bool|ResultWrapper|resource|object $result
2800 * @return bool|ResultWrapper
2802 protected function resultObject( $result ) {
2805 } elseif ( $result instanceof ResultWrapper
) {
2807 } elseif ( $result === true ) {
2808 // Successful write query
2811 return new ResultWrapper( $this, $result );
2815 public function ping() {
2816 # Stub. Not essential to override.
2820 public function getSessionLagStatus() {
2821 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2825 * Get the slave lag when the current transaction started
2827 * This is useful when transactions might use snapshot isolation
2828 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2829 * is this lag plus transaction duration. If they don't, it is still
2830 * safe to be pessimistic. This returns null if there is no transaction.
2832 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2835 public function getTransactionLagStatus() {
2836 return $this->mTrxLevel
2837 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
2842 * Get a slave lag estimate for this server
2844 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2847 public function getApproximateLagStatus() {
2849 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
2850 'since' => microtime( true )
2855 * Merge the result of getSessionLagStatus() for several DBs
2856 * using the most pessimistic values to estimate the lag of
2857 * any data derived from them in combination
2859 * This is information is useful for caching modules
2861 * @see WANObjectCache::set()
2862 * @see WANObjectCache::getWithSetCallback()
2864 * @param IDatabase $db1
2865 * @param IDatabase ...
2866 * @return array Map of values:
2867 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2868 * - since: oldest UNIX timestamp of any of the DB lag estimates
2869 * - pending: whether any of the DBs have uncommitted changes
2872 public static function getCacheSetOptions( IDatabase
$db1 ) {
2873 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
2874 foreach ( func_get_args() as $db ) {
2875 /** @var IDatabase $db */
2876 $status = $db->getSessionLagStatus();
2877 if ( $status['lag'] === false ) {
2878 $res['lag'] = false;
2879 } elseif ( $res['lag'] !== false ) {
2880 $res['lag'] = max( $res['lag'], $status['lag'] );
2882 $res['since'] = min( $res['since'], $status['since'] );
2883 $res['pending'] = $res['pending'] ?
: $db->writesPending();
2889 public function getLag() {
2893 function maxListLen() {
2897 public function encodeBlob( $b ) {
2901 public function decodeBlob( $b ) {
2902 if ( $b instanceof Blob
) {
2908 public function setSessionOptions( array $options ) {
2912 * Read and execute SQL commands from a file.
2914 * Returns true on success, error string or exception on failure (depending
2915 * on object's error ignore settings).
2917 * @param string $filename File name to open
2918 * @param bool|callable $lineCallback Optional function called before reading each line
2919 * @param bool|callable $resultCallback Optional function called for each MySQL result
2920 * @param bool|string $fname Calling function name or false if name should be
2921 * generated dynamically using $filename
2922 * @param bool|callable $inputCallback Optional function called for each
2923 * complete line sent
2924 * @throws Exception|MWException
2925 * @return bool|string
2927 public function sourceFile(
2928 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2930 MediaWiki\
suppressWarnings();
2931 $fp = fopen( $filename, 'r' );
2932 MediaWiki\restoreWarnings
();
2934 if ( false === $fp ) {
2935 throw new MWException( "Could not open \"{$filename}\".\n" );
2939 $fname = __METHOD__
. "( $filename )";
2943 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2944 } catch ( Exception
$e ) {
2955 * Get the full path of a patch file. Originally based on archive()
2956 * from updaters.inc. Keep in mind this always returns a patch, as
2957 * it fails back to MySQL if no DB-specific patch can be found
2959 * @param string $patch The name of the patch, like patch-something.sql
2960 * @return string Full path to patch file
2962 public function patchPath( $patch ) {
2965 $dbType = $this->getType();
2966 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2967 return "$IP/maintenance/$dbType/archives/$patch";
2969 return "$IP/maintenance/archives/$patch";
2973 public function setSchemaVars( $vars ) {
2974 $this->mSchemaVars
= $vars;
2978 * Read and execute commands from an open file handle.
2980 * Returns true on success, error string or exception on failure (depending
2981 * on object's error ignore settings).
2983 * @param resource $fp File handle
2984 * @param bool|callable $lineCallback Optional function called before reading each query
2985 * @param bool|callable $resultCallback Optional function called for each MySQL result
2986 * @param string $fname Calling function name
2987 * @param bool|callable $inputCallback Optional function called for each complete query sent
2988 * @return bool|string
2990 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
2991 $fname = __METHOD__
, $inputCallback = false
2995 while ( !feof( $fp ) ) {
2996 if ( $lineCallback ) {
2997 call_user_func( $lineCallback );
3000 $line = trim( fgets( $fp ) );
3002 if ( $line == '' ) {
3006 if ( '-' == $line[0] && '-' == $line[1] ) {
3014 $done = $this->streamStatementEnd( $cmd, $line );
3018 if ( $done ||
feof( $fp ) ) {
3019 $cmd = $this->replaceVars( $cmd );
3021 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3022 $res = $this->query( $cmd, $fname );
3024 if ( $resultCallback ) {
3025 call_user_func( $resultCallback, $res, $this );
3028 if ( false === $res ) {
3029 $err = $this->lastError();
3031 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3042 * Called by sourceStream() to check if we've reached a statement end
3044 * @param string $sql SQL assembled so far
3045 * @param string $newLine New line about to be added to $sql
3046 * @return bool Whether $newLine contains end of the statement
3048 public function streamStatementEnd( &$sql, &$newLine ) {
3049 if ( $this->delimiter
) {
3051 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3052 if ( $newLine != $prev ) {
3061 * Database independent variable replacement. Replaces a set of variables
3062 * in an SQL statement with their contents as given by $this->getSchemaVars().
3064 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3066 * - '{$var}' should be used for text and is passed through the database's
3068 * - `{$var}` should be used for identifiers (e.g. table and database names).
3069 * It is passed through the database's addIdentifierQuotes method which
3070 * can be overridden if the database uses something other than backticks.
3071 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3072 * database's tableName method.
3073 * - / *i* / passes the name that follows through the database's indexName method.
3074 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3075 * its use should be avoided. In 1.24 and older, string encoding was applied.
3077 * @param string $ins SQL statement to replace variables in
3078 * @return string The new SQL statement with variables replaced
3080 protected function replaceVars( $ins ) {
3082 $vars = $this->getSchemaVars();
3083 return preg_replace_callback(
3085 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3086 \'\{\$ (\w+) }\' | # 3. addQuotes
3087 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3088 /\*\$ (\w+) \*/ # 5. leave unencoded
3090 function ( $m ) use ( $that, $vars ) {
3091 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3092 // check for both nonexistent keys *and* the empty string.
3093 if ( isset( $m[1] ) && $m[1] !== '' ) {
3094 if ( $m[1] === 'i' ) {
3095 return $that->indexName( $m[2] );
3097 return $that->tableName( $m[2] );
3099 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3100 return $that->addQuotes( $vars[$m[3]] );
3101 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3102 return $that->addIdentifierQuotes( $vars[$m[4]] );
3103 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3104 return $vars[$m[5]];
3114 * Get schema variables. If none have been set via setSchemaVars(), then
3115 * use some defaults from the current object.
3119 protected function getSchemaVars() {
3120 if ( $this->mSchemaVars
) {
3121 return $this->mSchemaVars
;
3123 return $this->getDefaultSchemaVars();
3128 * Get schema variables to use if none have been set via setSchemaVars().
3130 * Override this in derived classes to provide variables for tables.sql
3131 * and SQL patch files.
3135 protected function getDefaultSchemaVars() {
3139 public function lockIsFree( $lockName, $method ) {
3143 public function lock( $lockName, $method, $timeout = 5 ) {
3147 public function unlock( $lockName, $method ) {
3151 public function namedLocksEnqueue() {
3156 * Lock specific tables
3158 * @param array $read Array of tables to lock for read access
3159 * @param array $write Array of tables to lock for write access
3160 * @param string $method Name of caller
3161 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3164 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3169 * Unlock specific tables
3171 * @param string $method The caller
3174 public function unlockTables( $method ) {
3180 * @param string $tableName
3181 * @param string $fName
3182 * @return bool|ResultWrapper
3185 public function dropTable( $tableName, $fName = __METHOD__
) {
3186 if ( !$this->tableExists( $tableName, $fName ) ) {
3189 $sql = "DROP TABLE " . $this->tableName( $tableName );
3190 if ( $this->cascadingDeletes() ) {
3194 return $this->query( $sql, $fName );
3198 * Get search engine class. All subclasses of this need to implement this
3199 * if they wish to use searching.
3203 public function getSearchEngine() {
3204 return 'SearchEngineDummy';
3207 public function getInfinity() {
3211 public function encodeExpiry( $expiry ) {
3212 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3213 ?
$this->getInfinity()
3214 : $this->timestamp( $expiry );
3217 public function decodeExpiry( $expiry, $format = TS_MW
) {
3218 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3220 : wfTimestamp( $format, $expiry );
3223 public function setBigSelects( $value = true ) {
3227 public function isReadOnly() {
3228 return ( $this->getReadOnlyReason() !== false );
3232 * @return string|bool Reason this DB is read-only or false if it is not
3234 protected function getReadOnlyReason() {
3235 $reason = $this->getLBInfo( 'readOnlyReason' );
3237 return is_string( $reason ) ?
$reason : false;
3244 public function __toString() {
3245 return (string)$this->mConn
;
3249 * Run a few simple sanity checks
3251 public function __destruct() {
3252 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3253 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3255 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3257 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3258 $callers[] = $callbackInfo[1];
3260 $callers = implode( ', ', $callers );
3261 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3269 abstract class Database
extends DatabaseBase
{
3270 // B/C until nothing type hints for DatabaseBase
3271 // @TODO: finish renaming DatabaseBase => Database