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 resource Database connection */
49 protected $mConn = null;
50 protected $mOpened = false;
52 /** @var callable[] */
53 protected $mTrxIdleCallbacks = array();
54 /** @var callable[] */
55 protected $mTrxPreCommitCallbacks = array();
57 protected $mTablePrefix;
61 protected $mLBInfo = array();
62 protected $mDefaultBigSelects = null;
63 protected $mSchemaVars = false;
65 protected $mSessionVars = array();
67 protected $preparedArgs;
69 protected $htmlErrors;
71 protected $delimiter = ';';
74 * Either 1 if a transaction is active or 0 otherwise.
75 * The other Trx fields may not be meaningfull if this is 0.
79 protected $mTrxLevel = 0;
82 * Either a short hexidecimal string if a transaction is active or ""
85 * @see DatabaseBase::mTrxLevel
87 protected $mTrxShortId = '';
90 * The UNIX time that the transaction started. Callers can assume that if
91 * snapshot isolation is used, then the data is *at least* up to date to that
92 * point (possibly more up-to-date since the first SELECT defines the snapshot).
95 * @see DatabaseBase::mTrxLevel
97 private $mTrxTimestamp = null;
100 * Remembers the function name given for starting the most recent transaction via begin().
101 * Used to provide additional context for error reporting.
104 * @see DatabaseBase::mTrxLevel
106 private $mTrxFname = null;
109 * Record if possible write queries were done in the last transaction started
112 * @see DatabaseBase::mTrxLevel
114 private $mTrxDoneWrites = false;
117 * Record if the current transaction was started implicitly due to DBO_TRX being set.
120 * @see DatabaseBase::mTrxLevel
122 private $mTrxAutomatic = false;
125 * Array of levels of atomicity within transactions
129 private $mTrxAtomicLevels = array();
132 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
136 private $mTrxAutomaticAtomic = false;
139 * Track the seconds spent in write queries for the current transaction
143 private $mTrxWriteDuration = 0.0;
147 * @var resource File handle for upgrade
149 protected $fileHandle = null;
153 * @var string[] Process cache of VIEWs names in the database
155 protected $allViews = null;
157 /** @var TransactionProfiler */
158 protected $trxProfiler;
161 * A string describing the current software version, and possibly
162 * other details in a user-friendly way. Will be listed on Special:Version, etc.
163 * Use getServerVersion() to get machine-friendly information.
165 * @return string Version information from the database server
167 public function getServerInfo() {
168 return $this->getServerVersion();
172 * @return string Command delimiter used by this database engine
174 public function getDelimiter() {
175 return $this->delimiter
;
179 * Boolean, controls output of large amounts of debug information.
180 * @param bool|null $debug
181 * - true to enable debugging
182 * - false to disable debugging
183 * - omitted or null to do nothing
185 * @return bool|null Previous value of the flag
187 public function debug( $debug = null ) {
188 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
192 * Turns buffering of SQL result sets on (true) or off (false). Default is
195 * Unbuffered queries are very troublesome in MySQL:
197 * - If another query is executed while the first query is being read
198 * out, the first query is killed. This means you can't call normal
199 * MediaWiki functions while you are reading an unbuffered query result
200 * from a normal wfGetDB() connection.
202 * - Unbuffered queries cause the MySQL server to use large amounts of
203 * memory and to hold broad locks which block other queries.
205 * If you want to limit client-side memory, it's almost always better to
206 * split up queries into batches using a LIMIT clause than to switch off
209 * @param null|bool $buffer
210 * @return null|bool The previous value of the flag
212 public function bufferResults( $buffer = null ) {
213 if ( is_null( $buffer ) ) {
214 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
216 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
221 * Turns on (false) or off (true) the automatic generation and sending
222 * of a "we're sorry, but there has been a database error" page on
223 * database errors. Default is on (false). When turned off, the
224 * code should use lastErrno() and lastError() to handle the
225 * situation as appropriate.
227 * Do not use this function outside of the Database classes.
229 * @param null|bool $ignoreErrors
230 * @return bool The previous value of the flag.
232 protected function ignoreErrors( $ignoreErrors = null ) {
233 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
237 * Gets the current transaction level.
239 * Historically, transactions were allowed to be "nested". This is no
240 * longer supported, so this function really only returns a boolean.
242 * @return int The previous value
244 public function trxLevel() {
245 return $this->mTrxLevel
;
249 * Get the UNIX timestamp of the time that the transaction was established
251 * This can be used to reason about the staleness of SELECT data
252 * in REPEATABLE-READ transaction isolation level.
254 * @return float|null Returns null if there is not active transaction
257 public function trxTimestamp() {
258 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
262 * Get/set the table prefix.
263 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
264 * @return string The previous table prefix.
266 public function tablePrefix( $prefix = null ) {
267 return wfSetVar( $this->mTablePrefix
, $prefix );
271 * Get/set the db schema.
272 * @param string $schema The database schema to set, or omitted to leave it unchanged.
273 * @return string The previous db schema.
275 public function dbSchema( $schema = null ) {
276 return wfSetVar( $this->mSchema
, $schema );
280 * Set the filehandle to copy write statements to.
282 * @param resource $fh File handle
284 public function setFileHandle( $fh ) {
285 $this->fileHandle
= $fh;
289 * Get properties passed down from the server info array of the load
292 * @param string $name The entry of the info array to get, or null to get the
295 * @return array|mixed|null
297 public function getLBInfo( $name = null ) {
298 if ( is_null( $name ) ) {
299 return $this->mLBInfo
;
301 if ( array_key_exists( $name, $this->mLBInfo
) ) {
302 return $this->mLBInfo
[$name];
310 * Set the LB info array, or a member of it. If called with one parameter,
311 * the LB info array is set to that parameter. If it is called with two
312 * parameters, the member with the given name is set to the given value.
314 * @param string $name
315 * @param array $value
317 public function setLBInfo( $name, $value = null ) {
318 if ( is_null( $value ) ) {
319 $this->mLBInfo
= $name;
321 $this->mLBInfo
[$name] = $value;
326 * @return TransactionProfiler
328 protected function getTransactionProfiler() {
329 return $this->trxProfiler
331 : Profiler
::instance()->getTransactionProfiler();
335 * Returns true if this database supports (and uses) cascading deletes
339 public function cascadingDeletes() {
344 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
348 public function cleanupTriggers() {
353 * Returns true if this database is strict about what can be put into an IP field.
354 * Specifically, it uses a NULL value instead of an empty string.
358 public function strictIPs() {
363 * Returns true if this database uses timestamps rather than integers
367 public function realTimestamps() {
372 * Returns true if this database does an implicit sort when doing GROUP BY
376 public function implicitGroupby() {
381 * Returns true if this database does an implicit order by when the column has an index
382 * For example: SELECT page_title FROM page LIMIT 1
386 public function implicitOrderby() {
391 * Returns true if this database can do a native search on IP columns
392 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
396 public function searchableIPs() {
401 * Returns true if this database can use functional indexes
405 public function functionalIndexes() {
410 * Return the last query that went through DatabaseBase::query()
413 public function lastQuery() {
414 return $this->mLastQuery
;
418 * Returns true if the connection may have been used for write queries.
419 * Should return true if unsure.
423 public function doneWrites() {
424 return (bool)$this->mDoneWrites
;
428 * Returns the last time the connection may have been used for write queries.
429 * Should return a timestamp if unsure.
431 * @return int|float UNIX timestamp or false
434 public function lastDoneWrites() {
435 return $this->mDoneWrites ?
: false;
439 * Returns true if there is a transaction open with possible write
440 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
444 public function writesOrCallbacksPending() {
445 return $this->mTrxLevel
&& (
446 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
451 * Get the time spend running write queries for this
453 * High times could be due to scanning, updates, locking, and such
455 * @return float|bool Returns false if not transaction is active
458 public function pendingWriteQueryDuration() {
459 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
463 * Is a connection to the database open?
466 public function isOpen() {
467 return $this->mOpened
;
471 * Set a flag for this connection
473 * @param int $flag DBO_* constants from Defines.php:
474 * - DBO_DEBUG: output some debug info (same as debug())
475 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
476 * - DBO_TRX: automatically start transactions
477 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
478 * and removes it in command line mode
479 * - DBO_PERSISTENT: use persistant database connection
481 public function setFlag( $flag ) {
482 global $wgDebugDBTransactions;
483 $this->mFlags |
= $flag;
484 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
485 wfDebug( "Implicit transactions are now enabled.\n" );
490 * Clear a flag for this connection
492 * @param int $flag DBO_* constants from Defines.php:
493 * - DBO_DEBUG: output some debug info (same as debug())
494 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
495 * - DBO_TRX: automatically start transactions
496 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
497 * and removes it in command line mode
498 * - DBO_PERSISTENT: use persistant database connection
500 public function clearFlag( $flag ) {
501 global $wgDebugDBTransactions;
502 $this->mFlags
&= ~
$flag;
503 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
504 wfDebug( "Implicit transactions are now disabled.\n" );
509 * Returns a boolean whether the flag $flag is set for this connection
511 * @param int $flag DBO_* constants from Defines.php:
512 * - DBO_DEBUG: output some debug info (same as debug())
513 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
514 * - DBO_TRX: automatically start transactions
515 * - DBO_PERSISTENT: use persistant database connection
518 public function getFlag( $flag ) {
519 return !!( $this->mFlags
& $flag );
523 * General read-only accessor
525 * @param string $name
528 public function getProperty( $name ) {
535 public function getWikiID() {
536 if ( $this->mTablePrefix
) {
537 return "{$this->mDBname}-{$this->mTablePrefix}";
539 return $this->mDBname
;
544 * Return a path to the DBMS-specific SQL file if it exists,
545 * otherwise default SQL file
547 * @param string $filename
550 private function getSqlFilePath( $filename ) {
552 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
553 if ( file_exists( $dbmsSpecificFilePath ) ) {
554 return $dbmsSpecificFilePath;
556 return "$IP/maintenance/$filename";
561 * Return a path to the DBMS-specific schema file,
562 * otherwise default to tables.sql
566 public function getSchemaPath() {
567 return $this->getSqlFilePath( 'tables.sql' );
571 * Return a path to the DBMS-specific update key file,
572 * otherwise default to update-keys.sql
576 public function getUpdateKeysPath() {
577 return $this->getSqlFilePath( 'update-keys.sql' );
581 * Get information about an index into an object
582 * @param string $table Table name
583 * @param string $index Index name
584 * @param string $fname Calling function name
585 * @return mixed Database-specific index description class or false if the index does not exist
587 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
590 * Wrapper for addslashes()
592 * @param string $s String to be slashed.
593 * @return string Slashed string.
595 abstract function strencode( $s );
600 * FIXME: It is possible to construct a Database object with no associated
601 * connection object, by specifying no parameters to __construct(). This
602 * feature is deprecated and should be removed.
604 * DatabaseBase subclasses should not be constructed directly in external
605 * code. DatabaseBase::factory() should be used instead.
607 * @param array $params Parameters passed from DatabaseBase::factory()
609 function __construct( array $params ) {
610 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
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
;
625 if ( $wgDebugDBTransactions ) {
626 wfDebug( "Implicit transaction open disabled.\n" );
629 $this->mFlags |
= DBO_TRX
;
630 if ( $wgDebugDBTransactions ) {
631 wfDebug( "Implicit transaction open enabled.\n" );
636 $this->mSessionVars
= $params['variables'];
638 /** Get the default table prefix*/
639 if ( $tablePrefix === 'get from global' ) {
640 $this->mTablePrefix
= $wgDBprefix;
642 $this->mTablePrefix
= $tablePrefix;
645 /** Get the database schema*/
646 if ( $schema === 'get from global' ) {
647 $this->mSchema
= $wgDBmwschema;
649 $this->mSchema
= $schema;
652 $this->mForeign
= $foreign;
654 if ( isset( $params['trxProfiler'] ) ) {
655 $this->trxProfiler
= $params['trxProfiler']; // override
659 $this->open( $server, $user, $password, $dbName );
664 * Called by serialize. Throw an exception when DB connection is serialized.
665 * This causes problems on some database engines because the connection is
666 * not restored on unserialize.
668 public function __sleep() {
669 throw new MWException( 'Database serialization may cause problems, since ' .
670 'the connection is not restored on wakeup.' );
674 * Given a DB type, construct the name of the appropriate child class of
675 * DatabaseBase. This is designed to replace all of the manual stuff like:
676 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
677 * as well as validate against the canonical list of DB types we have
679 * This factory function is mostly useful for when you need to connect to a
680 * database other than the MediaWiki default (such as for external auth,
681 * an extension, et cetera). Do not use this to connect to the MediaWiki
682 * database. Example uses in core:
683 * @see LoadBalancer::reallyOpenConnection()
684 * @see ForeignDBRepo::getMasterDB()
685 * @see WebInstallerDBConnect::execute()
689 * @param string $dbType A possible DB type
690 * @param array $p An array of options to pass to the constructor.
691 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
692 * @throws MWException If the database driver or extension cannot be found
693 * @return DatabaseBase|null DatabaseBase subclass or null
695 final public static function factory( $dbType, $p = array() ) {
696 $canonicalDBTypes = array(
697 'mysql' => array( 'mysqli', 'mysql' ),
698 'postgres' => array(),
705 $dbType = strtolower( $dbType );
706 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
707 $possibleDrivers = $canonicalDBTypes[$dbType];
708 if ( !empty( $p['driver'] ) ) {
709 if ( in_array( $p['driver'], $possibleDrivers ) ) {
710 $driver = $p['driver'];
712 throw new MWException( __METHOD__
.
713 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
716 foreach ( $possibleDrivers as $posDriver ) {
717 if ( extension_loaded( $posDriver ) ) {
718 $driver = $posDriver;
726 if ( $driver === false ) {
727 throw new MWException( __METHOD__
.
728 " no viable database extension found for type '$dbType'" );
731 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
732 // and everything else doesn't use a schema (e.g. null)
733 // Although postgres and oracle support schemas, we don't use them (yet)
734 // to maintain backwards compatibility
735 $defaultSchemas = array(
736 'mssql' => 'get from global',
739 $class = 'Database' . ucfirst( $driver );
740 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
741 // Resolve some defaults for b/c
742 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
743 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
744 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
745 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
746 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
747 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
748 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
749 if ( !isset( $p['schema'] ) ) {
750 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
752 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
754 return new $class( $p );
760 protected function installErrorHandler() {
761 $this->mPHPError
= false;
762 $this->htmlErrors
= ini_set( 'html_errors', '0' );
763 set_error_handler( array( $this, 'connectionErrorHandler' ) );
767 * @return bool|string
769 protected function restoreErrorHandler() {
770 restore_error_handler();
771 if ( $this->htmlErrors
!== false ) {
772 ini_set( 'html_errors', $this->htmlErrors
);
774 if ( $this->mPHPError
) {
775 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
776 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
786 * @param string $errstr
788 public function connectionErrorHandler( $errno, $errstr ) {
789 $this->mPHPError
= $errstr;
793 * Create a log context to pass to wfLogDBError or other logging functions.
795 * @param array $extras Additional data to add to context
798 protected function getLogContext( array $extras = array() ) {
801 'db_server' => $this->mServer
,
802 'db_name' => $this->mDBname
,
803 'db_user' => $this->mUser
,
810 * Closes a database connection.
811 * if it is open : commits any open transactions
813 * @throws MWException
814 * @return bool Operation success. true if already closed.
816 public function close() {
817 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
818 throw new MWException( "Transaction idle callbacks still pending." );
820 if ( $this->mConn
) {
821 if ( $this->trxLevel() ) {
822 if ( !$this->mTrxAutomatic
) {
823 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
824 " performing implicit commit before closing connection!" );
827 $this->commit( __METHOD__
, 'flush' );
830 $closed = $this->closeConnection();
831 $this->mConn
= false;
835 $this->mOpened
= false;
841 * Make sure isOpen() returns true as a sanity check
843 * @throws DBUnexpectedError
845 protected function assertOpen() {
846 if ( !$this->isOpen() ) {
847 throw new DBUnexpectedError( $this, "DB connection was already closed." );
852 * Closes underlying database connection
854 * @return bool Whether connection was closed successfully
856 abstract protected function closeConnection();
859 * @param string $error Fallback error message, used if none is given by DB
860 * @throws DBConnectionError
862 function reportConnectionError( $error = 'Unknown error' ) {
863 $myError = $this->lastError();
869 throw new DBConnectionError( $this, $error );
873 * The DBMS-dependent part of query()
875 * @param string $sql SQL query.
876 * @return ResultWrapper|bool Result object to feed to fetchObject,
877 * fetchRow, ...; or false on failure
879 abstract protected function doQuery( $sql );
882 * Determine whether a query writes to the DB.
883 * Should return true if unsure.
888 protected function isWriteQuery( $sql ) {
889 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
893 * Determine whether a SQL statement is sensitive to isolation level.
894 * A SQL statement is considered transactable if its result could vary
895 * depending on the transaction isolation level. Operational commands
896 * such as 'SET' and 'SHOW' are not considered to be transactable.
901 protected function isTransactableQuery( $sql ) {
902 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
903 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
907 * Run an SQL query and return the result. Normally throws a DBQueryError
908 * on failure. If errors are ignored, returns false instead.
910 * In new code, the query wrappers select(), insert(), update(), delete(),
911 * etc. should be used where possible, since they give much better DBMS
912 * independence and automatically quote or validate user input in a variety
913 * of contexts. This function is generally only useful for queries which are
914 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
917 * However, the query wrappers themselves should call this function.
919 * @param string $sql SQL query
920 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
921 * comment (you can use __METHOD__ or add some extra info)
922 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
923 * maybe best to catch the exception instead?
924 * @throws MWException
925 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
926 * for a successful read query, or false on failure if $tempIgnore set
928 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
929 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
931 $this->mLastQuery
= $sql;
933 $isWriteQuery = $this->isWriteQuery( $sql );
934 if ( $isWriteQuery ) {
935 if ( !$this->mDoneWrites
) {
936 wfDebug( __METHOD__
. ': Writes done: ' .
937 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
939 # Set a flag indicating that writes have been done
940 $this->mDoneWrites
= microtime( true );
943 # Add a comment for easy SHOW PROCESSLIST interpretation
944 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
945 $userName = $wgUser->getName();
946 if ( mb_strlen( $userName ) > 15 ) {
947 $userName = mb_substr( $userName, 0, 15 ) . '...';
949 $userName = str_replace( '/', '', $userName );
954 // Add trace comment to the begin of the sql string, right after the operator.
955 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
956 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
958 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
959 if ( $wgDebugDBTransactions ) {
960 wfDebug( "Implicit transaction start.\n" );
962 $this->begin( __METHOD__
. " ($fname)" );
963 $this->mTrxAutomatic
= true;
966 # Keep track of whether the transaction has write queries pending
967 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
968 $this->mTrxDoneWrites
= true;
969 $this->getTransactionProfiler()->transactionWritingIn(
970 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
973 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
974 # generalizeSQL will probably cut down the query to reasonable
975 # logging size most of the time. The substr is really just a sanity check.
977 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
978 $totalProf = 'DatabaseBase::query-master';
980 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
981 $totalProf = 'DatabaseBase::query';
983 # Include query transaction state
984 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
986 $profiler = Profiler
::instance();
987 if ( !$profiler instanceof ProfilerStub
) {
988 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
989 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
992 if ( $this->debug() ) {
996 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
998 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1000 $master = $isMaster ?
'master' : 'slave';
1001 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1004 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1006 # Avoid fatals if close() was called
1007 $this->assertOpen();
1009 # Do the query and handle errors
1010 $startTime = microtime( true );
1011 $ret = $this->doQuery( $commentedSql );
1012 $queryRuntime = microtime( true ) - $startTime;
1013 # Log the query time and feed it into the DB trx profiler
1014 $this->getTransactionProfiler()->recordQueryCompletion(
1015 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1017 MWDebug
::queryTime( $queryId );
1019 # Try reconnecting if the connection was lost
1020 if ( false === $ret && $this->wasErrorReissuable() ) {
1021 # Transaction is gone, like it or not
1022 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1023 $this->mTrxLevel
= 0;
1024 $this->mTrxIdleCallbacks
= array(); // bug 65263
1025 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1026 wfDebug( "Connection lost, reconnecting...\n" );
1027 # Stash the last error values since ping() might clear them
1028 $lastError = $this->lastError();
1029 $lastErrno = $this->lastErrno();
1030 if ( $this->ping() ) {
1031 wfDebug( "Reconnected\n" );
1032 $server = $this->getServer();
1033 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1034 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1037 # Leave $ret as false and let an error be reported.
1038 # Callers may catch the exception and continue to use the DB.
1039 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1041 # Should be safe to silently retry (no trx and thus no callbacks)
1042 $startTime = microtime( true );
1043 $ret = $this->doQuery( $commentedSql );
1044 $queryRuntime = microtime( true ) - $startTime;
1045 # Log the query time and feed it into the DB trx profiler
1046 $this->getTransactionProfiler()->recordQueryCompletion(
1047 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1050 wfDebug( "Failed\n" );
1054 if ( false === $ret ) {
1055 $this->reportQueryError(
1056 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1059 $res = $this->resultObject( $ret );
1061 // Destroy profile sections in the opposite order to their creation
1062 ScopedCallback
::consume( $queryProfSection );
1063 ScopedCallback
::consume( $totalProfSection );
1065 if ( $isWriteQuery && $this->mTrxLevel
) {
1066 $this->mTrxWriteDuration +
= $queryRuntime;
1073 * Report a query error. Log the error, and if neither the object ignore
1074 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1076 * @param string $error
1078 * @param string $sql
1079 * @param string $fname
1080 * @param bool $tempIgnore
1081 * @throws DBQueryError
1083 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1084 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1085 wfDebug( "SQL ERROR (ignored): $error\n" );
1087 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1089 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1090 $this->getLogContext( array(
1091 'method' => __METHOD__
,
1094 'sql1line' => $sql1line,
1098 wfDebug( "SQL ERROR: " . $error . "\n" );
1099 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1104 * Intended to be compatible with the PEAR::DB wrapper functions.
1105 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1107 * ? = scalar value, quoted as necessary
1108 * ! = raw SQL bit (a function for instance)
1109 * & = filename; reads the file and inserts as a blob
1110 * (we don't use this though...)
1112 * @param string $sql
1113 * @param string $func
1117 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1118 /* MySQL doesn't support prepared statements (yet), so just
1119 * pack up the query for reference. We'll manually replace
1122 return array( 'query' => $sql, 'func' => $func );
1126 * Free a prepared query, generated by prepare().
1127 * @param string $prepared
1129 protected function freePrepared( $prepared ) {
1130 /* No-op by default */
1134 * Execute a prepared query with the various arguments
1135 * @param string $prepared The prepared sql
1136 * @param mixed $args Either an array here, or put scalars as varargs
1138 * @return ResultWrapper
1140 public function execute( $prepared, $args = null ) {
1141 if ( !is_array( $args ) ) {
1143 $args = func_get_args();
1144 array_shift( $args );
1147 $sql = $this->fillPrepared( $prepared['query'], $args );
1149 return $this->query( $sql, $prepared['func'] );
1153 * For faking prepared SQL statements on DBs that don't support it directly.
1155 * @param string $preparedQuery A 'preparable' SQL statement
1156 * @param array $args Array of Arguments to fill it with
1157 * @return string Executable SQL
1159 public function fillPrepared( $preparedQuery, $args ) {
1161 $this->preparedArgs
=& $args;
1163 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1164 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1168 * preg_callback func for fillPrepared()
1169 * The arguments should be in $this->preparedArgs and must not be touched
1170 * while we're doing this.
1172 * @param array $matches
1173 * @throws DBUnexpectedError
1176 protected function fillPreparedArg( $matches ) {
1177 switch ( $matches[1] ) {
1186 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1188 switch ( $matches[1] ) {
1190 return $this->addQuotes( $arg );
1194 # return $this->addQuotes( file_get_contents( $arg ) );
1195 throw new DBUnexpectedError(
1197 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1200 throw new DBUnexpectedError(
1202 'Received invalid match. This should never happen!'
1208 * Free a result object returned by query() or select(). It's usually not
1209 * necessary to call this, just use unset() or let the variable holding
1210 * the result object go out of scope.
1212 * @param mixed $res A SQL result
1214 public function freeResult( $res ) {
1218 * A SELECT wrapper which returns a single field from a single result row.
1220 * Usually throws a DBQueryError on failure. If errors are explicitly
1221 * ignored, returns false on failure.
1223 * If no result rows are returned from the query, false is returned.
1225 * @param string|array $table Table name. See DatabaseBase::select() for details.
1226 * @param string $var The field name to select. This must be a valid SQL
1227 * fragment: do not use unvalidated user input.
1228 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1229 * @param string $fname The function name of the caller.
1230 * @param string|array $options The query options. See DatabaseBase::select() for details.
1232 * @return bool|mixed The value from the field, or false on failure.
1233 * @throws DBUnexpectedError
1235 public function selectField(
1236 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1238 if ( $var === '*' ) { // sanity
1239 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1242 if ( !is_array( $options ) ) {
1243 $options = array( $options );
1246 $options['LIMIT'] = 1;
1248 $res = $this->select( $table, $var, $cond, $fname, $options );
1249 if ( $res === false ||
!$this->numRows( $res ) ) {
1253 $row = $this->fetchRow( $res );
1255 if ( $row !== false ) {
1256 return reset( $row );
1263 * A SELECT wrapper which returns a list of single field values from result rows.
1265 * Usually throws a DBQueryError on failure. If errors are explicitly
1266 * ignored, returns false on failure.
1268 * If no result rows are returned from the query, false is returned.
1270 * @param string|array $table Table name. See DatabaseBase::select() for details.
1271 * @param string $var The field name to select. This must be a valid SQL
1272 * fragment: do not use unvalidated user input.
1273 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1274 * @param string $fname The function name of the caller.
1275 * @param string|array $options The query options. See DatabaseBase::select() for details.
1277 * @return bool|array The values from the field, or false on failure
1278 * @throws DBUnexpectedError
1281 public function selectFieldValues(
1282 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1284 if ( $var === '*' ) { // sanity
1285 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1288 if ( !is_array( $options ) ) {
1289 $options = array( $options );
1292 $res = $this->select( $table, $var, $cond, $fname, $options );
1293 if ( $res === false ) {
1298 foreach ( $res as $row ) {
1299 $values[] = $row->$var;
1306 * Returns an optional USE INDEX clause to go after the table, and a
1307 * string to go at the end of the query.
1309 * @param array $options Associative array of options to be turned into
1310 * an SQL query, valid keys are listed in the function.
1312 * @see DatabaseBase::select()
1314 public function makeSelectOptions( $options ) {
1315 $preLimitTail = $postLimitTail = '';
1318 $noKeyOptions = array();
1320 foreach ( $options as $key => $option ) {
1321 if ( is_numeric( $key ) ) {
1322 $noKeyOptions[$option] = true;
1326 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1328 $preLimitTail .= $this->makeOrderBy( $options );
1330 // if (isset($options['LIMIT'])) {
1331 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1332 // isset($options['OFFSET']) ? $options['OFFSET']
1336 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1337 $postLimitTail .= ' FOR UPDATE';
1340 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1341 $postLimitTail .= ' LOCK IN SHARE MODE';
1344 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1345 $startOpts .= 'DISTINCT';
1348 # Various MySQL extensions
1349 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1350 $startOpts .= ' /*! STRAIGHT_JOIN */';
1353 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1354 $startOpts .= ' HIGH_PRIORITY';
1357 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1358 $startOpts .= ' SQL_BIG_RESULT';
1361 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1362 $startOpts .= ' SQL_BUFFER_RESULT';
1365 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1366 $startOpts .= ' SQL_SMALL_RESULT';
1369 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1370 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1373 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1374 $startOpts .= ' SQL_CACHE';
1377 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1378 $startOpts .= ' SQL_NO_CACHE';
1381 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1382 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1387 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1391 * Returns an optional GROUP BY with an optional HAVING
1393 * @param array $options Associative array of options
1395 * @see DatabaseBase::select()
1398 public function makeGroupByWithHaving( $options ) {
1400 if ( isset( $options['GROUP BY'] ) ) {
1401 $gb = is_array( $options['GROUP BY'] )
1402 ?
implode( ',', $options['GROUP BY'] )
1403 : $options['GROUP BY'];
1404 $sql .= ' GROUP BY ' . $gb;
1406 if ( isset( $options['HAVING'] ) ) {
1407 $having = is_array( $options['HAVING'] )
1408 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1409 : $options['HAVING'];
1410 $sql .= ' HAVING ' . $having;
1417 * Returns an optional ORDER BY
1419 * @param array $options Associative array of options
1421 * @see DatabaseBase::select()
1424 public function makeOrderBy( $options ) {
1425 if ( isset( $options['ORDER BY'] ) ) {
1426 $ob = is_array( $options['ORDER BY'] )
1427 ?
implode( ',', $options['ORDER BY'] )
1428 : $options['ORDER BY'];
1430 return ' ORDER BY ' . $ob;
1437 * Execute a SELECT query constructed using the various parameters provided.
1438 * See below for full details of the parameters.
1440 * @param string|array $table Table name
1441 * @param string|array $vars Field names
1442 * @param string|array $conds Conditions
1443 * @param string $fname Caller function name
1444 * @param array $options Query options
1445 * @param array $join_conds Join conditions
1448 * @param string|array $table
1450 * May be either an array of table names, or a single string holding a table
1451 * name. If an array is given, table aliases can be specified, for example:
1453 * array( 'a' => 'user' )
1455 * This includes the user table in the query, with the alias "a" available
1456 * for use in field names (e.g. a.user_name).
1458 * All of the table names given here are automatically run through
1459 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1460 * added, and various other table name mappings to be performed.
1463 * @param string|array $vars
1465 * May be either a field name or an array of field names. The field names
1466 * can be complete fragments of SQL, for direct inclusion into the SELECT
1467 * query. If an array is given, field aliases can be specified, for example:
1469 * array( 'maxrev' => 'MAX(rev_id)' )
1471 * This includes an expression with the alias "maxrev" in the query.
1473 * If an expression is given, care must be taken to ensure that it is
1477 * @param string|array $conds
1479 * May be either a string containing a single condition, or an array of
1480 * conditions. If an array is given, the conditions constructed from each
1481 * element are combined with AND.
1483 * Array elements may take one of two forms:
1485 * - Elements with a numeric key are interpreted as raw SQL fragments.
1486 * - Elements with a string key are interpreted as equality conditions,
1487 * where the key is the field name.
1488 * - If the value of such an array element is a scalar (such as a
1489 * string), it will be treated as data and thus quoted appropriately.
1490 * If it is null, an IS NULL clause will be added.
1491 * - If the value is an array, an IN (...) clause will be constructed
1492 * from its non-null elements, and an IS NULL clause will be added
1493 * if null is present, such that the field may match any of the
1494 * elements in the array. The non-null elements will be quoted.
1496 * Note that expressions are often DBMS-dependent in their syntax.
1497 * DBMS-independent wrappers are provided for constructing several types of
1498 * expression commonly used in condition queries. See:
1499 * - DatabaseBase::buildLike()
1500 * - DatabaseBase::conditional()
1503 * @param string|array $options
1505 * Optional: Array of query options. Boolean options are specified by
1506 * including them in the array as a string value with a numeric key, for
1509 * array( 'FOR UPDATE' )
1511 * The supported options are:
1513 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1514 * with LIMIT can theoretically be used for paging through a result set,
1515 * but this is discouraged in MediaWiki for performance reasons.
1517 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1518 * and then the first rows are taken until the limit is reached. LIMIT
1519 * is applied to a result set after OFFSET.
1521 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1522 * changed until the next COMMIT.
1524 * - DISTINCT: Boolean: return only unique result rows.
1526 * - GROUP BY: May be either an SQL fragment string naming a field or
1527 * expression to group by, or an array of such SQL fragments.
1529 * - HAVING: May be either an string containing a HAVING clause or an array of
1530 * conditions building the HAVING clause. If an array is given, the conditions
1531 * constructed from each element are combined with AND.
1533 * - ORDER BY: May be either an SQL fragment giving a field name or
1534 * expression to order by, or an array of such SQL fragments.
1536 * - USE INDEX: This may be either a string giving the index name to use
1537 * for the query, or an array. If it is an associative array, each key
1538 * gives the table name (or alias), each value gives the index name to
1539 * use for that table. All strings are SQL fragments and so should be
1540 * validated by the caller.
1542 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1543 * instead of SELECT.
1545 * And also the following boolean MySQL extensions, see the MySQL manual
1546 * for documentation:
1548 * - LOCK IN SHARE MODE
1552 * - SQL_BUFFER_RESULT
1553 * - SQL_SMALL_RESULT
1554 * - SQL_CALC_FOUND_ROWS
1559 * @param string|array $join_conds
1561 * Optional associative array of table-specific join conditions. In the
1562 * most common case, this is unnecessary, since the join condition can be
1563 * in $conds. However, it is useful for doing a LEFT JOIN.
1565 * The key of the array contains the table name or alias. The value is an
1566 * array with two elements, numbered 0 and 1. The first gives the type of
1567 * join, the second is an SQL fragment giving the join condition for that
1568 * table. For example:
1570 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1572 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1573 * with no rows in it will be returned. If there was a query error, a
1574 * DBQueryError exception will be thrown, except if the "ignore errors"
1575 * option was set, in which case false will be returned.
1577 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1578 $options = array(), $join_conds = array() ) {
1579 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1581 return $this->query( $sql, $fname );
1585 * The equivalent of DatabaseBase::select() except that the constructed SQL
1586 * is returned, instead of being immediately executed. This can be useful for
1587 * doing UNION queries, where the SQL text of each query is needed. In general,
1588 * however, callers outside of Database classes should just use select().
1590 * @param string|array $table Table name
1591 * @param string|array $vars Field names
1592 * @param string|array $conds Conditions
1593 * @param string $fname Caller function name
1594 * @param string|array $options Query options
1595 * @param string|array $join_conds Join conditions
1597 * @return string SQL query string.
1598 * @see DatabaseBase::select()
1600 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1601 $options = array(), $join_conds = array()
1603 if ( is_array( $vars ) ) {
1604 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1607 $options = (array)$options;
1608 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1609 ?
$options['USE INDEX']
1612 if ( is_array( $table ) ) {
1614 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1615 } elseif ( $table != '' ) {
1616 if ( $table[0] == ' ' ) {
1617 $from = ' FROM ' . $table;
1620 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1626 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1627 $this->makeSelectOptions( $options );
1629 if ( !empty( $conds ) ) {
1630 if ( is_array( $conds ) ) {
1631 $conds = $this->makeList( $conds, LIST_AND
);
1633 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1635 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1638 if ( isset( $options['LIMIT'] ) ) {
1639 $sql = $this->limitResult( $sql, $options['LIMIT'],
1640 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1642 $sql = "$sql $postLimitTail";
1644 if ( isset( $options['EXPLAIN'] ) ) {
1645 $sql = 'EXPLAIN ' . $sql;
1652 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1653 * that a single row object is returned. If the query returns no rows,
1654 * false is returned.
1656 * @param string|array $table Table name
1657 * @param string|array $vars Field names
1658 * @param array $conds Conditions
1659 * @param string $fname Caller function name
1660 * @param string|array $options Query options
1661 * @param array|string $join_conds Join conditions
1663 * @return stdClass|bool
1665 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1666 $options = array(), $join_conds = array()
1668 $options = (array)$options;
1669 $options['LIMIT'] = 1;
1670 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1672 if ( $res === false ) {
1676 if ( !$this->numRows( $res ) ) {
1680 $obj = $this->fetchObject( $res );
1686 * Estimate the number of rows in dataset
1688 * MySQL allows you to estimate the number of rows that would be returned
1689 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1690 * index cardinality statistics, and is notoriously inaccurate, especially
1691 * when large numbers of rows have recently been added or deleted.
1693 * For DBMSs that don't support fast result size estimation, this function
1694 * will actually perform the SELECT COUNT(*).
1696 * Takes the same arguments as DatabaseBase::select().
1698 * @param string $table Table name
1699 * @param string $vars Unused
1700 * @param array|string $conds Filters on the table
1701 * @param string $fname Function name for profiling
1702 * @param array $options Options for select
1703 * @return int Row count
1705 public function estimateRowCount(
1706 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1709 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1712 $row = $this->fetchRow( $res );
1713 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1720 * Get the number of rows in dataset
1722 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1724 * Takes the same arguments as DatabaseBase::select().
1726 * @param string $table Table name
1727 * @param string $vars Unused
1728 * @param array|string $conds Filters on the table
1729 * @param string $fname Function name for profiling
1730 * @param array $options Options for select
1731 * @return int Row count
1734 public function selectRowCount(
1735 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1738 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1739 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1742 $row = $this->fetchRow( $res );
1743 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1750 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1751 * It's only slightly flawed. Don't use for anything important.
1753 * @param string $sql A SQL Query
1757 static function generalizeSQL( $sql ) {
1758 # This does the same as the regexp below would do, but in such a way
1759 # as to avoid crashing php on some large strings.
1760 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1762 $sql = str_replace( "\\\\", '', $sql );
1763 $sql = str_replace( "\\'", '', $sql );
1764 $sql = str_replace( "\\\"", '', $sql );
1765 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1766 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1768 # All newlines, tabs, etc replaced by single space
1769 $sql = preg_replace( '/\s+/', ' ', $sql );
1772 # except the ones surrounded by characters, e.g. l10n
1773 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1774 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1780 * Determines whether a field exists in a table
1782 * @param string $table Table name
1783 * @param string $field Filed to check on that table
1784 * @param string $fname Calling function name (optional)
1785 * @return bool Whether $table has filed $field
1787 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1788 $info = $this->fieldInfo( $table, $field );
1794 * Determines whether an index exists
1795 * Usually throws a DBQueryError on failure
1796 * If errors are explicitly ignored, returns NULL on failure
1798 * @param string $table
1799 * @param string $index
1800 * @param string $fname
1803 public function indexExists( $table, $index, $fname = __METHOD__
) {
1804 if ( !$this->tableExists( $table ) ) {
1808 $info = $this->indexInfo( $table, $index, $fname );
1809 if ( is_null( $info ) ) {
1812 return $info !== false;
1817 * Query whether a given table exists
1819 * @param string $table
1820 * @param string $fname
1823 public function tableExists( $table, $fname = __METHOD__
) {
1824 $table = $this->tableName( $table );
1825 $old = $this->ignoreErrors( true );
1826 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1827 $this->ignoreErrors( $old );
1833 * Determines if a given index is unique
1835 * @param string $table
1836 * @param string $index
1840 public function indexUnique( $table, $index ) {
1841 $indexInfo = $this->indexInfo( $table, $index );
1843 if ( !$indexInfo ) {
1847 return !$indexInfo[0]->Non_unique
;
1851 * Helper for DatabaseBase::insert().
1853 * @param array $options
1856 protected function makeInsertOptions( $options ) {
1857 return implode( ' ', $options );
1861 * INSERT wrapper, inserts an array into a table.
1865 * - A single associative array. The array keys are the field names, and
1866 * the values are the values to insert. The values are treated as data
1867 * and will be quoted appropriately. If NULL is inserted, this will be
1868 * converted to a database NULL.
1869 * - An array with numeric keys, holding a list of associative arrays.
1870 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1871 * each subarray must be identical to each other, and in the same order.
1873 * $options is an array of options, with boolean options encoded as values
1874 * with numeric keys, in the same style as $options in
1875 * DatabaseBase::select(). Supported options are:
1877 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1878 * any rows which cause duplicate key errors are not inserted. It's
1879 * possible to determine how many rows were successfully inserted using
1880 * DatabaseBase::affectedRows().
1882 * @param string $table Table name. This will be passed through
1883 * DatabaseBase::tableName().
1884 * @param array $a Array of rows to insert
1885 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1886 * @param array $options Array of options
1888 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1893 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1894 # No rows to insert, easy just return now
1895 if ( !count( $a ) ) {
1899 $table = $this->tableName( $table );
1901 if ( !is_array( $options ) ) {
1902 $options = array( $options );
1906 if ( isset( $options['fileHandle'] ) ) {
1907 $fh = $options['fileHandle'];
1909 $options = $this->makeInsertOptions( $options );
1911 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1913 $keys = array_keys( $a[0] );
1916 $keys = array_keys( $a );
1919 $sql = 'INSERT ' . $options .
1920 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1924 foreach ( $a as $row ) {
1930 $sql .= '(' . $this->makeList( $row ) . ')';
1933 $sql .= '(' . $this->makeList( $a ) . ')';
1936 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1938 } elseif ( $fh !== null ) {
1942 return (bool)$this->query( $sql, $fname );
1946 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1948 * @param array $options
1951 protected function makeUpdateOptionsArray( $options ) {
1952 if ( !is_array( $options ) ) {
1953 $options = array( $options );
1958 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1959 $opts[] = $this->lowPriorityOption();
1962 if ( in_array( 'IGNORE', $options ) ) {
1970 * Make UPDATE options for the DatabaseBase::update function
1972 * @param array $options The options passed to DatabaseBase::update
1975 protected function makeUpdateOptions( $options ) {
1976 $opts = $this->makeUpdateOptionsArray( $options );
1978 return implode( ' ', $opts );
1982 * UPDATE wrapper. Takes a condition array and a SET array.
1984 * @param string $table Name of the table to UPDATE. This will be passed through
1985 * DatabaseBase::tableName().
1986 * @param array $values An array of values to SET. For each array element,
1987 * the key gives the field name, and the value gives the data to set
1988 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1989 * @param array $conds An array of conditions (WHERE). See
1990 * DatabaseBase::select() for the details of the format of condition
1991 * arrays. Use '*' to update all rows.
1992 * @param string $fname The function name of the caller (from __METHOD__),
1993 * for logging and profiling.
1994 * @param array $options An array of UPDATE options, can be:
1995 * - IGNORE: Ignore unique key conflicts
1996 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1999 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2000 $table = $this->tableName( $table );
2001 $opts = $this->makeUpdateOptions( $options );
2002 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2004 if ( $conds !== array() && $conds !== '*' ) {
2005 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2008 return $this->query( $sql, $fname );
2012 * Makes an encoded list of strings from an array
2014 * @param array $a Containing the data
2015 * @param int $mode Constant
2016 * - LIST_COMMA: Comma separated, no field names
2017 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2018 * documentation for $conds in DatabaseBase::select().
2019 * - LIST_OR: ORed WHERE clause (without the WHERE)
2020 * - LIST_SET: Comma separated with field names, like a SET clause
2021 * - LIST_NAMES: Comma separated field names
2022 * @throws MWException|DBUnexpectedError
2025 public function makeList( $a, $mode = LIST_COMMA
) {
2026 if ( !is_array( $a ) ) {
2027 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2033 foreach ( $a as $field => $value ) {
2035 if ( $mode == LIST_AND
) {
2037 } elseif ( $mode == LIST_OR
) {
2046 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2047 $list .= "($value)";
2048 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2050 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2051 // Remove null from array to be handled separately if found
2052 $includeNull = false;
2053 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2054 $includeNull = true;
2055 unset( $value[$nullKey] );
2057 if ( count( $value ) == 0 && !$includeNull ) {
2058 throw new MWException( __METHOD__
. ": empty input for field $field" );
2059 } elseif ( count( $value ) == 0 ) {
2060 // only check if $field is null
2061 $list .= "$field IS NULL";
2063 // IN clause contains at least one valid element
2064 if ( $includeNull ) {
2065 // Group subconditions to ensure correct precedence
2068 if ( count( $value ) == 1 ) {
2069 // Special-case single values, as IN isn't terribly efficient
2070 // Don't necessarily assume the single key is 0; we don't
2071 // enforce linear numeric ordering on other arrays here.
2072 $value = array_values( $value );
2073 $list .= $field . " = " . $this->addQuotes( $value[0] );
2075 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2077 // if null present in array, append IS NULL
2078 if ( $includeNull ) {
2079 $list .= " OR $field IS NULL)";
2082 } elseif ( $value === null ) {
2083 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2084 $list .= "$field IS ";
2085 } elseif ( $mode == LIST_SET
) {
2086 $list .= "$field = ";
2090 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2091 $list .= "$field = ";
2093 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2101 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2102 * The keys on each level may be either integers or strings.
2104 * @param array $data Organized as 2-d
2105 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2106 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2107 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2108 * @return string|bool SQL fragment, or false if no items in array
2110 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2113 foreach ( $data as $base => $sub ) {
2114 if ( count( $sub ) ) {
2115 $conds[] = $this->makeList(
2116 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2122 return $this->makeList( $conds, LIST_OR
);
2124 // Nothing to search for...
2130 * Return aggregated value alias
2132 * @param array $valuedata
2133 * @param string $valuename
2137 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2142 * @param string $field
2145 public function bitNot( $field ) {
2150 * @param string $fieldLeft
2151 * @param string $fieldRight
2154 public function bitAnd( $fieldLeft, $fieldRight ) {
2155 return "($fieldLeft & $fieldRight)";
2159 * @param string $fieldLeft
2160 * @param string $fieldRight
2163 public function bitOr( $fieldLeft, $fieldRight ) {
2164 return "($fieldLeft | $fieldRight)";
2168 * Build a concatenation list to feed into a SQL query
2169 * @param array $stringList List of raw SQL expressions; caller is
2170 * responsible for any quoting
2173 public function buildConcat( $stringList ) {
2174 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2178 * Build a GROUP_CONCAT or equivalent statement for a query.
2180 * This is useful for combining a field for several rows into a single string.
2181 * NULL values will not appear in the output, duplicated values will appear,
2182 * and the resulting delimiter-separated values have no defined sort order.
2183 * Code using the results may need to use the PHP unique() or sort() methods.
2185 * @param string $delim Glue to bind the results together
2186 * @param string|array $table Table name
2187 * @param string $field Field name
2188 * @param string|array $conds Conditions
2189 * @param string|array $join_conds Join conditions
2190 * @return string SQL text
2193 public function buildGroupConcatField(
2194 $delim, $table, $field, $conds = '', $join_conds = array()
2196 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2198 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2202 * Change the current database
2204 * @todo Explain what exactly will fail if this is not overridden.
2208 * @return bool Success or failure
2210 public function selectDB( $db ) {
2211 # Stub. Shouldn't cause serious problems if it's not overridden, but
2212 # if your database engine supports a concept similar to MySQL's
2213 # databases you may as well.
2214 $this->mDBname
= $db;
2220 * Get the current DB name
2223 public function getDBname() {
2224 return $this->mDBname
;
2228 * Get the server hostname or IP address
2231 public function getServer() {
2232 return $this->mServer
;
2236 * Format a table name ready for use in constructing an SQL query
2238 * This does two important things: it quotes the table names to clean them up,
2239 * and it adds a table prefix if only given a table name with no quotes.
2241 * All functions of this object which require a table name call this function
2242 * themselves. Pass the canonical name to such functions. This is only needed
2243 * when calling query() directly.
2245 * @param string $name Database table name
2246 * @param string $format One of:
2247 * quoted - Automatically pass the table name through addIdentifierQuotes()
2248 * so that it can be used in a query.
2249 * raw - Do not add identifier quotes to the table name
2250 * @return string Full database name
2252 public function tableName( $name, $format = 'quoted' ) {
2253 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2254 # Skip the entire process when we have a string quoted on both ends.
2255 # Note that we check the end so that we will still quote any use of
2256 # use of `database`.table. But won't break things if someone wants
2257 # to query a database table with a dot in the name.
2258 if ( $this->isQuotedIdentifier( $name ) ) {
2262 # Lets test for any bits of text that should never show up in a table
2263 # name. Basically anything like JOIN or ON which are actually part of
2264 # SQL queries, but may end up inside of the table value to combine
2265 # sql. Such as how the API is doing.
2266 # Note that we use a whitespace test rather than a \b test to avoid
2267 # any remote case where a word like on may be inside of a table name
2268 # surrounded by symbols which may be considered word breaks.
2269 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2273 # Split database and table into proper variables.
2274 # We reverse the explode so that database.table and table both output
2275 # the correct table.
2276 $dbDetails = explode( '.', $name, 3 );
2277 if ( count( $dbDetails ) == 3 ) {
2278 list( $database, $schema, $table ) = $dbDetails;
2279 # We don't want any prefix added in this case
2281 } elseif ( count( $dbDetails ) == 2 ) {
2282 list( $database, $table ) = $dbDetails;
2283 # We don't want any prefix added in this case
2284 # In dbs that support it, $database may actually be the schema
2285 # but that doesn't affect any of the functionality here
2289 list( $table ) = $dbDetails;
2290 if ( $wgSharedDB !== null # We have a shared database
2291 && $this->mForeign
== false # We're not working on a foreign database
2292 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2293 && in_array( $table, $wgSharedTables ) # A shared table is selected
2295 $database = $wgSharedDB;
2296 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2297 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2300 $schema = $this->mSchema
; # Default schema
2301 $prefix = $this->mTablePrefix
; # Default prefix
2305 # Quote $table and apply the prefix if not quoted.
2306 # $tableName might be empty if this is called from Database::replaceVars()
2307 $tableName = "{$prefix}{$table}";
2308 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2309 $tableName = $this->addIdentifierQuotes( $tableName );
2312 # Quote $schema and merge it with the table name if needed
2313 if ( strlen( $schema ) ) {
2314 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2315 $schema = $this->addIdentifierQuotes( $schema );
2317 $tableName = $schema . '.' . $tableName;
2320 # Quote $database and merge it with the table name if needed
2321 if ( $database !== null ) {
2322 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2323 $database = $this->addIdentifierQuotes( $database );
2325 $tableName = $database . '.' . $tableName;
2332 * Fetch a number of table names into an array
2333 * This is handy when you need to construct SQL for joins
2336 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2337 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2338 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2342 public function tableNames() {
2343 $inArray = func_get_args();
2346 foreach ( $inArray as $name ) {
2347 $retVal[$name] = $this->tableName( $name );
2354 * Fetch a number of table names into an zero-indexed numerical array
2355 * This is handy when you need to construct SQL for joins
2358 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2359 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2360 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2364 public function tableNamesN() {
2365 $inArray = func_get_args();
2368 foreach ( $inArray as $name ) {
2369 $retVal[] = $this->tableName( $name );
2376 * Get an aliased table name
2377 * e.g. tableName AS newTableName
2379 * @param string $name Table name, see tableName()
2380 * @param string|bool $alias Alias (optional)
2381 * @return string SQL name for aliased table. Will not alias a table to its own name
2383 public function tableNameWithAlias( $name, $alias = false ) {
2384 if ( !$alias ||
$alias == $name ) {
2385 return $this->tableName( $name );
2387 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2392 * Gets an array of aliased table names
2394 * @param array $tables Array( [alias] => table )
2395 * @return string[] See tableNameWithAlias()
2397 public function tableNamesWithAlias( $tables ) {
2399 foreach ( $tables as $alias => $table ) {
2400 if ( is_numeric( $alias ) ) {
2403 $retval[] = $this->tableNameWithAlias( $table, $alias );
2410 * Get an aliased field name
2411 * e.g. fieldName AS newFieldName
2413 * @param string $name Field name
2414 * @param string|bool $alias Alias (optional)
2415 * @return string SQL name for aliased field. Will not alias a field to its own name
2417 public function fieldNameWithAlias( $name, $alias = false ) {
2418 if ( !$alias ||
(string)$alias === (string)$name ) {
2421 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2426 * Gets an array of aliased field names
2428 * @param array $fields Array( [alias] => field )
2429 * @return string[] See fieldNameWithAlias()
2431 public function fieldNamesWithAlias( $fields ) {
2433 foreach ( $fields as $alias => $field ) {
2434 if ( is_numeric( $alias ) ) {
2437 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2444 * Get the aliased table name clause for a FROM clause
2445 * which might have a JOIN and/or USE INDEX clause
2447 * @param array $tables ( [alias] => table )
2448 * @param array $use_index Same as for select()
2449 * @param array $join_conds Same as for select()
2452 protected function tableNamesWithUseIndexOrJOIN(
2453 $tables, $use_index = array(), $join_conds = array()
2457 $use_index = (array)$use_index;
2458 $join_conds = (array)$join_conds;
2460 foreach ( $tables as $alias => $table ) {
2461 if ( !is_string( $alias ) ) {
2462 // No alias? Set it equal to the table name
2465 // Is there a JOIN clause for this table?
2466 if ( isset( $join_conds[$alias] ) ) {
2467 list( $joinType, $conds ) = $join_conds[$alias];
2468 $tableClause = $joinType;
2469 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2470 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2471 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2473 $tableClause .= ' ' . $use;
2476 $on = $this->makeList( (array)$conds, LIST_AND
);
2478 $tableClause .= ' ON (' . $on . ')';
2481 $retJOIN[] = $tableClause;
2482 } elseif ( isset( $use_index[$alias] ) ) {
2483 // Is there an INDEX clause for this table?
2484 $tableClause = $this->tableNameWithAlias( $table, $alias );
2485 $tableClause .= ' ' . $this->useIndexClause(
2486 implode( ',', (array)$use_index[$alias] )
2489 $ret[] = $tableClause;
2491 $tableClause = $this->tableNameWithAlias( $table, $alias );
2493 $ret[] = $tableClause;
2497 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2498 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2499 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2501 // Compile our final table clause
2502 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2506 * Get the name of an index in a given table.
2508 * @protected Don't use outside of DatabaseBase and childs
2509 * @param string $index
2512 public function indexName( $index ) {
2513 // @FIXME: Make this protected once we move away from PHP 5.3
2514 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2516 // Backwards-compatibility hack
2518 'ar_usertext_timestamp' => 'usertext_timestamp',
2519 'un_user_id' => 'user_id',
2520 'un_user_ip' => 'user_ip',
2523 if ( isset( $renamed[$index] ) ) {
2524 return $renamed[$index];
2531 * Adds quotes and backslashes.
2533 * @param string|Blob $s
2536 public function addQuotes( $s ) {
2537 if ( $s instanceof Blob
) {
2540 if ( $s === null ) {
2543 # This will also quote numeric values. This should be harmless,
2544 # and protects against weird problems that occur when they really
2545 # _are_ strings such as article titles and string->number->string
2546 # conversion is not 1:1.
2547 return "'" . $this->strencode( $s ) . "'";
2552 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2553 * MySQL uses `backticks` while basically everything else uses double quotes.
2554 * Since MySQL is the odd one out here the double quotes are our generic
2555 * and we implement backticks in DatabaseMysql.
2560 public function addIdentifierQuotes( $s ) {
2561 return '"' . str_replace( '"', '""', $s ) . '"';
2565 * Returns if the given identifier looks quoted or not according to
2566 * the database convention for quoting identifiers .
2568 * @param string $name
2571 public function isQuotedIdentifier( $name ) {
2572 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2579 protected function escapeLikeInternal( $s ) {
2580 return addcslashes( $s, '\%_' );
2584 * LIKE statement wrapper, receives a variable-length argument list with
2585 * parts of pattern to match containing either string literals that will be
2586 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2587 * the function could be provided with an array of aforementioned
2590 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2591 * a LIKE clause that searches for subpages of 'My page title'.
2593 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2594 * $query .= $dbr->buildLike( $pattern );
2597 * @return string Fully built LIKE statement
2599 public function buildLike() {
2600 $params = func_get_args();
2602 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2603 $params = $params[0];
2608 foreach ( $params as $value ) {
2609 if ( $value instanceof LikeMatch
) {
2610 $s .= $value->toString();
2612 $s .= $this->escapeLikeInternal( $value );
2616 return " LIKE {$this->addQuotes( $s )} ";
2620 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2624 public function anyChar() {
2625 return new LikeMatch( '_' );
2629 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2633 public function anyString() {
2634 return new LikeMatch( '%' );
2638 * Returns an appropriately quoted sequence value for inserting a new row.
2639 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2640 * subclass will return an integer, and save the value for insertId()
2642 * Any implementation of this function should *not* involve reusing
2643 * sequence numbers created for rolled-back transactions.
2644 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2645 * @param string $seqName
2648 public function nextSequenceValue( $seqName ) {
2653 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2654 * is only needed because a) MySQL must be as efficient as possible due to
2655 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2656 * which index to pick. Anyway, other databases might have different
2657 * indexes on a given table. So don't bother overriding this unless you're
2659 * @param string $index
2662 public function useIndexClause( $index ) {
2667 * REPLACE query wrapper.
2669 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2670 * except that when there is a duplicate key error, the old row is deleted
2671 * and the new row is inserted in its place.
2673 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2674 * perform the delete, we need to know what the unique indexes are so that
2675 * we know how to find the conflicting rows.
2677 * It may be more efficient to leave off unique indexes which are unlikely
2678 * to collide. However if you do this, you run the risk of encountering
2679 * errors which wouldn't have occurred in MySQL.
2681 * @param string $table The table to replace the row(s) in.
2682 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2683 * a field name or an array of field names
2684 * @param array $rows Can be either a single row to insert, or multiple rows,
2685 * in the same format as for DatabaseBase::insert()
2686 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2688 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2689 $quotedTable = $this->tableName( $table );
2691 if ( count( $rows ) == 0 ) {
2696 if ( !is_array( reset( $rows ) ) ) {
2697 $rows = array( $rows );
2700 // @FXIME: this is not atomic, but a trx would break affectedRows()
2701 foreach ( $rows as $row ) {
2702 # Delete rows which collide
2703 if ( $uniqueIndexes ) {
2704 $sql = "DELETE FROM $quotedTable WHERE ";
2706 foreach ( $uniqueIndexes as $index ) {
2713 if ( is_array( $index ) ) {
2715 foreach ( $index as $col ) {
2721 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2724 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2728 $this->query( $sql, $fname );
2731 # Now insert the row
2732 $this->insert( $table, $row, $fname );
2737 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2740 * @param string $table Table name
2741 * @param array|string $rows Row(s) to insert
2742 * @param string $fname Caller function name
2744 * @return ResultWrapper
2746 protected function nativeReplace( $table, $rows, $fname ) {
2747 $table = $this->tableName( $table );
2750 if ( !is_array( reset( $rows ) ) ) {
2751 $rows = array( $rows );
2754 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2757 foreach ( $rows as $row ) {
2764 $sql .= '(' . $this->makeList( $row ) . ')';
2767 return $this->query( $sql, $fname );
2771 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2773 * This updates any conflicting rows (according to the unique indexes) using
2774 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2776 * $rows may be either:
2777 * - A single associative array. The array keys are the field names, and
2778 * the values are the values to insert. The values are treated as data
2779 * and will be quoted appropriately. If NULL is inserted, this will be
2780 * converted to a database NULL.
2781 * - An array with numeric keys, holding a list of associative arrays.
2782 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2783 * each subarray must be identical to each other, and in the same order.
2785 * It may be more efficient to leave off unique indexes which are unlikely
2786 * to collide. However if you do this, you run the risk of encountering
2787 * errors which wouldn't have occurred in MySQL.
2789 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2794 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2795 * @param array $rows A single row or list of rows to insert
2796 * @param array $uniqueIndexes List of single field names or field name tuples
2797 * @param array $set An array of values to SET. For each array element, the
2798 * key gives the field name, and the value gives the data to set that
2799 * field to. The data will be quoted by DatabaseBase::addQuotes().
2800 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2804 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2807 if ( !count( $rows ) ) {
2808 return true; // nothing to do
2811 if ( !is_array( reset( $rows ) ) ) {
2812 $rows = array( $rows );
2815 if ( count( $uniqueIndexes ) ) {
2816 $clauses = array(); // list WHERE clauses that each identify a single row
2817 foreach ( $rows as $row ) {
2818 foreach ( $uniqueIndexes as $index ) {
2819 $index = is_array( $index ) ?
$index : array( $index ); // columns
2820 $rowKey = array(); // unique key to this row
2821 foreach ( $index as $column ) {
2822 $rowKey[$column] = $row[$column];
2824 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2827 $where = array( $this->makeList( $clauses, LIST_OR
) );
2832 $useTrx = !$this->mTrxLevel
;
2834 $this->begin( $fname );
2837 # Update any existing conflicting row(s)
2838 if ( $where !== false ) {
2839 $ok = $this->update( $table, $set, $where, $fname );
2843 # Now insert any non-conflicting row(s)
2844 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2845 } catch ( Exception
$e ) {
2847 $this->rollback( $fname );
2852 $this->commit( $fname );
2859 * DELETE where the condition is a join.
2861 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2862 * we use sub-selects
2864 * For safety, an empty $conds will not delete everything. If you want to
2865 * delete all rows where the join condition matches, set $conds='*'.
2867 * DO NOT put the join condition in $conds.
2869 * @param string $delTable The table to delete from.
2870 * @param string $joinTable The other table.
2871 * @param string $delVar The variable to join on, in the first table.
2872 * @param string $joinVar The variable to join on, in the second table.
2873 * @param array $conds Condition array of field names mapped to variables,
2874 * ANDed together in the WHERE clause
2875 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2876 * @throws DBUnexpectedError
2878 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2882 throw new DBUnexpectedError( $this,
2883 'DatabaseBase::deleteJoin() called with empty $conds' );
2886 $delTable = $this->tableName( $delTable );
2887 $joinTable = $this->tableName( $joinTable );
2888 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2889 if ( $conds != '*' ) {
2890 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2894 $this->query( $sql, $fname );
2898 * Returns the size of a text field, or -1 for "unlimited"
2900 * @param string $table
2901 * @param string $field
2904 public function textFieldSize( $table, $field ) {
2905 $table = $this->tableName( $table );
2906 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2907 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2908 $row = $this->fetchObject( $res );
2912 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2922 * A string to insert into queries to show that they're low-priority, like
2923 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2924 * string and nothing bad should happen.
2926 * @return string Returns the text of the low priority option if it is
2927 * supported, or a blank string otherwise
2929 public function lowPriorityOption() {
2934 * DELETE query wrapper.
2936 * @param array $table Table name
2937 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2938 * for the format. Use $conds == "*" to delete all rows
2939 * @param string $fname Name of the calling function
2940 * @throws DBUnexpectedError
2941 * @return bool|ResultWrapper
2943 public function delete( $table, $conds, $fname = __METHOD__
) {
2945 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2948 $table = $this->tableName( $table );
2949 $sql = "DELETE FROM $table";
2951 if ( $conds != '*' ) {
2952 if ( is_array( $conds ) ) {
2953 $conds = $this->makeList( $conds, LIST_AND
);
2955 $sql .= ' WHERE ' . $conds;
2958 return $this->query( $sql, $fname );
2962 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2963 * into another table.
2965 * @param string $destTable The table name to insert into
2966 * @param string|array $srcTable May be either a table name, or an array of table names
2967 * to include in a join.
2969 * @param array $varMap Must be an associative array of the form
2970 * array( 'dest1' => 'source1', ...). Source items may be literals
2971 * rather than field names, but strings should be quoted with
2972 * DatabaseBase::addQuotes()
2974 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2975 * the details of the format of condition arrays. May be "*" to copy the
2978 * @param string $fname The function name of the caller, from __METHOD__
2980 * @param array $insertOptions Options for the INSERT part of the query, see
2981 * DatabaseBase::insert() for details.
2982 * @param array $selectOptions Options for the SELECT part of the query, see
2983 * DatabaseBase::select() for details.
2985 * @return ResultWrapper
2987 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2988 $fname = __METHOD__
,
2989 $insertOptions = array(), $selectOptions = array()
2991 $destTable = $this->tableName( $destTable );
2993 if ( !is_array( $insertOptions ) ) {
2994 $insertOptions = array( $insertOptions );
2997 $insertOptions = $this->makeInsertOptions( $insertOptions );
2999 if ( !is_array( $selectOptions ) ) {
3000 $selectOptions = array( $selectOptions );
3003 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3005 if ( is_array( $srcTable ) ) {
3006 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3008 $srcTable = $this->tableName( $srcTable );
3011 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3012 " SELECT $startOpts " . implode( ',', $varMap ) .
3013 " FROM $srcTable $useIndex ";
3015 if ( $conds != '*' ) {
3016 if ( is_array( $conds ) ) {
3017 $conds = $this->makeList( $conds, LIST_AND
);
3019 $sql .= " WHERE $conds";
3022 $sql .= " $tailOpts";
3024 return $this->query( $sql, $fname );
3028 * Construct a LIMIT query with optional offset. This is used for query
3029 * pages. The SQL should be adjusted so that only the first $limit rows
3030 * are returned. If $offset is provided as well, then the first $offset
3031 * rows should be discarded, and the next $limit rows should be returned.
3032 * If the result of the query is not ordered, then the rows to be returned
3033 * are theoretically arbitrary.
3035 * $sql is expected to be a SELECT, if that makes a difference.
3037 * The version provided by default works in MySQL and SQLite. It will very
3038 * likely need to be overridden for most other DBMSes.
3040 * @param string $sql SQL query we will append the limit too
3041 * @param int $limit The SQL limit
3042 * @param int|bool $offset The SQL offset (default false)
3043 * @throws DBUnexpectedError
3046 public function limitResult( $sql, $limit, $offset = false ) {
3047 if ( !is_numeric( $limit ) ) {
3048 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3051 return "$sql LIMIT "
3052 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3057 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3058 * within the UNION construct.
3061 public function unionSupportsOrderAndLimit() {
3062 return true; // True for almost every DB supported
3066 * Construct a UNION query
3067 * This is used for providing overload point for other DB abstractions
3068 * not compatible with the MySQL syntax.
3069 * @param array $sqls SQL statements to combine
3070 * @param bool $all Use UNION ALL
3071 * @return string SQL fragment
3073 public function unionQueries( $sqls, $all ) {
3074 $glue = $all ?
') UNION ALL (' : ') UNION (';
3076 return '(' . implode( $glue, $sqls ) . ')';
3080 * Returns an SQL expression for a simple conditional. This doesn't need
3081 * to be overridden unless CASE isn't supported in your DBMS.
3083 * @param string|array $cond SQL expression which will result in a boolean value
3084 * @param string $trueVal SQL expression to return if true
3085 * @param string $falseVal SQL expression to return if false
3086 * @return string SQL fragment
3088 public function conditional( $cond, $trueVal, $falseVal ) {
3089 if ( is_array( $cond ) ) {
3090 $cond = $this->makeList( $cond, LIST_AND
);
3093 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3097 * Returns a comand for str_replace function in SQL query.
3098 * Uses REPLACE() in MySQL
3100 * @param string $orig Column to modify
3101 * @param string $old Column to seek
3102 * @param string $new Column to replace with
3106 public function strreplace( $orig, $old, $new ) {
3107 return "REPLACE({$orig}, {$old}, {$new})";
3111 * Determines how long the server has been up
3116 public function getServerUptime() {
3121 * Determines if the last failure was due to a deadlock
3126 public function wasDeadlock() {
3131 * Determines if the last failure was due to a lock timeout
3136 public function wasLockTimeout() {
3141 * Determines if the last query error was something that should be dealt
3142 * with by pinging the connection and reissuing the query.
3147 public function wasErrorReissuable() {
3152 * Determines if the last failure was due to the database being read-only.
3157 public function wasReadOnlyError() {
3162 * Determines if the given query error was a connection drop
3165 * @param integer|string $errno
3168 public function wasConnectionError( $errno ) {
3173 * Perform a deadlock-prone transaction.
3175 * This function invokes a callback function to perform a set of write
3176 * queries. If a deadlock occurs during the processing, the transaction
3177 * will be rolled back and the callback function will be called again.
3180 * $dbw->deadlockLoop( callback, ... );
3182 * Extra arguments are passed through to the specified callback function.
3184 * Returns whatever the callback function returned on its successful,
3185 * iteration, or false on error, for example if the retry limit was
3189 * @throws DBQueryError
3191 public function deadlockLoop() {
3192 $args = func_get_args();
3193 $function = array_shift( $args );
3194 $tries = self
::DEADLOCK_TRIES
;
3196 $this->begin( __METHOD__
);
3202 $retVal = call_user_func_array( $function, $args );
3204 } catch ( DBQueryError
$e ) {
3205 if ( $this->wasDeadlock() ) {
3206 // Retry after a randomized delay
3207 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3209 // Throw the error back up
3213 } while ( --$tries > 0 );
3215 if ( $tries <= 0 ) {
3216 // Too many deadlocks; give up
3217 $this->rollback( __METHOD__
);
3220 $this->commit( __METHOD__
);
3227 * Wait for the slave to catch up to a given master position.
3229 * @param DBMasterPos $pos
3230 * @param int $timeout The maximum number of seconds to wait for
3232 * @return int Zero if the slave was past that position already,
3233 * greater than zero if we waited for some period of time, less than
3234 * zero if we timed out.
3236 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3237 # Real waits are implemented in the subclass.
3242 * Get the replication position of this slave
3244 * @return DBMasterPos|bool False if this is not a slave.
3246 public function getSlavePos() {
3252 * Get the position of this master
3254 * @return DBMasterPos|bool False if this is not a master
3256 public function getMasterPos() {
3262 * Run an anonymous function as soon as there is no transaction pending.
3263 * If there is a transaction and it is rolled back, then the callback is cancelled.
3264 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3265 * Callbacks must commit any transactions that they begin.
3267 * This is useful for updates to different systems or when separate transactions are needed.
3268 * For example, one might want to enqueue jobs into a system outside the database, but only
3269 * after the database is updated so that the jobs will see the data when they actually run.
3270 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3272 * @param callable $callback
3275 final public function onTransactionIdle( $callback ) {
3276 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3277 if ( !$this->mTrxLevel
) {
3278 $this->runOnTransactionIdleCallbacks();
3283 * Run an anonymous function before the current transaction commits or now if there is none.
3284 * If there is a transaction and it is rolled back, then the callback is cancelled.
3285 * Callbacks must not start nor commit any transactions.
3287 * This is useful for updates that easily cause deadlocks if locks are held too long
3288 * but where atomicity is strongly desired for these updates and some related updates.
3290 * @param callable $callback
3293 final public function onTransactionPreCommitOrIdle( $callback ) {
3294 if ( $this->mTrxLevel
) {
3295 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3297 $this->onTransactionIdle( $callback ); // this will trigger immediately
3302 * Actually any "on transaction idle" callbacks.
3306 protected function runOnTransactionIdleCallbacks() {
3307 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3309 $e = $ePrior = null; // last exception
3310 do { // callbacks may add callbacks :)
3311 $callbacks = $this->mTrxIdleCallbacks
;
3312 $this->mTrxIdleCallbacks
= array(); // recursion guard
3313 foreach ( $callbacks as $callback ) {
3315 list( $phpCallback ) = $callback;
3316 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3317 call_user_func( $phpCallback );
3318 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3319 } catch ( Exception
$e ) {
3321 MWExceptionHandler
::logException( $ePrior );
3326 } while ( count( $this->mTrxIdleCallbacks
) );
3328 if ( $e instanceof Exception
) {
3329 throw $e; // re-throw any last exception
3334 * Actually any "on transaction pre-commit" callbacks.
3338 protected function runOnTransactionPreCommitCallbacks() {
3339 $e = $ePrior = null; // last exception
3340 do { // callbacks may add callbacks :)
3341 $callbacks = $this->mTrxPreCommitCallbacks
;
3342 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3343 foreach ( $callbacks as $callback ) {
3345 list( $phpCallback ) = $callback;
3346 call_user_func( $phpCallback );
3347 } catch ( Exception
$e ) {
3349 MWExceptionHandler
::logException( $ePrior );
3354 } while ( count( $this->mTrxPreCommitCallbacks
) );
3356 if ( $e instanceof Exception
) {
3357 throw $e; // re-throw any last exception
3362 * Begin an atomic section of statements
3364 * If a transaction has been started already, just keep track of the given
3365 * section name to make sure the transaction is not committed pre-maturely.
3366 * This function can be used in layers (with sub-sections), so use a stack
3367 * to keep track of the different atomic sections. If there is no transaction,
3368 * start one implicitly.
3370 * The goal of this function is to create an atomic section of SQL queries
3371 * without having to start a new transaction if it already exists.
3373 * Atomic sections are more strict than transactions. With transactions,
3374 * attempting to begin a new transaction when one is already running results
3375 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3376 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3377 * and any database transactions cannot be began or committed until all atomic
3378 * levels are closed. There is no such thing as implicitly opening or closing
3379 * an atomic section.
3382 * @param string $fname
3385 final public function startAtomic( $fname = __METHOD__
) {
3386 if ( !$this->mTrxLevel
) {
3387 $this->begin( $fname );
3388 $this->mTrxAutomatic
= true;
3389 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3390 // in all changes being in one transaction to keep requests transactional.
3391 if ( !$this->getFlag( DBO_TRX
) ) {
3392 $this->mTrxAutomaticAtomic
= true;
3396 $this->mTrxAtomicLevels
[] = $fname;
3400 * Ends an atomic section of SQL statements
3402 * Ends the next section of atomic SQL statements and commits the transaction
3406 * @see DatabaseBase::startAtomic
3407 * @param string $fname
3410 final public function endAtomic( $fname = __METHOD__
) {
3411 if ( !$this->mTrxLevel
) {
3412 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3414 if ( !$this->mTrxAtomicLevels ||
3415 array_pop( $this->mTrxAtomicLevels
) !== $fname
3417 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3420 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3421 $this->commit( $fname, 'flush' );
3426 * Begin a transaction. If a transaction is already in progress,
3427 * that transaction will be committed before the new transaction is started.
3429 * Note that when the DBO_TRX flag is set (which is usually the case for web
3430 * requests, but not for maintenance scripts), any previous database query
3431 * will have started a transaction automatically.
3433 * Nesting of transactions is not supported. Attempts to nest transactions
3434 * will cause a warning, unless the current transaction was started
3435 * automatically because of the DBO_TRX flag.
3437 * @param string $fname
3440 final public function begin( $fname = __METHOD__
) {
3441 global $wgDebugDBTransactions;
3443 if ( $this->mTrxLevel
) { // implicit commit
3444 if ( $this->mTrxAtomicLevels
) {
3445 // If the current transaction was an automatic atomic one, then we definitely have
3446 // a problem. Same if there is any unclosed atomic level.
3447 throw new DBUnexpectedError( $this,
3448 "Attempted to start explicit transaction when atomic levels are still open."
3450 } elseif ( !$this->mTrxAutomatic
) {
3451 // We want to warn about inadvertently nested begin/commit pairs, but not about
3452 // auto-committing implicit transactions that were started by query() via DBO_TRX
3453 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3454 " performing implicit commit!";
3457 $this->getLogContext( array(
3458 'method' => __METHOD__
,
3463 // if the transaction was automatic and has done write operations,
3464 // log it if $wgDebugDBTransactions is enabled.
3465 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3466 wfDebug( "$fname: Automatic transaction with writes in progress" .
3467 " (from {$this->mTrxFname}), performing implicit commit!\n"
3472 $this->runOnTransactionPreCommitCallbacks();
3473 $writeTime = $this->pendingWriteQueryDuration();
3474 $this->doCommit( $fname );
3475 if ( $this->mTrxDoneWrites
) {
3476 $this->mDoneWrites
= microtime( true );
3477 $this->getTransactionProfiler()->transactionWritingOut(
3478 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3480 $this->runOnTransactionIdleCallbacks();
3483 # Avoid fatals if close() was called
3484 $this->assertOpen();
3486 $this->doBegin( $fname );
3487 $this->mTrxTimestamp
= microtime( true );
3488 $this->mTrxFname
= $fname;
3489 $this->mTrxDoneWrites
= false;
3490 $this->mTrxAutomatic
= false;
3491 $this->mTrxAutomaticAtomic
= false;
3492 $this->mTrxAtomicLevels
= array();
3493 $this->mTrxIdleCallbacks
= array();
3494 $this->mTrxPreCommitCallbacks
= array();
3495 $this->mTrxShortId
= wfRandomString( 12 );
3496 $this->mTrxWriteDuration
= 0.0;
3500 * Issues the BEGIN command to the database server.
3502 * @see DatabaseBase::begin()
3503 * @param string $fname
3505 protected function doBegin( $fname ) {
3506 $this->query( 'BEGIN', $fname );
3507 $this->mTrxLevel
= 1;
3511 * Commits a transaction previously started using begin().
3512 * If no transaction is in progress, a warning is issued.
3514 * Nesting of transactions is not supported.
3516 * @param string $fname
3517 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3518 * explicitly committing implicit transactions, or calling commit when no
3519 * transaction is in progress. This will silently break any ongoing
3520 * explicit transaction. Only set the flush flag if you are sure that it
3521 * is safe to ignore these warnings in your context.
3522 * @throws DBUnexpectedError
3524 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3525 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3526 // There are still atomic sections open. This cannot be ignored
3527 throw new DBUnexpectedError(
3529 "Attempted to commit transaction while atomic sections are still open"
3533 if ( $flush === 'flush' ) {
3534 if ( !$this->mTrxLevel
) {
3535 return; // nothing to do
3536 } elseif ( !$this->mTrxAutomatic
) {
3537 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3540 if ( !$this->mTrxLevel
) {
3541 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3542 return; // nothing to do
3543 } elseif ( $this->mTrxAutomatic
) {
3544 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3548 # Avoid fatals if close() was called
3549 $this->assertOpen();
3551 $this->runOnTransactionPreCommitCallbacks();
3552 $writeTime = $this->pendingWriteQueryDuration();
3553 $this->doCommit( $fname );
3554 if ( $this->mTrxDoneWrites
) {
3555 $this->mDoneWrites
= microtime( true );
3556 $this->getTransactionProfiler()->transactionWritingOut(
3557 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3559 $this->runOnTransactionIdleCallbacks();
3563 * Issues the COMMIT command to the database server.
3565 * @see DatabaseBase::commit()
3566 * @param string $fname
3568 protected function doCommit( $fname ) {
3569 if ( $this->mTrxLevel
) {
3570 $this->query( 'COMMIT', $fname );
3571 $this->mTrxLevel
= 0;
3576 * Rollback a transaction previously started using begin().
3577 * If no transaction is in progress, a warning is issued.
3579 * No-op on non-transactional databases.
3581 * @param string $fname
3582 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3583 * calling rollback when no transaction is in progress. This will silently
3584 * break any ongoing explicit transaction. Only set the flush flag if you
3585 * are sure that it is safe to ignore these warnings in your context.
3586 * @throws DBUnexpectedError
3587 * @since 1.23 Added $flush parameter
3589 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3590 if ( $flush !== 'flush' ) {
3591 if ( !$this->mTrxLevel
) {
3592 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3593 return; // nothing to do
3594 } elseif ( $this->mTrxAutomatic
) {
3595 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3598 if ( !$this->mTrxLevel
) {
3599 return; // nothing to do
3600 } elseif ( !$this->mTrxAutomatic
) {
3601 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3605 # Avoid fatals if close() was called
3606 $this->assertOpen();
3608 $this->doRollback( $fname );
3609 $this->mTrxIdleCallbacks
= array(); // cancel
3610 $this->mTrxPreCommitCallbacks
= array(); // cancel
3611 $this->mTrxAtomicLevels
= array();
3612 if ( $this->mTrxDoneWrites
) {
3613 $this->getTransactionProfiler()->transactionWritingOut(
3614 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3619 * Issues the ROLLBACK command to the database server.
3621 * @see DatabaseBase::rollback()
3622 * @param string $fname
3624 protected function doRollback( $fname ) {
3625 if ( $this->mTrxLevel
) {
3626 $this->query( 'ROLLBACK', $fname, true );
3627 $this->mTrxLevel
= 0;
3632 * Creates a new table with structure copied from existing table
3633 * Note that unlike most database abstraction functions, this function does not
3634 * automatically append database prefix, because it works at a lower
3635 * abstraction level.
3636 * The table names passed to this function shall not be quoted (this
3637 * function calls addIdentifierQuotes when needed).
3639 * @param string $oldName Name of table whose structure should be copied
3640 * @param string $newName Name of table to be created
3641 * @param bool $temporary Whether the new table should be temporary
3642 * @param string $fname Calling function name
3643 * @throws MWException
3644 * @return bool True if operation was successful
3646 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3649 throw new MWException(
3650 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3654 * List all tables on the database
3656 * @param string $prefix Only show tables with this prefix, e.g. mw_
3657 * @param string $fname Calling function name
3658 * @throws MWException
3661 function listTables( $prefix = null, $fname = __METHOD__
) {
3662 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3666 * Reset the views process cache set by listViews()
3669 final public function clearViewsCache() {
3670 $this->allViews
= null;
3674 * Lists all the VIEWs in the database
3676 * For caching purposes the list of all views should be stored in
3677 * $this->allViews. The process cache can be cleared with clearViewsCache()
3679 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3680 * @param string $fname Name of calling function
3681 * @throws MWException
3685 public function listViews( $prefix = null, $fname = __METHOD__
) {
3686 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3690 * Differentiates between a TABLE and a VIEW
3692 * @param string $name Name of the database-structure to test.
3693 * @throws MWException
3697 public function isView( $name ) {
3698 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3702 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3703 * to the format used for inserting into timestamp fields in this DBMS.
3705 * The result is unquoted, and needs to be passed through addQuotes()
3706 * before it can be included in raw SQL.
3708 * @param string|int $ts
3712 public function timestamp( $ts = 0 ) {
3713 return wfTimestamp( TS_MW
, $ts );
3717 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3718 * to the format used for inserting into timestamp fields in this DBMS. If
3719 * NULL is input, it is passed through, allowing NULL values to be inserted
3720 * into timestamp fields.
3722 * The result is unquoted, and needs to be passed through addQuotes()
3723 * before it can be included in raw SQL.
3725 * @param string|int $ts
3729 public function timestampOrNull( $ts = null ) {
3730 if ( is_null( $ts ) ) {
3733 return $this->timestamp( $ts );
3738 * Take the result from a query, and wrap it in a ResultWrapper if
3739 * necessary. Boolean values are passed through as is, to indicate success
3740 * of write queries or failure.
3742 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3743 * resource, and it was necessary to call this function to convert it to
3744 * a wrapper. Nowadays, raw database objects are never exposed to external
3745 * callers, so this is unnecessary in external code.
3747 * @param bool|ResultWrapper|resource|object $result
3748 * @return bool|ResultWrapper
3750 protected function resultObject( $result ) {
3753 } elseif ( $result instanceof ResultWrapper
) {
3755 } elseif ( $result === true ) {
3756 // Successful write query
3759 return new ResultWrapper( $this, $result );
3764 * Ping the server and try to reconnect if it there is no connection
3766 * @return bool Success or failure
3768 public function ping() {
3769 # Stub. Not essential to override.
3774 * Get slave lag. Currently supported only by MySQL.
3776 * Note that this function will generate a fatal error on many
3777 * installations. Most callers should use LoadBalancer::safeGetLag()
3780 * @return int Database replication lag in seconds
3782 public function getLag() {
3787 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3791 function maxListLen() {
3796 * Some DBMSs have a special format for inserting into blob fields, they
3797 * don't allow simple quoted strings to be inserted. To insert into such
3798 * a field, pass the data through this function before passing it to
3799 * DatabaseBase::insert().
3804 public function encodeBlob( $b ) {
3809 * Some DBMSs return a special placeholder object representing blob fields
3810 * in result objects. Pass the object through this function to return the
3813 * @param string|Blob $b
3816 public function decodeBlob( $b ) {
3817 if ( $b instanceof Blob
) {
3824 * Override database's default behavior. $options include:
3825 * 'connTimeout' : Set the connection timeout value in seconds.
3826 * May be useful for very long batch queries such as
3827 * full-wiki dumps, where a single query reads out over
3830 * @param array $options
3833 public function setSessionOptions( array $options ) {
3837 * Read and execute SQL commands from a file.
3839 * Returns true on success, error string or exception on failure (depending
3840 * on object's error ignore settings).
3842 * @param string $filename File name to open
3843 * @param bool|callable $lineCallback Optional function called before reading each line
3844 * @param bool|callable $resultCallback Optional function called for each MySQL result
3845 * @param bool|string $fname Calling function name or false if name should be
3846 * generated dynamically using $filename
3847 * @param bool|callable $inputCallback Optional function called for each
3848 * complete line sent
3849 * @throws Exception|MWException
3850 * @return bool|string
3852 public function sourceFile(
3853 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3855 MediaWiki\
suppressWarnings();
3856 $fp = fopen( $filename, 'r' );
3857 MediaWiki\restoreWarnings
();
3859 if ( false === $fp ) {
3860 throw new MWException( "Could not open \"{$filename}\".\n" );
3864 $fname = __METHOD__
. "( $filename )";
3868 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3869 } catch ( Exception
$e ) {
3880 * Get the full path of a patch file. Originally based on archive()
3881 * from updaters.inc. Keep in mind this always returns a patch, as
3882 * it fails back to MySQL if no DB-specific patch can be found
3884 * @param string $patch The name of the patch, like patch-something.sql
3885 * @return string Full path to patch file
3887 public function patchPath( $patch ) {
3890 $dbType = $this->getType();
3891 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3892 return "$IP/maintenance/$dbType/archives/$patch";
3894 return "$IP/maintenance/archives/$patch";
3899 * Set variables to be used in sourceFile/sourceStream, in preference to the
3900 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3901 * all. If it's set to false, $GLOBALS will be used.
3903 * @param bool|array $vars Mapping variable name to value.
3905 public function setSchemaVars( $vars ) {
3906 $this->mSchemaVars
= $vars;
3910 * Read and execute commands from an open file handle.
3912 * Returns true on success, error string or exception on failure (depending
3913 * on object's error ignore settings).
3915 * @param resource $fp File handle
3916 * @param bool|callable $lineCallback Optional function called before reading each query
3917 * @param bool|callable $resultCallback Optional function called for each MySQL result
3918 * @param string $fname Calling function name
3919 * @param bool|callable $inputCallback Optional function called for each complete query sent
3920 * @return bool|string
3922 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3923 $fname = __METHOD__
, $inputCallback = false
3927 while ( !feof( $fp ) ) {
3928 if ( $lineCallback ) {
3929 call_user_func( $lineCallback );
3932 $line = trim( fgets( $fp ) );
3934 if ( $line == '' ) {
3938 if ( '-' == $line[0] && '-' == $line[1] ) {
3946 $done = $this->streamStatementEnd( $cmd, $line );
3950 if ( $done ||
feof( $fp ) ) {
3951 $cmd = $this->replaceVars( $cmd );
3953 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3954 $res = $this->query( $cmd, $fname );
3956 if ( $resultCallback ) {
3957 call_user_func( $resultCallback, $res, $this );
3960 if ( false === $res ) {
3961 $err = $this->lastError();
3963 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3974 * Called by sourceStream() to check if we've reached a statement end
3976 * @param string $sql SQL assembled so far
3977 * @param string $newLine New line about to be added to $sql
3978 * @return bool Whether $newLine contains end of the statement
3980 public function streamStatementEnd( &$sql, &$newLine ) {
3981 if ( $this->delimiter
) {
3983 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3984 if ( $newLine != $prev ) {
3993 * Database independent variable replacement. Replaces a set of variables
3994 * in an SQL statement with their contents as given by $this->getSchemaVars().
3996 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3998 * - '{$var}' should be used for text and is passed through the database's
4000 * - `{$var}` should be used for identifiers (e.g. table and database names).
4001 * It is passed through the database's addIdentifierQuotes method which
4002 * can be overridden if the database uses something other than backticks.
4003 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4004 * database's tableName method.
4005 * - / *i* / passes the name that follows through the database's indexName method.
4006 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4007 * its use should be avoided. In 1.24 and older, string encoding was applied.
4009 * @param string $ins SQL statement to replace variables in
4010 * @return string The new SQL statement with variables replaced
4012 protected function replaceVars( $ins ) {
4014 $vars = $this->getSchemaVars();
4015 return preg_replace_callback(
4017 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4018 \'\{\$ (\w+) }\' | # 3. addQuotes
4019 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4020 /\*\$ (\w+) \*/ # 5. leave unencoded
4022 function ( $m ) use ( $that, $vars ) {
4023 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4024 // check for both nonexistent keys *and* the empty string.
4025 if ( isset( $m[1] ) && $m[1] !== '' ) {
4026 if ( $m[1] === 'i' ) {
4027 return $that->indexName( $m[2] );
4029 return $that->tableName( $m[2] );
4031 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4032 return $that->addQuotes( $vars[$m[3]] );
4033 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4034 return $that->addIdentifierQuotes( $vars[$m[4]] );
4035 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4036 return $vars[$m[5]];
4046 * Get schema variables. If none have been set via setSchemaVars(), then
4047 * use some defaults from the current object.
4051 protected function getSchemaVars() {
4052 if ( $this->mSchemaVars
) {
4053 return $this->mSchemaVars
;
4055 return $this->getDefaultSchemaVars();
4060 * Get schema variables to use if none have been set via setSchemaVars().
4062 * Override this in derived classes to provide variables for tables.sql
4063 * and SQL patch files.
4067 protected function getDefaultSchemaVars() {
4072 * Check to see if a named lock is available (non-blocking)
4074 * @param string $lockName Name of lock to poll
4075 * @param string $method Name of method calling us
4079 public function lockIsFree( $lockName, $method ) {
4084 * Acquire a named lock
4086 * Named locks are not related to transactions
4088 * @param string $lockName Name of lock to aquire
4089 * @param string $method Name of method calling us
4090 * @param int $timeout
4093 public function lock( $lockName, $method, $timeout = 5 ) {
4100 * Named locks are not related to transactions
4102 * @param string $lockName Name of lock to release
4103 * @param string $method Name of method calling us
4105 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4106 * by this thread (in which case the lock is not released), and NULL if the named
4107 * lock did not exist
4109 public function unlock( $lockName, $method ) {
4114 * Check to see if a named lock used by lock() use blocking queues
4119 public function namedLocksEnqueue() {
4124 * Lock specific tables
4126 * @param array $read Array of tables to lock for read access
4127 * @param array $write Array of tables to lock for write access
4128 * @param string $method Name of caller
4129 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4132 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4137 * Unlock specific tables
4139 * @param string $method The caller
4142 public function unlockTables( $method ) {
4148 * @param string $tableName
4149 * @param string $fName
4150 * @return bool|ResultWrapper
4153 public function dropTable( $tableName, $fName = __METHOD__
) {
4154 if ( !$this->tableExists( $tableName, $fName ) ) {
4157 $sql = "DROP TABLE " . $this->tableName( $tableName );
4158 if ( $this->cascadingDeletes() ) {
4162 return $this->query( $sql, $fName );
4166 * Get search engine class. All subclasses of this need to implement this
4167 * if they wish to use searching.
4171 public function getSearchEngine() {
4172 return 'SearchEngineDummy';
4176 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4177 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4178 * because "i" sorts after all numbers.
4182 public function getInfinity() {
4187 * Encode an expiry time into the DBMS dependent format
4189 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4192 public function encodeExpiry( $expiry ) {
4193 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4194 ?
$this->getInfinity()
4195 : $this->timestamp( $expiry );
4199 * Decode an expiry time into a DBMS independent format
4201 * @param string $expiry DB timestamp field value for expiry
4202 * @param int $format TS_* constant, defaults to TS_MW
4205 public function decodeExpiry( $expiry, $format = TS_MW
) {
4206 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4208 : wfTimestamp( $format, $expiry );
4212 * Allow or deny "big selects" for this session only. This is done by setting
4213 * the sql_big_selects session variable.
4215 * This is a MySQL-specific feature.
4217 * @param bool|string $value True for allow, false for deny, or "default" to
4218 * restore the initial value
4220 public function setBigSelects( $value = true ) {
4228 public function __toString() {
4229 return (string)$this->mConn
;
4233 * Run a few simple sanity checks
4235 public function __destruct() {
4236 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4237 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4239 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4241 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4242 $callers[] = $callbackInfo[1];
4244 $callers = implode( ', ', $callers );
4245 trigger_error( "DB transaction callbacks still pending (from $callers)." );