4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX
= 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var resource Database connection */
49 protected $mConn = null;
50 protected $mOpened = false;
52 /** @var callable[] */
53 protected $mTrxIdleCallbacks = array();
54 /** @var callable[] */
55 protected $mTrxPreCommitCallbacks = array();
57 protected $mTablePrefix;
61 protected $mLBInfo = array();
62 protected $mDefaultBigSelects = null;
63 protected $mSchemaVars = false;
65 protected $mSessionVars = array();
67 protected $preparedArgs;
69 protected $htmlErrors;
71 protected $delimiter = ';';
74 * Either 1 if a transaction is active or 0 otherwise.
75 * The other Trx fields may not be meaningfull if this is 0.
79 protected $mTrxLevel = 0;
82 * Either a short hexidecimal string if a transaction is active or ""
85 * @see DatabaseBase::mTrxLevel
87 protected $mTrxShortId = '';
90 * The UNIX time that the transaction started. Callers can assume that if
91 * snapshot isolation is used, then the data is *at least* up to date to that
92 * point (possibly more up-to-date since the first SELECT defines the snapshot).
95 * @see DatabaseBase::mTrxLevel
97 private $mTrxTimestamp = null;
100 * Remembers the function name given for starting the most recent transaction via begin().
101 * Used to provide additional context for error reporting.
104 * @see DatabaseBase::mTrxLevel
106 private $mTrxFname = null;
109 * Record if possible write queries were done in the last transaction started
112 * @see DatabaseBase::mTrxLevel
114 private $mTrxDoneWrites = false;
117 * Record if the current transaction was started implicitly due to DBO_TRX being set.
120 * @see DatabaseBase::mTrxLevel
122 private $mTrxAutomatic = false;
125 * Array of levels of atomicity within transactions
129 private $mTrxAtomicLevels = array();
132 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
136 private $mTrxAutomaticAtomic = false;
139 * Track the seconds spent in write queries for the current transaction
143 private $mTrxWriteDuration = 0.0;
147 * @var resource File handle for upgrade
149 protected $fileHandle = null;
153 * @var string[] Process cache of VIEWs names in the database
155 protected $allViews = null;
157 /** @var TransactionProfiler */
158 protected $trxProfiler;
161 * A string describing the current software version, and possibly
162 * other details in a user-friendly way. Will be listed on Special:Version, etc.
163 * Use getServerVersion() to get machine-friendly information.
165 * @return string Version information from the database server
167 public function getServerInfo() {
168 return $this->getServerVersion();
172 * @return string Command delimiter used by this database engine
174 public function getDelimiter() {
175 return $this->delimiter
;
179 * Boolean, controls output of large amounts of debug information.
180 * @param bool|null $debug
181 * - true to enable debugging
182 * - false to disable debugging
183 * - omitted or null to do nothing
185 * @return bool|null Previous value of the flag
187 public function debug( $debug = null ) {
188 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
192 * Turns buffering of SQL result sets on (true) or off (false). Default is
195 * Unbuffered queries are very troublesome in MySQL:
197 * - If another query is executed while the first query is being read
198 * out, the first query is killed. This means you can't call normal
199 * MediaWiki functions while you are reading an unbuffered query result
200 * from a normal wfGetDB() connection.
202 * - Unbuffered queries cause the MySQL server to use large amounts of
203 * memory and to hold broad locks which block other queries.
205 * If you want to limit client-side memory, it's almost always better to
206 * split up queries into batches using a LIMIT clause than to switch off
209 * @param null|bool $buffer
210 * @return null|bool The previous value of the flag
212 public function bufferResults( $buffer = null ) {
213 if ( is_null( $buffer ) ) {
214 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
216 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
221 * Turns on (false) or off (true) the automatic generation and sending
222 * of a "we're sorry, but there has been a database error" page on
223 * database errors. Default is on (false). When turned off, the
224 * code should use lastErrno() and lastError() to handle the
225 * situation as appropriate.
227 * Do not use this function outside of the Database classes.
229 * @param null|bool $ignoreErrors
230 * @return bool The previous value of the flag.
232 protected function ignoreErrors( $ignoreErrors = null ) {
233 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
237 * Gets the current transaction level.
239 * Historically, transactions were allowed to be "nested". This is no
240 * longer supported, so this function really only returns a boolean.
242 * @return int The previous value
244 public function trxLevel() {
245 return $this->mTrxLevel
;
249 * Get the UNIX timestamp of the time that the transaction was established
251 * This can be used to reason about the staleness of SELECT data
252 * in REPEATABLE-READ transaction isolation level.
254 * @return float|null Returns null if there is not active transaction
257 public function trxTimestamp() {
258 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
262 * Get/set the table prefix.
263 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
264 * @return string The previous table prefix.
266 public function tablePrefix( $prefix = null ) {
267 return wfSetVar( $this->mTablePrefix
, $prefix );
271 * Get/set the db schema.
272 * @param string $schema The database schema to set, or omitted to leave it unchanged.
273 * @return string The previous db schema.
275 public function dbSchema( $schema = null ) {
276 return wfSetVar( $this->mSchema
, $schema );
280 * Set the filehandle to copy write statements to.
282 * @param resource $fh File handle
284 public function setFileHandle( $fh ) {
285 $this->fileHandle
= $fh;
289 * Get properties passed down from the server info array of the load
292 * @param string $name The entry of the info array to get, or null to get the
295 * @return array|mixed|null
297 public function getLBInfo( $name = null ) {
298 if ( is_null( $name ) ) {
299 return $this->mLBInfo
;
301 if ( array_key_exists( $name, $this->mLBInfo
) ) {
302 return $this->mLBInfo
[$name];
310 * Set the LB info array, or a member of it. If called with one parameter,
311 * the LB info array is set to that parameter. If it is called with two
312 * parameters, the member with the given name is set to the given value.
314 * @param string $name
315 * @param array $value
317 public function setLBInfo( $name, $value = null ) {
318 if ( is_null( $value ) ) {
319 $this->mLBInfo
= $name;
321 $this->mLBInfo
[$name] = $value;
326 * @return TransactionProfiler
328 protected function getTransactionProfiler() {
329 return $this->trxProfiler
331 : Profiler
::instance()->getTransactionProfiler();
335 * Returns true if this database supports (and uses) cascading deletes
339 public function cascadingDeletes() {
344 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
348 public function cleanupTriggers() {
353 * Returns true if this database is strict about what can be put into an IP field.
354 * Specifically, it uses a NULL value instead of an empty string.
358 public function strictIPs() {
363 * Returns true if this database uses timestamps rather than integers
367 public function realTimestamps() {
372 * Returns true if this database does an implicit sort when doing GROUP BY
376 public function implicitGroupby() {
381 * Returns true if this database does an implicit order by when the column has an index
382 * For example: SELECT page_title FROM page LIMIT 1
386 public function implicitOrderby() {
391 * Returns true if this database can do a native search on IP columns
392 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
396 public function searchableIPs() {
401 * Returns true if this database can use functional indexes
405 public function functionalIndexes() {
410 * Return the last query that went through DatabaseBase::query()
413 public function lastQuery() {
414 return $this->mLastQuery
;
418 * Returns true if the connection may have been used for write queries.
419 * Should return true if unsure.
423 public function doneWrites() {
424 return (bool)$this->mDoneWrites
;
428 * Returns the last time the connection may have been used for write queries.
429 * Should return a timestamp if unsure.
431 * @return int|float UNIX timestamp or false
434 public function lastDoneWrites() {
435 return $this->mDoneWrites ?
: false;
439 * Returns true if there is a transaction open with possible write
440 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
444 public function writesOrCallbacksPending() {
445 return $this->mTrxLevel
&& (
446 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
451 * Get the time spend running write queries for this
453 * High times could be due to scanning, updates, locking, and such
455 * @return float|bool Returns false if not transaction is active
458 public function pendingWriteQueryDuration() {
459 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
463 * Is a connection to the database open?
466 public function isOpen() {
467 return $this->mOpened
;
471 * Set a flag for this connection
473 * @param int $flag DBO_* constants from Defines.php:
474 * - DBO_DEBUG: output some debug info (same as debug())
475 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
476 * - DBO_TRX: automatically start transactions
477 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
478 * and removes it in command line mode
479 * - DBO_PERSISTENT: use persistant database connection
481 public function setFlag( $flag ) {
482 $this->mFlags |
= $flag;
486 * Clear a flag for this connection
488 * @param int $flag DBO_* constants from Defines.php:
489 * - DBO_DEBUG: output some debug info (same as debug())
490 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
491 * - DBO_TRX: automatically start transactions
492 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
493 * and removes it in command line mode
494 * - DBO_PERSISTENT: use persistant database connection
496 public function clearFlag( $flag ) {
497 $this->mFlags
&= ~
$flag;
501 * Returns a boolean whether the flag $flag is set for this connection
503 * @param int $flag DBO_* constants from Defines.php:
504 * - DBO_DEBUG: output some debug info (same as debug())
505 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
506 * - DBO_TRX: automatically start transactions
507 * - DBO_PERSISTENT: use persistant database connection
510 public function getFlag( $flag ) {
511 return !!( $this->mFlags
& $flag );
515 * General read-only accessor
517 * @param string $name
520 public function getProperty( $name ) {
527 public function getWikiID() {
528 if ( $this->mTablePrefix
) {
529 return "{$this->mDBname}-{$this->mTablePrefix}";
531 return $this->mDBname
;
536 * Return a path to the DBMS-specific SQL file if it exists,
537 * otherwise default SQL file
539 * @param string $filename
542 private function getSqlFilePath( $filename ) {
544 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
545 if ( file_exists( $dbmsSpecificFilePath ) ) {
546 return $dbmsSpecificFilePath;
548 return "$IP/maintenance/$filename";
553 * Return a path to the DBMS-specific schema file,
554 * otherwise default to tables.sql
558 public function getSchemaPath() {
559 return $this->getSqlFilePath( 'tables.sql' );
563 * Return a path to the DBMS-specific update key file,
564 * otherwise default to update-keys.sql
568 public function getUpdateKeysPath() {
569 return $this->getSqlFilePath( 'update-keys.sql' );
573 * Get information about an index into an object
574 * @param string $table Table name
575 * @param string $index Index name
576 * @param string $fname Calling function name
577 * @return mixed Database-specific index description class or false if the index does not exist
579 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
582 * Wrapper for addslashes()
584 * @param string $s String to be slashed.
585 * @return string Slashed string.
587 abstract function strencode( $s );
592 * FIXME: It is possible to construct a Database object with no associated
593 * connection object, by specifying no parameters to __construct(). This
594 * feature is deprecated and should be removed.
596 * DatabaseBase subclasses should not be constructed directly in external
597 * code. DatabaseBase::factory() should be used instead.
599 * @param array $params Parameters passed from DatabaseBase::factory()
601 function __construct( array $params ) {
602 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
604 $server = $params['host'];
605 $user = $params['user'];
606 $password = $params['password'];
607 $dbName = $params['dbname'];
608 $flags = $params['flags'];
609 $tablePrefix = $params['tablePrefix'];
610 $schema = $params['schema'];
611 $foreign = $params['foreign'];
613 $this->mFlags
= $flags;
614 if ( $this->mFlags
& DBO_DEFAULT
) {
615 if ( $wgCommandLineMode ) {
616 $this->mFlags
&= ~DBO_TRX
;
618 $this->mFlags |
= DBO_TRX
;
622 $this->mSessionVars
= $params['variables'];
624 /** Get the default table prefix*/
625 if ( $tablePrefix === 'get from global' ) {
626 $this->mTablePrefix
= $wgDBprefix;
628 $this->mTablePrefix
= $tablePrefix;
631 /** Get the database schema*/
632 if ( $schema === 'get from global' ) {
633 $this->mSchema
= $wgDBmwschema;
635 $this->mSchema
= $schema;
638 $this->mForeign
= $foreign;
640 if ( isset( $params['trxProfiler'] ) ) {
641 $this->trxProfiler
= $params['trxProfiler']; // override
645 $this->open( $server, $user, $password, $dbName );
650 * Called by serialize. Throw an exception when DB connection is serialized.
651 * This causes problems on some database engines because the connection is
652 * not restored on unserialize.
654 public function __sleep() {
655 throw new MWException( 'Database serialization may cause problems, since ' .
656 'the connection is not restored on wakeup.' );
660 * Given a DB type, construct the name of the appropriate child class of
661 * DatabaseBase. This is designed to replace all of the manual stuff like:
662 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
663 * as well as validate against the canonical list of DB types we have
665 * This factory function is mostly useful for when you need to connect to a
666 * database other than the MediaWiki default (such as for external auth,
667 * an extension, et cetera). Do not use this to connect to the MediaWiki
668 * database. Example uses in core:
669 * @see LoadBalancer::reallyOpenConnection()
670 * @see ForeignDBRepo::getMasterDB()
671 * @see WebInstallerDBConnect::execute()
675 * @param string $dbType A possible DB type
676 * @param array $p An array of options to pass to the constructor.
677 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
678 * @throws MWException If the database driver or extension cannot be found
679 * @return DatabaseBase|null DatabaseBase subclass or null
681 final public static function factory( $dbType, $p = array() ) {
682 $canonicalDBTypes = array(
683 'mysql' => array( 'mysqli', 'mysql' ),
684 'postgres' => array(),
691 $dbType = strtolower( $dbType );
692 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
693 $possibleDrivers = $canonicalDBTypes[$dbType];
694 if ( !empty( $p['driver'] ) ) {
695 if ( in_array( $p['driver'], $possibleDrivers ) ) {
696 $driver = $p['driver'];
698 throw new MWException( __METHOD__
.
699 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
702 foreach ( $possibleDrivers as $posDriver ) {
703 if ( extension_loaded( $posDriver ) ) {
704 $driver = $posDriver;
712 if ( $driver === false ) {
713 throw new MWException( __METHOD__
.
714 " no viable database extension found for type '$dbType'" );
717 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
718 // and everything else doesn't use a schema (e.g. null)
719 // Although postgres and oracle support schemas, we don't use them (yet)
720 // to maintain backwards compatibility
721 $defaultSchemas = array(
722 'mssql' => 'get from global',
725 $class = 'Database' . ucfirst( $driver );
726 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
727 // Resolve some defaults for b/c
728 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
729 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
730 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
731 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
732 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
733 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
734 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
735 if ( !isset( $p['schema'] ) ) {
736 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
738 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
740 return new $class( $p );
746 protected function installErrorHandler() {
747 $this->mPHPError
= false;
748 $this->htmlErrors
= ini_set( 'html_errors', '0' );
749 set_error_handler( array( $this, 'connectionErrorHandler' ) );
753 * @return bool|string
755 protected function restoreErrorHandler() {
756 restore_error_handler();
757 if ( $this->htmlErrors
!== false ) {
758 ini_set( 'html_errors', $this->htmlErrors
);
760 if ( $this->mPHPError
) {
761 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
762 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
772 * @param string $errstr
774 public function connectionErrorHandler( $errno, $errstr ) {
775 $this->mPHPError
= $errstr;
779 * Create a log context to pass to wfLogDBError or other logging functions.
781 * @param array $extras Additional data to add to context
784 protected function getLogContext( array $extras = array() ) {
787 'db_server' => $this->mServer
,
788 'db_name' => $this->mDBname
,
789 'db_user' => $this->mUser
,
796 * Closes a database connection.
797 * if it is open : commits any open transactions
799 * @throws MWException
800 * @return bool Operation success. true if already closed.
802 public function close() {
803 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
804 throw new MWException( "Transaction idle callbacks still pending." );
806 if ( $this->mConn
) {
807 if ( $this->trxLevel() ) {
808 if ( !$this->mTrxAutomatic
) {
809 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
810 " performing implicit commit before closing connection!" );
813 $this->commit( __METHOD__
, 'flush' );
816 $closed = $this->closeConnection();
817 $this->mConn
= false;
821 $this->mOpened
= false;
827 * Make sure isOpen() returns true as a sanity check
829 * @throws DBUnexpectedError
831 protected function assertOpen() {
832 if ( !$this->isOpen() ) {
833 throw new DBUnexpectedError( $this, "DB connection was already closed." );
838 * Closes underlying database connection
840 * @return bool Whether connection was closed successfully
842 abstract protected function closeConnection();
845 * @param string $error Fallback error message, used if none is given by DB
846 * @throws DBConnectionError
848 function reportConnectionError( $error = 'Unknown error' ) {
849 $myError = $this->lastError();
855 throw new DBConnectionError( $this, $error );
859 * The DBMS-dependent part of query()
861 * @param string $sql SQL query.
862 * @return ResultWrapper|bool Result object to feed to fetchObject,
863 * fetchRow, ...; or false on failure
865 abstract protected function doQuery( $sql );
868 * Determine whether a query writes to the DB.
869 * Should return true if unsure.
874 protected function isWriteQuery( $sql ) {
875 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
879 * Determine whether a SQL statement is sensitive to isolation level.
880 * A SQL statement is considered transactable if its result could vary
881 * depending on the transaction isolation level. Operational commands
882 * such as 'SET' and 'SHOW' are not considered to be transactable.
887 protected function isTransactableQuery( $sql ) {
888 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
889 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
893 * Run an SQL query and return the result. Normally throws a DBQueryError
894 * on failure. If errors are ignored, returns false instead.
896 * In new code, the query wrappers select(), insert(), update(), delete(),
897 * etc. should be used where possible, since they give much better DBMS
898 * independence and automatically quote or validate user input in a variety
899 * of contexts. This function is generally only useful for queries which are
900 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
903 * However, the query wrappers themselves should call this function.
905 * @param string $sql SQL query
906 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
907 * comment (you can use __METHOD__ or add some extra info)
908 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
909 * maybe best to catch the exception instead?
910 * @throws MWException
911 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
912 * for a successful read query, or false on failure if $tempIgnore set
914 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
917 $this->mLastQuery
= $sql;
919 $isWriteQuery = $this->isWriteQuery( $sql );
920 if ( $isWriteQuery ) {
921 if ( !$this->mDoneWrites
) {
922 wfDebug( __METHOD__
. ': Writes done: ' .
923 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
925 # Set a flag indicating that writes have been done
926 $this->mDoneWrites
= microtime( true );
929 # Add a comment for easy SHOW PROCESSLIST interpretation
930 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
931 $userName = $wgUser->getName();
932 if ( mb_strlen( $userName ) > 15 ) {
933 $userName = mb_substr( $userName, 0, 15 ) . '...';
935 $userName = str_replace( '/', '', $userName );
940 // Add trace comment to the begin of the sql string, right after the operator.
941 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
942 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
944 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
945 $this->begin( __METHOD__
. " ($fname)" );
946 $this->mTrxAutomatic
= true;
949 # Keep track of whether the transaction has write queries pending
950 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
951 $this->mTrxDoneWrites
= true;
952 $this->getTransactionProfiler()->transactionWritingIn(
953 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
956 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
957 # generalizeSQL will probably cut down the query to reasonable
958 # logging size most of the time. The substr is really just a sanity check.
960 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
961 $totalProf = 'DatabaseBase::query-master';
963 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
964 $totalProf = 'DatabaseBase::query';
966 # Include query transaction state
967 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
969 $profiler = Profiler
::instance();
970 if ( !$profiler instanceof ProfilerStub
) {
971 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
972 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
975 if ( $this->debug() ) {
976 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $sql ) );
979 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
981 # Avoid fatals if close() was called
984 # Do the query and handle errors
985 $startTime = microtime( true );
986 $ret = $this->doQuery( $commentedSql );
987 $queryRuntime = microtime( true ) - $startTime;
988 # Log the query time and feed it into the DB trx profiler
989 $this->getTransactionProfiler()->recordQueryCompletion(
990 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
992 MWDebug
::queryTime( $queryId );
994 # Try reconnecting if the connection was lost
995 if ( false === $ret && $this->wasErrorReissuable() ) {
996 # Transaction is gone, like it or not
997 $hadTrx = $this->mTrxLevel
; // possible lost transaction
998 $this->mTrxLevel
= 0;
999 $this->mTrxIdleCallbacks
= array(); // bug 65263
1000 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1001 wfDebug( "Connection lost, reconnecting...\n" );
1002 # Stash the last error values since ping() might clear them
1003 $lastError = $this->lastError();
1004 $lastErrno = $this->lastErrno();
1005 if ( $this->ping() ) {
1006 wfDebug( "Reconnected\n" );
1007 $server = $this->getServer();
1008 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1009 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1012 # Leave $ret as false and let an error be reported.
1013 # Callers may catch the exception and continue to use the DB.
1014 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1016 # Should be safe to silently retry (no trx and thus no callbacks)
1017 $startTime = microtime( true );
1018 $ret = $this->doQuery( $commentedSql );
1019 $queryRuntime = microtime( true ) - $startTime;
1020 # Log the query time and feed it into the DB trx profiler
1021 $this->getTransactionProfiler()->recordQueryCompletion(
1022 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1025 wfDebug( "Failed\n" );
1029 if ( false === $ret ) {
1030 $this->reportQueryError(
1031 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1034 $res = $this->resultObject( $ret );
1036 // Destroy profile sections in the opposite order to their creation
1037 ScopedCallback
::consume( $queryProfSection );
1038 ScopedCallback
::consume( $totalProfSection );
1040 if ( $isWriteQuery && $this->mTrxLevel
) {
1041 $this->mTrxWriteDuration +
= $queryRuntime;
1048 * Report a query error. Log the error, and if neither the object ignore
1049 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1051 * @param string $error
1053 * @param string $sql
1054 * @param string $fname
1055 * @param bool $tempIgnore
1056 * @throws DBQueryError
1058 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1059 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1060 wfDebug( "SQL ERROR (ignored): $error\n" );
1062 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1064 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1065 $this->getLogContext( array(
1066 'method' => __METHOD__
,
1069 'sql1line' => $sql1line,
1073 wfDebug( "SQL ERROR: " . $error . "\n" );
1074 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1079 * Intended to be compatible with the PEAR::DB wrapper functions.
1080 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1082 * ? = scalar value, quoted as necessary
1083 * ! = raw SQL bit (a function for instance)
1084 * & = filename; reads the file and inserts as a blob
1085 * (we don't use this though...)
1087 * @param string $sql
1088 * @param string $func
1092 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1093 /* MySQL doesn't support prepared statements (yet), so just
1094 * pack up the query for reference. We'll manually replace
1097 return array( 'query' => $sql, 'func' => $func );
1101 * Free a prepared query, generated by prepare().
1102 * @param string $prepared
1104 protected function freePrepared( $prepared ) {
1105 /* No-op by default */
1109 * Execute a prepared query with the various arguments
1110 * @param string $prepared The prepared sql
1111 * @param mixed $args Either an array here, or put scalars as varargs
1113 * @return ResultWrapper
1115 public function execute( $prepared, $args = null ) {
1116 if ( !is_array( $args ) ) {
1118 $args = func_get_args();
1119 array_shift( $args );
1122 $sql = $this->fillPrepared( $prepared['query'], $args );
1124 return $this->query( $sql, $prepared['func'] );
1128 * For faking prepared SQL statements on DBs that don't support it directly.
1130 * @param string $preparedQuery A 'preparable' SQL statement
1131 * @param array $args Array of Arguments to fill it with
1132 * @return string Executable SQL
1134 public function fillPrepared( $preparedQuery, $args ) {
1136 $this->preparedArgs
=& $args;
1138 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1139 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1143 * preg_callback func for fillPrepared()
1144 * The arguments should be in $this->preparedArgs and must not be touched
1145 * while we're doing this.
1147 * @param array $matches
1148 * @throws DBUnexpectedError
1151 protected function fillPreparedArg( $matches ) {
1152 switch ( $matches[1] ) {
1161 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1163 switch ( $matches[1] ) {
1165 return $this->addQuotes( $arg );
1169 # return $this->addQuotes( file_get_contents( $arg ) );
1170 throw new DBUnexpectedError(
1172 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1175 throw new DBUnexpectedError(
1177 'Received invalid match. This should never happen!'
1183 * Free a result object returned by query() or select(). It's usually not
1184 * necessary to call this, just use unset() or let the variable holding
1185 * the result object go out of scope.
1187 * @param mixed $res A SQL result
1189 public function freeResult( $res ) {
1193 * A SELECT wrapper which returns a single field from a single result row.
1195 * Usually throws a DBQueryError on failure. If errors are explicitly
1196 * ignored, returns false on failure.
1198 * If no result rows are returned from the query, false is returned.
1200 * @param string|array $table Table name. See DatabaseBase::select() for details.
1201 * @param string $var The field name to select. This must be a valid SQL
1202 * fragment: do not use unvalidated user input.
1203 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1204 * @param string $fname The function name of the caller.
1205 * @param string|array $options The query options. See DatabaseBase::select() for details.
1207 * @return bool|mixed The value from the field, or false on failure.
1208 * @throws DBUnexpectedError
1210 public function selectField(
1211 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1213 if ( $var === '*' ) { // sanity
1214 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1217 if ( !is_array( $options ) ) {
1218 $options = array( $options );
1221 $options['LIMIT'] = 1;
1223 $res = $this->select( $table, $var, $cond, $fname, $options );
1224 if ( $res === false ||
!$this->numRows( $res ) ) {
1228 $row = $this->fetchRow( $res );
1230 if ( $row !== false ) {
1231 return reset( $row );
1238 * A SELECT wrapper which returns a list of single field values from result rows.
1240 * Usually throws a DBQueryError on failure. If errors are explicitly
1241 * ignored, returns false on failure.
1243 * If no result rows are returned from the query, false is returned.
1245 * @param string|array $table Table name. See DatabaseBase::select() for details.
1246 * @param string $var The field name to select. This must be a valid SQL
1247 * fragment: do not use unvalidated user input.
1248 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1249 * @param string $fname The function name of the caller.
1250 * @param string|array $options The query options. See DatabaseBase::select() for details.
1252 * @return bool|array The values from the field, or false on failure
1253 * @throws DBUnexpectedError
1256 public function selectFieldValues(
1257 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1259 if ( $var === '*' ) { // sanity
1260 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1263 if ( !is_array( $options ) ) {
1264 $options = array( $options );
1267 $res = $this->select( $table, $var, $cond, $fname, $options );
1268 if ( $res === false ) {
1273 foreach ( $res as $row ) {
1274 $values[] = $row->$var;
1281 * Returns an optional USE INDEX clause to go after the table, and a
1282 * string to go at the end of the query.
1284 * @param array $options Associative array of options to be turned into
1285 * an SQL query, valid keys are listed in the function.
1287 * @see DatabaseBase::select()
1289 public function makeSelectOptions( $options ) {
1290 $preLimitTail = $postLimitTail = '';
1293 $noKeyOptions = array();
1295 foreach ( $options as $key => $option ) {
1296 if ( is_numeric( $key ) ) {
1297 $noKeyOptions[$option] = true;
1301 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1303 $preLimitTail .= $this->makeOrderBy( $options );
1305 // if (isset($options['LIMIT'])) {
1306 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1307 // isset($options['OFFSET']) ? $options['OFFSET']
1311 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1312 $postLimitTail .= ' FOR UPDATE';
1315 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1316 $postLimitTail .= ' LOCK IN SHARE MODE';
1319 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1320 $startOpts .= 'DISTINCT';
1323 # Various MySQL extensions
1324 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1325 $startOpts .= ' /*! STRAIGHT_JOIN */';
1328 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1329 $startOpts .= ' HIGH_PRIORITY';
1332 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1333 $startOpts .= ' SQL_BIG_RESULT';
1336 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1337 $startOpts .= ' SQL_BUFFER_RESULT';
1340 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1341 $startOpts .= ' SQL_SMALL_RESULT';
1344 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1345 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1348 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1349 $startOpts .= ' SQL_CACHE';
1352 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1353 $startOpts .= ' SQL_NO_CACHE';
1356 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1357 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1362 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1366 * Returns an optional GROUP BY with an optional HAVING
1368 * @param array $options Associative array of options
1370 * @see DatabaseBase::select()
1373 public function makeGroupByWithHaving( $options ) {
1375 if ( isset( $options['GROUP BY'] ) ) {
1376 $gb = is_array( $options['GROUP BY'] )
1377 ?
implode( ',', $options['GROUP BY'] )
1378 : $options['GROUP BY'];
1379 $sql .= ' GROUP BY ' . $gb;
1381 if ( isset( $options['HAVING'] ) ) {
1382 $having = is_array( $options['HAVING'] )
1383 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1384 : $options['HAVING'];
1385 $sql .= ' HAVING ' . $having;
1392 * Returns an optional ORDER BY
1394 * @param array $options Associative array of options
1396 * @see DatabaseBase::select()
1399 public function makeOrderBy( $options ) {
1400 if ( isset( $options['ORDER BY'] ) ) {
1401 $ob = is_array( $options['ORDER BY'] )
1402 ?
implode( ',', $options['ORDER BY'] )
1403 : $options['ORDER BY'];
1405 return ' ORDER BY ' . $ob;
1412 * Execute a SELECT query constructed using the various parameters provided.
1413 * See below for full details of the parameters.
1415 * @param string|array $table Table name
1416 * @param string|array $vars Field names
1417 * @param string|array $conds Conditions
1418 * @param string $fname Caller function name
1419 * @param array $options Query options
1420 * @param array $join_conds Join conditions
1423 * @param string|array $table
1425 * May be either an array of table names, or a single string holding a table
1426 * name. If an array is given, table aliases can be specified, for example:
1428 * array( 'a' => 'user' )
1430 * This includes the user table in the query, with the alias "a" available
1431 * for use in field names (e.g. a.user_name).
1433 * All of the table names given here are automatically run through
1434 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1435 * added, and various other table name mappings to be performed.
1438 * @param string|array $vars
1440 * May be either a field name or an array of field names. The field names
1441 * can be complete fragments of SQL, for direct inclusion into the SELECT
1442 * query. If an array is given, field aliases can be specified, for example:
1444 * array( 'maxrev' => 'MAX(rev_id)' )
1446 * This includes an expression with the alias "maxrev" in the query.
1448 * If an expression is given, care must be taken to ensure that it is
1452 * @param string|array $conds
1454 * May be either a string containing a single condition, or an array of
1455 * conditions. If an array is given, the conditions constructed from each
1456 * element are combined with AND.
1458 * Array elements may take one of two forms:
1460 * - Elements with a numeric key are interpreted as raw SQL fragments.
1461 * - Elements with a string key are interpreted as equality conditions,
1462 * where the key is the field name.
1463 * - If the value of such an array element is a scalar (such as a
1464 * string), it will be treated as data and thus quoted appropriately.
1465 * If it is null, an IS NULL clause will be added.
1466 * - If the value is an array, an IN (...) clause will be constructed
1467 * from its non-null elements, and an IS NULL clause will be added
1468 * if null is present, such that the field may match any of the
1469 * elements in the array. The non-null elements will be quoted.
1471 * Note that expressions are often DBMS-dependent in their syntax.
1472 * DBMS-independent wrappers are provided for constructing several types of
1473 * expression commonly used in condition queries. See:
1474 * - DatabaseBase::buildLike()
1475 * - DatabaseBase::conditional()
1478 * @param string|array $options
1480 * Optional: Array of query options. Boolean options are specified by
1481 * including them in the array as a string value with a numeric key, for
1484 * array( 'FOR UPDATE' )
1486 * The supported options are:
1488 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1489 * with LIMIT can theoretically be used for paging through a result set,
1490 * but this is discouraged in MediaWiki for performance reasons.
1492 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1493 * and then the first rows are taken until the limit is reached. LIMIT
1494 * is applied to a result set after OFFSET.
1496 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1497 * changed until the next COMMIT.
1499 * - DISTINCT: Boolean: return only unique result rows.
1501 * - GROUP BY: May be either an SQL fragment string naming a field or
1502 * expression to group by, or an array of such SQL fragments.
1504 * - HAVING: May be either an string containing a HAVING clause or an array of
1505 * conditions building the HAVING clause. If an array is given, the conditions
1506 * constructed from each element are combined with AND.
1508 * - ORDER BY: May be either an SQL fragment giving a field name or
1509 * expression to order by, or an array of such SQL fragments.
1511 * - USE INDEX: This may be either a string giving the index name to use
1512 * for the query, or an array. If it is an associative array, each key
1513 * gives the table name (or alias), each value gives the index name to
1514 * use for that table. All strings are SQL fragments and so should be
1515 * validated by the caller.
1517 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1518 * instead of SELECT.
1520 * And also the following boolean MySQL extensions, see the MySQL manual
1521 * for documentation:
1523 * - LOCK IN SHARE MODE
1527 * - SQL_BUFFER_RESULT
1528 * - SQL_SMALL_RESULT
1529 * - SQL_CALC_FOUND_ROWS
1534 * @param string|array $join_conds
1536 * Optional associative array of table-specific join conditions. In the
1537 * most common case, this is unnecessary, since the join condition can be
1538 * in $conds. However, it is useful for doing a LEFT JOIN.
1540 * The key of the array contains the table name or alias. The value is an
1541 * array with two elements, numbered 0 and 1. The first gives the type of
1542 * join, the second is an SQL fragment giving the join condition for that
1543 * table. For example:
1545 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1547 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1548 * with no rows in it will be returned. If there was a query error, a
1549 * DBQueryError exception will be thrown, except if the "ignore errors"
1550 * option was set, in which case false will be returned.
1552 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1553 $options = array(), $join_conds = array() ) {
1554 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1556 return $this->query( $sql, $fname );
1560 * The equivalent of DatabaseBase::select() except that the constructed SQL
1561 * is returned, instead of being immediately executed. This can be useful for
1562 * doing UNION queries, where the SQL text of each query is needed. In general,
1563 * however, callers outside of Database classes should just use select().
1565 * @param string|array $table Table name
1566 * @param string|array $vars Field names
1567 * @param string|array $conds Conditions
1568 * @param string $fname Caller function name
1569 * @param string|array $options Query options
1570 * @param string|array $join_conds Join conditions
1572 * @return string SQL query string.
1573 * @see DatabaseBase::select()
1575 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1576 $options = array(), $join_conds = array()
1578 if ( is_array( $vars ) ) {
1579 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1582 $options = (array)$options;
1583 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1584 ?
$options['USE INDEX']
1587 if ( is_array( $table ) ) {
1589 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1590 } elseif ( $table != '' ) {
1591 if ( $table[0] == ' ' ) {
1592 $from = ' FROM ' . $table;
1595 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1601 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1602 $this->makeSelectOptions( $options );
1604 if ( !empty( $conds ) ) {
1605 if ( is_array( $conds ) ) {
1606 $conds = $this->makeList( $conds, LIST_AND
);
1608 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1610 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1613 if ( isset( $options['LIMIT'] ) ) {
1614 $sql = $this->limitResult( $sql, $options['LIMIT'],
1615 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1617 $sql = "$sql $postLimitTail";
1619 if ( isset( $options['EXPLAIN'] ) ) {
1620 $sql = 'EXPLAIN ' . $sql;
1627 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1628 * that a single row object is returned. If the query returns no rows,
1629 * false is returned.
1631 * @param string|array $table Table name
1632 * @param string|array $vars Field names
1633 * @param array $conds Conditions
1634 * @param string $fname Caller function name
1635 * @param string|array $options Query options
1636 * @param array|string $join_conds Join conditions
1638 * @return stdClass|bool
1640 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1641 $options = array(), $join_conds = array()
1643 $options = (array)$options;
1644 $options['LIMIT'] = 1;
1645 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1647 if ( $res === false ) {
1651 if ( !$this->numRows( $res ) ) {
1655 $obj = $this->fetchObject( $res );
1661 * Estimate the number of rows in dataset
1663 * MySQL allows you to estimate the number of rows that would be returned
1664 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1665 * index cardinality statistics, and is notoriously inaccurate, especially
1666 * when large numbers of rows have recently been added or deleted.
1668 * For DBMSs that don't support fast result size estimation, this function
1669 * will actually perform the SELECT COUNT(*).
1671 * Takes the same arguments as DatabaseBase::select().
1673 * @param string $table Table name
1674 * @param string $vars Unused
1675 * @param array|string $conds Filters on the table
1676 * @param string $fname Function name for profiling
1677 * @param array $options Options for select
1678 * @return int Row count
1680 public function estimateRowCount(
1681 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1684 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1687 $row = $this->fetchRow( $res );
1688 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1695 * Get the number of rows in dataset
1697 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1699 * Takes the same arguments as DatabaseBase::select().
1701 * @param string $table Table name
1702 * @param string $vars Unused
1703 * @param array|string $conds Filters on the table
1704 * @param string $fname Function name for profiling
1705 * @param array $options Options for select
1706 * @return int Row count
1709 public function selectRowCount(
1710 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1713 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1714 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1717 $row = $this->fetchRow( $res );
1718 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1725 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1726 * It's only slightly flawed. Don't use for anything important.
1728 * @param string $sql A SQL Query
1732 protected static function generalizeSQL( $sql ) {
1733 # This does the same as the regexp below would do, but in such a way
1734 # as to avoid crashing php on some large strings.
1735 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1737 $sql = str_replace( "\\\\", '', $sql );
1738 $sql = str_replace( "\\'", '', $sql );
1739 $sql = str_replace( "\\\"", '', $sql );
1740 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1741 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1743 # All newlines, tabs, etc replaced by single space
1744 $sql = preg_replace( '/\s+/', ' ', $sql );
1747 # except the ones surrounded by characters, e.g. l10n
1748 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1749 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1755 * Determines whether a field exists in a table
1757 * @param string $table Table name
1758 * @param string $field Filed to check on that table
1759 * @param string $fname Calling function name (optional)
1760 * @return bool Whether $table has filed $field
1762 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1763 $info = $this->fieldInfo( $table, $field );
1769 * Determines whether an index exists
1770 * Usually throws a DBQueryError on failure
1771 * If errors are explicitly ignored, returns NULL on failure
1773 * @param string $table
1774 * @param string $index
1775 * @param string $fname
1778 public function indexExists( $table, $index, $fname = __METHOD__
) {
1779 if ( !$this->tableExists( $table ) ) {
1783 $info = $this->indexInfo( $table, $index, $fname );
1784 if ( is_null( $info ) ) {
1787 return $info !== false;
1792 * Query whether a given table exists
1794 * @param string $table
1795 * @param string $fname
1798 public function tableExists( $table, $fname = __METHOD__
) {
1799 $table = $this->tableName( $table );
1800 $old = $this->ignoreErrors( true );
1801 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1802 $this->ignoreErrors( $old );
1808 * Determines if a given index is unique
1810 * @param string $table
1811 * @param string $index
1815 public function indexUnique( $table, $index ) {
1816 $indexInfo = $this->indexInfo( $table, $index );
1818 if ( !$indexInfo ) {
1822 return !$indexInfo[0]->Non_unique
;
1826 * Helper for DatabaseBase::insert().
1828 * @param array $options
1831 protected function makeInsertOptions( $options ) {
1832 return implode( ' ', $options );
1836 * INSERT wrapper, inserts an array into a table.
1840 * - A single associative array. The array keys are the field names, and
1841 * the values are the values to insert. The values are treated as data
1842 * and will be quoted appropriately. If NULL is inserted, this will be
1843 * converted to a database NULL.
1844 * - An array with numeric keys, holding a list of associative arrays.
1845 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1846 * each subarray must be identical to each other, and in the same order.
1848 * $options is an array of options, with boolean options encoded as values
1849 * with numeric keys, in the same style as $options in
1850 * DatabaseBase::select(). Supported options are:
1852 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1853 * any rows which cause duplicate key errors are not inserted. It's
1854 * possible to determine how many rows were successfully inserted using
1855 * DatabaseBase::affectedRows().
1857 * @param string $table Table name. This will be passed through
1858 * DatabaseBase::tableName().
1859 * @param array $a Array of rows to insert
1860 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1861 * @param array $options Array of options
1863 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1868 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1869 # No rows to insert, easy just return now
1870 if ( !count( $a ) ) {
1874 $table = $this->tableName( $table );
1876 if ( !is_array( $options ) ) {
1877 $options = array( $options );
1881 if ( isset( $options['fileHandle'] ) ) {
1882 $fh = $options['fileHandle'];
1884 $options = $this->makeInsertOptions( $options );
1886 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1888 $keys = array_keys( $a[0] );
1891 $keys = array_keys( $a );
1894 $sql = 'INSERT ' . $options .
1895 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1899 foreach ( $a as $row ) {
1905 $sql .= '(' . $this->makeList( $row ) . ')';
1908 $sql .= '(' . $this->makeList( $a ) . ')';
1911 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1913 } elseif ( $fh !== null ) {
1917 return (bool)$this->query( $sql, $fname );
1921 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1923 * @param array $options
1926 protected function makeUpdateOptionsArray( $options ) {
1927 if ( !is_array( $options ) ) {
1928 $options = array( $options );
1933 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1934 $opts[] = $this->lowPriorityOption();
1937 if ( in_array( 'IGNORE', $options ) ) {
1945 * Make UPDATE options for the DatabaseBase::update function
1947 * @param array $options The options passed to DatabaseBase::update
1950 protected function makeUpdateOptions( $options ) {
1951 $opts = $this->makeUpdateOptionsArray( $options );
1953 return implode( ' ', $opts );
1957 * UPDATE wrapper. Takes a condition array and a SET array.
1959 * @param string $table Name of the table to UPDATE. This will be passed through
1960 * DatabaseBase::tableName().
1961 * @param array $values An array of values to SET. For each array element,
1962 * the key gives the field name, and the value gives the data to set
1963 * that field to. The data will be quoted by DatabaseBase::addQuotes().
1964 * @param array $conds An array of conditions (WHERE). See
1965 * DatabaseBase::select() for the details of the format of condition
1966 * arrays. Use '*' to update all rows.
1967 * @param string $fname The function name of the caller (from __METHOD__),
1968 * for logging and profiling.
1969 * @param array $options An array of UPDATE options, can be:
1970 * - IGNORE: Ignore unique key conflicts
1971 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1974 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
1975 $table = $this->tableName( $table );
1976 $opts = $this->makeUpdateOptions( $options );
1977 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1979 if ( $conds !== array() && $conds !== '*' ) {
1980 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1983 return $this->query( $sql, $fname );
1987 * Makes an encoded list of strings from an array
1989 * @param array $a Containing the data
1990 * @param int $mode Constant
1991 * - LIST_COMMA: Comma separated, no field names
1992 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
1993 * documentation for $conds in DatabaseBase::select().
1994 * - LIST_OR: ORed WHERE clause (without the WHERE)
1995 * - LIST_SET: Comma separated with field names, like a SET clause
1996 * - LIST_NAMES: Comma separated field names
1997 * @throws MWException|DBUnexpectedError
2000 public function makeList( $a, $mode = LIST_COMMA
) {
2001 if ( !is_array( $a ) ) {
2002 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2008 foreach ( $a as $field => $value ) {
2010 if ( $mode == LIST_AND
) {
2012 } elseif ( $mode == LIST_OR
) {
2021 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2022 $list .= "($value)";
2023 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2025 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2026 // Remove null from array to be handled separately if found
2027 $includeNull = false;
2028 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2029 $includeNull = true;
2030 unset( $value[$nullKey] );
2032 if ( count( $value ) == 0 && !$includeNull ) {
2033 throw new MWException( __METHOD__
. ": empty input for field $field" );
2034 } elseif ( count( $value ) == 0 ) {
2035 // only check if $field is null
2036 $list .= "$field IS NULL";
2038 // IN clause contains at least one valid element
2039 if ( $includeNull ) {
2040 // Group subconditions to ensure correct precedence
2043 if ( count( $value ) == 1 ) {
2044 // Special-case single values, as IN isn't terribly efficient
2045 // Don't necessarily assume the single key is 0; we don't
2046 // enforce linear numeric ordering on other arrays here.
2047 $value = array_values( $value );
2048 $list .= $field . " = " . $this->addQuotes( $value[0] );
2050 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2052 // if null present in array, append IS NULL
2053 if ( $includeNull ) {
2054 $list .= " OR $field IS NULL)";
2057 } elseif ( $value === null ) {
2058 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2059 $list .= "$field IS ";
2060 } elseif ( $mode == LIST_SET
) {
2061 $list .= "$field = ";
2065 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2066 $list .= "$field = ";
2068 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2076 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2077 * The keys on each level may be either integers or strings.
2079 * @param array $data Organized as 2-d
2080 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2081 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2082 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2083 * @return string|bool SQL fragment, or false if no items in array
2085 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2088 foreach ( $data as $base => $sub ) {
2089 if ( count( $sub ) ) {
2090 $conds[] = $this->makeList(
2091 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2097 return $this->makeList( $conds, LIST_OR
);
2099 // Nothing to search for...
2105 * Return aggregated value alias
2107 * @param array $valuedata
2108 * @param string $valuename
2112 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2117 * @param string $field
2120 public function bitNot( $field ) {
2125 * @param string $fieldLeft
2126 * @param string $fieldRight
2129 public function bitAnd( $fieldLeft, $fieldRight ) {
2130 return "($fieldLeft & $fieldRight)";
2134 * @param string $fieldLeft
2135 * @param string $fieldRight
2138 public function bitOr( $fieldLeft, $fieldRight ) {
2139 return "($fieldLeft | $fieldRight)";
2143 * Build a concatenation list to feed into a SQL query
2144 * @param array $stringList List of raw SQL expressions; caller is
2145 * responsible for any quoting
2148 public function buildConcat( $stringList ) {
2149 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2153 * Build a GROUP_CONCAT or equivalent statement for a query.
2155 * This is useful for combining a field for several rows into a single string.
2156 * NULL values will not appear in the output, duplicated values will appear,
2157 * and the resulting delimiter-separated values have no defined sort order.
2158 * Code using the results may need to use the PHP unique() or sort() methods.
2160 * @param string $delim Glue to bind the results together
2161 * @param string|array $table Table name
2162 * @param string $field Field name
2163 * @param string|array $conds Conditions
2164 * @param string|array $join_conds Join conditions
2165 * @return string SQL text
2168 public function buildGroupConcatField(
2169 $delim, $table, $field, $conds = '', $join_conds = array()
2171 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2173 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2177 * Change the current database
2179 * @todo Explain what exactly will fail if this is not overridden.
2183 * @return bool Success or failure
2185 public function selectDB( $db ) {
2186 # Stub. Shouldn't cause serious problems if it's not overridden, but
2187 # if your database engine supports a concept similar to MySQL's
2188 # databases you may as well.
2189 $this->mDBname
= $db;
2195 * Get the current DB name
2198 public function getDBname() {
2199 return $this->mDBname
;
2203 * Get the server hostname or IP address
2206 public function getServer() {
2207 return $this->mServer
;
2211 * Format a table name ready for use in constructing an SQL query
2213 * This does two important things: it quotes the table names to clean them up,
2214 * and it adds a table prefix if only given a table name with no quotes.
2216 * All functions of this object which require a table name call this function
2217 * themselves. Pass the canonical name to such functions. This is only needed
2218 * when calling query() directly.
2220 * @param string $name Database table name
2221 * @param string $format One of:
2222 * quoted - Automatically pass the table name through addIdentifierQuotes()
2223 * so that it can be used in a query.
2224 * raw - Do not add identifier quotes to the table name
2225 * @return string Full database name
2227 public function tableName( $name, $format = 'quoted' ) {
2228 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2229 # Skip the entire process when we have a string quoted on both ends.
2230 # Note that we check the end so that we will still quote any use of
2231 # use of `database`.table. But won't break things if someone wants
2232 # to query a database table with a dot in the name.
2233 if ( $this->isQuotedIdentifier( $name ) ) {
2237 # Lets test for any bits of text that should never show up in a table
2238 # name. Basically anything like JOIN or ON which are actually part of
2239 # SQL queries, but may end up inside of the table value to combine
2240 # sql. Such as how the API is doing.
2241 # Note that we use a whitespace test rather than a \b test to avoid
2242 # any remote case where a word like on may be inside of a table name
2243 # surrounded by symbols which may be considered word breaks.
2244 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2248 # Split database and table into proper variables.
2249 # We reverse the explode so that database.table and table both output
2250 # the correct table.
2251 $dbDetails = explode( '.', $name, 3 );
2252 if ( count( $dbDetails ) == 3 ) {
2253 list( $database, $schema, $table ) = $dbDetails;
2254 # We don't want any prefix added in this case
2256 } elseif ( count( $dbDetails ) == 2 ) {
2257 list( $database, $table ) = $dbDetails;
2258 # We don't want any prefix added in this case
2259 # In dbs that support it, $database may actually be the schema
2260 # but that doesn't affect any of the functionality here
2264 list( $table ) = $dbDetails;
2265 if ( $wgSharedDB !== null # We have a shared database
2266 && $this->mForeign
== false # We're not working on a foreign database
2267 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2268 && in_array( $table, $wgSharedTables ) # A shared table is selected
2270 $database = $wgSharedDB;
2271 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2272 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2275 $schema = $this->mSchema
; # Default schema
2276 $prefix = $this->mTablePrefix
; # Default prefix
2280 # Quote $table and apply the prefix if not quoted.
2281 # $tableName might be empty if this is called from Database::replaceVars()
2282 $tableName = "{$prefix}{$table}";
2283 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2284 $tableName = $this->addIdentifierQuotes( $tableName );
2287 # Quote $schema and merge it with the table name if needed
2288 if ( strlen( $schema ) ) {
2289 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2290 $schema = $this->addIdentifierQuotes( $schema );
2292 $tableName = $schema . '.' . $tableName;
2295 # Quote $database and merge it with the table name if needed
2296 if ( $database !== null ) {
2297 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2298 $database = $this->addIdentifierQuotes( $database );
2300 $tableName = $database . '.' . $tableName;
2307 * Fetch a number of table names into an array
2308 * This is handy when you need to construct SQL for joins
2311 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2312 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2313 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2317 public function tableNames() {
2318 $inArray = func_get_args();
2321 foreach ( $inArray as $name ) {
2322 $retVal[$name] = $this->tableName( $name );
2329 * Fetch a number of table names into an zero-indexed numerical array
2330 * This is handy when you need to construct SQL for joins
2333 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2334 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2335 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2339 public function tableNamesN() {
2340 $inArray = func_get_args();
2343 foreach ( $inArray as $name ) {
2344 $retVal[] = $this->tableName( $name );
2351 * Get an aliased table name
2352 * e.g. tableName AS newTableName
2354 * @param string $name Table name, see tableName()
2355 * @param string|bool $alias Alias (optional)
2356 * @return string SQL name for aliased table. Will not alias a table to its own name
2358 public function tableNameWithAlias( $name, $alias = false ) {
2359 if ( !$alias ||
$alias == $name ) {
2360 return $this->tableName( $name );
2362 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2367 * Gets an array of aliased table names
2369 * @param array $tables Array( [alias] => table )
2370 * @return string[] See tableNameWithAlias()
2372 public function tableNamesWithAlias( $tables ) {
2374 foreach ( $tables as $alias => $table ) {
2375 if ( is_numeric( $alias ) ) {
2378 $retval[] = $this->tableNameWithAlias( $table, $alias );
2385 * Get an aliased field name
2386 * e.g. fieldName AS newFieldName
2388 * @param string $name Field name
2389 * @param string|bool $alias Alias (optional)
2390 * @return string SQL name for aliased field. Will not alias a field to its own name
2392 public function fieldNameWithAlias( $name, $alias = false ) {
2393 if ( !$alias ||
(string)$alias === (string)$name ) {
2396 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2401 * Gets an array of aliased field names
2403 * @param array $fields Array( [alias] => field )
2404 * @return string[] See fieldNameWithAlias()
2406 public function fieldNamesWithAlias( $fields ) {
2408 foreach ( $fields as $alias => $field ) {
2409 if ( is_numeric( $alias ) ) {
2412 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2419 * Get the aliased table name clause for a FROM clause
2420 * which might have a JOIN and/or USE INDEX clause
2422 * @param array $tables ( [alias] => table )
2423 * @param array $use_index Same as for select()
2424 * @param array $join_conds Same as for select()
2427 protected function tableNamesWithUseIndexOrJOIN(
2428 $tables, $use_index = array(), $join_conds = array()
2432 $use_index = (array)$use_index;
2433 $join_conds = (array)$join_conds;
2435 foreach ( $tables as $alias => $table ) {
2436 if ( !is_string( $alias ) ) {
2437 // No alias? Set it equal to the table name
2440 // Is there a JOIN clause for this table?
2441 if ( isset( $join_conds[$alias] ) ) {
2442 list( $joinType, $conds ) = $join_conds[$alias];
2443 $tableClause = $joinType;
2444 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2445 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2446 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2448 $tableClause .= ' ' . $use;
2451 $on = $this->makeList( (array)$conds, LIST_AND
);
2453 $tableClause .= ' ON (' . $on . ')';
2456 $retJOIN[] = $tableClause;
2457 } elseif ( isset( $use_index[$alias] ) ) {
2458 // Is there an INDEX clause for this table?
2459 $tableClause = $this->tableNameWithAlias( $table, $alias );
2460 $tableClause .= ' ' . $this->useIndexClause(
2461 implode( ',', (array)$use_index[$alias] )
2464 $ret[] = $tableClause;
2466 $tableClause = $this->tableNameWithAlias( $table, $alias );
2468 $ret[] = $tableClause;
2472 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2473 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2474 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2476 // Compile our final table clause
2477 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2481 * Get the name of an index in a given table.
2483 * @protected Don't use outside of DatabaseBase and childs
2484 * @param string $index
2487 public function indexName( $index ) {
2488 // @FIXME: Make this protected once we move away from PHP 5.3
2489 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2491 // Backwards-compatibility hack
2493 'ar_usertext_timestamp' => 'usertext_timestamp',
2494 'un_user_id' => 'user_id',
2495 'un_user_ip' => 'user_ip',
2498 if ( isset( $renamed[$index] ) ) {
2499 return $renamed[$index];
2506 * Adds quotes and backslashes.
2508 * @param string|Blob $s
2511 public function addQuotes( $s ) {
2512 if ( $s instanceof Blob
) {
2515 if ( $s === null ) {
2518 # This will also quote numeric values. This should be harmless,
2519 # and protects against weird problems that occur when they really
2520 # _are_ strings such as article titles and string->number->string
2521 # conversion is not 1:1.
2522 return "'" . $this->strencode( $s ) . "'";
2527 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2528 * MySQL uses `backticks` while basically everything else uses double quotes.
2529 * Since MySQL is the odd one out here the double quotes are our generic
2530 * and we implement backticks in DatabaseMysql.
2535 public function addIdentifierQuotes( $s ) {
2536 return '"' . str_replace( '"', '""', $s ) . '"';
2540 * Returns if the given identifier looks quoted or not according to
2541 * the database convention for quoting identifiers .
2543 * @param string $name
2546 public function isQuotedIdentifier( $name ) {
2547 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2554 protected function escapeLikeInternal( $s ) {
2555 return addcslashes( $s, '\%_' );
2559 * LIKE statement wrapper, receives a variable-length argument list with
2560 * parts of pattern to match containing either string literals that will be
2561 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2562 * the function could be provided with an array of aforementioned
2565 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2566 * a LIKE clause that searches for subpages of 'My page title'.
2568 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2569 * $query .= $dbr->buildLike( $pattern );
2572 * @return string Fully built LIKE statement
2574 public function buildLike() {
2575 $params = func_get_args();
2577 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2578 $params = $params[0];
2583 foreach ( $params as $value ) {
2584 if ( $value instanceof LikeMatch
) {
2585 $s .= $value->toString();
2587 $s .= $this->escapeLikeInternal( $value );
2591 return " LIKE {$this->addQuotes( $s )} ";
2595 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2599 public function anyChar() {
2600 return new LikeMatch( '_' );
2604 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2608 public function anyString() {
2609 return new LikeMatch( '%' );
2613 * Returns an appropriately quoted sequence value for inserting a new row.
2614 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2615 * subclass will return an integer, and save the value for insertId()
2617 * Any implementation of this function should *not* involve reusing
2618 * sequence numbers created for rolled-back transactions.
2619 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2620 * @param string $seqName
2623 public function nextSequenceValue( $seqName ) {
2628 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2629 * is only needed because a) MySQL must be as efficient as possible due to
2630 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2631 * which index to pick. Anyway, other databases might have different
2632 * indexes on a given table. So don't bother overriding this unless you're
2634 * @param string $index
2637 public function useIndexClause( $index ) {
2642 * REPLACE query wrapper.
2644 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2645 * except that when there is a duplicate key error, the old row is deleted
2646 * and the new row is inserted in its place.
2648 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2649 * perform the delete, we need to know what the unique indexes are so that
2650 * we know how to find the conflicting rows.
2652 * It may be more efficient to leave off unique indexes which are unlikely
2653 * to collide. However if you do this, you run the risk of encountering
2654 * errors which wouldn't have occurred in MySQL.
2656 * @param string $table The table to replace the row(s) in.
2657 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2658 * a field name or an array of field names
2659 * @param array $rows Can be either a single row to insert, or multiple rows,
2660 * in the same format as for DatabaseBase::insert()
2661 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2663 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2664 $quotedTable = $this->tableName( $table );
2666 if ( count( $rows ) == 0 ) {
2671 if ( !is_array( reset( $rows ) ) ) {
2672 $rows = array( $rows );
2675 // @FXIME: this is not atomic, but a trx would break affectedRows()
2676 foreach ( $rows as $row ) {
2677 # Delete rows which collide
2678 if ( $uniqueIndexes ) {
2679 $sql = "DELETE FROM $quotedTable WHERE ";
2681 foreach ( $uniqueIndexes as $index ) {
2688 if ( is_array( $index ) ) {
2690 foreach ( $index as $col ) {
2696 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2699 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2703 $this->query( $sql, $fname );
2706 # Now insert the row
2707 $this->insert( $table, $row, $fname );
2712 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2715 * @param string $table Table name
2716 * @param array|string $rows Row(s) to insert
2717 * @param string $fname Caller function name
2719 * @return ResultWrapper
2721 protected function nativeReplace( $table, $rows, $fname ) {
2722 $table = $this->tableName( $table );
2725 if ( !is_array( reset( $rows ) ) ) {
2726 $rows = array( $rows );
2729 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2732 foreach ( $rows as $row ) {
2739 $sql .= '(' . $this->makeList( $row ) . ')';
2742 return $this->query( $sql, $fname );
2746 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2748 * This updates any conflicting rows (according to the unique indexes) using
2749 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2751 * $rows may be either:
2752 * - A single associative array. The array keys are the field names, and
2753 * the values are the values to insert. The values are treated as data
2754 * and will be quoted appropriately. If NULL is inserted, this will be
2755 * converted to a database NULL.
2756 * - An array with numeric keys, holding a list of associative arrays.
2757 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2758 * each subarray must be identical to each other, and in the same order.
2760 * It may be more efficient to leave off unique indexes which are unlikely
2761 * to collide. However if you do this, you run the risk of encountering
2762 * errors which wouldn't have occurred in MySQL.
2764 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2769 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2770 * @param array $rows A single row or list of rows to insert
2771 * @param array $uniqueIndexes List of single field names or field name tuples
2772 * @param array $set An array of values to SET. For each array element, the
2773 * key gives the field name, and the value gives the data to set that
2774 * field to. The data will be quoted by DatabaseBase::addQuotes().
2775 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2779 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2782 if ( !count( $rows ) ) {
2783 return true; // nothing to do
2786 if ( !is_array( reset( $rows ) ) ) {
2787 $rows = array( $rows );
2790 if ( count( $uniqueIndexes ) ) {
2791 $clauses = array(); // list WHERE clauses that each identify a single row
2792 foreach ( $rows as $row ) {
2793 foreach ( $uniqueIndexes as $index ) {
2794 $index = is_array( $index ) ?
$index : array( $index ); // columns
2795 $rowKey = array(); // unique key to this row
2796 foreach ( $index as $column ) {
2797 $rowKey[$column] = $row[$column];
2799 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2802 $where = array( $this->makeList( $clauses, LIST_OR
) );
2807 $useTrx = !$this->mTrxLevel
;
2809 $this->begin( $fname );
2812 # Update any existing conflicting row(s)
2813 if ( $where !== false ) {
2814 $ok = $this->update( $table, $set, $where, $fname );
2818 # Now insert any non-conflicting row(s)
2819 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2820 } catch ( Exception
$e ) {
2822 $this->rollback( $fname );
2827 $this->commit( $fname );
2834 * DELETE where the condition is a join.
2836 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2837 * we use sub-selects
2839 * For safety, an empty $conds will not delete everything. If you want to
2840 * delete all rows where the join condition matches, set $conds='*'.
2842 * DO NOT put the join condition in $conds.
2844 * @param string $delTable The table to delete from.
2845 * @param string $joinTable The other table.
2846 * @param string $delVar The variable to join on, in the first table.
2847 * @param string $joinVar The variable to join on, in the second table.
2848 * @param array $conds Condition array of field names mapped to variables,
2849 * ANDed together in the WHERE clause
2850 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2851 * @throws DBUnexpectedError
2853 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2857 throw new DBUnexpectedError( $this,
2858 'DatabaseBase::deleteJoin() called with empty $conds' );
2861 $delTable = $this->tableName( $delTable );
2862 $joinTable = $this->tableName( $joinTable );
2863 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2864 if ( $conds != '*' ) {
2865 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2869 $this->query( $sql, $fname );
2873 * Returns the size of a text field, or -1 for "unlimited"
2875 * @param string $table
2876 * @param string $field
2879 public function textFieldSize( $table, $field ) {
2880 $table = $this->tableName( $table );
2881 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2882 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2883 $row = $this->fetchObject( $res );
2887 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2897 * A string to insert into queries to show that they're low-priority, like
2898 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2899 * string and nothing bad should happen.
2901 * @return string Returns the text of the low priority option if it is
2902 * supported, or a blank string otherwise
2904 public function lowPriorityOption() {
2909 * DELETE query wrapper.
2911 * @param array $table Table name
2912 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2913 * for the format. Use $conds == "*" to delete all rows
2914 * @param string $fname Name of the calling function
2915 * @throws DBUnexpectedError
2916 * @return bool|ResultWrapper
2918 public function delete( $table, $conds, $fname = __METHOD__
) {
2920 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2923 $table = $this->tableName( $table );
2924 $sql = "DELETE FROM $table";
2926 if ( $conds != '*' ) {
2927 if ( is_array( $conds ) ) {
2928 $conds = $this->makeList( $conds, LIST_AND
);
2930 $sql .= ' WHERE ' . $conds;
2933 return $this->query( $sql, $fname );
2937 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2938 * into another table.
2940 * @param string $destTable The table name to insert into
2941 * @param string|array $srcTable May be either a table name, or an array of table names
2942 * to include in a join.
2944 * @param array $varMap Must be an associative array of the form
2945 * array( 'dest1' => 'source1', ...). Source items may be literals
2946 * rather than field names, but strings should be quoted with
2947 * DatabaseBase::addQuotes()
2949 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2950 * the details of the format of condition arrays. May be "*" to copy the
2953 * @param string $fname The function name of the caller, from __METHOD__
2955 * @param array $insertOptions Options for the INSERT part of the query, see
2956 * DatabaseBase::insert() for details.
2957 * @param array $selectOptions Options for the SELECT part of the query, see
2958 * DatabaseBase::select() for details.
2960 * @return ResultWrapper
2962 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2963 $fname = __METHOD__
,
2964 $insertOptions = array(), $selectOptions = array()
2966 $destTable = $this->tableName( $destTable );
2968 if ( !is_array( $insertOptions ) ) {
2969 $insertOptions = array( $insertOptions );
2972 $insertOptions = $this->makeInsertOptions( $insertOptions );
2974 if ( !is_array( $selectOptions ) ) {
2975 $selectOptions = array( $selectOptions );
2978 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2980 if ( is_array( $srcTable ) ) {
2981 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2983 $srcTable = $this->tableName( $srcTable );
2986 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2987 " SELECT $startOpts " . implode( ',', $varMap ) .
2988 " FROM $srcTable $useIndex ";
2990 if ( $conds != '*' ) {
2991 if ( is_array( $conds ) ) {
2992 $conds = $this->makeList( $conds, LIST_AND
);
2994 $sql .= " WHERE $conds";
2997 $sql .= " $tailOpts";
2999 return $this->query( $sql, $fname );
3003 * Construct a LIMIT query with optional offset. This is used for query
3004 * pages. The SQL should be adjusted so that only the first $limit rows
3005 * are returned. If $offset is provided as well, then the first $offset
3006 * rows should be discarded, and the next $limit rows should be returned.
3007 * If the result of the query is not ordered, then the rows to be returned
3008 * are theoretically arbitrary.
3010 * $sql is expected to be a SELECT, if that makes a difference.
3012 * The version provided by default works in MySQL and SQLite. It will very
3013 * likely need to be overridden for most other DBMSes.
3015 * @param string $sql SQL query we will append the limit too
3016 * @param int $limit The SQL limit
3017 * @param int|bool $offset The SQL offset (default false)
3018 * @throws DBUnexpectedError
3021 public function limitResult( $sql, $limit, $offset = false ) {
3022 if ( !is_numeric( $limit ) ) {
3023 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3026 return "$sql LIMIT "
3027 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3032 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3033 * within the UNION construct.
3036 public function unionSupportsOrderAndLimit() {
3037 return true; // True for almost every DB supported
3041 * Construct a UNION query
3042 * This is used for providing overload point for other DB abstractions
3043 * not compatible with the MySQL syntax.
3044 * @param array $sqls SQL statements to combine
3045 * @param bool $all Use UNION ALL
3046 * @return string SQL fragment
3048 public function unionQueries( $sqls, $all ) {
3049 $glue = $all ?
') UNION ALL (' : ') UNION (';
3051 return '(' . implode( $glue, $sqls ) . ')';
3055 * Returns an SQL expression for a simple conditional. This doesn't need
3056 * to be overridden unless CASE isn't supported in your DBMS.
3058 * @param string|array $cond SQL expression which will result in a boolean value
3059 * @param string $trueVal SQL expression to return if true
3060 * @param string $falseVal SQL expression to return if false
3061 * @return string SQL fragment
3063 public function conditional( $cond, $trueVal, $falseVal ) {
3064 if ( is_array( $cond ) ) {
3065 $cond = $this->makeList( $cond, LIST_AND
);
3068 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3072 * Returns a comand for str_replace function in SQL query.
3073 * Uses REPLACE() in MySQL
3075 * @param string $orig Column to modify
3076 * @param string $old Column to seek
3077 * @param string $new Column to replace with
3081 public function strreplace( $orig, $old, $new ) {
3082 return "REPLACE({$orig}, {$old}, {$new})";
3086 * Determines how long the server has been up
3091 public function getServerUptime() {
3096 * Determines if the last failure was due to a deadlock
3101 public function wasDeadlock() {
3106 * Determines if the last failure was due to a lock timeout
3111 public function wasLockTimeout() {
3116 * Determines if the last query error was something that should be dealt
3117 * with by pinging the connection and reissuing the query.
3122 public function wasErrorReissuable() {
3127 * Determines if the last failure was due to the database being read-only.
3132 public function wasReadOnlyError() {
3137 * Determines if the given query error was a connection drop
3140 * @param integer|string $errno
3143 public function wasConnectionError( $errno ) {
3148 * Perform a deadlock-prone transaction.
3150 * This function invokes a callback function to perform a set of write
3151 * queries. If a deadlock occurs during the processing, the transaction
3152 * will be rolled back and the callback function will be called again.
3155 * $dbw->deadlockLoop( callback, ... );
3157 * Extra arguments are passed through to the specified callback function.
3159 * Returns whatever the callback function returned on its successful,
3160 * iteration, or false on error, for example if the retry limit was
3164 * @throws DBQueryError
3166 public function deadlockLoop() {
3167 $args = func_get_args();
3168 $function = array_shift( $args );
3169 $tries = self
::DEADLOCK_TRIES
;
3171 $this->begin( __METHOD__
);
3177 $retVal = call_user_func_array( $function, $args );
3179 } catch ( DBQueryError
$e ) {
3180 if ( $this->wasDeadlock() ) {
3181 // Retry after a randomized delay
3182 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3184 // Throw the error back up
3188 } while ( --$tries > 0 );
3190 if ( $tries <= 0 ) {
3191 // Too many deadlocks; give up
3192 $this->rollback( __METHOD__
);
3195 $this->commit( __METHOD__
);
3202 * Wait for the slave to catch up to a given master position.
3204 * @param DBMasterPos $pos
3205 * @param int $timeout The maximum number of seconds to wait for
3207 * @return int Zero if the slave was past that position already,
3208 * greater than zero if we waited for some period of time, less than
3209 * zero if we timed out.
3211 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3212 # Real waits are implemented in the subclass.
3217 * Get the replication position of this slave
3219 * @return DBMasterPos|bool False if this is not a slave.
3221 public function getSlavePos() {
3227 * Get the position of this master
3229 * @return DBMasterPos|bool False if this is not a master
3231 public function getMasterPos() {
3237 * Run an anonymous function as soon as there is no transaction pending.
3238 * If there is a transaction and it is rolled back, then the callback is cancelled.
3239 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3240 * Callbacks must commit any transactions that they begin.
3242 * This is useful for updates to different systems or when separate transactions are needed.
3243 * For example, one might want to enqueue jobs into a system outside the database, but only
3244 * after the database is updated so that the jobs will see the data when they actually run.
3245 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3247 * @param callable $callback
3250 final public function onTransactionIdle( $callback ) {
3251 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3252 if ( !$this->mTrxLevel
) {
3253 $this->runOnTransactionIdleCallbacks();
3258 * Run an anonymous function before the current transaction commits or now if there is none.
3259 * If there is a transaction and it is rolled back, then the callback is cancelled.
3260 * Callbacks must not start nor commit any transactions.
3262 * This is useful for updates that easily cause deadlocks if locks are held too long
3263 * but where atomicity is strongly desired for these updates and some related updates.
3265 * @param callable $callback
3268 final public function onTransactionPreCommitOrIdle( $callback ) {
3269 if ( $this->mTrxLevel
) {
3270 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3272 $this->onTransactionIdle( $callback ); // this will trigger immediately
3277 * Actually any "on transaction idle" callbacks.
3281 protected function runOnTransactionIdleCallbacks() {
3282 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3284 $e = $ePrior = null; // last exception
3285 do { // callbacks may add callbacks :)
3286 $callbacks = $this->mTrxIdleCallbacks
;
3287 $this->mTrxIdleCallbacks
= array(); // recursion guard
3288 foreach ( $callbacks as $callback ) {
3290 list( $phpCallback ) = $callback;
3291 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3292 call_user_func( $phpCallback );
3293 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3294 } catch ( Exception
$e ) {
3296 MWExceptionHandler
::logException( $ePrior );
3301 } while ( count( $this->mTrxIdleCallbacks
) );
3303 if ( $e instanceof Exception
) {
3304 throw $e; // re-throw any last exception
3309 * Actually any "on transaction pre-commit" callbacks.
3313 protected function runOnTransactionPreCommitCallbacks() {
3314 $e = $ePrior = null; // last exception
3315 do { // callbacks may add callbacks :)
3316 $callbacks = $this->mTrxPreCommitCallbacks
;
3317 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3318 foreach ( $callbacks as $callback ) {
3320 list( $phpCallback ) = $callback;
3321 call_user_func( $phpCallback );
3322 } catch ( Exception
$e ) {
3324 MWExceptionHandler
::logException( $ePrior );
3329 } while ( count( $this->mTrxPreCommitCallbacks
) );
3331 if ( $e instanceof Exception
) {
3332 throw $e; // re-throw any last exception
3337 * Begin an atomic section of statements
3339 * If a transaction has been started already, just keep track of the given
3340 * section name to make sure the transaction is not committed pre-maturely.
3341 * This function can be used in layers (with sub-sections), so use a stack
3342 * to keep track of the different atomic sections. If there is no transaction,
3343 * start one implicitly.
3345 * The goal of this function is to create an atomic section of SQL queries
3346 * without having to start a new transaction if it already exists.
3348 * Atomic sections are more strict than transactions. With transactions,
3349 * attempting to begin a new transaction when one is already running results
3350 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3351 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3352 * and any database transactions cannot be began or committed until all atomic
3353 * levels are closed. There is no such thing as implicitly opening or closing
3354 * an atomic section.
3357 * @param string $fname
3360 final public function startAtomic( $fname = __METHOD__
) {
3361 if ( !$this->mTrxLevel
) {
3362 $this->begin( $fname );
3363 $this->mTrxAutomatic
= true;
3364 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3365 // in all changes being in one transaction to keep requests transactional.
3366 if ( !$this->getFlag( DBO_TRX
) ) {
3367 $this->mTrxAutomaticAtomic
= true;
3371 $this->mTrxAtomicLevels
[] = $fname;
3375 * Ends an atomic section of SQL statements
3377 * Ends the next section of atomic SQL statements and commits the transaction
3381 * @see DatabaseBase::startAtomic
3382 * @param string $fname
3385 final public function endAtomic( $fname = __METHOD__
) {
3386 if ( !$this->mTrxLevel
) {
3387 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3389 if ( !$this->mTrxAtomicLevels ||
3390 array_pop( $this->mTrxAtomicLevels
) !== $fname
3392 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3395 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3396 $this->commit( $fname, 'flush' );
3401 * Begin a transaction. If a transaction is already in progress,
3402 * that transaction will be committed before the new transaction is started.
3404 * Note that when the DBO_TRX flag is set (which is usually the case for web
3405 * requests, but not for maintenance scripts), any previous database query
3406 * will have started a transaction automatically.
3408 * Nesting of transactions is not supported. Attempts to nest transactions
3409 * will cause a warning, unless the current transaction was started
3410 * automatically because of the DBO_TRX flag.
3412 * @param string $fname
3415 final public function begin( $fname = __METHOD__
) {
3416 if ( $this->mTrxLevel
) { // implicit commit
3417 if ( $this->mTrxAtomicLevels
) {
3418 // If the current transaction was an automatic atomic one, then we definitely have
3419 // a problem. Same if there is any unclosed atomic level.
3420 throw new DBUnexpectedError( $this,
3421 "Attempted to start explicit transaction when atomic levels are still open."
3423 } elseif ( !$this->mTrxAutomatic
) {
3424 // We want to warn about inadvertently nested begin/commit pairs, but not about
3425 // auto-committing implicit transactions that were started by query() via DBO_TRX
3426 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3427 " performing implicit commit!";
3430 $this->getLogContext( array(
3431 'method' => __METHOD__
,
3436 // if the transaction was automatic and has done write operations
3437 if ( $this->mTrxDoneWrites
) {
3438 wfDebug( "$fname: Automatic transaction with writes in progress" .
3439 " (from {$this->mTrxFname}), performing implicit commit!\n"
3444 $this->runOnTransactionPreCommitCallbacks();
3445 $writeTime = $this->pendingWriteQueryDuration();
3446 $this->doCommit( $fname );
3447 if ( $this->mTrxDoneWrites
) {
3448 $this->mDoneWrites
= microtime( true );
3449 $this->getTransactionProfiler()->transactionWritingOut(
3450 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3452 $this->runOnTransactionIdleCallbacks();
3455 # Avoid fatals if close() was called
3456 $this->assertOpen();
3458 $this->doBegin( $fname );
3459 $this->mTrxTimestamp
= microtime( true );
3460 $this->mTrxFname
= $fname;
3461 $this->mTrxDoneWrites
= false;
3462 $this->mTrxAutomatic
= false;
3463 $this->mTrxAutomaticAtomic
= false;
3464 $this->mTrxAtomicLevels
= array();
3465 $this->mTrxIdleCallbacks
= array();
3466 $this->mTrxPreCommitCallbacks
= array();
3467 $this->mTrxShortId
= wfRandomString( 12 );
3468 $this->mTrxWriteDuration
= 0.0;
3472 * Issues the BEGIN command to the database server.
3474 * @see DatabaseBase::begin()
3475 * @param string $fname
3477 protected function doBegin( $fname ) {
3478 $this->query( 'BEGIN', $fname );
3479 $this->mTrxLevel
= 1;
3483 * Commits a transaction previously started using begin().
3484 * If no transaction is in progress, a warning is issued.
3486 * Nesting of transactions is not supported.
3488 * @param string $fname
3489 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3490 * explicitly committing implicit transactions, or calling commit when no
3491 * transaction is in progress. This will silently break any ongoing
3492 * explicit transaction. Only set the flush flag if you are sure that it
3493 * is safe to ignore these warnings in your context.
3494 * @throws DBUnexpectedError
3496 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3497 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3498 // There are still atomic sections open. This cannot be ignored
3499 throw new DBUnexpectedError(
3501 "Attempted to commit transaction while atomic sections are still open"
3505 if ( $flush === 'flush' ) {
3506 if ( !$this->mTrxLevel
) {
3507 return; // nothing to do
3508 } elseif ( !$this->mTrxAutomatic
) {
3509 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3512 if ( !$this->mTrxLevel
) {
3513 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3514 return; // nothing to do
3515 } elseif ( $this->mTrxAutomatic
) {
3516 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3520 # Avoid fatals if close() was called
3521 $this->assertOpen();
3523 $this->runOnTransactionPreCommitCallbacks();
3524 $writeTime = $this->pendingWriteQueryDuration();
3525 $this->doCommit( $fname );
3526 if ( $this->mTrxDoneWrites
) {
3527 $this->mDoneWrites
= microtime( true );
3528 $this->getTransactionProfiler()->transactionWritingOut(
3529 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3531 $this->runOnTransactionIdleCallbacks();
3535 * Issues the COMMIT command to the database server.
3537 * @see DatabaseBase::commit()
3538 * @param string $fname
3540 protected function doCommit( $fname ) {
3541 if ( $this->mTrxLevel
) {
3542 $this->query( 'COMMIT', $fname );
3543 $this->mTrxLevel
= 0;
3548 * Rollback a transaction previously started using begin().
3549 * If no transaction is in progress, a warning is issued.
3551 * No-op on non-transactional databases.
3553 * @param string $fname
3554 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3555 * calling rollback when no transaction is in progress. This will silently
3556 * break any ongoing explicit transaction. Only set the flush flag if you
3557 * are sure that it is safe to ignore these warnings in your context.
3558 * @throws DBUnexpectedError
3559 * @since 1.23 Added $flush parameter
3561 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3562 if ( $flush !== 'flush' ) {
3563 if ( !$this->mTrxLevel
) {
3564 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3565 return; // nothing to do
3566 } elseif ( $this->mTrxAutomatic
) {
3567 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3570 if ( !$this->mTrxLevel
) {
3571 return; // nothing to do
3572 } elseif ( !$this->mTrxAutomatic
) {
3573 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3577 # Avoid fatals if close() was called
3578 $this->assertOpen();
3580 $this->doRollback( $fname );
3581 $this->mTrxIdleCallbacks
= array(); // cancel
3582 $this->mTrxPreCommitCallbacks
= array(); // cancel
3583 $this->mTrxAtomicLevels
= array();
3584 if ( $this->mTrxDoneWrites
) {
3585 $this->getTransactionProfiler()->transactionWritingOut(
3586 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3591 * Issues the ROLLBACK command to the database server.
3593 * @see DatabaseBase::rollback()
3594 * @param string $fname
3596 protected function doRollback( $fname ) {
3597 if ( $this->mTrxLevel
) {
3598 $this->query( 'ROLLBACK', $fname, true );
3599 $this->mTrxLevel
= 0;
3604 * Creates a new table with structure copied from existing table
3605 * Note that unlike most database abstraction functions, this function does not
3606 * automatically append database prefix, because it works at a lower
3607 * abstraction level.
3608 * The table names passed to this function shall not be quoted (this
3609 * function calls addIdentifierQuotes when needed).
3611 * @param string $oldName Name of table whose structure should be copied
3612 * @param string $newName Name of table to be created
3613 * @param bool $temporary Whether the new table should be temporary
3614 * @param string $fname Calling function name
3615 * @throws MWException
3616 * @return bool True if operation was successful
3618 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3621 throw new MWException(
3622 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3626 * List all tables on the database
3628 * @param string $prefix Only show tables with this prefix, e.g. mw_
3629 * @param string $fname Calling function name
3630 * @throws MWException
3633 function listTables( $prefix = null, $fname = __METHOD__
) {
3634 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3638 * Reset the views process cache set by listViews()
3641 final public function clearViewsCache() {
3642 $this->allViews
= null;
3646 * Lists all the VIEWs in the database
3648 * For caching purposes the list of all views should be stored in
3649 * $this->allViews. The process cache can be cleared with clearViewsCache()
3651 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3652 * @param string $fname Name of calling function
3653 * @throws MWException
3657 public function listViews( $prefix = null, $fname = __METHOD__
) {
3658 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3662 * Differentiates between a TABLE and a VIEW
3664 * @param string $name Name of the database-structure to test.
3665 * @throws MWException
3669 public function isView( $name ) {
3670 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3674 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3675 * to the format used for inserting into timestamp fields in this DBMS.
3677 * The result is unquoted, and needs to be passed through addQuotes()
3678 * before it can be included in raw SQL.
3680 * @param string|int $ts
3684 public function timestamp( $ts = 0 ) {
3685 return wfTimestamp( TS_MW
, $ts );
3689 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3690 * to the format used for inserting into timestamp fields in this DBMS. If
3691 * NULL is input, it is passed through, allowing NULL values to be inserted
3692 * into timestamp fields.
3694 * The result is unquoted, and needs to be passed through addQuotes()
3695 * before it can be included in raw SQL.
3697 * @param string|int $ts
3701 public function timestampOrNull( $ts = null ) {
3702 if ( is_null( $ts ) ) {
3705 return $this->timestamp( $ts );
3710 * Take the result from a query, and wrap it in a ResultWrapper if
3711 * necessary. Boolean values are passed through as is, to indicate success
3712 * of write queries or failure.
3714 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3715 * resource, and it was necessary to call this function to convert it to
3716 * a wrapper. Nowadays, raw database objects are never exposed to external
3717 * callers, so this is unnecessary in external code.
3719 * @param bool|ResultWrapper|resource|object $result
3720 * @return bool|ResultWrapper
3722 protected function resultObject( $result ) {
3725 } elseif ( $result instanceof ResultWrapper
) {
3727 } elseif ( $result === true ) {
3728 // Successful write query
3731 return new ResultWrapper( $this, $result );
3736 * Ping the server and try to reconnect if it there is no connection
3738 * @return bool Success or failure
3740 public function ping() {
3741 # Stub. Not essential to override.
3746 * Get slave lag. Currently supported only by MySQL.
3748 * Note that this function will generate a fatal error on many
3749 * installations. Most callers should use LoadBalancer::safeGetLag()
3752 * @return int Database replication lag in seconds
3754 public function getLag() {
3759 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3763 function maxListLen() {
3768 * Some DBMSs have a special format for inserting into blob fields, they
3769 * don't allow simple quoted strings to be inserted. To insert into such
3770 * a field, pass the data through this function before passing it to
3771 * DatabaseBase::insert().
3776 public function encodeBlob( $b ) {
3781 * Some DBMSs return a special placeholder object representing blob fields
3782 * in result objects. Pass the object through this function to return the
3785 * @param string|Blob $b
3788 public function decodeBlob( $b ) {
3789 if ( $b instanceof Blob
) {
3796 * Override database's default behavior. $options include:
3797 * 'connTimeout' : Set the connection timeout value in seconds.
3798 * May be useful for very long batch queries such as
3799 * full-wiki dumps, where a single query reads out over
3802 * @param array $options
3805 public function setSessionOptions( array $options ) {
3809 * Read and execute SQL commands from a file.
3811 * Returns true on success, error string or exception on failure (depending
3812 * on object's error ignore settings).
3814 * @param string $filename File name to open
3815 * @param bool|callable $lineCallback Optional function called before reading each line
3816 * @param bool|callable $resultCallback Optional function called for each MySQL result
3817 * @param bool|string $fname Calling function name or false if name should be
3818 * generated dynamically using $filename
3819 * @param bool|callable $inputCallback Optional function called for each
3820 * complete line sent
3821 * @throws Exception|MWException
3822 * @return bool|string
3824 public function sourceFile(
3825 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3827 MediaWiki\
suppressWarnings();
3828 $fp = fopen( $filename, 'r' );
3829 MediaWiki\restoreWarnings
();
3831 if ( false === $fp ) {
3832 throw new MWException( "Could not open \"{$filename}\".\n" );
3836 $fname = __METHOD__
. "( $filename )";
3840 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3841 } catch ( Exception
$e ) {
3852 * Get the full path of a patch file. Originally based on archive()
3853 * from updaters.inc. Keep in mind this always returns a patch, as
3854 * it fails back to MySQL if no DB-specific patch can be found
3856 * @param string $patch The name of the patch, like patch-something.sql
3857 * @return string Full path to patch file
3859 public function patchPath( $patch ) {
3862 $dbType = $this->getType();
3863 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3864 return "$IP/maintenance/$dbType/archives/$patch";
3866 return "$IP/maintenance/archives/$patch";
3871 * Set variables to be used in sourceFile/sourceStream, in preference to the
3872 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3873 * all. If it's set to false, $GLOBALS will be used.
3875 * @param bool|array $vars Mapping variable name to value.
3877 public function setSchemaVars( $vars ) {
3878 $this->mSchemaVars
= $vars;
3882 * Read and execute commands from an open file handle.
3884 * Returns true on success, error string or exception on failure (depending
3885 * on object's error ignore settings).
3887 * @param resource $fp File handle
3888 * @param bool|callable $lineCallback Optional function called before reading each query
3889 * @param bool|callable $resultCallback Optional function called for each MySQL result
3890 * @param string $fname Calling function name
3891 * @param bool|callable $inputCallback Optional function called for each complete query sent
3892 * @return bool|string
3894 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3895 $fname = __METHOD__
, $inputCallback = false
3899 while ( !feof( $fp ) ) {
3900 if ( $lineCallback ) {
3901 call_user_func( $lineCallback );
3904 $line = trim( fgets( $fp ) );
3906 if ( $line == '' ) {
3910 if ( '-' == $line[0] && '-' == $line[1] ) {
3918 $done = $this->streamStatementEnd( $cmd, $line );
3922 if ( $done ||
feof( $fp ) ) {
3923 $cmd = $this->replaceVars( $cmd );
3925 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3926 $res = $this->query( $cmd, $fname );
3928 if ( $resultCallback ) {
3929 call_user_func( $resultCallback, $res, $this );
3932 if ( false === $res ) {
3933 $err = $this->lastError();
3935 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3946 * Called by sourceStream() to check if we've reached a statement end
3948 * @param string $sql SQL assembled so far
3949 * @param string $newLine New line about to be added to $sql
3950 * @return bool Whether $newLine contains end of the statement
3952 public function streamStatementEnd( &$sql, &$newLine ) {
3953 if ( $this->delimiter
) {
3955 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3956 if ( $newLine != $prev ) {
3965 * Database independent variable replacement. Replaces a set of variables
3966 * in an SQL statement with their contents as given by $this->getSchemaVars().
3968 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3970 * - '{$var}' should be used for text and is passed through the database's
3972 * - `{$var}` should be used for identifiers (e.g. table and database names).
3973 * It is passed through the database's addIdentifierQuotes method which
3974 * can be overridden if the database uses something other than backticks.
3975 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
3976 * database's tableName method.
3977 * - / *i* / passes the name that follows through the database's indexName method.
3978 * - In all other cases, / *$var* / is left unencoded. Except for table options,
3979 * its use should be avoided. In 1.24 and older, string encoding was applied.
3981 * @param string $ins SQL statement to replace variables in
3982 * @return string The new SQL statement with variables replaced
3984 protected function replaceVars( $ins ) {
3986 $vars = $this->getSchemaVars();
3987 return preg_replace_callback(
3989 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
3990 \'\{\$ (\w+) }\' | # 3. addQuotes
3991 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
3992 /\*\$ (\w+) \*/ # 5. leave unencoded
3994 function ( $m ) use ( $that, $vars ) {
3995 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
3996 // check for both nonexistent keys *and* the empty string.
3997 if ( isset( $m[1] ) && $m[1] !== '' ) {
3998 if ( $m[1] === 'i' ) {
3999 return $that->indexName( $m[2] );
4001 return $that->tableName( $m[2] );
4003 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4004 return $that->addQuotes( $vars[$m[3]] );
4005 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4006 return $that->addIdentifierQuotes( $vars[$m[4]] );
4007 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4008 return $vars[$m[5]];
4018 * Get schema variables. If none have been set via setSchemaVars(), then
4019 * use some defaults from the current object.
4023 protected function getSchemaVars() {
4024 if ( $this->mSchemaVars
) {
4025 return $this->mSchemaVars
;
4027 return $this->getDefaultSchemaVars();
4032 * Get schema variables to use if none have been set via setSchemaVars().
4034 * Override this in derived classes to provide variables for tables.sql
4035 * and SQL patch files.
4039 protected function getDefaultSchemaVars() {
4044 * Check to see if a named lock is available (non-blocking)
4046 * @param string $lockName Name of lock to poll
4047 * @param string $method Name of method calling us
4051 public function lockIsFree( $lockName, $method ) {
4056 * Acquire a named lock
4058 * Named locks are not related to transactions
4060 * @param string $lockName Name of lock to aquire
4061 * @param string $method Name of method calling us
4062 * @param int $timeout
4065 public function lock( $lockName, $method, $timeout = 5 ) {
4072 * Named locks are not related to transactions
4074 * @param string $lockName Name of lock to release
4075 * @param string $method Name of method calling us
4077 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4078 * by this thread (in which case the lock is not released), and NULL if the named
4079 * lock did not exist
4081 public function unlock( $lockName, $method ) {
4086 * Check to see if a named lock used by lock() use blocking queues
4091 public function namedLocksEnqueue() {
4096 * Lock specific tables
4098 * @param array $read Array of tables to lock for read access
4099 * @param array $write Array of tables to lock for write access
4100 * @param string $method Name of caller
4101 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4104 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4109 * Unlock specific tables
4111 * @param string $method The caller
4114 public function unlockTables( $method ) {
4120 * @param string $tableName
4121 * @param string $fName
4122 * @return bool|ResultWrapper
4125 public function dropTable( $tableName, $fName = __METHOD__
) {
4126 if ( !$this->tableExists( $tableName, $fName ) ) {
4129 $sql = "DROP TABLE " . $this->tableName( $tableName );
4130 if ( $this->cascadingDeletes() ) {
4134 return $this->query( $sql, $fName );
4138 * Get search engine class. All subclasses of this need to implement this
4139 * if they wish to use searching.
4143 public function getSearchEngine() {
4144 return 'SearchEngineDummy';
4148 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4149 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4150 * because "i" sorts after all numbers.
4154 public function getInfinity() {
4159 * Encode an expiry time into the DBMS dependent format
4161 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4164 public function encodeExpiry( $expiry ) {
4165 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4166 ?
$this->getInfinity()
4167 : $this->timestamp( $expiry );
4171 * Decode an expiry time into a DBMS independent format
4173 * @param string $expiry DB timestamp field value for expiry
4174 * @param int $format TS_* constant, defaults to TS_MW
4177 public function decodeExpiry( $expiry, $format = TS_MW
) {
4178 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4180 : wfTimestamp( $format, $expiry );
4184 * Allow or deny "big selects" for this session only. This is done by setting
4185 * the sql_big_selects session variable.
4187 * This is a MySQL-specific feature.
4189 * @param bool|string $value True for allow, false for deny, or "default" to
4190 * restore the initial value
4192 public function setBigSelects( $value = true ) {
4200 public function __toString() {
4201 return (string)$this->mConn
;
4205 * Run a few simple sanity checks
4207 public function __destruct() {
4208 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4209 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4211 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4213 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4214 $callers[] = $callbackInfo[1];
4216 $callers = implode( ', ', $callers );
4217 trigger_error( "DB transaction callbacks still pending (from $callers)." );