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 if ( !$this->trxProfiler
) {
286 $this->trxProfiler
= new TransactionProfiler();
289 return $this->trxProfiler
;
293 * @param TransactionProfiler $profiler
296 public function setTransactionProfiler( TransactionProfiler
$profiler ) {
297 $this->trxProfiler
= $profiler;
301 * Returns true if this database supports (and uses) cascading deletes
305 public function cascadingDeletes() {
310 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
314 public function cleanupTriggers() {
319 * Returns true if this database is strict about what can be put into an IP field.
320 * Specifically, it uses a NULL value instead of an empty string.
324 public function strictIPs() {
329 * Returns true if this database uses timestamps rather than integers
333 public function realTimestamps() {
337 public function implicitGroupby() {
341 public function implicitOrderby() {
346 * Returns true if this database can do a native search on IP columns
347 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
351 public function searchableIPs() {
356 * Returns true if this database can use functional indexes
360 public function functionalIndexes() {
364 public function lastQuery() {
365 return $this->mLastQuery
;
368 public function doneWrites() {
369 return (bool)$this->mDoneWrites
;
372 public function lastDoneWrites() {
373 return $this->mDoneWrites ?
: false;
376 public function writesPending() {
377 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
380 public function writesOrCallbacksPending() {
381 return $this->mTrxLevel
&& (
382 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
386 public function pendingWriteQueryDuration() {
387 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
390 public function isOpen() {
391 return $this->mOpened
;
394 public function setFlag( $flag ) {
395 $this->mFlags |
= $flag;
398 public function clearFlag( $flag ) {
399 $this->mFlags
&= ~
$flag;
402 public function getFlag( $flag ) {
403 return !!( $this->mFlags
& $flag );
406 public function getProperty( $name ) {
410 public function getWikiID() {
411 if ( $this->mTablePrefix
) {
412 return "{$this->mDBname}-{$this->mTablePrefix}";
414 return $this->mDBname
;
419 * Return a path to the DBMS-specific SQL file if it exists,
420 * otherwise default SQL file
422 * @param string $filename
425 private function getSqlFilePath( $filename ) {
427 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
428 if ( file_exists( $dbmsSpecificFilePath ) ) {
429 return $dbmsSpecificFilePath;
431 return "$IP/maintenance/$filename";
436 * Return a path to the DBMS-specific schema file,
437 * otherwise default to tables.sql
441 public function getSchemaPath() {
442 return $this->getSqlFilePath( 'tables.sql' );
446 * Return a path to the DBMS-specific update key file,
447 * otherwise default to update-keys.sql
451 public function getUpdateKeysPath() {
452 return $this->getSqlFilePath( 'update-keys.sql' );
456 * Get information about an index into an object
457 * @param string $table Table name
458 * @param string $index Index name
459 * @param string $fname Calling function name
460 * @return mixed Database-specific index description class or false if the index does not exist
462 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
465 * Wrapper for addslashes()
467 * @param string $s String to be slashed.
468 * @return string Slashed string.
470 abstract function strencode( $s );
475 * FIXME: It is possible to construct a Database object with no associated
476 * connection object, by specifying no parameters to __construct(). This
477 * feature is deprecated and should be removed.
479 * DatabaseBase subclasses should not be constructed directly in external
480 * code. DatabaseBase::factory() should be used instead.
482 * @param array $params Parameters passed from DatabaseBase::factory()
484 function __construct( array $params ) {
485 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
487 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
489 $server = $params['host'];
490 $user = $params['user'];
491 $password = $params['password'];
492 $dbName = $params['dbname'];
493 $flags = $params['flags'];
494 $tablePrefix = $params['tablePrefix'];
495 $schema = $params['schema'];
496 $foreign = $params['foreign'];
498 $this->mFlags
= $flags;
499 if ( $this->mFlags
& DBO_DEFAULT
) {
500 if ( $wgCommandLineMode ) {
501 $this->mFlags
&= ~DBO_TRX
;
503 $this->mFlags |
= DBO_TRX
;
507 $this->mSessionVars
= $params['variables'];
509 /** Get the default table prefix*/
510 if ( $tablePrefix === 'get from global' ) {
511 $this->mTablePrefix
= $wgDBprefix;
513 $this->mTablePrefix
= $tablePrefix;
516 /** Get the database schema*/
517 if ( $schema === 'get from global' ) {
518 $this->mSchema
= $wgDBmwschema;
520 $this->mSchema
= $schema;
523 $this->mForeign
= $foreign;
525 if ( isset( $params['trxProfiler'] ) ) {
526 $this->trxProfiler
= $params['trxProfiler']; // override
530 $this->open( $server, $user, $password, $dbName );
535 * Called by serialize. Throw an exception when DB connection is serialized.
536 * This causes problems on some database engines because the connection is
537 * not restored on unserialize.
539 public function __sleep() {
540 throw new MWException( 'Database serialization may cause problems, since ' .
541 'the connection is not restored on wakeup.' );
545 * Given a DB type, construct the name of the appropriate child class of
546 * DatabaseBase. This is designed to replace all of the manual stuff like:
547 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
548 * as well as validate against the canonical list of DB types we have
550 * This factory function is mostly useful for when you need to connect to a
551 * database other than the MediaWiki default (such as for external auth,
552 * an extension, et cetera). Do not use this to connect to the MediaWiki
553 * database. Example uses in core:
554 * @see LoadBalancer::reallyOpenConnection()
555 * @see ForeignDBRepo::getMasterDB()
556 * @see WebInstallerDBConnect::execute()
560 * @param string $dbType A possible DB type
561 * @param array $p An array of options to pass to the constructor.
562 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
563 * @throws MWException If the database driver or extension cannot be found
564 * @return DatabaseBase|null DatabaseBase subclass or null
566 final public static function factory( $dbType, $p = array() ) {
567 $canonicalDBTypes = array(
568 'mysql' => array( 'mysqli', 'mysql' ),
569 'postgres' => array(),
576 $dbType = strtolower( $dbType );
577 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
578 $possibleDrivers = $canonicalDBTypes[$dbType];
579 if ( !empty( $p['driver'] ) ) {
580 if ( in_array( $p['driver'], $possibleDrivers ) ) {
581 $driver = $p['driver'];
583 throw new MWException( __METHOD__
.
584 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
587 foreach ( $possibleDrivers as $posDriver ) {
588 if ( extension_loaded( $posDriver ) ) {
589 $driver = $posDriver;
597 if ( $driver === false ) {
598 throw new MWException( __METHOD__
.
599 " no viable database extension found for type '$dbType'" );
602 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
603 // and everything else doesn't use a schema (e.g. null)
604 // Although postgres and oracle support schemas, we don't use them (yet)
605 // to maintain backwards compatibility
606 $defaultSchemas = array(
607 'mssql' => 'get from global',
610 $class = 'Database' . ucfirst( $driver );
611 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
612 // Resolve some defaults for b/c
613 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
614 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
615 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
616 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
617 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
618 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
619 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
620 if ( !isset( $p['schema'] ) ) {
621 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
623 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
625 return new $class( $p );
631 protected function installErrorHandler() {
632 $this->mPHPError
= false;
633 $this->htmlErrors
= ini_set( 'html_errors', '0' );
634 set_error_handler( array( $this, 'connectionErrorHandler' ) );
638 * @return bool|string
640 protected function restoreErrorHandler() {
641 restore_error_handler();
642 if ( $this->htmlErrors
!== false ) {
643 ini_set( 'html_errors', $this->htmlErrors
);
645 if ( $this->mPHPError
) {
646 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
647 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
657 * @param string $errstr
659 public function connectionErrorHandler( $errno, $errstr ) {
660 $this->mPHPError
= $errstr;
664 * Create a log context to pass to wfLogDBError or other logging functions.
666 * @param array $extras Additional data to add to context
669 protected function getLogContext( array $extras = array() ) {
672 'db_server' => $this->mServer
,
673 'db_name' => $this->mDBname
,
674 'db_user' => $this->mUser
,
680 public function close() {
681 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
682 throw new MWException( "Transaction idle callbacks still pending." );
684 if ( $this->mConn
) {
685 if ( $this->trxLevel() ) {
686 if ( !$this->mTrxAutomatic
) {
687 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
688 " performing implicit commit before closing connection!" );
691 $this->commit( __METHOD__
, 'flush' );
694 $closed = $this->closeConnection();
695 $this->mConn
= false;
699 $this->mOpened
= false;
705 * Make sure isOpen() returns true as a sanity check
707 * @throws DBUnexpectedError
709 protected function assertOpen() {
710 if ( !$this->isOpen() ) {
711 throw new DBUnexpectedError( $this, "DB connection was already closed." );
716 * Closes underlying database connection
718 * @return bool Whether connection was closed successfully
720 abstract protected function closeConnection();
722 function reportConnectionError( $error = 'Unknown error' ) {
723 $myError = $this->lastError();
729 throw new DBConnectionError( $this, $error );
733 * The DBMS-dependent part of query()
735 * @param string $sql SQL query.
736 * @return ResultWrapper|bool Result object to feed to fetchObject,
737 * fetchRow, ...; or false on failure
739 abstract protected function doQuery( $sql );
742 * Determine whether a query writes to the DB.
743 * Should return true if unsure.
748 protected function isWriteQuery( $sql ) {
749 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
753 * Determine whether a SQL statement is sensitive to isolation level.
754 * A SQL statement is considered transactable if its result could vary
755 * depending on the transaction isolation level. Operational commands
756 * such as 'SET' and 'SHOW' are not considered to be transactable.
761 protected function isTransactableQuery( $sql ) {
762 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
763 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
766 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
769 $this->mLastQuery
= $sql;
771 $isWriteQuery = $this->isWriteQuery( $sql );
772 if ( $isWriteQuery ) {
773 $reason = $this->getReadOnlyReason();
774 if ( $reason !== false ) {
775 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
777 # Set a flag indicating that writes have been done
778 $this->mDoneWrites
= microtime( true );
781 # Add a comment for easy SHOW PROCESSLIST interpretation
782 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
783 $userName = $wgUser->getName();
784 if ( mb_strlen( $userName ) > 15 ) {
785 $userName = mb_substr( $userName, 0, 15 ) . '...';
787 $userName = str_replace( '/', '', $userName );
792 // Add trace comment to the begin of the sql string, right after the operator.
793 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
794 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
796 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
797 $this->begin( __METHOD__
. " ($fname)" );
798 $this->mTrxAutomatic
= true;
801 # Keep track of whether the transaction has write queries pending
802 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
803 $this->mTrxDoneWrites
= true;
804 $this->getTransactionProfiler()->transactionWritingIn(
805 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
808 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
809 # generalizeSQL will probably cut down the query to reasonable
810 # logging size most of the time. The substr is really just a sanity check.
812 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
813 $totalProf = 'DatabaseBase::query-master';
815 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
816 $totalProf = 'DatabaseBase::query';
818 # Include query transaction state
819 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
821 $profiler = Profiler
::instance();
822 if ( !$profiler instanceof ProfilerStub
) {
823 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
824 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
827 if ( $this->debug() ) {
828 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
831 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
833 # Avoid fatals if close() was called
836 # Do the query and handle errors
837 $startTime = microtime( true );
838 $ret = $this->doQuery( $commentedSql );
839 $queryRuntime = microtime( true ) - $startTime;
840 # Log the query time and feed it into the DB trx profiler
841 $this->getTransactionProfiler()->recordQueryCompletion(
842 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
844 MWDebug
::queryTime( $queryId );
846 # Try reconnecting if the connection was lost
847 if ( false === $ret && $this->wasErrorReissuable() ) {
848 # Transaction is gone, like it or not
849 $hadTrx = $this->mTrxLevel
; // possible lost transaction
850 $this->mTrxLevel
= 0;
851 $this->mTrxIdleCallbacks
= array(); // bug 65263
852 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
853 wfDebug( "Connection lost, reconnecting...\n" );
854 # Stash the last error values since ping() might clear them
855 $lastError = $this->lastError();
856 $lastErrno = $this->lastErrno();
857 if ( $this->ping() ) {
858 wfDebug( "Reconnected\n" );
859 $server = $this->getServer();
860 $msg = __METHOD__
. ": lost connection to $server; reconnected";
861 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
864 # Leave $ret as false and let an error be reported.
865 # Callers may catch the exception and continue to use the DB.
866 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
868 # Should be safe to silently retry (no trx and thus no callbacks)
869 $startTime = microtime( true );
870 $ret = $this->doQuery( $commentedSql );
871 $queryRuntime = microtime( true ) - $startTime;
872 # Log the query time and feed it into the DB trx profiler
873 $this->getTransactionProfiler()->recordQueryCompletion(
874 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
877 wfDebug( "Failed\n" );
881 if ( false === $ret ) {
882 $this->reportQueryError(
883 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
886 $res = $this->resultObject( $ret );
888 // Destroy profile sections in the opposite order to their creation
889 ScopedCallback
::consume( $queryProfSection );
890 ScopedCallback
::consume( $totalProfSection );
892 if ( $isWriteQuery && $this->mTrxLevel
) {
893 $this->mTrxWriteDuration +
= $queryRuntime;
899 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
900 if ( $this->ignoreErrors() ||
$tempIgnore ) {
901 wfDebug( "SQL ERROR (ignored): $error\n" );
903 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
905 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
906 $this->getLogContext( array(
907 'method' => __METHOD__
,
910 'sql1line' => $sql1line,
914 wfDebug( "SQL ERROR: " . $error . "\n" );
915 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
920 * Intended to be compatible with the PEAR::DB wrapper functions.
921 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
923 * ? = scalar value, quoted as necessary
924 * ! = raw SQL bit (a function for instance)
925 * & = filename; reads the file and inserts as a blob
926 * (we don't use this though...)
929 * @param string $func
933 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
934 /* MySQL doesn't support prepared statements (yet), so just
935 * pack up the query for reference. We'll manually replace
938 return array( 'query' => $sql, 'func' => $func );
942 * Free a prepared query, generated by prepare().
943 * @param string $prepared
945 protected function freePrepared( $prepared ) {
946 /* No-op by default */
950 * Execute a prepared query with the various arguments
951 * @param string $prepared The prepared sql
952 * @param mixed $args Either an array here, or put scalars as varargs
954 * @return ResultWrapper
956 public function execute( $prepared, $args = null ) {
957 if ( !is_array( $args ) ) {
959 $args = func_get_args();
960 array_shift( $args );
963 $sql = $this->fillPrepared( $prepared['query'], $args );
965 return $this->query( $sql, $prepared['func'] );
969 * For faking prepared SQL statements on DBs that don't support it directly.
971 * @param string $preparedQuery A 'preparable' SQL statement
972 * @param array $args Array of Arguments to fill it with
973 * @return string Executable SQL
975 public function fillPrepared( $preparedQuery, $args ) {
977 $this->preparedArgs
=& $args;
979 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
980 array( &$this, 'fillPreparedArg' ), $preparedQuery );
984 * preg_callback func for fillPrepared()
985 * The arguments should be in $this->preparedArgs and must not be touched
986 * while we're doing this.
988 * @param array $matches
989 * @throws DBUnexpectedError
992 protected function fillPreparedArg( $matches ) {
993 switch ( $matches[1] ) {
1002 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1004 switch ( $matches[1] ) {
1006 return $this->addQuotes( $arg );
1010 # return $this->addQuotes( file_get_contents( $arg ) );
1011 throw new DBUnexpectedError(
1013 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1016 throw new DBUnexpectedError(
1018 'Received invalid match. This should never happen!'
1023 public function freeResult( $res ) {
1026 public function selectField(
1027 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1029 if ( $var === '*' ) { // sanity
1030 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1033 if ( !is_array( $options ) ) {
1034 $options = array( $options );
1037 $options['LIMIT'] = 1;
1039 $res = $this->select( $table, $var, $cond, $fname, $options );
1040 if ( $res === false ||
!$this->numRows( $res ) ) {
1044 $row = $this->fetchRow( $res );
1046 if ( $row !== false ) {
1047 return reset( $row );
1053 public function selectFieldValues(
1054 $table, $var, $cond = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1056 if ( $var === '*' ) { // sanity
1057 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1060 if ( !is_array( $options ) ) {
1061 $options = array( $options );
1064 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1065 if ( $res === false ) {
1070 foreach ( $res as $row ) {
1071 $values[] = $row->$var;
1078 * Returns an optional USE INDEX clause to go after the table, and a
1079 * string to go at the end of the query.
1081 * @param array $options Associative array of options to be turned into
1082 * an SQL query, valid keys are listed in the function.
1084 * @see DatabaseBase::select()
1086 public function makeSelectOptions( $options ) {
1087 $preLimitTail = $postLimitTail = '';
1090 $noKeyOptions = array();
1092 foreach ( $options as $key => $option ) {
1093 if ( is_numeric( $key ) ) {
1094 $noKeyOptions[$option] = true;
1098 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1100 $preLimitTail .= $this->makeOrderBy( $options );
1102 // if (isset($options['LIMIT'])) {
1103 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1104 // isset($options['OFFSET']) ? $options['OFFSET']
1108 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1109 $postLimitTail .= ' FOR UPDATE';
1112 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1113 $postLimitTail .= ' LOCK IN SHARE MODE';
1116 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1117 $startOpts .= 'DISTINCT';
1120 # Various MySQL extensions
1121 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1122 $startOpts .= ' /*! STRAIGHT_JOIN */';
1125 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1126 $startOpts .= ' HIGH_PRIORITY';
1129 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1130 $startOpts .= ' SQL_BIG_RESULT';
1133 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1134 $startOpts .= ' SQL_BUFFER_RESULT';
1137 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1138 $startOpts .= ' SQL_SMALL_RESULT';
1141 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1142 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1145 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1146 $startOpts .= ' SQL_CACHE';
1149 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1150 $startOpts .= ' SQL_NO_CACHE';
1153 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1154 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1159 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1163 * Returns an optional GROUP BY with an optional HAVING
1165 * @param array $options Associative array of options
1167 * @see DatabaseBase::select()
1170 public function makeGroupByWithHaving( $options ) {
1172 if ( isset( $options['GROUP BY'] ) ) {
1173 $gb = is_array( $options['GROUP BY'] )
1174 ?
implode( ',', $options['GROUP BY'] )
1175 : $options['GROUP BY'];
1176 $sql .= ' GROUP BY ' . $gb;
1178 if ( isset( $options['HAVING'] ) ) {
1179 $having = is_array( $options['HAVING'] )
1180 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1181 : $options['HAVING'];
1182 $sql .= ' HAVING ' . $having;
1189 * Returns an optional ORDER BY
1191 * @param array $options Associative array of options
1193 * @see DatabaseBase::select()
1196 public function makeOrderBy( $options ) {
1197 if ( isset( $options['ORDER BY'] ) ) {
1198 $ob = is_array( $options['ORDER BY'] )
1199 ?
implode( ',', $options['ORDER BY'] )
1200 : $options['ORDER BY'];
1202 return ' ORDER BY ' . $ob;
1208 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1209 $options = array(), $join_conds = array() ) {
1210 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1212 return $this->query( $sql, $fname );
1215 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1216 $options = array(), $join_conds = array()
1218 if ( is_array( $vars ) ) {
1219 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1222 $options = (array)$options;
1223 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1224 ?
$options['USE INDEX']
1227 if ( is_array( $table ) ) {
1229 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1230 } elseif ( $table != '' ) {
1231 if ( $table[0] == ' ' ) {
1232 $from = ' FROM ' . $table;
1235 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1241 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1242 $this->makeSelectOptions( $options );
1244 if ( !empty( $conds ) ) {
1245 if ( is_array( $conds ) ) {
1246 $conds = $this->makeList( $conds, LIST_AND
);
1248 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1250 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1253 if ( isset( $options['LIMIT'] ) ) {
1254 $sql = $this->limitResult( $sql, $options['LIMIT'],
1255 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1257 $sql = "$sql $postLimitTail";
1259 if ( isset( $options['EXPLAIN'] ) ) {
1260 $sql = 'EXPLAIN ' . $sql;
1266 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1267 $options = array(), $join_conds = array()
1269 $options = (array)$options;
1270 $options['LIMIT'] = 1;
1271 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1273 if ( $res === false ) {
1277 if ( !$this->numRows( $res ) ) {
1281 $obj = $this->fetchObject( $res );
1286 public function estimateRowCount(
1287 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1290 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1293 $row = $this->fetchRow( $res );
1294 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1300 public function selectRowCount(
1301 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1304 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1305 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1308 $row = $this->fetchRow( $res );
1309 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1316 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1317 * It's only slightly flawed. Don't use for anything important.
1319 * @param string $sql A SQL Query
1323 protected static function generalizeSQL( $sql ) {
1324 # This does the same as the regexp below would do, but in such a way
1325 # as to avoid crashing php on some large strings.
1326 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1328 $sql = str_replace( "\\\\", '', $sql );
1329 $sql = str_replace( "\\'", '', $sql );
1330 $sql = str_replace( "\\\"", '', $sql );
1331 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1332 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1334 # All newlines, tabs, etc replaced by single space
1335 $sql = preg_replace( '/\s+/', ' ', $sql );
1338 # except the ones surrounded by characters, e.g. l10n
1339 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1340 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1345 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1346 $info = $this->fieldInfo( $table, $field );
1351 public function indexExists( $table, $index, $fname = __METHOD__
) {
1352 if ( !$this->tableExists( $table ) ) {
1356 $info = $this->indexInfo( $table, $index, $fname );
1357 if ( is_null( $info ) ) {
1360 return $info !== false;
1364 public function tableExists( $table, $fname = __METHOD__
) {
1365 $table = $this->tableName( $table );
1366 $old = $this->ignoreErrors( true );
1367 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1368 $this->ignoreErrors( $old );
1373 public function indexUnique( $table, $index ) {
1374 $indexInfo = $this->indexInfo( $table, $index );
1376 if ( !$indexInfo ) {
1380 return !$indexInfo[0]->Non_unique
;
1384 * Helper for DatabaseBase::insert().
1386 * @param array $options
1389 protected function makeInsertOptions( $options ) {
1390 return implode( ' ', $options );
1393 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1394 # No rows to insert, easy just return now
1395 if ( !count( $a ) ) {
1399 $table = $this->tableName( $table );
1401 if ( !is_array( $options ) ) {
1402 $options = array( $options );
1406 if ( isset( $options['fileHandle'] ) ) {
1407 $fh = $options['fileHandle'];
1409 $options = $this->makeInsertOptions( $options );
1411 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1413 $keys = array_keys( $a[0] );
1416 $keys = array_keys( $a );
1419 $sql = 'INSERT ' . $options .
1420 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1424 foreach ( $a as $row ) {
1430 $sql .= '(' . $this->makeList( $row ) . ')';
1433 $sql .= '(' . $this->makeList( $a ) . ')';
1436 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1438 } elseif ( $fh !== null ) {
1442 return (bool)$this->query( $sql, $fname );
1446 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1448 * @param array $options
1451 protected function makeUpdateOptionsArray( $options ) {
1452 if ( !is_array( $options ) ) {
1453 $options = array( $options );
1458 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1459 $opts[] = $this->lowPriorityOption();
1462 if ( in_array( 'IGNORE', $options ) ) {
1470 * Make UPDATE options for the DatabaseBase::update function
1472 * @param array $options The options passed to DatabaseBase::update
1475 protected function makeUpdateOptions( $options ) {
1476 $opts = $this->makeUpdateOptionsArray( $options );
1478 return implode( ' ', $opts );
1481 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1482 $table = $this->tableName( $table );
1483 $opts = $this->makeUpdateOptions( $options );
1484 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1486 if ( $conds !== array() && $conds !== '*' ) {
1487 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1490 return $this->query( $sql, $fname );
1493 public function makeList( $a, $mode = LIST_COMMA
) {
1494 if ( !is_array( $a ) ) {
1495 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1501 foreach ( $a as $field => $value ) {
1503 if ( $mode == LIST_AND
) {
1505 } elseif ( $mode == LIST_OR
) {
1514 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1515 $list .= "($value)";
1516 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1518 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1519 // Remove null from array to be handled separately if found
1520 $includeNull = false;
1521 foreach ( array_keys( $value, null, true ) as $nullKey ) {
1522 $includeNull = true;
1523 unset( $value[$nullKey] );
1525 if ( count( $value ) == 0 && !$includeNull ) {
1526 throw new MWException( __METHOD__
. ": empty input for field $field" );
1527 } elseif ( count( $value ) == 0 ) {
1528 // only check if $field is null
1529 $list .= "$field IS NULL";
1531 // IN clause contains at least one valid element
1532 if ( $includeNull ) {
1533 // Group subconditions to ensure correct precedence
1536 if ( count( $value ) == 1 ) {
1537 // Special-case single values, as IN isn't terribly efficient
1538 // Don't necessarily assume the single key is 0; we don't
1539 // enforce linear numeric ordering on other arrays here.
1540 $value = array_values( $value );
1541 $list .= $field . " = " . $this->addQuotes( $value[0] );
1543 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1545 // if null present in array, append IS NULL
1546 if ( $includeNull ) {
1547 $list .= " OR $field IS NULL)";
1550 } elseif ( $value === null ) {
1551 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1552 $list .= "$field IS ";
1553 } elseif ( $mode == LIST_SET
) {
1554 $list .= "$field = ";
1558 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1559 $list .= "$field = ";
1561 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1568 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1571 foreach ( $data as $base => $sub ) {
1572 if ( count( $sub ) ) {
1573 $conds[] = $this->makeList(
1574 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1580 return $this->makeList( $conds, LIST_OR
);
1582 // Nothing to search for...
1588 * Return aggregated value alias
1590 * @param array $valuedata
1591 * @param string $valuename
1595 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1599 public function bitNot( $field ) {
1603 public function bitAnd( $fieldLeft, $fieldRight ) {
1604 return "($fieldLeft & $fieldRight)";
1607 public function bitOr( $fieldLeft, $fieldRight ) {
1608 return "($fieldLeft | $fieldRight)";
1611 public function buildConcat( $stringList ) {
1612 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1615 public function buildGroupConcatField(
1616 $delim, $table, $field, $conds = '', $join_conds = array()
1618 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
1620 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
1623 public function selectDB( $db ) {
1624 # Stub. Shouldn't cause serious problems if it's not overridden, but
1625 # if your database engine supports a concept similar to MySQL's
1626 # databases you may as well.
1627 $this->mDBname
= $db;
1632 public function getDBname() {
1633 return $this->mDBname
;
1636 public function getServer() {
1637 return $this->mServer
;
1641 * Format a table name ready for use in constructing an SQL query
1643 * This does two important things: it quotes the table names to clean them up,
1644 * and it adds a table prefix if only given a table name with no quotes.
1646 * All functions of this object which require a table name call this function
1647 * themselves. Pass the canonical name to such functions. This is only needed
1648 * when calling query() directly.
1650 * @param string $name Database table name
1651 * @param string $format One of:
1652 * quoted - Automatically pass the table name through addIdentifierQuotes()
1653 * so that it can be used in a query.
1654 * raw - Do not add identifier quotes to the table name
1655 * @return string Full database name
1657 public function tableName( $name, $format = 'quoted' ) {
1658 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
1659 # Skip the entire process when we have a string quoted on both ends.
1660 # Note that we check the end so that we will still quote any use of
1661 # use of `database`.table. But won't break things if someone wants
1662 # to query a database table with a dot in the name.
1663 if ( $this->isQuotedIdentifier( $name ) ) {
1667 # Lets test for any bits of text that should never show up in a table
1668 # name. Basically anything like JOIN or ON which are actually part of
1669 # SQL queries, but may end up inside of the table value to combine
1670 # sql. Such as how the API is doing.
1671 # Note that we use a whitespace test rather than a \b test to avoid
1672 # any remote case where a word like on may be inside of a table name
1673 # surrounded by symbols which may be considered word breaks.
1674 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1678 # Split database and table into proper variables.
1679 # We reverse the explode so that database.table and table both output
1680 # the correct table.
1681 $dbDetails = explode( '.', $name, 3 );
1682 if ( count( $dbDetails ) == 3 ) {
1683 list( $database, $schema, $table ) = $dbDetails;
1684 # We don't want any prefix added in this case
1686 } elseif ( count( $dbDetails ) == 2 ) {
1687 list( $database, $table ) = $dbDetails;
1688 # We don't want any prefix added in this case
1689 # In dbs that support it, $database may actually be the schema
1690 # but that doesn't affect any of the functionality here
1694 list( $table ) = $dbDetails;
1695 if ( $wgSharedDB !== null # We have a shared database
1696 && $this->mForeign
== false # We're not working on a foreign database
1697 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
1698 && in_array( $table, $wgSharedTables ) # A shared table is selected
1700 $database = $wgSharedDB;
1701 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
1702 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
1705 $schema = $this->mSchema
; # Default schema
1706 $prefix = $this->mTablePrefix
; # Default prefix
1710 # Quote $table and apply the prefix if not quoted.
1711 # $tableName might be empty if this is called from Database::replaceVars()
1712 $tableName = "{$prefix}{$table}";
1713 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
1714 $tableName = $this->addIdentifierQuotes( $tableName );
1717 # Quote $schema and merge it with the table name if needed
1718 if ( strlen( $schema ) ) {
1719 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
1720 $schema = $this->addIdentifierQuotes( $schema );
1722 $tableName = $schema . '.' . $tableName;
1725 # Quote $database and merge it with the table name if needed
1726 if ( $database !== null ) {
1727 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1728 $database = $this->addIdentifierQuotes( $database );
1730 $tableName = $database . '.' . $tableName;
1737 * Fetch a number of table names into an array
1738 * This is handy when you need to construct SQL for joins
1741 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
1742 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1743 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1747 public function tableNames() {
1748 $inArray = func_get_args();
1751 foreach ( $inArray as $name ) {
1752 $retVal[$name] = $this->tableName( $name );
1759 * Fetch a number of table names into an zero-indexed numerical array
1760 * This is handy when you need to construct SQL for joins
1763 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
1764 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1765 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1769 public function tableNamesN() {
1770 $inArray = func_get_args();
1773 foreach ( $inArray as $name ) {
1774 $retVal[] = $this->tableName( $name );
1781 * Get an aliased table name
1782 * e.g. tableName AS newTableName
1784 * @param string $name Table name, see tableName()
1785 * @param string|bool $alias Alias (optional)
1786 * @return string SQL name for aliased table. Will not alias a table to its own name
1788 public function tableNameWithAlias( $name, $alias = false ) {
1789 if ( !$alias ||
$alias == $name ) {
1790 return $this->tableName( $name );
1792 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1797 * Gets an array of aliased table names
1799 * @param array $tables Array( [alias] => table )
1800 * @return string[] See tableNameWithAlias()
1802 public function tableNamesWithAlias( $tables ) {
1804 foreach ( $tables as $alias => $table ) {
1805 if ( is_numeric( $alias ) ) {
1808 $retval[] = $this->tableNameWithAlias( $table, $alias );
1815 * Get an aliased field name
1816 * e.g. fieldName AS newFieldName
1818 * @param string $name Field name
1819 * @param string|bool $alias Alias (optional)
1820 * @return string SQL name for aliased field. Will not alias a field to its own name
1822 public function fieldNameWithAlias( $name, $alias = false ) {
1823 if ( !$alias ||
(string)$alias === (string)$name ) {
1826 return $name . ' AS ' . $alias; // PostgreSQL needs AS
1831 * Gets an array of aliased field names
1833 * @param array $fields Array( [alias] => field )
1834 * @return string[] See fieldNameWithAlias()
1836 public function fieldNamesWithAlias( $fields ) {
1838 foreach ( $fields as $alias => $field ) {
1839 if ( is_numeric( $alias ) ) {
1842 $retval[] = $this->fieldNameWithAlias( $field, $alias );
1849 * Get the aliased table name clause for a FROM clause
1850 * which might have a JOIN and/or USE INDEX clause
1852 * @param array $tables ( [alias] => table )
1853 * @param array $use_index Same as for select()
1854 * @param array $join_conds Same as for select()
1857 protected function tableNamesWithUseIndexOrJOIN(
1858 $tables, $use_index = array(), $join_conds = array()
1862 $use_index = (array)$use_index;
1863 $join_conds = (array)$join_conds;
1865 foreach ( $tables as $alias => $table ) {
1866 if ( !is_string( $alias ) ) {
1867 // No alias? Set it equal to the table name
1870 // Is there a JOIN clause for this table?
1871 if ( isset( $join_conds[$alias] ) ) {
1872 list( $joinType, $conds ) = $join_conds[$alias];
1873 $tableClause = $joinType;
1874 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
1875 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
1876 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
1878 $tableClause .= ' ' . $use;
1881 $on = $this->makeList( (array)$conds, LIST_AND
);
1883 $tableClause .= ' ON (' . $on . ')';
1886 $retJOIN[] = $tableClause;
1887 } elseif ( isset( $use_index[$alias] ) ) {
1888 // Is there an INDEX clause for this table?
1889 $tableClause = $this->tableNameWithAlias( $table, $alias );
1890 $tableClause .= ' ' . $this->useIndexClause(
1891 implode( ',', (array)$use_index[$alias] )
1894 $ret[] = $tableClause;
1896 $tableClause = $this->tableNameWithAlias( $table, $alias );
1898 $ret[] = $tableClause;
1902 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1903 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1904 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1906 // Compile our final table clause
1907 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
1911 * Get the name of an index in a given table.
1913 * @protected Don't use outside of DatabaseBase and childs
1914 * @param string $index
1917 public function indexName( $index ) {
1918 // @FIXME: Make this protected once we move away from PHP 5.3
1919 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
1921 // Backwards-compatibility hack
1923 'ar_usertext_timestamp' => 'usertext_timestamp',
1924 'un_user_id' => 'user_id',
1925 'un_user_ip' => 'user_ip',
1928 if ( isset( $renamed[$index] ) ) {
1929 return $renamed[$index];
1935 public function addQuotes( $s ) {
1936 if ( $s instanceof Blob
) {
1939 if ( $s === null ) {
1942 # This will also quote numeric values. This should be harmless,
1943 # and protects against weird problems that occur when they really
1944 # _are_ strings such as article titles and string->number->string
1945 # conversion is not 1:1.
1946 return "'" . $this->strencode( $s ) . "'";
1951 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1952 * MySQL uses `backticks` while basically everything else uses double quotes.
1953 * Since MySQL is the odd one out here the double quotes are our generic
1954 * and we implement backticks in DatabaseMysql.
1959 public function addIdentifierQuotes( $s ) {
1960 return '"' . str_replace( '"', '""', $s ) . '"';
1964 * Returns if the given identifier looks quoted or not according to
1965 * the database convention for quoting identifiers .
1967 * @param string $name
1970 public function isQuotedIdentifier( $name ) {
1971 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1978 protected function escapeLikeInternal( $s ) {
1979 return addcslashes( $s, '\%_' );
1982 public function buildLike() {
1983 $params = func_get_args();
1985 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1986 $params = $params[0];
1991 foreach ( $params as $value ) {
1992 if ( $value instanceof LikeMatch
) {
1993 $s .= $value->toString();
1995 $s .= $this->escapeLikeInternal( $value );
1999 return " LIKE {$this->addQuotes( $s )} ";
2002 public function anyChar() {
2003 return new LikeMatch( '_' );
2006 public function anyString() {
2007 return new LikeMatch( '%' );
2010 public function nextSequenceValue( $seqName ) {
2015 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2016 * is only needed because a) MySQL must be as efficient as possible due to
2017 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2018 * which index to pick. Anyway, other databases might have different
2019 * indexes on a given table. So don't bother overriding this unless you're
2021 * @param string $index
2024 public function useIndexClause( $index ) {
2028 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2029 $quotedTable = $this->tableName( $table );
2031 if ( count( $rows ) == 0 ) {
2036 if ( !is_array( reset( $rows ) ) ) {
2037 $rows = array( $rows );
2040 // @FXIME: this is not atomic, but a trx would break affectedRows()
2041 foreach ( $rows as $row ) {
2042 # Delete rows which collide
2043 if ( $uniqueIndexes ) {
2044 $sql = "DELETE FROM $quotedTable WHERE ";
2046 foreach ( $uniqueIndexes as $index ) {
2053 if ( is_array( $index ) ) {
2055 foreach ( $index as $col ) {
2061 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2064 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2068 $this->query( $sql, $fname );
2071 # Now insert the row
2072 $this->insert( $table, $row, $fname );
2077 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2080 * @param string $table Table name
2081 * @param array|string $rows Row(s) to insert
2082 * @param string $fname Caller function name
2084 * @return ResultWrapper
2086 protected function nativeReplace( $table, $rows, $fname ) {
2087 $table = $this->tableName( $table );
2090 if ( !is_array( reset( $rows ) ) ) {
2091 $rows = array( $rows );
2094 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2097 foreach ( $rows as $row ) {
2104 $sql .= '(' . $this->makeList( $row ) . ')';
2107 return $this->query( $sql, $fname );
2110 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2113 if ( !count( $rows ) ) {
2114 return true; // nothing to do
2117 if ( !is_array( reset( $rows ) ) ) {
2118 $rows = array( $rows );
2121 if ( count( $uniqueIndexes ) ) {
2122 $clauses = array(); // list WHERE clauses that each identify a single row
2123 foreach ( $rows as $row ) {
2124 foreach ( $uniqueIndexes as $index ) {
2125 $index = is_array( $index ) ?
$index : array( $index ); // columns
2126 $rowKey = array(); // unique key to this row
2127 foreach ( $index as $column ) {
2128 $rowKey[$column] = $row[$column];
2130 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2133 $where = array( $this->makeList( $clauses, LIST_OR
) );
2138 $useTrx = !$this->mTrxLevel
;
2140 $this->begin( $fname );
2143 # Update any existing conflicting row(s)
2144 if ( $where !== false ) {
2145 $ok = $this->update( $table, $set, $where, $fname );
2149 # Now insert any non-conflicting row(s)
2150 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2151 } catch ( Exception
$e ) {
2153 $this->rollback( $fname );
2158 $this->commit( $fname );
2164 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2168 throw new DBUnexpectedError( $this,
2169 'DatabaseBase::deleteJoin() called with empty $conds' );
2172 $delTable = $this->tableName( $delTable );
2173 $joinTable = $this->tableName( $joinTable );
2174 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2175 if ( $conds != '*' ) {
2176 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2180 $this->query( $sql, $fname );
2184 * Returns the size of a text field, or -1 for "unlimited"
2186 * @param string $table
2187 * @param string $field
2190 public function textFieldSize( $table, $field ) {
2191 $table = $this->tableName( $table );
2192 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2193 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2194 $row = $this->fetchObject( $res );
2198 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2208 * A string to insert into queries to show that they're low-priority, like
2209 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2210 * string and nothing bad should happen.
2212 * @return string Returns the text of the low priority option if it is
2213 * supported, or a blank string otherwise
2215 public function lowPriorityOption() {
2219 public function delete( $table, $conds, $fname = __METHOD__
) {
2221 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2224 $table = $this->tableName( $table );
2225 $sql = "DELETE FROM $table";
2227 if ( $conds != '*' ) {
2228 if ( is_array( $conds ) ) {
2229 $conds = $this->makeList( $conds, LIST_AND
);
2231 $sql .= ' WHERE ' . $conds;
2234 return $this->query( $sql, $fname );
2237 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2238 $fname = __METHOD__
,
2239 $insertOptions = array(), $selectOptions = array()
2241 $destTable = $this->tableName( $destTable );
2243 if ( !is_array( $insertOptions ) ) {
2244 $insertOptions = array( $insertOptions );
2247 $insertOptions = $this->makeInsertOptions( $insertOptions );
2249 if ( !is_array( $selectOptions ) ) {
2250 $selectOptions = array( $selectOptions );
2253 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2255 if ( is_array( $srcTable ) ) {
2256 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2258 $srcTable = $this->tableName( $srcTable );
2261 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2262 " SELECT $startOpts " . implode( ',', $varMap ) .
2263 " FROM $srcTable $useIndex ";
2265 if ( $conds != '*' ) {
2266 if ( is_array( $conds ) ) {
2267 $conds = $this->makeList( $conds, LIST_AND
);
2269 $sql .= " WHERE $conds";
2272 $sql .= " $tailOpts";
2274 return $this->query( $sql, $fname );
2278 * Construct a LIMIT query with optional offset. This is used for query
2279 * pages. The SQL should be adjusted so that only the first $limit rows
2280 * are returned. If $offset is provided as well, then the first $offset
2281 * rows should be discarded, and the next $limit rows should be returned.
2282 * If the result of the query is not ordered, then the rows to be returned
2283 * are theoretically arbitrary.
2285 * $sql is expected to be a SELECT, if that makes a difference.
2287 * The version provided by default works in MySQL and SQLite. It will very
2288 * likely need to be overridden for most other DBMSes.
2290 * @param string $sql SQL query we will append the limit too
2291 * @param int $limit The SQL limit
2292 * @param int|bool $offset The SQL offset (default false)
2293 * @throws DBUnexpectedError
2296 public function limitResult( $sql, $limit, $offset = false ) {
2297 if ( !is_numeric( $limit ) ) {
2298 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2301 return "$sql LIMIT "
2302 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2306 public function unionSupportsOrderAndLimit() {
2307 return true; // True for almost every DB supported
2310 public function unionQueries( $sqls, $all ) {
2311 $glue = $all ?
') UNION ALL (' : ') UNION (';
2313 return '(' . implode( $glue, $sqls ) . ')';
2316 public function conditional( $cond, $trueVal, $falseVal ) {
2317 if ( is_array( $cond ) ) {
2318 $cond = $this->makeList( $cond, LIST_AND
);
2321 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2324 public function strreplace( $orig, $old, $new ) {
2325 return "REPLACE({$orig}, {$old}, {$new})";
2328 public function getServerUptime() {
2332 public function wasDeadlock() {
2336 public function wasLockTimeout() {
2340 public function wasErrorReissuable() {
2344 public function wasReadOnlyError() {
2349 * Determines if the given query error was a connection drop
2352 * @param integer|string $errno
2355 public function wasConnectionError( $errno ) {
2360 * Perform a deadlock-prone transaction.
2362 * This function invokes a callback function to perform a set of write
2363 * queries. If a deadlock occurs during the processing, the transaction
2364 * will be rolled back and the callback function will be called again.
2367 * $dbw->deadlockLoop( callback, ... );
2369 * Extra arguments are passed through to the specified callback function.
2371 * Returns whatever the callback function returned on its successful,
2372 * iteration, or false on error, for example if the retry limit was
2375 * @throws DBUnexpectedError
2378 public function deadlockLoop() {
2379 $args = func_get_args();
2380 $function = array_shift( $args );
2381 $tries = self
::DEADLOCK_TRIES
;
2383 $this->begin( __METHOD__
);
2386 /** @var Exception $e */
2390 $retVal = call_user_func_array( $function, $args );
2392 } catch ( DBQueryError
$e ) {
2393 if ( $this->wasDeadlock() ) {
2394 // Retry after a randomized delay
2395 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
2397 // Throw the error back up
2401 } while ( --$tries > 0 );
2403 if ( $tries <= 0 ) {
2404 // Too many deadlocks; give up
2405 $this->rollback( __METHOD__
);
2408 $this->commit( __METHOD__
);
2414 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2415 # Real waits are implemented in the subclass.
2419 public function getSlavePos() {
2424 public function getMasterPos() {
2429 final public function onTransactionIdle( $callback ) {
2430 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
2431 if ( !$this->mTrxLevel
) {
2432 $this->runOnTransactionIdleCallbacks();
2436 final public function onTransactionPreCommitOrIdle( $callback ) {
2437 if ( $this->mTrxLevel
) {
2438 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
2440 $this->onTransactionIdle( $callback ); // this will trigger immediately
2445 * Actually any "on transaction idle" callbacks.
2449 protected function runOnTransactionIdleCallbacks() {
2450 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
2452 $e = $ePrior = null; // last exception
2453 do { // callbacks may add callbacks :)
2454 $callbacks = $this->mTrxIdleCallbacks
;
2455 $this->mTrxIdleCallbacks
= array(); // recursion guard
2456 foreach ( $callbacks as $callback ) {
2458 list( $phpCallback ) = $callback;
2459 $this->clearFlag( DBO_TRX
); // make each query its own transaction
2460 call_user_func( $phpCallback );
2462 $this->setFlag( DBO_TRX
); // restore automatic begin()
2464 $this->clearFlag( DBO_TRX
); // restore auto-commit
2466 } catch ( Exception
$e ) {
2468 MWExceptionHandler
::logException( $ePrior );
2471 // Some callbacks may use startAtomic/endAtomic, so make sure
2472 // their transactions are ended so other callbacks don't fail
2473 if ( $this->trxLevel() ) {
2474 $this->rollback( __METHOD__
);
2478 } while ( count( $this->mTrxIdleCallbacks
) );
2480 if ( $e instanceof Exception
) {
2481 throw $e; // re-throw any last exception
2486 * Actually any "on transaction pre-commit" callbacks.
2490 protected function runOnTransactionPreCommitCallbacks() {
2491 $e = $ePrior = null; // last exception
2492 do { // callbacks may add callbacks :)
2493 $callbacks = $this->mTrxPreCommitCallbacks
;
2494 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
2495 foreach ( $callbacks as $callback ) {
2497 list( $phpCallback ) = $callback;
2498 call_user_func( $phpCallback );
2499 } catch ( Exception
$e ) {
2501 MWExceptionHandler
::logException( $ePrior );
2506 } while ( count( $this->mTrxPreCommitCallbacks
) );
2508 if ( $e instanceof Exception
) {
2509 throw $e; // re-throw any last exception
2513 final public function startAtomic( $fname = __METHOD__
) {
2514 if ( !$this->mTrxLevel
) {
2515 $this->begin( $fname );
2516 $this->mTrxAutomatic
= true;
2517 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
2518 // in all changes being in one transaction to keep requests transactional.
2519 if ( !$this->getFlag( DBO_TRX
) ) {
2520 $this->mTrxAutomaticAtomic
= true;
2524 $this->mTrxAtomicLevels
[] = $fname;
2527 final public function endAtomic( $fname = __METHOD__
) {
2528 if ( !$this->mTrxLevel
) {
2529 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
2531 if ( !$this->mTrxAtomicLevels ||
2532 array_pop( $this->mTrxAtomicLevels
) !== $fname
2534 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
2537 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
2538 $this->commit( $fname, 'flush' );
2542 final public function doAtomicSection( $fname, $callback ) {
2543 if ( !is_callable( $callback ) ) {
2544 throw new UnexpectedValueException( "Invalid callback." );
2547 $this->startAtomic( $fname );
2549 call_user_func_array( $callback, array( $this, $fname ) );
2550 } catch ( Exception
$e ) {
2551 $this->rollback( $fname );
2554 $this->endAtomic( $fname );
2557 final public function begin( $fname = __METHOD__
) {
2558 if ( $this->mTrxLevel
) { // implicit commit
2559 if ( $this->mTrxAtomicLevels
) {
2560 // If the current transaction was an automatic atomic one, then we definitely have
2561 // a problem. Same if there is any unclosed atomic level.
2562 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2563 throw new DBUnexpectedError(
2565 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
2567 } elseif ( !$this->mTrxAutomatic
) {
2568 // We want to warn about inadvertently nested begin/commit pairs, but not about
2569 // auto-committing implicit transactions that were started by query() via DBO_TRX
2570 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2571 " performing implicit commit!";
2574 $this->getLogContext( array(
2575 'method' => __METHOD__
,
2580 // if the transaction was automatic and has done write operations
2581 if ( $this->mTrxDoneWrites
) {
2582 wfDebug( "$fname: Automatic transaction with writes in progress" .
2583 " (from {$this->mTrxFname}), performing implicit commit!\n"
2588 $this->runOnTransactionPreCommitCallbacks();
2589 $writeTime = $this->pendingWriteQueryDuration();
2590 $this->doCommit( $fname );
2591 if ( $this->mTrxDoneWrites
) {
2592 $this->mDoneWrites
= microtime( true );
2593 $this->getTransactionProfiler()->transactionWritingOut(
2594 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2596 $this->runOnTransactionIdleCallbacks();
2599 # Avoid fatals if close() was called
2600 $this->assertOpen();
2602 $this->doBegin( $fname );
2603 $this->mTrxTimestamp
= microtime( true );
2604 $this->mTrxFname
= $fname;
2605 $this->mTrxDoneWrites
= false;
2606 $this->mTrxAutomatic
= false;
2607 $this->mTrxAutomaticAtomic
= false;
2608 $this->mTrxAtomicLevels
= array();
2609 $this->mTrxIdleCallbacks
= array();
2610 $this->mTrxPreCommitCallbacks
= array();
2611 $this->mTrxShortId
= wfRandomString( 12 );
2612 $this->mTrxWriteDuration
= 0.0;
2613 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
2614 // Get an estimate of the slave lag before then, treating estimate staleness
2615 // as lag itself just to be safe
2616 $status = $this->getApproximateLagStatus();
2617 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
2621 * Issues the BEGIN command to the database server.
2623 * @see DatabaseBase::begin()
2624 * @param string $fname
2626 protected function doBegin( $fname ) {
2627 $this->query( 'BEGIN', $fname );
2628 $this->mTrxLevel
= 1;
2631 final public function commit( $fname = __METHOD__
, $flush = '' ) {
2632 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
2633 // There are still atomic sections open. This cannot be ignored
2634 $levels = implode( ', ', $this->mTrxAtomicLevels
);
2635 throw new DBUnexpectedError(
2637 "Got COMMIT while atomic sections $levels are still open"
2641 if ( $flush === 'flush' ) {
2642 if ( !$this->mTrxLevel
) {
2643 return; // nothing to do
2644 } elseif ( !$this->mTrxAutomatic
) {
2645 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
2648 if ( !$this->mTrxLevel
) {
2649 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2650 return; // nothing to do
2651 } elseif ( $this->mTrxAutomatic
) {
2652 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
2656 # Avoid fatals if close() was called
2657 $this->assertOpen();
2659 $this->runOnTransactionPreCommitCallbacks();
2660 $writeTime = $this->pendingWriteQueryDuration();
2661 $this->doCommit( $fname );
2662 if ( $this->mTrxDoneWrites
) {
2663 $this->mDoneWrites
= microtime( true );
2664 $this->getTransactionProfiler()->transactionWritingOut(
2665 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
2667 $this->runOnTransactionIdleCallbacks();
2671 * Issues the COMMIT command to the database server.
2673 * @see DatabaseBase::commit()
2674 * @param string $fname
2676 protected function doCommit( $fname ) {
2677 if ( $this->mTrxLevel
) {
2678 $this->query( 'COMMIT', $fname );
2679 $this->mTrxLevel
= 0;
2683 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
2684 if ( $flush !== 'flush' ) {
2685 if ( !$this->mTrxLevel
) {
2686 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2687 return; // nothing to do
2690 if ( !$this->mTrxLevel
) {
2691 return; // nothing to do
2695 # Avoid fatals if close() was called
2696 $this->assertOpen();
2698 $this->doRollback( $fname );
2699 $this->mTrxIdleCallbacks
= array(); // cancel
2700 $this->mTrxPreCommitCallbacks
= array(); // cancel
2701 $this->mTrxAtomicLevels
= array();
2702 if ( $this->mTrxDoneWrites
) {
2703 $this->getTransactionProfiler()->transactionWritingOut(
2704 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
2709 * Issues the ROLLBACK command to the database server.
2711 * @see DatabaseBase::rollback()
2712 * @param string $fname
2714 protected function doRollback( $fname ) {
2715 if ( $this->mTrxLevel
) {
2716 $this->query( 'ROLLBACK', $fname, true );
2717 $this->mTrxLevel
= 0;
2722 * Creates a new table with structure copied from existing table
2723 * Note that unlike most database abstraction functions, this function does not
2724 * automatically append database prefix, because it works at a lower
2725 * abstraction level.
2726 * The table names passed to this function shall not be quoted (this
2727 * function calls addIdentifierQuotes when needed).
2729 * @param string $oldName Name of table whose structure should be copied
2730 * @param string $newName Name of table to be created
2731 * @param bool $temporary Whether the new table should be temporary
2732 * @param string $fname Calling function name
2733 * @throws MWException
2734 * @return bool True if operation was successful
2736 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
2739 throw new MWException(
2740 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2743 function listTables( $prefix = null, $fname = __METHOD__
) {
2744 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2748 * Reset the views process cache set by listViews()
2751 final public function clearViewsCache() {
2752 $this->allViews
= null;
2756 * Lists all the VIEWs in the database
2758 * For caching purposes the list of all views should be stored in
2759 * $this->allViews. The process cache can be cleared with clearViewsCache()
2761 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
2762 * @param string $fname Name of calling function
2763 * @throws MWException
2767 public function listViews( $prefix = null, $fname = __METHOD__
) {
2768 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
2772 * Differentiates between a TABLE and a VIEW
2774 * @param string $name Name of the database-structure to test.
2775 * @throws MWException
2779 public function isView( $name ) {
2780 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
2783 public function timestamp( $ts = 0 ) {
2784 return wfTimestamp( TS_MW
, $ts );
2787 public function timestampOrNull( $ts = null ) {
2788 if ( is_null( $ts ) ) {
2791 return $this->timestamp( $ts );
2796 * Take the result from a query, and wrap it in a ResultWrapper if
2797 * necessary. Boolean values are passed through as is, to indicate success
2798 * of write queries or failure.
2800 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2801 * resource, and it was necessary to call this function to convert it to
2802 * a wrapper. Nowadays, raw database objects are never exposed to external
2803 * callers, so this is unnecessary in external code.
2805 * @param bool|ResultWrapper|resource|object $result
2806 * @return bool|ResultWrapper
2808 protected function resultObject( $result ) {
2811 } elseif ( $result instanceof ResultWrapper
) {
2813 } elseif ( $result === true ) {
2814 // Successful write query
2817 return new ResultWrapper( $this, $result );
2821 public function ping() {
2822 # Stub. Not essential to override.
2826 public function getSessionLagStatus() {
2827 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
2831 * Get the slave lag when the current transaction started
2833 * This is useful when transactions might use snapshot isolation
2834 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
2835 * is this lag plus transaction duration. If they don't, it is still
2836 * safe to be pessimistic. This returns null if there is no transaction.
2838 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
2841 public function getTransactionLagStatus() {
2842 return $this->mTrxLevel
2843 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
2848 * Get a slave lag estimate for this server
2850 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
2853 public function getApproximateLagStatus() {
2855 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
2856 'since' => microtime( true )
2861 * Merge the result of getSessionLagStatus() for several DBs
2862 * using the most pessimistic values to estimate the lag of
2863 * any data derived from them in combination
2865 * This is information is useful for caching modules
2867 * @see WANObjectCache::set()
2868 * @see WANObjectCache::getWithSetCallback()
2870 * @param IDatabase $db1
2871 * @param IDatabase ...
2872 * @return array Map of values:
2873 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
2874 * - since: oldest UNIX timestamp of any of the DB lag estimates
2875 * - pending: whether any of the DBs have uncommitted changes
2878 public static function getCacheSetOptions( IDatabase
$db1 ) {
2879 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
2880 foreach ( func_get_args() as $db ) {
2881 /** @var IDatabase $db */
2882 $status = $db->getSessionLagStatus();
2883 if ( $status['lag'] === false ) {
2884 $res['lag'] = false;
2885 } elseif ( $res['lag'] !== false ) {
2886 $res['lag'] = max( $res['lag'], $status['lag'] );
2888 $res['since'] = min( $res['since'], $status['since'] );
2889 $res['pending'] = $res['pending'] ?
: $db->writesPending();
2895 public function getLag() {
2899 function maxListLen() {
2903 public function encodeBlob( $b ) {
2907 public function decodeBlob( $b ) {
2908 if ( $b instanceof Blob
) {
2914 public function setSessionOptions( array $options ) {
2918 * Read and execute SQL commands from a file.
2920 * Returns true on success, error string or exception on failure (depending
2921 * on object's error ignore settings).
2923 * @param string $filename File name to open
2924 * @param bool|callable $lineCallback Optional function called before reading each line
2925 * @param bool|callable $resultCallback Optional function called for each MySQL result
2926 * @param bool|string $fname Calling function name or false if name should be
2927 * generated dynamically using $filename
2928 * @param bool|callable $inputCallback Optional function called for each
2929 * complete line sent
2930 * @throws Exception|MWException
2931 * @return bool|string
2933 public function sourceFile(
2934 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
2936 MediaWiki\
suppressWarnings();
2937 $fp = fopen( $filename, 'r' );
2938 MediaWiki\restoreWarnings
();
2940 if ( false === $fp ) {
2941 throw new MWException( "Could not open \"{$filename}\".\n" );
2945 $fname = __METHOD__
. "( $filename )";
2949 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
2950 } catch ( Exception
$e ) {
2961 * Get the full path of a patch file. Originally based on archive()
2962 * from updaters.inc. Keep in mind this always returns a patch, as
2963 * it fails back to MySQL if no DB-specific patch can be found
2965 * @param string $patch The name of the patch, like patch-something.sql
2966 * @return string Full path to patch file
2968 public function patchPath( $patch ) {
2971 $dbType = $this->getType();
2972 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2973 return "$IP/maintenance/$dbType/archives/$patch";
2975 return "$IP/maintenance/archives/$patch";
2979 public function setSchemaVars( $vars ) {
2980 $this->mSchemaVars
= $vars;
2984 * Read and execute commands from an open file handle.
2986 * Returns true on success, error string or exception on failure (depending
2987 * on object's error ignore settings).
2989 * @param resource $fp File handle
2990 * @param bool|callable $lineCallback Optional function called before reading each query
2991 * @param bool|callable $resultCallback Optional function called for each MySQL result
2992 * @param string $fname Calling function name
2993 * @param bool|callable $inputCallback Optional function called for each complete query sent
2994 * @return bool|string
2996 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
2997 $fname = __METHOD__
, $inputCallback = false
3001 while ( !feof( $fp ) ) {
3002 if ( $lineCallback ) {
3003 call_user_func( $lineCallback );
3006 $line = trim( fgets( $fp ) );
3008 if ( $line == '' ) {
3012 if ( '-' == $line[0] && '-' == $line[1] ) {
3020 $done = $this->streamStatementEnd( $cmd, $line );
3024 if ( $done ||
feof( $fp ) ) {
3025 $cmd = $this->replaceVars( $cmd );
3027 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3028 $res = $this->query( $cmd, $fname );
3030 if ( $resultCallback ) {
3031 call_user_func( $resultCallback, $res, $this );
3034 if ( false === $res ) {
3035 $err = $this->lastError();
3037 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3048 * Called by sourceStream() to check if we've reached a statement end
3050 * @param string $sql SQL assembled so far
3051 * @param string $newLine New line about to be added to $sql
3052 * @return bool Whether $newLine contains end of the statement
3054 public function streamStatementEnd( &$sql, &$newLine ) {
3055 if ( $this->delimiter
) {
3057 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3058 if ( $newLine != $prev ) {
3067 * Database independent variable replacement. Replaces a set of variables
3068 * in an SQL statement with their contents as given by $this->getSchemaVars().
3070 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3072 * - '{$var}' should be used for text and is passed through the database's
3074 * - `{$var}` should be used for identifiers (e.g. table and database names).
3075 * It is passed through the database's addIdentifierQuotes method which
3076 * can be overridden if the database uses something other than backticks.
3077 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3078 * database's tableName method.
3079 * - / *i* / passes the name that follows through the database's indexName method.
3080 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3081 * its use should be avoided. In 1.24 and older, string encoding was applied.
3083 * @param string $ins SQL statement to replace variables in
3084 * @return string The new SQL statement with variables replaced
3086 protected function replaceVars( $ins ) {
3088 $vars = $this->getSchemaVars();
3089 return preg_replace_callback(
3091 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3092 \'\{\$ (\w+) }\' | # 3. addQuotes
3093 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3094 /\*\$ (\w+) \*/ # 5. leave unencoded
3096 function ( $m ) use ( $that, $vars ) {
3097 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3098 // check for both nonexistent keys *and* the empty string.
3099 if ( isset( $m[1] ) && $m[1] !== '' ) {
3100 if ( $m[1] === 'i' ) {
3101 return $that->indexName( $m[2] );
3103 return $that->tableName( $m[2] );
3105 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
3106 return $that->addQuotes( $vars[$m[3]] );
3107 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
3108 return $that->addIdentifierQuotes( $vars[$m[4]] );
3109 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
3110 return $vars[$m[5]];
3120 * Get schema variables. If none have been set via setSchemaVars(), then
3121 * use some defaults from the current object.
3125 protected function getSchemaVars() {
3126 if ( $this->mSchemaVars
) {
3127 return $this->mSchemaVars
;
3129 return $this->getDefaultSchemaVars();
3134 * Get schema variables to use if none have been set via setSchemaVars().
3136 * Override this in derived classes to provide variables for tables.sql
3137 * and SQL patch files.
3141 protected function getDefaultSchemaVars() {
3145 public function lockIsFree( $lockName, $method ) {
3149 public function lock( $lockName, $method, $timeout = 5 ) {
3153 public function unlock( $lockName, $method ) {
3157 public function namedLocksEnqueue() {
3162 * Lock specific tables
3164 * @param array $read Array of tables to lock for read access
3165 * @param array $write Array of tables to lock for write access
3166 * @param string $method Name of caller
3167 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
3170 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3175 * Unlock specific tables
3177 * @param string $method The caller
3180 public function unlockTables( $method ) {
3186 * @param string $tableName
3187 * @param string $fName
3188 * @return bool|ResultWrapper
3191 public function dropTable( $tableName, $fName = __METHOD__
) {
3192 if ( !$this->tableExists( $tableName, $fName ) ) {
3195 $sql = "DROP TABLE " . $this->tableName( $tableName );
3196 if ( $this->cascadingDeletes() ) {
3200 return $this->query( $sql, $fName );
3204 * Get search engine class. All subclasses of this need to implement this
3205 * if they wish to use searching.
3209 public function getSearchEngine() {
3210 return 'SearchEngineDummy';
3213 public function getInfinity() {
3217 public function encodeExpiry( $expiry ) {
3218 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3219 ?
$this->getInfinity()
3220 : $this->timestamp( $expiry );
3223 public function decodeExpiry( $expiry, $format = TS_MW
) {
3224 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3226 : wfTimestamp( $format, $expiry );
3229 public function setBigSelects( $value = true ) {
3233 public function isReadOnly() {
3234 return ( $this->getReadOnlyReason() !== false );
3238 * @return string|bool Reason this DB is read-only or false if it is not
3240 protected function getReadOnlyReason() {
3241 $reason = $this->getLBInfo( 'readOnlyReason' );
3243 return is_string( $reason ) ?
$reason : false;
3250 public function __toString() {
3251 return (string)$this->mConn
;
3255 * Run a few simple sanity checks
3257 public function __destruct() {
3258 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
3259 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
3261 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
3263 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
3264 $callers[] = $callbackInfo[1];
3266 $callers = implode( ', ', $callers );
3267 trigger_error( "DB transaction callbacks still pending (from $callers)." );
3275 abstract class Database
extends DatabaseBase
{
3276 // B/C until nothing type hints for DatabaseBase
3277 // @TODO: finish renaming DatabaseBase => Database