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;
170 * A string describing the current software version, and possibly
171 * other details in a user-friendly way. Will be listed on Special:Version, etc.
172 * Use getServerVersion() to get machine-friendly information.
174 * @return string Version information from the database server
176 public function getServerInfo() {
177 return $this->getServerVersion();
181 * @return string Command delimiter used by this database engine
183 public function getDelimiter() {
184 return $this->delimiter
;
188 * Boolean, controls output of large amounts of debug information.
189 * @param bool|null $debug
190 * - true to enable debugging
191 * - false to disable debugging
192 * - omitted or null to do nothing
194 * @return bool|null Previous value of the flag
196 public function debug( $debug = null ) {
197 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
201 * Turns buffering of SQL result sets on (true) or off (false). Default is
204 * Unbuffered queries are very troublesome in MySQL:
206 * - If another query is executed while the first query is being read
207 * out, the first query is killed. This means you can't call normal
208 * MediaWiki functions while you are reading an unbuffered query result
209 * from a normal wfGetDB() connection.
211 * - Unbuffered queries cause the MySQL server to use large amounts of
212 * memory and to hold broad locks which block other queries.
214 * If you want to limit client-side memory, it's almost always better to
215 * split up queries into batches using a LIMIT clause than to switch off
218 * @param null|bool $buffer
219 * @return null|bool The previous value of the flag
221 public function bufferResults( $buffer = null ) {
222 if ( is_null( $buffer ) ) {
223 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
225 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
230 * Turns on (false) or off (true) the automatic generation and sending
231 * of a "we're sorry, but there has been a database error" page on
232 * database errors. Default is on (false). When turned off, the
233 * code should use lastErrno() and lastError() to handle the
234 * situation as appropriate.
236 * Do not use this function outside of the Database classes.
238 * @param null|bool $ignoreErrors
239 * @return bool The previous value of the flag.
241 protected function ignoreErrors( $ignoreErrors = null ) {
242 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
246 * Gets the current transaction level.
248 * Historically, transactions were allowed to be "nested". This is no
249 * longer supported, so this function really only returns a boolean.
251 * @return int The previous value
253 public function trxLevel() {
254 return $this->mTrxLevel
;
258 * Get the UNIX timestamp of the time that the transaction was established
260 * This can be used to reason about the staleness of SELECT data
261 * in REPEATABLE-READ transaction isolation level.
263 * @return float|null Returns null if there is not active transaction
266 public function trxTimestamp() {
267 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
271 * Get/set the table prefix.
272 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
273 * @return string The previous table prefix.
275 public function tablePrefix( $prefix = null ) {
276 return wfSetVar( $this->mTablePrefix
, $prefix );
280 * Get/set the db schema.
281 * @param string $schema The database schema to set, or omitted to leave it unchanged.
282 * @return string The previous db schema.
284 public function dbSchema( $schema = null ) {
285 return wfSetVar( $this->mSchema
, $schema );
289 * Set the filehandle to copy write statements to.
291 * @param resource $fh File handle
293 public function setFileHandle( $fh ) {
294 $this->fileHandle
= $fh;
298 * Get properties passed down from the server info array of the load
301 * @param string $name The entry of the info array to get, or null to get the
304 * @return array|mixed|null
306 public function getLBInfo( $name = null ) {
307 if ( is_null( $name ) ) {
308 return $this->mLBInfo
;
310 if ( array_key_exists( $name, $this->mLBInfo
) ) {
311 return $this->mLBInfo
[$name];
319 * Set the LB info array, or a member of it. If called with one parameter,
320 * the LB info array is set to that parameter. If it is called with two
321 * parameters, the member with the given name is set to the given value.
323 * @param string $name
324 * @param array $value
326 public function setLBInfo( $name, $value = null ) {
327 if ( is_null( $value ) ) {
328 $this->mLBInfo
= $name;
330 $this->mLBInfo
[$name] = $value;
335 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
337 * @param IDatabase $conn
340 public function setLazyMasterHandle( IDatabase
$conn ) {
341 $this->lazyMasterHandle
= $conn;
345 * @return IDatabase|null
346 * @see setLazyMasterHandle()
349 public function getLazyMasterHandle() {
350 return $this->lazyMasterHandle
;
354 * @return TransactionProfiler
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
359 : Profiler
::instance()->getTransactionProfiler();
363 * Returns true if this database supports (and uses) cascading deletes
367 public function cascadingDeletes() {
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
376 public function cleanupTriggers() {
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
386 public function strictIPs() {
391 * Returns true if this database uses timestamps rather than integers
395 public function realTimestamps() {
400 * Returns true if this database does an implicit sort when doing GROUP BY
404 public function implicitGroupby() {
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
414 public function implicitOrderby() {
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
424 public function searchableIPs() {
429 * Returns true if this database can use functional indexes
433 public function functionalIndexes() {
438 * Return the last query that went through DatabaseBase::query()
441 public function lastQuery() {
442 return $this->mLastQuery
;
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites
;
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
459 * @return int|float UNIX timestamp or false
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?
: false;
467 * @return bool Whether there is a transaction open with possible write queries
470 public function writesPending() {
471 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
475 * Returns true if there is a transaction open with possible write
476 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
480 public function writesOrCallbacksPending() {
481 return $this->mTrxLevel
&& (
482 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
487 * Get the time spend running write queries for this
489 * High times could be due to scanning, updates, locking, and such
491 * @return float|bool Returns false if not transaction is active
494 public function pendingWriteQueryDuration() {
495 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
499 * Is a connection to the database open?
502 public function isOpen() {
503 return $this->mOpened
;
507 * Set a flag for this connection
509 * @param int $flag DBO_* constants from Defines.php:
510 * - DBO_DEBUG: output some debug info (same as debug())
511 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
512 * - DBO_TRX: automatically start transactions
513 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
514 * and removes it in command line mode
515 * - DBO_PERSISTENT: use persistant database connection
517 public function setFlag( $flag ) {
518 $this->mFlags |
= $flag;
522 * Clear a flag for this connection
524 * @param int $flag DBO_* constants from Defines.php:
525 * - DBO_DEBUG: output some debug info (same as debug())
526 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
527 * - DBO_TRX: automatically start transactions
528 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
529 * and removes it in command line mode
530 * - DBO_PERSISTENT: use persistant database connection
532 public function clearFlag( $flag ) {
533 $this->mFlags
&= ~
$flag;
537 * Returns a boolean whether the flag $flag is set for this connection
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags
& $flag );
551 * General read-only accessor
553 * @param string $name
556 public function getProperty( $name ) {
563 public function getWikiID() {
564 if ( $this->mTablePrefix
) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
567 return $this->mDBname
;
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
575 * @param string $filename
578 private function getSqlFilePath( $filename ) {
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
584 return "$IP/maintenance/$filename";
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
609 * Get information about an index into an object
610 * @param string $table Table name
611 * @param string $index Index name
612 * @param string $fname Calling function name
613 * @return mixed Database-specific index description class or false if the index does not exist
615 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
618 * Wrapper for addslashes()
620 * @param string $s String to be slashed.
621 * @return string Slashed string.
623 abstract function strencode( $s );
628 * FIXME: It is possible to construct a Database object with no associated
629 * connection object, by specifying no parameters to __construct(). This
630 * feature is deprecated and should be removed.
632 * DatabaseBase subclasses should not be constructed directly in external
633 * code. DatabaseBase::factory() should be used instead.
635 * @param array $params Parameters passed from DatabaseBase::factory()
637 function __construct( array $params ) {
638 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
640 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
642 $server = $params['host'];
643 $user = $params['user'];
644 $password = $params['password'];
645 $dbName = $params['dbname'];
646 $flags = $params['flags'];
647 $tablePrefix = $params['tablePrefix'];
648 $schema = $params['schema'];
649 $foreign = $params['foreign'];
651 $this->mFlags
= $flags;
652 if ( $this->mFlags
& DBO_DEFAULT
) {
653 if ( $wgCommandLineMode ) {
654 $this->mFlags
&= ~DBO_TRX
;
656 $this->mFlags |
= DBO_TRX
;
660 $this->mSessionVars
= $params['variables'];
662 /** Get the default table prefix*/
663 if ( $tablePrefix === 'get from global' ) {
664 $this->mTablePrefix
= $wgDBprefix;
666 $this->mTablePrefix
= $tablePrefix;
669 /** Get the database schema*/
670 if ( $schema === 'get from global' ) {
671 $this->mSchema
= $wgDBmwschema;
673 $this->mSchema
= $schema;
676 $this->mForeign
= $foreign;
678 if ( isset( $params['trxProfiler'] ) ) {
679 $this->trxProfiler
= $params['trxProfiler']; // override
683 $this->open( $server, $user, $password, $dbName );
688 * Called by serialize. Throw an exception when DB connection is serialized.
689 * This causes problems on some database engines because the connection is
690 * not restored on unserialize.
692 public function __sleep() {
693 throw new MWException( 'Database serialization may cause problems, since ' .
694 'the connection is not restored on wakeup.' );
698 * Given a DB type, construct the name of the appropriate child class of
699 * DatabaseBase. This is designed to replace all of the manual stuff like:
700 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
701 * as well as validate against the canonical list of DB types we have
703 * This factory function is mostly useful for when you need to connect to a
704 * database other than the MediaWiki default (such as for external auth,
705 * an extension, et cetera). Do not use this to connect to the MediaWiki
706 * database. Example uses in core:
707 * @see LoadBalancer::reallyOpenConnection()
708 * @see ForeignDBRepo::getMasterDB()
709 * @see WebInstallerDBConnect::execute()
713 * @param string $dbType A possible DB type
714 * @param array $p An array of options to pass to the constructor.
715 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
716 * @throws MWException If the database driver or extension cannot be found
717 * @return DatabaseBase|null DatabaseBase subclass or null
719 final public static function factory( $dbType, $p = array() ) {
720 $canonicalDBTypes = array(
721 'mysql' => array( 'mysqli', 'mysql' ),
722 'postgres' => array(),
729 $dbType = strtolower( $dbType );
730 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
731 $possibleDrivers = $canonicalDBTypes[$dbType];
732 if ( !empty( $p['driver'] ) ) {
733 if ( in_array( $p['driver'], $possibleDrivers ) ) {
734 $driver = $p['driver'];
736 throw new MWException( __METHOD__
.
737 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
740 foreach ( $possibleDrivers as $posDriver ) {
741 if ( extension_loaded( $posDriver ) ) {
742 $driver = $posDriver;
750 if ( $driver === false ) {
751 throw new MWException( __METHOD__
.
752 " no viable database extension found for type '$dbType'" );
755 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
756 // and everything else doesn't use a schema (e.g. null)
757 // Although postgres and oracle support schemas, we don't use them (yet)
758 // to maintain backwards compatibility
759 $defaultSchemas = array(
760 'mssql' => 'get from global',
763 $class = 'Database' . ucfirst( $driver );
764 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
765 // Resolve some defaults for b/c
766 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
767 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
768 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
769 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
770 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
771 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
772 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
773 if ( !isset( $p['schema'] ) ) {
774 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
776 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
778 return new $class( $p );
784 protected function installErrorHandler() {
785 $this->mPHPError
= false;
786 $this->htmlErrors
= ini_set( 'html_errors', '0' );
787 set_error_handler( array( $this, 'connectionErrorHandler' ) );
791 * @return bool|string
793 protected function restoreErrorHandler() {
794 restore_error_handler();
795 if ( $this->htmlErrors
!== false ) {
796 ini_set( 'html_errors', $this->htmlErrors
);
798 if ( $this->mPHPError
) {
799 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
800 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
810 * @param string $errstr
812 public function connectionErrorHandler( $errno, $errstr ) {
813 $this->mPHPError
= $errstr;
817 * Create a log context to pass to wfLogDBError or other logging functions.
819 * @param array $extras Additional data to add to context
822 protected function getLogContext( array $extras = array() ) {
825 'db_server' => $this->mServer
,
826 'db_name' => $this->mDBname
,
827 'db_user' => $this->mUser
,
834 * Closes a database connection.
835 * if it is open : commits any open transactions
837 * @throws MWException
838 * @return bool Operation success. true if already closed.
840 public function close() {
841 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
842 throw new MWException( "Transaction idle callbacks still pending." );
844 if ( $this->mConn
) {
845 if ( $this->trxLevel() ) {
846 if ( !$this->mTrxAutomatic
) {
847 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
848 " performing implicit commit before closing connection!" );
851 $this->commit( __METHOD__
, 'flush' );
854 $closed = $this->closeConnection();
855 $this->mConn
= false;
859 $this->mOpened
= false;
865 * Make sure isOpen() returns true as a sanity check
867 * @throws DBUnexpectedError
869 protected function assertOpen() {
870 if ( !$this->isOpen() ) {
871 throw new DBUnexpectedError( $this, "DB connection was already closed." );
876 * Closes underlying database connection
878 * @return bool Whether connection was closed successfully
880 abstract protected function closeConnection();
883 * @param string $error Fallback error message, used if none is given by DB
884 * @throws DBConnectionError
886 function reportConnectionError( $error = 'Unknown error' ) {
887 $myError = $this->lastError();
893 throw new DBConnectionError( $this, $error );
897 * The DBMS-dependent part of query()
899 * @param string $sql SQL query.
900 * @return ResultWrapper|bool Result object to feed to fetchObject,
901 * fetchRow, ...; or false on failure
903 abstract protected function doQuery( $sql );
906 * Determine whether a query writes to the DB.
907 * Should return true if unsure.
912 protected function isWriteQuery( $sql ) {
913 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
917 * Determine whether a SQL statement is sensitive to isolation level.
918 * A SQL statement is considered transactable if its result could vary
919 * depending on the transaction isolation level. Operational commands
920 * such as 'SET' and 'SHOW' are not considered to be transactable.
925 protected function isTransactableQuery( $sql ) {
926 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
927 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
931 * Run an SQL query and return the result. Normally throws a DBQueryError
932 * on failure. If errors are ignored, returns false instead.
934 * In new code, the query wrappers select(), insert(), update(), delete(),
935 * etc. should be used where possible, since they give much better DBMS
936 * independence and automatically quote or validate user input in a variety
937 * of contexts. This function is generally only useful for queries which are
938 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
941 * However, the query wrappers themselves should call this function.
943 * @param string $sql SQL query
944 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
945 * comment (you can use __METHOD__ or add some extra info)
946 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
947 * maybe best to catch the exception instead?
948 * @throws MWException
949 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
950 * for a successful read query, or false on failure if $tempIgnore set
952 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
955 $this->mLastQuery
= $sql;
957 $isWriteQuery = $this->isWriteQuery( $sql );
958 if ( $isWriteQuery ) {
959 $reason = $this->getReadOnlyReason();
960 if ( $reason !== false ) {
961 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
963 # Set a flag indicating that writes have been done
964 $this->mDoneWrites
= microtime( true );
967 # Add a comment for easy SHOW PROCESSLIST interpretation
968 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
969 $userName = $wgUser->getName();
970 if ( mb_strlen( $userName ) > 15 ) {
971 $userName = mb_substr( $userName, 0, 15 ) . '...';
973 $userName = str_replace( '/', '', $userName );
978 // Add trace comment to the begin of the sql string, right after the operator.
979 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
980 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
982 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
983 $this->begin( __METHOD__
. " ($fname)" );
984 $this->mTrxAutomatic
= true;
987 # Keep track of whether the transaction has write queries pending
988 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
989 $this->mTrxDoneWrites
= true;
990 $this->getTransactionProfiler()->transactionWritingIn(
991 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
994 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
995 # generalizeSQL will probably cut down the query to reasonable
996 # logging size most of the time. The substr is really just a sanity check.
998 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
999 $totalProf = 'DatabaseBase::query-master';
1001 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1002 $totalProf = 'DatabaseBase::query';
1004 # Include query transaction state
1005 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1007 $profiler = Profiler
::instance();
1008 if ( !$profiler instanceof ProfilerStub
) {
1009 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1010 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1013 if ( $this->debug() ) {
1014 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
1017 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1019 # Avoid fatals if close() was called
1020 $this->assertOpen();
1022 # Do the query and handle errors
1023 $startTime = microtime( true );
1024 $ret = $this->doQuery( $commentedSql );
1025 $queryRuntime = microtime( true ) - $startTime;
1026 # Log the query time and feed it into the DB trx profiler
1027 $this->getTransactionProfiler()->recordQueryCompletion(
1028 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1030 MWDebug
::queryTime( $queryId );
1032 # Try reconnecting if the connection was lost
1033 if ( false === $ret && $this->wasErrorReissuable() ) {
1034 # Transaction is gone, like it or not
1035 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1036 $this->mTrxLevel
= 0;
1037 $this->mTrxIdleCallbacks
= array(); // bug 65263
1038 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1039 wfDebug( "Connection lost, reconnecting...\n" );
1040 # Stash the last error values since ping() might clear them
1041 $lastError = $this->lastError();
1042 $lastErrno = $this->lastErrno();
1043 if ( $this->ping() ) {
1044 wfDebug( "Reconnected\n" );
1045 $server = $this->getServer();
1046 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1047 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1050 # Leave $ret as false and let an error be reported.
1051 # Callers may catch the exception and continue to use the DB.
1052 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1054 # Should be safe to silently retry (no trx and thus no callbacks)
1055 $startTime = microtime( true );
1056 $ret = $this->doQuery( $commentedSql );
1057 $queryRuntime = microtime( true ) - $startTime;
1058 # Log the query time and feed it into the DB trx profiler
1059 $this->getTransactionProfiler()->recordQueryCompletion(
1060 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1063 wfDebug( "Failed\n" );
1067 if ( false === $ret ) {
1068 $this->reportQueryError(
1069 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1072 $res = $this->resultObject( $ret );
1074 // Destroy profile sections in the opposite order to their creation
1075 ScopedCallback
::consume( $queryProfSection );
1076 ScopedCallback
::consume( $totalProfSection );
1078 if ( $isWriteQuery && $this->mTrxLevel
) {
1079 $this->mTrxWriteDuration +
= $queryRuntime;
1086 * Report a query error. Log the error, and if neither the object ignore
1087 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1089 * @param string $error
1091 * @param string $sql
1092 * @param string $fname
1093 * @param bool $tempIgnore
1094 * @throws DBQueryError
1096 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1097 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1098 wfDebug( "SQL ERROR (ignored): $error\n" );
1100 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1102 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1103 $this->getLogContext( array(
1104 'method' => __METHOD__
,
1107 'sql1line' => $sql1line,
1111 wfDebug( "SQL ERROR: " . $error . "\n" );
1112 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1117 * Intended to be compatible with the PEAR::DB wrapper functions.
1118 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1120 * ? = scalar value, quoted as necessary
1121 * ! = raw SQL bit (a function for instance)
1122 * & = filename; reads the file and inserts as a blob
1123 * (we don't use this though...)
1125 * @param string $sql
1126 * @param string $func
1130 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1131 /* MySQL doesn't support prepared statements (yet), so just
1132 * pack up the query for reference. We'll manually replace
1135 return array( 'query' => $sql, 'func' => $func );
1139 * Free a prepared query, generated by prepare().
1140 * @param string $prepared
1142 protected function freePrepared( $prepared ) {
1143 /* No-op by default */
1147 * Execute a prepared query with the various arguments
1148 * @param string $prepared The prepared sql
1149 * @param mixed $args Either an array here, or put scalars as varargs
1151 * @return ResultWrapper
1153 public function execute( $prepared, $args = null ) {
1154 if ( !is_array( $args ) ) {
1156 $args = func_get_args();
1157 array_shift( $args );
1160 $sql = $this->fillPrepared( $prepared['query'], $args );
1162 return $this->query( $sql, $prepared['func'] );
1166 * For faking prepared SQL statements on DBs that don't support it directly.
1168 * @param string $preparedQuery A 'preparable' SQL statement
1169 * @param array $args Array of Arguments to fill it with
1170 * @return string Executable SQL
1172 public function fillPrepared( $preparedQuery, $args ) {
1174 $this->preparedArgs
=& $args;
1176 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1177 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1181 * preg_callback func for fillPrepared()
1182 * The arguments should be in $this->preparedArgs and must not be touched
1183 * while we're doing this.
1185 * @param array $matches
1186 * @throws DBUnexpectedError
1189 protected function fillPreparedArg( $matches ) {
1190 switch ( $matches[1] ) {
1199 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1201 switch ( $matches[1] ) {
1203 return $this->addQuotes( $arg );
1207 # return $this->addQuotes( file_get_contents( $arg ) );
1208 throw new DBUnexpectedError(
1210 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1213 throw new DBUnexpectedError(
1215 'Received invalid match. This should never happen!'
1221 * Free a result object returned by query() or select(). It's usually not
1222 * necessary to call this, just use unset() or let the variable holding
1223 * the result object go out of scope.
1225 * @param mixed $res A SQL result
1227 public function freeResult( $res ) {
1231 * A SELECT wrapper which returns a single field from a single result row.
1233 * Usually throws a DBQueryError on failure. If errors are explicitly
1234 * ignored, returns false on failure.
1236 * If no result rows are returned from the query, false is returned.
1238 * @param string|array $table Table name. See DatabaseBase::select() for details.
1239 * @param string $var The field name to select. This must be a valid SQL
1240 * fragment: do not use unvalidated user input.
1241 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1242 * @param string $fname The function name of the caller.
1243 * @param string|array $options The query options. See DatabaseBase::select() for details.
1245 * @return bool|mixed The value from the field, or false on failure.
1246 * @throws DBUnexpectedError
1248 public function selectField(
1249 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1251 if ( $var === '*' ) { // sanity
1252 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1255 if ( !is_array( $options ) ) {
1256 $options = array( $options );
1259 $options['LIMIT'] = 1;
1261 $res = $this->select( $table, $var, $cond, $fname, $options );
1262 if ( $res === false ||
!$this->numRows( $res ) ) {
1266 $row = $this->fetchRow( $res );
1268 if ( $row !== false ) {
1269 return reset( $row );
1276 * A SELECT wrapper which returns a list of single field values from result rows.
1278 * Usually throws a DBQueryError on failure. If errors are explicitly
1279 * ignored, returns false on failure.
1281 * If no result rows are returned from the query, false is returned.
1283 * @param string|array $table Table name. See DatabaseBase::select() for details.
1284 * @param string $var The field name to select. This must be a valid SQL
1285 * fragment: do not use unvalidated user input.
1286 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1287 * @param string $fname The function name of the caller.
1288 * @param string|array $options The query options. See DatabaseBase::select() for details.
1290 * @return bool|array The values from the field, or false on failure
1291 * @throws DBUnexpectedError
1294 public function selectFieldValues(
1295 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1297 if ( $var === '*' ) { // sanity
1298 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1301 if ( !is_array( $options ) ) {
1302 $options = array( $options );
1305 $res = $this->select( $table, $var, $cond, $fname, $options );
1306 if ( $res === false ) {
1311 foreach ( $res as $row ) {
1312 $values[] = $row->$var;
1319 * Returns an optional USE INDEX clause to go after the table, and a
1320 * string to go at the end of the query.
1322 * @param array $options Associative array of options to be turned into
1323 * an SQL query, valid keys are listed in the function.
1325 * @see DatabaseBase::select()
1327 public function makeSelectOptions( $options ) {
1328 $preLimitTail = $postLimitTail = '';
1331 $noKeyOptions = array();
1333 foreach ( $options as $key => $option ) {
1334 if ( is_numeric( $key ) ) {
1335 $noKeyOptions[$option] = true;
1339 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1341 $preLimitTail .= $this->makeOrderBy( $options );
1343 // if (isset($options['LIMIT'])) {
1344 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1345 // isset($options['OFFSET']) ? $options['OFFSET']
1349 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1350 $postLimitTail .= ' FOR UPDATE';
1353 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1354 $postLimitTail .= ' LOCK IN SHARE MODE';
1357 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1358 $startOpts .= 'DISTINCT';
1361 # Various MySQL extensions
1362 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1363 $startOpts .= ' /*! STRAIGHT_JOIN */';
1366 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1367 $startOpts .= ' HIGH_PRIORITY';
1370 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1371 $startOpts .= ' SQL_BIG_RESULT';
1374 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1375 $startOpts .= ' SQL_BUFFER_RESULT';
1378 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1379 $startOpts .= ' SQL_SMALL_RESULT';
1382 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1383 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1386 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1387 $startOpts .= ' SQL_CACHE';
1390 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1391 $startOpts .= ' SQL_NO_CACHE';
1394 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1395 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1400 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1404 * Returns an optional GROUP BY with an optional HAVING
1406 * @param array $options Associative array of options
1408 * @see DatabaseBase::select()
1411 public function makeGroupByWithHaving( $options ) {
1413 if ( isset( $options['GROUP BY'] ) ) {
1414 $gb = is_array( $options['GROUP BY'] )
1415 ?
implode( ',', $options['GROUP BY'] )
1416 : $options['GROUP BY'];
1417 $sql .= ' GROUP BY ' . $gb;
1419 if ( isset( $options['HAVING'] ) ) {
1420 $having = is_array( $options['HAVING'] )
1421 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1422 : $options['HAVING'];
1423 $sql .= ' HAVING ' . $having;
1430 * Returns an optional ORDER BY
1432 * @param array $options Associative array of options
1434 * @see DatabaseBase::select()
1437 public function makeOrderBy( $options ) {
1438 if ( isset( $options['ORDER BY'] ) ) {
1439 $ob = is_array( $options['ORDER BY'] )
1440 ?
implode( ',', $options['ORDER BY'] )
1441 : $options['ORDER BY'];
1443 return ' ORDER BY ' . $ob;
1450 * Execute a SELECT query constructed using the various parameters provided.
1451 * See below for full details of the parameters.
1453 * @param string|array $table Table name
1454 * @param string|array $vars Field names
1455 * @param string|array $conds Conditions
1456 * @param string $fname Caller function name
1457 * @param array $options Query options
1458 * @param array $join_conds Join conditions
1461 * @param string|array $table
1463 * May be either an array of table names, or a single string holding a table
1464 * name. If an array is given, table aliases can be specified, for example:
1466 * array( 'a' => 'user' )
1468 * This includes the user table in the query, with the alias "a" available
1469 * for use in field names (e.g. a.user_name).
1471 * All of the table names given here are automatically run through
1472 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1473 * added, and various other table name mappings to be performed.
1476 * @param string|array $vars
1478 * May be either a field name or an array of field names. The field names
1479 * can be complete fragments of SQL, for direct inclusion into the SELECT
1480 * query. If an array is given, field aliases can be specified, for example:
1482 * array( 'maxrev' => 'MAX(rev_id)' )
1484 * This includes an expression with the alias "maxrev" in the query.
1486 * If an expression is given, care must be taken to ensure that it is
1490 * @param string|array $conds
1492 * May be either a string containing a single condition, or an array of
1493 * conditions. If an array is given, the conditions constructed from each
1494 * element are combined with AND.
1496 * Array elements may take one of two forms:
1498 * - Elements with a numeric key are interpreted as raw SQL fragments.
1499 * - Elements with a string key are interpreted as equality conditions,
1500 * where the key is the field name.
1501 * - If the value of such an array element is a scalar (such as a
1502 * string), it will be treated as data and thus quoted appropriately.
1503 * If it is null, an IS NULL clause will be added.
1504 * - If the value is an array, an IN (...) clause will be constructed
1505 * from its non-null elements, and an IS NULL clause will be added
1506 * if null is present, such that the field may match any of the
1507 * elements in the array. The non-null elements will be quoted.
1509 * Note that expressions are often DBMS-dependent in their syntax.
1510 * DBMS-independent wrappers are provided for constructing several types of
1511 * expression commonly used in condition queries. See:
1512 * - DatabaseBase::buildLike()
1513 * - DatabaseBase::conditional()
1516 * @param string|array $options
1518 * Optional: Array of query options. Boolean options are specified by
1519 * including them in the array as a string value with a numeric key, for
1522 * array( 'FOR UPDATE' )
1524 * The supported options are:
1526 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1527 * with LIMIT can theoretically be used for paging through a result set,
1528 * but this is discouraged in MediaWiki for performance reasons.
1530 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1531 * and then the first rows are taken until the limit is reached. LIMIT
1532 * is applied to a result set after OFFSET.
1534 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1535 * changed until the next COMMIT.
1537 * - DISTINCT: Boolean: return only unique result rows.
1539 * - GROUP BY: May be either an SQL fragment string naming a field or
1540 * expression to group by, or an array of such SQL fragments.
1542 * - HAVING: May be either an string containing a HAVING clause or an array of
1543 * conditions building the HAVING clause. If an array is given, the conditions
1544 * constructed from each element are combined with AND.
1546 * - ORDER BY: May be either an SQL fragment giving a field name or
1547 * expression to order by, or an array of such SQL fragments.
1549 * - USE INDEX: This may be either a string giving the index name to use
1550 * for the query, or an array. If it is an associative array, each key
1551 * gives the table name (or alias), each value gives the index name to
1552 * use for that table. All strings are SQL fragments and so should be
1553 * validated by the caller.
1555 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1556 * instead of SELECT.
1558 * And also the following boolean MySQL extensions, see the MySQL manual
1559 * for documentation:
1561 * - LOCK IN SHARE MODE
1565 * - SQL_BUFFER_RESULT
1566 * - SQL_SMALL_RESULT
1567 * - SQL_CALC_FOUND_ROWS
1572 * @param string|array $join_conds
1574 * Optional associative array of table-specific join conditions. In the
1575 * most common case, this is unnecessary, since the join condition can be
1576 * in $conds. However, it is useful for doing a LEFT JOIN.
1578 * The key of the array contains the table name or alias. The value is an
1579 * array with two elements, numbered 0 and 1. The first gives the type of
1580 * join, the second is an SQL fragment giving the join condition for that
1581 * table. For example:
1583 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1585 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1586 * with no rows in it will be returned. If there was a query error, a
1587 * DBQueryError exception will be thrown, except if the "ignore errors"
1588 * option was set, in which case false will be returned.
1590 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1591 $options = array(), $join_conds = array() ) {
1592 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1594 return $this->query( $sql, $fname );
1598 * The equivalent of DatabaseBase::select() except that the constructed SQL
1599 * is returned, instead of being immediately executed. This can be useful for
1600 * doing UNION queries, where the SQL text of each query is needed. In general,
1601 * however, callers outside of Database classes should just use select().
1603 * @param string|array $table Table name
1604 * @param string|array $vars Field names
1605 * @param string|array $conds Conditions
1606 * @param string $fname Caller function name
1607 * @param string|array $options Query options
1608 * @param string|array $join_conds Join conditions
1610 * @return string SQL query string.
1611 * @see DatabaseBase::select()
1613 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1614 $options = array(), $join_conds = array()
1616 if ( is_array( $vars ) ) {
1617 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1620 $options = (array)$options;
1621 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1622 ?
$options['USE INDEX']
1625 if ( is_array( $table ) ) {
1627 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1628 } elseif ( $table != '' ) {
1629 if ( $table[0] == ' ' ) {
1630 $from = ' FROM ' . $table;
1633 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1639 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1640 $this->makeSelectOptions( $options );
1642 if ( !empty( $conds ) ) {
1643 if ( is_array( $conds ) ) {
1644 $conds = $this->makeList( $conds, LIST_AND
);
1646 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1648 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1651 if ( isset( $options['LIMIT'] ) ) {
1652 $sql = $this->limitResult( $sql, $options['LIMIT'],
1653 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1655 $sql = "$sql $postLimitTail";
1657 if ( isset( $options['EXPLAIN'] ) ) {
1658 $sql = 'EXPLAIN ' . $sql;
1665 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1666 * that a single row object is returned. If the query returns no rows,
1667 * false is returned.
1669 * @param string|array $table Table name
1670 * @param string|array $vars Field names
1671 * @param array $conds Conditions
1672 * @param string $fname Caller function name
1673 * @param string|array $options Query options
1674 * @param array|string $join_conds Join conditions
1676 * @return stdClass|bool
1678 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1679 $options = array(), $join_conds = array()
1681 $options = (array)$options;
1682 $options['LIMIT'] = 1;
1683 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1685 if ( $res === false ) {
1689 if ( !$this->numRows( $res ) ) {
1693 $obj = $this->fetchObject( $res );
1699 * Estimate the number of rows in dataset
1701 * MySQL allows you to estimate the number of rows that would be returned
1702 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1703 * index cardinality statistics, and is notoriously inaccurate, especially
1704 * when large numbers of rows have recently been added or deleted.
1706 * For DBMSs that don't support fast result size estimation, this function
1707 * will actually perform the SELECT COUNT(*).
1709 * Takes the same arguments as DatabaseBase::select().
1711 * @param string $table Table name
1712 * @param string $vars Unused
1713 * @param array|string $conds Filters on the table
1714 * @param string $fname Function name for profiling
1715 * @param array $options Options for select
1716 * @return int Row count
1718 public function estimateRowCount(
1719 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1722 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1725 $row = $this->fetchRow( $res );
1726 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1733 * Get the number of rows in dataset
1735 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1737 * Takes the same arguments as DatabaseBase::select().
1739 * @since 1.27 Added $join_conds parameter
1741 * @param array|string $tables Table names
1742 * @param string $vars Unused
1743 * @param array|string $conds Filters on the table
1744 * @param string $fname Function name for profiling
1745 * @param array $options Options for select
1746 * @param array $join_conds Join conditions (since 1.27)
1747 * @return int Row count
1749 public function selectRowCount(
1750 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1753 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1754 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1757 $row = $this->fetchRow( $res );
1758 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1765 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1766 * It's only slightly flawed. Don't use for anything important.
1768 * @param string $sql A SQL Query
1772 protected static function generalizeSQL( $sql ) {
1773 # This does the same as the regexp below would do, but in such a way
1774 # as to avoid crashing php on some large strings.
1775 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1777 $sql = str_replace( "\\\\", '', $sql );
1778 $sql = str_replace( "\\'", '', $sql );
1779 $sql = str_replace( "\\\"", '', $sql );
1780 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1781 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1783 # All newlines, tabs, etc replaced by single space
1784 $sql = preg_replace( '/\s+/', ' ', $sql );
1787 # except the ones surrounded by characters, e.g. l10n
1788 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1789 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1795 * Determines whether a field exists in a table
1797 * @param string $table Table name
1798 * @param string $field Filed to check on that table
1799 * @param string $fname Calling function name (optional)
1800 * @return bool Whether $table has filed $field
1802 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1803 $info = $this->fieldInfo( $table, $field );
1809 * Determines whether an index exists
1810 * Usually throws a DBQueryError on failure
1811 * If errors are explicitly ignored, returns NULL on failure
1813 * @param string $table
1814 * @param string $index
1815 * @param string $fname
1818 public function indexExists( $table, $index, $fname = __METHOD__
) {
1819 if ( !$this->tableExists( $table ) ) {
1823 $info = $this->indexInfo( $table, $index, $fname );
1824 if ( is_null( $info ) ) {
1827 return $info !== false;
1832 * Query whether a given table exists
1834 * @param string $table
1835 * @param string $fname
1838 public function tableExists( $table, $fname = __METHOD__
) {
1839 $table = $this->tableName( $table );
1840 $old = $this->ignoreErrors( true );
1841 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1842 $this->ignoreErrors( $old );
1848 * Determines if a given index is unique
1850 * @param string $table
1851 * @param string $index
1855 public function indexUnique( $table, $index ) {
1856 $indexInfo = $this->indexInfo( $table, $index );
1858 if ( !$indexInfo ) {
1862 return !$indexInfo[0]->Non_unique
;
1866 * Helper for DatabaseBase::insert().
1868 * @param array $options
1871 protected function makeInsertOptions( $options ) {
1872 return implode( ' ', $options );
1876 * INSERT wrapper, inserts an array into a table.
1880 * - A single associative array. The array keys are the field names, and
1881 * the values are the values to insert. The values are treated as data
1882 * and will be quoted appropriately. If NULL is inserted, this will be
1883 * converted to a database NULL.
1884 * - An array with numeric keys, holding a list of associative arrays.
1885 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1886 * each subarray must be identical to each other, and in the same order.
1888 * $options is an array of options, with boolean options encoded as values
1889 * with numeric keys, in the same style as $options in
1890 * DatabaseBase::select(). Supported options are:
1892 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1893 * any rows which cause duplicate key errors are not inserted. It's
1894 * possible to determine how many rows were successfully inserted using
1895 * DatabaseBase::affectedRows().
1897 * @param string $table Table name. This will be passed through
1898 * DatabaseBase::tableName().
1899 * @param array $a Array of rows to insert
1900 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1901 * @param array $options Array of options
1903 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1908 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1909 # No rows to insert, easy just return now
1910 if ( !count( $a ) ) {
1914 $table = $this->tableName( $table );
1916 if ( !is_array( $options ) ) {
1917 $options = array( $options );
1921 if ( isset( $options['fileHandle'] ) ) {
1922 $fh = $options['fileHandle'];
1924 $options = $this->makeInsertOptions( $options );
1926 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1928 $keys = array_keys( $a[0] );
1931 $keys = array_keys( $a );
1934 $sql = 'INSERT ' . $options .
1935 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1939 foreach ( $a as $row ) {
1945 $sql .= '(' . $this->makeList( $row ) . ')';
1948 $sql .= '(' . $this->makeList( $a ) . ')';
1951 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1953 } elseif ( $fh !== null ) {
1957 return (bool)$this->query( $sql, $fname );
1961 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1963 * @param array $options
1966 protected function makeUpdateOptionsArray( $options ) {
1967 if ( !is_array( $options ) ) {
1968 $options = array( $options );
1973 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1974 $opts[] = $this->lowPriorityOption();
1977 if ( in_array( 'IGNORE', $options ) ) {
1985 * Make UPDATE options for the DatabaseBase::update function
1987 * @param array $options The options passed to DatabaseBase::update
1990 protected function makeUpdateOptions( $options ) {
1991 $opts = $this->makeUpdateOptionsArray( $options );
1993 return implode( ' ', $opts );
1997 * UPDATE wrapper. Takes a condition array and a SET array.
1999 * @param string $table Name of the table to UPDATE. This will be passed through
2000 * DatabaseBase::tableName().
2001 * @param array $values An array of values to SET. For each array element,
2002 * the key gives the field name, and the value gives the data to set
2003 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2004 * @param array $conds An array of conditions (WHERE). See
2005 * DatabaseBase::select() for the details of the format of condition
2006 * arrays. Use '*' to update all rows.
2007 * @param string $fname The function name of the caller (from __METHOD__),
2008 * for logging and profiling.
2009 * @param array $options An array of UPDATE options, can be:
2010 * - IGNORE: Ignore unique key conflicts
2011 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2014 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2015 $table = $this->tableName( $table );
2016 $opts = $this->makeUpdateOptions( $options );
2017 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2019 if ( $conds !== array() && $conds !== '*' ) {
2020 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2023 return $this->query( $sql, $fname );
2027 * Makes an encoded list of strings from an array
2029 * @param array $a Containing the data
2030 * @param int $mode Constant
2031 * - LIST_COMMA: Comma separated, no field names
2032 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2033 * documentation for $conds in DatabaseBase::select().
2034 * - LIST_OR: ORed WHERE clause (without the WHERE)
2035 * - LIST_SET: Comma separated with field names, like a SET clause
2036 * - LIST_NAMES: Comma separated field names
2037 * @throws MWException|DBUnexpectedError
2040 public function makeList( $a, $mode = LIST_COMMA
) {
2041 if ( !is_array( $a ) ) {
2042 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2048 foreach ( $a as $field => $value ) {
2050 if ( $mode == LIST_AND
) {
2052 } elseif ( $mode == LIST_OR
) {
2061 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2062 $list .= "($value)";
2063 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2065 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2066 // Remove null from array to be handled separately if found
2067 $includeNull = false;
2068 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2069 $includeNull = true;
2070 unset( $value[$nullKey] );
2072 if ( count( $value ) == 0 && !$includeNull ) {
2073 throw new MWException( __METHOD__
. ": empty input for field $field" );
2074 } elseif ( count( $value ) == 0 ) {
2075 // only check if $field is null
2076 $list .= "$field IS NULL";
2078 // IN clause contains at least one valid element
2079 if ( $includeNull ) {
2080 // Group subconditions to ensure correct precedence
2083 if ( count( $value ) == 1 ) {
2084 // Special-case single values, as IN isn't terribly efficient
2085 // Don't necessarily assume the single key is 0; we don't
2086 // enforce linear numeric ordering on other arrays here.
2087 $value = array_values( $value );
2088 $list .= $field . " = " . $this->addQuotes( $value[0] );
2090 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2092 // if null present in array, append IS NULL
2093 if ( $includeNull ) {
2094 $list .= " OR $field IS NULL)";
2097 } elseif ( $value === null ) {
2098 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2099 $list .= "$field IS ";
2100 } elseif ( $mode == LIST_SET
) {
2101 $list .= "$field = ";
2105 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2106 $list .= "$field = ";
2108 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2116 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2117 * The keys on each level may be either integers or strings.
2119 * @param array $data Organized as 2-d
2120 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2121 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2122 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2123 * @return string|bool SQL fragment, or false if no items in array
2125 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2128 foreach ( $data as $base => $sub ) {
2129 if ( count( $sub ) ) {
2130 $conds[] = $this->makeList(
2131 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2137 return $this->makeList( $conds, LIST_OR
);
2139 // Nothing to search for...
2145 * Return aggregated value alias
2147 * @param array $valuedata
2148 * @param string $valuename
2152 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2157 * @param string $field
2160 public function bitNot( $field ) {
2165 * @param string $fieldLeft
2166 * @param string $fieldRight
2169 public function bitAnd( $fieldLeft, $fieldRight ) {
2170 return "($fieldLeft & $fieldRight)";
2174 * @param string $fieldLeft
2175 * @param string $fieldRight
2178 public function bitOr( $fieldLeft, $fieldRight ) {
2179 return "($fieldLeft | $fieldRight)";
2183 * Build a concatenation list to feed into a SQL query
2184 * @param array $stringList List of raw SQL expressions; caller is
2185 * responsible for any quoting
2188 public function buildConcat( $stringList ) {
2189 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2193 * Build a GROUP_CONCAT or equivalent statement for a query.
2195 * This is useful for combining a field for several rows into a single string.
2196 * NULL values will not appear in the output, duplicated values will appear,
2197 * and the resulting delimiter-separated values have no defined sort order.
2198 * Code using the results may need to use the PHP unique() or sort() methods.
2200 * @param string $delim Glue to bind the results together
2201 * @param string|array $table Table name
2202 * @param string $field Field name
2203 * @param string|array $conds Conditions
2204 * @param string|array $join_conds Join conditions
2205 * @return string SQL text
2208 public function buildGroupConcatField(
2209 $delim, $table, $field, $conds = '', $join_conds = array()
2211 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2213 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2217 * Change the current database
2219 * @todo Explain what exactly will fail if this is not overridden.
2223 * @return bool Success or failure
2225 public function selectDB( $db ) {
2226 # Stub. Shouldn't cause serious problems if it's not overridden, but
2227 # if your database engine supports a concept similar to MySQL's
2228 # databases you may as well.
2229 $this->mDBname
= $db;
2235 * Get the current DB name
2238 public function getDBname() {
2239 return $this->mDBname
;
2243 * Get the server hostname or IP address
2246 public function getServer() {
2247 return $this->mServer
;
2251 * Format a table name ready for use in constructing an SQL query
2253 * This does two important things: it quotes the table names to clean them up,
2254 * and it adds a table prefix if only given a table name with no quotes.
2256 * All functions of this object which require a table name call this function
2257 * themselves. Pass the canonical name to such functions. This is only needed
2258 * when calling query() directly.
2260 * @param string $name Database table name
2261 * @param string $format One of:
2262 * quoted - Automatically pass the table name through addIdentifierQuotes()
2263 * so that it can be used in a query.
2264 * raw - Do not add identifier quotes to the table name
2265 * @return string Full database name
2267 public function tableName( $name, $format = 'quoted' ) {
2268 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2269 # Skip the entire process when we have a string quoted on both ends.
2270 # Note that we check the end so that we will still quote any use of
2271 # use of `database`.table. But won't break things if someone wants
2272 # to query a database table with a dot in the name.
2273 if ( $this->isQuotedIdentifier( $name ) ) {
2277 # Lets test for any bits of text that should never show up in a table
2278 # name. Basically anything like JOIN or ON which are actually part of
2279 # SQL queries, but may end up inside of the table value to combine
2280 # sql. Such as how the API is doing.
2281 # Note that we use a whitespace test rather than a \b test to avoid
2282 # any remote case where a word like on may be inside of a table name
2283 # surrounded by symbols which may be considered word breaks.
2284 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2288 # Split database and table into proper variables.
2289 # We reverse the explode so that database.table and table both output
2290 # the correct table.
2291 $dbDetails = explode( '.', $name, 3 );
2292 if ( count( $dbDetails ) == 3 ) {
2293 list( $database, $schema, $table ) = $dbDetails;
2294 # We don't want any prefix added in this case
2296 } elseif ( count( $dbDetails ) == 2 ) {
2297 list( $database, $table ) = $dbDetails;
2298 # We don't want any prefix added in this case
2299 # In dbs that support it, $database may actually be the schema
2300 # but that doesn't affect any of the functionality here
2304 list( $table ) = $dbDetails;
2305 if ( $wgSharedDB !== null # We have a shared database
2306 && $this->mForeign
== false # We're not working on a foreign database
2307 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2308 && in_array( $table, $wgSharedTables ) # A shared table is selected
2310 $database = $wgSharedDB;
2311 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2312 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2315 $schema = $this->mSchema
; # Default schema
2316 $prefix = $this->mTablePrefix
; # Default prefix
2320 # Quote $table and apply the prefix if not quoted.
2321 # $tableName might be empty if this is called from Database::replaceVars()
2322 $tableName = "{$prefix}{$table}";
2323 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2324 $tableName = $this->addIdentifierQuotes( $tableName );
2327 # Quote $schema and merge it with the table name if needed
2328 if ( strlen( $schema ) ) {
2329 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2330 $schema = $this->addIdentifierQuotes( $schema );
2332 $tableName = $schema . '.' . $tableName;
2335 # Quote $database and merge it with the table name if needed
2336 if ( $database !== null ) {
2337 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2338 $database = $this->addIdentifierQuotes( $database );
2340 $tableName = $database . '.' . $tableName;
2347 * Fetch a number of table names into an array
2348 * This is handy when you need to construct SQL for joins
2351 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2352 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2353 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2357 public function tableNames() {
2358 $inArray = func_get_args();
2361 foreach ( $inArray as $name ) {
2362 $retVal[$name] = $this->tableName( $name );
2369 * Fetch a number of table names into an zero-indexed numerical array
2370 * This is handy when you need to construct SQL for joins
2373 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2374 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2375 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2379 public function tableNamesN() {
2380 $inArray = func_get_args();
2383 foreach ( $inArray as $name ) {
2384 $retVal[] = $this->tableName( $name );
2391 * Get an aliased table name
2392 * e.g. tableName AS newTableName
2394 * @param string $name Table name, see tableName()
2395 * @param string|bool $alias Alias (optional)
2396 * @return string SQL name for aliased table. Will not alias a table to its own name
2398 public function tableNameWithAlias( $name, $alias = false ) {
2399 if ( !$alias ||
$alias == $name ) {
2400 return $this->tableName( $name );
2402 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2407 * Gets an array of aliased table names
2409 * @param array $tables Array( [alias] => table )
2410 * @return string[] See tableNameWithAlias()
2412 public function tableNamesWithAlias( $tables ) {
2414 foreach ( $tables as $alias => $table ) {
2415 if ( is_numeric( $alias ) ) {
2418 $retval[] = $this->tableNameWithAlias( $table, $alias );
2425 * Get an aliased field name
2426 * e.g. fieldName AS newFieldName
2428 * @param string $name Field name
2429 * @param string|bool $alias Alias (optional)
2430 * @return string SQL name for aliased field. Will not alias a field to its own name
2432 public function fieldNameWithAlias( $name, $alias = false ) {
2433 if ( !$alias ||
(string)$alias === (string)$name ) {
2436 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2441 * Gets an array of aliased field names
2443 * @param array $fields Array( [alias] => field )
2444 * @return string[] See fieldNameWithAlias()
2446 public function fieldNamesWithAlias( $fields ) {
2448 foreach ( $fields as $alias => $field ) {
2449 if ( is_numeric( $alias ) ) {
2452 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2459 * Get the aliased table name clause for a FROM clause
2460 * which might have a JOIN and/or USE INDEX clause
2462 * @param array $tables ( [alias] => table )
2463 * @param array $use_index Same as for select()
2464 * @param array $join_conds Same as for select()
2467 protected function tableNamesWithUseIndexOrJOIN(
2468 $tables, $use_index = array(), $join_conds = array()
2472 $use_index = (array)$use_index;
2473 $join_conds = (array)$join_conds;
2475 foreach ( $tables as $alias => $table ) {
2476 if ( !is_string( $alias ) ) {
2477 // No alias? Set it equal to the table name
2480 // Is there a JOIN clause for this table?
2481 if ( isset( $join_conds[$alias] ) ) {
2482 list( $joinType, $conds ) = $join_conds[$alias];
2483 $tableClause = $joinType;
2484 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2485 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2486 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2488 $tableClause .= ' ' . $use;
2491 $on = $this->makeList( (array)$conds, LIST_AND
);
2493 $tableClause .= ' ON (' . $on . ')';
2496 $retJOIN[] = $tableClause;
2497 } elseif ( isset( $use_index[$alias] ) ) {
2498 // Is there an INDEX clause for this table?
2499 $tableClause = $this->tableNameWithAlias( $table, $alias );
2500 $tableClause .= ' ' . $this->useIndexClause(
2501 implode( ',', (array)$use_index[$alias] )
2504 $ret[] = $tableClause;
2506 $tableClause = $this->tableNameWithAlias( $table, $alias );
2508 $ret[] = $tableClause;
2512 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2513 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2514 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2516 // Compile our final table clause
2517 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2521 * Get the name of an index in a given table.
2523 * @protected Don't use outside of DatabaseBase and childs
2524 * @param string $index
2527 public function indexName( $index ) {
2528 // @FIXME: Make this protected once we move away from PHP 5.3
2529 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2531 // Backwards-compatibility hack
2533 'ar_usertext_timestamp' => 'usertext_timestamp',
2534 'un_user_id' => 'user_id',
2535 'un_user_ip' => 'user_ip',
2538 if ( isset( $renamed[$index] ) ) {
2539 return $renamed[$index];
2546 * Adds quotes and backslashes.
2548 * @param string|Blob $s
2551 public function addQuotes( $s ) {
2552 if ( $s instanceof Blob
) {
2555 if ( $s === null ) {
2558 # This will also quote numeric values. This should be harmless,
2559 # and protects against weird problems that occur when they really
2560 # _are_ strings such as article titles and string->number->string
2561 # conversion is not 1:1.
2562 return "'" . $this->strencode( $s ) . "'";
2567 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2568 * MySQL uses `backticks` while basically everything else uses double quotes.
2569 * Since MySQL is the odd one out here the double quotes are our generic
2570 * and we implement backticks in DatabaseMysql.
2575 public function addIdentifierQuotes( $s ) {
2576 return '"' . str_replace( '"', '""', $s ) . '"';
2580 * Returns if the given identifier looks quoted or not according to
2581 * the database convention for quoting identifiers .
2583 * @param string $name
2586 public function isQuotedIdentifier( $name ) {
2587 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2594 protected function escapeLikeInternal( $s ) {
2595 return addcslashes( $s, '\%_' );
2599 * LIKE statement wrapper, receives a variable-length argument list with
2600 * parts of pattern to match containing either string literals that will be
2601 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2602 * the function could be provided with an array of aforementioned
2605 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2606 * a LIKE clause that searches for subpages of 'My page title'.
2608 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2609 * $query .= $dbr->buildLike( $pattern );
2612 * @return string Fully built LIKE statement
2614 public function buildLike() {
2615 $params = func_get_args();
2617 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2618 $params = $params[0];
2623 foreach ( $params as $value ) {
2624 if ( $value instanceof LikeMatch
) {
2625 $s .= $value->toString();
2627 $s .= $this->escapeLikeInternal( $value );
2631 return " LIKE {$this->addQuotes( $s )} ";
2635 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2639 public function anyChar() {
2640 return new LikeMatch( '_' );
2644 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2648 public function anyString() {
2649 return new LikeMatch( '%' );
2653 * Returns an appropriately quoted sequence value for inserting a new row.
2654 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2655 * subclass will return an integer, and save the value for insertId()
2657 * Any implementation of this function should *not* involve reusing
2658 * sequence numbers created for rolled-back transactions.
2659 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2660 * @param string $seqName
2663 public function nextSequenceValue( $seqName ) {
2668 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2669 * is only needed because a) MySQL must be as efficient as possible due to
2670 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2671 * which index to pick. Anyway, other databases might have different
2672 * indexes on a given table. So don't bother overriding this unless you're
2674 * @param string $index
2677 public function useIndexClause( $index ) {
2682 * REPLACE query wrapper.
2684 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2685 * except that when there is a duplicate key error, the old row is deleted
2686 * and the new row is inserted in its place.
2688 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2689 * perform the delete, we need to know what the unique indexes are so that
2690 * we know how to find the conflicting rows.
2692 * It may be more efficient to leave off unique indexes which are unlikely
2693 * to collide. However if you do this, you run the risk of encountering
2694 * errors which wouldn't have occurred in MySQL.
2696 * @param string $table The table to replace the row(s) in.
2697 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2698 * a field name or an array of field names
2699 * @param array $rows Can be either a single row to insert, or multiple rows,
2700 * in the same format as for DatabaseBase::insert()
2701 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2703 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2704 $quotedTable = $this->tableName( $table );
2706 if ( count( $rows ) == 0 ) {
2711 if ( !is_array( reset( $rows ) ) ) {
2712 $rows = array( $rows );
2715 // @FXIME: this is not atomic, but a trx would break affectedRows()
2716 foreach ( $rows as $row ) {
2717 # Delete rows which collide
2718 if ( $uniqueIndexes ) {
2719 $sql = "DELETE FROM $quotedTable WHERE ";
2721 foreach ( $uniqueIndexes as $index ) {
2728 if ( is_array( $index ) ) {
2730 foreach ( $index as $col ) {
2736 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2739 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2743 $this->query( $sql, $fname );
2746 # Now insert the row
2747 $this->insert( $table, $row, $fname );
2752 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2755 * @param string $table Table name
2756 * @param array|string $rows Row(s) to insert
2757 * @param string $fname Caller function name
2759 * @return ResultWrapper
2761 protected function nativeReplace( $table, $rows, $fname ) {
2762 $table = $this->tableName( $table );
2765 if ( !is_array( reset( $rows ) ) ) {
2766 $rows = array( $rows );
2769 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2772 foreach ( $rows as $row ) {
2779 $sql .= '(' . $this->makeList( $row ) . ')';
2782 return $this->query( $sql, $fname );
2786 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2788 * This updates any conflicting rows (according to the unique indexes) using
2789 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2791 * $rows may be either:
2792 * - A single associative array. The array keys are the field names, and
2793 * the values are the values to insert. The values are treated as data
2794 * and will be quoted appropriately. If NULL is inserted, this will be
2795 * converted to a database NULL.
2796 * - An array with numeric keys, holding a list of associative arrays.
2797 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2798 * each subarray must be identical to each other, and in the same order.
2800 * It may be more efficient to leave off unique indexes which are unlikely
2801 * to collide. However if you do this, you run the risk of encountering
2802 * errors which wouldn't have occurred in MySQL.
2804 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2809 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2810 * @param array $rows A single row or list of rows to insert
2811 * @param array $uniqueIndexes List of single field names or field name tuples
2812 * @param array $set An array of values to SET. For each array element, the
2813 * key gives the field name, and the value gives the data to set that
2814 * field to. The data will be quoted by DatabaseBase::addQuotes().
2815 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2819 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2822 if ( !count( $rows ) ) {
2823 return true; // nothing to do
2826 if ( !is_array( reset( $rows ) ) ) {
2827 $rows = array( $rows );
2830 if ( count( $uniqueIndexes ) ) {
2831 $clauses = array(); // list WHERE clauses that each identify a single row
2832 foreach ( $rows as $row ) {
2833 foreach ( $uniqueIndexes as $index ) {
2834 $index = is_array( $index ) ?
$index : array( $index ); // columns
2835 $rowKey = array(); // unique key to this row
2836 foreach ( $index as $column ) {
2837 $rowKey[$column] = $row[$column];
2839 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2842 $where = array( $this->makeList( $clauses, LIST_OR
) );
2847 $useTrx = !$this->mTrxLevel
;
2849 $this->begin( $fname );
2852 # Update any existing conflicting row(s)
2853 if ( $where !== false ) {
2854 $ok = $this->update( $table, $set, $where, $fname );
2858 # Now insert any non-conflicting row(s)
2859 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2860 } catch ( Exception
$e ) {
2862 $this->rollback( $fname );
2867 $this->commit( $fname );
2874 * DELETE where the condition is a join.
2876 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2877 * we use sub-selects
2879 * For safety, an empty $conds will not delete everything. If you want to
2880 * delete all rows where the join condition matches, set $conds='*'.
2882 * DO NOT put the join condition in $conds.
2884 * @param string $delTable The table to delete from.
2885 * @param string $joinTable The other table.
2886 * @param string $delVar The variable to join on, in the first table.
2887 * @param string $joinVar The variable to join on, in the second table.
2888 * @param array $conds Condition array of field names mapped to variables,
2889 * ANDed together in the WHERE clause
2890 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2891 * @throws DBUnexpectedError
2893 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2897 throw new DBUnexpectedError( $this,
2898 'DatabaseBase::deleteJoin() called with empty $conds' );
2901 $delTable = $this->tableName( $delTable );
2902 $joinTable = $this->tableName( $joinTable );
2903 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2904 if ( $conds != '*' ) {
2905 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2909 $this->query( $sql, $fname );
2913 * Returns the size of a text field, or -1 for "unlimited"
2915 * @param string $table
2916 * @param string $field
2919 public function textFieldSize( $table, $field ) {
2920 $table = $this->tableName( $table );
2921 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2922 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2923 $row = $this->fetchObject( $res );
2927 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2937 * A string to insert into queries to show that they're low-priority, like
2938 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2939 * string and nothing bad should happen.
2941 * @return string Returns the text of the low priority option if it is
2942 * supported, or a blank string otherwise
2944 public function lowPriorityOption() {
2949 * DELETE query wrapper.
2951 * @param array $table Table name
2952 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2953 * for the format. Use $conds == "*" to delete all rows
2954 * @param string $fname Name of the calling function
2955 * @throws DBUnexpectedError
2956 * @return bool|ResultWrapper
2958 public function delete( $table, $conds, $fname = __METHOD__
) {
2960 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2963 $table = $this->tableName( $table );
2964 $sql = "DELETE FROM $table";
2966 if ( $conds != '*' ) {
2967 if ( is_array( $conds ) ) {
2968 $conds = $this->makeList( $conds, LIST_AND
);
2970 $sql .= ' WHERE ' . $conds;
2973 return $this->query( $sql, $fname );
2977 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2978 * into another table.
2980 * @param string $destTable The table name to insert into
2981 * @param string|array $srcTable May be either a table name, or an array of table names
2982 * to include in a join.
2984 * @param array $varMap Must be an associative array of the form
2985 * array( 'dest1' => 'source1', ...). Source items may be literals
2986 * rather than field names, but strings should be quoted with
2987 * DatabaseBase::addQuotes()
2989 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2990 * the details of the format of condition arrays. May be "*" to copy the
2993 * @param string $fname The function name of the caller, from __METHOD__
2995 * @param array $insertOptions Options for the INSERT part of the query, see
2996 * DatabaseBase::insert() for details.
2997 * @param array $selectOptions Options for the SELECT part of the query, see
2998 * DatabaseBase::select() for details.
3000 * @return ResultWrapper
3002 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3003 $fname = __METHOD__
,
3004 $insertOptions = array(), $selectOptions = array()
3006 $destTable = $this->tableName( $destTable );
3008 if ( !is_array( $insertOptions ) ) {
3009 $insertOptions = array( $insertOptions );
3012 $insertOptions = $this->makeInsertOptions( $insertOptions );
3014 if ( !is_array( $selectOptions ) ) {
3015 $selectOptions = array( $selectOptions );
3018 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3020 if ( is_array( $srcTable ) ) {
3021 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3023 $srcTable = $this->tableName( $srcTable );
3026 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3027 " SELECT $startOpts " . implode( ',', $varMap ) .
3028 " FROM $srcTable $useIndex ";
3030 if ( $conds != '*' ) {
3031 if ( is_array( $conds ) ) {
3032 $conds = $this->makeList( $conds, LIST_AND
);
3034 $sql .= " WHERE $conds";
3037 $sql .= " $tailOpts";
3039 return $this->query( $sql, $fname );
3043 * Construct a LIMIT query with optional offset. This is used for query
3044 * pages. The SQL should be adjusted so that only the first $limit rows
3045 * are returned. If $offset is provided as well, then the first $offset
3046 * rows should be discarded, and the next $limit rows should be returned.
3047 * If the result of the query is not ordered, then the rows to be returned
3048 * are theoretically arbitrary.
3050 * $sql is expected to be a SELECT, if that makes a difference.
3052 * The version provided by default works in MySQL and SQLite. It will very
3053 * likely need to be overridden for most other DBMSes.
3055 * @param string $sql SQL query we will append the limit too
3056 * @param int $limit The SQL limit
3057 * @param int|bool $offset The SQL offset (default false)
3058 * @throws DBUnexpectedError
3061 public function limitResult( $sql, $limit, $offset = false ) {
3062 if ( !is_numeric( $limit ) ) {
3063 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3066 return "$sql LIMIT "
3067 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3072 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3073 * within the UNION construct.
3076 public function unionSupportsOrderAndLimit() {
3077 return true; // True for almost every DB supported
3081 * Construct a UNION query
3082 * This is used for providing overload point for other DB abstractions
3083 * not compatible with the MySQL syntax.
3084 * @param array $sqls SQL statements to combine
3085 * @param bool $all Use UNION ALL
3086 * @return string SQL fragment
3088 public function unionQueries( $sqls, $all ) {
3089 $glue = $all ?
') UNION ALL (' : ') UNION (';
3091 return '(' . implode( $glue, $sqls ) . ')';
3095 * Returns an SQL expression for a simple conditional. This doesn't need
3096 * to be overridden unless CASE isn't supported in your DBMS.
3098 * @param string|array $cond SQL expression which will result in a boolean value
3099 * @param string $trueVal SQL expression to return if true
3100 * @param string $falseVal SQL expression to return if false
3101 * @return string SQL fragment
3103 public function conditional( $cond, $trueVal, $falseVal ) {
3104 if ( is_array( $cond ) ) {
3105 $cond = $this->makeList( $cond, LIST_AND
);
3108 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3112 * Returns a comand for str_replace function in SQL query.
3113 * Uses REPLACE() in MySQL
3115 * @param string $orig Column to modify
3116 * @param string $old Column to seek
3117 * @param string $new Column to replace with
3121 public function strreplace( $orig, $old, $new ) {
3122 return "REPLACE({$orig}, {$old}, {$new})";
3126 * Determines how long the server has been up
3131 public function getServerUptime() {
3136 * Determines if the last failure was due to a deadlock
3141 public function wasDeadlock() {
3146 * Determines if the last failure was due to a lock timeout
3151 public function wasLockTimeout() {
3156 * Determines if the last query error was something that should be dealt
3157 * with by pinging the connection and reissuing the query.
3162 public function wasErrorReissuable() {
3167 * Determines if the last failure was due to the database being read-only.
3172 public function wasReadOnlyError() {
3177 * Determines if the given query error was a connection drop
3180 * @param integer|string $errno
3183 public function wasConnectionError( $errno ) {
3188 * Perform a deadlock-prone transaction.
3190 * This function invokes a callback function to perform a set of write
3191 * queries. If a deadlock occurs during the processing, the transaction
3192 * will be rolled back and the callback function will be called again.
3195 * $dbw->deadlockLoop( callback, ... );
3197 * Extra arguments are passed through to the specified callback function.
3199 * Returns whatever the callback function returned on its successful,
3200 * iteration, or false on error, for example if the retry limit was
3204 * @throws DBQueryError
3206 public function deadlockLoop() {
3207 $args = func_get_args();
3208 $function = array_shift( $args );
3209 $tries = self
::DEADLOCK_TRIES
;
3211 $this->begin( __METHOD__
);
3217 $retVal = call_user_func_array( $function, $args );
3219 } catch ( DBQueryError
$e ) {
3220 if ( $this->wasDeadlock() ) {
3221 // Retry after a randomized delay
3222 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3224 // Throw the error back up
3228 } while ( --$tries > 0 );
3230 if ( $tries <= 0 ) {
3231 // Too many deadlocks; give up
3232 $this->rollback( __METHOD__
);
3235 $this->commit( __METHOD__
);
3242 * Wait for the slave to catch up to a given master position.
3244 * @param DBMasterPos $pos
3245 * @param int $timeout The maximum number of seconds to wait for
3247 * @return int Zero if the slave was past that position already,
3248 * greater than zero if we waited for some period of time, less than
3249 * zero if we timed out.
3251 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3252 # Real waits are implemented in the subclass.
3257 * Get the replication position of this slave
3259 * @return DBMasterPos|bool False if this is not a slave.
3261 public function getSlavePos() {
3267 * Get the position of this master
3269 * @return DBMasterPos|bool False if this is not a master
3271 public function getMasterPos() {
3277 * Run an anonymous function as soon as there is no transaction pending.
3278 * If there is a transaction and it is rolled back, then the callback is cancelled.
3279 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3280 * Callbacks must commit any transactions that they begin.
3282 * This is useful for updates to different systems or when separate transactions are needed.
3283 * For example, one might want to enqueue jobs into a system outside the database, but only
3284 * after the database is updated so that the jobs will see the data when they actually run.
3285 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3287 * @param callable $callback
3290 final public function onTransactionIdle( $callback ) {
3291 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3292 if ( !$this->mTrxLevel
) {
3293 $this->runOnTransactionIdleCallbacks();
3298 * Run an anonymous function before the current transaction commits or now if there is none.
3299 * If there is a transaction and it is rolled back, then the callback is cancelled.
3300 * Callbacks must not start nor commit any transactions.
3302 * This is useful for updates that easily cause deadlocks if locks are held too long
3303 * but where atomicity is strongly desired for these updates and some related updates.
3305 * @param callable $callback
3308 final public function onTransactionPreCommitOrIdle( $callback ) {
3309 if ( $this->mTrxLevel
) {
3310 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3312 $this->onTransactionIdle( $callback ); // this will trigger immediately
3317 * Actually any "on transaction idle" callbacks.
3321 protected function runOnTransactionIdleCallbacks() {
3322 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3324 $e = $ePrior = null; // last exception
3325 do { // callbacks may add callbacks :)
3326 $callbacks = $this->mTrxIdleCallbacks
;
3327 $this->mTrxIdleCallbacks
= array(); // recursion guard
3328 foreach ( $callbacks as $callback ) {
3330 list( $phpCallback ) = $callback;
3331 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3332 call_user_func( $phpCallback );
3334 $this->setFlag( DBO_TRX
); // restore automatic begin()
3336 $this->clearFlag( DBO_TRX
); // restore auto-commit
3338 } catch ( Exception
$e ) {
3340 MWExceptionHandler
::logException( $ePrior );
3343 // Some callbacks may use startAtomic/endAtomic, so make sure
3344 // their transactions are ended so other callbacks don't fail
3345 if ( $this->trxLevel() ) {
3346 $this->rollback( __METHOD__
);
3350 } while ( count( $this->mTrxIdleCallbacks
) );
3352 if ( $e instanceof Exception
) {
3353 throw $e; // re-throw any last exception
3358 * Actually any "on transaction pre-commit" callbacks.
3362 protected function runOnTransactionPreCommitCallbacks() {
3363 $e = $ePrior = null; // last exception
3364 do { // callbacks may add callbacks :)
3365 $callbacks = $this->mTrxPreCommitCallbacks
;
3366 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3367 foreach ( $callbacks as $callback ) {
3369 list( $phpCallback ) = $callback;
3370 call_user_func( $phpCallback );
3371 } catch ( Exception
$e ) {
3373 MWExceptionHandler
::logException( $ePrior );
3378 } while ( count( $this->mTrxPreCommitCallbacks
) );
3380 if ( $e instanceof Exception
) {
3381 throw $e; // re-throw any last exception
3386 * Begin an atomic section of statements
3388 * If a transaction has been started already, just keep track of the given
3389 * section name to make sure the transaction is not committed pre-maturely.
3390 * This function can be used in layers (with sub-sections), so use a stack
3391 * to keep track of the different atomic sections. If there is no transaction,
3392 * start one implicitly.
3394 * The goal of this function is to create an atomic section of SQL queries
3395 * without having to start a new transaction if it already exists.
3397 * Atomic sections are more strict than transactions. With transactions,
3398 * attempting to begin a new transaction when one is already running results
3399 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3400 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3401 * and any database transactions cannot be began or committed until all atomic
3402 * levels are closed. There is no such thing as implicitly opening or closing
3403 * an atomic section.
3406 * @param string $fname
3409 final public function startAtomic( $fname = __METHOD__
) {
3410 if ( !$this->mTrxLevel
) {
3411 $this->begin( $fname );
3412 $this->mTrxAutomatic
= true;
3413 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3414 // in all changes being in one transaction to keep requests transactional.
3415 if ( !$this->getFlag( DBO_TRX
) ) {
3416 $this->mTrxAutomaticAtomic
= true;
3420 $this->mTrxAtomicLevels
[] = $fname;
3424 * Ends an atomic section of SQL statements
3426 * Ends the next section of atomic SQL statements and commits the transaction
3430 * @see DatabaseBase::startAtomic
3431 * @param string $fname
3434 final public function endAtomic( $fname = __METHOD__
) {
3435 if ( !$this->mTrxLevel
) {
3436 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3438 if ( !$this->mTrxAtomicLevels ||
3439 array_pop( $this->mTrxAtomicLevels
) !== $fname
3441 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3444 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3445 $this->commit( $fname, 'flush' );
3450 * Begin a transaction. If a transaction is already in progress,
3451 * that transaction will be committed before the new transaction is started.
3453 * Note that when the DBO_TRX flag is set (which is usually the case for web
3454 * requests, but not for maintenance scripts), any previous database query
3455 * will have started a transaction automatically.
3457 * Nesting of transactions is not supported. Attempts to nest transactions
3458 * will cause a warning, unless the current transaction was started
3459 * automatically because of the DBO_TRX flag.
3461 * @param string $fname
3464 final public function begin( $fname = __METHOD__
) {
3465 if ( $this->mTrxLevel
) { // implicit commit
3466 if ( $this->mTrxAtomicLevels
) {
3467 // If the current transaction was an automatic atomic one, then we definitely have
3468 // a problem. Same if there is any unclosed atomic level.
3469 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3470 throw new DBUnexpectedError(
3472 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
3474 } elseif ( !$this->mTrxAutomatic
) {
3475 // We want to warn about inadvertently nested begin/commit pairs, but not about
3476 // auto-committing implicit transactions that were started by query() via DBO_TRX
3477 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3478 " performing implicit commit!";
3481 $this->getLogContext( array(
3482 'method' => __METHOD__
,
3487 // if the transaction was automatic and has done write operations
3488 if ( $this->mTrxDoneWrites
) {
3489 wfDebug( "$fname: Automatic transaction with writes in progress" .
3490 " (from {$this->mTrxFname}), performing implicit commit!\n"
3495 $this->runOnTransactionPreCommitCallbacks();
3496 $writeTime = $this->pendingWriteQueryDuration();
3497 $this->doCommit( $fname );
3498 if ( $this->mTrxDoneWrites
) {
3499 $this->mDoneWrites
= microtime( true );
3500 $this->getTransactionProfiler()->transactionWritingOut(
3501 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3503 $this->runOnTransactionIdleCallbacks();
3506 # Avoid fatals if close() was called
3507 $this->assertOpen();
3509 $this->doBegin( $fname );
3510 $this->mTrxTimestamp
= microtime( true );
3511 $this->mTrxFname
= $fname;
3512 $this->mTrxDoneWrites
= false;
3513 $this->mTrxAutomatic
= false;
3514 $this->mTrxAutomaticAtomic
= false;
3515 $this->mTrxAtomicLevels
= array();
3516 $this->mTrxIdleCallbacks
= array();
3517 $this->mTrxPreCommitCallbacks
= array();
3518 $this->mTrxShortId
= wfRandomString( 12 );
3519 $this->mTrxWriteDuration
= 0.0;
3520 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3521 // Get an estimate of the slave lag before then, treating estimate staleness
3522 // as lag itself just to be safe
3523 $status = $this->getApproximateLagStatus();
3524 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3528 * Issues the BEGIN command to the database server.
3530 * @see DatabaseBase::begin()
3531 * @param string $fname
3533 protected function doBegin( $fname ) {
3534 $this->query( 'BEGIN', $fname );
3535 $this->mTrxLevel
= 1;
3539 * Commits a transaction previously started using begin().
3540 * If no transaction is in progress, a warning is issued.
3542 * Nesting of transactions is not supported.
3544 * @param string $fname
3545 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3546 * explicitly committing implicit transactions, or calling commit when no
3547 * transaction is in progress. This will silently break any ongoing
3548 * explicit transaction. Only set the flush flag if you are sure that it
3549 * is safe to ignore these warnings in your context.
3550 * @throws DBUnexpectedError
3552 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3553 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3554 // There are still atomic sections open. This cannot be ignored
3555 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3556 throw new DBUnexpectedError(
3558 "Got COMMIT while atomic sections $levels are still open"
3562 if ( $flush === 'flush' ) {
3563 if ( !$this->mTrxLevel
) {
3564 return; // nothing to do
3565 } elseif ( !$this->mTrxAutomatic
) {
3566 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3569 if ( !$this->mTrxLevel
) {
3570 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3571 return; // nothing to do
3572 } elseif ( $this->mTrxAutomatic
) {
3573 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3577 # Avoid fatals if close() was called
3578 $this->assertOpen();
3580 $this->runOnTransactionPreCommitCallbacks();
3581 $writeTime = $this->pendingWriteQueryDuration();
3582 $this->doCommit( $fname );
3583 if ( $this->mTrxDoneWrites
) {
3584 $this->mDoneWrites
= microtime( true );
3585 $this->getTransactionProfiler()->transactionWritingOut(
3586 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3588 $this->runOnTransactionIdleCallbacks();
3592 * Issues the COMMIT command to the database server.
3594 * @see DatabaseBase::commit()
3595 * @param string $fname
3597 protected function doCommit( $fname ) {
3598 if ( $this->mTrxLevel
) {
3599 $this->query( 'COMMIT', $fname );
3600 $this->mTrxLevel
= 0;
3605 * Rollback a transaction previously started using begin().
3606 * If no transaction is in progress, a warning is issued.
3608 * No-op on non-transactional databases.
3610 * @param string $fname
3611 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3612 * calling rollback when no transaction is in progress. This will silently
3613 * break any ongoing explicit transaction. Only set the flush flag if you
3614 * are sure that it is safe to ignore these warnings in your context.
3615 * @throws DBUnexpectedError
3616 * @since 1.23 Added $flush parameter
3618 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3619 if ( $flush !== 'flush' ) {
3620 if ( !$this->mTrxLevel
) {
3621 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3622 return; // nothing to do
3623 } elseif ( $this->mTrxAutomatic
) {
3624 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3627 if ( !$this->mTrxLevel
) {
3628 return; // nothing to do
3629 } elseif ( !$this->mTrxAutomatic
) {
3630 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3634 # Avoid fatals if close() was called
3635 $this->assertOpen();
3637 $this->doRollback( $fname );
3638 $this->mTrxIdleCallbacks
= array(); // cancel
3639 $this->mTrxPreCommitCallbacks
= array(); // cancel
3640 $this->mTrxAtomicLevels
= array();
3641 if ( $this->mTrxDoneWrites
) {
3642 $this->getTransactionProfiler()->transactionWritingOut(
3643 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3648 * Issues the ROLLBACK command to the database server.
3650 * @see DatabaseBase::rollback()
3651 * @param string $fname
3653 protected function doRollback( $fname ) {
3654 if ( $this->mTrxLevel
) {
3655 $this->query( 'ROLLBACK', $fname, true );
3656 $this->mTrxLevel
= 0;
3661 * Creates a new table with structure copied from existing table
3662 * Note that unlike most database abstraction functions, this function does not
3663 * automatically append database prefix, because it works at a lower
3664 * abstraction level.
3665 * The table names passed to this function shall not be quoted (this
3666 * function calls addIdentifierQuotes when needed).
3668 * @param string $oldName Name of table whose structure should be copied
3669 * @param string $newName Name of table to be created
3670 * @param bool $temporary Whether the new table should be temporary
3671 * @param string $fname Calling function name
3672 * @throws MWException
3673 * @return bool True if operation was successful
3675 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3678 throw new MWException(
3679 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3683 * List all tables on the database
3685 * @param string $prefix Only show tables with this prefix, e.g. mw_
3686 * @param string $fname Calling function name
3687 * @throws MWException
3690 function listTables( $prefix = null, $fname = __METHOD__
) {
3691 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3695 * Reset the views process cache set by listViews()
3698 final public function clearViewsCache() {
3699 $this->allViews
= null;
3703 * Lists all the VIEWs in the database
3705 * For caching purposes the list of all views should be stored in
3706 * $this->allViews. The process cache can be cleared with clearViewsCache()
3708 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3709 * @param string $fname Name of calling function
3710 * @throws MWException
3714 public function listViews( $prefix = null, $fname = __METHOD__
) {
3715 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3719 * Differentiates between a TABLE and a VIEW
3721 * @param string $name Name of the database-structure to test.
3722 * @throws MWException
3726 public function isView( $name ) {
3727 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3731 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3732 * to the format used for inserting into timestamp fields in this DBMS.
3734 * The result is unquoted, and needs to be passed through addQuotes()
3735 * before it can be included in raw SQL.
3737 * @param string|int $ts
3741 public function timestamp( $ts = 0 ) {
3742 return wfTimestamp( TS_MW
, $ts );
3746 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3747 * to the format used for inserting into timestamp fields in this DBMS. If
3748 * NULL is input, it is passed through, allowing NULL values to be inserted
3749 * into timestamp fields.
3751 * The result is unquoted, and needs to be passed through addQuotes()
3752 * before it can be included in raw SQL.
3754 * @param string|int $ts
3758 public function timestampOrNull( $ts = null ) {
3759 if ( is_null( $ts ) ) {
3762 return $this->timestamp( $ts );
3767 * Take the result from a query, and wrap it in a ResultWrapper if
3768 * necessary. Boolean values are passed through as is, to indicate success
3769 * of write queries or failure.
3771 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3772 * resource, and it was necessary to call this function to convert it to
3773 * a wrapper. Nowadays, raw database objects are never exposed to external
3774 * callers, so this is unnecessary in external code.
3776 * @param bool|ResultWrapper|resource|object $result
3777 * @return bool|ResultWrapper
3779 protected function resultObject( $result ) {
3782 } elseif ( $result instanceof ResultWrapper
) {
3784 } elseif ( $result === true ) {
3785 // Successful write query
3788 return new ResultWrapper( $this, $result );
3793 * Ping the server and try to reconnect if it there is no connection
3795 * @return bool Success or failure
3797 public function ping() {
3798 # Stub. Not essential to override.
3802 public function getSessionLagStatus() {
3803 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3807 * Get the slave lag when the current transaction started
3809 * This is useful when transactions might use snapshot isolation
3810 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3811 * is this lag plus transaction duration. If they don't, it is still
3812 * safe to be pessimistic. This returns null if there is no transaction.
3814 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3817 public function getTransactionLagStatus() {
3818 return $this->mTrxLevel
3819 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
3824 * Get a slave lag estimate for this server
3826 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3829 public function getApproximateLagStatus() {
3831 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3832 'since' => microtime( true )
3837 * Merge the result of getSessionLagStatus() for several DBs
3838 * using the most pessimistic values to estimate the lag of
3839 * any data derived from them in combination
3841 * This is information is useful for caching modules
3843 * @see WANObjectCache::set()
3844 * @see WANObjectCache::getWithSetCallback()
3846 * @param IDatabase $db1
3847 * @param IDatabase ...
3848 * @return array Map of values:
3849 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3850 * - since: oldest UNIX timestamp of any of the DB lag estimates
3851 * - pending: whether any of the DBs have uncommitted changes
3854 public static function getCacheSetOptions( IDatabase
$db1 ) {
3855 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
3856 foreach ( func_get_args() as $db ) {
3857 /** @var IDatabase $db */
3858 $status = $db->getSessionLagStatus();
3859 if ( $status['lag'] === false ) {
3860 $res['lag'] = false;
3861 } elseif ( $res['lag'] !== false ) {
3862 $res['lag'] = max( $res['lag'], $status['lag'] );
3864 $res['since'] = min( $res['since'], $status['since'] );
3865 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3871 public function getLag() {
3876 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3880 function maxListLen() {
3885 * Some DBMSs have a special format for inserting into blob fields, they
3886 * don't allow simple quoted strings to be inserted. To insert into such
3887 * a field, pass the data through this function before passing it to
3888 * DatabaseBase::insert().
3893 public function encodeBlob( $b ) {
3898 * Some DBMSs return a special placeholder object representing blob fields
3899 * in result objects. Pass the object through this function to return the
3902 * @param string|Blob $b
3905 public function decodeBlob( $b ) {
3906 if ( $b instanceof Blob
) {
3913 * Override database's default behavior. $options include:
3914 * 'connTimeout' : Set the connection timeout value in seconds.
3915 * May be useful for very long batch queries such as
3916 * full-wiki dumps, where a single query reads out over
3919 * @param array $options
3922 public function setSessionOptions( array $options ) {
3926 * Read and execute SQL commands from a file.
3928 * Returns true on success, error string or exception on failure (depending
3929 * on object's error ignore settings).
3931 * @param string $filename File name to open
3932 * @param bool|callable $lineCallback Optional function called before reading each line
3933 * @param bool|callable $resultCallback Optional function called for each MySQL result
3934 * @param bool|string $fname Calling function name or false if name should be
3935 * generated dynamically using $filename
3936 * @param bool|callable $inputCallback Optional function called for each
3937 * complete line sent
3938 * @throws Exception|MWException
3939 * @return bool|string
3941 public function sourceFile(
3942 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3944 MediaWiki\
suppressWarnings();
3945 $fp = fopen( $filename, 'r' );
3946 MediaWiki\restoreWarnings
();
3948 if ( false === $fp ) {
3949 throw new MWException( "Could not open \"{$filename}\".\n" );
3953 $fname = __METHOD__
. "( $filename )";
3957 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3958 } catch ( Exception
$e ) {
3969 * Get the full path of a patch file. Originally based on archive()
3970 * from updaters.inc. Keep in mind this always returns a patch, as
3971 * it fails back to MySQL if no DB-specific patch can be found
3973 * @param string $patch The name of the patch, like patch-something.sql
3974 * @return string Full path to patch file
3976 public function patchPath( $patch ) {
3979 $dbType = $this->getType();
3980 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3981 return "$IP/maintenance/$dbType/archives/$patch";
3983 return "$IP/maintenance/archives/$patch";
3988 * Set variables to be used in sourceFile/sourceStream, in preference to the
3989 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3990 * all. If it's set to false, $GLOBALS will be used.
3992 * @param bool|array $vars Mapping variable name to value.
3994 public function setSchemaVars( $vars ) {
3995 $this->mSchemaVars
= $vars;
3999 * Read and execute commands from an open file handle.
4001 * Returns true on success, error string or exception on failure (depending
4002 * on object's error ignore settings).
4004 * @param resource $fp File handle
4005 * @param bool|callable $lineCallback Optional function called before reading each query
4006 * @param bool|callable $resultCallback Optional function called for each MySQL result
4007 * @param string $fname Calling function name
4008 * @param bool|callable $inputCallback Optional function called for each complete query sent
4009 * @return bool|string
4011 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4012 $fname = __METHOD__
, $inputCallback = false
4016 while ( !feof( $fp ) ) {
4017 if ( $lineCallback ) {
4018 call_user_func( $lineCallback );
4021 $line = trim( fgets( $fp ) );
4023 if ( $line == '' ) {
4027 if ( '-' == $line[0] && '-' == $line[1] ) {
4035 $done = $this->streamStatementEnd( $cmd, $line );
4039 if ( $done ||
feof( $fp ) ) {
4040 $cmd = $this->replaceVars( $cmd );
4042 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4043 $res = $this->query( $cmd, $fname );
4045 if ( $resultCallback ) {
4046 call_user_func( $resultCallback, $res, $this );
4049 if ( false === $res ) {
4050 $err = $this->lastError();
4052 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4063 * Called by sourceStream() to check if we've reached a statement end
4065 * @param string $sql SQL assembled so far
4066 * @param string $newLine New line about to be added to $sql
4067 * @return bool Whether $newLine contains end of the statement
4069 public function streamStatementEnd( &$sql, &$newLine ) {
4070 if ( $this->delimiter
) {
4072 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4073 if ( $newLine != $prev ) {
4082 * Database independent variable replacement. Replaces a set of variables
4083 * in an SQL statement with their contents as given by $this->getSchemaVars().
4085 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4087 * - '{$var}' should be used for text and is passed through the database's
4089 * - `{$var}` should be used for identifiers (e.g. table and database names).
4090 * It is passed through the database's addIdentifierQuotes method which
4091 * can be overridden if the database uses something other than backticks.
4092 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4093 * database's tableName method.
4094 * - / *i* / passes the name that follows through the database's indexName method.
4095 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4096 * its use should be avoided. In 1.24 and older, string encoding was applied.
4098 * @param string $ins SQL statement to replace variables in
4099 * @return string The new SQL statement with variables replaced
4101 protected function replaceVars( $ins ) {
4103 $vars = $this->getSchemaVars();
4104 return preg_replace_callback(
4106 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4107 \'\{\$ (\w+) }\' | # 3. addQuotes
4108 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4109 /\*\$ (\w+) \*/ # 5. leave unencoded
4111 function ( $m ) use ( $that, $vars ) {
4112 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4113 // check for both nonexistent keys *and* the empty string.
4114 if ( isset( $m[1] ) && $m[1] !== '' ) {
4115 if ( $m[1] === 'i' ) {
4116 return $that->indexName( $m[2] );
4118 return $that->tableName( $m[2] );
4120 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4121 return $that->addQuotes( $vars[$m[3]] );
4122 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4123 return $that->addIdentifierQuotes( $vars[$m[4]] );
4124 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4125 return $vars[$m[5]];
4135 * Get schema variables. If none have been set via setSchemaVars(), then
4136 * use some defaults from the current object.
4140 protected function getSchemaVars() {
4141 if ( $this->mSchemaVars
) {
4142 return $this->mSchemaVars
;
4144 return $this->getDefaultSchemaVars();
4149 * Get schema variables to use if none have been set via setSchemaVars().
4151 * Override this in derived classes to provide variables for tables.sql
4152 * and SQL patch files.
4156 protected function getDefaultSchemaVars() {
4161 * Check to see if a named lock is available (non-blocking)
4163 * @param string $lockName Name of lock to poll
4164 * @param string $method Name of method calling us
4168 public function lockIsFree( $lockName, $method ) {
4173 * Acquire a named lock
4175 * Named locks are not related to transactions
4177 * @param string $lockName Name of lock to aquire
4178 * @param string $method Name of method calling us
4179 * @param int $timeout
4182 public function lock( $lockName, $method, $timeout = 5 ) {
4189 * Named locks are not related to transactions
4191 * @param string $lockName Name of lock to release
4192 * @param string $method Name of method calling us
4194 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4195 * by this thread (in which case the lock is not released), and NULL if the named
4196 * lock did not exist
4198 public function unlock( $lockName, $method ) {
4203 * Check to see if a named lock used by lock() use blocking queues
4208 public function namedLocksEnqueue() {
4213 * Lock specific tables
4215 * @param array $read Array of tables to lock for read access
4216 * @param array $write Array of tables to lock for write access
4217 * @param string $method Name of caller
4218 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4221 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4226 * Unlock specific tables
4228 * @param string $method The caller
4231 public function unlockTables( $method ) {
4237 * @param string $tableName
4238 * @param string $fName
4239 * @return bool|ResultWrapper
4242 public function dropTable( $tableName, $fName = __METHOD__
) {
4243 if ( !$this->tableExists( $tableName, $fName ) ) {
4246 $sql = "DROP TABLE " . $this->tableName( $tableName );
4247 if ( $this->cascadingDeletes() ) {
4251 return $this->query( $sql, $fName );
4255 * Get search engine class. All subclasses of this need to implement this
4256 * if they wish to use searching.
4260 public function getSearchEngine() {
4261 return 'SearchEngineDummy';
4265 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4266 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4267 * because "i" sorts after all numbers.
4271 public function getInfinity() {
4276 * Encode an expiry time into the DBMS dependent format
4278 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4281 public function encodeExpiry( $expiry ) {
4282 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4283 ?
$this->getInfinity()
4284 : $this->timestamp( $expiry );
4288 * Decode an expiry time into a DBMS independent format
4290 * @param string $expiry DB timestamp field value for expiry
4291 * @param int $format TS_* constant, defaults to TS_MW
4294 public function decodeExpiry( $expiry, $format = TS_MW
) {
4295 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4297 : wfTimestamp( $format, $expiry );
4301 * Allow or deny "big selects" for this session only. This is done by setting
4302 * the sql_big_selects session variable.
4304 * This is a MySQL-specific feature.
4306 * @param bool|string $value True for allow, false for deny, or "default" to
4307 * restore the initial value
4309 public function setBigSelects( $value = true ) {
4313 public function isReadOnly() {
4314 return ( $this->getReadOnlyReason() !== false );
4318 * @return string|bool Reason this DB is read-only or false if it is not
4320 protected function getReadOnlyReason() {
4321 $reason = $this->getLBInfo( 'readOnlyReason' );
4323 return is_string( $reason ) ?
$reason : false;
4330 public function __toString() {
4331 return (string)$this->mConn
;
4335 * Run a few simple sanity checks
4337 public function __destruct() {
4338 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4339 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4341 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4343 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4344 $callers[] = $callbackInfo[1];
4346 $callers = implode( ', ', $callers );
4347 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4355 abstract class Database
extends DatabaseBase
{
4356 // B/C until nothing type hints for DatabaseBase
4357 // @TODO: finish renaming DatabaseBase => Database