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;
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 $this->mTrxAtomicLevels
= new SplStack
;
614 $server = $params['host'];
615 $user = $params['user'];
616 $password = $params['password'];
617 $dbName = $params['dbname'];
618 $flags = $params['flags'];
619 $tablePrefix = $params['tablePrefix'];
620 $schema = $params['schema'];
621 $foreign = $params['foreign'];
623 $this->mFlags
= $flags;
624 if ( $this->mFlags
& DBO_DEFAULT
) {
625 if ( $wgCommandLineMode ) {
626 $this->mFlags
&= ~DBO_TRX
;
627 if ( $wgDebugDBTransactions ) {
628 wfDebug( "Implicit transaction open disabled.\n" );
631 $this->mFlags |
= DBO_TRX
;
632 if ( $wgDebugDBTransactions ) {
633 wfDebug( "Implicit transaction open enabled.\n" );
638 $this->mSessionVars
= $params['variables'];
640 /** Get the default table prefix*/
641 if ( $tablePrefix === 'get from global' ) {
642 $this->mTablePrefix
= $wgDBprefix;
644 $this->mTablePrefix
= $tablePrefix;
647 /** Get the database schema*/
648 if ( $schema === 'get from global' ) {
649 $this->mSchema
= $wgDBmwschema;
651 $this->mSchema
= $schema;
654 $this->mForeign
= $foreign;
656 if ( isset( $params['trxProfiler'] ) ) {
657 $this->trxProfiler
= $params['trxProfiler']; // override
661 $this->open( $server, $user, $password, $dbName );
666 * Called by serialize. Throw an exception when DB connection is serialized.
667 * This causes problems on some database engines because the connection is
668 * not restored on unserialize.
670 public function __sleep() {
671 throw new MWException( 'Database serialization may cause problems, since ' .
672 'the connection is not restored on wakeup.' );
676 * Given a DB type, construct the name of the appropriate child class of
677 * DatabaseBase. This is designed to replace all of the manual stuff like:
678 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
679 * as well as validate against the canonical list of DB types we have
681 * This factory function is mostly useful for when you need to connect to a
682 * database other than the MediaWiki default (such as for external auth,
683 * an extension, et cetera). Do not use this to connect to the MediaWiki
684 * database. Example uses in core:
685 * @see LoadBalancer::reallyOpenConnection()
686 * @see ForeignDBRepo::getMasterDB()
687 * @see WebInstallerDBConnect::execute()
691 * @param string $dbType A possible DB type
692 * @param array $p An array of options to pass to the constructor.
693 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
694 * @throws MWException If the database driver or extension cannot be found
695 * @return DatabaseBase|null DatabaseBase subclass or null
697 final public static function factory( $dbType, $p = array() ) {
698 $canonicalDBTypes = array(
699 'mysql' => array( 'mysqli', 'mysql' ),
700 'postgres' => array(),
707 $dbType = strtolower( $dbType );
708 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
709 $possibleDrivers = $canonicalDBTypes[$dbType];
710 if ( !empty( $p['driver'] ) ) {
711 if ( in_array( $p['driver'], $possibleDrivers ) ) {
712 $driver = $p['driver'];
714 throw new MWException( __METHOD__
.
715 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
718 foreach ( $possibleDrivers as $posDriver ) {
719 if ( extension_loaded( $posDriver ) ) {
720 $driver = $posDriver;
728 if ( $driver === false ) {
729 throw new MWException( __METHOD__
.
730 " no viable database extension found for type '$dbType'" );
733 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
734 // and everything else doesn't use a schema (e.g. null)
735 // Although postgres and oracle support schemas, we don't use them (yet)
736 // to maintain backwards compatibility
737 $defaultSchemas = array(
738 'mssql' => 'get from global',
741 $class = 'Database' . ucfirst( $driver );
742 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
743 // Resolve some defaults for b/c
744 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
745 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
746 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
747 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
748 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
749 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
750 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
751 if ( !isset( $p['schema'] ) ) {
752 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
754 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
756 return new $class( $p );
762 protected function installErrorHandler() {
763 $this->mPHPError
= false;
764 $this->htmlErrors
= ini_set( 'html_errors', '0' );
765 set_error_handler( array( $this, 'connectionErrorHandler' ) );
769 * @return bool|string
771 protected function restoreErrorHandler() {
772 restore_error_handler();
773 if ( $this->htmlErrors
!== false ) {
774 ini_set( 'html_errors', $this->htmlErrors
);
776 if ( $this->mPHPError
) {
777 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
778 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
788 * @param string $errstr
790 public function connectionErrorHandler( $errno, $errstr ) {
791 $this->mPHPError
= $errstr;
795 * Create a log context to pass to wfLogDBError or other logging functions.
797 * @param array $extras Additional data to add to context
800 protected function getLogContext( array $extras = array() ) {
803 'db_server' => $this->mServer
,
804 'db_name' => $this->mDBname
,
805 'db_user' => $this->mUser
,
812 * Closes a database connection.
813 * if it is open : commits any open transactions
815 * @throws MWException
816 * @return bool Operation success. true if already closed.
818 public function close() {
819 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
820 throw new MWException( "Transaction idle callbacks still pending." );
822 if ( $this->mConn
) {
823 if ( $this->trxLevel() ) {
824 if ( !$this->mTrxAutomatic
) {
825 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
826 " performing implicit commit before closing connection!" );
829 $this->commit( __METHOD__
, 'flush' );
832 $closed = $this->closeConnection();
833 $this->mConn
= false;
837 $this->mOpened
= false;
843 * Make sure isOpen() returns true as a sanity check
845 * @throws DBUnexpectedError
847 protected function assertOpen() {
848 if ( !$this->isOpen() ) {
849 throw new DBUnexpectedError( $this, "DB connection was already closed." );
854 * Closes underlying database connection
856 * @return bool Whether connection was closed successfully
858 abstract protected function closeConnection();
861 * @param string $error Fallback error message, used if none is given by DB
862 * @throws DBConnectionError
864 function reportConnectionError( $error = 'Unknown error' ) {
865 $myError = $this->lastError();
871 throw new DBConnectionError( $this, $error );
875 * The DBMS-dependent part of query()
877 * @param string $sql SQL query.
878 * @return ResultWrapper|bool Result object to feed to fetchObject,
879 * fetchRow, ...; or false on failure
881 abstract protected function doQuery( $sql );
884 * Determine whether a query writes to the DB.
885 * Should return true if unsure.
890 protected function isWriteQuery( $sql ) {
891 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
895 * Determine whether a SQL statement is sensitive to isolation level.
896 * A SQL statement is considered transactable if its result could vary
897 * depending on the transaction isolation level. Operational commands
898 * such as 'SET' and 'SHOW' are not considered to be transactable.
903 protected function isTransactableQuery( $sql ) {
904 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
905 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
909 * Run an SQL query and return the result. Normally throws a DBQueryError
910 * on failure. If errors are ignored, returns false instead.
912 * In new code, the query wrappers select(), insert(), update(), delete(),
913 * etc. should be used where possible, since they give much better DBMS
914 * independence and automatically quote or validate user input in a variety
915 * of contexts. This function is generally only useful for queries which are
916 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
919 * However, the query wrappers themselves should call this function.
921 * @param string $sql SQL query
922 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
923 * comment (you can use __METHOD__ or add some extra info)
924 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
925 * maybe best to catch the exception instead?
926 * @throws MWException
927 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
928 * for a successful read query, or false on failure if $tempIgnore set
930 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
931 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
933 $this->mLastQuery
= $sql;
935 $isWriteQuery = $this->isWriteQuery( $sql );
936 if ( $isWriteQuery ) {
937 if ( !$this->mDoneWrites
) {
938 wfDebug( __METHOD__
. ': Writes done: ' .
939 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
941 # Set a flag indicating that writes have been done
942 $this->mDoneWrites
= microtime( true );
945 # Add a comment for easy SHOW PROCESSLIST interpretation
946 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
947 $userName = $wgUser->getName();
948 if ( mb_strlen( $userName ) > 15 ) {
949 $userName = mb_substr( $userName, 0, 15 ) . '...';
951 $userName = str_replace( '/', '', $userName );
956 // Add trace comment to the begin of the sql string, right after the operator.
957 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
958 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
960 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
961 if ( $wgDebugDBTransactions ) {
962 wfDebug( "Implicit transaction start.\n" );
964 $this->begin( __METHOD__
. " ($fname)" );
965 $this->mTrxAutomatic
= true;
968 # Keep track of whether the transaction has write queries pending
969 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
970 $this->mTrxDoneWrites
= true;
971 $this->getTransactionProfiler()->transactionWritingIn(
972 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
975 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
976 # generalizeSQL will probably cut down the query to reasonable
977 # logging size most of the time. The substr is really just a sanity check.
979 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
980 $totalProf = 'DatabaseBase::query-master';
982 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
983 $totalProf = 'DatabaseBase::query';
985 # Include query transaction state
986 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
988 $profiler = Profiler
::instance();
989 if ( !$profiler instanceof ProfilerStub
) {
990 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
991 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
994 if ( $this->debug() ) {
998 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1000 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1002 $master = $isMaster ?
'master' : 'slave';
1003 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1006 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1008 # Avoid fatals if close() was called
1009 $this->assertOpen();
1011 # Do the query and handle errors
1012 $startTime = microtime( true );
1013 $ret = $this->doQuery( $commentedSql );
1014 $queryRuntime = microtime( true ) - $startTime;
1015 # Log the query time and feed it into the DB trx profiler
1016 $this->getTransactionProfiler()->recordQueryCompletion(
1017 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1019 MWDebug
::queryTime( $queryId );
1021 # Try reconnecting if the connection was lost
1022 if ( false === $ret && $this->wasErrorReissuable() ) {
1023 # Transaction is gone, like it or not
1024 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1025 $this->mTrxLevel
= 0;
1026 $this->mTrxIdleCallbacks
= array(); // bug 65263
1027 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1028 wfDebug( "Connection lost, reconnecting...\n" );
1029 # Stash the last error values since ping() might clear them
1030 $lastError = $this->lastError();
1031 $lastErrno = $this->lastErrno();
1032 if ( $this->ping() ) {
1033 wfDebug( "Reconnected\n" );
1034 $server = $this->getServer();
1035 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1036 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1039 # Leave $ret as false and let an error be reported.
1040 # Callers may catch the exception and continue to use the DB.
1041 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1043 # Should be safe to silently retry (no trx and thus no callbacks)
1044 $startTime = microtime( true );
1045 $ret = $this->doQuery( $commentedSql );
1046 $queryRuntime = microtime( true ) - $startTime;
1047 # Log the query time and feed it into the DB trx profiler
1048 $this->getTransactionProfiler()->recordQueryCompletion(
1049 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1052 wfDebug( "Failed\n" );
1056 if ( false === $ret ) {
1057 $this->reportQueryError(
1058 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1061 $res = $this->resultObject( $ret );
1063 // Destroy profile sections in the opposite order to their creation
1064 $queryProfSection = false;
1065 $totalProfSection = false;
1067 if ( $isWriteQuery && $this->mTrxLevel
) {
1068 $this->mTrxWriteDuration +
= $queryRuntime;
1075 * Report a query error. Log the error, and if neither the object ignore
1076 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1078 * @param string $error
1080 * @param string $sql
1081 * @param string $fname
1082 * @param bool $tempIgnore
1083 * @throws DBQueryError
1085 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1086 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1087 wfDebug( "SQL ERROR (ignored): $error\n" );
1089 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1091 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1092 $this->getLogContext( array(
1093 'method' => __METHOD__
,
1096 'sql1line' => $sql1line,
1100 wfDebug( "SQL ERROR: " . $error . "\n" );
1101 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1106 * Intended to be compatible with the PEAR::DB wrapper functions.
1107 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1109 * ? = scalar value, quoted as necessary
1110 * ! = raw SQL bit (a function for instance)
1111 * & = filename; reads the file and inserts as a blob
1112 * (we don't use this though...)
1114 * @param string $sql
1115 * @param string $func
1119 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1120 /* MySQL doesn't support prepared statements (yet), so just
1121 * pack up the query for reference. We'll manually replace
1124 return array( 'query' => $sql, 'func' => $func );
1128 * Free a prepared query, generated by prepare().
1129 * @param string $prepared
1131 protected function freePrepared( $prepared ) {
1132 /* No-op by default */
1136 * Execute a prepared query with the various arguments
1137 * @param string $prepared The prepared sql
1138 * @param mixed $args Either an array here, or put scalars as varargs
1140 * @return ResultWrapper
1142 public function execute( $prepared, $args = null ) {
1143 if ( !is_array( $args ) ) {
1145 $args = func_get_args();
1146 array_shift( $args );
1149 $sql = $this->fillPrepared( $prepared['query'], $args );
1151 return $this->query( $sql, $prepared['func'] );
1155 * For faking prepared SQL statements on DBs that don't support it directly.
1157 * @param string $preparedQuery A 'preparable' SQL statement
1158 * @param array $args Array of Arguments to fill it with
1159 * @return string Executable SQL
1161 public function fillPrepared( $preparedQuery, $args ) {
1163 $this->preparedArgs
=& $args;
1165 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1166 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1170 * preg_callback func for fillPrepared()
1171 * The arguments should be in $this->preparedArgs and must not be touched
1172 * while we're doing this.
1174 * @param array $matches
1175 * @throws DBUnexpectedError
1178 protected function fillPreparedArg( $matches ) {
1179 switch ( $matches[1] ) {
1188 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1190 switch ( $matches[1] ) {
1192 return $this->addQuotes( $arg );
1196 # return $this->addQuotes( file_get_contents( $arg ) );
1197 throw new DBUnexpectedError(
1199 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1202 throw new DBUnexpectedError(
1204 'Received invalid match. This should never happen!'
1210 * Free a result object returned by query() or select(). It's usually not
1211 * necessary to call this, just use unset() or let the variable holding
1212 * the result object go out of scope.
1214 * @param mixed $res A SQL result
1216 public function freeResult( $res ) {
1220 * A SELECT wrapper which returns a single field from a single result row.
1222 * Usually throws a DBQueryError on failure. If errors are explicitly
1223 * ignored, returns false on failure.
1225 * If no result rows are returned from the query, false is returned.
1227 * @param string|array $table Table name. See DatabaseBase::select() for details.
1228 * @param string $var The field name to select. This must be a valid SQL
1229 * fragment: do not use unvalidated user input.
1230 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1231 * @param string $fname The function name of the caller.
1232 * @param string|array $options The query options. See DatabaseBase::select() for details.
1234 * @return bool|mixed The value from the field, or false on failure.
1236 public function selectField(
1237 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1239 if ( $var === '*' ) { // sanity
1240 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1243 if ( !is_array( $options ) ) {
1244 $options = array( $options );
1247 $options['LIMIT'] = 1;
1249 $res = $this->select( $table, $var, $cond, $fname, $options );
1250 if ( $res === false ||
!$this->numRows( $res ) ) {
1254 $row = $this->fetchRow( $res );
1256 if ( $row !== false ) {
1257 return reset( $row );
1264 * A SELECT wrapper which returns a list of single field values from result rows.
1266 * Usually throws a DBQueryError on failure. If errors are explicitly
1267 * ignored, returns false on failure.
1269 * If no result rows are returned from the query, false is returned.
1271 * @param string|array $table Table name. See DatabaseBase::select() for details.
1272 * @param string $var The field name to select. This must be a valid SQL
1273 * fragment: do not use unvalidated user input.
1274 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1275 * @param string $fname The function name of the caller.
1276 * @param string|array $options The query options. See DatabaseBase::select() for details.
1278 * @return bool|array The values from the field, or false on failure
1279 * @throws DBUnexpectedError
1282 public function selectFieldValues(
1283 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1285 if ( $var === '*' ) { // sanity
1286 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1289 if ( !is_array( $options ) ) {
1290 $options = array( $options );
1293 $res = $this->select( $table, $var, $cond, $fname, $options );
1294 if ( $res === false ) {
1299 foreach ( $res as $row ) {
1300 $values[] = $row->$var;
1307 * Returns an optional USE INDEX clause to go after the table, and a
1308 * string to go at the end of the query.
1310 * @param array $options Associative array of options to be turned into
1311 * an SQL query, valid keys are listed in the function.
1313 * @see DatabaseBase::select()
1315 public function makeSelectOptions( $options ) {
1316 $preLimitTail = $postLimitTail = '';
1319 $noKeyOptions = array();
1321 foreach ( $options as $key => $option ) {
1322 if ( is_numeric( $key ) ) {
1323 $noKeyOptions[$option] = true;
1327 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1329 $preLimitTail .= $this->makeOrderBy( $options );
1331 // if (isset($options['LIMIT'])) {
1332 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1333 // isset($options['OFFSET']) ? $options['OFFSET']
1337 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1338 $postLimitTail .= ' FOR UPDATE';
1341 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1342 $postLimitTail .= ' LOCK IN SHARE MODE';
1345 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1346 $startOpts .= 'DISTINCT';
1349 # Various MySQL extensions
1350 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1351 $startOpts .= ' /*! STRAIGHT_JOIN */';
1354 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1355 $startOpts .= ' HIGH_PRIORITY';
1358 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1359 $startOpts .= ' SQL_BIG_RESULT';
1362 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1363 $startOpts .= ' SQL_BUFFER_RESULT';
1366 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1367 $startOpts .= ' SQL_SMALL_RESULT';
1370 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1371 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1374 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1375 $startOpts .= ' SQL_CACHE';
1378 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1379 $startOpts .= ' SQL_NO_CACHE';
1382 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1383 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1388 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1392 * Returns an optional GROUP BY with an optional HAVING
1394 * @param array $options Associative array of options
1396 * @see DatabaseBase::select()
1399 public function makeGroupByWithHaving( $options ) {
1401 if ( isset( $options['GROUP BY'] ) ) {
1402 $gb = is_array( $options['GROUP BY'] )
1403 ?
implode( ',', $options['GROUP BY'] )
1404 : $options['GROUP BY'];
1405 $sql .= ' GROUP BY ' . $gb;
1407 if ( isset( $options['HAVING'] ) ) {
1408 $having = is_array( $options['HAVING'] )
1409 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1410 : $options['HAVING'];
1411 $sql .= ' HAVING ' . $having;
1418 * Returns an optional ORDER BY
1420 * @param array $options Associative array of options
1422 * @see DatabaseBase::select()
1425 public function makeOrderBy( $options ) {
1426 if ( isset( $options['ORDER BY'] ) ) {
1427 $ob = is_array( $options['ORDER BY'] )
1428 ?
implode( ',', $options['ORDER BY'] )
1429 : $options['ORDER BY'];
1431 return ' ORDER BY ' . $ob;
1438 * Execute a SELECT query constructed using the various parameters provided.
1439 * See below for full details of the parameters.
1441 * @param string|array $table Table name
1442 * @param string|array $vars Field names
1443 * @param string|array $conds Conditions
1444 * @param string $fname Caller function name
1445 * @param array $options Query options
1446 * @param array $join_conds Join conditions
1449 * @param string|array $table
1451 * May be either an array of table names, or a single string holding a table
1452 * name. If an array is given, table aliases can be specified, for example:
1454 * array( 'a' => 'user' )
1456 * This includes the user table in the query, with the alias "a" available
1457 * for use in field names (e.g. a.user_name).
1459 * All of the table names given here are automatically run through
1460 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1461 * added, and various other table name mappings to be performed.
1464 * @param string|array $vars
1466 * May be either a field name or an array of field names. The field names
1467 * can be complete fragments of SQL, for direct inclusion into the SELECT
1468 * query. If an array is given, field aliases can be specified, for example:
1470 * array( 'maxrev' => 'MAX(rev_id)' )
1472 * This includes an expression with the alias "maxrev" in the query.
1474 * If an expression is given, care must be taken to ensure that it is
1478 * @param string|array $conds
1480 * May be either a string containing a single condition, or an array of
1481 * conditions. If an array is given, the conditions constructed from each
1482 * element are combined with AND.
1484 * Array elements may take one of two forms:
1486 * - Elements with a numeric key are interpreted as raw SQL fragments.
1487 * - Elements with a string key are interpreted as equality conditions,
1488 * where the key is the field name.
1489 * - If the value of such an array element is a scalar (such as a
1490 * string), it will be treated as data and thus quoted appropriately.
1491 * If it is null, an IS NULL clause will be added.
1492 * - If the value is an array, an IN (...) clause will be constructed
1493 * from its non-null elements, and an IS NULL clause will be added
1494 * if null is present, such that the field may match any of the
1495 * elements in the array. The non-null elements will be quoted.
1497 * Note that expressions are often DBMS-dependent in their syntax.
1498 * DBMS-independent wrappers are provided for constructing several types of
1499 * expression commonly used in condition queries. See:
1500 * - DatabaseBase::buildLike()
1501 * - DatabaseBase::conditional()
1504 * @param string|array $options
1506 * Optional: Array of query options. Boolean options are specified by
1507 * including them in the array as a string value with a numeric key, for
1510 * array( 'FOR UPDATE' )
1512 * The supported options are:
1514 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1515 * with LIMIT can theoretically be used for paging through a result set,
1516 * but this is discouraged in MediaWiki for performance reasons.
1518 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1519 * and then the first rows are taken until the limit is reached. LIMIT
1520 * is applied to a result set after OFFSET.
1522 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1523 * changed until the next COMMIT.
1525 * - DISTINCT: Boolean: return only unique result rows.
1527 * - GROUP BY: May be either an SQL fragment string naming a field or
1528 * expression to group by, or an array of such SQL fragments.
1530 * - HAVING: May be either an string containing a HAVING clause or an array of
1531 * conditions building the HAVING clause. If an array is given, the conditions
1532 * constructed from each element are combined with AND.
1534 * - ORDER BY: May be either an SQL fragment giving a field name or
1535 * expression to order by, or an array of such SQL fragments.
1537 * - USE INDEX: This may be either a string giving the index name to use
1538 * for the query, or an array. If it is an associative array, each key
1539 * gives the table name (or alias), each value gives the index name to
1540 * use for that table. All strings are SQL fragments and so should be
1541 * validated by the caller.
1543 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1544 * instead of SELECT.
1546 * And also the following boolean MySQL extensions, see the MySQL manual
1547 * for documentation:
1549 * - LOCK IN SHARE MODE
1553 * - SQL_BUFFER_RESULT
1554 * - SQL_SMALL_RESULT
1555 * - SQL_CALC_FOUND_ROWS
1560 * @param string|array $join_conds
1562 * Optional associative array of table-specific join conditions. In the
1563 * most common case, this is unnecessary, since the join condition can be
1564 * in $conds. However, it is useful for doing a LEFT JOIN.
1566 * The key of the array contains the table name or alias. The value is an
1567 * array with two elements, numbered 0 and 1. The first gives the type of
1568 * join, the second is an SQL fragment giving the join condition for that
1569 * table. For example:
1571 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1573 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1574 * with no rows in it will be returned. If there was a query error, a
1575 * DBQueryError exception will be thrown, except if the "ignore errors"
1576 * option was set, in which case false will be returned.
1578 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1579 $options = array(), $join_conds = array() ) {
1580 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1582 return $this->query( $sql, $fname );
1586 * The equivalent of DatabaseBase::select() except that the constructed SQL
1587 * is returned, instead of being immediately executed. This can be useful for
1588 * doing UNION queries, where the SQL text of each query is needed. In general,
1589 * however, callers outside of Database classes should just use select().
1591 * @param string|array $table Table name
1592 * @param string|array $vars Field names
1593 * @param string|array $conds Conditions
1594 * @param string $fname Caller function name
1595 * @param string|array $options Query options
1596 * @param string|array $join_conds Join conditions
1598 * @return string SQL query string.
1599 * @see DatabaseBase::select()
1601 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1602 $options = array(), $join_conds = array()
1604 if ( is_array( $vars ) ) {
1605 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1608 $options = (array)$options;
1609 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1610 ?
$options['USE INDEX']
1613 if ( is_array( $table ) ) {
1615 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1616 } elseif ( $table != '' ) {
1617 if ( $table[0] == ' ' ) {
1618 $from = ' FROM ' . $table;
1621 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1627 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1628 $this->makeSelectOptions( $options );
1630 if ( !empty( $conds ) ) {
1631 if ( is_array( $conds ) ) {
1632 $conds = $this->makeList( $conds, LIST_AND
);
1634 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1636 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1639 if ( isset( $options['LIMIT'] ) ) {
1640 $sql = $this->limitResult( $sql, $options['LIMIT'],
1641 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1643 $sql = "$sql $postLimitTail";
1645 if ( isset( $options['EXPLAIN'] ) ) {
1646 $sql = 'EXPLAIN ' . $sql;
1653 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1654 * that a single row object is returned. If the query returns no rows,
1655 * false is returned.
1657 * @param string|array $table Table name
1658 * @param string|array $vars Field names
1659 * @param array $conds Conditions
1660 * @param string $fname Caller function name
1661 * @param string|array $options Query options
1662 * @param array|string $join_conds Join conditions
1664 * @return stdClass|bool
1666 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1667 $options = array(), $join_conds = array()
1669 $options = (array)$options;
1670 $options['LIMIT'] = 1;
1671 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1673 if ( $res === false ) {
1677 if ( !$this->numRows( $res ) ) {
1681 $obj = $this->fetchObject( $res );
1687 * Estimate the number of rows in dataset
1689 * MySQL allows you to estimate the number of rows that would be returned
1690 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1691 * index cardinality statistics, and is notoriously inaccurate, especially
1692 * when large numbers of rows have recently been added or deleted.
1694 * For DBMSs that don't support fast result size estimation, this function
1695 * will actually perform the SELECT COUNT(*).
1697 * Takes the same arguments as DatabaseBase::select().
1699 * @param string $table Table name
1700 * @param string $vars Unused
1701 * @param array|string $conds Filters on the table
1702 * @param string $fname Function name for profiling
1703 * @param array $options Options for select
1704 * @return int Row count
1706 public function estimateRowCount(
1707 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1710 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1713 $row = $this->fetchRow( $res );
1714 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1721 * Get the number of rows in dataset
1723 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1725 * Takes the same arguments as DatabaseBase::select().
1727 * @param string $table Table name
1728 * @param string $vars Unused
1729 * @param array|string $conds Filters on the table
1730 * @param string $fname Function name for profiling
1731 * @param array $options Options for select
1732 * @return int Row count
1735 public function selectRowCount(
1736 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1739 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1740 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1743 $row = $this->fetchRow( $res );
1744 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1751 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1752 * It's only slightly flawed. Don't use for anything important.
1754 * @param string $sql A SQL Query
1758 static function generalizeSQL( $sql ) {
1759 # This does the same as the regexp below would do, but in such a way
1760 # as to avoid crashing php on some large strings.
1761 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1763 $sql = str_replace( "\\\\", '', $sql );
1764 $sql = str_replace( "\\'", '', $sql );
1765 $sql = str_replace( "\\\"", '', $sql );
1766 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1767 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1769 # All newlines, tabs, etc replaced by single space
1770 $sql = preg_replace( '/\s+/', ' ', $sql );
1773 # except the ones surrounded by characters, e.g. l10n
1774 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1775 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1781 * Determines whether a field exists in a table
1783 * @param string $table Table name
1784 * @param string $field Filed to check on that table
1785 * @param string $fname Calling function name (optional)
1786 * @return bool Whether $table has filed $field
1788 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1789 $info = $this->fieldInfo( $table, $field );
1795 * Determines whether an index exists
1796 * Usually throws a DBQueryError on failure
1797 * If errors are explicitly ignored, returns NULL on failure
1799 * @param string $table
1800 * @param string $index
1801 * @param string $fname
1804 public function indexExists( $table, $index, $fname = __METHOD__
) {
1805 if ( !$this->tableExists( $table ) ) {
1809 $info = $this->indexInfo( $table, $index, $fname );
1810 if ( is_null( $info ) ) {
1813 return $info !== false;
1818 * Query whether a given table exists
1820 * @param string $table
1821 * @param string $fname
1824 public function tableExists( $table, $fname = __METHOD__
) {
1825 $table = $this->tableName( $table );
1826 $old = $this->ignoreErrors( true );
1827 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1828 $this->ignoreErrors( $old );
1834 * Determines if a given index is unique
1836 * @param string $table
1837 * @param string $index
1841 public function indexUnique( $table, $index ) {
1842 $indexInfo = $this->indexInfo( $table, $index );
1844 if ( !$indexInfo ) {
1848 return !$indexInfo[0]->Non_unique
;
1852 * Helper for DatabaseBase::insert().
1854 * @param array $options
1857 protected function makeInsertOptions( $options ) {
1858 return implode( ' ', $options );
1862 * INSERT wrapper, inserts an array into a table.
1866 * - A single associative array. The array keys are the field names, and
1867 * the values are the values to insert. The values are treated as data
1868 * and will be quoted appropriately. If NULL is inserted, this will be
1869 * converted to a database NULL.
1870 * - An array with numeric keys, holding a list of associative arrays.
1871 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1872 * each subarray must be identical to each other, and in the same order.
1874 * $options is an array of options, with boolean options encoded as values
1875 * with numeric keys, in the same style as $options in
1876 * DatabaseBase::select(). Supported options are:
1878 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1879 * any rows which cause duplicate key errors are not inserted. It's
1880 * possible to determine how many rows were successfully inserted using
1881 * DatabaseBase::affectedRows().
1883 * @param string $table Table name. This will be passed through
1884 * DatabaseBase::tableName().
1885 * @param array $a Array of rows to insert
1886 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1887 * @param array $options Array of options
1889 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1894 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1895 # No rows to insert, easy just return now
1896 if ( !count( $a ) ) {
1900 $table = $this->tableName( $table );
1902 if ( !is_array( $options ) ) {
1903 $options = array( $options );
1907 if ( isset( $options['fileHandle'] ) ) {
1908 $fh = $options['fileHandle'];
1910 $options = $this->makeInsertOptions( $options );
1912 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1914 $keys = array_keys( $a[0] );
1917 $keys = array_keys( $a );
1920 $sql = 'INSERT ' . $options .
1921 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1925 foreach ( $a as $row ) {
1931 $sql .= '(' . $this->makeList( $row ) . ')';
1934 $sql .= '(' . $this->makeList( $a ) . ')';
1937 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1939 } elseif ( $fh !== null ) {
1943 return (bool)$this->query( $sql, $fname );
1947 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1949 * @param array $options
1952 protected function makeUpdateOptionsArray( $options ) {
1953 if ( !is_array( $options ) ) {
1954 $options = array( $options );
1959 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1960 $opts[] = $this->lowPriorityOption();
1963 if ( in_array( 'IGNORE', $options ) ) {
1971 * Make UPDATE options for the DatabaseBase::update function
1973 * @param array $options The options passed to DatabaseBase::update
1976 protected function makeUpdateOptions( $options ) {
1977 $opts = $this->makeUpdateOptionsArray( $options );
1979 return implode( ' ', $opts );
1983 * UPDATE wrapper. Takes a condition array and a SET array.
1985 * @param string $table Name of the table to UPDATE. This will be passed through
1986 * DatabaseBase::tableName().
1987 * @param array $values An array of values to SET. For each array element,
1988 * the key gives the field name, and the value gives the data to set
1989 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1990 * @param array $conds An array of conditions (WHERE). See
1991 * DatabaseBase::select() for the details of the format of condition
1992 * arrays. Use '*' to update all rows.
1993 * @param string $fname The function name of the caller (from __METHOD__),
1994 * for logging and profiling.
1995 * @param array $options An array of UPDATE options, can be:
1996 * - IGNORE: Ignore unique key conflicts
1997 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2000 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2001 $table = $this->tableName( $table );
2002 $opts = $this->makeUpdateOptions( $options );
2003 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2005 if ( $conds !== array() && $conds !== '*' ) {
2006 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2009 return $this->query( $sql, $fname );
2013 * Makes an encoded list of strings from an array
2015 * @param array $a Containing the data
2016 * @param int $mode Constant
2017 * - LIST_COMMA: Comma separated, no field names
2018 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2019 * documentation for $conds in DatabaseBase::select().
2020 * - LIST_OR: ORed WHERE clause (without the WHERE)
2021 * - LIST_SET: Comma separated with field names, like a SET clause
2022 * - LIST_NAMES: Comma separated field names
2023 * @throws MWException|DBUnexpectedError
2026 public function makeList( $a, $mode = LIST_COMMA
) {
2027 if ( !is_array( $a ) ) {
2028 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2034 foreach ( $a as $field => $value ) {
2036 if ( $mode == LIST_AND
) {
2038 } elseif ( $mode == LIST_OR
) {
2047 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2048 $list .= "($value)";
2049 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2051 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2052 // Remove null from array to be handled separately if found
2053 $includeNull = false;
2054 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2055 $includeNull = true;
2056 unset( $value[$nullKey] );
2058 if ( count( $value ) == 0 && !$includeNull ) {
2059 throw new MWException( __METHOD__
. ": empty input for field $field" );
2060 } elseif ( count( $value ) == 0 ) {
2061 // only check if $field is null
2062 $list .= "$field IS NULL";
2064 // IN clause contains at least one valid element
2065 if ( $includeNull ) {
2066 // Group subconditions to ensure correct precedence
2069 if ( count( $value ) == 1 ) {
2070 // Special-case single values, as IN isn't terribly efficient
2071 // Don't necessarily assume the single key is 0; we don't
2072 // enforce linear numeric ordering on other arrays here.
2073 $value = array_values( $value );
2074 $list .= $field . " = " . $this->addQuotes( $value[0] );
2076 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2078 // if null present in array, append IS NULL
2079 if ( $includeNull ) {
2080 $list .= " OR $field IS NULL)";
2083 } elseif ( $value === null ) {
2084 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2085 $list .= "$field IS ";
2086 } elseif ( $mode == LIST_SET
) {
2087 $list .= "$field = ";
2091 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2092 $list .= "$field = ";
2094 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2102 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2103 * The keys on each level may be either integers or strings.
2105 * @param array $data Organized as 2-d
2106 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2107 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2108 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2109 * @return string|bool SQL fragment, or false if no items in array
2111 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2114 foreach ( $data as $base => $sub ) {
2115 if ( count( $sub ) ) {
2116 $conds[] = $this->makeList(
2117 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2123 return $this->makeList( $conds, LIST_OR
);
2125 // Nothing to search for...
2131 * Return aggregated value alias
2133 * @param array $valuedata
2134 * @param string $valuename
2138 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2143 * @param string $field
2146 public function bitNot( $field ) {
2151 * @param string $fieldLeft
2152 * @param string $fieldRight
2155 public function bitAnd( $fieldLeft, $fieldRight ) {
2156 return "($fieldLeft & $fieldRight)";
2160 * @param string $fieldLeft
2161 * @param string $fieldRight
2164 public function bitOr( $fieldLeft, $fieldRight ) {
2165 return "($fieldLeft | $fieldRight)";
2169 * Build a concatenation list to feed into a SQL query
2170 * @param array $stringList List of raw SQL expressions; caller is
2171 * responsible for any quoting
2174 public function buildConcat( $stringList ) {
2175 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2179 * Build a GROUP_CONCAT or equivalent statement for a query.
2181 * This is useful for combining a field for several rows into a single string.
2182 * NULL values will not appear in the output, duplicated values will appear,
2183 * and the resulting delimiter-separated values have no defined sort order.
2184 * Code using the results may need to use the PHP unique() or sort() methods.
2186 * @param string $delim Glue to bind the results together
2187 * @param string|array $table Table name
2188 * @param string $field Field name
2189 * @param string|array $conds Conditions
2190 * @param string|array $join_conds Join conditions
2191 * @return string SQL text
2194 public function buildGroupConcatField(
2195 $delim, $table, $field, $conds = '', $join_conds = array()
2197 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2199 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2203 * Change the current database
2205 * @todo Explain what exactly will fail if this is not overridden.
2209 * @return bool Success or failure
2211 public function selectDB( $db ) {
2212 # Stub. Shouldn't cause serious problems if it's not overridden, but
2213 # if your database engine supports a concept similar to MySQL's
2214 # databases you may as well.
2215 $this->mDBname
= $db;
2221 * Get the current DB name
2224 public function getDBname() {
2225 return $this->mDBname
;
2229 * Get the server hostname or IP address
2232 public function getServer() {
2233 return $this->mServer
;
2237 * Format a table name ready for use in constructing an SQL query
2239 * This does two important things: it quotes the table names to clean them up,
2240 * and it adds a table prefix if only given a table name with no quotes.
2242 * All functions of this object which require a table name call this function
2243 * themselves. Pass the canonical name to such functions. This is only needed
2244 * when calling query() directly.
2246 * @param string $name Database table name
2247 * @param string $format One of:
2248 * quoted - Automatically pass the table name through addIdentifierQuotes()
2249 * so that it can be used in a query.
2250 * raw - Do not add identifier quotes to the table name
2251 * @return string Full database name
2253 public function tableName( $name, $format = 'quoted' ) {
2254 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2255 # Skip the entire process when we have a string quoted on both ends.
2256 # Note that we check the end so that we will still quote any use of
2257 # use of `database`.table. But won't break things if someone wants
2258 # to query a database table with a dot in the name.
2259 if ( $this->isQuotedIdentifier( $name ) ) {
2263 # Lets test for any bits of text that should never show up in a table
2264 # name. Basically anything like JOIN or ON which are actually part of
2265 # SQL queries, but may end up inside of the table value to combine
2266 # sql. Such as how the API is doing.
2267 # Note that we use a whitespace test rather than a \b test to avoid
2268 # any remote case where a word like on may be inside of a table name
2269 # surrounded by symbols which may be considered word breaks.
2270 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2274 # Split database and table into proper variables.
2275 # We reverse the explode so that database.table and table both output
2276 # the correct table.
2277 $dbDetails = explode( '.', $name, 3 );
2278 if ( count( $dbDetails ) == 3 ) {
2279 list( $database, $schema, $table ) = $dbDetails;
2280 # We don't want any prefix added in this case
2282 } elseif ( count( $dbDetails ) == 2 ) {
2283 list( $database, $table ) = $dbDetails;
2284 # We don't want any prefix added in this case
2285 # In dbs that support it, $database may actually be the schema
2286 # but that doesn't affect any of the functionality here
2290 list( $table ) = $dbDetails;
2291 if ( $wgSharedDB !== null # We have a shared database
2292 && $this->mForeign
== false # We're not working on a foreign database
2293 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2294 && in_array( $table, $wgSharedTables ) # A shared table is selected
2296 $database = $wgSharedDB;
2297 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2298 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2301 $schema = $this->mSchema
; # Default schema
2302 $prefix = $this->mTablePrefix
; # Default prefix
2306 # Quote $table and apply the prefix if not quoted.
2307 # $tableName might be empty if this is called from Database::replaceVars()
2308 $tableName = "{$prefix}{$table}";
2309 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2310 $tableName = $this->addIdentifierQuotes( $tableName );
2313 # Quote $schema and merge it with the table name if needed
2314 if ( strlen( $schema ) ) {
2315 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2316 $schema = $this->addIdentifierQuotes( $schema );
2318 $tableName = $schema . '.' . $tableName;
2321 # Quote $database and merge it with the table name if needed
2322 if ( $database !== null ) {
2323 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2324 $database = $this->addIdentifierQuotes( $database );
2326 $tableName = $database . '.' . $tableName;
2333 * Fetch a number of table names into an array
2334 * This is handy when you need to construct SQL for joins
2337 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2338 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2339 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2343 public function tableNames() {
2344 $inArray = func_get_args();
2347 foreach ( $inArray as $name ) {
2348 $retVal[$name] = $this->tableName( $name );
2355 * Fetch a number of table names into an zero-indexed numerical array
2356 * This is handy when you need to construct SQL for joins
2359 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2360 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2361 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2365 public function tableNamesN() {
2366 $inArray = func_get_args();
2369 foreach ( $inArray as $name ) {
2370 $retVal[] = $this->tableName( $name );
2377 * Get an aliased table name
2378 * e.g. tableName AS newTableName
2380 * @param string $name Table name, see tableName()
2381 * @param string|bool $alias Alias (optional)
2382 * @return string SQL name for aliased table. Will not alias a table to its own name
2384 public function tableNameWithAlias( $name, $alias = false ) {
2385 if ( !$alias ||
$alias == $name ) {
2386 return $this->tableName( $name );
2388 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2393 * Gets an array of aliased table names
2395 * @param array $tables Array( [alias] => table )
2396 * @return string[] See tableNameWithAlias()
2398 public function tableNamesWithAlias( $tables ) {
2400 foreach ( $tables as $alias => $table ) {
2401 if ( is_numeric( $alias ) ) {
2404 $retval[] = $this->tableNameWithAlias( $table, $alias );
2411 * Get an aliased field name
2412 * e.g. fieldName AS newFieldName
2414 * @param string $name Field name
2415 * @param string|bool $alias Alias (optional)
2416 * @return string SQL name for aliased field. Will not alias a field to its own name
2418 public function fieldNameWithAlias( $name, $alias = false ) {
2419 if ( !$alias ||
(string)$alias === (string)$name ) {
2422 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2427 * Gets an array of aliased field names
2429 * @param array $fields Array( [alias] => field )
2430 * @return string[] See fieldNameWithAlias()
2432 public function fieldNamesWithAlias( $fields ) {
2434 foreach ( $fields as $alias => $field ) {
2435 if ( is_numeric( $alias ) ) {
2438 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2445 * Get the aliased table name clause for a FROM clause
2446 * which might have a JOIN and/or USE INDEX clause
2448 * @param array $tables ( [alias] => table )
2449 * @param array $use_index Same as for select()
2450 * @param array $join_conds Same as for select()
2453 protected function tableNamesWithUseIndexOrJOIN(
2454 $tables, $use_index = array(), $join_conds = array()
2458 $use_index = (array)$use_index;
2459 $join_conds = (array)$join_conds;
2461 foreach ( $tables as $alias => $table ) {
2462 if ( !is_string( $alias ) ) {
2463 // No alias? Set it equal to the table name
2466 // Is there a JOIN clause for this table?
2467 if ( isset( $join_conds[$alias] ) ) {
2468 list( $joinType, $conds ) = $join_conds[$alias];
2469 $tableClause = $joinType;
2470 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2471 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2472 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2474 $tableClause .= ' ' . $use;
2477 $on = $this->makeList( (array)$conds, LIST_AND
);
2479 $tableClause .= ' ON (' . $on . ')';
2482 $retJOIN[] = $tableClause;
2483 } elseif ( isset( $use_index[$alias] ) ) {
2484 // Is there an INDEX clause for this table?
2485 $tableClause = $this->tableNameWithAlias( $table, $alias );
2486 $tableClause .= ' ' . $this->useIndexClause(
2487 implode( ',', (array)$use_index[$alias] )
2490 $ret[] = $tableClause;
2492 $tableClause = $this->tableNameWithAlias( $table, $alias );
2494 $ret[] = $tableClause;
2498 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2499 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2500 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2502 // Compile our final table clause
2503 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2507 * Get the name of an index in a given table.
2509 * @protected Don't use outside of DatabaseBase and childs
2510 * @param string $index
2513 public function indexName( $index ) {
2514 // @FIXME: Make this protected once we move away from PHP 5.3
2515 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2517 // Backwards-compatibility hack
2519 'ar_usertext_timestamp' => 'usertext_timestamp',
2520 'un_user_id' => 'user_id',
2521 'un_user_ip' => 'user_ip',
2524 if ( isset( $renamed[$index] ) ) {
2525 return $renamed[$index];
2532 * Adds quotes and backslashes.
2534 * @param string|Blob $s
2537 public function addQuotes( $s ) {
2538 if ( $s instanceof Blob
) {
2541 if ( $s === null ) {
2544 # This will also quote numeric values. This should be harmless,
2545 # and protects against weird problems that occur when they really
2546 # _are_ strings such as article titles and string->number->string
2547 # conversion is not 1:1.
2548 return "'" . $this->strencode( $s ) . "'";
2553 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2554 * MySQL uses `backticks` while basically everything else uses double quotes.
2555 * Since MySQL is the odd one out here the double quotes are our generic
2556 * and we implement backticks in DatabaseMysql.
2561 public function addIdentifierQuotes( $s ) {
2562 return '"' . str_replace( '"', '""', $s ) . '"';
2566 * Returns if the given identifier looks quoted or not according to
2567 * the database convention for quoting identifiers .
2569 * @param string $name
2572 public function isQuotedIdentifier( $name ) {
2573 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2580 protected function escapeLikeInternal( $s ) {
2581 return addcslashes( $s, '\%_' );
2585 * LIKE statement wrapper, receives a variable-length argument list with
2586 * parts of pattern to match containing either string literals that will be
2587 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2588 * the function could be provided with an array of aforementioned
2591 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2592 * a LIKE clause that searches for subpages of 'My page title'.
2594 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2595 * $query .= $dbr->buildLike( $pattern );
2598 * @return string Fully built LIKE statement
2600 public function buildLike() {
2601 $params = func_get_args();
2603 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2604 $params = $params[0];
2609 foreach ( $params as $value ) {
2610 if ( $value instanceof LikeMatch
) {
2611 $s .= $value->toString();
2613 $s .= $this->escapeLikeInternal( $value );
2617 return " LIKE {$this->addQuotes( $s )} ";
2621 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2625 public function anyChar() {
2626 return new LikeMatch( '_' );
2630 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2634 public function anyString() {
2635 return new LikeMatch( '%' );
2639 * Returns an appropriately quoted sequence value for inserting a new row.
2640 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2641 * subclass will return an integer, and save the value for insertId()
2643 * Any implementation of this function should *not* involve reusing
2644 * sequence numbers created for rolled-back transactions.
2645 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2646 * @param string $seqName
2649 public function nextSequenceValue( $seqName ) {
2654 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2655 * is only needed because a) MySQL must be as efficient as possible due to
2656 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2657 * which index to pick. Anyway, other databases might have different
2658 * indexes on a given table. So don't bother overriding this unless you're
2660 * @param string $index
2663 public function useIndexClause( $index ) {
2668 * REPLACE query wrapper.
2670 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2671 * except that when there is a duplicate key error, the old row is deleted
2672 * and the new row is inserted in its place.
2674 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2675 * perform the delete, we need to know what the unique indexes are so that
2676 * we know how to find the conflicting rows.
2678 * It may be more efficient to leave off unique indexes which are unlikely
2679 * to collide. However if you do this, you run the risk of encountering
2680 * errors which wouldn't have occurred in MySQL.
2682 * @param string $table The table to replace the row(s) in.
2683 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2684 * a field name or an array of field names
2685 * @param array $rows Can be either a single row to insert, or multiple rows,
2686 * in the same format as for DatabaseBase::insert()
2687 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2689 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2690 $quotedTable = $this->tableName( $table );
2692 if ( count( $rows ) == 0 ) {
2697 if ( !is_array( reset( $rows ) ) ) {
2698 $rows = array( $rows );
2701 // @FXIME: this is not atomic, but a trx would break affectedRows()
2702 foreach ( $rows as $row ) {
2703 # Delete rows which collide
2704 if ( $uniqueIndexes ) {
2705 $sql = "DELETE FROM $quotedTable WHERE ";
2707 foreach ( $uniqueIndexes as $index ) {
2714 if ( is_array( $index ) ) {
2716 foreach ( $index as $col ) {
2722 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2725 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2729 $this->query( $sql, $fname );
2732 # Now insert the row
2733 $this->insert( $table, $row, $fname );
2738 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2741 * @param string $table Table name
2742 * @param array|string $rows Row(s) to insert
2743 * @param string $fname Caller function name
2745 * @return ResultWrapper
2747 protected function nativeReplace( $table, $rows, $fname ) {
2748 $table = $this->tableName( $table );
2751 if ( !is_array( reset( $rows ) ) ) {
2752 $rows = array( $rows );
2755 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2758 foreach ( $rows as $row ) {
2765 $sql .= '(' . $this->makeList( $row ) . ')';
2768 return $this->query( $sql, $fname );
2772 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2774 * This updates any conflicting rows (according to the unique indexes) using
2775 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2777 * $rows may be either:
2778 * - A single associative array. The array keys are the field names, and
2779 * the values are the values to insert. The values are treated as data
2780 * and will be quoted appropriately. If NULL is inserted, this will be
2781 * converted to a database NULL.
2782 * - An array with numeric keys, holding a list of associative arrays.
2783 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2784 * each subarray must be identical to each other, and in the same order.
2786 * It may be more efficient to leave off unique indexes which are unlikely
2787 * to collide. However if you do this, you run the risk of encountering
2788 * errors which wouldn't have occurred in MySQL.
2790 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2795 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2796 * @param array $rows A single row or list of rows to insert
2797 * @param array $uniqueIndexes List of single field names or field name tuples
2798 * @param array $set An array of values to SET. For each array element, the
2799 * key gives the field name, and the value gives the data to set that
2800 * field to. The data will be quoted by DatabaseBase::addQuotes().
2801 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2805 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2808 if ( !count( $rows ) ) {
2809 return true; // nothing to do
2812 if ( !is_array( reset( $rows ) ) ) {
2813 $rows = array( $rows );
2816 if ( count( $uniqueIndexes ) ) {
2817 $clauses = array(); // list WHERE clauses that each identify a single row
2818 foreach ( $rows as $row ) {
2819 foreach ( $uniqueIndexes as $index ) {
2820 $index = is_array( $index ) ?
$index : array( $index ); // columns
2821 $rowKey = array(); // unique key to this row
2822 foreach ( $index as $column ) {
2823 $rowKey[$column] = $row[$column];
2825 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2828 $where = array( $this->makeList( $clauses, LIST_OR
) );
2833 $useTrx = !$this->mTrxLevel
;
2835 $this->begin( $fname );
2838 # Update any existing conflicting row(s)
2839 if ( $where !== false ) {
2840 $ok = $this->update( $table, $set, $where, $fname );
2844 # Now insert any non-conflicting row(s)
2845 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2846 } catch ( Exception
$e ) {
2848 $this->rollback( $fname );
2853 $this->commit( $fname );
2860 * DELETE where the condition is a join.
2862 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2863 * we use sub-selects
2865 * For safety, an empty $conds will not delete everything. If you want to
2866 * delete all rows where the join condition matches, set $conds='*'.
2868 * DO NOT put the join condition in $conds.
2870 * @param string $delTable The table to delete from.
2871 * @param string $joinTable The other table.
2872 * @param string $delVar The variable to join on, in the first table.
2873 * @param string $joinVar The variable to join on, in the second table.
2874 * @param array $conds Condition array of field names mapped to variables,
2875 * ANDed together in the WHERE clause
2876 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2877 * @throws DBUnexpectedError
2879 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2883 throw new DBUnexpectedError( $this,
2884 'DatabaseBase::deleteJoin() called with empty $conds' );
2887 $delTable = $this->tableName( $delTable );
2888 $joinTable = $this->tableName( $joinTable );
2889 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2890 if ( $conds != '*' ) {
2891 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2895 $this->query( $sql, $fname );
2899 * Returns the size of a text field, or -1 for "unlimited"
2901 * @param string $table
2902 * @param string $field
2905 public function textFieldSize( $table, $field ) {
2906 $table = $this->tableName( $table );
2907 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2908 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2909 $row = $this->fetchObject( $res );
2913 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2923 * A string to insert into queries to show that they're low-priority, like
2924 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2925 * string and nothing bad should happen.
2927 * @return string Returns the text of the low priority option if it is
2928 * supported, or a blank string otherwise
2930 public function lowPriorityOption() {
2935 * DELETE query wrapper.
2937 * @param array $table Table name
2938 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2939 * for the format. Use $conds == "*" to delete all rows
2940 * @param string $fname Name of the calling function
2941 * @throws DBUnexpectedError
2942 * @return bool|ResultWrapper
2944 public function delete( $table, $conds, $fname = __METHOD__
) {
2946 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2949 $table = $this->tableName( $table );
2950 $sql = "DELETE FROM $table";
2952 if ( $conds != '*' ) {
2953 if ( is_array( $conds ) ) {
2954 $conds = $this->makeList( $conds, LIST_AND
);
2956 $sql .= ' WHERE ' . $conds;
2959 return $this->query( $sql, $fname );
2963 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2964 * into another table.
2966 * @param string $destTable The table name to insert into
2967 * @param string|array $srcTable May be either a table name, or an array of table names
2968 * to include in a join.
2970 * @param array $varMap Must be an associative array of the form
2971 * array( 'dest1' => 'source1', ...). Source items may be literals
2972 * rather than field names, but strings should be quoted with
2973 * DatabaseBase::addQuotes()
2975 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2976 * the details of the format of condition arrays. May be "*" to copy the
2979 * @param string $fname The function name of the caller, from __METHOD__
2981 * @param array $insertOptions Options for the INSERT part of the query, see
2982 * DatabaseBase::insert() for details.
2983 * @param array $selectOptions Options for the SELECT part of the query, see
2984 * DatabaseBase::select() for details.
2986 * @return ResultWrapper
2988 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2989 $fname = __METHOD__
,
2990 $insertOptions = array(), $selectOptions = array()
2992 $destTable = $this->tableName( $destTable );
2994 if ( !is_array( $insertOptions ) ) {
2995 $insertOptions = array( $insertOptions );
2998 $insertOptions = $this->makeInsertOptions( $insertOptions );
3000 if ( !is_array( $selectOptions ) ) {
3001 $selectOptions = array( $selectOptions );
3004 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3006 if ( is_array( $srcTable ) ) {
3007 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3009 $srcTable = $this->tableName( $srcTable );
3012 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3013 " SELECT $startOpts " . implode( ',', $varMap ) .
3014 " FROM $srcTable $useIndex ";
3016 if ( $conds != '*' ) {
3017 if ( is_array( $conds ) ) {
3018 $conds = $this->makeList( $conds, LIST_AND
);
3020 $sql .= " WHERE $conds";
3023 $sql .= " $tailOpts";
3025 return $this->query( $sql, $fname );
3029 * Construct a LIMIT query with optional offset. This is used for query
3030 * pages. The SQL should be adjusted so that only the first $limit rows
3031 * are returned. If $offset is provided as well, then the first $offset
3032 * rows should be discarded, and the next $limit rows should be returned.
3033 * If the result of the query is not ordered, then the rows to be returned
3034 * are theoretically arbitrary.
3036 * $sql is expected to be a SELECT, if that makes a difference.
3038 * The version provided by default works in MySQL and SQLite. It will very
3039 * likely need to be overridden for most other DBMSes.
3041 * @param string $sql SQL query we will append the limit too
3042 * @param int $limit The SQL limit
3043 * @param int|bool $offset The SQL offset (default false)
3044 * @throws DBUnexpectedError
3047 public function limitResult( $sql, $limit, $offset = false ) {
3048 if ( !is_numeric( $limit ) ) {
3049 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3052 return "$sql LIMIT "
3053 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3058 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3059 * within the UNION construct.
3062 public function unionSupportsOrderAndLimit() {
3063 return true; // True for almost every DB supported
3067 * Construct a UNION query
3068 * This is used for providing overload point for other DB abstractions
3069 * not compatible with the MySQL syntax.
3070 * @param array $sqls SQL statements to combine
3071 * @param bool $all Use UNION ALL
3072 * @return string SQL fragment
3074 public function unionQueries( $sqls, $all ) {
3075 $glue = $all ?
') UNION ALL (' : ') UNION (';
3077 return '(' . implode( $glue, $sqls ) . ')';
3081 * Returns an SQL expression for a simple conditional. This doesn't need
3082 * to be overridden unless CASE isn't supported in your DBMS.
3084 * @param string|array $cond SQL expression which will result in a boolean value
3085 * @param string $trueVal SQL expression to return if true
3086 * @param string $falseVal SQL expression to return if false
3087 * @return string SQL fragment
3089 public function conditional( $cond, $trueVal, $falseVal ) {
3090 if ( is_array( $cond ) ) {
3091 $cond = $this->makeList( $cond, LIST_AND
);
3094 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3098 * Returns a comand for str_replace function in SQL query.
3099 * Uses REPLACE() in MySQL
3101 * @param string $orig Column to modify
3102 * @param string $old Column to seek
3103 * @param string $new Column to replace with
3107 public function strreplace( $orig, $old, $new ) {
3108 return "REPLACE({$orig}, {$old}, {$new})";
3112 * Determines how long the server has been up
3117 public function getServerUptime() {
3122 * Determines if the last failure was due to a deadlock
3127 public function wasDeadlock() {
3132 * Determines if the last failure was due to a lock timeout
3137 public function wasLockTimeout() {
3142 * Determines if the last query error was something that should be dealt
3143 * with by pinging the connection and reissuing the query.
3148 public function wasErrorReissuable() {
3153 * Determines if the last failure was due to the database being read-only.
3158 public function wasReadOnlyError() {
3163 * Determines if the given query error was a connection drop
3166 * @param integer|string $errno
3169 public function wasConnectionError( $errno ) {
3174 * Perform a deadlock-prone transaction.
3176 * This function invokes a callback function to perform a set of write
3177 * queries. If a deadlock occurs during the processing, the transaction
3178 * will be rolled back and the callback function will be called again.
3181 * $dbw->deadlockLoop( callback, ... );
3183 * Extra arguments are passed through to the specified callback function.
3185 * Returns whatever the callback function returned on its successful,
3186 * iteration, or false on error, for example if the retry limit was
3190 * @throws DBQueryError
3192 public function deadlockLoop() {
3193 $args = func_get_args();
3194 $function = array_shift( $args );
3195 $tries = self
::DEADLOCK_TRIES
;
3196 if ( is_array( $function ) ) {
3197 $fname = $function[0];
3202 $this->begin( __METHOD__
);
3208 $retVal = call_user_func_array( $function, $args );
3210 } catch ( DBQueryError
$e ) {
3211 if ( $this->wasDeadlock() ) {
3212 // Retry after a randomized delay
3213 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3215 // Throw the error back up
3219 } while ( --$tries > 0 );
3221 if ( $tries <= 0 ) {
3222 // Too many deadlocks; give up
3223 $this->rollback( __METHOD__
);
3226 $this->commit( __METHOD__
);
3233 * Wait for the slave to catch up to a given master position.
3235 * @param DBMasterPos $pos
3236 * @param int $timeout The maximum number of seconds to wait for
3238 * @return int Zero if the slave was past that position already,
3239 * greater than zero if we waited for some period of time, less than
3240 * zero if we timed out.
3242 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3243 # Real waits are implemented in the subclass.
3248 * Get the replication position of this slave
3250 * @return DBMasterPos|bool False if this is not a slave.
3252 public function getSlavePos() {
3258 * Get the position of this master
3260 * @return DBMasterPos|bool False if this is not a master
3262 public function getMasterPos() {
3268 * Run an anonymous function as soon as there is no transaction pending.
3269 * If there is a transaction and it is rolled back, then the callback is cancelled.
3270 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3271 * Callbacks must commit any transactions that they begin.
3273 * This is useful for updates to different systems or when separate transactions are needed.
3274 * For example, one might want to enqueue jobs into a system outside the database, but only
3275 * after the database is updated so that the jobs will see the data when they actually run.
3276 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3278 * @param callable $callback
3281 final public function onTransactionIdle( $callback ) {
3282 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3283 if ( !$this->mTrxLevel
) {
3284 $this->runOnTransactionIdleCallbacks();
3289 * Run an anonymous function before the current transaction commits or now if there is none.
3290 * If there is a transaction and it is rolled back, then the callback is cancelled.
3291 * Callbacks must not start nor commit any transactions.
3293 * This is useful for updates that easily cause deadlocks if locks are held too long
3294 * but where atomicity is strongly desired for these updates and some related updates.
3296 * @param callable $callback
3299 final public function onTransactionPreCommitOrIdle( $callback ) {
3300 if ( $this->mTrxLevel
) {
3301 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3303 $this->onTransactionIdle( $callback ); // this will trigger immediately
3308 * Actually any "on transaction idle" callbacks.
3312 protected function runOnTransactionIdleCallbacks() {
3313 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3315 $e = $ePrior = null; // last exception
3316 do { // callbacks may add callbacks :)
3317 $callbacks = $this->mTrxIdleCallbacks
;
3318 $this->mTrxIdleCallbacks
= array(); // recursion guard
3319 foreach ( $callbacks as $callback ) {
3321 list( $phpCallback ) = $callback;
3322 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3323 call_user_func( $phpCallback );
3324 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3325 } catch ( Exception
$e ) {
3327 MWExceptionHandler
::logException( $ePrior );
3332 } while ( count( $this->mTrxIdleCallbacks
) );
3334 if ( $e instanceof Exception
) {
3335 throw $e; // re-throw any last exception
3340 * Actually any "on transaction pre-commit" callbacks.
3344 protected function runOnTransactionPreCommitCallbacks() {
3345 $e = $ePrior = null; // last exception
3346 do { // callbacks may add callbacks :)
3347 $callbacks = $this->mTrxPreCommitCallbacks
;
3348 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3349 foreach ( $callbacks as $callback ) {
3351 list( $phpCallback ) = $callback;
3352 call_user_func( $phpCallback );
3353 } catch ( Exception
$e ) {
3355 MWExceptionHandler
::logException( $ePrior );
3360 } while ( count( $this->mTrxPreCommitCallbacks
) );
3362 if ( $e instanceof Exception
) {
3363 throw $e; // re-throw any last exception
3368 * Begin an atomic section of statements
3370 * If a transaction has been started already, just keep track of the given
3371 * section name to make sure the transaction is not committed pre-maturely.
3372 * This function can be used in layers (with sub-sections), so use a stack
3373 * to keep track of the different atomic sections. If there is no transaction,
3374 * start one implicitly.
3376 * The goal of this function is to create an atomic section of SQL queries
3377 * without having to start a new transaction if it already exists.
3379 * Atomic sections are more strict than transactions. With transactions,
3380 * attempting to begin a new transaction when one is already running results
3381 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3382 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3383 * and any database transactions cannot be began or committed until all atomic
3384 * levels are closed. There is no such thing as implicitly opening or closing
3385 * an atomic section.
3388 * @param string $fname
3391 final public function startAtomic( $fname = __METHOD__
) {
3392 if ( !$this->mTrxLevel
) {
3393 $this->begin( $fname );
3394 $this->mTrxAutomatic
= true;
3395 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3396 // in all changes being in one transaction to keep requests transactional.
3397 if ( !$this->getFlag( DBO_TRX
) ) {
3398 $this->mTrxAutomaticAtomic
= true;
3402 $this->mTrxAtomicLevels
->push( $fname );
3406 * Ends an atomic section of SQL statements
3408 * Ends the next section of atomic SQL statements and commits the transaction
3412 * @see DatabaseBase::startAtomic
3413 * @param string $fname
3416 final public function endAtomic( $fname = __METHOD__
) {
3417 if ( !$this->mTrxLevel
) {
3418 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3420 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3421 $this->mTrxAtomicLevels
->pop() !== $fname
3423 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3426 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3427 $this->commit( $fname, 'flush' );
3432 * Begin a transaction. If a transaction is already in progress,
3433 * that transaction will be committed before the new transaction is started.
3435 * Note that when the DBO_TRX flag is set (which is usually the case for web
3436 * requests, but not for maintenance scripts), any previous database query
3437 * will have started a transaction automatically.
3439 * Nesting of transactions is not supported. Attempts to nest transactions
3440 * will cause a warning, unless the current transaction was started
3441 * automatically because of the DBO_TRX flag.
3443 * @param string $fname
3446 final public function begin( $fname = __METHOD__
) {
3447 global $wgDebugDBTransactions;
3449 if ( $this->mTrxLevel
) { // implicit commit
3450 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3451 // If the current transaction was an automatic atomic one, then we definitely have
3452 // a problem. Same if there is any unclosed atomic level.
3453 throw new DBUnexpectedError( $this,
3454 "Attempted to start explicit transaction when atomic levels are still open."
3456 } elseif ( !$this->mTrxAutomatic
) {
3457 // We want to warn about inadvertently nested begin/commit pairs, but not about
3458 // auto-committing implicit transactions that were started by query() via DBO_TRX
3459 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3460 " performing implicit commit!";
3463 $this->getLogContext( array(
3464 'method' => __METHOD__
,
3469 // if the transaction was automatic and has done write operations,
3470 // log it if $wgDebugDBTransactions is enabled.
3471 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3472 wfDebug( "$fname: Automatic transaction with writes in progress" .
3473 " (from {$this->mTrxFname}), performing implicit commit!\n"
3478 $this->runOnTransactionPreCommitCallbacks();
3479 $writeTime = $this->pendingWriteQueryDuration();
3480 $this->doCommit( $fname );
3481 if ( $this->mTrxDoneWrites
) {
3482 $this->mDoneWrites
= microtime( true );
3483 $this->getTransactionProfiler()->transactionWritingOut(
3484 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3486 $this->runOnTransactionIdleCallbacks();
3489 # Avoid fatals if close() was called
3490 $this->assertOpen();
3492 $this->doBegin( $fname );
3493 $this->mTrxTimestamp
= microtime( true );
3494 $this->mTrxFname
= $fname;
3495 $this->mTrxDoneWrites
= false;
3496 $this->mTrxAutomatic
= false;
3497 $this->mTrxAutomaticAtomic
= false;
3498 $this->mTrxAtomicLevels
= new SplStack
;
3499 $this->mTrxIdleCallbacks
= array();
3500 $this->mTrxPreCommitCallbacks
= array();
3501 $this->mTrxShortId
= wfRandomString( 12 );
3502 $this->mTrxWriteDuration
= 0.0;
3506 * Issues the BEGIN command to the database server.
3508 * @see DatabaseBase::begin()
3509 * @param string $fname
3511 protected function doBegin( $fname ) {
3512 $this->query( 'BEGIN', $fname );
3513 $this->mTrxLevel
= 1;
3517 * Commits a transaction previously started using begin().
3518 * If no transaction is in progress, a warning is issued.
3520 * Nesting of transactions is not supported.
3522 * @param string $fname
3523 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3524 * explicitly committing implicit transactions, or calling commit when no
3525 * transaction is in progress. This will silently break any ongoing
3526 * explicit transaction. Only set the flush flag if you are sure that it
3527 * is safe to ignore these warnings in your context.
3528 * @throws DBUnexpectedError
3530 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3531 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3532 // There are still atomic sections open. This cannot be ignored
3533 throw new DBUnexpectedError(
3535 "Attempted to commit transaction while atomic sections are still open"
3539 if ( $flush === 'flush' ) {
3540 if ( !$this->mTrxLevel
) {
3541 return; // nothing to do
3542 } elseif ( !$this->mTrxAutomatic
) {
3543 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3546 if ( !$this->mTrxLevel
) {
3547 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3548 return; // nothing to do
3549 } elseif ( $this->mTrxAutomatic
) {
3550 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3554 # Avoid fatals if close() was called
3555 $this->assertOpen();
3557 $this->runOnTransactionPreCommitCallbacks();
3558 $writeTime = $this->pendingWriteQueryDuration();
3559 $this->doCommit( $fname );
3560 if ( $this->mTrxDoneWrites
) {
3561 $this->mDoneWrites
= microtime( true );
3562 $this->getTransactionProfiler()->transactionWritingOut(
3563 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3565 $this->runOnTransactionIdleCallbacks();
3569 * Issues the COMMIT command to the database server.
3571 * @see DatabaseBase::commit()
3572 * @param string $fname
3574 protected function doCommit( $fname ) {
3575 if ( $this->mTrxLevel
) {
3576 $this->query( 'COMMIT', $fname );
3577 $this->mTrxLevel
= 0;
3582 * Rollback a transaction previously started using begin().
3583 * If no transaction is in progress, a warning is issued.
3585 * No-op on non-transactional databases.
3587 * @param string $fname
3588 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3589 * calling rollback when no transaction is in progress. This will silently
3590 * break any ongoing explicit transaction. Only set the flush flag if you
3591 * are sure that it is safe to ignore these warnings in your context.
3592 * @throws DBUnexpectedError
3593 * @since 1.23 Added $flush parameter
3595 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3596 if ( $flush !== 'flush' ) {
3597 if ( !$this->mTrxLevel
) {
3598 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3599 return; // nothing to do
3600 } elseif ( $this->mTrxAutomatic
) {
3601 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3604 if ( !$this->mTrxLevel
) {
3605 return; // nothing to do
3606 } elseif ( !$this->mTrxAutomatic
) {
3607 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3611 # Avoid fatals if close() was called
3612 $this->assertOpen();
3614 $this->doRollback( $fname );
3615 $this->mTrxIdleCallbacks
= array(); // cancel
3616 $this->mTrxPreCommitCallbacks
= array(); // cancel
3617 $this->mTrxAtomicLevels
= new SplStack
;
3618 if ( $this->mTrxDoneWrites
) {
3619 $this->getTransactionProfiler()->transactionWritingOut(
3620 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3625 * Issues the ROLLBACK command to the database server.
3627 * @see DatabaseBase::rollback()
3628 * @param string $fname
3630 protected function doRollback( $fname ) {
3631 if ( $this->mTrxLevel
) {
3632 $this->query( 'ROLLBACK', $fname, true );
3633 $this->mTrxLevel
= 0;
3638 * Creates a new table with structure copied from existing table
3639 * Note that unlike most database abstraction functions, this function does not
3640 * automatically append database prefix, because it works at a lower
3641 * abstraction level.
3642 * The table names passed to this function shall not be quoted (this
3643 * function calls addIdentifierQuotes when needed).
3645 * @param string $oldName Name of table whose structure should be copied
3646 * @param string $newName Name of table to be created
3647 * @param bool $temporary Whether the new table should be temporary
3648 * @param string $fname Calling function name
3649 * @throws MWException
3650 * @return bool True if operation was successful
3652 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3655 throw new MWException(
3656 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3660 * List all tables on the database
3662 * @param string $prefix Only show tables with this prefix, e.g. mw_
3663 * @param string $fname Calling function name
3664 * @throws MWException
3667 function listTables( $prefix = null, $fname = __METHOD__
) {
3668 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3672 * Reset the views process cache set by listViews()
3675 final public function clearViewsCache() {
3676 $this->allViews
= null;
3680 * Lists all the VIEWs in the database
3682 * For caching purposes the list of all views should be stored in
3683 * $this->allViews. The process cache can be cleared with clearViewsCache()
3685 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3686 * @param string $fname Name of calling function
3687 * @throws MWException
3691 public function listViews( $prefix = null, $fname = __METHOD__
) {
3692 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3696 * Differentiates between a TABLE and a VIEW
3698 * @param string $name Name of the database-structure to test.
3699 * @throws MWException
3703 public function isView( $name ) {
3704 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3708 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3709 * to the format used for inserting into timestamp fields in this DBMS.
3711 * The result is unquoted, and needs to be passed through addQuotes()
3712 * before it can be included in raw SQL.
3714 * @param string|int $ts
3718 public function timestamp( $ts = 0 ) {
3719 return wfTimestamp( TS_MW
, $ts );
3723 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3724 * to the format used for inserting into timestamp fields in this DBMS. If
3725 * NULL is input, it is passed through, allowing NULL values to be inserted
3726 * into timestamp fields.
3728 * The result is unquoted, and needs to be passed through addQuotes()
3729 * before it can be included in raw SQL.
3731 * @param string|int $ts
3735 public function timestampOrNull( $ts = null ) {
3736 if ( is_null( $ts ) ) {
3739 return $this->timestamp( $ts );
3744 * Take the result from a query, and wrap it in a ResultWrapper if
3745 * necessary. Boolean values are passed through as is, to indicate success
3746 * of write queries or failure.
3748 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3749 * resource, and it was necessary to call this function to convert it to
3750 * a wrapper. Nowadays, raw database objects are never exposed to external
3751 * callers, so this is unnecessary in external code.
3753 * @param bool|ResultWrapper|resource|object $result
3754 * @return bool|ResultWrapper
3756 protected function resultObject( $result ) {
3759 } elseif ( $result instanceof ResultWrapper
) {
3761 } elseif ( $result === true ) {
3762 // Successful write query
3765 return new ResultWrapper( $this, $result );
3770 * Ping the server and try to reconnect if it there is no connection
3772 * @return bool Success or failure
3774 public function ping() {
3775 # Stub. Not essential to override.
3780 * Get slave lag. Currently supported only by MySQL.
3782 * Note that this function will generate a fatal error on many
3783 * installations. Most callers should use LoadBalancer::safeGetLag()
3786 * @return int Database replication lag in seconds
3788 public function getLag() {
3793 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3797 function maxListLen() {
3802 * Some DBMSs have a special format for inserting into blob fields, they
3803 * don't allow simple quoted strings to be inserted. To insert into such
3804 * a field, pass the data through this function before passing it to
3805 * DatabaseBase::insert().
3810 public function encodeBlob( $b ) {
3815 * Some DBMSs return a special placeholder object representing blob fields
3816 * in result objects. Pass the object through this function to return the
3819 * @param string|Blob $b
3822 public function decodeBlob( $b ) {
3823 if ( $b instanceof Blob
) {
3830 * Override database's default behavior. $options include:
3831 * 'connTimeout' : Set the connection timeout value in seconds.
3832 * May be useful for very long batch queries such as
3833 * full-wiki dumps, where a single query reads out over
3836 * @param array $options
3839 public function setSessionOptions( array $options ) {
3843 * Read and execute SQL commands from a file.
3845 * Returns true on success, error string or exception on failure (depending
3846 * on object's error ignore settings).
3848 * @param string $filename File name to open
3849 * @param bool|callable $lineCallback Optional function called before reading each line
3850 * @param bool|callable $resultCallback Optional function called for each MySQL result
3851 * @param bool|string $fname Calling function name or false if name should be
3852 * generated dynamically using $filename
3853 * @param bool|callable $inputCallback Optional function called for each
3854 * complete line sent
3855 * @throws Exception|MWException
3856 * @return bool|string
3858 public function sourceFile(
3859 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3861 MediaWiki\
suppressWarnings();
3862 $fp = fopen( $filename, 'r' );
3863 MediaWiki\restoreWarnings
();
3865 if ( false === $fp ) {
3866 throw new MWException( "Could not open \"{$filename}\".\n" );
3870 $fname = __METHOD__
. "( $filename )";
3874 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3875 } catch ( Exception
$e ) {
3886 * Get the full path of a patch file. Originally based on archive()
3887 * from updaters.inc. Keep in mind this always returns a patch, as
3888 * it fails back to MySQL if no DB-specific patch can be found
3890 * @param string $patch The name of the patch, like patch-something.sql
3891 * @return string Full path to patch file
3893 public function patchPath( $patch ) {
3896 $dbType = $this->getType();
3897 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3898 return "$IP/maintenance/$dbType/archives/$patch";
3900 return "$IP/maintenance/archives/$patch";
3905 * Set variables to be used in sourceFile/sourceStream, in preference to the
3906 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3907 * all. If it's set to false, $GLOBALS will be used.
3909 * @param bool|array $vars Mapping variable name to value.
3911 public function setSchemaVars( $vars ) {
3912 $this->mSchemaVars
= $vars;
3916 * Read and execute commands from an open file handle.
3918 * Returns true on success, error string or exception on failure (depending
3919 * on object's error ignore settings).
3921 * @param resource $fp File handle
3922 * @param bool|callable $lineCallback Optional function called before reading each query
3923 * @param bool|callable $resultCallback Optional function called for each MySQL result
3924 * @param string $fname Calling function name
3925 * @param bool|callable $inputCallback Optional function called for each complete query sent
3926 * @return bool|string
3928 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3929 $fname = __METHOD__
, $inputCallback = false
3933 while ( !feof( $fp ) ) {
3934 if ( $lineCallback ) {
3935 call_user_func( $lineCallback );
3938 $line = trim( fgets( $fp ) );
3940 if ( $line == '' ) {
3944 if ( '-' == $line[0] && '-' == $line[1] ) {
3952 $done = $this->streamStatementEnd( $cmd, $line );
3956 if ( $done ||
feof( $fp ) ) {
3957 $cmd = $this->replaceVars( $cmd );
3959 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3960 $res = $this->query( $cmd, $fname );
3962 if ( $resultCallback ) {
3963 call_user_func( $resultCallback, $res, $this );
3966 if ( false === $res ) {
3967 $err = $this->lastError();
3969 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3980 * Called by sourceStream() to check if we've reached a statement end
3982 * @param string $sql SQL assembled so far
3983 * @param string $newLine New line about to be added to $sql
3984 * @return bool Whether $newLine contains end of the statement
3986 public function streamStatementEnd( &$sql, &$newLine ) {
3987 if ( $this->delimiter
) {
3989 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3990 if ( $newLine != $prev ) {
3999 * Database independent variable replacement. Replaces a set of variables
4000 * in an SQL statement with their contents as given by $this->getSchemaVars().
4002 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4004 * - '{$var}' should be used for text and is passed through the database's
4006 * - `{$var}` should be used for identifiers (e.g. table and database names).
4007 * It is passed through the database's addIdentifierQuotes method which
4008 * can be overridden if the database uses something other than backticks.
4009 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4010 * database's tableName method.
4011 * - / *i* / passes the name that follows through the database's indexName method.
4012 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4013 * its use should be avoided. In 1.24 and older, string encoding was applied.
4015 * @param string $ins SQL statement to replace variables in
4016 * @return string The new SQL statement with variables replaced
4018 protected function replaceVars( $ins ) {
4020 $vars = $this->getSchemaVars();
4021 return preg_replace_callback(
4023 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4024 \'\{\$ (\w+) }\' | # 3. addQuotes
4025 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4026 /\*\$ (\w+) \*/ # 5. leave unencoded
4028 function ( $m ) use ( $that, $vars ) {
4029 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4030 // check for both nonexistent keys *and* the empty string.
4031 if ( isset( $m[1] ) && $m[1] !== '' ) {
4032 if ( $m[1] === 'i' ) {
4033 return $that->indexName( $m[2] );
4035 return $that->tableName( $m[2] );
4037 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4038 return $that->addQuotes( $vars[$m[3]] );
4039 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4040 return $that->addIdentifierQuotes( $vars[$m[4]] );
4041 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4042 return $vars[$m[5]];
4052 * Get schema variables. If none have been set via setSchemaVars(), then
4053 * use some defaults from the current object.
4057 protected function getSchemaVars() {
4058 if ( $this->mSchemaVars
) {
4059 return $this->mSchemaVars
;
4061 return $this->getDefaultSchemaVars();
4066 * Get schema variables to use if none have been set via setSchemaVars().
4068 * Override this in derived classes to provide variables for tables.sql
4069 * and SQL patch files.
4073 protected function getDefaultSchemaVars() {
4078 * Check to see if a named lock is available (non-blocking)
4080 * @param string $lockName Name of lock to poll
4081 * @param string $method Name of method calling us
4085 public function lockIsFree( $lockName, $method ) {
4090 * Acquire a named lock
4092 * Named locks are not related to transactions
4094 * @param string $lockName Name of lock to aquire
4095 * @param string $method Name of method calling us
4096 * @param int $timeout
4099 public function lock( $lockName, $method, $timeout = 5 ) {
4106 * Named locks are not related to transactions
4108 * @param string $lockName Name of lock to release
4109 * @param string $method Name of method calling us
4111 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4112 * by this thread (in which case the lock is not released), and NULL if the named
4113 * lock did not exist
4115 public function unlock( $lockName, $method ) {
4120 * Check to see if a named lock used by lock() use blocking queues
4125 public function namedLocksEnqueue() {
4130 * Lock specific tables
4132 * @param array $read Array of tables to lock for read access
4133 * @param array $write Array of tables to lock for write access
4134 * @param string $method Name of caller
4135 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4138 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4143 * Unlock specific tables
4145 * @param string $method The caller
4148 public function unlockTables( $method ) {
4154 * @param string $tableName
4155 * @param string $fName
4156 * @return bool|ResultWrapper
4159 public function dropTable( $tableName, $fName = __METHOD__
) {
4160 if ( !$this->tableExists( $tableName, $fName ) ) {
4163 $sql = "DROP TABLE " . $this->tableName( $tableName );
4164 if ( $this->cascadingDeletes() ) {
4168 return $this->query( $sql, $fName );
4172 * Get search engine class. All subclasses of this need to implement this
4173 * if they wish to use searching.
4177 public function getSearchEngine() {
4178 return 'SearchEngineDummy';
4182 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4183 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4184 * because "i" sorts after all numbers.
4188 public function getInfinity() {
4193 * Encode an expiry time into the DBMS dependent format
4195 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4198 public function encodeExpiry( $expiry ) {
4199 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4200 ?
$this->getInfinity()
4201 : $this->timestamp( $expiry );
4205 * Decode an expiry time into a DBMS independent format
4207 * @param string $expiry DB timestamp field value for expiry
4208 * @param int $format TS_* constant, defaults to TS_MW
4211 public function decodeExpiry( $expiry, $format = TS_MW
) {
4212 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4214 : wfTimestamp( $format, $expiry );
4218 * Allow or deny "big selects" for this session only. This is done by setting
4219 * the sql_big_selects session variable.
4221 * This is a MySQL-specific feature.
4223 * @param bool|string $value True for allow, false for deny, or "default" to
4224 * restore the initial value
4226 public function setBigSelects( $value = true ) {
4234 public function __toString() {
4235 return (string)$this->mConn
;
4239 * Run a few simple sanity checks
4241 public function __destruct() {
4242 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4243 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4245 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4247 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4248 $callers[] = $callbackInfo[1];
4250 $callers = implode( ', ', $callers );
4251 trigger_error( "DB transaction callbacks still pending (from $callers)." );