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 * Interface for classes that implement or wrap DatabaseBase
36 * Database abstraction object
39 abstract class DatabaseBase
implements IDatabase
{
40 /** Number of times to re-try an operation in case of deadlock */
41 const DEADLOCK_TRIES
= 4;
43 /** Minimum time to wait before retry, in microseconds */
44 const DEADLOCK_DELAY_MIN
= 500000;
46 /** Maximum time to wait before retry */
47 const DEADLOCK_DELAY_MAX
= 1500000;
49 protected $mLastQuery = '';
50 protected $mDoneWrites = false;
51 protected $mPHPError = false;
53 protected $mServer, $mUser, $mPassword, $mDBname;
55 /** @var resource Database connection */
56 protected $mConn = null;
57 protected $mOpened = false;
59 /** @var callable[] */
60 protected $mTrxIdleCallbacks = array();
61 /** @var callable[] */
62 protected $mTrxPreCommitCallbacks = array();
64 protected $mTablePrefix;
68 protected $mErrorCount = 0;
69 protected $mLBInfo = array();
70 protected $mDefaultBigSelects = null;
71 protected $mSchemaVars = false;
73 protected $preparedArgs;
75 protected $htmlErrors;
77 protected $delimiter = ';';
80 * Either 1 if a transaction is active or 0 otherwise.
81 * The other Trx fields may not be meaningfull if this is 0.
85 protected $mTrxLevel = 0;
88 * Either a short hexidecimal string if a transaction is active or ""
91 * @see DatabaseBase::mTrxLevel
93 protected $mTrxShortId = '';
96 * The UNIX time that the transaction started. Callers can assume that if
97 * snapshot isolation is used, then the data is *at least* up to date to that
98 * point (possibly more up-to-date since the first SELECT defines the snapshot).
101 * @see DatabaseBase::mTrxLevel
103 private $mTrxTimestamp = 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;
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
142 private $mTrxAutomaticAtomic = false;
146 * @var resource File handle for upgrade
148 protected $fileHandle = null;
152 * @var string[] Process cache of VIEWs names in the database
154 protected $allViews = null;
156 /** @var TransactionProfiler */
157 protected $trxProfiler;
160 * A string describing the current software version, and possibly
161 * other details in a user-friendly way. Will be listed on Special:Version, etc.
162 * Use getServerVersion() to get machine-friendly information.
164 * @return string Version information from the database server
166 public function getServerInfo() {
167 return $this->getServerVersion();
171 * @return string Command delimiter used by this database engine
173 public function getDelimiter() {
174 return $this->delimiter
;
178 * Boolean, controls output of large amounts of debug information.
179 * @param bool|null $debug
180 * - true to enable debugging
181 * - false to disable debugging
182 * - omitted or null to do nothing
184 * @return bool|null Previous value of the flag
186 public function debug( $debug = null ) {
187 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
191 * Turns buffering of SQL result sets on (true) or off (false). Default is
194 * Unbuffered queries are very troublesome in MySQL:
196 * - If another query is executed while the first query is being read
197 * out, the first query is killed. This means you can't call normal
198 * MediaWiki functions while you are reading an unbuffered query result
199 * from a normal wfGetDB() connection.
201 * - Unbuffered queries cause the MySQL server to use large amounts of
202 * memory and to hold broad locks which block other queries.
204 * If you want to limit client-side memory, it's almost always better to
205 * split up queries into batches using a LIMIT clause than to switch off
208 * @param null|bool $buffer
209 * @return null|bool The previous value of the flag
211 public function bufferResults( $buffer = null ) {
212 if ( is_null( $buffer ) ) {
213 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
215 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
220 * Turns on (false) or off (true) the automatic generation and sending
221 * of a "we're sorry, but there has been a database error" page on
222 * database errors. Default is on (false). When turned off, the
223 * code should use lastErrno() and lastError() to handle the
224 * situation as appropriate.
226 * Do not use this function outside of the Database classes.
228 * @param null|bool $ignoreErrors
229 * @return bool The previous value of the flag.
231 public function ignoreErrors( $ignoreErrors = null ) {
232 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
236 * Gets the current transaction level.
238 * Historically, transactions were allowed to be "nested". This is no
239 * longer supported, so this function really only returns a boolean.
241 * @return int The previous value
243 public function trxLevel() {
244 return $this->mTrxLevel
;
248 * Get the UNIX timestamp of the time that the transaction was established
250 * This can be used to reason about the staleness of SELECT data
251 * in REPEATABLE-READ transaction isolation level.
253 * @return float|null Returns null if there is not active transaction
256 public function trxTimestamp() {
257 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
261 * Get/set the number of errors logged. Only useful when errors are ignored
262 * @param int $count The count to set, or omitted to leave it unchanged.
263 * @return int The error count
265 public function errorCount( $count = null ) {
266 return wfSetVar( $this->mErrorCount
, $count );
270 * Get/set the table prefix.
271 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
272 * @return string The previous table prefix.
274 public function tablePrefix( $prefix = null ) {
275 return wfSetVar( $this->mTablePrefix
, $prefix );
279 * Get/set the db schema.
280 * @param string $schema The database schema to set, or omitted to leave it unchanged.
281 * @return string The previous db schema.
283 public function dbSchema( $schema = null ) {
284 return wfSetVar( $this->mSchema
, $schema );
288 * Set the filehandle to copy write statements to.
290 * @param resource $fh File handle
292 public function setFileHandle( $fh ) {
293 $this->fileHandle
= $fh;
297 * Get properties passed down from the server info array of the load
300 * @param string $name The entry of the info array to get, or null to get the
303 * @return array|mixed|null
305 public function getLBInfo( $name = null ) {
306 if ( is_null( $name ) ) {
307 return $this->mLBInfo
;
309 if ( array_key_exists( $name, $this->mLBInfo
) ) {
310 return $this->mLBInfo
[$name];
318 * Set the LB info array, or a member of it. If called with one parameter,
319 * the LB info array is set to that parameter. If it is called with two
320 * parameters, the member with the given name is set to the given value.
322 * @param string $name
323 * @param array $value
325 public function setLBInfo( $name, $value = null ) {
326 if ( is_null( $value ) ) {
327 $this->mLBInfo
= $name;
329 $this->mLBInfo
[$name] = $value;
334 * Set lag time in seconds for a fake slave
336 * @param mixed $lag Valid values for this parameter are determined by the
337 * subclass, but should be a PHP scalar or array that would be sensible
338 * as part of $wgLBFactoryConf.
340 public function setFakeSlaveLag( $lag ) {
344 * Make this connection a fake master
346 * @param bool $enabled
348 public function setFakeMaster( $enabled = true ) {
352 * @return TransactionProfiler
354 protected function getTransactionProfiler() {
355 return $this->trxProfiler
357 : Profiler
::instance()->getTransactionProfiler();
361 * Returns true if this database supports (and uses) cascading deletes
365 public function cascadingDeletes() {
370 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
374 public function cleanupTriggers() {
379 * Returns true if this database is strict about what can be put into an IP field.
380 * Specifically, it uses a NULL value instead of an empty string.
384 public function strictIPs() {
389 * Returns true if this database uses timestamps rather than integers
393 public function realTimestamps() {
398 * Returns true if this database does an implicit sort when doing GROUP BY
402 public function implicitGroupby() {
407 * Returns true if this database does an implicit order by when the column has an index
408 * For example: SELECT page_title FROM page LIMIT 1
412 public function implicitOrderby() {
417 * Returns true if this database can do a native search on IP columns
418 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
422 public function searchableIPs() {
427 * Returns true if this database can use functional indexes
431 public function functionalIndexes() {
436 * Return the last query that went through DatabaseBase::query()
439 public function lastQuery() {
440 return $this->mLastQuery
;
444 * Returns true if the connection may have been used for write queries.
445 * Should return true if unsure.
449 public function doneWrites() {
450 return (bool)$this->mDoneWrites
;
454 * Returns the last time the connection may have been used for write queries.
455 * Should return a timestamp if unsure.
457 * @return int|float UNIX timestamp or false
460 public function lastDoneWrites() {
461 return $this->mDoneWrites ?
: false;
465 * Returns true if there is a transaction open with possible write
466 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
470 public function writesOrCallbacksPending() {
471 return $this->mTrxLevel
&& (
472 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
477 * Is a connection to the database open?
480 public function isOpen() {
481 return $this->mOpened
;
485 * Set a flag for this connection
487 * @param int $flag DBO_* constants from Defines.php:
488 * - DBO_DEBUG: output some debug info (same as debug())
489 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
490 * - DBO_TRX: automatically start transactions
491 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
492 * and removes it in command line mode
493 * - DBO_PERSISTENT: use persistant database connection
495 public function setFlag( $flag ) {
496 global $wgDebugDBTransactions;
497 $this->mFlags |
= $flag;
498 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
499 wfDebug( "Implicit transactions are now enabled.\n" );
504 * Clear a flag for this connection
506 * @param int $flag DBO_* constants from Defines.php:
507 * - DBO_DEBUG: output some debug info (same as debug())
508 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
509 * - DBO_TRX: automatically start transactions
510 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
511 * and removes it in command line mode
512 * - DBO_PERSISTENT: use persistant database connection
514 public function clearFlag( $flag ) {
515 global $wgDebugDBTransactions;
516 $this->mFlags
&= ~
$flag;
517 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
518 wfDebug( "Implicit transactions are now disabled.\n" );
523 * Returns a boolean whether the flag $flag is set for this connection
525 * @param int $flag DBO_* constants from Defines.php:
526 * - DBO_DEBUG: output some debug info (same as debug())
527 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
528 * - DBO_TRX: automatically start transactions
529 * - DBO_PERSISTENT: use persistant database connection
532 public function getFlag( $flag ) {
533 return !!( $this->mFlags
& $flag );
537 * General read-only accessor
539 * @param string $name
542 public function getProperty( $name ) {
549 public function getWikiID() {
550 if ( $this->mTablePrefix
) {
551 return "{$this->mDBname}-{$this->mTablePrefix}";
553 return $this->mDBname
;
558 * Return a path to the DBMS-specific SQL file if it exists,
559 * otherwise default SQL file
561 * @param string $filename
564 private function getSqlFilePath( $filename ) {
566 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
567 if ( file_exists( $dbmsSpecificFilePath ) ) {
568 return $dbmsSpecificFilePath;
570 return "$IP/maintenance/$filename";
575 * Return a path to the DBMS-specific schema file,
576 * otherwise default to tables.sql
580 public function getSchemaPath() {
581 return $this->getSqlFilePath( 'tables.sql' );
585 * Return a path to the DBMS-specific update key file,
586 * otherwise default to update-keys.sql
590 public function getUpdateKeysPath() {
591 return $this->getSqlFilePath( 'update-keys.sql' );
595 * Get the type of the DBMS, as it appears in $wgDBtype.
599 abstract function getType();
602 * Open a connection to the database. Usually aborts on failure
604 * @param string $server Database server host
605 * @param string $user Database user name
606 * @param string $password Database user password
607 * @param string $dbName Database name
609 * @throws DBConnectionError
611 abstract function open( $server, $user, $password, $dbName );
614 * Fetch the next row from the given result object, in object form.
615 * Fields can be retrieved with $row->fieldname, with fields acting like
617 * If no more rows are available, false is returned.
619 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
620 * @return stdClass|bool
621 * @throws DBUnexpectedError Thrown if the database returns an error
623 abstract function fetchObject( $res );
626 * Fetch the next row from the given result object, in associative array
627 * form. Fields are retrieved with $row['fieldname'].
628 * If no more rows are available, false is returned.
630 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
632 * @throws DBUnexpectedError Thrown if the database returns an error
634 abstract function fetchRow( $res );
637 * Get the number of rows in a result object
639 * @param mixed $res A SQL result
642 abstract function numRows( $res );
645 * Get the number of fields in a result object
646 * @see http://www.php.net/mysql_num_fields
648 * @param mixed $res A SQL result
651 abstract function numFields( $res );
654 * Get a field name in a result object
655 * @see http://www.php.net/mysql_field_name
657 * @param mixed $res A SQL result
661 abstract function fieldName( $res, $n );
664 * Get the inserted value of an auto-increment row
666 * The value inserted should be fetched from nextSequenceValue()
669 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
670 * $dbw->insert( 'page', array( 'page_id' => $id ) );
671 * $id = $dbw->insertId();
675 abstract function insertId();
678 * Change the position of the cursor in a result object
679 * @see http://www.php.net/mysql_data_seek
681 * @param mixed $res A SQL result
684 abstract function dataSeek( $res, $row );
687 * Get the last error number
688 * @see http://www.php.net/mysql_errno
692 abstract function lastErrno();
695 * Get a description of the last error
696 * @see http://www.php.net/mysql_error
700 abstract function lastError();
703 * mysql_fetch_field() wrapper
704 * Returns false if the field doesn't exist
706 * @param string $table Table name
707 * @param string $field Field name
711 abstract function fieldInfo( $table, $field );
714 * Get information about an index into an object
715 * @param string $table Table name
716 * @param string $index Index name
717 * @param string $fname Calling function name
718 * @return mixed Database-specific index description class or false if the index does not exist
720 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
723 * Get the number of rows affected by the last write query
724 * @see http://www.php.net/mysql_affected_rows
728 abstract function affectedRows();
731 * Wrapper for addslashes()
733 * @param string $s String to be slashed.
734 * @return string Slashed string.
736 abstract function strencode( $s );
739 * Returns a wikitext link to the DB's website, e.g.,
740 * return "[http://www.mysql.com/ MySQL]";
741 * Should at least contain plain text, if for some reason
742 * your database has no website.
744 * @return string Wikitext of a link to the server software's web site
746 abstract function getSoftwareLink();
749 * A string describing the current software version, like from
750 * mysql_get_server_info().
752 * @return string Version information from the database server.
754 abstract function getServerVersion();
759 * FIXME: It is possible to construct a Database object with no associated
760 * connection object, by specifying no parameters to __construct(). This
761 * feature is deprecated and should be removed.
763 * DatabaseBase subclasses should not be constructed directly in external
764 * code. DatabaseBase::factory() should be used instead.
766 * @param array $params Parameters passed from DatabaseBase::factory()
768 function __construct( array $params ) {
769 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
771 $this->mTrxAtomicLevels
= new SplStack
;
773 $server = $params['host'];
774 $user = $params['user'];
775 $password = $params['password'];
776 $dbName = $params['dbname'];
777 $flags = $params['flags'];
778 $tablePrefix = $params['tablePrefix'];
779 $schema = $params['schema'];
780 $foreign = $params['foreign'];
782 $this->mFlags
= $flags;
783 if ( $this->mFlags
& DBO_DEFAULT
) {
784 if ( $wgCommandLineMode ) {
785 $this->mFlags
&= ~DBO_TRX
;
786 if ( $wgDebugDBTransactions ) {
787 wfDebug( "Implicit transaction open disabled.\n" );
790 $this->mFlags |
= DBO_TRX
;
791 if ( $wgDebugDBTransactions ) {
792 wfDebug( "Implicit transaction open enabled.\n" );
797 /** Get the default table prefix*/
798 if ( $tablePrefix == 'get from global' ) {
799 $this->mTablePrefix
= $wgDBprefix;
801 $this->mTablePrefix
= $tablePrefix;
804 /** Get the database schema*/
805 if ( $schema == 'get from global' ) {
806 $this->mSchema
= $wgDBmwschema;
808 $this->mSchema
= $schema;
811 $this->mForeign
= $foreign;
813 if ( isset( $params['trxProfiler'] ) ) {
814 $this->trxProfiler
= $params['trxProfiler']; // override
818 $this->open( $server, $user, $password, $dbName );
821 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
822 $trxProf = $this->getTransactionProfiler();
823 $trxProf->recordConnection( $this->mServer
, $this->mDBname
, $isMaster );
827 * Called by serialize. Throw an exception when DB connection is serialized.
828 * This causes problems on some database engines because the connection is
829 * not restored on unserialize.
831 public function __sleep() {
832 throw new MWException( 'Database serialization may cause problems, since ' .
833 'the connection is not restored on wakeup.' );
837 * Given a DB type, construct the name of the appropriate child class of
838 * DatabaseBase. This is designed to replace all of the manual stuff like:
839 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
840 * as well as validate against the canonical list of DB types we have
842 * This factory function is mostly useful for when you need to connect to a
843 * database other than the MediaWiki default (such as for external auth,
844 * an extension, et cetera). Do not use this to connect to the MediaWiki
845 * database. Example uses in core:
846 * @see LoadBalancer::reallyOpenConnection()
847 * @see ForeignDBRepo::getMasterDB()
848 * @see WebInstallerDBConnect::execute()
852 * @param string $dbType A possible DB type
853 * @param array $p An array of options to pass to the constructor.
854 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
855 * @throws MWException If the database driver or extension cannot be found
856 * @return DatabaseBase|null DatabaseBase subclass or null
858 final public static function factory( $dbType, $p = array() ) {
859 $canonicalDBTypes = array(
860 'mysql' => array( 'mysqli', 'mysql' ),
861 'postgres' => array(),
868 $dbType = strtolower( $dbType );
869 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
870 $possibleDrivers = $canonicalDBTypes[$dbType];
871 if ( !empty( $p['driver'] ) ) {
872 if ( in_array( $p['driver'], $possibleDrivers ) ) {
873 $driver = $p['driver'];
875 throw new MWException( __METHOD__
.
876 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
879 foreach ( $possibleDrivers as $posDriver ) {
880 if ( extension_loaded( $posDriver ) ) {
881 $driver = $posDriver;
889 if ( $driver === false ) {
890 throw new MWException( __METHOD__
.
891 " no viable database extension found for type '$dbType'" );
894 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
895 // and everything else doesn't use a schema (e.g. null)
896 // Although postgres and oracle support schemas, we don't use them (yet)
897 // to maintain backwards compatibility
898 $defaultSchemas = array(
903 'mssql' => 'get from global',
906 $class = 'Database' . ucfirst( $driver );
907 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
908 // Resolve some defaults for b/c
909 $p['host'] = isset( $p['host'] ) ?
$p['host'] : false;
910 $p['user'] = isset( $p['user'] ) ?
$p['user'] : false;
911 $p['password'] = isset( $p['password'] ) ?
$p['password'] : false;
912 $p['dbname'] = isset( $p['dbname'] ) ?
$p['dbname'] : false;
913 $p['flags'] = isset( $p['flags'] ) ?
$p['flags'] : 0;
914 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global';
915 $p['schema'] = isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType];
916 $p['foreign'] = isset( $p['foreign'] ) ?
$p['foreign'] : false;
918 return new $class( $p );
924 protected function installErrorHandler() {
925 $this->mPHPError
= false;
926 $this->htmlErrors
= ini_set( 'html_errors', '0' );
927 set_error_handler( array( $this, 'connectionErrorHandler' ) );
931 * @return bool|string
933 protected function restoreErrorHandler() {
934 restore_error_handler();
935 if ( $this->htmlErrors
!== false ) {
936 ini_set( 'html_errors', $this->htmlErrors
);
938 if ( $this->mPHPError
) {
939 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
940 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
950 * @param string $errstr
952 public function connectionErrorHandler( $errno, $errstr ) {
953 $this->mPHPError
= $errstr;
957 * Create a log context to pass to wfLogDBError or other logging functions.
959 * @param array $extras Additional data to add to context
962 protected function getLogContext( array $extras = array() ) {
965 'db_server' => $this->mServer
,
966 'db_name' => $this->mDBname
,
967 'db_user' => $this->mUser
,
974 * Closes a database connection.
975 * if it is open : commits any open transactions
977 * @throws MWException
978 * @return bool Operation success. true if already closed.
980 public function close() {
981 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
982 throw new MWException( "Transaction idle callbacks still pending." );
984 if ( $this->mConn
) {
985 if ( $this->trxLevel() ) {
986 if ( !$this->mTrxAutomatic
) {
987 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
988 " performing implicit commit before closing connection!" );
991 $this->commit( __METHOD__
, 'flush' );
994 $closed = $this->closeConnection();
995 $this->mConn
= false;
999 $this->mOpened
= false;
1005 * Closes underlying database connection
1007 * @return bool Whether connection was closed successfully
1009 abstract protected function closeConnection();
1012 * @param string $error Fallback error message, used if none is given by DB
1013 * @throws DBConnectionError
1015 function reportConnectionError( $error = 'Unknown error' ) {
1016 $myError = $this->lastError();
1022 throw new DBConnectionError( $this, $error );
1026 * The DBMS-dependent part of query()
1028 * @param string $sql SQL query.
1029 * @return ResultWrapper|bool Result object to feed to fetchObject,
1030 * fetchRow, ...; or false on failure
1032 abstract protected function doQuery( $sql );
1035 * Determine whether a query writes to the DB.
1036 * Should return true if unsure.
1038 * @param string $sql
1041 public function isWriteQuery( $sql ) {
1042 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1046 * Determine whether a SQL statement is sensitive to isolation level.
1047 * A SQL statement is considered transactable if its result could vary
1048 * depending on the transaction isolation level. Operational commands
1049 * such as 'SET' and 'SHOW' are not considered to be transactable.
1051 * @param string $sql
1054 public function isTransactableQuery( $sql ) {
1055 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1056 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1060 * Run an SQL query and return the result. Normally throws a DBQueryError
1061 * on failure. If errors are ignored, returns false instead.
1063 * In new code, the query wrappers select(), insert(), update(), delete(),
1064 * etc. should be used where possible, since they give much better DBMS
1065 * independence and automatically quote or validate user input in a variety
1066 * of contexts. This function is generally only useful for queries which are
1067 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1070 * However, the query wrappers themselves should call this function.
1072 * @param string $sql SQL query
1073 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1074 * comment (you can use __METHOD__ or add some extra info)
1075 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1076 * maybe best to catch the exception instead?
1077 * @throws MWException
1078 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1079 * for a successful read query, or false on failure if $tempIgnore set
1081 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1082 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1084 $this->mLastQuery
= $sql;
1086 $isWriteQuery = $this->isWriteQuery( $sql );
1087 if ( $isWriteQuery ) {
1088 if ( !$this->mDoneWrites
) {
1089 wfDebug( __METHOD__
. ': Writes done: ' .
1090 DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1092 # Set a flag indicating that writes have been done
1093 $this->mDoneWrites
= microtime( true );
1096 # Add a comment for easy SHOW PROCESSLIST interpretation
1097 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1098 $userName = $wgUser->getName();
1099 if ( mb_strlen( $userName ) > 15 ) {
1100 $userName = mb_substr( $userName, 0, 15 ) . '...';
1102 $userName = str_replace( '/', '', $userName );
1107 // Add trace comment to the begin of the sql string, right after the operator.
1108 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1109 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1111 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
1112 if ( $wgDebugDBTransactions ) {
1113 wfDebug( "Implicit transaction start.\n" );
1115 $this->begin( __METHOD__
. " ($fname)" );
1116 $this->mTrxAutomatic
= true;
1119 # Keep track of whether the transaction has write queries pending
1120 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1121 $this->mTrxDoneWrites
= true;
1122 $this->getTransactionProfiler()->transactionWritingIn(
1123 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1126 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1127 # generalizeSQL will probably cut down the query to reasonable
1128 # logging size most of the time. The substr is really just a sanity check.
1130 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1131 $totalProf = 'DatabaseBase::query-master';
1133 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1134 $totalProf = 'DatabaseBase::query';
1136 # Include query transaction state
1137 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1139 $profiler = Profiler
::instance();
1140 if ( !$profiler instanceof ProfilerStub
) {
1141 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1142 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1145 if ( $this->debug() ) {
1149 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1151 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1153 $master = $isMaster ?
'master' : 'slave';
1154 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1157 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1159 # Avoid fatals if close() was called
1160 if ( !$this->isOpen() ) {
1161 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1164 # Do the query and handle errors
1165 $startTime = microtime( true );
1166 $ret = $this->doQuery( $commentedSql );
1167 # Log the query time and feed it into the DB trx profiler
1168 $this->getTransactionProfiler()->recordQueryCompletion(
1169 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1171 MWDebug
::queryTime( $queryId );
1173 # Try reconnecting if the connection was lost
1174 if ( false === $ret && $this->wasErrorReissuable() ) {
1175 # Transaction is gone, like it or not
1176 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1177 $this->mTrxLevel
= 0;
1178 $this->mTrxIdleCallbacks
= array(); // bug 65263
1179 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1180 wfDebug( "Connection lost, reconnecting...\n" );
1181 # Stash the last error values since ping() might clear them
1182 $lastError = $this->lastError();
1183 $lastErrno = $this->lastErrno();
1184 if ( $this->ping() ) {
1185 wfDebug( "Reconnected\n" );
1186 $server = $this->getServer();
1187 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1188 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1191 # Leave $ret as false and let an error be reported.
1192 # Callers may catch the exception and continue to use the DB.
1193 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1195 # Should be safe to silently retry (no trx and thus no callbacks)
1196 $startTime = microtime( true );
1197 $ret = $this->doQuery( $commentedSql );
1198 # Log the query time and feed it into the DB trx profiler
1199 $this->getTransactionProfiler()->recordQueryCompletion(
1200 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1203 wfDebug( "Failed\n" );
1207 if ( false === $ret ) {
1208 $this->reportQueryError(
1209 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1212 $res = $this->resultObject( $ret );
1214 // Destroy profile sections in the opposite order to their creation
1215 $queryProfSection = false;
1216 $totalProfSection = false;
1222 * Report a query error. Log the error, and if neither the object ignore
1223 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1225 * @param string $error
1227 * @param string $sql
1228 * @param string $fname
1229 * @param bool $tempIgnore
1230 * @throws DBQueryError
1232 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1233 # Ignore errors during error handling to avoid infinite recursion
1234 $ignore = $this->ignoreErrors( true );
1235 ++
$this->mErrorCount
;
1237 if ( $ignore ||
$tempIgnore ) {
1238 wfDebug( "SQL ERROR (ignored): $error\n" );
1239 $this->ignoreErrors( $ignore );
1241 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1243 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1244 $this->getLogContext( array(
1245 'method' => __METHOD__
,
1248 'sql1line' => $sql1line,
1252 wfDebug( "SQL ERROR: " . $error . "\n" );
1253 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1258 * Intended to be compatible with the PEAR::DB wrapper functions.
1259 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1261 * ? = scalar value, quoted as necessary
1262 * ! = raw SQL bit (a function for instance)
1263 * & = filename; reads the file and inserts as a blob
1264 * (we don't use this though...)
1266 * @param string $sql
1267 * @param string $func
1271 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1272 /* MySQL doesn't support prepared statements (yet), so just
1273 * pack up the query for reference. We'll manually replace
1276 return array( 'query' => $sql, 'func' => $func );
1280 * Free a prepared query, generated by prepare().
1281 * @param string $prepared
1283 protected function freePrepared( $prepared ) {
1284 /* No-op by default */
1288 * Execute a prepared query with the various arguments
1289 * @param string $prepared The prepared sql
1290 * @param mixed $args Either an array here, or put scalars as varargs
1292 * @return ResultWrapper
1294 public function execute( $prepared, $args = null ) {
1295 if ( !is_array( $args ) ) {
1297 $args = func_get_args();
1298 array_shift( $args );
1301 $sql = $this->fillPrepared( $prepared['query'], $args );
1303 return $this->query( $sql, $prepared['func'] );
1307 * For faking prepared SQL statements on DBs that don't support it directly.
1309 * @param string $preparedQuery A 'preparable' SQL statement
1310 * @param array $args Array of Arguments to fill it with
1311 * @return string Executable SQL
1313 public function fillPrepared( $preparedQuery, $args ) {
1315 $this->preparedArgs
=& $args;
1317 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1318 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1322 * preg_callback func for fillPrepared()
1323 * The arguments should be in $this->preparedArgs and must not be touched
1324 * while we're doing this.
1326 * @param array $matches
1327 * @throws DBUnexpectedError
1330 protected function fillPreparedArg( $matches ) {
1331 switch ( $matches[1] ) {
1340 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1342 switch ( $matches[1] ) {
1344 return $this->addQuotes( $arg );
1348 # return $this->addQuotes( file_get_contents( $arg ) );
1349 throw new DBUnexpectedError(
1351 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1354 throw new DBUnexpectedError(
1356 'Received invalid match. This should never happen!'
1362 * Free a result object returned by query() or select(). It's usually not
1363 * necessary to call this, just use unset() or let the variable holding
1364 * the result object go out of scope.
1366 * @param mixed $res A SQL result
1368 public function freeResult( $res ) {
1372 * A SELECT wrapper which returns a single field from a single result row.
1374 * Usually throws a DBQueryError on failure. If errors are explicitly
1375 * ignored, returns false on failure.
1377 * If no result rows are returned from the query, false is returned.
1379 * @param string|array $table Table name. See DatabaseBase::select() for details.
1380 * @param string $var The field name to select. This must be a valid SQL
1381 * fragment: do not use unvalidated user input.
1382 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1383 * @param string $fname The function name of the caller.
1384 * @param string|array $options The query options. See DatabaseBase::select() for details.
1386 * @return bool|mixed The value from the field, or false on failure.
1388 public function selectField(
1389 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1391 if ( $var === '*' ) { // sanity
1392 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1395 if ( !is_array( $options ) ) {
1396 $options = array( $options );
1399 $options['LIMIT'] = 1;
1401 $res = $this->select( $table, $var, $cond, $fname, $options );
1402 if ( $res === false ||
!$this->numRows( $res ) ) {
1406 $row = $this->fetchRow( $res );
1408 if ( $row !== false ) {
1409 return reset( $row );
1416 * A SELECT wrapper which returns a list of single field values from result rows.
1418 * Usually throws a DBQueryError on failure. If errors are explicitly
1419 * ignored, returns false on failure.
1421 * If no result rows are returned from the query, false is returned.
1423 * @param string|array $table Table name. See DatabaseBase::select() for details.
1424 * @param string $var The field name to select. This must be a valid SQL
1425 * fragment: do not use unvalidated user input.
1426 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1427 * @param string $fname The function name of the caller.
1428 * @param string|array $options The query options. See DatabaseBase::select() for details.
1430 * @return bool|array The values from the field, or false on failure
1433 public function selectFieldValues(
1434 $table, $var, $cond = '', $fname = __METHOD__
, $options = array()
1436 if ( $var === '*' ) { // sanity
1437 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1440 if ( !is_array( $options ) ) {
1441 $options = array( $options );
1444 $res = $this->select( $table, $var, $cond, $fname, $options );
1445 if ( $res === false ) {
1450 foreach ( $res as $row ) {
1451 $values[] = $row->$var;
1458 * Returns an optional USE INDEX clause to go after the table, and a
1459 * string to go at the end of the query.
1461 * @param array $options Associative array of options to be turned into
1462 * an SQL query, valid keys are listed in the function.
1464 * @see DatabaseBase::select()
1466 public function makeSelectOptions( $options ) {
1467 $preLimitTail = $postLimitTail = '';
1470 $noKeyOptions = array();
1472 foreach ( $options as $key => $option ) {
1473 if ( is_numeric( $key ) ) {
1474 $noKeyOptions[$option] = true;
1478 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1480 $preLimitTail .= $this->makeOrderBy( $options );
1482 // if (isset($options['LIMIT'])) {
1483 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1484 // isset($options['OFFSET']) ? $options['OFFSET']
1488 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1489 $postLimitTail .= ' FOR UPDATE';
1492 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1493 $postLimitTail .= ' LOCK IN SHARE MODE';
1496 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1497 $startOpts .= 'DISTINCT';
1500 # Various MySQL extensions
1501 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1502 $startOpts .= ' /*! STRAIGHT_JOIN */';
1505 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1506 $startOpts .= ' HIGH_PRIORITY';
1509 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1510 $startOpts .= ' SQL_BIG_RESULT';
1513 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1514 $startOpts .= ' SQL_BUFFER_RESULT';
1517 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1518 $startOpts .= ' SQL_SMALL_RESULT';
1521 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1522 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1525 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1526 $startOpts .= ' SQL_CACHE';
1529 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1530 $startOpts .= ' SQL_NO_CACHE';
1533 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1534 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1539 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1543 * Returns an optional GROUP BY with an optional HAVING
1545 * @param array $options Associative array of options
1547 * @see DatabaseBase::select()
1550 public function makeGroupByWithHaving( $options ) {
1552 if ( isset( $options['GROUP BY'] ) ) {
1553 $gb = is_array( $options['GROUP BY'] )
1554 ?
implode( ',', $options['GROUP BY'] )
1555 : $options['GROUP BY'];
1556 $sql .= ' GROUP BY ' . $gb;
1558 if ( isset( $options['HAVING'] ) ) {
1559 $having = is_array( $options['HAVING'] )
1560 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1561 : $options['HAVING'];
1562 $sql .= ' HAVING ' . $having;
1569 * Returns an optional ORDER BY
1571 * @param array $options Associative array of options
1573 * @see DatabaseBase::select()
1576 public function makeOrderBy( $options ) {
1577 if ( isset( $options['ORDER BY'] ) ) {
1578 $ob = is_array( $options['ORDER BY'] )
1579 ?
implode( ',', $options['ORDER BY'] )
1580 : $options['ORDER BY'];
1582 return ' ORDER BY ' . $ob;
1589 * Execute a SELECT query constructed using the various parameters provided.
1590 * See below for full details of the parameters.
1592 * @param string|array $table Table name
1593 * @param string|array $vars Field names
1594 * @param string|array $conds Conditions
1595 * @param string $fname Caller function name
1596 * @param array $options Query options
1597 * @param array $join_conds Join conditions
1600 * @param string|array $table
1602 * May be either an array of table names, or a single string holding a table
1603 * name. If an array is given, table aliases can be specified, for example:
1605 * array( 'a' => 'user' )
1607 * This includes the user table in the query, with the alias "a" available
1608 * for use in field names (e.g. a.user_name).
1610 * All of the table names given here are automatically run through
1611 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1612 * added, and various other table name mappings to be performed.
1615 * @param string|array $vars
1617 * May be either a field name or an array of field names. The field names
1618 * can be complete fragments of SQL, for direct inclusion into the SELECT
1619 * query. If an array is given, field aliases can be specified, for example:
1621 * array( 'maxrev' => 'MAX(rev_id)' )
1623 * This includes an expression with the alias "maxrev" in the query.
1625 * If an expression is given, care must be taken to ensure that it is
1629 * @param string|array $conds
1631 * May be either a string containing a single condition, or an array of
1632 * conditions. If an array is given, the conditions constructed from each
1633 * element are combined with AND.
1635 * Array elements may take one of two forms:
1637 * - Elements with a numeric key are interpreted as raw SQL fragments.
1638 * - Elements with a string key are interpreted as equality conditions,
1639 * where the key is the field name.
1640 * - If the value of such an array element is a scalar (such as a
1641 * string), it will be treated as data and thus quoted appropriately.
1642 * If it is null, an IS NULL clause will be added.
1643 * - If the value is an array, an IN (...) clause will be constructed
1644 * from its non-null elements, and an IS NULL clause will be added
1645 * if null is present, such that the field may match any of the
1646 * elements in the array. The non-null elements will be quoted.
1648 * Note that expressions are often DBMS-dependent in their syntax.
1649 * DBMS-independent wrappers are provided for constructing several types of
1650 * expression commonly used in condition queries. See:
1651 * - DatabaseBase::buildLike()
1652 * - DatabaseBase::conditional()
1655 * @param string|array $options
1657 * Optional: Array of query options. Boolean options are specified by
1658 * including them in the array as a string value with a numeric key, for
1661 * array( 'FOR UPDATE' )
1663 * The supported options are:
1665 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1666 * with LIMIT can theoretically be used for paging through a result set,
1667 * but this is discouraged in MediaWiki for performance reasons.
1669 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1670 * and then the first rows are taken until the limit is reached. LIMIT
1671 * is applied to a result set after OFFSET.
1673 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1674 * changed until the next COMMIT.
1676 * - DISTINCT: Boolean: return only unique result rows.
1678 * - GROUP BY: May be either an SQL fragment string naming a field or
1679 * expression to group by, or an array of such SQL fragments.
1681 * - HAVING: May be either an string containing a HAVING clause or an array of
1682 * conditions building the HAVING clause. If an array is given, the conditions
1683 * constructed from each element are combined with AND.
1685 * - ORDER BY: May be either an SQL fragment giving a field name or
1686 * expression to order by, or an array of such SQL fragments.
1688 * - USE INDEX: This may be either a string giving the index name to use
1689 * for the query, or an array. If it is an associative array, each key
1690 * gives the table name (or alias), each value gives the index name to
1691 * use for that table. All strings are SQL fragments and so should be
1692 * validated by the caller.
1694 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1695 * instead of SELECT.
1697 * And also the following boolean MySQL extensions, see the MySQL manual
1698 * for documentation:
1700 * - LOCK IN SHARE MODE
1704 * - SQL_BUFFER_RESULT
1705 * - SQL_SMALL_RESULT
1706 * - SQL_CALC_FOUND_ROWS
1711 * @param string|array $join_conds
1713 * Optional associative array of table-specific join conditions. In the
1714 * most common case, this is unnecessary, since the join condition can be
1715 * in $conds. However, it is useful for doing a LEFT JOIN.
1717 * The key of the array contains the table name or alias. The value is an
1718 * array with two elements, numbered 0 and 1. The first gives the type of
1719 * join, the second is an SQL fragment giving the join condition for that
1720 * table. For example:
1722 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1724 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1725 * with no rows in it will be returned. If there was a query error, a
1726 * DBQueryError exception will be thrown, except if the "ignore errors"
1727 * option was set, in which case false will be returned.
1729 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1730 $options = array(), $join_conds = array() ) {
1731 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1733 return $this->query( $sql, $fname );
1737 * The equivalent of DatabaseBase::select() except that the constructed SQL
1738 * is returned, instead of being immediately executed. This can be useful for
1739 * doing UNION queries, where the SQL text of each query is needed. In general,
1740 * however, callers outside of Database classes should just use select().
1742 * @param string|array $table Table name
1743 * @param string|array $vars Field names
1744 * @param string|array $conds Conditions
1745 * @param string $fname Caller function name
1746 * @param string|array $options Query options
1747 * @param string|array $join_conds Join conditions
1749 * @return string SQL query string.
1750 * @see DatabaseBase::select()
1752 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1753 $options = array(), $join_conds = array()
1755 if ( is_array( $vars ) ) {
1756 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1759 $options = (array)$options;
1760 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1761 ?
$options['USE INDEX']
1764 if ( is_array( $table ) ) {
1766 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1767 } elseif ( $table != '' ) {
1768 if ( $table[0] == ' ' ) {
1769 $from = ' FROM ' . $table;
1772 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1778 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1779 $this->makeSelectOptions( $options );
1781 if ( !empty( $conds ) ) {
1782 if ( is_array( $conds ) ) {
1783 $conds = $this->makeList( $conds, LIST_AND
);
1785 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1787 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1790 if ( isset( $options['LIMIT'] ) ) {
1791 $sql = $this->limitResult( $sql, $options['LIMIT'],
1792 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1794 $sql = "$sql $postLimitTail";
1796 if ( isset( $options['EXPLAIN'] ) ) {
1797 $sql = 'EXPLAIN ' . $sql;
1804 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1805 * that a single row object is returned. If the query returns no rows,
1806 * false is returned.
1808 * @param string|array $table Table name
1809 * @param string|array $vars Field names
1810 * @param array $conds Conditions
1811 * @param string $fname Caller function name
1812 * @param string|array $options Query options
1813 * @param array|string $join_conds Join conditions
1815 * @return stdClass|bool
1817 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1818 $options = array(), $join_conds = array()
1820 $options = (array)$options;
1821 $options['LIMIT'] = 1;
1822 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1824 if ( $res === false ) {
1828 if ( !$this->numRows( $res ) ) {
1832 $obj = $this->fetchObject( $res );
1838 * Estimate the number of rows in dataset
1840 * MySQL allows you to estimate the number of rows that would be returned
1841 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1842 * index cardinality statistics, and is notoriously inaccurate, especially
1843 * when large numbers of rows have recently been added or deleted.
1845 * For DBMSs that don't support fast result size estimation, this function
1846 * will actually perform the SELECT COUNT(*).
1848 * Takes the same arguments as DatabaseBase::select().
1850 * @param string $table Table name
1851 * @param string $vars Unused
1852 * @param array|string $conds Filters on the table
1853 * @param string $fname Function name for profiling
1854 * @param array $options Options for select
1855 * @return int Row count
1857 public function estimateRowCount(
1858 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1861 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1864 $row = $this->fetchRow( $res );
1865 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1872 * Get the number of rows in dataset
1874 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1876 * Takes the same arguments as DatabaseBase::select().
1878 * @param string $table Table name
1879 * @param string $vars Unused
1880 * @param array|string $conds Filters on the table
1881 * @param string $fname Function name for profiling
1882 * @param array $options Options for select
1883 * @return int Row count
1886 public function selectRowCount(
1887 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1890 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1891 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1894 $row = $this->fetchRow( $res );
1895 $rows = ( isset( $row['rowcount'] ) ) ?
(int)$row['rowcount'] : 0;
1902 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1903 * It's only slightly flawed. Don't use for anything important.
1905 * @param string $sql A SQL Query
1909 static function generalizeSQL( $sql ) {
1910 # This does the same as the regexp below would do, but in such a way
1911 # as to avoid crashing php on some large strings.
1912 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1914 $sql = str_replace( "\\\\", '', $sql );
1915 $sql = str_replace( "\\'", '', $sql );
1916 $sql = str_replace( "\\\"", '', $sql );
1917 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1918 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1920 # All newlines, tabs, etc replaced by single space
1921 $sql = preg_replace( '/\s+/', ' ', $sql );
1924 # except the ones surrounded by characters, e.g. l10n
1925 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1926 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1932 * Determines whether a field exists in a table
1934 * @param string $table Table name
1935 * @param string $field Filed to check on that table
1936 * @param string $fname Calling function name (optional)
1937 * @return bool Whether $table has filed $field
1939 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1940 $info = $this->fieldInfo( $table, $field );
1946 * Determines whether an index exists
1947 * Usually throws a DBQueryError on failure
1948 * If errors are explicitly ignored, returns NULL on failure
1950 * @param string $table
1951 * @param string $index
1952 * @param string $fname
1955 public function indexExists( $table, $index, $fname = __METHOD__
) {
1956 if ( !$this->tableExists( $table ) ) {
1960 $info = $this->indexInfo( $table, $index, $fname );
1961 if ( is_null( $info ) ) {
1964 return $info !== false;
1969 * Query whether a given table exists
1971 * @param string $table
1972 * @param string $fname
1975 public function tableExists( $table, $fname = __METHOD__
) {
1976 $table = $this->tableName( $table );
1977 $old = $this->ignoreErrors( true );
1978 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1979 $this->ignoreErrors( $old );
1985 * Determines if a given index is unique
1987 * @param string $table
1988 * @param string $index
1992 public function indexUnique( $table, $index ) {
1993 $indexInfo = $this->indexInfo( $table, $index );
1995 if ( !$indexInfo ) {
1999 return !$indexInfo[0]->Non_unique
;
2003 * Helper for DatabaseBase::insert().
2005 * @param array $options
2008 protected function makeInsertOptions( $options ) {
2009 return implode( ' ', $options );
2013 * INSERT wrapper, inserts an array into a table.
2017 * - A single associative array. The array keys are the field names, and
2018 * the values are the values to insert. The values are treated as data
2019 * and will be quoted appropriately. If NULL is inserted, this will be
2020 * converted to a database NULL.
2021 * - An array with numeric keys, holding a list of associative arrays.
2022 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2023 * each subarray must be identical to each other, and in the same order.
2025 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2028 * $options is an array of options, with boolean options encoded as values
2029 * with numeric keys, in the same style as $options in
2030 * DatabaseBase::select(). Supported options are:
2032 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2033 * any rows which cause duplicate key errors are not inserted. It's
2034 * possible to determine how many rows were successfully inserted using
2035 * DatabaseBase::affectedRows().
2037 * @param string $table Table name. This will be passed through
2038 * DatabaseBase::tableName().
2039 * @param array $a Array of rows to insert
2040 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2041 * @param array $options Array of options
2045 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2046 # No rows to insert, easy just return now
2047 if ( !count( $a ) ) {
2051 $table = $this->tableName( $table );
2053 if ( !is_array( $options ) ) {
2054 $options = array( $options );
2058 if ( isset( $options['fileHandle'] ) ) {
2059 $fh = $options['fileHandle'];
2061 $options = $this->makeInsertOptions( $options );
2063 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2065 $keys = array_keys( $a[0] );
2068 $keys = array_keys( $a );
2071 $sql = 'INSERT ' . $options .
2072 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2076 foreach ( $a as $row ) {
2082 $sql .= '(' . $this->makeList( $row ) . ')';
2085 $sql .= '(' . $this->makeList( $a ) . ')';
2088 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2090 } elseif ( $fh !== null ) {
2094 return (bool)$this->query( $sql, $fname );
2098 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2100 * @param array $options
2103 protected function makeUpdateOptionsArray( $options ) {
2104 if ( !is_array( $options ) ) {
2105 $options = array( $options );
2110 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2111 $opts[] = $this->lowPriorityOption();
2114 if ( in_array( 'IGNORE', $options ) ) {
2122 * Make UPDATE options for the DatabaseBase::update function
2124 * @param array $options The options passed to DatabaseBase::update
2127 protected function makeUpdateOptions( $options ) {
2128 $opts = $this->makeUpdateOptionsArray( $options );
2130 return implode( ' ', $opts );
2134 * UPDATE wrapper. Takes a condition array and a SET array.
2136 * @param string $table Name of the table to UPDATE. This will be passed through
2137 * DatabaseBase::tableName().
2138 * @param array $values An array of values to SET. For each array element,
2139 * the key gives the field name, and the value gives the data to set
2140 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2141 * @param array $conds An array of conditions (WHERE). See
2142 * DatabaseBase::select() for the details of the format of condition
2143 * arrays. Use '*' to update all rows.
2144 * @param string $fname The function name of the caller (from __METHOD__),
2145 * for logging and profiling.
2146 * @param array $options An array of UPDATE options, can be:
2147 * - IGNORE: Ignore unique key conflicts
2148 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2151 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2152 $table = $this->tableName( $table );
2153 $opts = $this->makeUpdateOptions( $options );
2154 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2156 if ( $conds !== array() && $conds !== '*' ) {
2157 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2160 return $this->query( $sql, $fname );
2164 * Makes an encoded list of strings from an array
2166 * @param array $a Containing the data
2167 * @param int $mode Constant
2168 * - LIST_COMMA: Comma separated, no field names
2169 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2170 * documentation for $conds in DatabaseBase::select().
2171 * - LIST_OR: ORed WHERE clause (without the WHERE)
2172 * - LIST_SET: Comma separated with field names, like a SET clause
2173 * - LIST_NAMES: Comma separated field names
2174 * @throws MWException|DBUnexpectedError
2177 public function makeList( $a, $mode = LIST_COMMA
) {
2178 if ( !is_array( $a ) ) {
2179 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2185 foreach ( $a as $field => $value ) {
2187 if ( $mode == LIST_AND
) {
2189 } elseif ( $mode == LIST_OR
) {
2198 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2199 $list .= "($value)";
2200 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2202 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2203 // Remove null from array to be handled separately if found
2204 $includeNull = false;
2205 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2206 $includeNull = true;
2207 unset( $value[$nullKey] );
2209 if ( count( $value ) == 0 && !$includeNull ) {
2210 throw new MWException( __METHOD__
. ": empty input for field $field" );
2211 } elseif ( count( $value ) == 0 ) {
2212 // only check if $field is null
2213 $list .= "$field IS NULL";
2215 // IN clause contains at least one valid element
2216 if ( $includeNull ) {
2217 // Group subconditions to ensure correct precedence
2220 if ( count( $value ) == 1 ) {
2221 // Special-case single values, as IN isn't terribly efficient
2222 // Don't necessarily assume the single key is 0; we don't
2223 // enforce linear numeric ordering on other arrays here.
2224 $value = array_values( $value );
2225 $list .= $field . " = " . $this->addQuotes( $value[0] );
2227 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2229 // if null present in array, append IS NULL
2230 if ( $includeNull ) {
2231 $list .= " OR $field IS NULL)";
2234 } elseif ( $value === null ) {
2235 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2236 $list .= "$field IS ";
2237 } elseif ( $mode == LIST_SET
) {
2238 $list .= "$field = ";
2242 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2243 $list .= "$field = ";
2245 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2253 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2254 * The keys on each level may be either integers or strings.
2256 * @param array $data Organized as 2-d
2257 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2258 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2259 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2260 * @return string|bool SQL fragment, or false if no items in array
2262 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2265 foreach ( $data as $base => $sub ) {
2266 if ( count( $sub ) ) {
2267 $conds[] = $this->makeList(
2268 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2274 return $this->makeList( $conds, LIST_OR
);
2276 // Nothing to search for...
2282 * Return aggregated value alias
2284 * @param array $valuedata
2285 * @param string $valuename
2289 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2294 * @param string $field
2297 public function bitNot( $field ) {
2302 * @param string $fieldLeft
2303 * @param string $fieldRight
2306 public function bitAnd( $fieldLeft, $fieldRight ) {
2307 return "($fieldLeft & $fieldRight)";
2311 * @param string $fieldLeft
2312 * @param string $fieldRight
2315 public function bitOr( $fieldLeft, $fieldRight ) {
2316 return "($fieldLeft | $fieldRight)";
2320 * Build a concatenation list to feed into a SQL query
2321 * @param array $stringList List of raw SQL expressions; caller is
2322 * responsible for any quoting
2325 public function buildConcat( $stringList ) {
2326 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2330 * Build a GROUP_CONCAT or equivalent statement for a query.
2332 * This is useful for combining a field for several rows into a single string.
2333 * NULL values will not appear in the output, duplicated values will appear,
2334 * and the resulting delimiter-separated values have no defined sort order.
2335 * Code using the results may need to use the PHP unique() or sort() methods.
2337 * @param string $delim Glue to bind the results together
2338 * @param string|array $table Table name
2339 * @param string $field Field name
2340 * @param string|array $conds Conditions
2341 * @param string|array $join_conds Join conditions
2342 * @return string SQL text
2345 public function buildGroupConcatField(
2346 $delim, $table, $field, $conds = '', $join_conds = array()
2348 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2350 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2354 * Change the current database
2356 * @todo Explain what exactly will fail if this is not overridden.
2360 * @return bool Success or failure
2362 public function selectDB( $db ) {
2363 # Stub. Shouldn't cause serious problems if it's not overridden, but
2364 # if your database engine supports a concept similar to MySQL's
2365 # databases you may as well.
2366 $this->mDBname
= $db;
2372 * Get the current DB name
2375 public function getDBname() {
2376 return $this->mDBname
;
2380 * Get the server hostname or IP address
2383 public function getServer() {
2384 return $this->mServer
;
2388 * Format a table name ready for use in constructing an SQL query
2390 * This does two important things: it quotes the table names to clean them up,
2391 * and it adds a table prefix if only given a table name with no quotes.
2393 * All functions of this object which require a table name call this function
2394 * themselves. Pass the canonical name to such functions. This is only needed
2395 * when calling query() directly.
2397 * @param string $name Database table name
2398 * @param string $format One of:
2399 * quoted - Automatically pass the table name through addIdentifierQuotes()
2400 * so that it can be used in a query.
2401 * raw - Do not add identifier quotes to the table name
2402 * @return string Full database name
2404 public function tableName( $name, $format = 'quoted' ) {
2405 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2406 # Skip the entire process when we have a string quoted on both ends.
2407 # Note that we check the end so that we will still quote any use of
2408 # use of `database`.table. But won't break things if someone wants
2409 # to query a database table with a dot in the name.
2410 if ( $this->isQuotedIdentifier( $name ) ) {
2414 # Lets test for any bits of text that should never show up in a table
2415 # name. Basically anything like JOIN or ON which are actually part of
2416 # SQL queries, but may end up inside of the table value to combine
2417 # sql. Such as how the API is doing.
2418 # Note that we use a whitespace test rather than a \b test to avoid
2419 # any remote case where a word like on may be inside of a table name
2420 # surrounded by symbols which may be considered word breaks.
2421 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2425 # Split database and table into proper variables.
2426 # We reverse the explode so that database.table and table both output
2427 # the correct table.
2428 $dbDetails = explode( '.', $name, 3 );
2429 if ( count( $dbDetails ) == 3 ) {
2430 list( $database, $schema, $table ) = $dbDetails;
2431 # We don't want any prefix added in this case
2433 } elseif ( count( $dbDetails ) == 2 ) {
2434 list( $database, $table ) = $dbDetails;
2435 # We don't want any prefix added in this case
2436 # In dbs that support it, $database may actually be the schema
2437 # but that doesn't affect any of the functionality here
2441 list( $table ) = $dbDetails;
2442 if ( $wgSharedDB !== null # We have a shared database
2443 && $this->mForeign
== false # We're not working on a foreign database
2444 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2445 && in_array( $table, $wgSharedTables ) # A shared table is selected
2447 $database = $wgSharedDB;
2448 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2449 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2452 $schema = $this->mSchema
; # Default schema
2453 $prefix = $this->mTablePrefix
; # Default prefix
2457 # Quote $table and apply the prefix if not quoted.
2458 # $tableName might be empty if this is called from Database::replaceVars()
2459 $tableName = "{$prefix}{$table}";
2460 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2461 $tableName = $this->addIdentifierQuotes( $tableName );
2464 # Quote $schema and merge it with the table name if needed
2465 if ( $schema !== null ) {
2466 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2467 $schema = $this->addIdentifierQuotes( $schema );
2469 $tableName = $schema . '.' . $tableName;
2472 # Quote $database and merge it with the table name if needed
2473 if ( $database !== null ) {
2474 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2475 $database = $this->addIdentifierQuotes( $database );
2477 $tableName = $database . '.' . $tableName;
2484 * Fetch a number of table names into an array
2485 * This is handy when you need to construct SQL for joins
2488 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2489 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2490 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2494 public function tableNames() {
2495 $inArray = func_get_args();
2498 foreach ( $inArray as $name ) {
2499 $retVal[$name] = $this->tableName( $name );
2506 * Fetch a number of table names into an zero-indexed numerical array
2507 * This is handy when you need to construct SQL for joins
2510 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2511 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2512 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2516 public function tableNamesN() {
2517 $inArray = func_get_args();
2520 foreach ( $inArray as $name ) {
2521 $retVal[] = $this->tableName( $name );
2528 * Get an aliased table name
2529 * e.g. tableName AS newTableName
2531 * @param string $name Table name, see tableName()
2532 * @param string|bool $alias Alias (optional)
2533 * @return string SQL name for aliased table. Will not alias a table to its own name
2535 public function tableNameWithAlias( $name, $alias = false ) {
2536 if ( !$alias ||
$alias == $name ) {
2537 return $this->tableName( $name );
2539 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2544 * Gets an array of aliased table names
2546 * @param array $tables Array( [alias] => table )
2547 * @return string[] See tableNameWithAlias()
2549 public function tableNamesWithAlias( $tables ) {
2551 foreach ( $tables as $alias => $table ) {
2552 if ( is_numeric( $alias ) ) {
2555 $retval[] = $this->tableNameWithAlias( $table, $alias );
2562 * Get an aliased field name
2563 * e.g. fieldName AS newFieldName
2565 * @param string $name Field name
2566 * @param string|bool $alias Alias (optional)
2567 * @return string SQL name for aliased field. Will not alias a field to its own name
2569 public function fieldNameWithAlias( $name, $alias = false ) {
2570 if ( !$alias ||
(string)$alias === (string)$name ) {
2573 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2578 * Gets an array of aliased field names
2580 * @param array $fields Array( [alias] => field )
2581 * @return string[] See fieldNameWithAlias()
2583 public function fieldNamesWithAlias( $fields ) {
2585 foreach ( $fields as $alias => $field ) {
2586 if ( is_numeric( $alias ) ) {
2589 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2596 * Get the aliased table name clause for a FROM clause
2597 * which might have a JOIN and/or USE INDEX clause
2599 * @param array $tables ( [alias] => table )
2600 * @param array $use_index Same as for select()
2601 * @param array $join_conds Same as for select()
2604 protected function tableNamesWithUseIndexOrJOIN(
2605 $tables, $use_index = array(), $join_conds = array()
2609 $use_index = (array)$use_index;
2610 $join_conds = (array)$join_conds;
2612 foreach ( $tables as $alias => $table ) {
2613 if ( !is_string( $alias ) ) {
2614 // No alias? Set it equal to the table name
2617 // Is there a JOIN clause for this table?
2618 if ( isset( $join_conds[$alias] ) ) {
2619 list( $joinType, $conds ) = $join_conds[$alias];
2620 $tableClause = $joinType;
2621 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2622 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2623 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2625 $tableClause .= ' ' . $use;
2628 $on = $this->makeList( (array)$conds, LIST_AND
);
2630 $tableClause .= ' ON (' . $on . ')';
2633 $retJOIN[] = $tableClause;
2634 } elseif ( isset( $use_index[$alias] ) ) {
2635 // Is there an INDEX clause for this table?
2636 $tableClause = $this->tableNameWithAlias( $table, $alias );
2637 $tableClause .= ' ' . $this->useIndexClause(
2638 implode( ',', (array)$use_index[$alias] )
2641 $ret[] = $tableClause;
2643 $tableClause = $this->tableNameWithAlias( $table, $alias );
2645 $ret[] = $tableClause;
2649 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2650 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2651 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2653 // Compile our final table clause
2654 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2658 * Get the name of an index in a given table.
2660 * @protected Don't use outside of DatabaseBase and childs
2661 * @param string $index
2664 public function indexName( $index ) {
2665 // @FIXME: Make this protected once we move away from PHP 5.3
2666 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2668 // Backwards-compatibility hack
2670 'ar_usertext_timestamp' => 'usertext_timestamp',
2671 'un_user_id' => 'user_id',
2672 'un_user_ip' => 'user_ip',
2675 if ( isset( $renamed[$index] ) ) {
2676 return $renamed[$index];
2683 * Adds quotes and backslashes.
2685 * @param string|Blob $s
2688 public function addQuotes( $s ) {
2689 if ( $s instanceof Blob
) {
2692 if ( $s === null ) {
2695 # This will also quote numeric values. This should be harmless,
2696 # and protects against weird problems that occur when they really
2697 # _are_ strings such as article titles and string->number->string
2698 # conversion is not 1:1.
2699 return "'" . $this->strencode( $s ) . "'";
2704 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2705 * MySQL uses `backticks` while basically everything else uses double quotes.
2706 * Since MySQL is the odd one out here the double quotes are our generic
2707 * and we implement backticks in DatabaseMysql.
2712 public function addIdentifierQuotes( $s ) {
2713 return '"' . str_replace( '"', '""', $s ) . '"';
2717 * Returns if the given identifier looks quoted or not according to
2718 * the database convention for quoting identifiers .
2720 * @param string $name
2723 public function isQuotedIdentifier( $name ) {
2724 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2731 protected function escapeLikeInternal( $s ) {
2732 return addcslashes( $s, '\%_' );
2736 * LIKE statement wrapper, receives a variable-length argument list with
2737 * parts of pattern to match containing either string literals that will be
2738 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2739 * the function could be provided with an array of aforementioned
2742 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2743 * a LIKE clause that searches for subpages of 'My page title'.
2745 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2746 * $query .= $dbr->buildLike( $pattern );
2749 * @return string Fully built LIKE statement
2751 public function buildLike() {
2752 $params = func_get_args();
2754 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2755 $params = $params[0];
2760 foreach ( $params as $value ) {
2761 if ( $value instanceof LikeMatch
) {
2762 $s .= $value->toString();
2764 $s .= $this->escapeLikeInternal( $value );
2768 return " LIKE {$this->addQuotes( $s )} ";
2772 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2776 public function anyChar() {
2777 return new LikeMatch( '_' );
2781 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2785 public function anyString() {
2786 return new LikeMatch( '%' );
2790 * Returns an appropriately quoted sequence value for inserting a new row.
2791 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2792 * subclass will return an integer, and save the value for insertId()
2794 * Any implementation of this function should *not* involve reusing
2795 * sequence numbers created for rolled-back transactions.
2796 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2797 * @param string $seqName
2800 public function nextSequenceValue( $seqName ) {
2805 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2806 * is only needed because a) MySQL must be as efficient as possible due to
2807 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2808 * which index to pick. Anyway, other databases might have different
2809 * indexes on a given table. So don't bother overriding this unless you're
2811 * @param string $index
2814 public function useIndexClause( $index ) {
2819 * REPLACE query wrapper.
2821 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2822 * except that when there is a duplicate key error, the old row is deleted
2823 * and the new row is inserted in its place.
2825 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2826 * perform the delete, we need to know what the unique indexes are so that
2827 * we know how to find the conflicting rows.
2829 * It may be more efficient to leave off unique indexes which are unlikely
2830 * to collide. However if you do this, you run the risk of encountering
2831 * errors which wouldn't have occurred in MySQL.
2833 * @param string $table The table to replace the row(s) in.
2834 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2835 * a field name or an array of field names
2836 * @param array $rows Can be either a single row to insert, or multiple rows,
2837 * in the same format as for DatabaseBase::insert()
2838 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2840 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2841 $quotedTable = $this->tableName( $table );
2843 if ( count( $rows ) == 0 ) {
2848 if ( !is_array( reset( $rows ) ) ) {
2849 $rows = array( $rows );
2852 foreach ( $rows as $row ) {
2853 # Delete rows which collide
2854 if ( $uniqueIndexes ) {
2855 $sql = "DELETE FROM $quotedTable WHERE ";
2857 foreach ( $uniqueIndexes as $index ) {
2864 if ( is_array( $index ) ) {
2866 foreach ( $index as $col ) {
2872 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2875 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2879 $this->query( $sql, $fname );
2882 # Now insert the row
2883 $this->insert( $table, $row, $fname );
2888 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2891 * @param string $table Table name
2892 * @param array|string $rows Row(s) to insert
2893 * @param string $fname Caller function name
2895 * @return ResultWrapper
2897 protected function nativeReplace( $table, $rows, $fname ) {
2898 $table = $this->tableName( $table );
2901 if ( !is_array( reset( $rows ) ) ) {
2902 $rows = array( $rows );
2905 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2908 foreach ( $rows as $row ) {
2915 $sql .= '(' . $this->makeList( $row ) . ')';
2918 return $this->query( $sql, $fname );
2922 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2924 * This updates any conflicting rows (according to the unique indexes) using
2925 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2927 * $rows may be either:
2928 * - A single associative array. The array keys are the field names, and
2929 * the values are the values to insert. The values are treated as data
2930 * and will be quoted appropriately. If NULL is inserted, this will be
2931 * converted to a database NULL.
2932 * - An array with numeric keys, holding a list of associative arrays.
2933 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2934 * each subarray must be identical to each other, and in the same order.
2936 * It may be more efficient to leave off unique indexes which are unlikely
2937 * to collide. However if you do this, you run the risk of encountering
2938 * errors which wouldn't have occurred in MySQL.
2940 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2945 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2946 * @param array $rows A single row or list of rows to insert
2947 * @param array $uniqueIndexes List of single field names or field name tuples
2948 * @param array $set An array of values to SET. For each array element, the
2949 * key gives the field name, and the value gives the data to set that
2950 * field to. The data will be quoted by DatabaseBase::addQuotes().
2951 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2955 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2958 if ( !count( $rows ) ) {
2959 return true; // nothing to do
2962 if ( !is_array( reset( $rows ) ) ) {
2963 $rows = array( $rows );
2966 if ( count( $uniqueIndexes ) ) {
2967 $clauses = array(); // list WHERE clauses that each identify a single row
2968 foreach ( $rows as $row ) {
2969 foreach ( $uniqueIndexes as $index ) {
2970 $index = is_array( $index ) ?
$index : array( $index ); // columns
2971 $rowKey = array(); // unique key to this row
2972 foreach ( $index as $column ) {
2973 $rowKey[$column] = $row[$column];
2975 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2978 $where = array( $this->makeList( $clauses, LIST_OR
) );
2983 $useTrx = !$this->mTrxLevel
;
2985 $this->begin( $fname );
2988 # Update any existing conflicting row(s)
2989 if ( $where !== false ) {
2990 $ok = $this->update( $table, $set, $where, $fname );
2994 # Now insert any non-conflicting row(s)
2995 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2996 } catch ( Exception
$e ) {
2998 $this->rollback( $fname );
3003 $this->commit( $fname );
3010 * DELETE where the condition is a join.
3012 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3013 * we use sub-selects
3015 * For safety, an empty $conds will not delete everything. If you want to
3016 * delete all rows where the join condition matches, set $conds='*'.
3018 * DO NOT put the join condition in $conds.
3020 * @param string $delTable The table to delete from.
3021 * @param string $joinTable The other table.
3022 * @param string $delVar The variable to join on, in the first table.
3023 * @param string $joinVar The variable to join on, in the second table.
3024 * @param array $conds Condition array of field names mapped to variables,
3025 * ANDed together in the WHERE clause
3026 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3027 * @throws DBUnexpectedError
3029 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3033 throw new DBUnexpectedError( $this,
3034 'DatabaseBase::deleteJoin() called with empty $conds' );
3037 $delTable = $this->tableName( $delTable );
3038 $joinTable = $this->tableName( $joinTable );
3039 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3040 if ( $conds != '*' ) {
3041 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
3045 $this->query( $sql, $fname );
3049 * Returns the size of a text field, or -1 for "unlimited"
3051 * @param string $table
3052 * @param string $field
3055 public function textFieldSize( $table, $field ) {
3056 $table = $this->tableName( $table );
3057 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3058 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3059 $row = $this->fetchObject( $res );
3063 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3073 * A string to insert into queries to show that they're low-priority, like
3074 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3075 * string and nothing bad should happen.
3077 * @return string Returns the text of the low priority option if it is
3078 * supported, or a blank string otherwise
3080 public function lowPriorityOption() {
3085 * DELETE query wrapper.
3087 * @param array $table Table name
3088 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3089 * for the format. Use $conds == "*" to delete all rows
3090 * @param string $fname Name of the calling function
3091 * @throws DBUnexpectedError
3092 * @return bool|ResultWrapper
3094 public function delete( $table, $conds, $fname = __METHOD__
) {
3096 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3099 $table = $this->tableName( $table );
3100 $sql = "DELETE FROM $table";
3102 if ( $conds != '*' ) {
3103 if ( is_array( $conds ) ) {
3104 $conds = $this->makeList( $conds, LIST_AND
);
3106 $sql .= ' WHERE ' . $conds;
3109 return $this->query( $sql, $fname );
3113 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3114 * into another table.
3116 * @param string $destTable The table name to insert into
3117 * @param string|array $srcTable May be either a table name, or an array of table names
3118 * to include in a join.
3120 * @param array $varMap Must be an associative array of the form
3121 * array( 'dest1' => 'source1', ...). Source items may be literals
3122 * rather than field names, but strings should be quoted with
3123 * DatabaseBase::addQuotes()
3125 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3126 * the details of the format of condition arrays. May be "*" to copy the
3129 * @param string $fname The function name of the caller, from __METHOD__
3131 * @param array $insertOptions Options for the INSERT part of the query, see
3132 * DatabaseBase::insert() for details.
3133 * @param array $selectOptions Options for the SELECT part of the query, see
3134 * DatabaseBase::select() for details.
3136 * @return ResultWrapper
3138 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3139 $fname = __METHOD__
,
3140 $insertOptions = array(), $selectOptions = array()
3142 $destTable = $this->tableName( $destTable );
3144 if ( !is_array( $insertOptions ) ) {
3145 $insertOptions = array( $insertOptions );
3148 $insertOptions = $this->makeInsertOptions( $insertOptions );
3150 if ( !is_array( $selectOptions ) ) {
3151 $selectOptions = array( $selectOptions );
3154 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3156 if ( is_array( $srcTable ) ) {
3157 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3159 $srcTable = $this->tableName( $srcTable );
3162 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3163 " SELECT $startOpts " . implode( ',', $varMap ) .
3164 " FROM $srcTable $useIndex ";
3166 if ( $conds != '*' ) {
3167 if ( is_array( $conds ) ) {
3168 $conds = $this->makeList( $conds, LIST_AND
);
3170 $sql .= " WHERE $conds";
3173 $sql .= " $tailOpts";
3175 return $this->query( $sql, $fname );
3179 * Construct a LIMIT query with optional offset. This is used for query
3180 * pages. The SQL should be adjusted so that only the first $limit rows
3181 * are returned. If $offset is provided as well, then the first $offset
3182 * rows should be discarded, and the next $limit rows should be returned.
3183 * If the result of the query is not ordered, then the rows to be returned
3184 * are theoretically arbitrary.
3186 * $sql is expected to be a SELECT, if that makes a difference.
3188 * The version provided by default works in MySQL and SQLite. It will very
3189 * likely need to be overridden for most other DBMSes.
3191 * @param string $sql SQL query we will append the limit too
3192 * @param int $limit The SQL limit
3193 * @param int|bool $offset The SQL offset (default false)
3194 * @throws DBUnexpectedError
3197 public function limitResult( $sql, $limit, $offset = false ) {
3198 if ( !is_numeric( $limit ) ) {
3199 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3202 return "$sql LIMIT "
3203 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3208 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3209 * within the UNION construct.
3212 public function unionSupportsOrderAndLimit() {
3213 return true; // True for almost every DB supported
3217 * Construct a UNION query
3218 * This is used for providing overload point for other DB abstractions
3219 * not compatible with the MySQL syntax.
3220 * @param array $sqls SQL statements to combine
3221 * @param bool $all Use UNION ALL
3222 * @return string SQL fragment
3224 public function unionQueries( $sqls, $all ) {
3225 $glue = $all ?
') UNION ALL (' : ') UNION (';
3227 return '(' . implode( $glue, $sqls ) . ')';
3231 * Returns an SQL expression for a simple conditional. This doesn't need
3232 * to be overridden unless CASE isn't supported in your DBMS.
3234 * @param string|array $cond SQL expression which will result in a boolean value
3235 * @param string $trueVal SQL expression to return if true
3236 * @param string $falseVal SQL expression to return if false
3237 * @return string SQL fragment
3239 public function conditional( $cond, $trueVal, $falseVal ) {
3240 if ( is_array( $cond ) ) {
3241 $cond = $this->makeList( $cond, LIST_AND
);
3244 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3248 * Returns a comand for str_replace function in SQL query.
3249 * Uses REPLACE() in MySQL
3251 * @param string $orig Column to modify
3252 * @param string $old Column to seek
3253 * @param string $new Column to replace with
3257 public function strreplace( $orig, $old, $new ) {
3258 return "REPLACE({$orig}, {$old}, {$new})";
3262 * Determines how long the server has been up
3267 public function getServerUptime() {
3272 * Determines if the last failure was due to a deadlock
3277 public function wasDeadlock() {
3282 * Determines if the last failure was due to a lock timeout
3287 public function wasLockTimeout() {
3292 * Determines if the last query error was something that should be dealt
3293 * with by pinging the connection and reissuing the query.
3298 public function wasErrorReissuable() {
3303 * Determines if the last failure was due to the database being read-only.
3308 public function wasReadOnlyError() {
3313 * Perform a deadlock-prone transaction.
3315 * This function invokes a callback function to perform a set of write
3316 * queries. If a deadlock occurs during the processing, the transaction
3317 * will be rolled back and the callback function will be called again.
3320 * $dbw->deadlockLoop( callback, ... );
3322 * Extra arguments are passed through to the specified callback function.
3324 * Returns whatever the callback function returned on its successful,
3325 * iteration, or false on error, for example if the retry limit was
3330 public function deadlockLoop() {
3331 $this->begin( __METHOD__
);
3332 $args = func_get_args();
3333 $function = array_shift( $args );
3334 $oldIgnore = $this->ignoreErrors( true );
3335 $tries = self
::DEADLOCK_TRIES
;
3337 if ( is_array( $function ) ) {
3338 $fname = $function[0];
3344 $retVal = call_user_func_array( $function, $args );
3345 $error = $this->lastError();
3346 $errno = $this->lastErrno();
3347 $sql = $this->lastQuery();
3350 if ( $this->wasDeadlock() ) {
3352 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3354 $this->reportQueryError( $error, $errno, $sql, $fname );
3357 } while ( $this->wasDeadlock() && --$tries > 0 );
3359 $this->ignoreErrors( $oldIgnore );
3361 if ( $tries <= 0 ) {
3362 $this->rollback( __METHOD__
);
3363 $this->reportQueryError( $error, $errno, $sql, $fname );
3367 $this->commit( __METHOD__
);
3374 * Wait for the slave to catch up to a given master position.
3376 * @param DBMasterPos $pos
3377 * @param int $timeout The maximum number of seconds to wait for
3379 * @return int Zero if the slave was past that position already,
3380 * greater than zero if we waited for some period of time, less than
3381 * zero if we timed out.
3383 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3384 # Real waits are implemented in the subclass.
3389 * Get the replication position of this slave
3391 * @return DBMasterPos|bool False if this is not a slave.
3393 public function getSlavePos() {
3399 * Get the position of this master
3401 * @return DBMasterPos|bool False if this is not a master
3403 public function getMasterPos() {
3409 * Run an anonymous function as soon as there is no transaction pending.
3410 * If there is a transaction and it is rolled back, then the callback is cancelled.
3411 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3412 * Callbacks must commit any transactions that they begin.
3414 * This is useful for updates to different systems or when separate transactions are needed.
3415 * For example, one might want to enqueue jobs into a system outside the database, but only
3416 * after the database is updated so that the jobs will see the data when they actually run.
3417 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3419 * @param callable $callback
3422 final public function onTransactionIdle( $callback ) {
3423 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3424 if ( !$this->mTrxLevel
) {
3425 $this->runOnTransactionIdleCallbacks();
3430 * Run an anonymous function before the current transaction commits or now if there is none.
3431 * If there is a transaction and it is rolled back, then the callback is cancelled.
3432 * Callbacks must not start nor commit any transactions.
3434 * This is useful for updates that easily cause deadlocks if locks are held too long
3435 * but where atomicity is strongly desired for these updates and some related updates.
3437 * @param callable $callback
3440 final public function onTransactionPreCommitOrIdle( $callback ) {
3441 if ( $this->mTrxLevel
) {
3442 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3444 $this->onTransactionIdle( $callback ); // this will trigger immediately
3449 * Actually any "on transaction idle" callbacks.
3453 protected function runOnTransactionIdleCallbacks() {
3454 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3456 $e = $ePrior = null; // last exception
3457 do { // callbacks may add callbacks :)
3458 $callbacks = $this->mTrxIdleCallbacks
;
3459 $this->mTrxIdleCallbacks
= array(); // recursion guard
3460 foreach ( $callbacks as $callback ) {
3462 list( $phpCallback ) = $callback;
3463 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3464 call_user_func( $phpCallback );
3465 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3466 } catch ( Exception
$e ) {
3468 MWExceptionHandler
::logException( $ePrior );
3473 } while ( count( $this->mTrxIdleCallbacks
) );
3475 if ( $e instanceof Exception
) {
3476 throw $e; // re-throw any last exception
3481 * Actually any "on transaction pre-commit" callbacks.
3485 protected function runOnTransactionPreCommitCallbacks() {
3486 $e = $ePrior = null; // last exception
3487 do { // callbacks may add callbacks :)
3488 $callbacks = $this->mTrxPreCommitCallbacks
;
3489 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3490 foreach ( $callbacks as $callback ) {
3492 list( $phpCallback ) = $callback;
3493 call_user_func( $phpCallback );
3494 } catch ( Exception
$e ) {
3496 MWExceptionHandler
::logException( $ePrior );
3501 } while ( count( $this->mTrxPreCommitCallbacks
) );
3503 if ( $e instanceof Exception
) {
3504 throw $e; // re-throw any last exception
3509 * Begin an atomic section of statements
3511 * If a transaction has been started already, just keep track of the given
3512 * section name to make sure the transaction is not committed pre-maturely.
3513 * This function can be used in layers (with sub-sections), so use a stack
3514 * to keep track of the different atomic sections. If there is no transaction,
3515 * start one implicitly.
3517 * The goal of this function is to create an atomic section of SQL queries
3518 * without having to start a new transaction if it already exists.
3520 * Atomic sections are more strict than transactions. With transactions,
3521 * attempting to begin a new transaction when one is already running results
3522 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3523 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3524 * and any database transactions cannot be began or committed until all atomic
3525 * levels are closed. There is no such thing as implicitly opening or closing
3526 * an atomic section.
3529 * @param string $fname
3532 final public function startAtomic( $fname = __METHOD__
) {
3533 if ( !$this->mTrxLevel
) {
3534 $this->begin( $fname );
3535 $this->mTrxAutomatic
= true;
3536 $this->mTrxAutomaticAtomic
= true;
3539 $this->mTrxAtomicLevels
->push( $fname );
3543 * Ends an atomic section of SQL statements
3545 * Ends the next section of atomic SQL statements and commits the transaction
3549 * @see DatabaseBase::startAtomic
3550 * @param string $fname
3553 final public function endAtomic( $fname = __METHOD__
) {
3554 if ( !$this->mTrxLevel
) {
3555 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3557 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3558 $this->mTrxAtomicLevels
->pop() !== $fname
3560 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3563 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3564 $this->commit( $fname, 'flush' );
3569 * Begin a transaction. If a transaction is already in progress,
3570 * that transaction will be committed before the new transaction is started.
3572 * Note that when the DBO_TRX flag is set (which is usually the case for web
3573 * requests, but not for maintenance scripts), any previous database query
3574 * will have started a transaction automatically.
3576 * Nesting of transactions is not supported. Attempts to nest transactions
3577 * will cause a warning, unless the current transaction was started
3578 * automatically because of the DBO_TRX flag.
3580 * @param string $fname
3583 final public function begin( $fname = __METHOD__
) {
3584 global $wgDebugDBTransactions;
3586 if ( $this->mTrxLevel
) { // implicit commit
3587 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3588 // If the current transaction was an automatic atomic one, then we definitely have
3589 // a problem. Same if there is any unclosed atomic level.
3590 throw new DBUnexpectedError( $this,
3591 "Attempted to start explicit transaction when atomic levels are still open."
3593 } elseif ( !$this->mTrxAutomatic
) {
3594 // We want to warn about inadvertently nested begin/commit pairs, but not about
3595 // auto-committing implicit transactions that were started by query() via DBO_TRX
3596 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3597 " performing implicit commit!";
3600 $this->getLogContext( array(
3601 'method' => __METHOD__
,
3606 // if the transaction was automatic and has done write operations,
3607 // log it if $wgDebugDBTransactions is enabled.
3608 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3609 wfDebug( "$fname: Automatic transaction with writes in progress" .
3610 " (from {$this->mTrxFname}), performing implicit commit!\n"
3615 $this->runOnTransactionPreCommitCallbacks();
3616 $this->doCommit( $fname );
3617 if ( $this->mTrxDoneWrites
) {
3618 $this->getTransactionProfiler()->transactionWritingOut(
3619 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3621 $this->runOnTransactionIdleCallbacks();
3624 # Avoid fatals if close() was called
3625 if ( !$this->isOpen() ) {
3626 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3629 $this->doBegin( $fname );
3630 $this->mTrxTimestamp
= microtime( true );
3631 $this->mTrxFname
= $fname;
3632 $this->mTrxDoneWrites
= false;
3633 $this->mTrxAutomatic
= false;
3634 $this->mTrxAutomaticAtomic
= false;
3635 $this->mTrxAtomicLevels
= new SplStack
;
3636 $this->mTrxIdleCallbacks
= array();
3637 $this->mTrxPreCommitCallbacks
= array();
3638 $this->mTrxShortId
= wfRandomString( 12 );
3642 * Issues the BEGIN command to the database server.
3644 * @see DatabaseBase::begin()
3645 * @param string $fname
3647 protected function doBegin( $fname ) {
3648 $this->query( 'BEGIN', $fname );
3649 $this->mTrxLevel
= 1;
3653 * Commits a transaction previously started using begin().
3654 * If no transaction is in progress, a warning is issued.
3656 * Nesting of transactions is not supported.
3658 * @param string $fname
3659 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3660 * explicitly committing implicit transactions, or calling commit when no
3661 * transaction is in progress. This will silently break any ongoing
3662 * explicit transaction. Only set the flush flag if you are sure that it
3663 * is safe to ignore these warnings in your context.
3664 * @throws DBUnexpectedError
3666 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3667 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3668 // There are still atomic sections open. This cannot be ignored
3669 throw new DBUnexpectedError(
3671 "Attempted to commit transaction while atomic sections are still open"
3675 if ( $flush === 'flush' ) {
3676 if ( !$this->mTrxLevel
) {
3677 return; // nothing to do
3678 } elseif ( !$this->mTrxAutomatic
) {
3679 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3682 if ( !$this->mTrxLevel
) {
3683 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3684 return; // nothing to do
3685 } elseif ( $this->mTrxAutomatic
) {
3686 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3690 # Avoid fatals if close() was called
3691 if ( !$this->isOpen() ) {
3692 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3695 $this->runOnTransactionPreCommitCallbacks();
3696 $this->doCommit( $fname );
3697 if ( $this->mTrxDoneWrites
) {
3698 $this->getTransactionProfiler()->transactionWritingOut(
3699 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3701 $this->runOnTransactionIdleCallbacks();
3705 * Issues the COMMIT command to the database server.
3707 * @see DatabaseBase::commit()
3708 * @param string $fname
3710 protected function doCommit( $fname ) {
3711 if ( $this->mTrxLevel
) {
3712 $this->query( 'COMMIT', $fname );
3713 $this->mTrxLevel
= 0;
3718 * Rollback a transaction previously started using begin().
3719 * If no transaction is in progress, a warning is issued.
3721 * No-op on non-transactional databases.
3723 * @param string $fname
3724 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3725 * calling rollback when no transaction is in progress. This will silently
3726 * break any ongoing explicit transaction. Only set the flush flag if you
3727 * are sure that it is safe to ignore these warnings in your context.
3728 * @throws DBUnexpectedError
3729 * @since 1.23 Added $flush parameter
3731 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3732 if ( $flush !== 'flush' ) {
3733 if ( !$this->mTrxLevel
) {
3734 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3735 return; // nothing to do
3736 } elseif ( $this->mTrxAutomatic
) {
3737 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3740 if ( !$this->mTrxLevel
) {
3741 return; // nothing to do
3742 } elseif ( !$this->mTrxAutomatic
) {
3743 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3747 # Avoid fatals if close() was called
3748 if ( !$this->isOpen() ) {
3749 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3752 $this->doRollback( $fname );
3753 $this->mTrxIdleCallbacks
= array(); // cancel
3754 $this->mTrxPreCommitCallbacks
= array(); // cancel
3755 $this->mTrxAtomicLevels
= new SplStack
;
3756 if ( $this->mTrxDoneWrites
) {
3757 $this->getTransactionProfiler()->transactionWritingOut(
3758 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3763 * Issues the ROLLBACK command to the database server.
3765 * @see DatabaseBase::rollback()
3766 * @param string $fname
3768 protected function doRollback( $fname ) {
3769 if ( $this->mTrxLevel
) {
3770 $this->query( 'ROLLBACK', $fname, true );
3771 $this->mTrxLevel
= 0;
3776 * Creates a new table with structure copied from existing table
3777 * Note that unlike most database abstraction functions, this function does not
3778 * automatically append database prefix, because it works at a lower
3779 * abstraction level.
3780 * The table names passed to this function shall not be quoted (this
3781 * function calls addIdentifierQuotes when needed).
3783 * @param string $oldName Name of table whose structure should be copied
3784 * @param string $newName Name of table to be created
3785 * @param bool $temporary Whether the new table should be temporary
3786 * @param string $fname Calling function name
3787 * @throws MWException
3788 * @return bool True if operation was successful
3790 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3793 throw new MWException(
3794 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3798 * List all tables on the database
3800 * @param string $prefix Only show tables with this prefix, e.g. mw_
3801 * @param string $fname Calling function name
3802 * @throws MWException
3804 function listTables( $prefix = null, $fname = __METHOD__
) {
3805 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3809 * Reset the views process cache set by listViews()
3812 final public function clearViewsCache() {
3813 $this->allViews
= null;
3817 * Lists all the VIEWs in the database
3819 * For caching purposes the list of all views should be stored in
3820 * $this->allViews. The process cache can be cleared with clearViewsCache()
3822 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3823 * @param string $fname Name of calling function
3824 * @throws MWException
3827 public function listViews( $prefix = null, $fname = __METHOD__
) {
3828 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3832 * Differentiates between a TABLE and a VIEW
3834 * @param string $name Name of the database-structure to test.
3835 * @throws MWException
3838 public function isView( $name ) {
3839 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3843 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3844 * to the format used for inserting into timestamp fields in this DBMS.
3846 * The result is unquoted, and needs to be passed through addQuotes()
3847 * before it can be included in raw SQL.
3849 * @param string|int $ts
3853 public function timestamp( $ts = 0 ) {
3854 return wfTimestamp( TS_MW
, $ts );
3858 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3859 * to the format used for inserting into timestamp fields in this DBMS. If
3860 * NULL is input, it is passed through, allowing NULL values to be inserted
3861 * into timestamp fields.
3863 * The result is unquoted, and needs to be passed through addQuotes()
3864 * before it can be included in raw SQL.
3866 * @param string|int $ts
3870 public function timestampOrNull( $ts = null ) {
3871 if ( is_null( $ts ) ) {
3874 return $this->timestamp( $ts );
3879 * Take the result from a query, and wrap it in a ResultWrapper if
3880 * necessary. Boolean values are passed through as is, to indicate success
3881 * of write queries or failure.
3883 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3884 * resource, and it was necessary to call this function to convert it to
3885 * a wrapper. Nowadays, raw database objects are never exposed to external
3886 * callers, so this is unnecessary in external code. For compatibility with
3887 * old code, ResultWrapper objects are passed through unaltered.
3889 * @param bool|ResultWrapper|resource $result
3890 * @return bool|ResultWrapper
3892 public function resultObject( $result ) {
3893 if ( empty( $result ) ) {
3895 } elseif ( $result instanceof ResultWrapper
) {
3897 } elseif ( $result === true ) {
3898 // Successful write query
3901 return new ResultWrapper( $this, $result );
3906 * Ping the server and try to reconnect if it there is no connection
3908 * @return bool Success or failure
3910 public function ping() {
3911 # Stub. Not essential to override.
3916 * Get slave lag. Currently supported only by MySQL.
3918 * Note that this function will generate a fatal error on many
3919 * installations. Most callers should use LoadBalancer::safeGetLag()
3922 * @return int Database replication lag in seconds
3924 public function getLag() {
3929 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3933 function maxListLen() {
3938 * Some DBMSs have a special format for inserting into blob fields, they
3939 * don't allow simple quoted strings to be inserted. To insert into such
3940 * a field, pass the data through this function before passing it to
3941 * DatabaseBase::insert().
3946 public function encodeBlob( $b ) {
3951 * Some DBMSs return a special placeholder object representing blob fields
3952 * in result objects. Pass the object through this function to return the
3955 * @param string|Blob $b
3958 public function decodeBlob( $b ) {
3959 if ( $b instanceof Blob
) {
3966 * Override database's default behavior. $options include:
3967 * 'connTimeout' : Set the connection timeout value in seconds.
3968 * May be useful for very long batch queries such as
3969 * full-wiki dumps, where a single query reads out over
3972 * @param array $options
3975 public function setSessionOptions( array $options ) {
3979 * Read and execute SQL commands from a file.
3981 * Returns true on success, error string or exception on failure (depending
3982 * on object's error ignore settings).
3984 * @param string $filename File name to open
3985 * @param bool|callable $lineCallback Optional function called before reading each line
3986 * @param bool|callable $resultCallback Optional function called for each MySQL result
3987 * @param bool|string $fname Calling function name or false if name should be
3988 * generated dynamically using $filename
3989 * @param bool|callable $inputCallback Optional function called for each
3990 * complete line sent
3991 * @throws Exception|MWException
3992 * @return bool|string
3994 public function sourceFile(
3995 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3997 wfSuppressWarnings();
3998 $fp = fopen( $filename, 'r' );
3999 wfRestoreWarnings();
4001 if ( false === $fp ) {
4002 throw new MWException( "Could not open \"{$filename}\".\n" );
4006 $fname = __METHOD__
. "( $filename )";
4010 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4011 } catch ( Exception
$e ) {
4022 * Get the full path of a patch file. Originally based on archive()
4023 * from updaters.inc. Keep in mind this always returns a patch, as
4024 * it fails back to MySQL if no DB-specific patch can be found
4026 * @param string $patch The name of the patch, like patch-something.sql
4027 * @return string Full path to patch file
4029 public function patchPath( $patch ) {
4032 $dbType = $this->getType();
4033 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4034 return "$IP/maintenance/$dbType/archives/$patch";
4036 return "$IP/maintenance/archives/$patch";
4041 * Set variables to be used in sourceFile/sourceStream, in preference to the
4042 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4043 * all. If it's set to false, $GLOBALS will be used.
4045 * @param bool|array $vars Mapping variable name to value.
4047 public function setSchemaVars( $vars ) {
4048 $this->mSchemaVars
= $vars;
4052 * Read and execute commands from an open file handle.
4054 * Returns true on success, error string or exception on failure (depending
4055 * on object's error ignore settings).
4057 * @param resource $fp File handle
4058 * @param bool|callable $lineCallback Optional function called before reading each query
4059 * @param bool|callable $resultCallback Optional function called for each MySQL result
4060 * @param string $fname Calling function name
4061 * @param bool|callable $inputCallback Optional function called for each complete query sent
4062 * @return bool|string
4064 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4065 $fname = __METHOD__
, $inputCallback = false
4069 while ( !feof( $fp ) ) {
4070 if ( $lineCallback ) {
4071 call_user_func( $lineCallback );
4074 $line = trim( fgets( $fp ) );
4076 if ( $line == '' ) {
4080 if ( '-' == $line[0] && '-' == $line[1] ) {
4088 $done = $this->streamStatementEnd( $cmd, $line );
4092 if ( $done ||
feof( $fp ) ) {
4093 $cmd = $this->replaceVars( $cmd );
4095 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4096 $res = $this->query( $cmd, $fname );
4098 if ( $resultCallback ) {
4099 call_user_func( $resultCallback, $res, $this );
4102 if ( false === $res ) {
4103 $err = $this->lastError();
4105 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4116 * Called by sourceStream() to check if we've reached a statement end
4118 * @param string $sql SQL assembled so far
4119 * @param string $newLine New line about to be added to $sql
4120 * @return bool Whether $newLine contains end of the statement
4122 public function streamStatementEnd( &$sql, &$newLine ) {
4123 if ( $this->delimiter
) {
4125 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4126 if ( $newLine != $prev ) {
4135 * Database independent variable replacement. Replaces a set of variables
4136 * in an SQL statement with their contents as given by $this->getSchemaVars().
4138 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4140 * - '{$var}' should be used for text and is passed through the database's
4142 * - `{$var}` should be used for identifiers (e.g. table and database names).
4143 * It is passed through the database's addIdentifierQuotes method which
4144 * can be overridden if the database uses something other than backticks.
4145 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4146 * database's tableName method.
4147 * - / *i* / passes the name that follows through the database's indexName method.
4148 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4149 * its use should be avoided. In 1.24 and older, string encoding was applied.
4151 * @param string $ins SQL statement to replace variables in
4152 * @return string The new SQL statement with variables replaced
4154 protected function replaceVars( $ins ) {
4156 $vars = $this->getSchemaVars();
4157 return preg_replace_callback(
4159 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4160 \'\{\$ (\w+) }\' | # 3. addQuotes
4161 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4162 /\*\$ (\w+) \*/ # 5. leave unencoded
4164 function ( $m ) use ( $that, $vars ) {
4165 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4166 // check for both nonexistent keys *and* the empty string.
4167 if ( isset( $m[1] ) && $m[1] !== '' ) {
4168 if ( $m[1] === 'i' ) {
4169 return $that->indexName( $m[2] );
4171 return $that->tableName( $m[2] );
4173 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4174 return $that->addQuotes( $vars[$m[3]] );
4175 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4176 return $that->addIdentifierQuotes( $vars[$m[4]] );
4177 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4178 return $vars[$m[5]];
4188 * Get schema variables. If none have been set via setSchemaVars(), then
4189 * use some defaults from the current object.
4193 protected function getSchemaVars() {
4194 if ( $this->mSchemaVars
) {
4195 return $this->mSchemaVars
;
4197 return $this->getDefaultSchemaVars();
4202 * Get schema variables to use if none have been set via setSchemaVars().
4204 * Override this in derived classes to provide variables for tables.sql
4205 * and SQL patch files.
4209 protected function getDefaultSchemaVars() {
4214 * Check to see if a named lock is available. This is non-blocking.
4216 * @param string $lockName Name of lock to poll
4217 * @param string $method Name of method calling us
4221 public function lockIsFree( $lockName, $method ) {
4226 * Acquire a named lock
4228 * Abstracted from Filestore::lock() so child classes can implement for
4231 * @param string $lockName Name of lock to aquire
4232 * @param string $method Name of method calling us
4233 * @param int $timeout
4236 public function lock( $lockName, $method, $timeout = 5 ) {
4243 * @param string $lockName Name of lock to release
4244 * @param string $method Name of method calling us
4246 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4247 * by this thread (in which case the lock is not released), and NULL if the named
4248 * lock did not exist
4250 public function unlock( $lockName, $method ) {
4255 * Lock specific tables
4257 * @param array $read Array of tables to lock for read access
4258 * @param array $write Array of tables to lock for write access
4259 * @param string $method Name of caller
4260 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4263 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4268 * Unlock specific tables
4270 * @param string $method The caller
4273 public function unlockTables( $method ) {
4279 * @param string $tableName
4280 * @param string $fName
4281 * @return bool|ResultWrapper
4284 public function dropTable( $tableName, $fName = __METHOD__
) {
4285 if ( !$this->tableExists( $tableName, $fName ) ) {
4288 $sql = "DROP TABLE " . $this->tableName( $tableName );
4289 if ( $this->cascadingDeletes() ) {
4293 return $this->query( $sql, $fName );
4297 * Get search engine class. All subclasses of this need to implement this
4298 * if they wish to use searching.
4302 public function getSearchEngine() {
4303 return 'SearchEngineDummy';
4307 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4308 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4309 * because "i" sorts after all numbers.
4313 public function getInfinity() {
4318 * Encode an expiry time into the DBMS dependent format
4320 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4323 public function encodeExpiry( $expiry ) {
4324 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4325 ?
$this->getInfinity()
4326 : $this->timestamp( $expiry );
4330 * Decode an expiry time into a DBMS independent format
4332 * @param string $expiry DB timestamp field value for expiry
4333 * @param int $format TS_* constant, defaults to TS_MW
4336 public function decodeExpiry( $expiry, $format = TS_MW
) {
4337 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4339 : wfTimestamp( $format, $expiry );
4343 * Allow or deny "big selects" for this session only. This is done by setting
4344 * the sql_big_selects session variable.
4346 * This is a MySQL-specific feature.
4348 * @param bool|string $value True for allow, false for deny, or "default" to
4349 * restore the initial value
4351 public function setBigSelects( $value = true ) {
4359 public function __toString() {
4360 return (string)$this->mConn
;
4364 * Run a few simple sanity checks
4366 public function __destruct() {
4367 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4368 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4370 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4372 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4373 $callers[] = $callbackInfo[1];
4375 $callers = implode( ', ', $callers );
4376 trigger_error( "DB transaction callbacks still pending (from $callers)." );