4 * @defgroup Database Database
6 * This file deals with database interface functions
7 * and query specifics/optimisations.
9 * This program is free software; you can redistribute it and/or modify
10 * it under the terms of the GNU General Public License as published by
11 * the Free Software Foundation; either version 2 of the License, or
12 * (at your option) any later version.
14 * This program is distributed in the hope that it will be useful,
15 * but WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 * GNU General Public License for more details.
19 * You should have received a copy of the GNU General Public License along
20 * with this program; if not, write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
22 * http://www.gnu.org/copyleft/gpl.html
29 * Database abstraction object
32 abstract class DatabaseBase
implements IDatabase
{
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES
= 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN
= 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX
= 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var BagOStuff APC cache */
51 /** @var resource Database connection */
52 protected $mConn = null;
53 protected $mOpened = false;
55 /** @var callable[] */
56 protected $mTrxIdleCallbacks = array();
57 /** @var callable[] */
58 protected $mTrxPreCommitCallbacks = array();
60 protected $mTablePrefix;
64 protected $mLBInfo = array();
65 protected $mDefaultBigSelects = null;
66 protected $mSchemaVars = false;
68 protected $mSessionVars = array();
70 protected $preparedArgs;
72 protected $htmlErrors;
74 protected $delimiter = ';';
77 * Either 1 if a transaction is active or 0 otherwise.
78 * The other Trx fields may not be meaningfull if this is 0.
82 protected $mTrxLevel = 0;
85 * Either a short hexidecimal string if a transaction is active or ""
88 * @see DatabaseBase::mTrxLevel
90 protected $mTrxShortId = '';
93 * The UNIX time that the transaction started. Callers can assume that if
94 * snapshot isolation is used, then the data is *at least* up to date to that
95 * point (possibly more up-to-date since the first SELECT defines the snapshot).
98 * @see DatabaseBase::mTrxLevel
100 private $mTrxTimestamp = null;
102 /** @var float Lag estimate at the time of BEGIN */
103 private $mTrxSlaveLag = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
135 private $mTrxAtomicLevels = array();
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
145 * Track the seconds spent in write queries for the current transaction
149 private $mTrxWriteDuration = 0.0;
151 /** @var IDatabase|null Lazy handle to the master DB this server replicates from */
152 private $lazyMasterHandle;
156 * @var resource File handle for upgrade
158 protected $fileHandle = null;
162 * @var string[] Process cache of VIEWs names in the database
164 protected $allViews = null;
166 /** @var TransactionProfiler */
167 protected $trxProfiler;
170 * A string describing the current software version, and possibly
171 * other details in a user-friendly way. Will be listed on Special:Version, etc.
172 * Use getServerVersion() to get machine-friendly information.
174 * @return string Version information from the database server
176 public function getServerInfo() {
177 return $this->getServerVersion();
181 * @return string Command delimiter used by this database engine
183 public function getDelimiter() {
184 return $this->delimiter
;
188 * Boolean, controls output of large amounts of debug information.
189 * @param bool|null $debug
190 * - true to enable debugging
191 * - false to disable debugging
192 * - omitted or null to do nothing
194 * @return bool|null Previous value of the flag
196 public function debug( $debug = null ) {
197 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
201 * Turns buffering of SQL result sets on (true) or off (false). Default is
204 * Unbuffered queries are very troublesome in MySQL:
206 * - If another query is executed while the first query is being read
207 * out, the first query is killed. This means you can't call normal
208 * MediaWiki functions while you are reading an unbuffered query result
209 * from a normal wfGetDB() connection.
211 * - Unbuffered queries cause the MySQL server to use large amounts of
212 * memory and to hold broad locks which block other queries.
214 * If you want to limit client-side memory, it's almost always better to
215 * split up queries into batches using a LIMIT clause than to switch off
218 * @param null|bool $buffer
219 * @return null|bool The previous value of the flag
221 public function bufferResults( $buffer = null ) {
222 if ( is_null( $buffer ) ) {
223 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
225 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
230 * Turns on (false) or off (true) the automatic generation and sending
231 * of a "we're sorry, but there has been a database error" page on
232 * database errors. Default is on (false). When turned off, the
233 * code should use lastErrno() and lastError() to handle the
234 * situation as appropriate.
236 * Do not use this function outside of the Database classes.
238 * @param null|bool $ignoreErrors
239 * @return bool The previous value of the flag.
241 protected function ignoreErrors( $ignoreErrors = null ) {
242 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
246 * Gets the current transaction level.
248 * Historically, transactions were allowed to be "nested". This is no
249 * longer supported, so this function really only returns a boolean.
251 * @return int The previous value
253 public function trxLevel() {
254 return $this->mTrxLevel
;
258 * Get the UNIX timestamp of the time that the transaction was established
260 * This can be used to reason about the staleness of SELECT data
261 * in REPEATABLE-READ transaction isolation level.
263 * @return float|null Returns null if there is not active transaction
266 public function trxTimestamp() {
267 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
271 * Get/set the table prefix.
272 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
273 * @return string The previous table prefix.
275 public function tablePrefix( $prefix = null ) {
276 return wfSetVar( $this->mTablePrefix
, $prefix );
280 * Get/set the db schema.
281 * @param string $schema The database schema to set, or omitted to leave it unchanged.
282 * @return string The previous db schema.
284 public function dbSchema( $schema = null ) {
285 return wfSetVar( $this->mSchema
, $schema );
289 * Set the filehandle to copy write statements to.
291 * @param resource $fh File handle
293 public function setFileHandle( $fh ) {
294 $this->fileHandle
= $fh;
298 * Get properties passed down from the server info array of the load
301 * @param string $name The entry of the info array to get, or null to get the
304 * @return array|mixed|null
306 public function getLBInfo( $name = null ) {
307 if ( is_null( $name ) ) {
308 return $this->mLBInfo
;
310 if ( array_key_exists( $name, $this->mLBInfo
) ) {
311 return $this->mLBInfo
[$name];
319 * Set the LB info array, or a member of it. If called with one parameter,
320 * the LB info array is set to that parameter. If it is called with two
321 * parameters, the member with the given name is set to the given value.
323 * @param string $name
324 * @param array $value
326 public function setLBInfo( $name, $value = null ) {
327 if ( is_null( $value ) ) {
328 $this->mLBInfo
= $name;
330 $this->mLBInfo
[$name] = $value;
335 * Set a lazy-connecting DB handle to the master DB (for replication status purposes)
337 * @param IDatabase $conn
340 public function setLazyMasterHandle( IDatabase
$conn ) {
341 $this->lazyMasterHandle
= $conn;
345 * @return IDatabase|null
346 * @see setLazyMasterHandle()
349 public function getLazyMasterHandle() {
350 return $this->lazyMasterHandle
;
354 * @return TransactionProfiler
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
359 : Profiler
::instance()->getTransactionProfiler();
363 * Returns true if this database supports (and uses) cascading deletes
367 public function cascadingDeletes() {
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
376 public function cleanupTriggers() {
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
386 public function strictIPs() {
391 * Returns true if this database uses timestamps rather than integers
395 public function realTimestamps() {
400 * Returns true if this database does an implicit sort when doing GROUP BY
404 public function implicitGroupby() {
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
414 public function implicitOrderby() {
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
424 public function searchableIPs() {
429 * Returns true if this database can use functional indexes
433 public function functionalIndexes() {
438 * Return the last query that went through DatabaseBase::query()
441 public function lastQuery() {
442 return $this->mLastQuery
;
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites
;
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
459 * @return int|float UNIX timestamp or false
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?
: false;
467 * @return bool Whether there is a transaction open with possible write queries
470 public function writesPending() {
471 return $this->mTrxLevel
&& $this->mTrxDoneWrites
;
475 * Returns true if there is a transaction open with possible write
476 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
480 public function writesOrCallbacksPending() {
481 return $this->mTrxLevel
&& (
482 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
487 * Get the time spend running write queries for this
489 * High times could be due to scanning, updates, locking, and such
491 * @return float|bool Returns false if not transaction is active
494 public function pendingWriteQueryDuration() {
495 return $this->mTrxLevel ?
$this->mTrxWriteDuration
: false;
499 * Is a connection to the database open?
502 public function isOpen() {
503 return $this->mOpened
;
507 * Set a flag for this connection
509 * @param int $flag DBO_* constants from Defines.php:
510 * - DBO_DEBUG: output some debug info (same as debug())
511 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
512 * - DBO_TRX: automatically start transactions
513 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
514 * and removes it in command line mode
515 * - DBO_PERSISTENT: use persistant database connection
517 public function setFlag( $flag ) {
518 $this->mFlags |
= $flag;
522 * Clear a flag for this connection
524 * @param int $flag DBO_* constants from Defines.php:
525 * - DBO_DEBUG: output some debug info (same as debug())
526 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
527 * - DBO_TRX: automatically start transactions
528 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
529 * and removes it in command line mode
530 * - DBO_PERSISTENT: use persistant database connection
532 public function clearFlag( $flag ) {
533 $this->mFlags
&= ~
$flag;
537 * Returns a boolean whether the flag $flag is set for this connection
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags
& $flag );
551 * General read-only accessor
553 * @param string $name
556 public function getProperty( $name ) {
563 public function getWikiID() {
564 if ( $this->mTablePrefix
) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
567 return $this->mDBname
;
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
575 * @param string $filename
578 private function getSqlFilePath( $filename ) {
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
584 return "$IP/maintenance/$filename";
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
609 * Get information about an index into an object
610 * @param string $table Table name
611 * @param string $index Index name
612 * @param string $fname Calling function name
613 * @return mixed Database-specific index description class or false if the index does not exist
615 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
618 * Wrapper for addslashes()
620 * @param string $s String to be slashed.
621 * @return string Slashed string.
623 abstract function strencode( $s );
628 * FIXME: It is possible to construct a Database object with no associated
629 * connection object, by specifying no parameters to __construct(). This
630 * feature is deprecated and should be removed.
632 * DatabaseBase subclasses should not be constructed directly in external
633 * code. DatabaseBase::factory() should be used instead.
635 * @param array $params Parameters passed from DatabaseBase::factory()
637 function __construct( array $params ) {
638 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode;
640 $this->srvCache
= ObjectCache
::getLocalServerInstance( 'hash' );
642 $server = $params['host'];
643 $user = $params['user'];
644 $password = $params['password'];
645 $dbName = $params['dbname'];
646 $flags = $params['flags'];
647 $tablePrefix = $params['tablePrefix'];
648 $schema = $params['schema'];
649 $foreign = $params['foreign'];
651 $this->mFlags
= $flags;
652 if ( $this->mFlags
& DBO_DEFAULT
) {
653 if ( $wgCommandLineMode ) {
654 $this->mFlags
&= ~DBO_TRX
;
656 $this->mFlags |
= DBO_TRX
;
660 $this->mSessionVars
= $params['variables'];
662 /** Get the default table prefix*/
663 if ( $tablePrefix === 'get from global' ) {
664 $this->mTablePrefix
= $wgDBprefix;
666 $this->mTablePrefix
= $tablePrefix;
669 /** Get the database schema*/
670 if ( $schema === 'get from global' ) {
671 $this->mSchema
= $wgDBmwschema;
673 $this->mSchema
= $schema;
676 $this->mForeign
= $foreign;
678 if ( isset( $params['trxProfiler'] ) ) {
679 $this->trxProfiler
= $params['trxProfiler']; // override
683 $this->open( $server, $user, $password, $dbName );
688 * Called by serialize. Throw an exception when DB connection is serialized.
689 * This causes problems on some database engines because the connection is
690 * not restored on unserialize.
692 public function __sleep() {
693 throw new MWException( 'Database serialization may cause problems, since ' .
694 'the connection is not restored on wakeup.' );
698 * Given a DB type, construct the name of the appropriate child class of
699 * DatabaseBase. This is designed to replace all of the manual stuff like:
700 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
701 * as well as validate against the canonical list of DB types we have
703 * This factory function is mostly useful for when you need to connect to a
704 * database other than the MediaWiki default (such as for external auth,
705 * an extension, et cetera). Do not use this to connect to the MediaWiki
706 * database. Example uses in core:
707 * @see LoadBalancer::reallyOpenConnection()
708 * @see ForeignDBRepo::getMasterDB()
709 * @see WebInstallerDBConnect::execute()
713 * @param string $dbType A possible DB type
714 * @param array $p An array of options to pass to the constructor.
715 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
716 * @throws MWException If the database driver or extension cannot be found
717 * @return DatabaseBase|null DatabaseBase subclass or null
719 final public static function factory( $dbType, $p = array() ) {
720 $canonicalDBTypes = array(
721 'mysql' => array( 'mysqli', 'mysql' ),
722 'postgres' => array(),
729 $dbType = strtolower( $dbType );
730 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
731 $possibleDrivers = $canonicalDBTypes[$dbType];
732 if ( !empty( $p['driver'] ) ) {
733 if ( in_array( $p['driver'], $possibleDrivers ) ) {
734 $driver = $p['driver'];
736 throw new MWException( __METHOD__
.
737 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
740 foreach ( $possibleDrivers as $posDriver ) {
741 if ( extension_loaded( $posDriver ) ) {
742 $driver = $posDriver;
750 if ( $driver === false ) {
751 throw new MWException( __METHOD__
.
752 " no viable database extension found for type '$dbType'" );
755 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
756 // and everything else doesn't use a schema (e.g. null)
757 // Although postgres and oracle support schemas, we don't use them (yet)
758 // to maintain backwards compatibility
759 $defaultSchemas = array(
760 'mssql' => 'get from global',
763 $class = 'Database' . ucfirst( $driver );
764 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
765 // Resolve some defaults for b/c
766 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
767 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
768 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
769 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
770 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
771 $p['variables'] = isset( $p['variables'] ) ?
$p['variables'] : array();
772 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
773 if ( !isset( $p['schema'] ) ) {
774 $p['schema'] = isset( $defaultSchemas[$dbType] ) ?
$defaultSchemas[$dbType] : null;
776 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
778 return new $class( $p );
784 protected function installErrorHandler() {
785 $this->mPHPError
= false;
786 $this->htmlErrors
= ini_set( 'html_errors', '0' );
787 set_error_handler( array( $this, 'connectionErrorHandler' ) );
791 * @return bool|string
793 protected function restoreErrorHandler() {
794 restore_error_handler();
795 if ( $this->htmlErrors
!== false ) {
796 ini_set( 'html_errors', $this->htmlErrors
);
798 if ( $this->mPHPError
) {
799 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
800 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
810 * @param string $errstr
812 public function connectionErrorHandler( $errno, $errstr ) {
813 $this->mPHPError
= $errstr;
817 * Create a log context to pass to wfLogDBError or other logging functions.
819 * @param array $extras Additional data to add to context
822 protected function getLogContext( array $extras = array() ) {
825 'db_server' => $this->mServer
,
826 'db_name' => $this->mDBname
,
827 'db_user' => $this->mUser
,
834 * Closes a database connection.
835 * if it is open : commits any open transactions
837 * @throws MWException
838 * @return bool Operation success. true if already closed.
840 public function close() {
841 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
842 throw new MWException( "Transaction idle callbacks still pending." );
844 if ( $this->mConn
) {
845 if ( $this->trxLevel() ) {
846 if ( !$this->mTrxAutomatic
) {
847 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
848 " performing implicit commit before closing connection!" );
851 $this->commit( __METHOD__
, 'flush' );
854 $closed = $this->closeConnection();
855 $this->mConn
= false;
859 $this->mOpened
= false;
865 * Make sure isOpen() returns true as a sanity check
867 * @throws DBUnexpectedError
869 protected function assertOpen() {
870 if ( !$this->isOpen() ) {
871 throw new DBUnexpectedError( $this, "DB connection was already closed." );
876 * Closes underlying database connection
878 * @return bool Whether connection was closed successfully
880 abstract protected function closeConnection();
883 * @param string $error Fallback error message, used if none is given by DB
884 * @throws DBConnectionError
886 function reportConnectionError( $error = 'Unknown error' ) {
887 $myError = $this->lastError();
893 throw new DBConnectionError( $this, $error );
897 * The DBMS-dependent part of query()
899 * @param string $sql SQL query.
900 * @return ResultWrapper|bool Result object to feed to fetchObject,
901 * fetchRow, ...; or false on failure
903 abstract protected function doQuery( $sql );
906 * Determine whether a query writes to the DB.
907 * Should return true if unsure.
912 protected function isWriteQuery( $sql ) {
913 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
917 * Determine whether a SQL statement is sensitive to isolation level.
918 * A SQL statement is considered transactable if its result could vary
919 * depending on the transaction isolation level. Operational commands
920 * such as 'SET' and 'SHOW' are not considered to be transactable.
925 protected function isTransactableQuery( $sql ) {
926 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
927 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
931 * Run an SQL query and return the result. Normally throws a DBQueryError
932 * on failure. If errors are ignored, returns false instead.
934 * In new code, the query wrappers select(), insert(), update(), delete(),
935 * etc. should be used where possible, since they give much better DBMS
936 * independence and automatically quote or validate user input in a variety
937 * of contexts. This function is generally only useful for queries which are
938 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
941 * However, the query wrappers themselves should call this function.
943 * @param string $sql SQL query
944 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
945 * comment (you can use __METHOD__ or add some extra info)
946 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
947 * maybe best to catch the exception instead?
948 * @throws MWException
949 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
950 * for a successful read query, or false on failure if $tempIgnore set
952 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
955 $this->mLastQuery
= $sql;
957 $isWriteQuery = $this->isWriteQuery( $sql );
958 if ( $isWriteQuery ) {
959 $reason = $this->getReadOnlyReason();
960 if ( $reason !== false ) {
961 throw new DBReadOnlyError( $this, "Database is read-only: $reason" );
963 # Set a flag indicating that writes have been done
964 $this->mDoneWrites
= microtime( true );
967 # Add a comment for easy SHOW PROCESSLIST interpretation
968 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
969 $userName = $wgUser->getName();
970 if ( mb_strlen( $userName ) > 15 ) {
971 $userName = mb_substr( $userName, 0, 15 ) . '...';
973 $userName = str_replace( '/', '', $userName );
978 // Add trace comment to the begin of the sql string, right after the operator.
979 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
980 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
982 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
983 $this->begin( __METHOD__
. " ($fname)" );
984 $this->mTrxAutomatic
= true;
987 # Keep track of whether the transaction has write queries pending
988 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
989 $this->mTrxDoneWrites
= true;
990 $this->getTransactionProfiler()->transactionWritingIn(
991 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
994 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
995 # generalizeSQL will probably cut down the query to reasonable
996 # logging size most of the time. The substr is really just a sanity check.
998 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
999 $totalProf = 'DatabaseBase::query-master';
1001 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1002 $totalProf = 'DatabaseBase::query';
1004 # Include query transaction state
1005 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1007 $profiler = Profiler
::instance();
1008 if ( !$profiler instanceof ProfilerStub
) {
1009 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1010 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1013 if ( $this->debug() ) {
1014 wfDebugLog( 'queries', sprintf( "%s: %s", $this->mDBname
, $commentedSql ) );
1017 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1019 # Avoid fatals if close() was called
1020 $this->assertOpen();
1022 # Do the query and handle errors
1023 $startTime = microtime( true );
1024 $ret = $this->doQuery( $commentedSql );
1025 $queryRuntime = microtime( true ) - $startTime;
1026 # Log the query time and feed it into the DB trx profiler
1027 $this->getTransactionProfiler()->recordQueryCompletion(
1028 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1030 MWDebug
::queryTime( $queryId );
1032 # Try reconnecting if the connection was lost
1033 if ( false === $ret && $this->wasErrorReissuable() ) {
1034 # Transaction is gone, like it or not
1035 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1036 $this->mTrxLevel
= 0;
1037 $this->mTrxIdleCallbacks
= array(); // bug 65263
1038 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1039 wfDebug( "Connection lost, reconnecting...\n" );
1040 # Stash the last error values since ping() might clear them
1041 $lastError = $this->lastError();
1042 $lastErrno = $this->lastErrno();
1043 if ( $this->ping() ) {
1044 wfDebug( "Reconnected\n" );
1045 $server = $this->getServer();
1046 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1047 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1050 # Leave $ret as false and let an error be reported.
1051 # Callers may catch the exception and continue to use the DB.
1052 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1054 # Should be safe to silently retry (no trx and thus no callbacks)
1055 $startTime = microtime( true );
1056 $ret = $this->doQuery( $commentedSql );
1057 $queryRuntime = microtime( true ) - $startTime;
1058 # Log the query time and feed it into the DB trx profiler
1059 $this->getTransactionProfiler()->recordQueryCompletion(
1060 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1063 wfDebug( "Failed\n" );
1067 if ( false === $ret ) {
1068 $this->reportQueryError(
1069 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1072 $res = $this->resultObject( $ret );
1074 // Destroy profile sections in the opposite order to their creation
1075 ScopedCallback
::consume( $queryProfSection );
1076 ScopedCallback
::consume( $totalProfSection );
1078 if ( $isWriteQuery && $this->mTrxLevel
) {
1079 $this->mTrxWriteDuration +
= $queryRuntime;
1086 * Report a query error. Log the error, and if neither the object ignore
1087 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1089 * @param string $error
1091 * @param string $sql
1092 * @param string $fname
1093 * @param bool $tempIgnore
1094 * @throws DBQueryError
1096 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1097 if ( $this->ignoreErrors() ||
$tempIgnore ) {
1098 wfDebug( "SQL ERROR (ignored): $error\n" );
1100 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1102 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1103 $this->getLogContext( array(
1104 'method' => __METHOD__
,
1107 'sql1line' => $sql1line,
1111 wfDebug( "SQL ERROR: " . $error . "\n" );
1112 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1117 * Intended to be compatible with the PEAR::DB wrapper functions.
1118 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1120 * ? = scalar value, quoted as necessary
1121 * ! = raw SQL bit (a function for instance)
1122 * & = filename; reads the file and inserts as a blob
1123 * (we don't use this though...)
1125 * @param string $sql
1126 * @param string $func
1130 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1131 /* MySQL doesn't support prepared statements (yet), so just
1132 * pack up the query for reference. We'll manually replace
1135 return array( 'query' => $sql, 'func' => $func );
1139 * Free a prepared query, generated by prepare().
1140 * @param string $prepared
1142 protected function freePrepared( $prepared ) {
1143 /* No-op by default */
1147 * Execute a prepared query with the various arguments
1148 * @param string $prepared The prepared sql
1149 * @param mixed $args Either an array here, or put scalars as varargs
1151 * @return ResultWrapper
1153 public function execute( $prepared, $args = null ) {
1154 if ( !is_array( $args ) ) {
1156 $args = func_get_args();
1157 array_shift( $args );
1160 $sql = $this->fillPrepared( $prepared['query'], $args );
1162 return $this->query( $sql, $prepared['func'] );
1166 * For faking prepared SQL statements on DBs that don't support it directly.
1168 * @param string $preparedQuery A 'preparable' SQL statement
1169 * @param array $args Array of Arguments to fill it with
1170 * @return string Executable SQL
1172 public function fillPrepared( $preparedQuery, $args ) {
1174 $this->preparedArgs
=& $args;
1176 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1177 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1181 * preg_callback func for fillPrepared()
1182 * The arguments should be in $this->preparedArgs and must not be touched
1183 * while we're doing this.
1185 * @param array $matches
1186 * @throws DBUnexpectedError
1189 protected function fillPreparedArg( $matches ) {
1190 switch ( $matches[1] ) {
1199 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1201 switch ( $matches[1] ) {
1203 return $this->addQuotes( $arg );
1207 # return $this->addQuotes( file_get_contents( $arg ) );
1208 throw new DBUnexpectedError(
1210 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1213 throw new DBUnexpectedError(
1215 'Received invalid match. This should never happen!'
1221 * Free a result object returned by query() or select(). It's usually not
1222 * necessary to call this, just use unset() or let the variable holding
1223 * the result object go out of scope.
1225 * @param mixed $res A SQL result
1227 public function freeResult( $res ) {
1231 * A SELECT wrapper which returns a single field from a single result row.
1233 * Usually throws a DBQueryError on failure. If errors are explicitly
1234 * ignored, returns false on failure.
1236 * If no result rows are returned from the query, false is returned.
1238 * @param string|array $table Table name. See DatabaseBase::select() for details.
1239 * @param string $var The field name to select. This must be a valid SQL
1240 * fragment: do not use unvalidated user input.
1241 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1242 * @param string $fname The function name of the caller.
1243 * @param string|array $options The query options. See DatabaseBase::select() for details.
1245 * @return bool|mixed The value from the field, or false on failure.
1246 * @throws DBUnexpectedError
1248 public function selectField(
1249 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1251 if ( $var === '*' ) { // sanity
1252 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1255 if ( !is_array( $options ) ) {
1256 $options = array( $options );
1259 $options['LIMIT'] = 1;
1261 $res = $this->select( $table, $var, $cond, $fname, $options );
1262 if ( $res === false ||
!$this->numRows( $res ) ) {
1266 $row = $this->fetchRow( $res );
1268 if ( $row !== false ) {
1269 return reset( $row );
1276 * A SELECT wrapper which returns a list of single field values from result rows.
1278 * Usually throws a DBQueryError on failure. If errors are explicitly
1279 * ignored, returns false on failure.
1281 * If no result rows are returned from the query, false is returned.
1283 * @param string|array $table Table name. See DatabaseBase::select() for details.
1284 * @param string $var The field name to select. This must be a valid SQL
1285 * fragment: do not use unvalidated user input.
1286 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1287 * @param string $fname The function name of the caller.
1288 * @param string|array $options The query options. See DatabaseBase::select() for details.
1289 * @param string|array $join_conds The join conditions. See DatabaseBase::select() for details.
1291 * @return bool|array The values from the field, or false on failure
1292 * @throws DBUnexpectedError
1295 public function selectFieldValues(
1296 $table, $var, $cond = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1298 if ( $var === '*' ) { // sanity
1299 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1302 if ( !is_array( $options ) ) {
1303 $options = array( $options );
1306 $res = $this->select( $table, $var, $cond, $fname, $options, $join_conds );
1307 if ( $res === false ) {
1312 foreach ( $res as $row ) {
1313 $values[] = $row->$var;
1320 * Returns an optional USE INDEX clause to go after the table, and a
1321 * string to go at the end of the query.
1323 * @param array $options Associative array of options to be turned into
1324 * an SQL query, valid keys are listed in the function.
1326 * @see DatabaseBase::select()
1328 public function makeSelectOptions( $options ) {
1329 $preLimitTail = $postLimitTail = '';
1332 $noKeyOptions = array();
1334 foreach ( $options as $key => $option ) {
1335 if ( is_numeric( $key ) ) {
1336 $noKeyOptions[$option] = true;
1340 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1342 $preLimitTail .= $this->makeOrderBy( $options );
1344 // if (isset($options['LIMIT'])) {
1345 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1346 // isset($options['OFFSET']) ? $options['OFFSET']
1350 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1351 $postLimitTail .= ' FOR UPDATE';
1354 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1355 $postLimitTail .= ' LOCK IN SHARE MODE';
1358 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1359 $startOpts .= 'DISTINCT';
1362 # Various MySQL extensions
1363 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1364 $startOpts .= ' /*! STRAIGHT_JOIN */';
1367 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1368 $startOpts .= ' HIGH_PRIORITY';
1371 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1372 $startOpts .= ' SQL_BIG_RESULT';
1375 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1376 $startOpts .= ' SQL_BUFFER_RESULT';
1379 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1380 $startOpts .= ' SQL_SMALL_RESULT';
1383 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1384 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1387 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1388 $startOpts .= ' SQL_CACHE';
1391 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1392 $startOpts .= ' SQL_NO_CACHE';
1395 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1396 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1401 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1405 * Returns an optional GROUP BY with an optional HAVING
1407 * @param array $options Associative array of options
1409 * @see DatabaseBase::select()
1412 public function makeGroupByWithHaving( $options ) {
1414 if ( isset( $options['GROUP BY'] ) ) {
1415 $gb = is_array( $options['GROUP BY'] )
1416 ?
implode( ',', $options['GROUP BY'] )
1417 : $options['GROUP BY'];
1418 $sql .= ' GROUP BY ' . $gb;
1420 if ( isset( $options['HAVING'] ) ) {
1421 $having = is_array( $options['HAVING'] )
1422 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1423 : $options['HAVING'];
1424 $sql .= ' HAVING ' . $having;
1431 * Returns an optional ORDER BY
1433 * @param array $options Associative array of options
1435 * @see DatabaseBase::select()
1438 public function makeOrderBy( $options ) {
1439 if ( isset( $options['ORDER BY'] ) ) {
1440 $ob = is_array( $options['ORDER BY'] )
1441 ?
implode( ',', $options['ORDER BY'] )
1442 : $options['ORDER BY'];
1444 return ' ORDER BY ' . $ob;
1451 * Execute a SELECT query constructed using the various parameters provided.
1452 * See below for full details of the parameters.
1454 * @param string|array $table Table name
1455 * @param string|array $vars Field names
1456 * @param string|array $conds Conditions
1457 * @param string $fname Caller function name
1458 * @param array $options Query options
1459 * @param array $join_conds Join conditions
1462 * @param string|array $table
1464 * May be either an array of table names, or a single string holding a table
1465 * name. If an array is given, table aliases can be specified, for example:
1467 * array( 'a' => 'user' )
1469 * This includes the user table in the query, with the alias "a" available
1470 * for use in field names (e.g. a.user_name).
1472 * All of the table names given here are automatically run through
1473 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1474 * added, and various other table name mappings to be performed.
1477 * @param string|array $vars
1479 * May be either a field name or an array of field names. The field names
1480 * can be complete fragments of SQL, for direct inclusion into the SELECT
1481 * query. If an array is given, field aliases can be specified, for example:
1483 * array( 'maxrev' => 'MAX(rev_id)' )
1485 * This includes an expression with the alias "maxrev" in the query.
1487 * If an expression is given, care must be taken to ensure that it is
1491 * @param string|array $conds
1493 * May be either a string containing a single condition, or an array of
1494 * conditions. If an array is given, the conditions constructed from each
1495 * element are combined with AND.
1497 * Array elements may take one of two forms:
1499 * - Elements with a numeric key are interpreted as raw SQL fragments.
1500 * - Elements with a string key are interpreted as equality conditions,
1501 * where the key is the field name.
1502 * - If the value of such an array element is a scalar (such as a
1503 * string), it will be treated as data and thus quoted appropriately.
1504 * If it is null, an IS NULL clause will be added.
1505 * - If the value is an array, an IN (...) clause will be constructed
1506 * from its non-null elements, and an IS NULL clause will be added
1507 * if null is present, such that the field may match any of the
1508 * elements in the array. The non-null elements will be quoted.
1510 * Note that expressions are often DBMS-dependent in their syntax.
1511 * DBMS-independent wrappers are provided for constructing several types of
1512 * expression commonly used in condition queries. See:
1513 * - DatabaseBase::buildLike()
1514 * - DatabaseBase::conditional()
1517 * @param string|array $options
1519 * Optional: Array of query options. Boolean options are specified by
1520 * including them in the array as a string value with a numeric key, for
1523 * array( 'FOR UPDATE' )
1525 * The supported options are:
1527 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1528 * with LIMIT can theoretically be used for paging through a result set,
1529 * but this is discouraged in MediaWiki for performance reasons.
1531 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1532 * and then the first rows are taken until the limit is reached. LIMIT
1533 * is applied to a result set after OFFSET.
1535 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1536 * changed until the next COMMIT.
1538 * - DISTINCT: Boolean: return only unique result rows.
1540 * - GROUP BY: May be either an SQL fragment string naming a field or
1541 * expression to group by, or an array of such SQL fragments.
1543 * - HAVING: May be either an string containing a HAVING clause or an array of
1544 * conditions building the HAVING clause. If an array is given, the conditions
1545 * constructed from each element are combined with AND.
1547 * - ORDER BY: May be either an SQL fragment giving a field name or
1548 * expression to order by, or an array of such SQL fragments.
1550 * - USE INDEX: This may be either a string giving the index name to use
1551 * for the query, or an array. If it is an associative array, each key
1552 * gives the table name (or alias), each value gives the index name to
1553 * use for that table. All strings are SQL fragments and so should be
1554 * validated by the caller.
1556 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1557 * instead of SELECT.
1559 * And also the following boolean MySQL extensions, see the MySQL manual
1560 * for documentation:
1562 * - LOCK IN SHARE MODE
1566 * - SQL_BUFFER_RESULT
1567 * - SQL_SMALL_RESULT
1568 * - SQL_CALC_FOUND_ROWS
1573 * @param string|array $join_conds
1575 * Optional associative array of table-specific join conditions. In the
1576 * most common case, this is unnecessary, since the join condition can be
1577 * in $conds. However, it is useful for doing a LEFT JOIN.
1579 * The key of the array contains the table name or alias. The value is an
1580 * array with two elements, numbered 0 and 1. The first gives the type of
1581 * join, the second is an SQL fragment giving the join condition for that
1582 * table. For example:
1584 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1586 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1587 * with no rows in it will be returned. If there was a query error, a
1588 * DBQueryError exception will be thrown, except if the "ignore errors"
1589 * option was set, in which case false will be returned.
1591 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1592 $options = array(), $join_conds = array() ) {
1593 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1595 return $this->query( $sql, $fname );
1599 * The equivalent of DatabaseBase::select() except that the constructed SQL
1600 * is returned, instead of being immediately executed. This can be useful for
1601 * doing UNION queries, where the SQL text of each query is needed. In general,
1602 * however, callers outside of Database classes should just use select().
1604 * @param string|array $table Table name
1605 * @param string|array $vars Field names
1606 * @param string|array $conds Conditions
1607 * @param string $fname Caller function name
1608 * @param string|array $options Query options
1609 * @param string|array $join_conds Join conditions
1611 * @return string SQL query string.
1612 * @see DatabaseBase::select()
1614 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1615 $options = array(), $join_conds = array()
1617 if ( is_array( $vars ) ) {
1618 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1621 $options = (array)$options;
1622 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1623 ?
$options['USE INDEX']
1626 if ( is_array( $table ) ) {
1628 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1629 } elseif ( $table != '' ) {
1630 if ( $table[0] == ' ' ) {
1631 $from = ' FROM ' . $table;
1634 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1640 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1641 $this->makeSelectOptions( $options );
1643 if ( !empty( $conds ) ) {
1644 if ( is_array( $conds ) ) {
1645 $conds = $this->makeList( $conds, LIST_AND
);
1647 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1649 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1652 if ( isset( $options['LIMIT'] ) ) {
1653 $sql = $this->limitResult( $sql, $options['LIMIT'],
1654 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1656 $sql = "$sql $postLimitTail";
1658 if ( isset( $options['EXPLAIN'] ) ) {
1659 $sql = 'EXPLAIN ' . $sql;
1666 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1667 * that a single row object is returned. If the query returns no rows,
1668 * false is returned.
1670 * @param string|array $table Table name
1671 * @param string|array $vars Field names
1672 * @param array $conds Conditions
1673 * @param string $fname Caller function name
1674 * @param string|array $options Query options
1675 * @param array|string $join_conds Join conditions
1677 * @return stdClass|bool
1679 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1680 $options = array(), $join_conds = array()
1682 $options = (array)$options;
1683 $options['LIMIT'] = 1;
1684 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1686 if ( $res === false ) {
1690 if ( !$this->numRows( $res ) ) {
1694 $obj = $this->fetchObject( $res );
1700 * Estimate the number of rows in dataset
1702 * MySQL allows you to estimate the number of rows that would be returned
1703 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1704 * index cardinality statistics, and is notoriously inaccurate, especially
1705 * when large numbers of rows have recently been added or deleted.
1707 * For DBMSs that don't support fast result size estimation, this function
1708 * will actually perform the SELECT COUNT(*).
1710 * Takes the same arguments as DatabaseBase::select().
1712 * @param string $table Table name
1713 * @param string $vars Unused
1714 * @param array|string $conds Filters on the table
1715 * @param string $fname Function name for profiling
1716 * @param array $options Options for select
1717 * @return int Row count
1719 public function estimateRowCount(
1720 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1723 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1726 $row = $this->fetchRow( $res );
1727 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1734 * Get the number of rows in dataset
1736 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1738 * Takes the same arguments as DatabaseBase::select().
1740 * @since 1.27 Added $join_conds parameter
1742 * @param array|string $tables Table names
1743 * @param string $vars Unused
1744 * @param array|string $conds Filters on the table
1745 * @param string $fname Function name for profiling
1746 * @param array $options Options for select
1747 * @param array $join_conds Join conditions (since 1.27)
1748 * @return int Row count
1750 public function selectRowCount(
1751 $tables, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array(), $join_conds = array()
1754 $sql = $this->selectSQLText( $tables, '1', $conds, $fname, $options, $join_conds );
1755 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1758 $row = $this->fetchRow( $res );
1759 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1766 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1767 * It's only slightly flawed. Don't use for anything important.
1769 * @param string $sql A SQL Query
1773 protected static function generalizeSQL( $sql ) {
1774 # This does the same as the regexp below would do, but in such a way
1775 # as to avoid crashing php on some large strings.
1776 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1778 $sql = str_replace( "\\\\", '', $sql );
1779 $sql = str_replace( "\\'", '', $sql );
1780 $sql = str_replace( "\\\"", '', $sql );
1781 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1782 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1784 # All newlines, tabs, etc replaced by single space
1785 $sql = preg_replace( '/\s+/', ' ', $sql );
1788 # except the ones surrounded by characters, e.g. l10n
1789 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1790 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1796 * Determines whether a field exists in a table
1798 * @param string $table Table name
1799 * @param string $field Filed to check on that table
1800 * @param string $fname Calling function name (optional)
1801 * @return bool Whether $table has filed $field
1803 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1804 $info = $this->fieldInfo( $table, $field );
1810 * Determines whether an index exists
1811 * Usually throws a DBQueryError on failure
1812 * If errors are explicitly ignored, returns NULL on failure
1814 * @param string $table
1815 * @param string $index
1816 * @param string $fname
1819 public function indexExists( $table, $index, $fname = __METHOD__
) {
1820 if ( !$this->tableExists( $table ) ) {
1824 $info = $this->indexInfo( $table, $index, $fname );
1825 if ( is_null( $info ) ) {
1828 return $info !== false;
1833 * Query whether a given table exists
1835 * @param string $table
1836 * @param string $fname
1839 public function tableExists( $table, $fname = __METHOD__
) {
1840 $table = $this->tableName( $table );
1841 $old = $this->ignoreErrors( true );
1842 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1843 $this->ignoreErrors( $old );
1849 * Determines if a given index is unique
1851 * @param string $table
1852 * @param string $index
1856 public function indexUnique( $table, $index ) {
1857 $indexInfo = $this->indexInfo( $table, $index );
1859 if ( !$indexInfo ) {
1863 return !$indexInfo[0]->Non_unique
;
1867 * Helper for DatabaseBase::insert().
1869 * @param array $options
1872 protected function makeInsertOptions( $options ) {
1873 return implode( ' ', $options );
1877 * INSERT wrapper, inserts an array into a table.
1881 * - A single associative array. The array keys are the field names, and
1882 * the values are the values to insert. The values are treated as data
1883 * and will be quoted appropriately. If NULL is inserted, this will be
1884 * converted to a database NULL.
1885 * - An array with numeric keys, holding a list of associative arrays.
1886 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1887 * each subarray must be identical to each other, and in the same order.
1889 * $options is an array of options, with boolean options encoded as values
1890 * with numeric keys, in the same style as $options in
1891 * DatabaseBase::select(). Supported options are:
1893 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1894 * any rows which cause duplicate key errors are not inserted. It's
1895 * possible to determine how many rows were successfully inserted using
1896 * DatabaseBase::affectedRows().
1898 * @param string $table Table name. This will be passed through
1899 * DatabaseBase::tableName().
1900 * @param array $a Array of rows to insert
1901 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1902 * @param array $options Array of options
1904 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1909 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1910 # No rows to insert, easy just return now
1911 if ( !count( $a ) ) {
1915 $table = $this->tableName( $table );
1917 if ( !is_array( $options ) ) {
1918 $options = array( $options );
1922 if ( isset( $options['fileHandle'] ) ) {
1923 $fh = $options['fileHandle'];
1925 $options = $this->makeInsertOptions( $options );
1927 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1929 $keys = array_keys( $a[0] );
1932 $keys = array_keys( $a );
1935 $sql = 'INSERT ' . $options .
1936 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1940 foreach ( $a as $row ) {
1946 $sql .= '(' . $this->makeList( $row ) . ')';
1949 $sql .= '(' . $this->makeList( $a ) . ')';
1952 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1954 } elseif ( $fh !== null ) {
1958 return (bool)$this->query( $sql, $fname );
1962 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1964 * @param array $options
1967 protected function makeUpdateOptionsArray( $options ) {
1968 if ( !is_array( $options ) ) {
1969 $options = array( $options );
1974 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1975 $opts[] = $this->lowPriorityOption();
1978 if ( in_array( 'IGNORE', $options ) ) {
1986 * Make UPDATE options for the DatabaseBase::update function
1988 * @param array $options The options passed to DatabaseBase::update
1991 protected function makeUpdateOptions( $options ) {
1992 $opts = $this->makeUpdateOptionsArray( $options );
1994 return implode( ' ', $opts );
1998 * UPDATE wrapper. Takes a condition array and a SET array.
2000 * @param string $table Name of the table to UPDATE. This will be passed through
2001 * DatabaseBase::tableName().
2002 * @param array $values An array of values to SET. For each array element,
2003 * the key gives the field name, and the value gives the data to set
2004 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2005 * @param array $conds An array of conditions (WHERE). See
2006 * DatabaseBase::select() for the details of the format of condition
2007 * arrays. Use '*' to update all rows.
2008 * @param string $fname The function name of the caller (from __METHOD__),
2009 * for logging and profiling.
2010 * @param array $options An array of UPDATE options, can be:
2011 * - IGNORE: Ignore unique key conflicts
2012 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2015 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2016 $table = $this->tableName( $table );
2017 $opts = $this->makeUpdateOptions( $options );
2018 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2020 if ( $conds !== array() && $conds !== '*' ) {
2021 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2024 return $this->query( $sql, $fname );
2028 * Makes an encoded list of strings from an array
2030 * @param array $a Containing the data
2031 * @param int $mode Constant
2032 * - LIST_COMMA: Comma separated, no field names
2033 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2034 * documentation for $conds in DatabaseBase::select().
2035 * - LIST_OR: ORed WHERE clause (without the WHERE)
2036 * - LIST_SET: Comma separated with field names, like a SET clause
2037 * - LIST_NAMES: Comma separated field names
2038 * @throws MWException|DBUnexpectedError
2041 public function makeList( $a, $mode = LIST_COMMA
) {
2042 if ( !is_array( $a ) ) {
2043 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2049 foreach ( $a as $field => $value ) {
2051 if ( $mode == LIST_AND
) {
2053 } elseif ( $mode == LIST_OR
) {
2062 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2063 $list .= "($value)";
2064 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2066 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2067 // Remove null from array to be handled separately if found
2068 $includeNull = false;
2069 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2070 $includeNull = true;
2071 unset( $value[$nullKey] );
2073 if ( count( $value ) == 0 && !$includeNull ) {
2074 throw new MWException( __METHOD__
. ": empty input for field $field" );
2075 } elseif ( count( $value ) == 0 ) {
2076 // only check if $field is null
2077 $list .= "$field IS NULL";
2079 // IN clause contains at least one valid element
2080 if ( $includeNull ) {
2081 // Group subconditions to ensure correct precedence
2084 if ( count( $value ) == 1 ) {
2085 // Special-case single values, as IN isn't terribly efficient
2086 // Don't necessarily assume the single key is 0; we don't
2087 // enforce linear numeric ordering on other arrays here.
2088 $value = array_values( $value );
2089 $list .= $field . " = " . $this->addQuotes( $value[0] );
2091 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2093 // if null present in array, append IS NULL
2094 if ( $includeNull ) {
2095 $list .= " OR $field IS NULL)";
2098 } elseif ( $value === null ) {
2099 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2100 $list .= "$field IS ";
2101 } elseif ( $mode == LIST_SET
) {
2102 $list .= "$field = ";
2106 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2107 $list .= "$field = ";
2109 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2117 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2118 * The keys on each level may be either integers or strings.
2120 * @param array $data Organized as 2-d
2121 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2122 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2123 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2124 * @return string|bool SQL fragment, or false if no items in array
2126 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2129 foreach ( $data as $base => $sub ) {
2130 if ( count( $sub ) ) {
2131 $conds[] = $this->makeList(
2132 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2138 return $this->makeList( $conds, LIST_OR
);
2140 // Nothing to search for...
2146 * Return aggregated value alias
2148 * @param array $valuedata
2149 * @param string $valuename
2153 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2158 * @param string $field
2161 public function bitNot( $field ) {
2166 * @param string $fieldLeft
2167 * @param string $fieldRight
2170 public function bitAnd( $fieldLeft, $fieldRight ) {
2171 return "($fieldLeft & $fieldRight)";
2175 * @param string $fieldLeft
2176 * @param string $fieldRight
2179 public function bitOr( $fieldLeft, $fieldRight ) {
2180 return "($fieldLeft | $fieldRight)";
2184 * Build a concatenation list to feed into a SQL query
2185 * @param array $stringList List of raw SQL expressions; caller is
2186 * responsible for any quoting
2189 public function buildConcat( $stringList ) {
2190 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2194 * Build a GROUP_CONCAT or equivalent statement for a query.
2196 * This is useful for combining a field for several rows into a single string.
2197 * NULL values will not appear in the output, duplicated values will appear,
2198 * and the resulting delimiter-separated values have no defined sort order.
2199 * Code using the results may need to use the PHP unique() or sort() methods.
2201 * @param string $delim Glue to bind the results together
2202 * @param string|array $table Table name
2203 * @param string $field Field name
2204 * @param string|array $conds Conditions
2205 * @param string|array $join_conds Join conditions
2206 * @return string SQL text
2209 public function buildGroupConcatField(
2210 $delim, $table, $field, $conds = '', $join_conds = array()
2212 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2214 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2218 * Change the current database
2220 * @todo Explain what exactly will fail if this is not overridden.
2224 * @return bool Success or failure
2226 public function selectDB( $db ) {
2227 # Stub. Shouldn't cause serious problems if it's not overridden, but
2228 # if your database engine supports a concept similar to MySQL's
2229 # databases you may as well.
2230 $this->mDBname
= $db;
2236 * Get the current DB name
2239 public function getDBname() {
2240 return $this->mDBname
;
2244 * Get the server hostname or IP address
2247 public function getServer() {
2248 return $this->mServer
;
2252 * Format a table name ready for use in constructing an SQL query
2254 * This does two important things: it quotes the table names to clean them up,
2255 * and it adds a table prefix if only given a table name with no quotes.
2257 * All functions of this object which require a table name call this function
2258 * themselves. Pass the canonical name to such functions. This is only needed
2259 * when calling query() directly.
2261 * @param string $name Database table name
2262 * @param string $format One of:
2263 * quoted - Automatically pass the table name through addIdentifierQuotes()
2264 * so that it can be used in a query.
2265 * raw - Do not add identifier quotes to the table name
2266 * @return string Full database name
2268 public function tableName( $name, $format = 'quoted' ) {
2269 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2270 # Skip the entire process when we have a string quoted on both ends.
2271 # Note that we check the end so that we will still quote any use of
2272 # use of `database`.table. But won't break things if someone wants
2273 # to query a database table with a dot in the name.
2274 if ( $this->isQuotedIdentifier( $name ) ) {
2278 # Lets test for any bits of text that should never show up in a table
2279 # name. Basically anything like JOIN or ON which are actually part of
2280 # SQL queries, but may end up inside of the table value to combine
2281 # sql. Such as how the API is doing.
2282 # Note that we use a whitespace test rather than a \b test to avoid
2283 # any remote case where a word like on may be inside of a table name
2284 # surrounded by symbols which may be considered word breaks.
2285 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2289 # Split database and table into proper variables.
2290 # We reverse the explode so that database.table and table both output
2291 # the correct table.
2292 $dbDetails = explode( '.', $name, 3 );
2293 if ( count( $dbDetails ) == 3 ) {
2294 list( $database, $schema, $table ) = $dbDetails;
2295 # We don't want any prefix added in this case
2297 } elseif ( count( $dbDetails ) == 2 ) {
2298 list( $database, $table ) = $dbDetails;
2299 # We don't want any prefix added in this case
2300 # In dbs that support it, $database may actually be the schema
2301 # but that doesn't affect any of the functionality here
2305 list( $table ) = $dbDetails;
2306 if ( $wgSharedDB !== null # We have a shared database
2307 && $this->mForeign
== false # We're not working on a foreign database
2308 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2309 && in_array( $table, $wgSharedTables ) # A shared table is selected
2311 $database = $wgSharedDB;
2312 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2313 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2316 $schema = $this->mSchema
; # Default schema
2317 $prefix = $this->mTablePrefix
; # Default prefix
2321 # Quote $table and apply the prefix if not quoted.
2322 # $tableName might be empty if this is called from Database::replaceVars()
2323 $tableName = "{$prefix}{$table}";
2324 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2325 $tableName = $this->addIdentifierQuotes( $tableName );
2328 # Quote $schema and merge it with the table name if needed
2329 if ( strlen( $schema ) ) {
2330 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2331 $schema = $this->addIdentifierQuotes( $schema );
2333 $tableName = $schema . '.' . $tableName;
2336 # Quote $database and merge it with the table name if needed
2337 if ( $database !== null ) {
2338 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2339 $database = $this->addIdentifierQuotes( $database );
2341 $tableName = $database . '.' . $tableName;
2348 * Fetch a number of table names into an array
2349 * This is handy when you need to construct SQL for joins
2352 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2353 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2354 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2358 public function tableNames() {
2359 $inArray = func_get_args();
2362 foreach ( $inArray as $name ) {
2363 $retVal[$name] = $this->tableName( $name );
2370 * Fetch a number of table names into an zero-indexed numerical array
2371 * This is handy when you need to construct SQL for joins
2374 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2375 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2376 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2380 public function tableNamesN() {
2381 $inArray = func_get_args();
2384 foreach ( $inArray as $name ) {
2385 $retVal[] = $this->tableName( $name );
2392 * Get an aliased table name
2393 * e.g. tableName AS newTableName
2395 * @param string $name Table name, see tableName()
2396 * @param string|bool $alias Alias (optional)
2397 * @return string SQL name for aliased table. Will not alias a table to its own name
2399 public function tableNameWithAlias( $name, $alias = false ) {
2400 if ( !$alias ||
$alias == $name ) {
2401 return $this->tableName( $name );
2403 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2408 * Gets an array of aliased table names
2410 * @param array $tables Array( [alias] => table )
2411 * @return string[] See tableNameWithAlias()
2413 public function tableNamesWithAlias( $tables ) {
2415 foreach ( $tables as $alias => $table ) {
2416 if ( is_numeric( $alias ) ) {
2419 $retval[] = $this->tableNameWithAlias( $table, $alias );
2426 * Get an aliased field name
2427 * e.g. fieldName AS newFieldName
2429 * @param string $name Field name
2430 * @param string|bool $alias Alias (optional)
2431 * @return string SQL name for aliased field. Will not alias a field to its own name
2433 public function fieldNameWithAlias( $name, $alias = false ) {
2434 if ( !$alias ||
(string)$alias === (string)$name ) {
2437 return $name . ' AS ' . $alias; // PostgreSQL needs AS
2442 * Gets an array of aliased field names
2444 * @param array $fields Array( [alias] => field )
2445 * @return string[] See fieldNameWithAlias()
2447 public function fieldNamesWithAlias( $fields ) {
2449 foreach ( $fields as $alias => $field ) {
2450 if ( is_numeric( $alias ) ) {
2453 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2460 * Get the aliased table name clause for a FROM clause
2461 * which might have a JOIN and/or USE INDEX clause
2463 * @param array $tables ( [alias] => table )
2464 * @param array $use_index Same as for select()
2465 * @param array $join_conds Same as for select()
2468 protected function tableNamesWithUseIndexOrJOIN(
2469 $tables, $use_index = array(), $join_conds = array()
2473 $use_index = (array)$use_index;
2474 $join_conds = (array)$join_conds;
2476 foreach ( $tables as $alias => $table ) {
2477 if ( !is_string( $alias ) ) {
2478 // No alias? Set it equal to the table name
2481 // Is there a JOIN clause for this table?
2482 if ( isset( $join_conds[$alias] ) ) {
2483 list( $joinType, $conds ) = $join_conds[$alias];
2484 $tableClause = $joinType;
2485 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2486 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2487 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2489 $tableClause .= ' ' . $use;
2492 $on = $this->makeList( (array)$conds, LIST_AND
);
2494 $tableClause .= ' ON (' . $on . ')';
2497 $retJOIN[] = $tableClause;
2498 } elseif ( isset( $use_index[$alias] ) ) {
2499 // Is there an INDEX clause for this table?
2500 $tableClause = $this->tableNameWithAlias( $table, $alias );
2501 $tableClause .= ' ' . $this->useIndexClause(
2502 implode( ',', (array)$use_index[$alias] )
2505 $ret[] = $tableClause;
2507 $tableClause = $this->tableNameWithAlias( $table, $alias );
2509 $ret[] = $tableClause;
2513 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2514 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2515 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2517 // Compile our final table clause
2518 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2522 * Get the name of an index in a given table.
2524 * @protected Don't use outside of DatabaseBase and childs
2525 * @param string $index
2528 public function indexName( $index ) {
2529 // @FIXME: Make this protected once we move away from PHP 5.3
2530 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2532 // Backwards-compatibility hack
2534 'ar_usertext_timestamp' => 'usertext_timestamp',
2535 'un_user_id' => 'user_id',
2536 'un_user_ip' => 'user_ip',
2539 if ( isset( $renamed[$index] ) ) {
2540 return $renamed[$index];
2547 * Adds quotes and backslashes.
2549 * @param string|Blob $s
2552 public function addQuotes( $s ) {
2553 if ( $s instanceof Blob
) {
2556 if ( $s === null ) {
2559 # This will also quote numeric values. This should be harmless,
2560 # and protects against weird problems that occur when they really
2561 # _are_ strings such as article titles and string->number->string
2562 # conversion is not 1:1.
2563 return "'" . $this->strencode( $s ) . "'";
2568 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2569 * MySQL uses `backticks` while basically everything else uses double quotes.
2570 * Since MySQL is the odd one out here the double quotes are our generic
2571 * and we implement backticks in DatabaseMysql.
2576 public function addIdentifierQuotes( $s ) {
2577 return '"' . str_replace( '"', '""', $s ) . '"';
2581 * Returns if the given identifier looks quoted or not according to
2582 * the database convention for quoting identifiers .
2584 * @param string $name
2587 public function isQuotedIdentifier( $name ) {
2588 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2595 protected function escapeLikeInternal( $s ) {
2596 return addcslashes( $s, '\%_' );
2600 * LIKE statement wrapper, receives a variable-length argument list with
2601 * parts of pattern to match containing either string literals that will be
2602 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2603 * the function could be provided with an array of aforementioned
2606 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2607 * a LIKE clause that searches for subpages of 'My page title'.
2609 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2610 * $query .= $dbr->buildLike( $pattern );
2613 * @return string Fully built LIKE statement
2615 public function buildLike() {
2616 $params = func_get_args();
2618 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2619 $params = $params[0];
2624 foreach ( $params as $value ) {
2625 if ( $value instanceof LikeMatch
) {
2626 $s .= $value->toString();
2628 $s .= $this->escapeLikeInternal( $value );
2632 return " LIKE {$this->addQuotes( $s )} ";
2636 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2640 public function anyChar() {
2641 return new LikeMatch( '_' );
2645 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2649 public function anyString() {
2650 return new LikeMatch( '%' );
2654 * Returns an appropriately quoted sequence value for inserting a new row.
2655 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2656 * subclass will return an integer, and save the value for insertId()
2658 * Any implementation of this function should *not* involve reusing
2659 * sequence numbers created for rolled-back transactions.
2660 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2661 * @param string $seqName
2664 public function nextSequenceValue( $seqName ) {
2669 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2670 * is only needed because a) MySQL must be as efficient as possible due to
2671 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2672 * which index to pick. Anyway, other databases might have different
2673 * indexes on a given table. So don't bother overriding this unless you're
2675 * @param string $index
2678 public function useIndexClause( $index ) {
2683 * REPLACE query wrapper.
2685 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2686 * except that when there is a duplicate key error, the old row is deleted
2687 * and the new row is inserted in its place.
2689 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2690 * perform the delete, we need to know what the unique indexes are so that
2691 * we know how to find the conflicting rows.
2693 * It may be more efficient to leave off unique indexes which are unlikely
2694 * to collide. However if you do this, you run the risk of encountering
2695 * errors which wouldn't have occurred in MySQL.
2697 * @param string $table The table to replace the row(s) in.
2698 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2699 * a field name or an array of field names
2700 * @param array $rows Can be either a single row to insert, or multiple rows,
2701 * in the same format as for DatabaseBase::insert()
2702 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2704 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2705 $quotedTable = $this->tableName( $table );
2707 if ( count( $rows ) == 0 ) {
2712 if ( !is_array( reset( $rows ) ) ) {
2713 $rows = array( $rows );
2716 // @FXIME: this is not atomic, but a trx would break affectedRows()
2717 foreach ( $rows as $row ) {
2718 # Delete rows which collide
2719 if ( $uniqueIndexes ) {
2720 $sql = "DELETE FROM $quotedTable WHERE ";
2722 foreach ( $uniqueIndexes as $index ) {
2729 if ( is_array( $index ) ) {
2731 foreach ( $index as $col ) {
2737 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2740 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2744 $this->query( $sql, $fname );
2747 # Now insert the row
2748 $this->insert( $table, $row, $fname );
2753 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2756 * @param string $table Table name
2757 * @param array|string $rows Row(s) to insert
2758 * @param string $fname Caller function name
2760 * @return ResultWrapper
2762 protected function nativeReplace( $table, $rows, $fname ) {
2763 $table = $this->tableName( $table );
2766 if ( !is_array( reset( $rows ) ) ) {
2767 $rows = array( $rows );
2770 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2773 foreach ( $rows as $row ) {
2780 $sql .= '(' . $this->makeList( $row ) . ')';
2783 return $this->query( $sql, $fname );
2787 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2789 * This updates any conflicting rows (according to the unique indexes) using
2790 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2792 * $rows may be either:
2793 * - A single associative array. The array keys are the field names, and
2794 * the values are the values to insert. The values are treated as data
2795 * and will be quoted appropriately. If NULL is inserted, this will be
2796 * converted to a database NULL.
2797 * - An array with numeric keys, holding a list of associative arrays.
2798 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2799 * each subarray must be identical to each other, and in the same order.
2801 * It may be more efficient to leave off unique indexes which are unlikely
2802 * to collide. However if you do this, you run the risk of encountering
2803 * errors which wouldn't have occurred in MySQL.
2805 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2810 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2811 * @param array $rows A single row or list of rows to insert
2812 * @param array $uniqueIndexes List of single field names or field name tuples
2813 * @param array $set An array of values to SET. For each array element, the
2814 * key gives the field name, and the value gives the data to set that
2815 * field to. The data will be quoted by DatabaseBase::addQuotes().
2816 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2820 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2823 if ( !count( $rows ) ) {
2824 return true; // nothing to do
2827 if ( !is_array( reset( $rows ) ) ) {
2828 $rows = array( $rows );
2831 if ( count( $uniqueIndexes ) ) {
2832 $clauses = array(); // list WHERE clauses that each identify a single row
2833 foreach ( $rows as $row ) {
2834 foreach ( $uniqueIndexes as $index ) {
2835 $index = is_array( $index ) ?
$index : array( $index ); // columns
2836 $rowKey = array(); // unique key to this row
2837 foreach ( $index as $column ) {
2838 $rowKey[$column] = $row[$column];
2840 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2843 $where = array( $this->makeList( $clauses, LIST_OR
) );
2848 $useTrx = !$this->mTrxLevel
;
2850 $this->begin( $fname );
2853 # Update any existing conflicting row(s)
2854 if ( $where !== false ) {
2855 $ok = $this->update( $table, $set, $where, $fname );
2859 # Now insert any non-conflicting row(s)
2860 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2861 } catch ( Exception
$e ) {
2863 $this->rollback( $fname );
2868 $this->commit( $fname );
2875 * DELETE where the condition is a join.
2877 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2878 * we use sub-selects
2880 * For safety, an empty $conds will not delete everything. If you want to
2881 * delete all rows where the join condition matches, set $conds='*'.
2883 * DO NOT put the join condition in $conds.
2885 * @param string $delTable The table to delete from.
2886 * @param string $joinTable The other table.
2887 * @param string $delVar The variable to join on, in the first table.
2888 * @param string $joinVar The variable to join on, in the second table.
2889 * @param array $conds Condition array of field names mapped to variables,
2890 * ANDed together in the WHERE clause
2891 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2892 * @throws DBUnexpectedError
2894 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2898 throw new DBUnexpectedError( $this,
2899 'DatabaseBase::deleteJoin() called with empty $conds' );
2902 $delTable = $this->tableName( $delTable );
2903 $joinTable = $this->tableName( $joinTable );
2904 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2905 if ( $conds != '*' ) {
2906 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2910 $this->query( $sql, $fname );
2914 * Returns the size of a text field, or -1 for "unlimited"
2916 * @param string $table
2917 * @param string $field
2920 public function textFieldSize( $table, $field ) {
2921 $table = $this->tableName( $table );
2922 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2923 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2924 $row = $this->fetchObject( $res );
2928 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2938 * A string to insert into queries to show that they're low-priority, like
2939 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2940 * string and nothing bad should happen.
2942 * @return string Returns the text of the low priority option if it is
2943 * supported, or a blank string otherwise
2945 public function lowPriorityOption() {
2950 * DELETE query wrapper.
2952 * @param array $table Table name
2953 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2954 * for the format. Use $conds == "*" to delete all rows
2955 * @param string $fname Name of the calling function
2956 * @throws DBUnexpectedError
2957 * @return bool|ResultWrapper
2959 public function delete( $table, $conds, $fname = __METHOD__
) {
2961 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2964 $table = $this->tableName( $table );
2965 $sql = "DELETE FROM $table";
2967 if ( $conds != '*' ) {
2968 if ( is_array( $conds ) ) {
2969 $conds = $this->makeList( $conds, LIST_AND
);
2971 $sql .= ' WHERE ' . $conds;
2974 return $this->query( $sql, $fname );
2978 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2979 * into another table.
2981 * @param string $destTable The table name to insert into
2982 * @param string|array $srcTable May be either a table name, or an array of table names
2983 * to include in a join.
2985 * @param array $varMap Must be an associative array of the form
2986 * array( 'dest1' => 'source1', ...). Source items may be literals
2987 * rather than field names, but strings should be quoted with
2988 * DatabaseBase::addQuotes()
2990 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2991 * the details of the format of condition arrays. May be "*" to copy the
2994 * @param string $fname The function name of the caller, from __METHOD__
2996 * @param array $insertOptions Options for the INSERT part of the query, see
2997 * DatabaseBase::insert() for details.
2998 * @param array $selectOptions Options for the SELECT part of the query, see
2999 * DatabaseBase::select() for details.
3001 * @return ResultWrapper
3003 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3004 $fname = __METHOD__
,
3005 $insertOptions = array(), $selectOptions = array()
3007 $destTable = $this->tableName( $destTable );
3009 if ( !is_array( $insertOptions ) ) {
3010 $insertOptions = array( $insertOptions );
3013 $insertOptions = $this->makeInsertOptions( $insertOptions );
3015 if ( !is_array( $selectOptions ) ) {
3016 $selectOptions = array( $selectOptions );
3019 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3021 if ( is_array( $srcTable ) ) {
3022 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3024 $srcTable = $this->tableName( $srcTable );
3027 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3028 " SELECT $startOpts " . implode( ',', $varMap ) .
3029 " FROM $srcTable $useIndex ";
3031 if ( $conds != '*' ) {
3032 if ( is_array( $conds ) ) {
3033 $conds = $this->makeList( $conds, LIST_AND
);
3035 $sql .= " WHERE $conds";
3038 $sql .= " $tailOpts";
3040 return $this->query( $sql, $fname );
3044 * Construct a LIMIT query with optional offset. This is used for query
3045 * pages. The SQL should be adjusted so that only the first $limit rows
3046 * are returned. If $offset is provided as well, then the first $offset
3047 * rows should be discarded, and the next $limit rows should be returned.
3048 * If the result of the query is not ordered, then the rows to be returned
3049 * are theoretically arbitrary.
3051 * $sql is expected to be a SELECT, if that makes a difference.
3053 * The version provided by default works in MySQL and SQLite. It will very
3054 * likely need to be overridden for most other DBMSes.
3056 * @param string $sql SQL query we will append the limit too
3057 * @param int $limit The SQL limit
3058 * @param int|bool $offset The SQL offset (default false)
3059 * @throws DBUnexpectedError
3062 public function limitResult( $sql, $limit, $offset = false ) {
3063 if ( !is_numeric( $limit ) ) {
3064 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3067 return "$sql LIMIT "
3068 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3073 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3074 * within the UNION construct.
3077 public function unionSupportsOrderAndLimit() {
3078 return true; // True for almost every DB supported
3082 * Construct a UNION query
3083 * This is used for providing overload point for other DB abstractions
3084 * not compatible with the MySQL syntax.
3085 * @param array $sqls SQL statements to combine
3086 * @param bool $all Use UNION ALL
3087 * @return string SQL fragment
3089 public function unionQueries( $sqls, $all ) {
3090 $glue = $all ?
') UNION ALL (' : ') UNION (';
3092 return '(' . implode( $glue, $sqls ) . ')';
3096 * Returns an SQL expression for a simple conditional. This doesn't need
3097 * to be overridden unless CASE isn't supported in your DBMS.
3099 * @param string|array $cond SQL expression which will result in a boolean value
3100 * @param string $trueVal SQL expression to return if true
3101 * @param string $falseVal SQL expression to return if false
3102 * @return string SQL fragment
3104 public function conditional( $cond, $trueVal, $falseVal ) {
3105 if ( is_array( $cond ) ) {
3106 $cond = $this->makeList( $cond, LIST_AND
);
3109 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3113 * Returns a comand for str_replace function in SQL query.
3114 * Uses REPLACE() in MySQL
3116 * @param string $orig Column to modify
3117 * @param string $old Column to seek
3118 * @param string $new Column to replace with
3122 public function strreplace( $orig, $old, $new ) {
3123 return "REPLACE({$orig}, {$old}, {$new})";
3127 * Determines how long the server has been up
3132 public function getServerUptime() {
3137 * Determines if the last failure was due to a deadlock
3142 public function wasDeadlock() {
3147 * Determines if the last failure was due to a lock timeout
3152 public function wasLockTimeout() {
3157 * Determines if the last query error was something that should be dealt
3158 * with by pinging the connection and reissuing the query.
3163 public function wasErrorReissuable() {
3168 * Determines if the last failure was due to the database being read-only.
3173 public function wasReadOnlyError() {
3178 * Determines if the given query error was a connection drop
3181 * @param integer|string $errno
3184 public function wasConnectionError( $errno ) {
3189 * Perform a deadlock-prone transaction.
3191 * This function invokes a callback function to perform a set of write
3192 * queries. If a deadlock occurs during the processing, the transaction
3193 * will be rolled back and the callback function will be called again.
3196 * $dbw->deadlockLoop( callback, ... );
3198 * Extra arguments are passed through to the specified callback function.
3200 * Returns whatever the callback function returned on its successful,
3201 * iteration, or false on error, for example if the retry limit was
3205 * @throws DBQueryError
3207 public function deadlockLoop() {
3208 $args = func_get_args();
3209 $function = array_shift( $args );
3210 $tries = self
::DEADLOCK_TRIES
;
3212 $this->begin( __METHOD__
);
3218 $retVal = call_user_func_array( $function, $args );
3220 } catch ( DBQueryError
$e ) {
3221 if ( $this->wasDeadlock() ) {
3222 // Retry after a randomized delay
3223 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3225 // Throw the error back up
3229 } while ( --$tries > 0 );
3231 if ( $tries <= 0 ) {
3232 // Too many deadlocks; give up
3233 $this->rollback( __METHOD__
);
3236 $this->commit( __METHOD__
);
3243 * Wait for the slave to catch up to a given master position.
3245 * @param DBMasterPos $pos
3246 * @param int $timeout The maximum number of seconds to wait for
3248 * @return int Zero if the slave was past that position already,
3249 * greater than zero if we waited for some period of time, less than
3250 * zero if we timed out.
3252 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3253 # Real waits are implemented in the subclass.
3258 * Get the replication position of this slave
3260 * @return DBMasterPos|bool False if this is not a slave.
3262 public function getSlavePos() {
3268 * Get the position of this master
3270 * @return DBMasterPos|bool False if this is not a master
3272 public function getMasterPos() {
3278 * Run an anonymous function as soon as there is no transaction pending.
3279 * If there is a transaction and it is rolled back, then the callback is cancelled.
3280 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3281 * Callbacks must commit any transactions that they begin.
3283 * This is useful for updates to different systems or when separate transactions are needed.
3284 * For example, one might want to enqueue jobs into a system outside the database, but only
3285 * after the database is updated so that the jobs will see the data when they actually run.
3286 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3288 * @param callable $callback
3291 final public function onTransactionIdle( $callback ) {
3292 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3293 if ( !$this->mTrxLevel
) {
3294 $this->runOnTransactionIdleCallbacks();
3299 * Run an anonymous function before the current transaction commits or now if there is none.
3300 * If there is a transaction and it is rolled back, then the callback is cancelled.
3301 * Callbacks must not start nor commit any transactions.
3303 * This is useful for updates that easily cause deadlocks if locks are held too long
3304 * but where atomicity is strongly desired for these updates and some related updates.
3306 * @param callable $callback
3309 final public function onTransactionPreCommitOrIdle( $callback ) {
3310 if ( $this->mTrxLevel
) {
3311 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3313 $this->onTransactionIdle( $callback ); // this will trigger immediately
3318 * Actually any "on transaction idle" callbacks.
3322 protected function runOnTransactionIdleCallbacks() {
3323 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3325 $e = $ePrior = null; // last exception
3326 do { // callbacks may add callbacks :)
3327 $callbacks = $this->mTrxIdleCallbacks
;
3328 $this->mTrxIdleCallbacks
= array(); // recursion guard
3329 foreach ( $callbacks as $callback ) {
3331 list( $phpCallback ) = $callback;
3332 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3333 call_user_func( $phpCallback );
3335 $this->setFlag( DBO_TRX
); // restore automatic begin()
3337 $this->clearFlag( DBO_TRX
); // restore auto-commit
3339 } catch ( Exception
$e ) {
3341 MWExceptionHandler
::logException( $ePrior );
3344 // Some callbacks may use startAtomic/endAtomic, so make sure
3345 // their transactions are ended so other callbacks don't fail
3346 if ( $this->trxLevel() ) {
3347 $this->rollback( __METHOD__
);
3351 } while ( count( $this->mTrxIdleCallbacks
) );
3353 if ( $e instanceof Exception
) {
3354 throw $e; // re-throw any last exception
3359 * Actually any "on transaction pre-commit" callbacks.
3363 protected function runOnTransactionPreCommitCallbacks() {
3364 $e = $ePrior = null; // last exception
3365 do { // callbacks may add callbacks :)
3366 $callbacks = $this->mTrxPreCommitCallbacks
;
3367 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3368 foreach ( $callbacks as $callback ) {
3370 list( $phpCallback ) = $callback;
3371 call_user_func( $phpCallback );
3372 } catch ( Exception
$e ) {
3374 MWExceptionHandler
::logException( $ePrior );
3379 } while ( count( $this->mTrxPreCommitCallbacks
) );
3381 if ( $e instanceof Exception
) {
3382 throw $e; // re-throw any last exception
3387 * Begin an atomic section of statements
3389 * If a transaction has been started already, just keep track of the given
3390 * section name to make sure the transaction is not committed pre-maturely.
3391 * This function can be used in layers (with sub-sections), so use a stack
3392 * to keep track of the different atomic sections. If there is no transaction,
3393 * start one implicitly.
3395 * The goal of this function is to create an atomic section of SQL queries
3396 * without having to start a new transaction if it already exists.
3398 * Atomic sections are more strict than transactions. With transactions,
3399 * attempting to begin a new transaction when one is already running results
3400 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3401 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3402 * and any database transactions cannot be began or committed until all atomic
3403 * levels are closed. There is no such thing as implicitly opening or closing
3404 * an atomic section.
3407 * @param string $fname
3410 final public function startAtomic( $fname = __METHOD__
) {
3411 if ( !$this->mTrxLevel
) {
3412 $this->begin( $fname );
3413 $this->mTrxAutomatic
= true;
3414 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3415 // in all changes being in one transaction to keep requests transactional.
3416 if ( !$this->getFlag( DBO_TRX
) ) {
3417 $this->mTrxAutomaticAtomic
= true;
3421 $this->mTrxAtomicLevels
[] = $fname;
3425 * Ends an atomic section of SQL statements
3427 * Ends the next section of atomic SQL statements and commits the transaction
3431 * @see DatabaseBase::startAtomic
3432 * @param string $fname
3435 final public function endAtomic( $fname = __METHOD__
) {
3436 if ( !$this->mTrxLevel
) {
3437 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3439 if ( !$this->mTrxAtomicLevels ||
3440 array_pop( $this->mTrxAtomicLevels
) !== $fname
3442 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3445 if ( !$this->mTrxAtomicLevels
&& $this->mTrxAutomaticAtomic
) {
3446 $this->commit( $fname, 'flush' );
3450 final public function doAtomicSection( $fname, $callback ) {
3451 if ( !is_callable( $callback ) ) {
3452 throw new UnexpectedValueException( "Invalid callback." );
3455 $this->startAtomic( $fname );
3457 call_user_func_array( $callback, array( $this, $fname ) );
3458 } catch ( Exception
$e ) {
3459 $this->rollback( $fname );
3462 $this->endAtomic( $fname );
3466 * Begin a transaction. If a transaction is already in progress,
3467 * that transaction will be committed before the new transaction is started.
3469 * Note that when the DBO_TRX flag is set (which is usually the case for web
3470 * requests, but not for maintenance scripts), any previous database query
3471 * will have started a transaction automatically.
3473 * Nesting of transactions is not supported. Attempts to nest transactions
3474 * will cause a warning, unless the current transaction was started
3475 * automatically because of the DBO_TRX flag.
3477 * @param string $fname
3480 final public function begin( $fname = __METHOD__
) {
3481 if ( $this->mTrxLevel
) { // implicit commit
3482 if ( $this->mTrxAtomicLevels
) {
3483 // If the current transaction was an automatic atomic one, then we definitely have
3484 // a problem. Same if there is any unclosed atomic level.
3485 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3486 throw new DBUnexpectedError(
3488 "Got explicit BEGIN from $fname while atomic section(s) $levels are open."
3490 } elseif ( !$this->mTrxAutomatic
) {
3491 // We want to warn about inadvertently nested begin/commit pairs, but not about
3492 // auto-committing implicit transactions that were started by query() via DBO_TRX
3493 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3494 " performing implicit commit!";
3497 $this->getLogContext( array(
3498 'method' => __METHOD__
,
3503 // if the transaction was automatic and has done write operations
3504 if ( $this->mTrxDoneWrites
) {
3505 wfDebug( "$fname: Automatic transaction with writes in progress" .
3506 " (from {$this->mTrxFname}), performing implicit commit!\n"
3511 $this->runOnTransactionPreCommitCallbacks();
3512 $writeTime = $this->pendingWriteQueryDuration();
3513 $this->doCommit( $fname );
3514 if ( $this->mTrxDoneWrites
) {
3515 $this->mDoneWrites
= microtime( true );
3516 $this->getTransactionProfiler()->transactionWritingOut(
3517 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3519 $this->runOnTransactionIdleCallbacks();
3522 # Avoid fatals if close() was called
3523 $this->assertOpen();
3525 $this->doBegin( $fname );
3526 $this->mTrxTimestamp
= microtime( true );
3527 $this->mTrxFname
= $fname;
3528 $this->mTrxDoneWrites
= false;
3529 $this->mTrxAutomatic
= false;
3530 $this->mTrxAutomaticAtomic
= false;
3531 $this->mTrxAtomicLevels
= array();
3532 $this->mTrxIdleCallbacks
= array();
3533 $this->mTrxPreCommitCallbacks
= array();
3534 $this->mTrxShortId
= wfRandomString( 12 );
3535 $this->mTrxWriteDuration
= 0.0;
3536 // First SELECT after BEGIN will establish the snapshot in REPEATABLE-READ.
3537 // Get an estimate of the slave lag before then, treating estimate staleness
3538 // as lag itself just to be safe
3539 $status = $this->getApproximateLagStatus();
3540 $this->mTrxSlaveLag
= $status['lag'] +
( microtime( true ) - $status['since'] );
3544 * Issues the BEGIN command to the database server.
3546 * @see DatabaseBase::begin()
3547 * @param string $fname
3549 protected function doBegin( $fname ) {
3550 $this->query( 'BEGIN', $fname );
3551 $this->mTrxLevel
= 1;
3555 * Commits a transaction previously started using begin().
3556 * If no transaction is in progress, a warning is issued.
3558 * Nesting of transactions is not supported.
3560 * @param string $fname
3561 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3562 * explicitly committing implicit transactions, or calling commit when no
3563 * transaction is in progress. This will silently break any ongoing
3564 * explicit transaction. Only set the flush flag if you are sure that it
3565 * is safe to ignore these warnings in your context.
3566 * @throws DBUnexpectedError
3568 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3569 if ( $this->mTrxLevel
&& $this->mTrxAtomicLevels
) {
3570 // There are still atomic sections open. This cannot be ignored
3571 $levels = implode( ', ', $this->mTrxAtomicLevels
);
3572 throw new DBUnexpectedError(
3574 "Got COMMIT while atomic sections $levels are still open"
3578 if ( $flush === 'flush' ) {
3579 if ( !$this->mTrxLevel
) {
3580 return; // nothing to do
3581 } elseif ( !$this->mTrxAutomatic
) {
3582 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3585 if ( !$this->mTrxLevel
) {
3586 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3587 return; // nothing to do
3588 } elseif ( $this->mTrxAutomatic
) {
3589 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3593 # Avoid fatals if close() was called
3594 $this->assertOpen();
3596 $this->runOnTransactionPreCommitCallbacks();
3597 $writeTime = $this->pendingWriteQueryDuration();
3598 $this->doCommit( $fname );
3599 if ( $this->mTrxDoneWrites
) {
3600 $this->mDoneWrites
= microtime( true );
3601 $this->getTransactionProfiler()->transactionWritingOut(
3602 $this->mServer
, $this->mDBname
, $this->mTrxShortId
, $writeTime );
3604 $this->runOnTransactionIdleCallbacks();
3608 * Issues the COMMIT command to the database server.
3610 * @see DatabaseBase::commit()
3611 * @param string $fname
3613 protected function doCommit( $fname ) {
3614 if ( $this->mTrxLevel
) {
3615 $this->query( 'COMMIT', $fname );
3616 $this->mTrxLevel
= 0;
3621 * Rollback a transaction previously started using begin().
3622 * If no transaction is in progress, a warning is issued.
3624 * No-op on non-transactional databases.
3626 * @param string $fname
3627 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3628 * calling rollback when no transaction is in progress. This will silently
3629 * break any ongoing explicit transaction. Only set the flush flag if you
3630 * are sure that it is safe to ignore these warnings in your context.
3631 * @throws DBUnexpectedError
3632 * @since 1.23 Added $flush parameter
3634 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3635 if ( $flush !== 'flush' ) {
3636 if ( !$this->mTrxLevel
) {
3637 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3638 return; // nothing to do
3639 } elseif ( $this->mTrxAutomatic
) {
3640 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3643 if ( !$this->mTrxLevel
) {
3644 return; // nothing to do
3645 } elseif ( !$this->mTrxAutomatic
) {
3646 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3650 # Avoid fatals if close() was called
3651 $this->assertOpen();
3653 $this->doRollback( $fname );
3654 $this->mTrxIdleCallbacks
= array(); // cancel
3655 $this->mTrxPreCommitCallbacks
= array(); // cancel
3656 $this->mTrxAtomicLevels
= array();
3657 if ( $this->mTrxDoneWrites
) {
3658 $this->getTransactionProfiler()->transactionWritingOut(
3659 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3664 * Issues the ROLLBACK command to the database server.
3666 * @see DatabaseBase::rollback()
3667 * @param string $fname
3669 protected function doRollback( $fname ) {
3670 if ( $this->mTrxLevel
) {
3671 $this->query( 'ROLLBACK', $fname, true );
3672 $this->mTrxLevel
= 0;
3677 * Creates a new table with structure copied from existing table
3678 * Note that unlike most database abstraction functions, this function does not
3679 * automatically append database prefix, because it works at a lower
3680 * abstraction level.
3681 * The table names passed to this function shall not be quoted (this
3682 * function calls addIdentifierQuotes when needed).
3684 * @param string $oldName Name of table whose structure should be copied
3685 * @param string $newName Name of table to be created
3686 * @param bool $temporary Whether the new table should be temporary
3687 * @param string $fname Calling function name
3688 * @throws MWException
3689 * @return bool True if operation was successful
3691 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3694 throw new MWException(
3695 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3699 * List all tables on the database
3701 * @param string $prefix Only show tables with this prefix, e.g. mw_
3702 * @param string $fname Calling function name
3703 * @throws MWException
3706 function listTables( $prefix = null, $fname = __METHOD__
) {
3707 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3711 * Reset the views process cache set by listViews()
3714 final public function clearViewsCache() {
3715 $this->allViews
= null;
3719 * Lists all the VIEWs in the database
3721 * For caching purposes the list of all views should be stored in
3722 * $this->allViews. The process cache can be cleared with clearViewsCache()
3724 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3725 * @param string $fname Name of calling function
3726 * @throws MWException
3730 public function listViews( $prefix = null, $fname = __METHOD__
) {
3731 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3735 * Differentiates between a TABLE and a VIEW
3737 * @param string $name Name of the database-structure to test.
3738 * @throws MWException
3742 public function isView( $name ) {
3743 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3747 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3748 * to the format used for inserting into timestamp fields in this DBMS.
3750 * The result is unquoted, and needs to be passed through addQuotes()
3751 * before it can be included in raw SQL.
3753 * @param string|int $ts
3757 public function timestamp( $ts = 0 ) {
3758 return wfTimestamp( TS_MW
, $ts );
3762 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3763 * to the format used for inserting into timestamp fields in this DBMS. If
3764 * NULL is input, it is passed through, allowing NULL values to be inserted
3765 * into timestamp fields.
3767 * The result is unquoted, and needs to be passed through addQuotes()
3768 * before it can be included in raw SQL.
3770 * @param string|int $ts
3774 public function timestampOrNull( $ts = null ) {
3775 if ( is_null( $ts ) ) {
3778 return $this->timestamp( $ts );
3783 * Take the result from a query, and wrap it in a ResultWrapper if
3784 * necessary. Boolean values are passed through as is, to indicate success
3785 * of write queries or failure.
3787 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3788 * resource, and it was necessary to call this function to convert it to
3789 * a wrapper. Nowadays, raw database objects are never exposed to external
3790 * callers, so this is unnecessary in external code.
3792 * @param bool|ResultWrapper|resource|object $result
3793 * @return bool|ResultWrapper
3795 protected function resultObject( $result ) {
3798 } elseif ( $result instanceof ResultWrapper
) {
3800 } elseif ( $result === true ) {
3801 // Successful write query
3804 return new ResultWrapper( $this, $result );
3809 * Ping the server and try to reconnect if it there is no connection
3811 * @return bool Success or failure
3813 public function ping() {
3814 # Stub. Not essential to override.
3818 public function getSessionLagStatus() {
3819 return $this->getTransactionLagStatus() ?
: $this->getApproximateLagStatus();
3823 * Get the slave lag when the current transaction started
3825 * This is useful when transactions might use snapshot isolation
3826 * (e.g. REPEATABLE-READ in innodb), so the "real" lag of that data
3827 * is this lag plus transaction duration. If they don't, it is still
3828 * safe to be pessimistic. This returns null if there is no transaction.
3830 * @return array|null ('lag': seconds or false on error, 'since': UNIX timestamp of BEGIN)
3833 public function getTransactionLagStatus() {
3834 return $this->mTrxLevel
3835 ?
array( 'lag' => $this->mTrxSlaveLag
, 'since' => $this->trxTimestamp() )
3840 * Get a slave lag estimate for this server
3842 * @return array ('lag': seconds or false on error, 'since': UNIX timestamp of estimate)
3845 public function getApproximateLagStatus() {
3847 'lag' => $this->getLBInfo( 'slave' ) ?
$this->getLag() : 0,
3848 'since' => microtime( true )
3853 * Merge the result of getSessionLagStatus() for several DBs
3854 * using the most pessimistic values to estimate the lag of
3855 * any data derived from them in combination
3857 * This is information is useful for caching modules
3859 * @see WANObjectCache::set()
3860 * @see WANObjectCache::getWithSetCallback()
3862 * @param IDatabase $db1
3863 * @param IDatabase ...
3864 * @return array Map of values:
3865 * - lag: highest lag of any of the DBs or false on error (e.g. replication stopped)
3866 * - since: oldest UNIX timestamp of any of the DB lag estimates
3867 * - pending: whether any of the DBs have uncommitted changes
3870 public static function getCacheSetOptions( IDatabase
$db1 ) {
3871 $res = array( 'lag' => 0, 'since' => INF
, 'pending' => false );
3872 foreach ( func_get_args() as $db ) {
3873 /** @var IDatabase $db */
3874 $status = $db->getSessionLagStatus();
3875 if ( $status['lag'] === false ) {
3876 $res['lag'] = false;
3877 } elseif ( $res['lag'] !== false ) {
3878 $res['lag'] = max( $res['lag'], $status['lag'] );
3880 $res['since'] = min( $res['since'], $status['since'] );
3881 $res['pending'] = $res['pending'] ?
: $db->writesPending();
3887 public function getLag() {
3892 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3896 function maxListLen() {
3901 * Some DBMSs have a special format for inserting into blob fields, they
3902 * don't allow simple quoted strings to be inserted. To insert into such
3903 * a field, pass the data through this function before passing it to
3904 * DatabaseBase::insert().
3909 public function encodeBlob( $b ) {
3914 * Some DBMSs return a special placeholder object representing blob fields
3915 * in result objects. Pass the object through this function to return the
3918 * @param string|Blob $b
3921 public function decodeBlob( $b ) {
3922 if ( $b instanceof Blob
) {
3929 * Override database's default behavior. $options include:
3930 * 'connTimeout' : Set the connection timeout value in seconds.
3931 * May be useful for very long batch queries such as
3932 * full-wiki dumps, where a single query reads out over
3935 * @param array $options
3938 public function setSessionOptions( array $options ) {
3942 * Read and execute SQL commands from a file.
3944 * Returns true on success, error string or exception on failure (depending
3945 * on object's error ignore settings).
3947 * @param string $filename File name to open
3948 * @param bool|callable $lineCallback Optional function called before reading each line
3949 * @param bool|callable $resultCallback Optional function called for each MySQL result
3950 * @param bool|string $fname Calling function name or false if name should be
3951 * generated dynamically using $filename
3952 * @param bool|callable $inputCallback Optional function called for each
3953 * complete line sent
3954 * @throws Exception|MWException
3955 * @return bool|string
3957 public function sourceFile(
3958 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3960 MediaWiki\
suppressWarnings();
3961 $fp = fopen( $filename, 'r' );
3962 MediaWiki\restoreWarnings
();
3964 if ( false === $fp ) {
3965 throw new MWException( "Could not open \"{$filename}\".\n" );
3969 $fname = __METHOD__
. "( $filename )";
3973 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3974 } catch ( Exception
$e ) {
3985 * Get the full path of a patch file. Originally based on archive()
3986 * from updaters.inc. Keep in mind this always returns a patch, as
3987 * it fails back to MySQL if no DB-specific patch can be found
3989 * @param string $patch The name of the patch, like patch-something.sql
3990 * @return string Full path to patch file
3992 public function patchPath( $patch ) {
3995 $dbType = $this->getType();
3996 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3997 return "$IP/maintenance/$dbType/archives/$patch";
3999 return "$IP/maintenance/archives/$patch";
4004 * Set variables to be used in sourceFile/sourceStream, in preference to the
4005 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4006 * all. If it's set to false, $GLOBALS will be used.
4008 * @param bool|array $vars Mapping variable name to value.
4010 public function setSchemaVars( $vars ) {
4011 $this->mSchemaVars
= $vars;
4015 * Read and execute commands from an open file handle.
4017 * Returns true on success, error string or exception on failure (depending
4018 * on object's error ignore settings).
4020 * @param resource $fp File handle
4021 * @param bool|callable $lineCallback Optional function called before reading each query
4022 * @param bool|callable $resultCallback Optional function called for each MySQL result
4023 * @param string $fname Calling function name
4024 * @param bool|callable $inputCallback Optional function called for each complete query sent
4025 * @return bool|string
4027 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4028 $fname = __METHOD__
, $inputCallback = false
4032 while ( !feof( $fp ) ) {
4033 if ( $lineCallback ) {
4034 call_user_func( $lineCallback );
4037 $line = trim( fgets( $fp ) );
4039 if ( $line == '' ) {
4043 if ( '-' == $line[0] && '-' == $line[1] ) {
4051 $done = $this->streamStatementEnd( $cmd, $line );
4055 if ( $done ||
feof( $fp ) ) {
4056 $cmd = $this->replaceVars( $cmd );
4058 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4059 $res = $this->query( $cmd, $fname );
4061 if ( $resultCallback ) {
4062 call_user_func( $resultCallback, $res, $this );
4065 if ( false === $res ) {
4066 $err = $this->lastError();
4068 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4079 * Called by sourceStream() to check if we've reached a statement end
4081 * @param string $sql SQL assembled so far
4082 * @param string $newLine New line about to be added to $sql
4083 * @return bool Whether $newLine contains end of the statement
4085 public function streamStatementEnd( &$sql, &$newLine ) {
4086 if ( $this->delimiter
) {
4088 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4089 if ( $newLine != $prev ) {
4098 * Database independent variable replacement. Replaces a set of variables
4099 * in an SQL statement with their contents as given by $this->getSchemaVars().
4101 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4103 * - '{$var}' should be used for text and is passed through the database's
4105 * - `{$var}` should be used for identifiers (e.g. table and database names).
4106 * It is passed through the database's addIdentifierQuotes method which
4107 * can be overridden if the database uses something other than backticks.
4108 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4109 * database's tableName method.
4110 * - / *i* / passes the name that follows through the database's indexName method.
4111 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4112 * its use should be avoided. In 1.24 and older, string encoding was applied.
4114 * @param string $ins SQL statement to replace variables in
4115 * @return string The new SQL statement with variables replaced
4117 protected function replaceVars( $ins ) {
4119 $vars = $this->getSchemaVars();
4120 return preg_replace_callback(
4122 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4123 \'\{\$ (\w+) }\' | # 3. addQuotes
4124 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4125 /\*\$ (\w+) \*/ # 5. leave unencoded
4127 function ( $m ) use ( $that, $vars ) {
4128 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4129 // check for both nonexistent keys *and* the empty string.
4130 if ( isset( $m[1] ) && $m[1] !== '' ) {
4131 if ( $m[1] === 'i' ) {
4132 return $that->indexName( $m[2] );
4134 return $that->tableName( $m[2] );
4136 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4137 return $that->addQuotes( $vars[$m[3]] );
4138 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4139 return $that->addIdentifierQuotes( $vars[$m[4]] );
4140 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4141 return $vars[$m[5]];
4151 * Get schema variables. If none have been set via setSchemaVars(), then
4152 * use some defaults from the current object.
4156 protected function getSchemaVars() {
4157 if ( $this->mSchemaVars
) {
4158 return $this->mSchemaVars
;
4160 return $this->getDefaultSchemaVars();
4165 * Get schema variables to use if none have been set via setSchemaVars().
4167 * Override this in derived classes to provide variables for tables.sql
4168 * and SQL patch files.
4172 protected function getDefaultSchemaVars() {
4177 * Check to see if a named lock is available (non-blocking)
4179 * @param string $lockName Name of lock to poll
4180 * @param string $method Name of method calling us
4184 public function lockIsFree( $lockName, $method ) {
4189 * Acquire a named lock
4191 * Named locks are not related to transactions
4193 * @param string $lockName Name of lock to aquire
4194 * @param string $method Name of method calling us
4195 * @param int $timeout
4198 public function lock( $lockName, $method, $timeout = 5 ) {
4205 * Named locks are not related to transactions
4207 * @param string $lockName Name of lock to release
4208 * @param string $method Name of method calling us
4210 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4211 * by this thread (in which case the lock is not released), and NULL if the named
4212 * lock did not exist
4214 public function unlock( $lockName, $method ) {
4219 * Check to see if a named lock used by lock() use blocking queues
4224 public function namedLocksEnqueue() {
4229 * Lock specific tables
4231 * @param array $read Array of tables to lock for read access
4232 * @param array $write Array of tables to lock for write access
4233 * @param string $method Name of caller
4234 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4237 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4242 * Unlock specific tables
4244 * @param string $method The caller
4247 public function unlockTables( $method ) {
4253 * @param string $tableName
4254 * @param string $fName
4255 * @return bool|ResultWrapper
4258 public function dropTable( $tableName, $fName = __METHOD__
) {
4259 if ( !$this->tableExists( $tableName, $fName ) ) {
4262 $sql = "DROP TABLE " . $this->tableName( $tableName );
4263 if ( $this->cascadingDeletes() ) {
4267 return $this->query( $sql, $fName );
4271 * Get search engine class. All subclasses of this need to implement this
4272 * if they wish to use searching.
4276 public function getSearchEngine() {
4277 return 'SearchEngineDummy';
4281 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4282 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4283 * because "i" sorts after all numbers.
4287 public function getInfinity() {
4292 * Encode an expiry time into the DBMS dependent format
4294 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4297 public function encodeExpiry( $expiry ) {
4298 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4299 ?
$this->getInfinity()
4300 : $this->timestamp( $expiry );
4304 * Decode an expiry time into a DBMS independent format
4306 * @param string $expiry DB timestamp field value for expiry
4307 * @param int $format TS_* constant, defaults to TS_MW
4310 public function decodeExpiry( $expiry, $format = TS_MW
) {
4311 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4313 : wfTimestamp( $format, $expiry );
4317 * Allow or deny "big selects" for this session only. This is done by setting
4318 * the sql_big_selects session variable.
4320 * This is a MySQL-specific feature.
4322 * @param bool|string $value True for allow, false for deny, or "default" to
4323 * restore the initial value
4325 public function setBigSelects( $value = true ) {
4329 public function isReadOnly() {
4330 return ( $this->getReadOnlyReason() !== false );
4334 * @return string|bool Reason this DB is read-only or false if it is not
4336 protected function getReadOnlyReason() {
4337 $reason = $this->getLBInfo( 'readOnlyReason' );
4339 return is_string( $reason ) ?
$reason : false;
4346 public function __toString() {
4347 return (string)$this->mConn
;
4351 * Run a few simple sanity checks
4353 public function __destruct() {
4354 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4355 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4357 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4359 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4360 $callers[] = $callbackInfo[1];
4362 $callers = implode( ', ', $callers );
4363 trigger_error( "DB transaction callbacks still pending (from $callers)." );
4371 abstract class Database
extends DatabaseBase
{
4372 // B/C until nothing type hints for DatabaseBase
4373 // @TODO: finish renaming DatabaseBase => Database