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 * Returns true if there is a transaction open with possible write
446 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
450 public function writesOrCallbacksPending() {
451 return $this->mTrxLevel
&& (
452 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
457 * Get the time spend running write queries for this
459 * High times could be due to scanning, updates, locking, and such
461 * @return float|bool Returns false if not transaction is active
464 public function pendingWriteQueryDuration() {
465 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
469 * Is a connection to the database open?
472 public function isOpen() {
473 return $this->mOpened
;
477 * Set a flag for this connection
479 * @param int $flag DBO_* constants from Defines.php:
480 * - DBO_DEBUG: output some debug info (same as debug())
481 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
482 * - DBO_TRX: automatically start transactions
483 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
484 * and removes it in command line mode
485 * - DBO_PERSISTENT: use persistant database connection
487 public function setFlag( $flag ) {
488 $this->mFlags |
= $flag;
492 * Clear a flag for this connection
494 * @param int $flag DBO_* constants from Defines.php:
495 * - DBO_DEBUG: output some debug info (same as debug())
496 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
497 * - DBO_TRX: automatically start transactions
498 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
499 * and removes it in command line mode
500 * - DBO_PERSISTENT: use persistant database connection
502 public function clearFlag( $flag ) {
503 $this->mFlags
&= ~
$flag;
507 * Returns a boolean whether the flag $flag is set for this connection
509 * @param int $flag DBO_* constants from Defines.php:
510 * - DBO_DEBUG: output some debug info (same as debug())
511 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
512 * - DBO_TRX: automatically start transactions
513 * - DBO_PERSISTENT: use persistant database connection
516 public function getFlag( $flag ) {
517 return !!( $this->mFlags
& $flag );
521 * General read-only accessor
523 * @param string $name
526 public function getProperty( $name ) {
533 public function getWikiID() {
534 if ( $this->mTablePrefix
) {
535 return "{$this->mDBname}-{$this->mTablePrefix}";
537 return $this->mDBname
;
542 * Return a path to the DBMS-specific SQL file if it exists,
543 * otherwise default SQL file
545 * @param string $filename
548 private function getSqlFilePath( $filename ) {
550 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
551 if ( file_exists( $dbmsSpecificFilePath ) ) {
552 return $dbmsSpecificFilePath;
554 return "$IP/maintenance/$filename";
559 * Return a path to the DBMS-specific schema file,
560 * otherwise default to tables.sql
564 public function getSchemaPath() {
565 return $this->getSqlFilePath( 'tables.sql' );
569 * Return a path to the DBMS-specific update key file,
570 * otherwise default to update-keys.sql
574 public function getUpdateKeysPath() {
575 return $this->getSqlFilePath( 'update-keys.sql' );
579 * Get information about an index into an object
580 * @param string $table Table name
581 * @param string $index Index name
582 * @param string $fname Calling function name
583 * @return mixed Database-specific index description class or false if the index does not exist
585 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
588 * Wrapper for addslashes()
590 * @param string $s String to be slashed.
591 * @return string Slashed string.
593 abstract function strencode( $s );
598 * FIXME: It is possible to construct a Database object with no associated
599 * connection object, by specifying no parameters to __construct(). This
600 * feature is deprecated and should be removed.
602 * DatabaseBase subclasses should not be constructed directly in external
603 * code. DatabaseBase::factory() should be used instead.
605 * @param array $params Parameters passed from DatabaseBase::factory()
607 function __construct( array $params ) {
608 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
610 $this->srvCache
= ObjectCache
::newAccelerator( 'hash' );
612 $server = $params['host'];
613 $user = $params['user'];
614 $password = $params['password'];
615 $dbName = $params['dbname'];
616 $flags = $params['flags'];
617 $tablePrefix = $params['tablePrefix'];
618 $schema = $params['schema'];
619 $foreign = $params['foreign'];
621 $this->mFlags
= $flags;
622 if ( $this->mFlags
& DBO_DEFAULT
) {
623 if ( $wgCommandLineMode ) {
624 $this->mFlags
&= ~DBO_TRX
;
626 $this->mFlags |
= DBO_TRX
;
630 $this->mSessionVars
= $params['variables'];
632 /** Get the default table prefix*/
633 if ( $tablePrefix === 'get from global' ) {
634 $this->mTablePrefix
= $wgDBprefix;
636 $this->mTablePrefix
= $tablePrefix;
639 /** Get the database schema*/
640 if ( $schema === 'get from global' ) {
641 $this->mSchema
= $wgDBmwschema;
643 $this->mSchema
= $schema;
646 $this->mForeign
= $foreign;
648 if ( isset( $params['trxProfiler'] ) ) {
649 $this->trxProfiler
= $params['trxProfiler']; // override
653 $this->open( $server, $user, $password, $dbName );
658 * Called by serialize. Throw an exception when DB connection is serialized.
659 * This causes problems on some database engines because the connection is
660 * not restored on unserialize.
662 public function __sleep() {
663 throw new MWException( 'Database serialization may cause problems, since ' .
664 'the connection is not restored on wakeup.' );
668 * Given a DB type, construct the name of the appropriate child class of
669 * DatabaseBase. This is designed to replace all of the manual stuff like:
670 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
671 * as well as validate against the canonical list of DB types we have
673 * This factory function is mostly useful for when you need to connect to a
674 * database other than the MediaWiki default (such as for external auth,
675 * an extension, et cetera). Do not use this to connect to the MediaWiki
676 * database. Example uses in core:
677 * @see LoadBalancer::reallyOpenConnection()
678 * @see ForeignDBRepo::getMasterDB()
679 * @see WebInstallerDBConnect::execute()
683 * @param string $dbType A possible DB type
684 * @param array $p An array of options to pass to the constructor.
685 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
686 * @throws MWException If the database driver or extension cannot be found
687 * @return DatabaseBase|null DatabaseBase subclass or null
689 final public static function factory( $dbType, $p = array() ) {
690 $canonicalDBTypes = array(
691 'mysql' => array( 'mysqli', 'mysql' ),
692 'postgres' => array(),
699 $dbType = strtolower( $dbType );
700 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
701 $possibleDrivers = $canonicalDBTypes[$dbType];
702 if ( !empty( $p['driver'] ) ) {
703 if ( in_array( $p['driver'], $possibleDrivers ) ) {
704 $driver = $p['driver'];
706 throw new MWException( __METHOD__
.
707 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
710 foreach ( $possibleDrivers as $posDriver ) {
711 if ( extension_loaded( $posDriver ) ) {
712 $driver = $posDriver;
720 if ( $driver === false ) {
721 throw new MWException( __METHOD__
.
722 " no viable database extension found for type '$dbType'" );
725 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
726 // and everything else doesn't use a schema (e.g. null)
727 // Although postgres and oracle support schemas, we don't use them (yet)
728 // to maintain backwards compatibility
729 $defaultSchemas = array(
730 'mssql' => 'get from global',
733 $class = 'Database' . ucfirst( $driver );
734 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
735 // Resolve some defaults for b/c
736 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
737 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
738 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
739 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
740 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
741 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
742 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
743 if ( !isset( $p['schema'] ) ) {
744 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
746 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
748 return new $class( $p );
754 protected function installErrorHandler() {
755 $this->mPHPError
= false;
756 $this->htmlErrors
= ini_set( 'html_errors', '0' );
757 set_error_handler( array( $this, 'connectionErrorHandler' ) );
761 * @return bool|string
763 protected function restoreErrorHandler() {
764 restore_error_handler();
765 if ( $this->htmlErrors
!== false ) {
766 ini_set( 'html_errors', $this->htmlErrors
);
768 if ( $this->mPHPError
) {
769 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
770 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
780 * @param string $errstr
782 public function connectionErrorHandler( $errno, $errstr ) {
783 $this->mPHPError
= $errstr;
787 * Create a log context to pass to wfLogDBError or other logging functions.
789 * @param array $extras Additional data to add to context
792 protected function getLogContext( array $extras = array() ) {
795 'db_server' => $this->mServer
,
796 'db_name' => $this->mDBname
,
797 'db_user' => $this->mUser
,
804 * Closes a database connection.
805 * if it is open : commits any open transactions
807 * @throws MWException
808 * @return bool Operation success. true if already closed.
810 public function close() {
811 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
812 throw new MWException( "Transaction idle callbacks still pending." );
814 if ( $this->mConn
) {
815 if ( $this->trxLevel() ) {
816 if ( !$this->mTrxAutomatic
) {
817 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
818 " performing implicit commit before closing connection!" );
821 $this->commit( __METHOD__
, 'flush' );
824 $closed = $this->closeConnection();
825 $this->mConn
= false;
829 $this->mOpened
= false;
835 * Make sure isOpen() returns true as a sanity check
837 * @throws DBUnexpectedError
839 protected function assertOpen() {
840 if ( !$this->isOpen() ) {
841 throw new DBUnexpectedError( $this, "DB connection was already closed." );
846 * Closes underlying database connection
848 * @return bool Whether connection was closed successfully
850 abstract protected function closeConnection();
853 * @param string $error Fallback error message, used if none is given by DB
854 * @throws DBConnectionError
856 function reportConnectionError( $error = 'Unknown error' ) {
857 $myError = $this->lastError();
863 throw new DBConnectionError( $this, $error );
867 * The DBMS-dependent part of query()
869 * @param string $sql SQL query.
870 * @return ResultWrapper|bool Result object to feed to fetchObject,
871 * fetchRow, ...; or false on failure
873 abstract protected function doQuery( $sql );
876 * Determine whether a query writes to the DB.
877 * Should return true if unsure.
882 protected function isWriteQuery( $sql ) {
883 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
887 * Determine whether a SQL statement is sensitive to isolation level.
888 * A SQL statement is considered transactable if its result could vary
889 * depending on the transaction isolation level. Operational commands
890 * such as 'SET' and 'SHOW' are not considered to be transactable.
895 protected function isTransactableQuery( $sql ) {
896 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
897 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
901 * Run an SQL query and return the result. Normally throws a DBQueryError
902 * on failure. If errors are ignored, returns false instead.
904 * In new code, the query wrappers select(), insert(), update(), delete(),
905 * etc. should be used where possible, since they give much better DBMS
906 * independence and automatically quote or validate user input in a variety
907 * of contexts. This function is generally only useful for queries which are
908 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
911 * However, the query wrappers themselves should call this function.
913 * @param string $sql SQL query
914 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
915 * comment (you can use __METHOD__ or add some extra info)
916 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
917 * maybe best to catch the exception instead?
918 * @throws MWException
919 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
920 * for a successful read query, or false on failure if $tempIgnore set
922 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
925 $this->mLastQuery
= $sql;
927 $isWriteQuery = $this->isWriteQuery( $sql );
928 if ( $isWriteQuery ) {
929 $reason = $this->getReadOnlyReason();
930 if ( $reason !== false ) {
931 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
933 # Set a flag indicating that writes have been done
934 $this->mDoneWrites
= microtime( true );
937 # Add a comment for easy SHOW PROCESSLIST interpretation
938 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
939 $userName = $wgUser->getName();
940 if ( mb_strlen( $userName ) > 15 ) {
941 $userName = mb_substr( $userName, 0, 15 ) . '...';
943 $userName = str_replace( '/', '', $userName );
948 // Add trace comment to the begin of the sql string, right after the operator.
949 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
950 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
952 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
953 $this->begin( __METHOD__
. " ($fname)" );
954 $this->mTrxAutomatic
= true;
957 # Keep track of whether the transaction has write queries pending
958 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
959 $this->mTrxDoneWrites
= true;
960 $this->getTransactionProfiler()->transactionWritingIn(
961 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
964 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
965 # generalizeSQL will probably cut down the query to reasonable
966 # logging size most of the time. The substr is really just a sanity check.
968 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
969 $totalProf = 'DatabaseBase::query-master';
971 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
972 $totalProf = 'DatabaseBase::query';
974 # Include query transaction state
975 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
977 $profiler = Profiler
::instance();
978 if ( !$profiler instanceof ProfilerStub
) {
979 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
980 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
983 if ( $this->debug() ) {
984 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $sql ) );
987 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
989 # Avoid fatals if close() was called
992 # Do the query and handle errors
993 $startTime = microtime( true );
994 $ret = $this->doQuery( $commentedSql );
995 $queryRuntime = microtime( true ) - $startTime;
996 # Log the query time and feed it into the DB trx profiler
997 $this->getTransactionProfiler()->recordQueryCompletion(
998 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1000 MWDebug
::queryTime( $queryId );
1002 # Try reconnecting if the connection was lost
1003 if ( false === $ret && $this->wasErrorReissuable() ) {
1004 # Transaction is gone, like it or not
1005 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1006 $this->mTrxLevel
= 0;
1007 $this->mTrxIdleCallbacks
= array(); // bug 65263
1008 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1009 wfDebug( "Connection lost, reconnecting...\n" );
1010 # Stash the last error values since ping() might clear them
1011 $lastError = $this->lastError();
1012 $lastErrno = $this->lastErrno();
1013 if ( $this->ping() ) {
1014 wfDebug( "Reconnected\n" );
1015 $server = $this->getServer();
1016 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1017 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1020 # Leave $ret as false and let an error be reported.
1021 # Callers may catch the exception and continue to use the DB.
1022 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1024 # Should be safe to silently retry (no trx and thus no callbacks)
1025 $startTime = microtime( true );
1026 $ret = $this->doQuery( $commentedSql );
1027 $queryRuntime = microtime( true ) - $startTime;
1028 # Log the query time and feed it into the DB trx profiler
1029 $this->getTransactionProfiler()->recordQueryCompletion(
1030 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1033 wfDebug( "Failed\n" );
1037 if ( false === $ret ) {
1038 $this->reportQueryError(
1039 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1042 $res = $this->resultObject( $ret );
1044 // Destroy profile sections in the opposite order to their creation
1045 ScopedCallback
::consume( $queryProfSection );
1046 ScopedCallback
::consume( $totalProfSection );
1048 if ( $isWriteQuery && $this->mTrxLevel
) {
1049 $this->mTrxWriteDuration +
= $queryRuntime;
1056 * Report a query error. Log the error, and if neither the object ignore
1057 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1059 * @param string $error
1061 * @param string $sql
1062 * @param string $fname
1063 * @param bool $tempIgnore
1064 * @throws DBQueryError
1066 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1067 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1068 wfDebug( "SQL ERROR (ignored): $error\n" );
1070 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1072 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1073 $this->getLogContext( array(
1074 'method' => __METHOD__
,
1077 'sql1line' => $sql1line,
1081 wfDebug( "SQL ERROR: " . $error . "\n" );
1082 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1087 * Intended to be compatible with the PEAR::DB wrapper functions.
1088 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1090 * ? = scalar value, quoted as necessary
1091 * ! = raw SQL bit (a function for instance)
1092 * & = filename; reads the file and inserts as a blob
1093 * (we don't use this though...)
1095 * @param string $sql
1096 * @param string $func
1100 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1101 /* MySQL doesn't support prepared statements (yet), so just
1102 * pack up the query for reference. We'll manually replace
1105 return array( 'query' => $sql, 'func' => $func );
1109 * Free a prepared query, generated by prepare().
1110 * @param string $prepared
1112 protected function freePrepared( $prepared ) {
1113 /* No-op by default */
1117 * Execute a prepared query with the various arguments
1118 * @param string $prepared The prepared sql
1119 * @param mixed $args Either an array here, or put scalars as varargs
1121 * @return ResultWrapper
1123 public function execute( $prepared, $args = null ) {
1124 if ( !is_array( $args ) ) {
1126 $args = func_get_args();
1127 array_shift( $args );
1130 $sql = $this->fillPrepared( $prepared['query'], $args );
1132 return $this->query( $sql, $prepared['func'] );
1136 * For faking prepared SQL statements on DBs that don't support it directly.
1138 * @param string $preparedQuery A 'preparable' SQL statement
1139 * @param array $args Array of Arguments to fill it with
1140 * @return string Executable SQL
1142 public function fillPrepared( $preparedQuery, $args ) {
1144 $this->preparedArgs
=& $args;
1146 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1147 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1151 * preg_callback func for fillPrepared()
1152 * The arguments should be in $this->preparedArgs and must not be touched
1153 * while we're doing this.
1155 * @param array $matches
1156 * @throws DBUnexpectedError
1159 protected function fillPreparedArg( $matches ) {
1160 switch ( $matches[1] ) {
1169 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1171 switch ( $matches[1] ) {
1173 return $this->addQuotes( $arg );
1177 # return $this->addQuotes( file_get_contents( $arg ) );
1178 throw new DBUnexpectedError(
1180 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1183 throw new DBUnexpectedError(
1185 'Received invalid match. This should never happen!'
1191 * Free a result object returned by query() or select(). It's usually not
1192 * necessary to call this, just use unset() or let the variable holding
1193 * the result object go out of scope.
1195 * @param mixed $res A SQL result
1197 public function freeResult( $res ) {
1201 * A SELECT wrapper which returns a single field from a single result row.
1203 * Usually throws a DBQueryError on failure. If errors are explicitly
1204 * ignored, returns false on failure.
1206 * If no result rows are returned from the query, false is returned.
1208 * @param string|array $table Table name. See DatabaseBase::select() for details.
1209 * @param string $var The field name to select. This must be a valid SQL
1210 * fragment: do not use unvalidated user input.
1211 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1212 * @param string $fname The function name of the caller.
1213 * @param string|array $options The query options. See DatabaseBase::select() for details.
1215 * @return bool|mixed The value from the field, or false on failure.
1216 * @throws DBUnexpectedError
1218 public function selectField(
1219 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1221 if ( $var === '*' ) { // sanity
1222 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1225 if ( !is_array( $options ) ) {
1226 $options = array( $options );
1229 $options['LIMIT'] = 1;
1231 $res = $this->select( $table, $var, $cond, $fname, $options );
1232 if ( $res === false ||
!$this->numRows( $res ) ) {
1236 $row = $this->fetchRow( $res );
1238 if ( $row !== false ) {
1239 return reset( $row );
1246 * A SELECT wrapper which returns a list of single field values from result rows.
1248 * Usually throws a DBQueryError on failure. If errors are explicitly
1249 * ignored, returns false on failure.
1251 * If no result rows are returned from the query, false is returned.
1253 * @param string|array $table Table name. See DatabaseBase::select() for details.
1254 * @param string $var The field name to select. This must be a valid SQL
1255 * fragment: do not use unvalidated user input.
1256 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1257 * @param string $fname The function name of the caller.
1258 * @param string|array $options The query options. See DatabaseBase::select() for details.
1260 * @return bool|array The values from the field, or false on failure
1261 * @throws DBUnexpectedError
1264 public function selectFieldValues(
1265 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1267 if ( $var === '*' ) { // sanity
1268 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1271 if ( !is_array( $options ) ) {
1272 $options = array( $options );
1275 $res = $this->select( $table, $var, $cond, $fname, $options );
1276 if ( $res === false ) {
1281 foreach ( $res as $row ) {
1282 $values[] = $row->$var;
1289 * Returns an optional USE INDEX clause to go after the table, and a
1290 * string to go at the end of the query.
1292 * @param array $options Associative array of options to be turned into
1293 * an SQL query, valid keys are listed in the function.
1295 * @see DatabaseBase::select()
1297 public function makeSelectOptions( $options ) {
1298 $preLimitTail = $postLimitTail = '';
1301 $noKeyOptions = array();
1303 foreach ( $options as $key => $option ) {
1304 if ( is_numeric( $key ) ) {
1305 $noKeyOptions[$option] = true;
1309 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1311 $preLimitTail .= $this->makeOrderBy( $options );
1313 // if (isset($options['LIMIT'])) {
1314 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1315 // isset($options['OFFSET']) ? $options['OFFSET']
1319 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1320 $postLimitTail .= ' FOR UPDATE';
1323 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1324 $postLimitTail .= ' LOCK IN SHARE MODE';
1327 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1328 $startOpts .= 'DISTINCT';
1331 # Various MySQL extensions
1332 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1333 $startOpts .= ' /*! STRAIGHT_JOIN */';
1336 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1337 $startOpts .= ' HIGH_PRIORITY';
1340 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1341 $startOpts .= ' SQL_BIG_RESULT';
1344 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1345 $startOpts .= ' SQL_BUFFER_RESULT';
1348 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1349 $startOpts .= ' SQL_SMALL_RESULT';
1352 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1353 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1356 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1357 $startOpts .= ' SQL_CACHE';
1360 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1361 $startOpts .= ' SQL_NO_CACHE';
1364 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1365 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1370 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1374 * Returns an optional GROUP BY with an optional HAVING
1376 * @param array $options Associative array of options
1378 * @see DatabaseBase::select()
1381 public function makeGroupByWithHaving( $options ) {
1383 if ( isset( $options['GROUP BY'] ) ) {
1384 $gb = is_array( $options['GROUP BY'] )
1385 ?
implode( ',', $options['GROUP BY'] )
1386 : $options['GROUP BY'];
1387 $sql .= ' GROUP BY ' . $gb;
1389 if ( isset( $options['HAVING'] ) ) {
1390 $having = is_array( $options['HAVING'] )
1391 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1392 : $options['HAVING'];
1393 $sql .= ' HAVING ' . $having;
1400 * Returns an optional ORDER BY
1402 * @param array $options Associative array of options
1404 * @see DatabaseBase::select()
1407 public function makeOrderBy( $options ) {
1408 if ( isset( $options['ORDER BY'] ) ) {
1409 $ob = is_array( $options['ORDER BY'] )
1410 ?
implode( ',', $options['ORDER BY'] )
1411 : $options['ORDER BY'];
1413 return ' ORDER BY ' . $ob;
1420 * Execute a SELECT query constructed using the various parameters provided.
1421 * See below for full details of the parameters.
1423 * @param string|array $table Table name
1424 * @param string|array $vars Field names
1425 * @param string|array $conds Conditions
1426 * @param string $fname Caller function name
1427 * @param array $options Query options
1428 * @param array $join_conds Join conditions
1431 * @param string|array $table
1433 * May be either an array of table names, or a single string holding a table
1434 * name. If an array is given, table aliases can be specified, for example:
1436 * array( 'a' => 'user' )
1438 * This includes the user table in the query, with the alias "a" available
1439 * for use in field names (e.g. a.user_name).
1441 * All of the table names given here are automatically run through
1442 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1443 * added, and various other table name mappings to be performed.
1446 * @param string|array $vars
1448 * May be either a field name or an array of field names. The field names
1449 * can be complete fragments of SQL, for direct inclusion into the SELECT
1450 * query. If an array is given, field aliases can be specified, for example:
1452 * array( 'maxrev' => 'MAX(rev_id)' )
1454 * This includes an expression with the alias "maxrev" in the query.
1456 * If an expression is given, care must be taken to ensure that it is
1460 * @param string|array $conds
1462 * May be either a string containing a single condition, or an array of
1463 * conditions. If an array is given, the conditions constructed from each
1464 * element are combined with AND.
1466 * Array elements may take one of two forms:
1468 * - Elements with a numeric key are interpreted as raw SQL fragments.
1469 * - Elements with a string key are interpreted as equality conditions,
1470 * where the key is the field name.
1471 * - If the value of such an array element is a scalar (such as a
1472 * string), it will be treated as data and thus quoted appropriately.
1473 * If it is null, an IS NULL clause will be added.
1474 * - If the value is an array, an IN (...) clause will be constructed
1475 * from its non-null elements, and an IS NULL clause will be added
1476 * if null is present, such that the field may match any of the
1477 * elements in the array. The non-null elements will be quoted.
1479 * Note that expressions are often DBMS-dependent in their syntax.
1480 * DBMS-independent wrappers are provided for constructing several types of
1481 * expression commonly used in condition queries. See:
1482 * - DatabaseBase::buildLike()
1483 * - DatabaseBase::conditional()
1486 * @param string|array $options
1488 * Optional: Array of query options. Boolean options are specified by
1489 * including them in the array as a string value with a numeric key, for
1492 * array( 'FOR UPDATE' )
1494 * The supported options are:
1496 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1497 * with LIMIT can theoretically be used for paging through a result set,
1498 * but this is discouraged in MediaWiki for performance reasons.
1500 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1501 * and then the first rows are taken until the limit is reached. LIMIT
1502 * is applied to a result set after OFFSET.
1504 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1505 * changed until the next COMMIT.
1507 * - DISTINCT: Boolean: return only unique result rows.
1509 * - GROUP BY: May be either an SQL fragment string naming a field or
1510 * expression to group by, or an array of such SQL fragments.
1512 * - HAVING: May be either an string containing a HAVING clause or an array of
1513 * conditions building the HAVING clause. If an array is given, the conditions
1514 * constructed from each element are combined with AND.
1516 * - ORDER BY: May be either an SQL fragment giving a field name or
1517 * expression to order by, or an array of such SQL fragments.
1519 * - USE INDEX: This may be either a string giving the index name to use
1520 * for the query, or an array. If it is an associative array, each key
1521 * gives the table name (or alias), each value gives the index name to
1522 * use for that table. All strings are SQL fragments and so should be
1523 * validated by the caller.
1525 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1526 * instead of SELECT.
1528 * And also the following boolean MySQL extensions, see the MySQL manual
1529 * for documentation:
1531 * - LOCK IN SHARE MODE
1535 * - SQL_BUFFER_RESULT
1536 * - SQL_SMALL_RESULT
1537 * - SQL_CALC_FOUND_ROWS
1542 * @param string|array $join_conds
1544 * Optional associative array of table-specific join conditions. In the
1545 * most common case, this is unnecessary, since the join condition can be
1546 * in $conds. However, it is useful for doing a LEFT JOIN.
1548 * The key of the array contains the table name or alias. The value is an
1549 * array with two elements, numbered 0 and 1. The first gives the type of
1550 * join, the second is an SQL fragment giving the join condition for that
1551 * table. For example:
1553 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1555 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1556 * with no rows in it will be returned. If there was a query error, a
1557 * DBQueryError exception will be thrown, except if the "ignore errors"
1558 * option was set, in which case false will be returned.
1560 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1561 $options = array(), $join_conds = array() ) {
1562 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1564 return $this->query( $sql, $fname );
1568 * The equivalent of DatabaseBase::select() except that the constructed SQL
1569 * is returned, instead of being immediately executed. This can be useful for
1570 * doing UNION queries, where the SQL text of each query is needed. In general,
1571 * however, callers outside of Database classes should just use select().
1573 * @param string|array $table Table name
1574 * @param string|array $vars Field names
1575 * @param string|array $conds Conditions
1576 * @param string $fname Caller function name
1577 * @param string|array $options Query options
1578 * @param string|array $join_conds Join conditions
1580 * @return string SQL query string.
1581 * @see DatabaseBase::select()
1583 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1584 $options = array(), $join_conds = array()
1586 if ( is_array( $vars ) ) {
1587 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1590 $options = (array)$options;
1591 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1592 ?
$options['USE INDEX']
1595 if ( is_array( $table ) ) {
1597 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1598 } elseif ( $table != '' ) {
1599 if ( $table[0] == ' ' ) {
1600 $from = ' FROM ' . $table;
1603 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1609 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1610 $this->makeSelectOptions( $options );
1612 if ( !empty( $conds ) ) {
1613 if ( is_array( $conds ) ) {
1614 $conds = $this->makeList( $conds, LIST_AND
);
1616 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1618 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1621 if ( isset( $options['LIMIT'] ) ) {
1622 $sql = $this->limitResult( $sql, $options['LIMIT'],
1623 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1625 $sql = "$sql $postLimitTail";
1627 if ( isset( $options['EXPLAIN'] ) ) {
1628 $sql = 'EXPLAIN ' . $sql;
1635 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1636 * that a single row object is returned. If the query returns no rows,
1637 * false is returned.
1639 * @param string|array $table Table name
1640 * @param string|array $vars Field names
1641 * @param array $conds Conditions
1642 * @param string $fname Caller function name
1643 * @param string|array $options Query options
1644 * @param array|string $join_conds Join conditions
1646 * @return stdClass|bool
1648 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1649 $options = array(), $join_conds = array()
1651 $options = (array)$options;
1652 $options['LIMIT'] = 1;
1653 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1655 if ( $res === false ) {
1659 if ( !$this->numRows( $res ) ) {
1663 $obj = $this->fetchObject( $res );
1669 * Estimate the number of rows in dataset
1671 * MySQL allows you to estimate the number of rows that would be returned
1672 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1673 * index cardinality statistics, and is notoriously inaccurate, especially
1674 * when large numbers of rows have recently been added or deleted.
1676 * For DBMSs that don't support fast result size estimation, this function
1677 * will actually perform the SELECT COUNT(*).
1679 * Takes the same arguments as DatabaseBase::select().
1681 * @param string $table Table name
1682 * @param string $vars Unused
1683 * @param array|string $conds Filters on the table
1684 * @param string $fname Function name for profiling
1685 * @param array $options Options for select
1686 * @return int Row count
1688 public function estimateRowCount(
1689 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1692 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1695 $row = $this->fetchRow( $res );
1696 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1703 * Get the number of rows in dataset
1705 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1707 * Takes the same arguments as DatabaseBase::select().
1709 * @since 1.27 Added $join_conds parameter
1711 * @param array|string $tables Table names
1712 * @param string $vars Unused
1713 * @param array|string $conds Filters on the table
1714 * @param string $fname Function name for profiling
1715 * @param array $options Options for select
1716 * @param array $join_conds Join conditions (since 1.27)
1717 * @return int Row count
1719 public function selectRowCount(
1720 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1723 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1724 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1727 $row = $this->fetchRow( $res );
1728 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1735 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1736 * It's only slightly flawed. Don't use for anything important.
1738 * @param string $sql A SQL Query
1742 protected static function generalizeSQL( $sql ) {
1743 # This does the same as the regexp below would do, but in such a way
1744 # as to avoid crashing php on some large strings.
1745 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1747 $sql = str_replace( "\\\\", '', $sql );
1748 $sql = str_replace( "\\'", '', $sql );
1749 $sql = str_replace( "\\\"", '', $sql );
1750 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1751 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1753 # All newlines, tabs, etc replaced by single space
1754 $sql = preg_replace( '/\s+/', ' ', $sql );
1757 # except the ones surrounded by characters, e.g. l10n
1758 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1759 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1765 * Determines whether a field exists in a table
1767 * @param string $table Table name
1768 * @param string $field Filed to check on that table
1769 * @param string $fname Calling function name (optional)
1770 * @return bool Whether $table has filed $field
1772 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1773 $info = $this->fieldInfo( $table, $field );
1779 * Determines whether an index exists
1780 * Usually throws a DBQueryError on failure
1781 * If errors are explicitly ignored, returns NULL on failure
1783 * @param string $table
1784 * @param string $index
1785 * @param string $fname
1788 public function indexExists( $table, $index, $fname = __METHOD__
) {
1789 if ( !$this->tableExists( $table ) ) {
1793 $info = $this->indexInfo( $table, $index, $fname );
1794 if ( is_null( $info ) ) {
1797 return $info !== false;
1802 * Query whether a given table exists
1804 * @param string $table
1805 * @param string $fname
1808 public function tableExists( $table, $fname = __METHOD__
) {
1809 $table = $this->tableName( $table );
1810 $old = $this->ignoreErrors( true );
1811 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1812 $this->ignoreErrors( $old );
1818 * Determines if a given index is unique
1820 * @param string $table
1821 * @param string $index
1825 public function indexUnique( $table, $index ) {
1826 $indexInfo = $this->indexInfo( $table, $index );
1828 if ( !$indexInfo ) {
1832 return !$indexInfo[0]->Non_unique
;
1836 * Helper for DatabaseBase::insert().
1838 * @param array $options
1841 protected function makeInsertOptions( $options ) {
1842 return implode( ' ', $options );
1846 * INSERT wrapper, inserts an array into a table.
1850 * - A single associative array. The array keys are the field names, and
1851 * the values are the values to insert. The values are treated as data
1852 * and will be quoted appropriately. If NULL is inserted, this will be
1853 * converted to a database NULL.
1854 * - An array with numeric keys, holding a list of associative arrays.
1855 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1856 * each subarray must be identical to each other, and in the same order.
1858 * $options is an array of options, with boolean options encoded as values
1859 * with numeric keys, in the same style as $options in
1860 * DatabaseBase::select(). Supported options are:
1862 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1863 * any rows which cause duplicate key errors are not inserted. It's
1864 * possible to determine how many rows were successfully inserted using
1865 * DatabaseBase::affectedRows().
1867 * @param string $table Table name. This will be passed through
1868 * DatabaseBase::tableName().
1869 * @param array $a Array of rows to insert
1870 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1871 * @param array $options Array of options
1873 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1878 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1879 # No rows to insert, easy just return now
1880 if ( !count( $a ) ) {
1884 $table = $this->tableName( $table );
1886 if ( !is_array( $options ) ) {
1887 $options = array( $options );
1891 if ( isset( $options['fileHandle'] ) ) {
1892 $fh = $options['fileHandle'];
1894 $options = $this->makeInsertOptions( $options );
1896 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1898 $keys = array_keys( $a[0] );
1901 $keys = array_keys( $a );
1904 $sql = 'INSERT ' . $options .
1905 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1909 foreach ( $a as $row ) {
1915 $sql .= '(' . $this->makeList( $row ) . ')';
1918 $sql .= '(' . $this->makeList( $a ) . ')';
1921 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1923 } elseif ( $fh !== null ) {
1927 return (bool)$this->query( $sql, $fname );
1931 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1933 * @param array $options
1936 protected function makeUpdateOptionsArray( $options ) {
1937 if ( !is_array( $options ) ) {
1938 $options = array( $options );
1943 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1944 $opts[] = $this->lowPriorityOption();
1947 if ( in_array( 'IGNORE', $options ) ) {
1955 * Make UPDATE options for the DatabaseBase::update function
1957 * @param array $options The options passed to DatabaseBase::update
1960 protected function makeUpdateOptions( $options ) {
1961 $opts = $this->makeUpdateOptionsArray( $options );
1963 return implode( ' ', $opts );
1967 * UPDATE wrapper. Takes a condition array and a SET array.
1969 * @param string $table Name of the table to UPDATE. This will be passed through
1970 * DatabaseBase::tableName().
1971 * @param array $values An array of values to SET. For each array element,
1972 * the key gives the field name, and the value gives the data to set
1973 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1974 * @param array $conds An array of conditions (WHERE). See
1975 * DatabaseBase::select() for the details of the format of condition
1976 * arrays. Use '*' to update all rows.
1977 * @param string $fname The function name of the caller (from __METHOD__),
1978 * for logging and profiling.
1979 * @param array $options An array of UPDATE options, can be:
1980 * - IGNORE: Ignore unique key conflicts
1981 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1984 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1985 $table = $this->tableName( $table );
1986 $opts = $this->makeUpdateOptions( $options );
1987 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1989 if ( $conds !== array() && $conds !== '*' ) {
1990 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1993 return $this->query( $sql, $fname );
1997 * Makes an encoded list of strings from an array
1999 * @param array $a Containing the data
2000 * @param int $mode Constant
2001 * - LIST_COMMA: Comma separated, no field names
2002 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2003 * documentation for $conds in DatabaseBase::select().
2004 * - LIST_OR: ORed WHERE clause (without the WHERE)
2005 * - LIST_SET: Comma separated with field names, like a SET clause
2006 * - LIST_NAMES: Comma separated field names
2007 * @throws MWException|DBUnexpectedError
2010 public function makeList( $a, $mode = LIST_COMMA
) {
2011 if ( !is_array( $a ) ) {
2012 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2018 foreach ( $a as $field => $value ) {
2020 if ( $mode == LIST_AND
) {
2022 } elseif ( $mode == LIST_OR
) {
2031 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2032 $list .= "($value)";
2033 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2035 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2036 // Remove null from array to be handled separately if found
2037 $includeNull = false;
2038 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2039 $includeNull = true;
2040 unset( $value[$nullKey] );
2042 if ( count( $value ) == 0 && !$includeNull ) {
2043 throw new MWException( __METHOD__
. ": empty input for field $field" );
2044 } elseif ( count( $value ) == 0 ) {
2045 // only check if $field is null
2046 $list .= "$field IS NULL";
2048 // IN clause contains at least one valid element
2049 if ( $includeNull ) {
2050 // Group subconditions to ensure correct precedence
2053 if ( count( $value ) == 1 ) {
2054 // Special-case single values, as IN isn't terribly efficient
2055 // Don't necessarily assume the single key is 0; we don't
2056 // enforce linear numeric ordering on other arrays here.
2057 $value = array_values( $value );
2058 $list .= $field . " = " . $this->addQuotes( $value[0] );
2060 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2062 // if null present in array, append IS NULL
2063 if ( $includeNull ) {
2064 $list .= " OR $field IS NULL)";
2067 } elseif ( $value === null ) {
2068 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2069 $list .= "$field IS ";
2070 } elseif ( $mode == LIST_SET
) {
2071 $list .= "$field = ";
2075 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2076 $list .= "$field = ";
2078 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2086 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2087 * The keys on each level may be either integers or strings.
2089 * @param array $data Organized as 2-d
2090 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2091 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2092 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2093 * @return string|bool SQL fragment, or false if no items in array
2095 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2098 foreach ( $data as $base => $sub ) {
2099 if ( count( $sub ) ) {
2100 $conds[] = $this->makeList(
2101 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2107 return $this->makeList( $conds, LIST_OR
);
2109 // Nothing to search for...
2115 * Return aggregated value alias
2117 * @param array $valuedata
2118 * @param string $valuename
2122 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2127 * @param string $field
2130 public function bitNot( $field ) {
2135 * @param string $fieldLeft
2136 * @param string $fieldRight
2139 public function bitAnd( $fieldLeft, $fieldRight ) {
2140 return "($fieldLeft & $fieldRight)";
2144 * @param string $fieldLeft
2145 * @param string $fieldRight
2148 public function bitOr( $fieldLeft, $fieldRight ) {
2149 return "($fieldLeft | $fieldRight)";
2153 * Build a concatenation list to feed into a SQL query
2154 * @param array $stringList List of raw SQL expressions; caller is
2155 * responsible for any quoting
2158 public function buildConcat( $stringList ) {
2159 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2163 * Build a GROUP_CONCAT or equivalent statement for a query.
2165 * This is useful for combining a field for several rows into a single string.
2166 * NULL values will not appear in the output, duplicated values will appear,
2167 * and the resulting delimiter-separated values have no defined sort order.
2168 * Code using the results may need to use the PHP unique() or sort() methods.
2170 * @param string $delim Glue to bind the results together
2171 * @param string|array $table Table name
2172 * @param string $field Field name
2173 * @param string|array $conds Conditions
2174 * @param string|array $join_conds Join conditions
2175 * @return string SQL text
2178 public function buildGroupConcatField(
2179 $delim, $table, $field, $conds = '', $join_conds = array()
2181 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2183 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2187 * Change the current database
2189 * @todo Explain what exactly will fail if this is not overridden.
2193 * @return bool Success or failure
2195 public function selectDB( $db ) {
2196 # Stub. Shouldn't cause serious problems if it's not overridden, but
2197 # if your database engine supports a concept similar to MySQL's
2198 # databases you may as well.
2199 $this->mDBname
= $db;
2205 * Get the current DB name
2208 public function getDBname() {
2209 return $this->mDBname
;
2213 * Get the server hostname or IP address
2216 public function getServer() {
2217 return $this->mServer
;
2221 * Format a table name ready for use in constructing an SQL query
2223 * This does two important things: it quotes the table names to clean them up,
2224 * and it adds a table prefix if only given a table name with no quotes.
2226 * All functions of this object which require a table name call this function
2227 * themselves. Pass the canonical name to such functions. This is only needed
2228 * when calling query() directly.
2230 * @param string $name Database table name
2231 * @param string $format One of:
2232 * quoted - Automatically pass the table name through addIdentifierQuotes()
2233 * so that it can be used in a query.
2234 * raw - Do not add identifier quotes to the table name
2235 * @return string Full database name
2237 public function tableName( $name, $format = 'quoted' ) {
2238 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2239 # Skip the entire process when we have a string quoted on both ends.
2240 # Note that we check the end so that we will still quote any use of
2241 # use of `database`.table. But won't break things if someone wants
2242 # to query a database table with a dot in the name.
2243 if ( $this->isQuotedIdentifier( $name ) ) {
2247 # Lets test for any bits of text that should never show up in a table
2248 # name. Basically anything like JOIN or ON which are actually part of
2249 # SQL queries, but may end up inside of the table value to combine
2250 # sql. Such as how the API is doing.
2251 # Note that we use a whitespace test rather than a \b test to avoid
2252 # any remote case where a word like on may be inside of a table name
2253 # surrounded by symbols which may be considered word breaks.
2254 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2258 # Split database and table into proper variables.
2259 # We reverse the explode so that database.table and table both output
2260 # the correct table.
2261 $dbDetails = explode( '.', $name, 3 );
2262 if ( count( $dbDetails ) == 3 ) {
2263 list( $database, $schema, $table ) = $dbDetails;
2264 # We don't want any prefix added in this case
2266 } elseif ( count( $dbDetails ) == 2 ) {
2267 list( $database, $table ) = $dbDetails;
2268 # We don't want any prefix added in this case
2269 # In dbs that support it, $database may actually be the schema
2270 # but that doesn't affect any of the functionality here
2274 list( $table ) = $dbDetails;
2275 if ( $wgSharedDB !== null # We have a shared database
2276 && $this->mForeign
== false # We're not working on a foreign database
2277 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2278 && in_array( $table, $wgSharedTables ) # A shared table is selected
2280 $database = $wgSharedDB;
2281 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2282 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2285 $schema = $this->mSchema
; # Default schema
2286 $prefix = $this->mTablePrefix
; # Default prefix
2290 # Quote $table and apply the prefix if not quoted.
2291 # $tableName might be empty if this is called from Database::replaceVars()
2292 $tableName = "{$prefix}{$table}";
2293 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2294 $tableName = $this->addIdentifierQuotes( $tableName );
2297 # Quote $schema and merge it with the table name if needed
2298 if ( strlen( $schema ) ) {
2299 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2300 $schema = $this->addIdentifierQuotes( $schema );
2302 $tableName = $schema . '.' . $tableName;
2305 # Quote $database and merge it with the table name if needed
2306 if ( $database !== null ) {
2307 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2308 $database = $this->addIdentifierQuotes( $database );
2310 $tableName = $database . '.' . $tableName;
2317 * Fetch a number of table names into an array
2318 * This is handy when you need to construct SQL for joins
2321 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2322 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2323 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2327 public function tableNames() {
2328 $inArray = func_get_args();
2331 foreach ( $inArray as $name ) {
2332 $retVal[$name] = $this->tableName( $name );
2339 * Fetch a number of table names into an zero-indexed numerical array
2340 * This is handy when you need to construct SQL for joins
2343 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2344 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2345 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2349 public function tableNamesN() {
2350 $inArray = func_get_args();
2353 foreach ( $inArray as $name ) {
2354 $retVal[] = $this->tableName( $name );
2361 * Get an aliased table name
2362 * e.g. tableName AS newTableName
2364 * @param string $name Table name, see tableName()
2365 * @param string|bool $alias Alias (optional)
2366 * @return string SQL name for aliased table. Will not alias a table to its own name
2368 public function tableNameWithAlias( $name, $alias = false ) {
2369 if ( !$alias ||
$alias == $name ) {
2370 return $this->tableName( $name );
2372 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2377 * Gets an array of aliased table names
2379 * @param array $tables Array( [alias] => table )
2380 * @return string[] See tableNameWithAlias()
2382 public function tableNamesWithAlias( $tables ) {
2384 foreach ( $tables as $alias => $table ) {
2385 if ( is_numeric( $alias ) ) {
2388 $retval[] = $this->tableNameWithAlias( $table, $alias );
2395 * Get an aliased field name
2396 * e.g. fieldName AS newFieldName
2398 * @param string $name Field name
2399 * @param string|bool $alias Alias (optional)
2400 * @return string SQL name for aliased field. Will not alias a field to its own name
2402 public function fieldNameWithAlias( $name, $alias = false ) {
2403 if ( !$alias ||
(string)$alias === (string)$name ) {
2406 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2411 * Gets an array of aliased field names
2413 * @param array $fields Array( [alias] => field )
2414 * @return string[] See fieldNameWithAlias()
2416 public function fieldNamesWithAlias( $fields ) {
2418 foreach ( $fields as $alias => $field ) {
2419 if ( is_numeric( $alias ) ) {
2422 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2429 * Get the aliased table name clause for a FROM clause
2430 * which might have a JOIN and/or USE INDEX clause
2432 * @param array $tables ( [alias] => table )
2433 * @param array $use_index Same as for select()
2434 * @param array $join_conds Same as for select()
2437 protected function tableNamesWithUseIndexOrJOIN(
2438 $tables, $use_index = array(), $join_conds = array()
2442 $use_index = (array)$use_index;
2443 $join_conds = (array)$join_conds;
2445 foreach ( $tables as $alias => $table ) {
2446 if ( !is_string( $alias ) ) {
2447 // No alias? Set it equal to the table name
2450 // Is there a JOIN clause for this table?
2451 if ( isset( $join_conds[$alias] ) ) {
2452 list( $joinType, $conds ) = $join_conds[$alias];
2453 $tableClause = $joinType;
2454 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2455 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2456 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2458 $tableClause .= ' ' . $use;
2461 $on = $this->makeList( (array)$conds, LIST_AND
);
2463 $tableClause .= ' ON (' . $on . ')';
2466 $retJOIN[] = $tableClause;
2467 } elseif ( isset( $use_index[$alias] ) ) {
2468 // Is there an INDEX clause for this table?
2469 $tableClause = $this->tableNameWithAlias( $table, $alias );
2470 $tableClause .= ' ' . $this->useIndexClause(
2471 implode( ',', (array)$use_index[$alias] )
2474 $ret[] = $tableClause;
2476 $tableClause = $this->tableNameWithAlias( $table, $alias );
2478 $ret[] = $tableClause;
2482 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2483 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2484 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2486 // Compile our final table clause
2487 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2491 * Get the name of an index in a given table.
2493 * @protected Don't use outside of DatabaseBase and childs
2494 * @param string $index
2497 public function indexName( $index ) {
2498 // @FIXME: Make this protected once we move away from PHP 5.3
2499 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2501 // Backwards-compatibility hack
2503 'ar_usertext_timestamp' => 'usertext_timestamp',
2504 'un_user_id' => 'user_id',
2505 'un_user_ip' => 'user_ip',
2508 if ( isset( $renamed[$index] ) ) {
2509 return $renamed[$index];
2516 * Adds quotes and backslashes.
2518 * @param string|Blob $s
2521 public function addQuotes( $s ) {
2522 if ( $s instanceof Blob
) {
2525 if ( $s === null ) {
2528 # This will also quote numeric values. This should be harmless,
2529 # and protects against weird problems that occur when they really
2530 # _are_ strings such as article titles and string->number->string
2531 # conversion is not 1:1.
2532 return "'" . $this->strencode( $s ) . "'";
2537 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2538 * MySQL uses `backticks` while basically everything else uses double quotes.
2539 * Since MySQL is the odd one out here the double quotes are our generic
2540 * and we implement backticks in DatabaseMysql.
2545 public function addIdentifierQuotes( $s ) {
2546 return '"' . str_replace( '"', '""', $s ) . '"';
2550 * Returns if the given identifier looks quoted or not according to
2551 * the database convention for quoting identifiers .
2553 * @param string $name
2556 public function isQuotedIdentifier( $name ) {
2557 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2564 protected function escapeLikeInternal( $s ) {
2565 return addcslashes( $s, '\%_' );
2569 * LIKE statement wrapper, receives a variable-length argument list with
2570 * parts of pattern to match containing either string literals that will be
2571 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2572 * the function could be provided with an array of aforementioned
2575 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2576 * a LIKE clause that searches for subpages of 'My page title'.
2578 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2579 * $query .= $dbr->buildLike( $pattern );
2582 * @return string Fully built LIKE statement
2584 public function buildLike() {
2585 $params = func_get_args();
2587 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2588 $params = $params[0];
2593 foreach ( $params as $value ) {
2594 if ( $value instanceof LikeMatch
) {
2595 $s .= $value->toString();
2597 $s .= $this->escapeLikeInternal( $value );
2601 return " LIKE {$this->addQuotes( $s )} ";
2605 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2609 public function anyChar() {
2610 return new LikeMatch( '_' );
2614 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2618 public function anyString() {
2619 return new LikeMatch( '%' );
2623 * Returns an appropriately quoted sequence value for inserting a new row.
2624 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2625 * subclass will return an integer, and save the value for insertId()
2627 * Any implementation of this function should *not* involve reusing
2628 * sequence numbers created for rolled-back transactions.
2629 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2630 * @param string $seqName
2633 public function nextSequenceValue( $seqName ) {
2638 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2639 * is only needed because a) MySQL must be as efficient as possible due to
2640 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2641 * which index to pick. Anyway, other databases might have different
2642 * indexes on a given table. So don't bother overriding this unless you're
2644 * @param string $index
2647 public function useIndexClause( $index ) {
2652 * REPLACE query wrapper.
2654 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2655 * except that when there is a duplicate key error, the old row is deleted
2656 * and the new row is inserted in its place.
2658 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2659 * perform the delete, we need to know what the unique indexes are so that
2660 * we know how to find the conflicting rows.
2662 * It may be more efficient to leave off unique indexes which are unlikely
2663 * to collide. However if you do this, you run the risk of encountering
2664 * errors which wouldn't have occurred in MySQL.
2666 * @param string $table The table to replace the row(s) in.
2667 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2668 * a field name or an array of field names
2669 * @param array $rows Can be either a single row to insert, or multiple rows,
2670 * in the same format as for DatabaseBase::insert()
2671 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2673 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2674 $quotedTable = $this->tableName( $table );
2676 if ( count( $rows ) == 0 ) {
2681 if ( !is_array( reset( $rows ) ) ) {
2682 $rows = array( $rows );
2685 // @FXIME: this is not atomic, but a trx would break affectedRows()
2686 foreach ( $rows as $row ) {
2687 # Delete rows which collide
2688 if ( $uniqueIndexes ) {
2689 $sql = "DELETE FROM $quotedTable WHERE ";
2691 foreach ( $uniqueIndexes as $index ) {
2698 if ( is_array( $index ) ) {
2700 foreach ( $index as $col ) {
2706 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2709 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2713 $this->query( $sql, $fname );
2716 # Now insert the row
2717 $this->insert( $table, $row, $fname );
2722 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2725 * @param string $table Table name
2726 * @param array|string $rows Row(s) to insert
2727 * @param string $fname Caller function name
2729 * @return ResultWrapper
2731 protected function nativeReplace( $table, $rows, $fname ) {
2732 $table = $this->tableName( $table );
2735 if ( !is_array( reset( $rows ) ) ) {
2736 $rows = array( $rows );
2739 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2742 foreach ( $rows as $row ) {
2749 $sql .= '(' . $this->makeList( $row ) . ')';
2752 return $this->query( $sql, $fname );
2756 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2758 * This updates any conflicting rows (according to the unique indexes) using
2759 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2761 * $rows may be either:
2762 * - A single associative array. The array keys are the field names, and
2763 * the values are the values to insert. The values are treated as data
2764 * and will be quoted appropriately. If NULL is inserted, this will be
2765 * converted to a database NULL.
2766 * - An array with numeric keys, holding a list of associative arrays.
2767 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2768 * each subarray must be identical to each other, and in the same order.
2770 * It may be more efficient to leave off unique indexes which are unlikely
2771 * to collide. However if you do this, you run the risk of encountering
2772 * errors which wouldn't have occurred in MySQL.
2774 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2779 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2780 * @param array $rows A single row or list of rows to insert
2781 * @param array $uniqueIndexes List of single field names or field name tuples
2782 * @param array $set An array of values to SET. For each array element, the
2783 * key gives the field name, and the value gives the data to set that
2784 * field to. The data will be quoted by DatabaseBase::addQuotes().
2785 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2789 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2792 if ( !count( $rows ) ) {
2793 return true; // nothing to do
2796 if ( !is_array( reset( $rows ) ) ) {
2797 $rows = array( $rows );
2800 if ( count( $uniqueIndexes ) ) {
2801 $clauses = array(); // list WHERE clauses that each identify a single row
2802 foreach ( $rows as $row ) {
2803 foreach ( $uniqueIndexes as $index ) {
2804 $index = is_array( $index ) ?
$index : array( $index ); // columns
2805 $rowKey = array(); // unique key to this row
2806 foreach ( $index as $column ) {
2807 $rowKey[$column] = $row[$column];
2809 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2812 $where = array( $this->makeList( $clauses, LIST_OR
) );
2817 $useTrx = !$this->mTrxLevel
;
2819 $this->begin( $fname );
2822 # Update any existing conflicting row(s)
2823 if ( $where !== false ) {
2824 $ok = $this->update( $table, $set, $where, $fname );
2828 # Now insert any non-conflicting row(s)
2829 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2830 } catch ( Exception
$e ) {
2832 $this->rollback( $fname );
2837 $this->commit( $fname );
2844 * DELETE where the condition is a join.
2846 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2847 * we use sub-selects
2849 * For safety, an empty $conds will not delete everything. If you want to
2850 * delete all rows where the join condition matches, set $conds='*'.
2852 * DO NOT put the join condition in $conds.
2854 * @param string $delTable The table to delete from.
2855 * @param string $joinTable The other table.
2856 * @param string $delVar The variable to join on, in the first table.
2857 * @param string $joinVar The variable to join on, in the second table.
2858 * @param array $conds Condition array of field names mapped to variables,
2859 * ANDed together in the WHERE clause
2860 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2861 * @throws DBUnexpectedError
2863 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2867 throw new DBUnexpectedError( $this,
2868 'DatabaseBase::deleteJoin() called with empty $conds' );
2871 $delTable = $this->tableName( $delTable );
2872 $joinTable = $this->tableName( $joinTable );
2873 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2874 if ( $conds != '*' ) {
2875 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2879 $this->query( $sql, $fname );
2883 * Returns the size of a text field, or -1 for "unlimited"
2885 * @param string $table
2886 * @param string $field
2889 public function textFieldSize( $table, $field ) {
2890 $table = $this->tableName( $table );
2891 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2892 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2893 $row = $this->fetchObject( $res );
2897 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2907 * A string to insert into queries to show that they're low-priority, like
2908 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2909 * string and nothing bad should happen.
2911 * @return string Returns the text of the low priority option if it is
2912 * supported, or a blank string otherwise
2914 public function lowPriorityOption() {
2919 * DELETE query wrapper.
2921 * @param array $table Table name
2922 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2923 * for the format. Use $conds == "*" to delete all rows
2924 * @param string $fname Name of the calling function
2925 * @throws DBUnexpectedError
2926 * @return bool|ResultWrapper
2928 public function delete( $table, $conds, $fname = __METHOD__
) {
2930 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2933 $table = $this->tableName( $table );
2934 $sql = "DELETE FROM $table";
2936 if ( $conds != '*' ) {
2937 if ( is_array( $conds ) ) {
2938 $conds = $this->makeList( $conds, LIST_AND
);
2940 $sql .= ' WHERE ' . $conds;
2943 return $this->query( $sql, $fname );
2947 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2948 * into another table.
2950 * @param string $destTable The table name to insert into
2951 * @param string|array $srcTable May be either a table name, or an array of table names
2952 * to include in a join.
2954 * @param array $varMap Must be an associative array of the form
2955 * array( 'dest1' => 'source1', ...). Source items may be literals
2956 * rather than field names, but strings should be quoted with
2957 * DatabaseBase::addQuotes()
2959 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2960 * the details of the format of condition arrays. May be "*" to copy the
2963 * @param string $fname The function name of the caller, from __METHOD__
2965 * @param array $insertOptions Options for the INSERT part of the query, see
2966 * DatabaseBase::insert() for details.
2967 * @param array $selectOptions Options for the SELECT part of the query, see
2968 * DatabaseBase::select() for details.
2970 * @return ResultWrapper
2972 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2973 $fname = __METHOD__
,
2974 $insertOptions = array(), $selectOptions = array()
2976 $destTable = $this->tableName( $destTable );
2978 if ( !is_array( $insertOptions ) ) {
2979 $insertOptions = array( $insertOptions );
2982 $insertOptions = $this->makeInsertOptions( $insertOptions );
2984 if ( !is_array( $selectOptions ) ) {
2985 $selectOptions = array( $selectOptions );
2988 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2990 if ( is_array( $srcTable ) ) {
2991 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2993 $srcTable = $this->tableName( $srcTable );
2996 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2997 " SELECT $startOpts " . implode( ',', $varMap ) .
2998 " FROM $srcTable $useIndex ";
3000 if ( $conds != '*' ) {
3001 if ( is_array( $conds ) ) {
3002 $conds = $this->makeList( $conds, LIST_AND
);
3004 $sql .= " WHERE $conds";
3007 $sql .= " $tailOpts";
3009 return $this->query( $sql, $fname );
3013 * Construct a LIMIT query with optional offset. This is used for query
3014 * pages. The SQL should be adjusted so that only the first $limit rows
3015 * are returned. If $offset is provided as well, then the first $offset
3016 * rows should be discarded, and the next $limit rows should be returned.
3017 * If the result of the query is not ordered, then the rows to be returned
3018 * are theoretically arbitrary.
3020 * $sql is expected to be a SELECT, if that makes a difference.
3022 * The version provided by default works in MySQL and SQLite. It will very
3023 * likely need to be overridden for most other DBMSes.
3025 * @param string $sql SQL query we will append the limit too
3026 * @param int $limit The SQL limit
3027 * @param int|bool $offset The SQL offset (default false)
3028 * @throws DBUnexpectedError
3031 public function limitResult( $sql, $limit, $offset = false ) {
3032 if ( !is_numeric( $limit ) ) {
3033 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3036 return "$sql LIMIT "
3037 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3042 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3043 * within the UNION construct.
3046 public function unionSupportsOrderAndLimit() {
3047 return true; // True for almost every DB supported
3051 * Construct a UNION query
3052 * This is used for providing overload point for other DB abstractions
3053 * not compatible with the MySQL syntax.
3054 * @param array $sqls SQL statements to combine
3055 * @param bool $all Use UNION ALL
3056 * @return string SQL fragment
3058 public function unionQueries( $sqls, $all ) {
3059 $glue = $all ?
') UNION ALL (' : ') UNION (';
3061 return '(' . implode( $glue, $sqls ) . ')';
3065 * Returns an SQL expression for a simple conditional. This doesn't need
3066 * to be overridden unless CASE isn't supported in your DBMS.
3068 * @param string|array $cond SQL expression which will result in a boolean value
3069 * @param string $trueVal SQL expression to return if true
3070 * @param string $falseVal SQL expression to return if false
3071 * @return string SQL fragment
3073 public function conditional( $cond, $trueVal, $falseVal ) {
3074 if ( is_array( $cond ) ) {
3075 $cond = $this->makeList( $cond, LIST_AND
);
3078 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3082 * Returns a comand for str_replace function in SQL query.
3083 * Uses REPLACE() in MySQL
3085 * @param string $orig Column to modify
3086 * @param string $old Column to seek
3087 * @param string $new Column to replace with
3091 public function strreplace( $orig, $old, $new ) {
3092 return "REPLACE({$orig}, {$old}, {$new})";
3096 * Determines how long the server has been up
3101 public function getServerUptime() {
3106 * Determines if the last failure was due to a deadlock
3111 public function wasDeadlock() {
3116 * Determines if the last failure was due to a lock timeout
3121 public function wasLockTimeout() {
3126 * Determines if the last query error was something that should be dealt
3127 * with by pinging the connection and reissuing the query.
3132 public function wasErrorReissuable() {
3137 * Determines if the last failure was due to the database being read-only.
3142 public function wasReadOnlyError() {
3147 * Determines if the given query error was a connection drop
3150 * @param integer|string $errno
3153 public function wasConnectionError( $errno ) {
3158 * Perform a deadlock-prone transaction.
3160 * This function invokes a callback function to perform a set of write
3161 * queries. If a deadlock occurs during the processing, the transaction
3162 * will be rolled back and the callback function will be called again.
3165 * $dbw->deadlockLoop( callback, ... );
3167 * Extra arguments are passed through to the specified callback function.
3169 * Returns whatever the callback function returned on its successful,
3170 * iteration, or false on error, for example if the retry limit was
3174 * @throws DBQueryError
3176 public function deadlockLoop() {
3177 $args = func_get_args();
3178 $function = array_shift( $args );
3179 $tries = self
::DEADLOCK_TRIES
;
3181 $this->begin( __METHOD__
);
3187 $retVal = call_user_func_array( $function, $args );
3189 } catch ( DBQueryError
$e ) {
3190 if ( $this->wasDeadlock() ) {
3191 // Retry after a randomized delay
3192 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3194 // Throw the error back up
3198 } while ( --$tries > 0 );
3200 if ( $tries <= 0 ) {
3201 // Too many deadlocks; give up
3202 $this->rollback( __METHOD__
);
3205 $this->commit( __METHOD__
);
3212 * Wait for the slave to catch up to a given master position.
3214 * @param DBMasterPos $pos
3215 * @param int $timeout The maximum number of seconds to wait for
3217 * @return int Zero if the slave was past that position already,
3218 * greater than zero if we waited for some period of time, less than
3219 * zero if we timed out.
3221 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3222 # Real waits are implemented in the subclass.
3227 * Get the replication position of this slave
3229 * @return DBMasterPos|bool False if this is not a slave.
3231 public function getSlavePos() {
3237 * Get the position of this master
3239 * @return DBMasterPos|bool False if this is not a master
3241 public function getMasterPos() {
3247 * Run an anonymous function as soon as there is no transaction pending.
3248 * If there is a transaction and it is rolled back, then the callback is cancelled.
3249 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3250 * Callbacks must commit any transactions that they begin.
3252 * This is useful for updates to different systems or when separate transactions are needed.
3253 * For example, one might want to enqueue jobs into a system outside the database, but only
3254 * after the database is updated so that the jobs will see the data when they actually run.
3255 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3257 * @param callable $callback
3260 final public function onTransactionIdle( $callback ) {
3261 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3262 if ( !$this->mTrxLevel
) {
3263 $this->runOnTransactionIdleCallbacks();
3268 * Run an anonymous function before the current transaction commits or now if there is none.
3269 * If there is a transaction and it is rolled back, then the callback is cancelled.
3270 * Callbacks must not start nor commit any transactions.
3272 * This is useful for updates that easily cause deadlocks if locks are held too long
3273 * but where atomicity is strongly desired for these updates and some related updates.
3275 * @param callable $callback
3278 final public function onTransactionPreCommitOrIdle( $callback ) {
3279 if ( $this->mTrxLevel
) {
3280 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3282 $this->onTransactionIdle( $callback ); // this will trigger immediately
3287 * Actually any "on transaction idle" callbacks.
3291 protected function runOnTransactionIdleCallbacks() {
3292 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3294 $e = $ePrior = null; // last exception
3295 do { // callbacks may add callbacks :)
3296 $callbacks = $this->mTrxIdleCallbacks
;
3297 $this->mTrxIdleCallbacks
= array(); // recursion guard
3298 foreach ( $callbacks as $callback ) {
3300 list( $phpCallback ) = $callback;
3301 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3302 call_user_func( $phpCallback );
3303 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3304 } catch ( Exception
$e ) {
3306 MWExceptionHandler
::logException( $ePrior );
3311 } while ( count( $this->mTrxIdleCallbacks
) );
3313 if ( $e instanceof Exception
) {
3314 throw $e; // re-throw any last exception
3319 * Actually any "on transaction pre-commit" callbacks.
3323 protected function runOnTransactionPreCommitCallbacks() {
3324 $e = $ePrior = null; // last exception
3325 do { // callbacks may add callbacks :)
3326 $callbacks = $this->mTrxPreCommitCallbacks
;
3327 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3328 foreach ( $callbacks as $callback ) {
3330 list( $phpCallback ) = $callback;
3331 call_user_func( $phpCallback );
3332 } catch ( Exception
$e ) {
3334 MWExceptionHandler
::logException( $ePrior );
3339 } while ( count( $this->mTrxPreCommitCallbacks
) );
3341 if ( $e instanceof Exception
) {
3342 throw $e; // re-throw any last exception
3347 * Begin an atomic section of statements
3349 * If a transaction has been started already, just keep track of the given
3350 * section name to make sure the transaction is not committed pre-maturely.
3351 * This function can be used in layers (with sub-sections), so use a stack
3352 * to keep track of the different atomic sections. If there is no transaction,
3353 * start one implicitly.
3355 * The goal of this function is to create an atomic section of SQL queries
3356 * without having to start a new transaction if it already exists.
3358 * Atomic sections are more strict than transactions. With transactions,
3359 * attempting to begin a new transaction when one is already running results
3360 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3361 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3362 * and any database transactions cannot be began or committed until all atomic
3363 * levels are closed. There is no such thing as implicitly opening or closing
3364 * an atomic section.
3367 * @param string $fname
3370 final public function startAtomic( $fname = __METHOD__
) {
3371 if ( !$this->mTrxLevel
) {
3372 $this->begin( $fname );
3373 $this->mTrxAutomatic
= true;
3374 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3375 // in all changes being in one transaction to keep requests transactional.
3376 if ( !$this->getFlag( DBO_TRX
) ) {
3377 $this->mTrxAutomaticAtomic
= true;
3381 $this->mTrxAtomicLevels
[] = $fname;
3385 * Ends an atomic section of SQL statements
3387 * Ends the next section of atomic SQL statements and commits the transaction
3391 * @see DatabaseBase::startAtomic
3392 * @param string $fname
3395 final public function endAtomic( $fname = __METHOD__
) {
3396 if ( !$this->mTrxLevel
) {
3397 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3399 if ( !$this->mTrxAtomicLevels ||
3400 array_pop( $this->mTrxAtomicLevels
) !== $fname
3402 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3405 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3406 $this->commit( $fname, 'flush' );
3411 * Begin a transaction. If a transaction is already in progress,
3412 * that transaction will be committed before the new transaction is started.
3414 * Note that when the DBO_TRX flag is set (which is usually the case for web
3415 * requests, but not for maintenance scripts), any previous database query
3416 * will have started a transaction automatically.
3418 * Nesting of transactions is not supported. Attempts to nest transactions
3419 * will cause a warning, unless the current transaction was started
3420 * automatically because of the DBO_TRX flag.
3422 * @param string $fname
3425 final public function begin( $fname = __METHOD__
) {
3426 if ( $this->mTrxLevel
) { // implicit commit
3427 if ( $this->mTrxAtomicLevels
) {
3428 // If the current transaction was an automatic atomic one, then we definitely have
3429 // a problem. Same if there is any unclosed atomic level.
3430 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3431 throw new DBUnexpectedError(
3433 "Got explicit BEGIN while atomic sections $levels are still open."
3435 } elseif ( !$this->mTrxAutomatic
) {
3436 // We want to warn about inadvertently nested begin/commit pairs, but not about
3437 // auto-committing implicit transactions that were started by query() via DBO_TRX
3438 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3439 " performing implicit commit!";
3442 $this->getLogContext( array(
3443 'method' => __METHOD__
,
3448 // if the transaction was automatic and has done write operations
3449 if ( $this->mTrxDoneWrites
) {
3450 wfDebug( "$fname: Automatic transaction with writes in progress" .
3451 " (from {$this->mTrxFname}), performing implicit commit!\n"
3456 $this->runOnTransactionPreCommitCallbacks();
3457 $writeTime = $this->pendingWriteQueryDuration();
3458 $this->doCommit( $fname );
3459 if ( $this->mTrxDoneWrites
) {
3460 $this->mDoneWrites
= microtime( true );
3461 $this->getTransactionProfiler()->transactionWritingOut(
3462 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3464 $this->runOnTransactionIdleCallbacks();
3467 # Avoid fatals if close() was called
3468 $this->assertOpen();
3470 $this->doBegin( $fname );
3471 $this->mTrxTimestamp
= microtime( true );
3472 $this->mTrxFname
= $fname;
3473 $this->mTrxDoneWrites
= false;
3474 $this->mTrxAutomatic
= false;
3475 $this->mTrxAutomaticAtomic
= false;
3476 $this->mTrxAtomicLevels
= array();
3477 $this->mTrxIdleCallbacks
= array();
3478 $this->mTrxPreCommitCallbacks
= array();
3479 $this->mTrxShortId
= wfRandomString( 12 );
3480 $this->mTrxWriteDuration
= 0.0;
3481 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3482 // Get an estimate of the slave lag before then, treating estimate staleness
3483 // as lag itself just to be safe
3484 $status = $this->getApproximateLagStatus();
3485 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3489 * Issues the BEGIN command to the database server.
3491 * @see DatabaseBase::begin()
3492 * @param string $fname
3494 protected function doBegin( $fname ) {
3495 $this->query( 'BEGIN', $fname );
3496 $this->mTrxLevel
= 1;
3500 * Commits a transaction previously started using begin().
3501 * If no transaction is in progress, a warning is issued.
3503 * Nesting of transactions is not supported.
3505 * @param string $fname
3506 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3507 * explicitly committing implicit transactions, or calling commit when no
3508 * transaction is in progress. This will silently break any ongoing
3509 * explicit transaction. Only set the flush flag if you are sure that it
3510 * is safe to ignore these warnings in your context.
3511 * @throws DBUnexpectedError
3513 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3514 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3515 // There are still atomic sections open. This cannot be ignored
3516 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3517 throw new DBUnexpectedError(
3519 "Got COMMIT while atomic sections $levels are still open"
3523 if ( $flush === 'flush' ) {
3524 if ( !$this->mTrxLevel
) {
3525 return; // nothing to do
3526 } elseif ( !$this->mTrxAutomatic
) {
3527 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3530 if ( !$this->mTrxLevel
) {
3531 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3532 return; // nothing to do
3533 } elseif ( $this->mTrxAutomatic
) {
3534 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3538 # Avoid fatals if close() was called
3539 $this->assertOpen();
3541 $this->runOnTransactionPreCommitCallbacks();
3542 $writeTime = $this->pendingWriteQueryDuration();
3543 $this->doCommit( $fname );
3544 if ( $this->mTrxDoneWrites
) {
3545 $this->mDoneWrites
= microtime( true );
3546 $this->getTransactionProfiler()->transactionWritingOut(
3547 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3549 $this->runOnTransactionIdleCallbacks();
3553 * Issues the COMMIT command to the database server.
3555 * @see DatabaseBase::commit()
3556 * @param string $fname
3558 protected function doCommit( $fname ) {
3559 if ( $this->mTrxLevel
) {
3560 $this->query( 'COMMIT', $fname );
3561 $this->mTrxLevel
= 0;
3566 * Rollback a transaction previously started using begin().
3567 * If no transaction is in progress, a warning is issued.
3569 * No-op on non-transactional databases.
3571 * @param string $fname
3572 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3573 * calling rollback when no transaction is in progress. This will silently
3574 * break any ongoing explicit transaction. Only set the flush flag if you
3575 * are sure that it is safe to ignore these warnings in your context.
3576 * @throws DBUnexpectedError
3577 * @since 1.23 Added $flush parameter
3579 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3580 if ( $flush !== 'flush' ) {
3581 if ( !$this->mTrxLevel
) {
3582 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3583 return; // nothing to do
3584 } elseif ( $this->mTrxAutomatic
) {
3585 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3588 if ( !$this->mTrxLevel
) {
3589 return; // nothing to do
3590 } elseif ( !$this->mTrxAutomatic
) {
3591 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3595 # Avoid fatals if close() was called
3596 $this->assertOpen();
3598 $this->doRollback( $fname );
3599 $this->mTrxIdleCallbacks
= array(); // cancel
3600 $this->mTrxPreCommitCallbacks
= array(); // cancel
3601 $this->mTrxAtomicLevels
= array();
3602 if ( $this->mTrxDoneWrites
) {
3603 $this->getTransactionProfiler()->transactionWritingOut(
3604 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3609 * Issues the ROLLBACK command to the database server.
3611 * @see DatabaseBase::rollback()
3612 * @param string $fname
3614 protected function doRollback( $fname ) {
3615 if ( $this->mTrxLevel
) {
3616 $this->query( 'ROLLBACK', $fname, true );
3617 $this->mTrxLevel
= 0;
3622 * Creates a new table with structure copied from existing table
3623 * Note that unlike most database abstraction functions, this function does not
3624 * automatically append database prefix, because it works at a lower
3625 * abstraction level.
3626 * The table names passed to this function shall not be quoted (this
3627 * function calls addIdentifierQuotes when needed).
3629 * @param string $oldName Name of table whose structure should be copied
3630 * @param string $newName Name of table to be created
3631 * @param bool $temporary Whether the new table should be temporary
3632 * @param string $fname Calling function name
3633 * @throws MWException
3634 * @return bool True if operation was successful
3636 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3639 throw new MWException(
3640 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3644 * List all tables on the database
3646 * @param string $prefix Only show tables with this prefix, e.g. mw_
3647 * @param string $fname Calling function name
3648 * @throws MWException
3651 function listTables( $prefix = null, $fname = __METHOD__
) {
3652 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3656 * Reset the views process cache set by listViews()
3659 final public function clearViewsCache() {
3660 $this->allViews
= null;
3664 * Lists all the VIEWs in the database
3666 * For caching purposes the list of all views should be stored in
3667 * $this->allViews. The process cache can be cleared with clearViewsCache()
3669 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3670 * @param string $fname Name of calling function
3671 * @throws MWException
3675 public function listViews( $prefix = null, $fname = __METHOD__
) {
3676 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3680 * Differentiates between a TABLE and a VIEW
3682 * @param string $name Name of the database-structure to test.
3683 * @throws MWException
3687 public function isView( $name ) {
3688 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3692 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3693 * to the format used for inserting into timestamp fields in this DBMS.
3695 * The result is unquoted, and needs to be passed through addQuotes()
3696 * before it can be included in raw SQL.
3698 * @param string|int $ts
3702 public function timestamp( $ts = 0 ) {
3703 return wfTimestamp( TS_MW
, $ts );
3707 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3708 * to the format used for inserting into timestamp fields in this DBMS. If
3709 * NULL is input, it is passed through, allowing NULL values to be inserted
3710 * into timestamp fields.
3712 * The result is unquoted, and needs to be passed through addQuotes()
3713 * before it can be included in raw SQL.
3715 * @param string|int $ts
3719 public function timestampOrNull( $ts = null ) {
3720 if ( is_null( $ts ) ) {
3723 return $this->timestamp( $ts );
3728 * Take the result from a query, and wrap it in a ResultWrapper if
3729 * necessary. Boolean values are passed through as is, to indicate success
3730 * of write queries or failure.
3732 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3733 * resource, and it was necessary to call this function to convert it to
3734 * a wrapper. Nowadays, raw database objects are never exposed to external
3735 * callers, so this is unnecessary in external code.
3737 * @param bool|ResultWrapper|resource|object $result
3738 * @return bool|ResultWrapper
3740 protected function resultObject( $result ) {
3743 } elseif ( $result instanceof ResultWrapper
) {
3745 } elseif ( $result === true ) {
3746 // Successful write query
3749 return new ResultWrapper( $this, $result );
3754 * Ping the server and try to reconnect if it there is no connection
3756 * @return bool Success or failure
3758 public function ping() {
3759 # Stub. Not essential to override.
3764 * Get the slave lag when the current transaction started
3765 * or a general lag estimate if not transaction is active
3767 * This is useful when transactions might use snapshot isolation
3768 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3769 * is this lag plus transaction duration. If they don't, it is still
3770 * safe to be pessimistic. In AUTO-COMMIT mode, this still gives an
3771 * indication of the staleness of subsequent reads.
3773 * @return array ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3776 public function getSessionLagStatus() {
3777 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3781 * Get the slave lag when the current transaction started
3783 * This is useful when transactions might use snapshot isolation
3784 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3785 * is this lag plus transaction duration. If they don't, it is still
3786 * safe to be pessimistic. This returns null if there is no transaction.
3788 * @return array|null ('lag': seconds, 'since': UNIX timestamp of BEGIN)
3791 public function getTransactionLagStatus() {
3792 return $this->mTrxLevel
3793 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
3798 * Get a slave lag estimate for this server
3800 * @return array ('lag': seconds, 'since': UNIX timestamp of estimate)
3803 public function getApproximateLagStatus() {
3805 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3806 'since' => microtime( true )
3811 * Merge the result of getSessionLagStatus() for several DBs
3812 * using the most pessimistic values to estimate the lag of
3813 * any data derived from them in combination
3815 * This is information is useful for caching modules
3817 * @see WANObjectCache::set()
3818 * @see WANObjectCache::getWithSetCallback()
3820 * @param IDatabase $db1
3821 * @param IDatabase ...
3822 * @return array ('lag': highest lag, 'since': lowest estimate UNIX timestamp)
3825 public static function getCacheSetOptions( IDatabase
$db1 ) {
3826 $res = array( 'lag' => 0, 'since' => INF
);
3827 foreach ( func_get_args() as $db ) {
3828 /** @var IDatabase $db */
3829 $status = $db->getSessionLagStatus();
3830 $res['lag'] = max( $res['lag'], $status['lag'] );
3831 $res['since'] = min( $res['since'], $status['since'] );
3838 * Get slave lag. Currently supported only by MySQL.
3840 * Note that this function will generate a fatal error on many
3841 * installations. Most callers should use LoadBalancer::safeGetLag()
3844 * @return int Database replication lag in seconds
3846 public function getLag() {
3851 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3855 function maxListLen() {
3860 * Some DBMSs have a special format for inserting into blob fields, they
3861 * don't allow simple quoted strings to be inserted. To insert into such
3862 * a field, pass the data through this function before passing it to
3863 * DatabaseBase::insert().
3868 public function encodeBlob( $b ) {
3873 * Some DBMSs return a special placeholder object representing blob fields
3874 * in result objects. Pass the object through this function to return the
3877 * @param string|Blob $b
3880 public function decodeBlob( $b ) {
3881 if ( $b instanceof Blob
) {
3888 * Override database's default behavior. $options include:
3889 * 'connTimeout' : Set the connection timeout value in seconds.
3890 * May be useful for very long batch queries such as
3891 * full-wiki dumps, where a single query reads out over
3894 * @param array $options
3897 public function setSessionOptions( array $options ) {
3901 * Read and execute SQL commands from a file.
3903 * Returns true on success, error string or exception on failure (depending
3904 * on object's error ignore settings).
3906 * @param string $filename File name to open
3907 * @param bool|callable $lineCallback Optional function called before reading each line
3908 * @param bool|callable $resultCallback Optional function called for each MySQL result
3909 * @param bool|string $fname Calling function name or false if name should be
3910 * generated dynamically using $filename
3911 * @param bool|callable $inputCallback Optional function called for each
3912 * complete line sent
3913 * @throws Exception|MWException
3914 * @return bool|string
3916 public function sourceFile(
3917 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3919 MediaWiki\
suppressWarnings();
3920 $fp = fopen( $filename, 'r' );
3921 MediaWiki\restoreWarnings
();
3923 if ( false === $fp ) {
3924 throw new MWException( "Could not open \"{$filename}\".\n" );
3928 $fname = __METHOD__
. "( $filename )";
3932 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3933 } catch ( Exception
$e ) {
3944 * Get the full path of a patch file. Originally based on archive()
3945 * from updaters.inc. Keep in mind this always returns a patch, as
3946 * it fails back to MySQL if no DB-specific patch can be found
3948 * @param string $patch The name of the patch, like patch-something.sql
3949 * @return string Full path to patch file
3951 public function patchPath( $patch ) {
3954 $dbType = $this->getType();
3955 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3956 return "$IP/maintenance/$dbType/archives/$patch";
3958 return "$IP/maintenance/archives/$patch";
3963 * Set variables to be used in sourceFile/sourceStream, in preference to the
3964 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3965 * all. If it's set to false, $GLOBALS will be used.
3967 * @param bool|array $vars Mapping variable name to value.
3969 public function setSchemaVars( $vars ) {
3970 $this->mSchemaVars
= $vars;
3974 * Read and execute commands from an open file handle.
3976 * Returns true on success, error string or exception on failure (depending
3977 * on object's error ignore settings).
3979 * @param resource $fp File handle
3980 * @param bool|callable $lineCallback Optional function called before reading each query
3981 * @param bool|callable $resultCallback Optional function called for each MySQL result
3982 * @param string $fname Calling function name
3983 * @param bool|callable $inputCallback Optional function called for each complete query sent
3984 * @return bool|string
3986 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3987 $fname = __METHOD__
, $inputCallback = false
3991 while ( !feof( $fp ) ) {
3992 if ( $lineCallback ) {
3993 call_user_func( $lineCallback );
3996 $line = trim( fgets( $fp ) );
3998 if ( $line == '' ) {
4002 if ( '-' == $line[0] && '-' == $line[1] ) {
4010 $done = $this->streamStatementEnd( $cmd, $line );
4014 if ( $done ||
feof( $fp ) ) {
4015 $cmd = $this->replaceVars( $cmd );
4017 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4018 $res = $this->query( $cmd, $fname );
4020 if ( $resultCallback ) {
4021 call_user_func( $resultCallback, $res, $this );
4024 if ( false === $res ) {
4025 $err = $this->lastError();
4027 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4038 * Called by sourceStream() to check if we've reached a statement end
4040 * @param string $sql SQL assembled so far
4041 * @param string $newLine New line about to be added to $sql
4042 * @return bool Whether $newLine contains end of the statement
4044 public function streamStatementEnd( &$sql, &$newLine ) {
4045 if ( $this->delimiter
) {
4047 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4048 if ( $newLine != $prev ) {
4057 * Database independent variable replacement. Replaces a set of variables
4058 * in an SQL statement with their contents as given by $this->getSchemaVars().
4060 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4062 * - '{$var}' should be used for text and is passed through the database's
4064 * - `{$var}` should be used for identifiers (e.g. table and database names).
4065 * It is passed through the database's addIdentifierQuotes method which
4066 * can be overridden if the database uses something other than backticks.
4067 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4068 * database's tableName method.
4069 * - / *i* / passes the name that follows through the database's indexName method.
4070 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4071 * its use should be avoided. In 1.24 and older, string encoding was applied.
4073 * @param string $ins SQL statement to replace variables in
4074 * @return string The new SQL statement with variables replaced
4076 protected function replaceVars( $ins ) {
4078 $vars = $this->getSchemaVars();
4079 return preg_replace_callback(
4081 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4082 \'\{\$ (\w+) }\' | # 3. addQuotes
4083 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4084 /\*\$ (\w+) \*/ # 5. leave unencoded
4086 function ( $m ) use ( $that, $vars ) {
4087 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4088 // check for both nonexistent keys *and* the empty string.
4089 if ( isset( $m[1] ) && $m[1] !== '' ) {
4090 if ( $m[1] === 'i' ) {
4091 return $that->indexName( $m[2] );
4093 return $that->tableName( $m[2] );
4095 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4096 return $that->addQuotes( $vars[$m[3]] );
4097 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4098 return $that->addIdentifierQuotes( $vars[$m[4]] );
4099 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4100 return $vars[$m[5]];
4110 * Get schema variables. If none have been set via setSchemaVars(), then
4111 * use some defaults from the current object.
4115 protected function getSchemaVars() {
4116 if ( $this->mSchemaVars
) {
4117 return $this->mSchemaVars
;
4119 return $this->getDefaultSchemaVars();
4124 * Get schema variables to use if none have been set via setSchemaVars().
4126 * Override this in derived classes to provide variables for tables.sql
4127 * and SQL patch files.
4131 protected function getDefaultSchemaVars() {
4136 * Check to see if a named lock is available (non-blocking)
4138 * @param string $lockName Name of lock to poll
4139 * @param string $method Name of method calling us
4143 public function lockIsFree( $lockName, $method ) {
4148 * Acquire a named lock
4150 * Named locks are not related to transactions
4152 * @param string $lockName Name of lock to aquire
4153 * @param string $method Name of method calling us
4154 * @param int $timeout
4157 public function lock( $lockName, $method, $timeout = 5 ) {
4164 * Named locks are not related to transactions
4166 * @param string $lockName Name of lock to release
4167 * @param string $method Name of method calling us
4169 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4170 * by this thread (in which case the lock is not released), and NULL if the named
4171 * lock did not exist
4173 public function unlock( $lockName, $method ) {
4178 * Check to see if a named lock used by lock() use blocking queues
4183 public function namedLocksEnqueue() {
4188 * Lock specific tables
4190 * @param array $read Array of tables to lock for read access
4191 * @param array $write Array of tables to lock for write access
4192 * @param string $method Name of caller
4193 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4196 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4201 * Unlock specific tables
4203 * @param string $method The caller
4206 public function unlockTables( $method ) {
4212 * @param string $tableName
4213 * @param string $fName
4214 * @return bool|ResultWrapper
4217 public function dropTable( $tableName, $fName = __METHOD__
) {
4218 if ( !$this->tableExists( $tableName, $fName ) ) {
4221 $sql = "DROP TABLE " . $this->tableName( $tableName );
4222 if ( $this->cascadingDeletes() ) {
4226 return $this->query( $sql, $fName );
4230 * Get search engine class. All subclasses of this need to implement this
4231 * if they wish to use searching.
4235 public function getSearchEngine() {
4236 return 'SearchEngineDummy';
4240 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4241 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4242 * because "i" sorts after all numbers.
4246 public function getInfinity() {
4251 * Encode an expiry time into the DBMS dependent format
4253 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4256 public function encodeExpiry( $expiry ) {
4257 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4258 ?
$this->getInfinity()
4259 : $this->timestamp( $expiry );
4263 * Decode an expiry time into a DBMS independent format
4265 * @param string $expiry DB timestamp field value for expiry
4266 * @param int $format TS_* constant, defaults to TS_MW
4269 public function decodeExpiry( $expiry, $format = TS_MW
) {
4270 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4272 : wfTimestamp( $format, $expiry );
4276 * Allow or deny "big selects" for this session only. This is done by setting
4277 * the sql_big_selects session variable.
4279 * This is a MySQL-specific feature.
4281 * @param bool|string $value True for allow, false for deny, or "default" to
4282 * restore the initial value
4284 public function setBigSelects( $value = true ) {
4288 public function isReadOnly() {
4289 return ( $this->getReadOnlyReason() !== false );
4293 * @return string|bool Reason this DB is read-only or false if it is not
4295 protected function getReadOnlyReason() {
4296 $reason = $this->getLBInfo( 'readOnlyReason' );
4298 return is_string( $reason ) ?
$reason : false;
4305 public function __toString() {
4306 return (string)$this->mConn
;
4310 * Run a few simple sanity checks
4312 public function __destruct() {
4313 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4314 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4316 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4318 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4319 $callers[] = $callbackInfo[1];
4321 $callers = implode( ', ', $callers );
4322 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4330 abstract class Database
extends DatabaseBase
{
4331 // B/C until nothing type hints for DatabaseBase
4332 // @TODO: finish renaming DatabaseBase => Database