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;
153 * @var resource File handle for upgrade
155 protected $fileHandle = null;
159 * @var string[] Process cache of VIEWs names in the database
161 protected $allViews = null;
163 /** @var TransactionProfiler */
164 protected $trxProfiler;
167 * A string describing the current software version, and possibly
168 * other details in a user-friendly way. Will be listed on Special:Version, etc.
169 * Use getServerVersion() to get machine-friendly information.
171 * @return string Version information from the database server
173 public function getServerInfo() {
174 return $this->getServerVersion();
178 * @return string Command delimiter used by this database engine
180 public function getDelimiter() {
181 return $this->delimiter
;
185 * Boolean, controls output of large amounts of debug information.
186 * @param bool|null $debug
187 * - true to enable debugging
188 * - false to disable debugging
189 * - omitted or null to do nothing
191 * @return bool|null Previous value of the flag
193 public function debug( $debug = null ) {
194 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
198 * Turns buffering of SQL result sets on (true) or off (false). Default is
201 * Unbuffered queries are very troublesome in MySQL:
203 * - If another query is executed while the first query is being read
204 * out, the first query is killed. This means you can't call normal
205 * MediaWiki functions while you are reading an unbuffered query result
206 * from a normal wfGetDB() connection.
208 * - Unbuffered queries cause the MySQL server to use large amounts of
209 * memory and to hold broad locks which block other queries.
211 * If you want to limit client-side memory, it's almost always better to
212 * split up queries into batches using a LIMIT clause than to switch off
215 * @param null|bool $buffer
216 * @return null|bool The previous value of the flag
218 public function bufferResults( $buffer = null ) {
219 if ( is_null( $buffer ) ) {
220 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
222 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
227 * Turns on (false) or off (true) the automatic generation and sending
228 * of a "we're sorry, but there has been a database error" page on
229 * database errors. Default is on (false). When turned off, the
230 * code should use lastErrno() and lastError() to handle the
231 * situation as appropriate.
233 * Do not use this function outside of the Database classes.
235 * @param null|bool $ignoreErrors
236 * @return bool The previous value of the flag.
238 protected function ignoreErrors( $ignoreErrors = null ) {
239 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
243 * Gets the current transaction level.
245 * Historically, transactions were allowed to be "nested". This is no
246 * longer supported, so this function really only returns a boolean.
248 * @return int The previous value
250 public function trxLevel() {
251 return $this->mTrxLevel
;
255 * Get the UNIX timestamp of the time that the transaction was established
257 * This can be used to reason about the staleness of SELECT data
258 * in REPEATABLE-READ transaction isolation level.
260 * @return float|null Returns null if there is not active transaction
263 public function trxTimestamp() {
264 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
268 * Get/set the table prefix.
269 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
270 * @return string The previous table prefix.
272 public function tablePrefix( $prefix = null ) {
273 return wfSetVar( $this->mTablePrefix
, $prefix );
277 * Get/set the db schema.
278 * @param string $schema The database schema to set, or omitted to leave it unchanged.
279 * @return string The previous db schema.
281 public function dbSchema( $schema = null ) {
282 return wfSetVar( $this->mSchema
, $schema );
286 * Set the filehandle to copy write statements to.
288 * @param resource $fh File handle
290 public function setFileHandle( $fh ) {
291 $this->fileHandle
= $fh;
295 * Get properties passed down from the server info array of the load
298 * @param string $name The entry of the info array to get, or null to get the
301 * @return array|mixed|null
303 public function getLBInfo( $name = null ) {
304 if ( is_null( $name ) ) {
305 return $this->mLBInfo
;
307 if ( array_key_exists( $name, $this->mLBInfo
) ) {
308 return $this->mLBInfo
[$name];
316 * Set the LB info array, or a member of it. If called with one parameter,
317 * the LB info array is set to that parameter. If it is called with two
318 * parameters, the member with the given name is set to the given value.
320 * @param string $name
321 * @param array $value
323 public function setLBInfo( $name, $value = null ) {
324 if ( is_null( $value ) ) {
325 $this->mLBInfo
= $name;
327 $this->mLBInfo
[$name] = $value;
332 * @return TransactionProfiler
334 protected function getTransactionProfiler() {
335 return $this->trxProfiler
337 : Profiler
::instance()->getTransactionProfiler();
341 * Returns true if this database supports (and uses) cascading deletes
345 public function cascadingDeletes() {
350 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
354 public function cleanupTriggers() {
359 * Returns true if this database is strict about what can be put into an IP field.
360 * Specifically, it uses a NULL value instead of an empty string.
364 public function strictIPs() {
369 * Returns true if this database uses timestamps rather than integers
373 public function realTimestamps() {
378 * Returns true if this database does an implicit sort when doing GROUP BY
382 public function implicitGroupby() {
387 * Returns true if this database does an implicit order by when the column has an index
388 * For example: SELECT page_title FROM page LIMIT 1
392 public function implicitOrderby() {
397 * Returns true if this database can do a native search on IP columns
398 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
402 public function searchableIPs() {
407 * Returns true if this database can use functional indexes
411 public function functionalIndexes() {
416 * Return the last query that went through DatabaseBase::query()
419 public function lastQuery() {
420 return $this->mLastQuery
;
424 * Returns true if the connection may have been used for write queries.
425 * Should return true if unsure.
429 public function doneWrites() {
430 return (bool)$this->mDoneWrites
;
434 * Returns the last time the connection may have been used for write queries.
435 * Should return a timestamp if unsure.
437 * @return int|float UNIX timestamp or false
440 public function lastDoneWrites() {
441 return $this->mDoneWrites ?
: false;
445 * @return bool Whether there is a transaction open with possible write queries
448 public function writesPending() {
449 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
453 * Returns true if there is a transaction open with possible write
454 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
458 public function writesOrCallbacksPending() {
459 return $this->mTrxLevel
&& (
460 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
465 * Get the time spend running write queries for this
467 * High times could be due to scanning, updates, locking, and such
469 * @return float|bool Returns false if not transaction is active
472 public function pendingWriteQueryDuration() {
473 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
477 * Is a connection to the database open?
480 public function isOpen() {
481 return $this->mOpened
;
485 * Set a flag for this connection
487 * @param int $flag DBO_* constants from Defines.php:
488 * - DBO_DEBUG: output some debug info (same as debug())
489 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
490 * - DBO_TRX: automatically start transactions
491 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
492 * and removes it in command line mode
493 * - DBO_PERSISTENT: use persistant database connection
495 public function setFlag( $flag ) {
496 $this->mFlags |
= $flag;
500 * Clear a flag for this connection
502 * @param int $flag DBO_* constants from Defines.php:
503 * - DBO_DEBUG: output some debug info (same as debug())
504 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
505 * - DBO_TRX: automatically start transactions
506 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
507 * and removes it in command line mode
508 * - DBO_PERSISTENT: use persistant database connection
510 public function clearFlag( $flag ) {
511 $this->mFlags
&= ~
$flag;
515 * Returns a boolean whether the flag $flag is set for this connection
517 * @param int $flag DBO_* constants from Defines.php:
518 * - DBO_DEBUG: output some debug info (same as debug())
519 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
520 * - DBO_TRX: automatically start transactions
521 * - DBO_PERSISTENT: use persistant database connection
524 public function getFlag( $flag ) {
525 return !!( $this->mFlags
& $flag );
529 * General read-only accessor
531 * @param string $name
534 public function getProperty( $name ) {
541 public function getWikiID() {
542 if ( $this->mTablePrefix
) {
543 return "{$this->mDBname}-{$this->mTablePrefix}";
545 return $this->mDBname
;
550 * Return a path to the DBMS-specific SQL file if it exists,
551 * otherwise default SQL file
553 * @param string $filename
556 private function getSqlFilePath( $filename ) {
558 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
559 if ( file_exists( $dbmsSpecificFilePath ) ) {
560 return $dbmsSpecificFilePath;
562 return "$IP/maintenance/$filename";
567 * Return a path to the DBMS-specific schema file,
568 * otherwise default to tables.sql
572 public function getSchemaPath() {
573 return $this->getSqlFilePath( 'tables.sql' );
577 * Return a path to the DBMS-specific update key file,
578 * otherwise default to update-keys.sql
582 public function getUpdateKeysPath() {
583 return $this->getSqlFilePath( 'update-keys.sql' );
587 * Get information about an index into an object
588 * @param string $table Table name
589 * @param string $index Index name
590 * @param string $fname Calling function name
591 * @return mixed Database-specific index description class or false if the index does not exist
593 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
596 * Wrapper for addslashes()
598 * @param string $s String to be slashed.
599 * @return string Slashed string.
601 abstract function strencode( $s );
606 * FIXME: It is possible to construct a Database object with no associated
607 * connection object, by specifying no parameters to __construct(). This
608 * feature is deprecated and should be removed.
610 * DatabaseBase subclasses should not be constructed directly in external
611 * code. DatabaseBase::factory() should be used instead.
613 * @param array $params Parameters passed from DatabaseBase::factory()
615 function __construct( array $params ) {
616 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
618 $this->mTrxAtomicLevels
= new SplStack
;
619 $this->srvCache
= ObjectCache
::newAccelerator( 'hash' );
621 $server = $params['host'];
622 $user = $params['user'];
623 $password = $params['password'];
624 $dbName = $params['dbname'];
625 $flags = $params['flags'];
626 $tablePrefix = $params['tablePrefix'];
627 $schema = $params['schema'];
628 $foreign = $params['foreign'];
630 $this->mFlags
= $flags;
631 if ( $this->mFlags
& DBO_DEFAULT
) {
632 if ( $wgCommandLineMode ) {
633 $this->mFlags
&= ~DBO_TRX
;
635 $this->mFlags |
= DBO_TRX
;
639 $this->mSessionVars
= $params['variables'];
641 /** Get the default table prefix*/
642 if ( $tablePrefix === 'get from global' ) {
643 $this->mTablePrefix
= $wgDBprefix;
645 $this->mTablePrefix
= $tablePrefix;
648 /** Get the database schema*/
649 if ( $schema === 'get from global' ) {
650 $this->mSchema
= $wgDBmwschema;
652 $this->mSchema
= $schema;
655 $this->mForeign
= $foreign;
657 if ( isset( $params['trxProfiler'] ) ) {
658 $this->trxProfiler
= $params['trxProfiler']; // override
662 $this->open( $server, $user, $password, $dbName );
667 * Called by serialize. Throw an exception when DB connection is serialized.
668 * This causes problems on some database engines because the connection is
669 * not restored on unserialize.
671 public function __sleep() {
672 throw new MWException( 'Database serialization may cause problems, since ' .
673 'the connection is not restored on wakeup.' );
677 * Given a DB type, construct the name of the appropriate child class of
678 * DatabaseBase. This is designed to replace all of the manual stuff like:
679 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
680 * as well as validate against the canonical list of DB types we have
682 * This factory function is mostly useful for when you need to connect to a
683 * database other than the MediaWiki default (such as for external auth,
684 * an extension, et cetera). Do not use this to connect to the MediaWiki
685 * database. Example uses in core:
686 * @see LoadBalancer::reallyOpenConnection()
687 * @see ForeignDBRepo::getMasterDB()
688 * @see WebInstallerDBConnect::execute()
692 * @param string $dbType A possible DB type
693 * @param array $p An array of options to pass to the constructor.
694 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
695 * @throws MWException If the database driver or extension cannot be found
696 * @return DatabaseBase|null DatabaseBase subclass or null
698 final public static function factory( $dbType, $p = array() ) {
699 $canonicalDBTypes = array(
700 'mysql' => array( 'mysqli', 'mysql' ),
701 'postgres' => array(),
708 $dbType = strtolower( $dbType );
709 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
710 $possibleDrivers = $canonicalDBTypes[$dbType];
711 if ( !empty( $p['driver'] ) ) {
712 if ( in_array( $p['driver'], $possibleDrivers ) ) {
713 $driver = $p['driver'];
715 throw new MWException( __METHOD__
.
716 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
719 foreach ( $possibleDrivers as $posDriver ) {
720 if ( extension_loaded( $posDriver ) ) {
721 $driver = $posDriver;
729 if ( $driver === false ) {
730 throw new MWException( __METHOD__
.
731 " no viable database extension found for type '$dbType'" );
734 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
735 // and everything else doesn't use a schema (e.g. null)
736 // Although postgres and oracle support schemas, we don't use them (yet)
737 // to maintain backwards compatibility
738 $defaultSchemas = array(
739 'mssql' => 'get from global',
742 $class = 'Database' . ucfirst( $driver );
743 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
744 // Resolve some defaults for b/c
745 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
746 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
747 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
748 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
749 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
750 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
751 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
752 if ( !isset( $p['schema'] ) ) {
753 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
755 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
757 return new $class( $p );
763 protected function installErrorHandler() {
764 $this->mPHPError
= false;
765 $this->htmlErrors
= ini_set( 'html_errors', '0' );
766 set_error_handler( array( $this, 'connectionErrorHandler' ) );
770 * @return bool|string
772 protected function restoreErrorHandler() {
773 restore_error_handler();
774 if ( $this->htmlErrors
!== false ) {
775 ini_set( 'html_errors', $this->htmlErrors
);
777 if ( $this->mPHPError
) {
778 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
779 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
789 * @param string $errstr
791 public function connectionErrorHandler( $errno, $errstr ) {
792 $this->mPHPError
= $errstr;
796 * Create a log context to pass to wfLogDBError or other logging functions.
798 * @param array $extras Additional data to add to context
801 protected function getLogContext( array $extras = array() ) {
804 'db_server' => $this->mServer
,
805 'db_name' => $this->mDBname
,
806 'db_user' => $this->mUser
,
813 * Closes a database connection.
814 * if it is open : commits any open transactions
816 * @throws MWException
817 * @return bool Operation success. true if already closed.
819 public function close() {
820 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
821 throw new MWException( "Transaction idle callbacks still pending." );
823 if ( $this->mConn
) {
824 if ( $this->trxLevel() ) {
825 if ( !$this->mTrxAutomatic
) {
826 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
827 " performing implicit commit before closing connection!" );
830 $this->commit( __METHOD__
, 'flush' );
833 $closed = $this->closeConnection();
834 $this->mConn
= false;
838 $this->mOpened
= false;
844 * Make sure isOpen() returns true as a sanity check
846 * @throws DBUnexpectedError
848 protected function assertOpen() {
849 if ( !$this->isOpen() ) {
850 throw new DBUnexpectedError( $this, "DB connection was already closed." );
855 * Closes underlying database connection
857 * @return bool Whether connection was closed successfully
859 abstract protected function closeConnection();
862 * @param string $error Fallback error message, used if none is given by DB
863 * @throws DBConnectionError
865 function reportConnectionError( $error = 'Unknown error' ) {
866 $myError = $this->lastError();
872 throw new DBConnectionError( $this, $error );
876 * The DBMS-dependent part of query()
878 * @param string $sql SQL query.
879 * @return ResultWrapper|bool Result object to feed to fetchObject,
880 * fetchRow, ...; or false on failure
882 abstract protected function doQuery( $sql );
885 * Determine whether a query writes to the DB.
886 * Should return true if unsure.
891 protected function isWriteQuery( $sql ) {
892 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
896 * Determine whether a SQL statement is sensitive to isolation level.
897 * A SQL statement is considered transactable if its result could vary
898 * depending on the transaction isolation level. Operational commands
899 * such as 'SET' and 'SHOW' are not considered to be transactable.
904 protected function isTransactableQuery( $sql ) {
905 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
906 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
910 * Run an SQL query and return the result. Normally throws a DBQueryError
911 * on failure. If errors are ignored, returns false instead.
913 * In new code, the query wrappers select(), insert(), update(), delete(),
914 * etc. should be used where possible, since they give much better DBMS
915 * independence and automatically quote or validate user input in a variety
916 * of contexts. This function is generally only useful for queries which are
917 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
920 * However, the query wrappers themselves should call this function.
922 * @param string $sql SQL query
923 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
924 * comment (you can use __METHOD__ or add some extra info)
925 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
926 * maybe best to catch the exception instead?
927 * @throws MWException
928 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
929 * for a successful read query, or false on failure if $tempIgnore set
931 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
934 $this->mLastQuery
= $sql;
936 $isWriteQuery = $this->isWriteQuery( $sql );
937 if ( $isWriteQuery ) {
938 $reason = $this->getReadOnlyReason();
939 if ( $reason !== false ) {
940 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
942 # Set a flag indicating that writes have been done
943 $this->mDoneWrites
= microtime( true );
946 # Add a comment for easy SHOW PROCESSLIST interpretation
947 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
948 $userName = $wgUser->getName();
949 if ( mb_strlen( $userName ) > 15 ) {
950 $userName = mb_substr( $userName, 0, 15 ) . '...';
952 $userName = str_replace( '/', '', $userName );
957 // Add trace comment to the begin of the sql string, right after the operator.
958 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
959 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
961 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
962 $this->begin( __METHOD__
. " ($fname)" );
963 $this->mTrxAutomatic
= true;
966 # Keep track of whether the transaction has write queries pending
967 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
968 $this->mTrxDoneWrites
= true;
969 $this->getTransactionProfiler()->transactionWritingIn(
970 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
973 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
974 # generalizeSQL will probably cut down the query to reasonable
975 # logging size most of the time. The substr is really just a sanity check.
977 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
978 $totalProf = 'DatabaseBase::query-master';
980 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
981 $totalProf = 'DatabaseBase::query';
983 # Include query transaction state
984 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
986 $profiler = Profiler
::instance();
987 if ( !$profiler instanceof ProfilerStub
) {
988 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
989 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
992 if ( $this->debug() ) {
993 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $sql ) );
996 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
998 # Avoid fatals if close() was called
1001 # Do the query and handle errors
1002 $startTime = microtime( true );
1003 $ret = $this->doQuery( $commentedSql );
1004 $queryRuntime = microtime( true ) - $startTime;
1005 # Log the query time and feed it into the DB trx profiler
1006 $this->getTransactionProfiler()->recordQueryCompletion(
1007 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1009 MWDebug
::queryTime( $queryId );
1011 # Try reconnecting if the connection was lost
1012 if ( false === $ret && $this->wasErrorReissuable() ) {
1013 # Transaction is gone, like it or not
1014 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1015 $this->mTrxLevel
= 0;
1016 $this->mTrxIdleCallbacks
= array(); // bug 65263
1017 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1018 wfDebug( "Connection lost, reconnecting...\n" );
1019 # Stash the last error values since ping() might clear them
1020 $lastError = $this->lastError();
1021 $lastErrno = $this->lastErrno();
1022 if ( $this->ping() ) {
1023 wfDebug( "Reconnected\n" );
1024 $server = $this->getServer();
1025 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1026 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1029 # Leave $ret as false and let an error be reported.
1030 # Callers may catch the exception and continue to use the DB.
1031 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1033 # Should be safe to silently retry (no trx and thus no callbacks)
1034 $startTime = microtime( true );
1035 $ret = $this->doQuery( $commentedSql );
1036 $queryRuntime = microtime( true ) - $startTime;
1037 # Log the query time and feed it into the DB trx profiler
1038 $this->getTransactionProfiler()->recordQueryCompletion(
1039 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1042 wfDebug( "Failed\n" );
1046 if ( false === $ret ) {
1047 $this->reportQueryError(
1048 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1051 $res = $this->resultObject( $ret );
1053 // Destroy profile sections in the opposite order to their creation
1054 ScopedCallback
::consume( $queryProfSection );
1055 ScopedCallback
::consume( $totalProfSection );
1057 if ( $isWriteQuery && $this->mTrxLevel
) {
1058 $this->mTrxWriteDuration +
= $queryRuntime;
1065 * Report a query error. Log the error, and if neither the object ignore
1066 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1068 * @param string $error
1070 * @param string $sql
1071 * @param string $fname
1072 * @param bool $tempIgnore
1073 * @throws DBQueryError
1075 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1076 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1077 wfDebug( "SQL ERROR (ignored): $error\n" );
1079 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1081 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1082 $this->getLogContext( array(
1083 'method' => __METHOD__
,
1086 'sql1line' => $sql1line,
1090 wfDebug( "SQL ERROR: " . $error . "\n" );
1091 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1096 * Intended to be compatible with the PEAR::DB wrapper functions.
1097 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1099 * ? = scalar value, quoted as necessary
1100 * ! = raw SQL bit (a function for instance)
1101 * & = filename; reads the file and inserts as a blob
1102 * (we don't use this though...)
1104 * @param string $sql
1105 * @param string $func
1109 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1110 /* MySQL doesn't support prepared statements (yet), so just
1111 * pack up the query for reference. We'll manually replace
1114 return array( 'query' => $sql, 'func' => $func );
1118 * Free a prepared query, generated by prepare().
1119 * @param string $prepared
1121 protected function freePrepared( $prepared ) {
1122 /* No-op by default */
1126 * Execute a prepared query with the various arguments
1127 * @param string $prepared The prepared sql
1128 * @param mixed $args Either an array here, or put scalars as varargs
1130 * @return ResultWrapper
1132 public function execute( $prepared, $args = null ) {
1133 if ( !is_array( $args ) ) {
1135 $args = func_get_args();
1136 array_shift( $args );
1139 $sql = $this->fillPrepared( $prepared['query'], $args );
1141 return $this->query( $sql, $prepared['func'] );
1145 * For faking prepared SQL statements on DBs that don't support it directly.
1147 * @param string $preparedQuery A 'preparable' SQL statement
1148 * @param array $args Array of Arguments to fill it with
1149 * @return string Executable SQL
1151 public function fillPrepared( $preparedQuery, $args ) {
1153 $this->preparedArgs
=& $args;
1155 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1156 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1160 * preg_callback func for fillPrepared()
1161 * The arguments should be in $this->preparedArgs and must not be touched
1162 * while we're doing this.
1164 * @param array $matches
1165 * @throws DBUnexpectedError
1168 protected function fillPreparedArg( $matches ) {
1169 switch ( $matches[1] ) {
1178 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1180 switch ( $matches[1] ) {
1182 return $this->addQuotes( $arg );
1186 # return $this->addQuotes( file_get_contents( $arg ) );
1187 throw new DBUnexpectedError(
1189 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1192 throw new DBUnexpectedError(
1194 'Received invalid match. This should never happen!'
1200 * Free a result object returned by query() or select(). It's usually not
1201 * necessary to call this, just use unset() or let the variable holding
1202 * the result object go out of scope.
1204 * @param mixed $res A SQL result
1206 public function freeResult( $res ) {
1210 * A SELECT wrapper which returns a single field from a single result row.
1212 * Usually throws a DBQueryError on failure. If errors are explicitly
1213 * ignored, returns false on failure.
1215 * If no result rows are returned from the query, false is returned.
1217 * @param string|array $table Table name. See DatabaseBase::select() for details.
1218 * @param string $var The field name to select. This must be a valid SQL
1219 * fragment: do not use unvalidated user input.
1220 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1221 * @param string $fname The function name of the caller.
1222 * @param string|array $options The query options. See DatabaseBase::select() for details.
1224 * @return bool|mixed The value from the field, or false on failure.
1225 * @throws DBUnexpectedError
1227 public function selectField(
1228 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1230 if ( $var === '*' ) { // sanity
1231 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1234 if ( !is_array( $options ) ) {
1235 $options = array( $options );
1238 $options['LIMIT'] = 1;
1240 $res = $this->select( $table, $var, $cond, $fname, $options );
1241 if ( $res === false ||
!$this->numRows( $res ) ) {
1245 $row = $this->fetchRow( $res );
1247 if ( $row !== false ) {
1248 return reset( $row );
1255 * A SELECT wrapper which returns a list of single field values from result rows.
1257 * Usually throws a DBQueryError on failure. If errors are explicitly
1258 * ignored, returns false on failure.
1260 * If no result rows are returned from the query, false is returned.
1262 * @param string|array $table Table name. See DatabaseBase::select() for details.
1263 * @param string $var The field name to select. This must be a valid SQL
1264 * fragment: do not use unvalidated user input.
1265 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1266 * @param string $fname The function name of the caller.
1267 * @param string|array $options The query options. See DatabaseBase::select() for details.
1269 * @return bool|array The values from the field, or false on failure
1270 * @throws DBUnexpectedError
1273 public function selectFieldValues(
1274 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1276 if ( $var === '*' ) { // sanity
1277 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1280 if ( !is_array( $options ) ) {
1281 $options = array( $options );
1284 $res = $this->select( $table, $var, $cond, $fname, $options );
1285 if ( $res === false ) {
1290 foreach ( $res as $row ) {
1291 $values[] = $row->$var;
1298 * Returns an optional USE INDEX clause to go after the table, and a
1299 * string to go at the end of the query.
1301 * @param array $options Associative array of options to be turned into
1302 * an SQL query, valid keys are listed in the function.
1304 * @see DatabaseBase::select()
1306 public function makeSelectOptions( $options ) {
1307 $preLimitTail = $postLimitTail = '';
1310 $noKeyOptions = array();
1312 foreach ( $options as $key => $option ) {
1313 if ( is_numeric( $key ) ) {
1314 $noKeyOptions[$option] = true;
1318 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1320 $preLimitTail .= $this->makeOrderBy( $options );
1322 // if (isset($options['LIMIT'])) {
1323 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1324 // isset($options['OFFSET']) ? $options['OFFSET']
1328 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1329 $postLimitTail .= ' FOR UPDATE';
1332 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1333 $postLimitTail .= ' LOCK IN SHARE MODE';
1336 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1337 $startOpts .= 'DISTINCT';
1340 # Various MySQL extensions
1341 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1342 $startOpts .= ' /*! STRAIGHT_JOIN */';
1345 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1346 $startOpts .= ' HIGH_PRIORITY';
1349 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1350 $startOpts .= ' SQL_BIG_RESULT';
1353 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1354 $startOpts .= ' SQL_BUFFER_RESULT';
1357 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1358 $startOpts .= ' SQL_SMALL_RESULT';
1361 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1362 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1365 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1366 $startOpts .= ' SQL_CACHE';
1369 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1370 $startOpts .= ' SQL_NO_CACHE';
1373 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1374 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1379 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1383 * Returns an optional GROUP BY with an optional HAVING
1385 * @param array $options Associative array of options
1387 * @see DatabaseBase::select()
1390 public function makeGroupByWithHaving( $options ) {
1392 if ( isset( $options['GROUP BY'] ) ) {
1393 $gb = is_array( $options['GROUP BY'] )
1394 ?
implode( ',', $options['GROUP BY'] )
1395 : $options['GROUP BY'];
1396 $sql .= ' GROUP BY ' . $gb;
1398 if ( isset( $options['HAVING'] ) ) {
1399 $having = is_array( $options['HAVING'] )
1400 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1401 : $options['HAVING'];
1402 $sql .= ' HAVING ' . $having;
1409 * Returns an optional ORDER BY
1411 * @param array $options Associative array of options
1413 * @see DatabaseBase::select()
1416 public function makeOrderBy( $options ) {
1417 if ( isset( $options['ORDER BY'] ) ) {
1418 $ob = is_array( $options['ORDER BY'] )
1419 ?
implode( ',', $options['ORDER BY'] )
1420 : $options['ORDER BY'];
1422 return ' ORDER BY ' . $ob;
1429 * Execute a SELECT query constructed using the various parameters provided.
1430 * See below for full details of the parameters.
1432 * @param string|array $table Table name
1433 * @param string|array $vars Field names
1434 * @param string|array $conds Conditions
1435 * @param string $fname Caller function name
1436 * @param array $options Query options
1437 * @param array $join_conds Join conditions
1440 * @param string|array $table
1442 * May be either an array of table names, or a single string holding a table
1443 * name. If an array is given, table aliases can be specified, for example:
1445 * array( 'a' => 'user' )
1447 * This includes the user table in the query, with the alias "a" available
1448 * for use in field names (e.g. a.user_name).
1450 * All of the table names given here are automatically run through
1451 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1452 * added, and various other table name mappings to be performed.
1455 * @param string|array $vars
1457 * May be either a field name or an array of field names. The field names
1458 * can be complete fragments of SQL, for direct inclusion into the SELECT
1459 * query. If an array is given, field aliases can be specified, for example:
1461 * array( 'maxrev' => 'MAX(rev_id)' )
1463 * This includes an expression with the alias "maxrev" in the query.
1465 * If an expression is given, care must be taken to ensure that it is
1469 * @param string|array $conds
1471 * May be either a string containing a single condition, or an array of
1472 * conditions. If an array is given, the conditions constructed from each
1473 * element are combined with AND.
1475 * Array elements may take one of two forms:
1477 * - Elements with a numeric key are interpreted as raw SQL fragments.
1478 * - Elements with a string key are interpreted as equality conditions,
1479 * where the key is the field name.
1480 * - If the value of such an array element is a scalar (such as a
1481 * string), it will be treated as data and thus quoted appropriately.
1482 * If it is null, an IS NULL clause will be added.
1483 * - If the value is an array, an IN (...) clause will be constructed
1484 * from its non-null elements, and an IS NULL clause will be added
1485 * if null is present, such that the field may match any of the
1486 * elements in the array. The non-null elements will be quoted.
1488 * Note that expressions are often DBMS-dependent in their syntax.
1489 * DBMS-independent wrappers are provided for constructing several types of
1490 * expression commonly used in condition queries. See:
1491 * - DatabaseBase::buildLike()
1492 * - DatabaseBase::conditional()
1495 * @param string|array $options
1497 * Optional: Array of query options. Boolean options are specified by
1498 * including them in the array as a string value with a numeric key, for
1501 * array( 'FOR UPDATE' )
1503 * The supported options are:
1505 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1506 * with LIMIT can theoretically be used for paging through a result set,
1507 * but this is discouraged in MediaWiki for performance reasons.
1509 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1510 * and then the first rows are taken until the limit is reached. LIMIT
1511 * is applied to a result set after OFFSET.
1513 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1514 * changed until the next COMMIT.
1516 * - DISTINCT: Boolean: return only unique result rows.
1518 * - GROUP BY: May be either an SQL fragment string naming a field or
1519 * expression to group by, or an array of such SQL fragments.
1521 * - HAVING: May be either an string containing a HAVING clause or an array of
1522 * conditions building the HAVING clause. If an array is given, the conditions
1523 * constructed from each element are combined with AND.
1525 * - ORDER BY: May be either an SQL fragment giving a field name or
1526 * expression to order by, or an array of such SQL fragments.
1528 * - USE INDEX: This may be either a string giving the index name to use
1529 * for the query, or an array. If it is an associative array, each key
1530 * gives the table name (or alias), each value gives the index name to
1531 * use for that table. All strings are SQL fragments and so should be
1532 * validated by the caller.
1534 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1535 * instead of SELECT.
1537 * And also the following boolean MySQL extensions, see the MySQL manual
1538 * for documentation:
1540 * - LOCK IN SHARE MODE
1544 * - SQL_BUFFER_RESULT
1545 * - SQL_SMALL_RESULT
1546 * - SQL_CALC_FOUND_ROWS
1551 * @param string|array $join_conds
1553 * Optional associative array of table-specific join conditions. In the
1554 * most common case, this is unnecessary, since the join condition can be
1555 * in $conds. However, it is useful for doing a LEFT JOIN.
1557 * The key of the array contains the table name or alias. The value is an
1558 * array with two elements, numbered 0 and 1. The first gives the type of
1559 * join, the second is an SQL fragment giving the join condition for that
1560 * table. For example:
1562 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1564 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1565 * with no rows in it will be returned. If there was a query error, a
1566 * DBQueryError exception will be thrown, except if the "ignore errors"
1567 * option was set, in which case false will be returned.
1569 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1570 $options = array(), $join_conds = array() ) {
1571 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1573 return $this->query( $sql, $fname );
1577 * The equivalent of DatabaseBase::select() except that the constructed SQL
1578 * is returned, instead of being immediately executed. This can be useful for
1579 * doing UNION queries, where the SQL text of each query is needed. In general,
1580 * however, callers outside of Database classes should just use select().
1582 * @param string|array $table Table name
1583 * @param string|array $vars Field names
1584 * @param string|array $conds Conditions
1585 * @param string $fname Caller function name
1586 * @param string|array $options Query options
1587 * @param string|array $join_conds Join conditions
1589 * @return string SQL query string.
1590 * @see DatabaseBase::select()
1592 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1593 $options = array(), $join_conds = array()
1595 if ( is_array( $vars ) ) {
1596 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1599 $options = (array)$options;
1600 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1601 ?
$options['USE INDEX']
1604 if ( is_array( $table ) ) {
1606 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1607 } elseif ( $table != '' ) {
1608 if ( $table[0] == ' ' ) {
1609 $from = ' FROM ' . $table;
1612 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1618 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1619 $this->makeSelectOptions( $options );
1621 if ( !empty( $conds ) ) {
1622 if ( is_array( $conds ) ) {
1623 $conds = $this->makeList( $conds, LIST_AND
);
1625 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1627 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1630 if ( isset( $options['LIMIT'] ) ) {
1631 $sql = $this->limitResult( $sql, $options['LIMIT'],
1632 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1634 $sql = "$sql $postLimitTail";
1636 if ( isset( $options['EXPLAIN'] ) ) {
1637 $sql = 'EXPLAIN ' . $sql;
1644 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1645 * that a single row object is returned. If the query returns no rows,
1646 * false is returned.
1648 * @param string|array $table Table name
1649 * @param string|array $vars Field names
1650 * @param array $conds Conditions
1651 * @param string $fname Caller function name
1652 * @param string|array $options Query options
1653 * @param array|string $join_conds Join conditions
1655 * @return stdClass|bool
1657 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1658 $options = array(), $join_conds = array()
1660 $options = (array)$options;
1661 $options['LIMIT'] = 1;
1662 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1664 if ( $res === false ) {
1668 if ( !$this->numRows( $res ) ) {
1672 $obj = $this->fetchObject( $res );
1678 * Estimate the number of rows in dataset
1680 * MySQL allows you to estimate the number of rows that would be returned
1681 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1682 * index cardinality statistics, and is notoriously inaccurate, especially
1683 * when large numbers of rows have recently been added or deleted.
1685 * For DBMSs that don't support fast result size estimation, this function
1686 * will actually perform the SELECT COUNT(*).
1688 * Takes the same arguments as DatabaseBase::select().
1690 * @param string $table Table name
1691 * @param string $vars Unused
1692 * @param array|string $conds Filters on the table
1693 * @param string $fname Function name for profiling
1694 * @param array $options Options for select
1695 * @return int Row count
1697 public function estimateRowCount(
1698 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1701 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1704 $row = $this->fetchRow( $res );
1705 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1712 * Get the number of rows in dataset
1714 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1716 * Takes the same arguments as DatabaseBase::select().
1718 * @since 1.27 Added $join_conds parameter
1720 * @param array|string $tables Table names
1721 * @param string $vars Unused
1722 * @param array|string $conds Filters on the table
1723 * @param string $fname Function name for profiling
1724 * @param array $options Options for select
1725 * @param array $join_conds Join conditions (since 1.27)
1726 * @return int Row count
1728 public function selectRowCount(
1729 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1732 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1733 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1736 $row = $this->fetchRow( $res );
1737 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1744 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1745 * It's only slightly flawed. Don't use for anything important.
1747 * @param string $sql A SQL Query
1751 protected static function generalizeSQL( $sql ) {
1752 # This does the same as the regexp below would do, but in such a way
1753 # as to avoid crashing php on some large strings.
1754 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1756 $sql = str_replace( "\\\\", '', $sql );
1757 $sql = str_replace( "\\'", '', $sql );
1758 $sql = str_replace( "\\\"", '', $sql );
1759 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1760 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1762 # All newlines, tabs, etc replaced by single space
1763 $sql = preg_replace( '/\s+/', ' ', $sql );
1766 # except the ones surrounded by characters, e.g. l10n
1767 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1768 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1774 * Determines whether a field exists in a table
1776 * @param string $table Table name
1777 * @param string $field Filed to check on that table
1778 * @param string $fname Calling function name (optional)
1779 * @return bool Whether $table has filed $field
1781 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1782 $info = $this->fieldInfo( $table, $field );
1788 * Determines whether an index exists
1789 * Usually throws a DBQueryError on failure
1790 * If errors are explicitly ignored, returns NULL on failure
1792 * @param string $table
1793 * @param string $index
1794 * @param string $fname
1797 public function indexExists( $table, $index, $fname = __METHOD__
) {
1798 if ( !$this->tableExists( $table ) ) {
1802 $info = $this->indexInfo( $table, $index, $fname );
1803 if ( is_null( $info ) ) {
1806 return $info !== false;
1811 * Query whether a given table exists
1813 * @param string $table
1814 * @param string $fname
1817 public function tableExists( $table, $fname = __METHOD__
) {
1818 $table = $this->tableName( $table );
1819 $old = $this->ignoreErrors( true );
1820 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1821 $this->ignoreErrors( $old );
1827 * Determines if a given index is unique
1829 * @param string $table
1830 * @param string $index
1834 public function indexUnique( $table, $index ) {
1835 $indexInfo = $this->indexInfo( $table, $index );
1837 if ( !$indexInfo ) {
1841 return !$indexInfo[0]->Non_unique
;
1845 * Helper for DatabaseBase::insert().
1847 * @param array $options
1850 protected function makeInsertOptions( $options ) {
1851 return implode( ' ', $options );
1855 * INSERT wrapper, inserts an array into a table.
1859 * - A single associative array. The array keys are the field names, and
1860 * the values are the values to insert. The values are treated as data
1861 * and will be quoted appropriately. If NULL is inserted, this will be
1862 * converted to a database NULL.
1863 * - An array with numeric keys, holding a list of associative arrays.
1864 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1865 * each subarray must be identical to each other, and in the same order.
1867 * $options is an array of options, with boolean options encoded as values
1868 * with numeric keys, in the same style as $options in
1869 * DatabaseBase::select(). Supported options are:
1871 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1872 * any rows which cause duplicate key errors are not inserted. It's
1873 * possible to determine how many rows were successfully inserted using
1874 * DatabaseBase::affectedRows().
1876 * @param string $table Table name. This will be passed through
1877 * DatabaseBase::tableName().
1878 * @param array $a Array of rows to insert
1879 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1880 * @param array $options Array of options
1882 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1887 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1888 # No rows to insert, easy just return now
1889 if ( !count( $a ) ) {
1893 $table = $this->tableName( $table );
1895 if ( !is_array( $options ) ) {
1896 $options = array( $options );
1900 if ( isset( $options['fileHandle'] ) ) {
1901 $fh = $options['fileHandle'];
1903 $options = $this->makeInsertOptions( $options );
1905 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1907 $keys = array_keys( $a[0] );
1910 $keys = array_keys( $a );
1913 $sql = 'INSERT ' . $options .
1914 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1918 foreach ( $a as $row ) {
1924 $sql .= '(' . $this->makeList( $row ) . ')';
1927 $sql .= '(' . $this->makeList( $a ) . ')';
1930 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1932 } elseif ( $fh !== null ) {
1936 return (bool)$this->query( $sql, $fname );
1940 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1942 * @param array $options
1945 protected function makeUpdateOptionsArray( $options ) {
1946 if ( !is_array( $options ) ) {
1947 $options = array( $options );
1952 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1953 $opts[] = $this->lowPriorityOption();
1956 if ( in_array( 'IGNORE', $options ) ) {
1964 * Make UPDATE options for the DatabaseBase::update function
1966 * @param array $options The options passed to DatabaseBase::update
1969 protected function makeUpdateOptions( $options ) {
1970 $opts = $this->makeUpdateOptionsArray( $options );
1972 return implode( ' ', $opts );
1976 * UPDATE wrapper. Takes a condition array and a SET array.
1978 * @param string $table Name of the table to UPDATE. This will be passed through
1979 * DatabaseBase::tableName().
1980 * @param array $values An array of values to SET. For each array element,
1981 * the key gives the field name, and the value gives the data to set
1982 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1983 * @param array $conds An array of conditions (WHERE). See
1984 * DatabaseBase::select() for the details of the format of condition
1985 * arrays. Use '*' to update all rows.
1986 * @param string $fname The function name of the caller (from __METHOD__),
1987 * for logging and profiling.
1988 * @param array $options An array of UPDATE options, can be:
1989 * - IGNORE: Ignore unique key conflicts
1990 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1993 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1994 $table = $this->tableName( $table );
1995 $opts = $this->makeUpdateOptions( $options );
1996 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1998 if ( $conds !== array() && $conds !== '*' ) {
1999 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2002 return $this->query( $sql, $fname );
2006 * Makes an encoded list of strings from an array
2008 * @param array $a Containing the data
2009 * @param int $mode Constant
2010 * - LIST_COMMA: Comma separated, no field names
2011 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2012 * documentation for $conds in DatabaseBase::select().
2013 * - LIST_OR: ORed WHERE clause (without the WHERE)
2014 * - LIST_SET: Comma separated with field names, like a SET clause
2015 * - LIST_NAMES: Comma separated field names
2016 * @throws MWException|DBUnexpectedError
2019 public function makeList( $a, $mode = LIST_COMMA
) {
2020 if ( !is_array( $a ) ) {
2021 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2027 foreach ( $a as $field => $value ) {
2029 if ( $mode == LIST_AND
) {
2031 } elseif ( $mode == LIST_OR
) {
2040 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2041 $list .= "($value)";
2042 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2044 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2045 // Remove null from array to be handled separately if found
2046 $includeNull = false;
2047 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2048 $includeNull = true;
2049 unset( $value[$nullKey] );
2051 if ( count( $value ) == 0 && !$includeNull ) {
2052 throw new MWException( __METHOD__
. ": empty input for field $field" );
2053 } elseif ( count( $value ) == 0 ) {
2054 // only check if $field is null
2055 $list .= "$field IS NULL";
2057 // IN clause contains at least one valid element
2058 if ( $includeNull ) {
2059 // Group subconditions to ensure correct precedence
2062 if ( count( $value ) == 1 ) {
2063 // Special-case single values, as IN isn't terribly efficient
2064 // Don't necessarily assume the single key is 0; we don't
2065 // enforce linear numeric ordering on other arrays here.
2066 $value = array_values( $value );
2067 $list .= $field . " = " . $this->addQuotes( $value[0] );
2069 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2071 // if null present in array, append IS NULL
2072 if ( $includeNull ) {
2073 $list .= " OR $field IS NULL)";
2076 } elseif ( $value === null ) {
2077 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2078 $list .= "$field IS ";
2079 } elseif ( $mode == LIST_SET
) {
2080 $list .= "$field = ";
2084 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2085 $list .= "$field = ";
2087 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2095 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2096 * The keys on each level may be either integers or strings.
2098 * @param array $data Organized as 2-d
2099 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2100 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2101 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2102 * @return string|bool SQL fragment, or false if no items in array
2104 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2107 foreach ( $data as $base => $sub ) {
2108 if ( count( $sub ) ) {
2109 $conds[] = $this->makeList(
2110 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2116 return $this->makeList( $conds, LIST_OR
);
2118 // Nothing to search for...
2124 * Return aggregated value alias
2126 * @param array $valuedata
2127 * @param string $valuename
2131 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2136 * @param string $field
2139 public function bitNot( $field ) {
2144 * @param string $fieldLeft
2145 * @param string $fieldRight
2148 public function bitAnd( $fieldLeft, $fieldRight ) {
2149 return "($fieldLeft & $fieldRight)";
2153 * @param string $fieldLeft
2154 * @param string $fieldRight
2157 public function bitOr( $fieldLeft, $fieldRight ) {
2158 return "($fieldLeft | $fieldRight)";
2162 * Build a concatenation list to feed into a SQL query
2163 * @param array $stringList List of raw SQL expressions; caller is
2164 * responsible for any quoting
2167 public function buildConcat( $stringList ) {
2168 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2172 * Build a GROUP_CONCAT or equivalent statement for a query.
2174 * This is useful for combining a field for several rows into a single string.
2175 * NULL values will not appear in the output, duplicated values will appear,
2176 * and the resulting delimiter-separated values have no defined sort order.
2177 * Code using the results may need to use the PHP unique() or sort() methods.
2179 * @param string $delim Glue to bind the results together
2180 * @param string|array $table Table name
2181 * @param string $field Field name
2182 * @param string|array $conds Conditions
2183 * @param string|array $join_conds Join conditions
2184 * @return string SQL text
2187 public function buildGroupConcatField(
2188 $delim, $table, $field, $conds = '', $join_conds = array()
2190 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2192 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2196 * Change the current database
2198 * @todo Explain what exactly will fail if this is not overridden.
2202 * @return bool Success or failure
2204 public function selectDB( $db ) {
2205 # Stub. Shouldn't cause serious problems if it's not overridden, but
2206 # if your database engine supports a concept similar to MySQL's
2207 # databases you may as well.
2208 $this->mDBname
= $db;
2214 * Get the current DB name
2217 public function getDBname() {
2218 return $this->mDBname
;
2222 * Get the server hostname or IP address
2225 public function getServer() {
2226 return $this->mServer
;
2230 * Format a table name ready for use in constructing an SQL query
2232 * This does two important things: it quotes the table names to clean them up,
2233 * and it adds a table prefix if only given a table name with no quotes.
2235 * All functions of this object which require a table name call this function
2236 * themselves. Pass the canonical name to such functions. This is only needed
2237 * when calling query() directly.
2239 * @param string $name Database table name
2240 * @param string $format One of:
2241 * quoted - Automatically pass the table name through addIdentifierQuotes()
2242 * so that it can be used in a query.
2243 * raw - Do not add identifier quotes to the table name
2244 * @return string Full database name
2246 public function tableName( $name, $format = 'quoted' ) {
2247 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2248 # Skip the entire process when we have a string quoted on both ends.
2249 # Note that we check the end so that we will still quote any use of
2250 # use of `database`.table. But won't break things if someone wants
2251 # to query a database table with a dot in the name.
2252 if ( $this->isQuotedIdentifier( $name ) ) {
2256 # Lets test for any bits of text that should never show up in a table
2257 # name. Basically anything like JOIN or ON which are actually part of
2258 # SQL queries, but may end up inside of the table value to combine
2259 # sql. Such as how the API is doing.
2260 # Note that we use a whitespace test rather than a \b test to avoid
2261 # any remote case where a word like on may be inside of a table name
2262 # surrounded by symbols which may be considered word breaks.
2263 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2267 # Split database and table into proper variables.
2268 # We reverse the explode so that database.table and table both output
2269 # the correct table.
2270 $dbDetails = explode( '.', $name, 3 );
2271 if ( count( $dbDetails ) == 3 ) {
2272 list( $database, $schema, $table ) = $dbDetails;
2273 # We don't want any prefix added in this case
2275 } elseif ( count( $dbDetails ) == 2 ) {
2276 list( $database, $table ) = $dbDetails;
2277 # We don't want any prefix added in this case
2278 # In dbs that support it, $database may actually be the schema
2279 # but that doesn't affect any of the functionality here
2283 list( $table ) = $dbDetails;
2284 if ( $wgSharedDB !== null # We have a shared database
2285 && $this->mForeign
== false # We're not working on a foreign database
2286 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2287 && in_array( $table, $wgSharedTables ) # A shared table is selected
2289 $database = $wgSharedDB;
2290 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2291 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2294 $schema = $this->mSchema
; # Default schema
2295 $prefix = $this->mTablePrefix
; # Default prefix
2299 # Quote $table and apply the prefix if not quoted.
2300 # $tableName might be empty if this is called from Database::replaceVars()
2301 $tableName = "{$prefix}{$table}";
2302 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2303 $tableName = $this->addIdentifierQuotes( $tableName );
2306 # Quote $schema and merge it with the table name if needed
2307 if ( strlen( $schema ) ) {
2308 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2309 $schema = $this->addIdentifierQuotes( $schema );
2311 $tableName = $schema . '.' . $tableName;
2314 # Quote $database and merge it with the table name if needed
2315 if ( $database !== null ) {
2316 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2317 $database = $this->addIdentifierQuotes( $database );
2319 $tableName = $database . '.' . $tableName;
2326 * Fetch a number of table names into an array
2327 * This is handy when you need to construct SQL for joins
2330 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2331 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2332 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2336 public function tableNames() {
2337 $inArray = func_get_args();
2340 foreach ( $inArray as $name ) {
2341 $retVal[$name] = $this->tableName( $name );
2348 * Fetch a number of table names into an zero-indexed numerical array
2349 * This is handy when you need to construct SQL for joins
2352 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2353 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2354 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2358 public function tableNamesN() {
2359 $inArray = func_get_args();
2362 foreach ( $inArray as $name ) {
2363 $retVal[] = $this->tableName( $name );
2370 * Get an aliased table name
2371 * e.g. tableName AS newTableName
2373 * @param string $name Table name, see tableName()
2374 * @param string|bool $alias Alias (optional)
2375 * @return string SQL name for aliased table. Will not alias a table to its own name
2377 public function tableNameWithAlias( $name, $alias = false ) {
2378 if ( !$alias ||
$alias == $name ) {
2379 return $this->tableName( $name );
2381 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2386 * Gets an array of aliased table names
2388 * @param array $tables Array( [alias] => table )
2389 * @return string[] See tableNameWithAlias()
2391 public function tableNamesWithAlias( $tables ) {
2393 foreach ( $tables as $alias => $table ) {
2394 if ( is_numeric( $alias ) ) {
2397 $retval[] = $this->tableNameWithAlias( $table, $alias );
2404 * Get an aliased field name
2405 * e.g. fieldName AS newFieldName
2407 * @param string $name Field name
2408 * @param string|bool $alias Alias (optional)
2409 * @return string SQL name for aliased field. Will not alias a field to its own name
2411 public function fieldNameWithAlias( $name, $alias = false ) {
2412 if ( !$alias ||
(string)$alias === (string)$name ) {
2415 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2420 * Gets an array of aliased field names
2422 * @param array $fields Array( [alias] => field )
2423 * @return string[] See fieldNameWithAlias()
2425 public function fieldNamesWithAlias( $fields ) {
2427 foreach ( $fields as $alias => $field ) {
2428 if ( is_numeric( $alias ) ) {
2431 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2438 * Get the aliased table name clause for a FROM clause
2439 * which might have a JOIN and/or USE INDEX clause
2441 * @param array $tables ( [alias] => table )
2442 * @param array $use_index Same as for select()
2443 * @param array $join_conds Same as for select()
2446 protected function tableNamesWithUseIndexOrJOIN(
2447 $tables, $use_index = array(), $join_conds = array()
2451 $use_index = (array)$use_index;
2452 $join_conds = (array)$join_conds;
2454 foreach ( $tables as $alias => $table ) {
2455 if ( !is_string( $alias ) ) {
2456 // No alias? Set it equal to the table name
2459 // Is there a JOIN clause for this table?
2460 if ( isset( $join_conds[$alias] ) ) {
2461 list( $joinType, $conds ) = $join_conds[$alias];
2462 $tableClause = $joinType;
2463 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2464 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2465 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2467 $tableClause .= ' ' . $use;
2470 $on = $this->makeList( (array)$conds, LIST_AND
);
2472 $tableClause .= ' ON (' . $on . ')';
2475 $retJOIN[] = $tableClause;
2476 } elseif ( isset( $use_index[$alias] ) ) {
2477 // Is there an INDEX clause for this table?
2478 $tableClause = $this->tableNameWithAlias( $table, $alias );
2479 $tableClause .= ' ' . $this->useIndexClause(
2480 implode( ',', (array)$use_index[$alias] )
2483 $ret[] = $tableClause;
2485 $tableClause = $this->tableNameWithAlias( $table, $alias );
2487 $ret[] = $tableClause;
2491 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2492 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2493 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2495 // Compile our final table clause
2496 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2500 * Get the name of an index in a given table.
2502 * @protected Don't use outside of DatabaseBase and childs
2503 * @param string $index
2506 public function indexName( $index ) {
2507 // @FIXME: Make this protected once we move away from PHP 5.3
2508 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2510 // Backwards-compatibility hack
2512 'ar_usertext_timestamp' => 'usertext_timestamp',
2513 'un_user_id' => 'user_id',
2514 'un_user_ip' => 'user_ip',
2517 if ( isset( $renamed[$index] ) ) {
2518 return $renamed[$index];
2525 * Adds quotes and backslashes.
2527 * @param string|Blob $s
2530 public function addQuotes( $s ) {
2531 if ( $s instanceof Blob
) {
2534 if ( $s === null ) {
2537 # This will also quote numeric values. This should be harmless,
2538 # and protects against weird problems that occur when they really
2539 # _are_ strings such as article titles and string->number->string
2540 # conversion is not 1:1.
2541 return "'" . $this->strencode( $s ) . "'";
2546 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2547 * MySQL uses `backticks` while basically everything else uses double quotes.
2548 * Since MySQL is the odd one out here the double quotes are our generic
2549 * and we implement backticks in DatabaseMysql.
2554 public function addIdentifierQuotes( $s ) {
2555 return '"' . str_replace( '"', '""', $s ) . '"';
2559 * Returns if the given identifier looks quoted or not according to
2560 * the database convention for quoting identifiers .
2562 * @param string $name
2565 public function isQuotedIdentifier( $name ) {
2566 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2573 protected function escapeLikeInternal( $s ) {
2574 return addcslashes( $s, '\%_' );
2578 * LIKE statement wrapper, receives a variable-length argument list with
2579 * parts of pattern to match containing either string literals that will be
2580 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2581 * the function could be provided with an array of aforementioned
2584 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2585 * a LIKE clause that searches for subpages of 'My page title'.
2587 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2588 * $query .= $dbr->buildLike( $pattern );
2591 * @return string Fully built LIKE statement
2593 public function buildLike() {
2594 $params = func_get_args();
2596 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2597 $params = $params[0];
2602 foreach ( $params as $value ) {
2603 if ( $value instanceof LikeMatch
) {
2604 $s .= $value->toString();
2606 $s .= $this->escapeLikeInternal( $value );
2610 return " LIKE {$this->addQuotes( $s )} ";
2614 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2618 public function anyChar() {
2619 return new LikeMatch( '_' );
2623 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2627 public function anyString() {
2628 return new LikeMatch( '%' );
2632 * Returns an appropriately quoted sequence value for inserting a new row.
2633 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2634 * subclass will return an integer, and save the value for insertId()
2636 * Any implementation of this function should *not* involve reusing
2637 * sequence numbers created for rolled-back transactions.
2638 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2639 * @param string $seqName
2642 public function nextSequenceValue( $seqName ) {
2647 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2648 * is only needed because a) MySQL must be as efficient as possible due to
2649 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2650 * which index to pick. Anyway, other databases might have different
2651 * indexes on a given table. So don't bother overriding this unless you're
2653 * @param string $index
2656 public function useIndexClause( $index ) {
2661 * REPLACE query wrapper.
2663 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2664 * except that when there is a duplicate key error, the old row is deleted
2665 * and the new row is inserted in its place.
2667 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2668 * perform the delete, we need to know what the unique indexes are so that
2669 * we know how to find the conflicting rows.
2671 * It may be more efficient to leave off unique indexes which are unlikely
2672 * to collide. However if you do this, you run the risk of encountering
2673 * errors which wouldn't have occurred in MySQL.
2675 * @param string $table The table to replace the row(s) in.
2676 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2677 * a field name or an array of field names
2678 * @param array $rows Can be either a single row to insert, or multiple rows,
2679 * in the same format as for DatabaseBase::insert()
2680 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2682 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2683 $quotedTable = $this->tableName( $table );
2685 if ( count( $rows ) == 0 ) {
2690 if ( !is_array( reset( $rows ) ) ) {
2691 $rows = array( $rows );
2694 // @FXIME: this is not atomic, but a trx would break affectedRows()
2695 foreach ( $rows as $row ) {
2696 # Delete rows which collide
2697 if ( $uniqueIndexes ) {
2698 $sql = "DELETE FROM $quotedTable WHERE ";
2700 foreach ( $uniqueIndexes as $index ) {
2707 if ( is_array( $index ) ) {
2709 foreach ( $index as $col ) {
2715 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2718 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2722 $this->query( $sql, $fname );
2725 # Now insert the row
2726 $this->insert( $table, $row, $fname );
2731 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2734 * @param string $table Table name
2735 * @param array|string $rows Row(s) to insert
2736 * @param string $fname Caller function name
2738 * @return ResultWrapper
2740 protected function nativeReplace( $table, $rows, $fname ) {
2741 $table = $this->tableName( $table );
2744 if ( !is_array( reset( $rows ) ) ) {
2745 $rows = array( $rows );
2748 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2751 foreach ( $rows as $row ) {
2758 $sql .= '(' . $this->makeList( $row ) . ')';
2761 return $this->query( $sql, $fname );
2765 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2767 * This updates any conflicting rows (according to the unique indexes) using
2768 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2770 * $rows may be either:
2771 * - A single associative array. The array keys are the field names, and
2772 * the values are the values to insert. The values are treated as data
2773 * and will be quoted appropriately. If NULL is inserted, this will be
2774 * converted to a database NULL.
2775 * - An array with numeric keys, holding a list of associative arrays.
2776 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2777 * each subarray must be identical to each other, and in the same order.
2779 * It may be more efficient to leave off unique indexes which are unlikely
2780 * to collide. However if you do this, you run the risk of encountering
2781 * errors which wouldn't have occurred in MySQL.
2783 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2788 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2789 * @param array $rows A single row or list of rows to insert
2790 * @param array $uniqueIndexes List of single field names or field name tuples
2791 * @param array $set An array of values to SET. For each array element, the
2792 * key gives the field name, and the value gives the data to set that
2793 * field to. The data will be quoted by DatabaseBase::addQuotes().
2794 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2798 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2801 if ( !count( $rows ) ) {
2802 return true; // nothing to do
2805 if ( !is_array( reset( $rows ) ) ) {
2806 $rows = array( $rows );
2809 if ( count( $uniqueIndexes ) ) {
2810 $clauses = array(); // list WHERE clauses that each identify a single row
2811 foreach ( $rows as $row ) {
2812 foreach ( $uniqueIndexes as $index ) {
2813 $index = is_array( $index ) ?
$index : array( $index ); // columns
2814 $rowKey = array(); // unique key to this row
2815 foreach ( $index as $column ) {
2816 $rowKey[$column] = $row[$column];
2818 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2821 $where = array( $this->makeList( $clauses, LIST_OR
) );
2826 $useTrx = !$this->mTrxLevel
;
2828 $this->begin( $fname );
2831 # Update any existing conflicting row(s)
2832 if ( $where !== false ) {
2833 $ok = $this->update( $table, $set, $where, $fname );
2837 # Now insert any non-conflicting row(s)
2838 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2839 } catch ( Exception
$e ) {
2841 $this->rollback( $fname );
2846 $this->commit( $fname );
2853 * DELETE where the condition is a join.
2855 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2856 * we use sub-selects
2858 * For safety, an empty $conds will not delete everything. If you want to
2859 * delete all rows where the join condition matches, set $conds='*'.
2861 * DO NOT put the join condition in $conds.
2863 * @param string $delTable The table to delete from.
2864 * @param string $joinTable The other table.
2865 * @param string $delVar The variable to join on, in the first table.
2866 * @param string $joinVar The variable to join on, in the second table.
2867 * @param array $conds Condition array of field names mapped to variables,
2868 * ANDed together in the WHERE clause
2869 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2870 * @throws DBUnexpectedError
2872 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2876 throw new DBUnexpectedError( $this,
2877 'DatabaseBase::deleteJoin() called with empty $conds' );
2880 $delTable = $this->tableName( $delTable );
2881 $joinTable = $this->tableName( $joinTable );
2882 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2883 if ( $conds != '*' ) {
2884 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2888 $this->query( $sql, $fname );
2892 * Returns the size of a text field, or -1 for "unlimited"
2894 * @param string $table
2895 * @param string $field
2898 public function textFieldSize( $table, $field ) {
2899 $table = $this->tableName( $table );
2900 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2901 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2902 $row = $this->fetchObject( $res );
2906 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2916 * A string to insert into queries to show that they're low-priority, like
2917 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2918 * string and nothing bad should happen.
2920 * @return string Returns the text of the low priority option if it is
2921 * supported, or a blank string otherwise
2923 public function lowPriorityOption() {
2928 * DELETE query wrapper.
2930 * @param array $table Table name
2931 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2932 * for the format. Use $conds == "*" to delete all rows
2933 * @param string $fname Name of the calling function
2934 * @throws DBUnexpectedError
2935 * @return bool|ResultWrapper
2937 public function delete( $table, $conds, $fname = __METHOD__
) {
2939 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2942 $table = $this->tableName( $table );
2943 $sql = "DELETE FROM $table";
2945 if ( $conds != '*' ) {
2946 if ( is_array( $conds ) ) {
2947 $conds = $this->makeList( $conds, LIST_AND
);
2949 $sql .= ' WHERE ' . $conds;
2952 return $this->query( $sql, $fname );
2956 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2957 * into another table.
2959 * @param string $destTable The table name to insert into
2960 * @param string|array $srcTable May be either a table name, or an array of table names
2961 * to include in a join.
2963 * @param array $varMap Must be an associative array of the form
2964 * array( 'dest1' => 'source1', ...). Source items may be literals
2965 * rather than field names, but strings should be quoted with
2966 * DatabaseBase::addQuotes()
2968 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2969 * the details of the format of condition arrays. May be "*" to copy the
2972 * @param string $fname The function name of the caller, from __METHOD__
2974 * @param array $insertOptions Options for the INSERT part of the query, see
2975 * DatabaseBase::insert() for details.
2976 * @param array $selectOptions Options for the SELECT part of the query, see
2977 * DatabaseBase::select() for details.
2979 * @return ResultWrapper
2981 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2982 $fname = __METHOD__
,
2983 $insertOptions = array(), $selectOptions = array()
2985 $destTable = $this->tableName( $destTable );
2987 if ( !is_array( $insertOptions ) ) {
2988 $insertOptions = array( $insertOptions );
2991 $insertOptions = $this->makeInsertOptions( $insertOptions );
2993 if ( !is_array( $selectOptions ) ) {
2994 $selectOptions = array( $selectOptions );
2997 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2999 if ( is_array( $srcTable ) ) {
3000 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3002 $srcTable = $this->tableName( $srcTable );
3005 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3006 " SELECT $startOpts " . implode( ',', $varMap ) .
3007 " FROM $srcTable $useIndex ";
3009 if ( $conds != '*' ) {
3010 if ( is_array( $conds ) ) {
3011 $conds = $this->makeList( $conds, LIST_AND
);
3013 $sql .= " WHERE $conds";
3016 $sql .= " $tailOpts";
3018 return $this->query( $sql, $fname );
3022 * Construct a LIMIT query with optional offset. This is used for query
3023 * pages. The SQL should be adjusted so that only the first $limit rows
3024 * are returned. If $offset is provided as well, then the first $offset
3025 * rows should be discarded, and the next $limit rows should be returned.
3026 * If the result of the query is not ordered, then the rows to be returned
3027 * are theoretically arbitrary.
3029 * $sql is expected to be a SELECT, if that makes a difference.
3031 * The version provided by default works in MySQL and SQLite. It will very
3032 * likely need to be overridden for most other DBMSes.
3034 * @param string $sql SQL query we will append the limit too
3035 * @param int $limit The SQL limit
3036 * @param int|bool $offset The SQL offset (default false)
3037 * @throws DBUnexpectedError
3040 public function limitResult( $sql, $limit, $offset = false ) {
3041 if ( !is_numeric( $limit ) ) {
3042 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3045 return "$sql LIMIT "
3046 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3051 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3052 * within the UNION construct.
3055 public function unionSupportsOrderAndLimit() {
3056 return true; // True for almost every DB supported
3060 * Construct a UNION query
3061 * This is used for providing overload point for other DB abstractions
3062 * not compatible with the MySQL syntax.
3063 * @param array $sqls SQL statements to combine
3064 * @param bool $all Use UNION ALL
3065 * @return string SQL fragment
3067 public function unionQueries( $sqls, $all ) {
3068 $glue = $all ?
') UNION ALL (' : ') UNION (';
3070 return '(' . implode( $glue, $sqls ) . ')';
3074 * Returns an SQL expression for a simple conditional. This doesn't need
3075 * to be overridden unless CASE isn't supported in your DBMS.
3077 * @param string|array $cond SQL expression which will result in a boolean value
3078 * @param string $trueVal SQL expression to return if true
3079 * @param string $falseVal SQL expression to return if false
3080 * @return string SQL fragment
3082 public function conditional( $cond, $trueVal, $falseVal ) {
3083 if ( is_array( $cond ) ) {
3084 $cond = $this->makeList( $cond, LIST_AND
);
3087 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3091 * Returns a comand for str_replace function in SQL query.
3092 * Uses REPLACE() in MySQL
3094 * @param string $orig Column to modify
3095 * @param string $old Column to seek
3096 * @param string $new Column to replace with
3100 public function strreplace( $orig, $old, $new ) {
3101 return "REPLACE({$orig}, {$old}, {$new})";
3105 * Determines how long the server has been up
3110 public function getServerUptime() {
3115 * Determines if the last failure was due to a deadlock
3120 public function wasDeadlock() {
3125 * Determines if the last failure was due to a lock timeout
3130 public function wasLockTimeout() {
3135 * Determines if the last query error was something that should be dealt
3136 * with by pinging the connection and reissuing the query.
3141 public function wasErrorReissuable() {
3146 * Determines if the last failure was due to the database being read-only.
3151 public function wasReadOnlyError() {
3156 * Determines if the given query error was a connection drop
3159 * @param integer|string $errno
3162 public function wasConnectionError( $errno ) {
3167 * Perform a deadlock-prone transaction.
3169 * This function invokes a callback function to perform a set of write
3170 * queries. If a deadlock occurs during the processing, the transaction
3171 * will be rolled back and the callback function will be called again.
3174 * $dbw->deadlockLoop( callback, ... );
3176 * Extra arguments are passed through to the specified callback function.
3178 * Returns whatever the callback function returned on its successful,
3179 * iteration, or false on error, for example if the retry limit was
3183 * @throws DBQueryError
3185 public function deadlockLoop() {
3186 $args = func_get_args();
3187 $function = array_shift( $args );
3188 $tries = self
::DEADLOCK_TRIES
;
3190 $this->begin( __METHOD__
);
3196 $retVal = call_user_func_array( $function, $args );
3198 } catch ( DBQueryError
$e ) {
3199 if ( $this->wasDeadlock() ) {
3200 // Retry after a randomized delay
3201 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3203 // Throw the error back up
3207 } while ( --$tries > 0 );
3209 if ( $tries <= 0 ) {
3210 // Too many deadlocks; give up
3211 $this->rollback( __METHOD__
);
3214 $this->commit( __METHOD__
);
3221 * Wait for the slave to catch up to a given master position.
3223 * @param DBMasterPos $pos
3224 * @param int $timeout The maximum number of seconds to wait for
3226 * @return int Zero if the slave was past that position already,
3227 * greater than zero if we waited for some period of time, less than
3228 * zero if we timed out.
3230 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3231 # Real waits are implemented in the subclass.
3236 * Get the replication position of this slave
3238 * @return DBMasterPos|bool False if this is not a slave.
3240 public function getSlavePos() {
3246 * Get the position of this master
3248 * @return DBMasterPos|bool False if this is not a master
3250 public function getMasterPos() {
3256 * Run an anonymous function as soon as there is no transaction pending.
3257 * If there is a transaction and it is rolled back, then the callback is cancelled.
3258 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3259 * Callbacks must commit any transactions that they begin.
3261 * This is useful for updates to different systems or when separate transactions are needed.
3262 * For example, one might want to enqueue jobs into a system outside the database, but only
3263 * after the database is updated so that the jobs will see the data when they actually run.
3264 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3266 * @param callable $callback
3269 final public function onTransactionIdle( $callback ) {
3270 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3271 if ( !$this->mTrxLevel
) {
3272 $this->runOnTransactionIdleCallbacks();
3277 * Run an anonymous function before the current transaction commits or now if there is none.
3278 * If there is a transaction and it is rolled back, then the callback is cancelled.
3279 * Callbacks must not start nor commit any transactions.
3281 * This is useful for updates that easily cause deadlocks if locks are held too long
3282 * but where atomicity is strongly desired for these updates and some related updates.
3284 * @param callable $callback
3287 final public function onTransactionPreCommitOrIdle( $callback ) {
3288 if ( $this->mTrxLevel
) {
3289 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3291 $this->onTransactionIdle( $callback ); // this will trigger immediately
3296 * Actually any "on transaction idle" callbacks.
3300 protected function runOnTransactionIdleCallbacks() {
3301 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3303 $e = $ePrior = null; // last exception
3304 do { // callbacks may add callbacks :)
3305 $callbacks = $this->mTrxIdleCallbacks
;
3306 $this->mTrxIdleCallbacks
= array(); // recursion guard
3307 foreach ( $callbacks as $callback ) {
3309 list( $phpCallback ) = $callback;
3310 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3311 call_user_func( $phpCallback );
3312 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3313 } catch ( Exception
$e ) {
3315 MWExceptionHandler
::logException( $ePrior );
3320 } while ( count( $this->mTrxIdleCallbacks
) );
3322 if ( $e instanceof Exception
) {
3323 throw $e; // re-throw any last exception
3328 * Actually any "on transaction pre-commit" callbacks.
3332 protected function runOnTransactionPreCommitCallbacks() {
3333 $e = $ePrior = null; // last exception
3334 do { // callbacks may add callbacks :)
3335 $callbacks = $this->mTrxPreCommitCallbacks
;
3336 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3337 foreach ( $callbacks as $callback ) {
3339 list( $phpCallback ) = $callback;
3340 call_user_func( $phpCallback );
3341 } catch ( Exception
$e ) {
3343 MWExceptionHandler
::logException( $ePrior );
3348 } while ( count( $this->mTrxPreCommitCallbacks
) );
3350 if ( $e instanceof Exception
) {
3351 throw $e; // re-throw any last exception
3356 * Begin an atomic section of statements
3358 * If a transaction has been started already, just keep track of the given
3359 * section name to make sure the transaction is not committed pre-maturely.
3360 * This function can be used in layers (with sub-sections), so use a stack
3361 * to keep track of the different atomic sections. If there is no transaction,
3362 * start one implicitly.
3364 * The goal of this function is to create an atomic section of SQL queries
3365 * without having to start a new transaction if it already exists.
3367 * Atomic sections are more strict than transactions. With transactions,
3368 * attempting to begin a new transaction when one is already running results
3369 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3370 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3371 * and any database transactions cannot be began or committed until all atomic
3372 * levels are closed. There is no such thing as implicitly opening or closing
3373 * an atomic section.
3376 * @param string $fname
3379 final public function startAtomic( $fname = __METHOD__
) {
3380 if ( !$this->mTrxLevel
) {
3381 $this->begin( $fname );
3382 $this->mTrxAutomatic
= true;
3383 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3384 // in all changes being in one transaction to keep requests transactional.
3385 if ( !$this->getFlag( DBO_TRX
) ) {
3386 $this->mTrxAutomaticAtomic
= true;
3390 $this->mTrxAtomicLevels
[] = $fname;
3394 * Ends an atomic section of SQL statements
3396 * Ends the next section of atomic SQL statements and commits the transaction
3400 * @see DatabaseBase::startAtomic
3401 * @param string $fname
3404 final public function endAtomic( $fname = __METHOD__
) {
3405 if ( !$this->mTrxLevel
) {
3406 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3408 if ( !$this->mTrxAtomicLevels ||
3409 array_pop( $this->mTrxAtomicLevels
) !== $fname
3411 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3414 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3415 $this->commit( $fname, 'flush' );
3420 * Begin a transaction. If a transaction is already in progress,
3421 * that transaction will be committed before the new transaction is started.
3423 * Note that when the DBO_TRX flag is set (which is usually the case for web
3424 * requests, but not for maintenance scripts), any previous database query
3425 * will have started a transaction automatically.
3427 * Nesting of transactions is not supported. Attempts to nest transactions
3428 * will cause a warning, unless the current transaction was started
3429 * automatically because of the DBO_TRX flag.
3431 * @param string $fname
3434 final public function begin( $fname = __METHOD__
) {
3435 if ( $this->mTrxLevel
) { // implicit commit
3436 if ( $this->mTrxAtomicLevels
) {
3437 // If the current transaction was an automatic atomic one, then we definitely have
3438 // a problem. Same if there is any unclosed atomic level.
3439 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3440 throw new DBUnexpectedError(
3442 "Got explicit BEGIN while atomic sections $levels are still open."
3444 } elseif ( !$this->mTrxAutomatic
) {
3445 // We want to warn about inadvertently nested begin/commit pairs, but not about
3446 // auto-committing implicit transactions that were started by query() via DBO_TRX
3447 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3448 " performing implicit commit!";
3451 $this->getLogContext( array(
3452 'method' => __METHOD__
,
3457 // if the transaction was automatic and has done write operations
3458 if ( $this->mTrxDoneWrites
) {
3459 wfDebug( "$fname: Automatic transaction with writes in progress" .
3460 " (from {$this->mTrxFname}), performing implicit commit!\n"
3465 $this->runOnTransactionPreCommitCallbacks();
3466 $writeTime = $this->pendingWriteQueryDuration();
3467 $this->doCommit( $fname );
3468 if ( $this->mTrxDoneWrites
) {
3469 $this->mDoneWrites
= microtime( true );
3470 $this->getTransactionProfiler()->transactionWritingOut(
3471 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3473 $this->runOnTransactionIdleCallbacks();
3476 # Avoid fatals if close() was called
3477 $this->assertOpen();
3479 $this->doBegin( $fname );
3480 $this->mTrxTimestamp
= microtime( true );
3481 $this->mTrxFname
= $fname;
3482 $this->mTrxDoneWrites
= false;
3483 $this->mTrxAutomatic
= false;
3484 $this->mTrxAutomaticAtomic
= false;
3485 $this->mTrxAtomicLevels
= array();
3486 $this->mTrxIdleCallbacks
= array();
3487 $this->mTrxPreCommitCallbacks
= array();
3488 $this->mTrxShortId
= wfRandomString( 12 );
3489 $this->mTrxWriteDuration
= 0.0;
3490 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3491 // Get an estimate of the slave lag before then, treating estimate staleness
3492 // as lag itself just to be safe
3493 $status = $this->getApproximateLagStatus();
3494 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3498 * Issues the BEGIN command to the database server.
3500 * @see DatabaseBase::begin()
3501 * @param string $fname
3503 protected function doBegin( $fname ) {
3504 $this->query( 'BEGIN', $fname );
3505 $this->mTrxLevel
= 1;
3509 * Commits a transaction previously started using begin().
3510 * If no transaction is in progress, a warning is issued.
3512 * Nesting of transactions is not supported.
3514 * @param string $fname
3515 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3516 * explicitly committing implicit transactions, or calling commit when no
3517 * transaction is in progress. This will silently break any ongoing
3518 * explicit transaction. Only set the flush flag if you are sure that it
3519 * is safe to ignore these warnings in your context.
3520 * @throws DBUnexpectedError
3522 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3523 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3524 // There are still atomic sections open. This cannot be ignored
3525 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3526 throw new DBUnexpectedError(
3528 "Got COMMIT while atomic sections $levels are still open"
3532 if ( $flush === 'flush' ) {
3533 if ( !$this->mTrxLevel
) {
3534 return; // nothing to do
3535 } elseif ( !$this->mTrxAutomatic
) {
3536 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3539 if ( !$this->mTrxLevel
) {
3540 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3541 return; // nothing to do
3542 } elseif ( $this->mTrxAutomatic
) {
3543 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3547 # Avoid fatals if close() was called
3548 $this->assertOpen();
3550 $this->runOnTransactionPreCommitCallbacks();
3551 $writeTime = $this->pendingWriteQueryDuration();
3552 $this->doCommit( $fname );
3553 if ( $this->mTrxDoneWrites
) {
3554 $this->mDoneWrites
= microtime( true );
3555 $this->getTransactionProfiler()->transactionWritingOut(
3556 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3558 $this->runOnTransactionIdleCallbacks();
3562 * Issues the COMMIT command to the database server.
3564 * @see DatabaseBase::commit()
3565 * @param string $fname
3567 protected function doCommit( $fname ) {
3568 if ( $this->mTrxLevel
) {
3569 $this->query( 'COMMIT', $fname );
3570 $this->mTrxLevel
= 0;
3575 * Rollback a transaction previously started using begin().
3576 * If no transaction is in progress, a warning is issued.
3578 * No-op on non-transactional databases.
3580 * @param string $fname
3581 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3582 * calling rollback when no transaction is in progress. This will silently
3583 * break any ongoing explicit transaction. Only set the flush flag if you
3584 * are sure that it is safe to ignore these warnings in your context.
3585 * @throws DBUnexpectedError
3586 * @since 1.23 Added $flush parameter
3588 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3589 if ( $flush !== 'flush' ) {
3590 if ( !$this->mTrxLevel
) {
3591 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3592 return; // nothing to do
3593 } elseif ( $this->mTrxAutomatic
) {
3594 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3597 if ( !$this->mTrxLevel
) {
3598 return; // nothing to do
3599 } elseif ( !$this->mTrxAutomatic
) {
3600 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3604 # Avoid fatals if close() was called
3605 $this->assertOpen();
3607 $this->doRollback( $fname );
3608 $this->mTrxIdleCallbacks
= array(); // cancel
3609 $this->mTrxPreCommitCallbacks
= array(); // cancel
3610 $this->mTrxAtomicLevels
= array();
3611 if ( $this->mTrxDoneWrites
) {
3612 $this->getTransactionProfiler()->transactionWritingOut(
3613 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3618 * Issues the ROLLBACK command to the database server.
3620 * @see DatabaseBase::rollback()
3621 * @param string $fname
3623 protected function doRollback( $fname ) {
3624 if ( $this->mTrxLevel
) {
3625 $this->query( 'ROLLBACK', $fname, true );
3626 $this->mTrxLevel
= 0;
3631 * Creates a new table with structure copied from existing table
3632 * Note that unlike most database abstraction functions, this function does not
3633 * automatically append database prefix, because it works at a lower
3634 * abstraction level.
3635 * The table names passed to this function shall not be quoted (this
3636 * function calls addIdentifierQuotes when needed).
3638 * @param string $oldName Name of table whose structure should be copied
3639 * @param string $newName Name of table to be created
3640 * @param bool $temporary Whether the new table should be temporary
3641 * @param string $fname Calling function name
3642 * @throws MWException
3643 * @return bool True if operation was successful
3645 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3648 throw new MWException(
3649 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3653 * List all tables on the database
3655 * @param string $prefix Only show tables with this prefix, e.g. mw_
3656 * @param string $fname Calling function name
3657 * @throws MWException
3660 function listTables( $prefix = null, $fname = __METHOD__
) {
3661 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3665 * Reset the views process cache set by listViews()
3668 final public function clearViewsCache() {
3669 $this->allViews
= null;
3673 * Lists all the VIEWs in the database
3675 * For caching purposes the list of all views should be stored in
3676 * $this->allViews. The process cache can be cleared with clearViewsCache()
3678 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3679 * @param string $fname Name of calling function
3680 * @throws MWException
3684 public function listViews( $prefix = null, $fname = __METHOD__
) {
3685 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3689 * Differentiates between a TABLE and a VIEW
3691 * @param string $name Name of the database-structure to test.
3692 * @throws MWException
3696 public function isView( $name ) {
3697 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3701 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3702 * to the format used for inserting into timestamp fields in this DBMS.
3704 * The result is unquoted, and needs to be passed through addQuotes()
3705 * before it can be included in raw SQL.
3707 * @param string|int $ts
3711 public function timestamp( $ts = 0 ) {
3712 return wfTimestamp( TS_MW
, $ts );
3716 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3717 * to the format used for inserting into timestamp fields in this DBMS. If
3718 * NULL is input, it is passed through, allowing NULL values to be inserted
3719 * into timestamp fields.
3721 * The result is unquoted, and needs to be passed through addQuotes()
3722 * before it can be included in raw SQL.
3724 * @param string|int $ts
3728 public function timestampOrNull( $ts = null ) {
3729 if ( is_null( $ts ) ) {
3732 return $this->timestamp( $ts );
3737 * Take the result from a query, and wrap it in a ResultWrapper if
3738 * necessary. Boolean values are passed through as is, to indicate success
3739 * of write queries or failure.
3741 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3742 * resource, and it was necessary to call this function to convert it to
3743 * a wrapper. Nowadays, raw database objects are never exposed to external
3744 * callers, so this is unnecessary in external code.
3746 * @param bool|ResultWrapper|resource|object $result
3747 * @return bool|ResultWrapper
3749 protected function resultObject( $result ) {
3752 } elseif ( $result instanceof ResultWrapper
) {
3754 } elseif ( $result === true ) {
3755 // Successful write query
3758 return new ResultWrapper( $this, $result );
3763 * Ping the server and try to reconnect if it there is no connection
3765 * @return bool Success or failure
3767 public function ping() {
3768 # Stub. Not essential to override.
3773 * Get the slave lag when the current transaction started
3774 * or a general lag estimate if not transaction is active
3776 * This is useful when transactions might use snapshot isolation
3777 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3778 * is this lag plus transaction duration. If they don't, it is still
3779 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
3780 * indication of the staleness of subsequent reads.
3782 * @return array ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3785 public function getSessionLagStatus() {
3786 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3790 * Get the slave lag when the current transaction started
3792 * This is useful when transactions might use snapshot isolation
3793 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3794 * is this lag plus transaction duration. If they don't, it is still
3795 * safe to be pessimistic. This returns null if there is no transaction.
3797 * @return array|null ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3800 public function getTransactionLagStatus() {
3801 return $this->mTrxLevel
3802 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
3807 * Get a slave lag estimate for this server
3809 * @return array ('lag': seconds, 'since': UNIX timestamp of estimate)
3812 public function getApproximateLagStatus() {
3814 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3815 'since' => microtime( true )
3820 * Merge the result of getSessionLagStatus() for several DBs
3821 * using the most pessimistic values to estimate the lag of
3822 * any data derived from them in combination
3824 * This is information is useful for caching modules
3826 * @see WANObjectCache::set()
3827 * @see WANObjectCache::getWithSetCallback()
3829 * @param IDatabase $db1
3830 * @param IDatabase ...
3831 * @return array Map of values:
3832 * - lag: highest lag of any of the DBs
3833 * - since: oldest UNIX timestamp of any of the DB lag estimates
3834 * - pending: whether any of the DBs have uncommitted changes
3837 public static function getCacheSetOptions( IDatabase
$db1 ) {
3838 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
3839 foreach ( func_get_args() as $db ) {
3840 /** @var IDatabase $db */
3841 $status = $db->getSessionLagStatus();
3842 $res['lag'] = max( $res['lag'], $status['lag'] );
3843 $res['since'] = min( $res['since'], $status['since'] );
3844 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3851 * Get slave lag. Currently supported only by MySQL.
3853 * Note that this function will generate a fatal error on many
3854 * installations. Most callers should use LoadBalancer::safeGetLag()
3857 * @return int Database replication lag in seconds
3859 public function getLag() {
3864 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3868 function maxListLen() {
3873 * Some DBMSs have a special format for inserting into blob fields, they
3874 * don't allow simple quoted strings to be inserted. To insert into such
3875 * a field, pass the data through this function before passing it to
3876 * DatabaseBase::insert().
3881 public function encodeBlob( $b ) {
3886 * Some DBMSs return a special placeholder object representing blob fields
3887 * in result objects. Pass the object through this function to return the
3890 * @param string|Blob $b
3893 public function decodeBlob( $b ) {
3894 if ( $b instanceof Blob
) {
3901 * Override database's default behavior. $options include:
3902 * 'connTimeout' : Set the connection timeout value in seconds.
3903 * May be useful for very long batch queries such as
3904 * full-wiki dumps, where a single query reads out over
3907 * @param array $options
3910 public function setSessionOptions( array $options ) {
3914 * Read and execute SQL commands from a file.
3916 * Returns true on success, error string or exception on failure (depending
3917 * on object's error ignore settings).
3919 * @param string $filename File name to open
3920 * @param bool|callable $lineCallback Optional function called before reading each line
3921 * @param bool|callable $resultCallback Optional function called for each MySQL result
3922 * @param bool|string $fname Calling function name or false if name should be
3923 * generated dynamically using $filename
3924 * @param bool|callable $inputCallback Optional function called for each
3925 * complete line sent
3926 * @throws Exception|MWException
3927 * @return bool|string
3929 public function sourceFile(
3930 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3932 MediaWiki\
suppressWarnings();
3933 $fp = fopen( $filename, 'r' );
3934 MediaWiki\restoreWarnings
();
3936 if ( false === $fp ) {
3937 throw new MWException( "Could not open \"{$filename}\".\n" );
3941 $fname = __METHOD__
. "( $filename )";
3945 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3946 } catch ( Exception
$e ) {
3957 * Get the full path of a patch file. Originally based on archive()
3958 * from updaters.inc. Keep in mind this always returns a patch, as
3959 * it fails back to MySQL if no DB-specific patch can be found
3961 * @param string $patch The name of the patch, like patch-something.sql
3962 * @return string Full path to patch file
3964 public function patchPath( $patch ) {
3967 $dbType = $this->getType();
3968 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3969 return "$IP/maintenance/$dbType/archives/$patch";
3971 return "$IP/maintenance/archives/$patch";
3976 * Set variables to be used in sourceFile/sourceStream, in preference to the
3977 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3978 * all. If it's set to false, $GLOBALS will be used.
3980 * @param bool|array $vars Mapping variable name to value.
3982 public function setSchemaVars( $vars ) {
3983 $this->mSchemaVars
= $vars;
3987 * Read and execute commands from an open file handle.
3989 * Returns true on success, error string or exception on failure (depending
3990 * on object's error ignore settings).
3992 * @param resource $fp File handle
3993 * @param bool|callable $lineCallback Optional function called before reading each query
3994 * @param bool|callable $resultCallback Optional function called for each MySQL result
3995 * @param string $fname Calling function name
3996 * @param bool|callable $inputCallback Optional function called for each complete query sent
3997 * @return bool|string
3999 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4000 $fname = __METHOD__
, $inputCallback = false
4004 while ( !feof( $fp ) ) {
4005 if ( $lineCallback ) {
4006 call_user_func( $lineCallback );
4009 $line = trim( fgets( $fp ) );
4011 if ( $line == '' ) {
4015 if ( '-' == $line[0] && '-' == $line[1] ) {
4023 $done = $this->streamStatementEnd( $cmd, $line );
4027 if ( $done ||
feof( $fp ) ) {
4028 $cmd = $this->replaceVars( $cmd );
4030 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4031 $res = $this->query( $cmd, $fname );
4033 if ( $resultCallback ) {
4034 call_user_func( $resultCallback, $res, $this );
4037 if ( false === $res ) {
4038 $err = $this->lastError();
4040 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4051 * Called by sourceStream() to check if we've reached a statement end
4053 * @param string $sql SQL assembled so far
4054 * @param string $newLine New line about to be added to $sql
4055 * @return bool Whether $newLine contains end of the statement
4057 public function streamStatementEnd( &$sql, &$newLine ) {
4058 if ( $this->delimiter
) {
4060 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4061 if ( $newLine != $prev ) {
4070 * Database independent variable replacement. Replaces a set of variables
4071 * in an SQL statement with their contents as given by $this->getSchemaVars().
4073 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4075 * - '{$var}' should be used for text and is passed through the database's
4077 * - `{$var}` should be used for identifiers (e.g. table and database names).
4078 * It is passed through the database's addIdentifierQuotes method which
4079 * can be overridden if the database uses something other than backticks.
4080 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4081 * database's tableName method.
4082 * - / *i* / passes the name that follows through the database's indexName method.
4083 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4084 * its use should be avoided. In 1.24 and older, string encoding was applied.
4086 * @param string $ins SQL statement to replace variables in
4087 * @return string The new SQL statement with variables replaced
4089 protected function replaceVars( $ins ) {
4091 $vars = $this->getSchemaVars();
4092 return preg_replace_callback(
4094 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4095 \'\{\$ (\w+) }\' | # 3. addQuotes
4096 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4097 /\*\$ (\w+) \*/ # 5. leave unencoded
4099 function ( $m ) use ( $that, $vars ) {
4100 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4101 // check for both nonexistent keys *and* the empty string.
4102 if ( isset( $m[1] ) && $m[1] !== '' ) {
4103 if ( $m[1] === 'i' ) {
4104 return $that->indexName( $m[2] );
4106 return $that->tableName( $m[2] );
4108 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4109 return $that->addQuotes( $vars[$m[3]] );
4110 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4111 return $that->addIdentifierQuotes( $vars[$m[4]] );
4112 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4113 return $vars[$m[5]];
4123 * Get schema variables. If none have been set via setSchemaVars(), then
4124 * use some defaults from the current object.
4128 protected function getSchemaVars() {
4129 if ( $this->mSchemaVars
) {
4130 return $this->mSchemaVars
;
4132 return $this->getDefaultSchemaVars();
4137 * Get schema variables to use if none have been set via setSchemaVars().
4139 * Override this in derived classes to provide variables for tables.sql
4140 * and SQL patch files.
4144 protected function getDefaultSchemaVars() {
4149 * Check to see if a named lock is available (non-blocking)
4151 * @param string $lockName Name of lock to poll
4152 * @param string $method Name of method calling us
4156 public function lockIsFree( $lockName, $method ) {
4161 * Acquire a named lock
4163 * Named locks are not related to transactions
4165 * @param string $lockName Name of lock to aquire
4166 * @param string $method Name of method calling us
4167 * @param int $timeout
4170 public function lock( $lockName, $method, $timeout = 5 ) {
4177 * Named locks are not related to transactions
4179 * @param string $lockName Name of lock to release
4180 * @param string $method Name of method calling us
4182 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4183 * by this thread (in which case the lock is not released), and NULL if the named
4184 * lock did not exist
4186 public function unlock( $lockName, $method ) {
4191 * Check to see if a named lock used by lock() use blocking queues
4196 public function namedLocksEnqueue() {
4201 * Lock specific tables
4203 * @param array $read Array of tables to lock for read access
4204 * @param array $write Array of tables to lock for write access
4205 * @param string $method Name of caller
4206 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4209 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4214 * Unlock specific tables
4216 * @param string $method The caller
4219 public function unlockTables( $method ) {
4225 * @param string $tableName
4226 * @param string $fName
4227 * @return bool|ResultWrapper
4230 public function dropTable( $tableName, $fName = __METHOD__
) {
4231 if ( !$this->tableExists( $tableName, $fName ) ) {
4234 $sql = "DROP TABLE " . $this->tableName( $tableName );
4235 if ( $this->cascadingDeletes() ) {
4239 return $this->query( $sql, $fName );
4243 * Get search engine class. All subclasses of this need to implement this
4244 * if they wish to use searching.
4248 public function getSearchEngine() {
4249 return 'SearchEngineDummy';
4253 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4254 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4255 * because "i" sorts after all numbers.
4259 public function getInfinity() {
4264 * Encode an expiry time into the DBMS dependent format
4266 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4269 public function encodeExpiry( $expiry ) {
4270 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4271 ?
$this->getInfinity()
4272 : $this->timestamp( $expiry );
4276 * Decode an expiry time into a DBMS independent format
4278 * @param string $expiry DB timestamp field value for expiry
4279 * @param int $format TS_* constant, defaults to TS_MW
4282 public function decodeExpiry( $expiry, $format = TS_MW
) {
4283 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4285 : wfTimestamp( $format, $expiry );
4289 * Allow or deny "big selects" for this session only. This is done by setting
4290 * the sql_big_selects session variable.
4292 * This is a MySQL-specific feature.
4294 * @param bool|string $value True for allow, false for deny, or "default" to
4295 * restore the initial value
4297 public function setBigSelects( $value = true ) {
4301 public function isReadOnly() {
4302 return ( $this->getReadOnlyReason() !== false );
4306 * @return string|bool Reason this DB is read-only or false if it is not
4308 protected function getReadOnlyReason() {
4309 $reason = $this->getLBInfo( 'readOnlyReason' );
4311 return is_string( $reason ) ?
$reason : false;
4318 public function __toString() {
4319 return (string)$this->mConn
;
4323 * Run a few simple sanity checks
4325 public function __destruct() {
4326 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4327 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4329 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4331 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4332 $callers[] = $callbackInfo[1];
4334 $callers = implode( ', ', $callers );
4335 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4343 abstract class Database
extends DatabaseBase
{
4344 // B/C until nothing type hints for DatabaseBase
4345 // @TODO: finish renaming DatabaseBase => Database