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 /** How many row changes in a write query trigger a log entry */
50 const LOG_WRITE_THRESHOLD
= 300;
52 protected $mLastQuery = '';
53 protected $mDoneWrites = false;
54 protected $mPHPError = false;
56 protected $mServer, $mUser, $mPassword, $mDBname;
58 /** @var resource Database connection */
59 protected $mConn = null;
60 protected $mOpened = false;
62 /** @var callable[] */
63 protected $mTrxIdleCallbacks = array();
64 /** @var callable[] */
65 protected $mTrxPreCommitCallbacks = array();
67 protected $mTablePrefix;
71 protected $mErrorCount = 0;
72 protected $mLBInfo = array();
73 protected $mDefaultBigSelects = null;
74 protected $mSchemaVars = false;
76 protected $preparedArgs;
78 protected $htmlErrors;
80 protected $delimiter = ';';
83 * Either 1 if a transaction is active or 0 otherwise.
84 * The other Trx fields may not be meaningfull if this is 0.
88 protected $mTrxLevel = 0;
91 * Either a short hexidecimal string if a transaction is active or ""
94 * @see DatabaseBase::mTrxLevel
96 protected $mTrxShortId = '';
99 * The UNIX time that the transaction started. Callers can assume that if
100 * snapshot isolation is used, then the data is *at least* up to date to that
101 * point (possibly more up-to-date since the first SELECT defines the snapshot).
104 * @see DatabaseBase::mTrxLevel
106 private $mTrxTimestamp = null;
109 * Remembers the function name given for starting the most recent transaction via begin().
110 * Used to provide additional context for error reporting.
113 * @see DatabaseBase::mTrxLevel
115 private $mTrxFname = null;
118 * Record if possible write queries were done in the last transaction started
121 * @see DatabaseBase::mTrxLevel
123 private $mTrxDoneWrites = false;
126 * Record if the current transaction was started implicitly due to DBO_TRX being set.
129 * @see DatabaseBase::mTrxLevel
131 private $mTrxAutomatic = false;
134 * Array of levels of atomicity within transactions
138 private $mTrxAtomicLevels;
141 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
145 private $mTrxAutomaticAtomic = false;
149 * @var resource File handle for upgrade
151 protected $fileHandle = null;
155 * @var string[] Process cache of VIEWs names in the database
157 protected $allViews = null;
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 * Returns true if this database supports (and uses) cascading deletes
356 public function cascadingDeletes() {
361 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
365 public function cleanupTriggers() {
370 * Returns true if this database is strict about what can be put into an IP field.
371 * Specifically, it uses a NULL value instead of an empty string.
375 public function strictIPs() {
380 * Returns true if this database uses timestamps rather than integers
384 public function realTimestamps() {
389 * Returns true if this database does an implicit sort when doing GROUP BY
393 public function implicitGroupby() {
398 * Returns true if this database does an implicit order by when the column has an index
399 * For example: SELECT page_title FROM page LIMIT 1
403 public function implicitOrderby() {
408 * Returns true if this database can do a native search on IP columns
409 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
413 public function searchableIPs() {
418 * Returns true if this database can use functional indexes
422 public function functionalIndexes() {
427 * Return the last query that went through DatabaseBase::query()
430 public function lastQuery() {
431 return $this->mLastQuery
;
435 * Returns true if the connection may have been used for write queries.
436 * Should return true if unsure.
440 public function doneWrites() {
441 return (bool)$this->mDoneWrites
;
445 * Returns the last time the connection may have been used for write queries.
446 * Should return a timestamp if unsure.
448 * @return int|float UNIX timestamp or false
451 public function lastDoneWrites() {
452 return $this->mDoneWrites ?
: false;
456 * Returns true if there is a transaction open with possible write
457 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
461 public function writesOrCallbacksPending() {
462 return $this->mTrxLevel
&& (
463 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
468 * Is a connection to the database open?
471 public function isOpen() {
472 return $this->mOpened
;
476 * Set a flag for this connection
478 * @param int $flag DBO_* constants from Defines.php:
479 * - DBO_DEBUG: output some debug info (same as debug())
480 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
481 * - DBO_TRX: automatically start transactions
482 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
483 * and removes it in command line mode
484 * - DBO_PERSISTENT: use persistant database connection
486 public function setFlag( $flag ) {
487 global $wgDebugDBTransactions;
488 $this->mFlags |
= $flag;
489 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
490 wfDebug( "Implicit transactions are now enabled.\n" );
495 * Clear a flag for this connection
497 * @param int $flag DBO_* constants from Defines.php:
498 * - DBO_DEBUG: output some debug info (same as debug())
499 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
500 * - DBO_TRX: automatically start transactions
501 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
502 * and removes it in command line mode
503 * - DBO_PERSISTENT: use persistant database connection
505 public function clearFlag( $flag ) {
506 global $wgDebugDBTransactions;
507 $this->mFlags
&= ~
$flag;
508 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
509 wfDebug( "Implicit transactions are now disabled.\n" );
514 * Returns a boolean whether the flag $flag is set for this connection
516 * @param int $flag DBO_* constants from Defines.php:
517 * - DBO_DEBUG: output some debug info (same as debug())
518 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
519 * - DBO_TRX: automatically start transactions
520 * - DBO_PERSISTENT: use persistant database connection
523 public function getFlag( $flag ) {
524 return !!( $this->mFlags
& $flag );
528 * General read-only accessor
530 * @param string $name
533 public function getProperty( $name ) {
540 public function getWikiID() {
541 if ( $this->mTablePrefix
) {
542 return "{$this->mDBname}-{$this->mTablePrefix}";
544 return $this->mDBname
;
549 * Return a path to the DBMS-specific SQL file if it exists,
550 * otherwise default SQL file
552 * @param string $filename
555 private function getSqlFilePath( $filename ) {
557 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
558 if ( file_exists( $dbmsSpecificFilePath ) ) {
559 return $dbmsSpecificFilePath;
561 return "$IP/maintenance/$filename";
566 * Return a path to the DBMS-specific schema file,
567 * otherwise default to tables.sql
571 public function getSchemaPath() {
572 return $this->getSqlFilePath( 'tables.sql' );
576 * Return a path to the DBMS-specific update key file,
577 * otherwise default to update-keys.sql
581 public function getUpdateKeysPath() {
582 return $this->getSqlFilePath( 'update-keys.sql' );
586 * Get the type of the DBMS, as it appears in $wgDBtype.
590 abstract function getType();
593 * Open a connection to the database. Usually aborts on failure
595 * @param string $server Database server host
596 * @param string $user Database user name
597 * @param string $password Database user password
598 * @param string $dbName Database name
600 * @throws DBConnectionError
602 abstract function open( $server, $user, $password, $dbName );
605 * Fetch the next row from the given result object, in object form.
606 * Fields can be retrieved with $row->fieldname, with fields acting like
608 * If no more rows are available, false is returned.
610 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
611 * @return stdClass|bool
612 * @throws DBUnexpectedError Thrown if the database returns an error
614 abstract function fetchObject( $res );
617 * Fetch the next row from the given result object, in associative array
618 * form. Fields are retrieved with $row['fieldname'].
619 * If no more rows are available, false is returned.
621 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
623 * @throws DBUnexpectedError Thrown if the database returns an error
625 abstract function fetchRow( $res );
628 * Get the number of rows in a result object
630 * @param mixed $res A SQL result
633 abstract function numRows( $res );
636 * Get the number of fields in a result object
637 * @see http://www.php.net/mysql_num_fields
639 * @param mixed $res A SQL result
642 abstract function numFields( $res );
645 * Get a field name in a result object
646 * @see http://www.php.net/mysql_field_name
648 * @param mixed $res A SQL result
652 abstract function fieldName( $res, $n );
655 * Get the inserted value of an auto-increment row
657 * The value inserted should be fetched from nextSequenceValue()
660 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
661 * $dbw->insert( 'page', array( 'page_id' => $id ) );
662 * $id = $dbw->insertId();
666 abstract function insertId();
669 * Change the position of the cursor in a result object
670 * @see http://www.php.net/mysql_data_seek
672 * @param mixed $res A SQL result
675 abstract function dataSeek( $res, $row );
678 * Get the last error number
679 * @see http://www.php.net/mysql_errno
683 abstract function lastErrno();
686 * Get a description of the last error
687 * @see http://www.php.net/mysql_error
691 abstract function lastError();
694 * mysql_fetch_field() wrapper
695 * Returns false if the field doesn't exist
697 * @param string $table Table name
698 * @param string $field Field name
702 abstract function fieldInfo( $table, $field );
705 * Get information about an index into an object
706 * @param string $table Table name
707 * @param string $index Index name
708 * @param string $fname Calling function name
709 * @return mixed Database-specific index description class or false if the index does not exist
711 abstract function indexInfo( $table, $index, $fname = __METHOD__
);
714 * Get the number of rows affected by the last write query
715 * @see http://www.php.net/mysql_affected_rows
719 abstract function affectedRows();
722 * Wrapper for addslashes()
724 * @param string $s String to be slashed.
725 * @return string Slashed string.
727 abstract function strencode( $s );
730 * Returns a wikitext link to the DB's website, e.g.,
731 * return "[http://www.mysql.com/ MySQL]";
732 * Should at least contain plain text, if for some reason
733 * your database has no website.
735 * @return string Wikitext of a link to the server software's web site
737 abstract function getSoftwareLink();
740 * A string describing the current software version, like from
741 * mysql_get_server_info().
743 * @return string Version information from the database server.
745 abstract function getServerVersion();
750 * FIXME: It is possible to construct a Database object with no associated
751 * connection object, by specifying no parameters to __construct(). This
752 * feature is deprecated and should be removed.
754 * DatabaseBase subclasses should not be constructed directly in external
755 * code. DatabaseBase::factory() should be used instead.
757 * @param array $params Parameters passed from DatabaseBase::factory()
759 function __construct( $params = null ) {
760 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
762 $this->mTrxAtomicLevels
= new SplStack
;
764 if ( is_array( $params ) ) { // MW 1.22
765 $server = $params['host'];
766 $user = $params['user'];
767 $password = $params['password'];
768 $dbName = $params['dbname'];
769 $flags = $params['flags'];
770 $tablePrefix = $params['tablePrefix'];
771 $schema = $params['schema'];
772 $foreign = $params['foreign'];
773 } else { // legacy calling pattern
774 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
775 $args = func_get_args();
776 $server = isset( $args[0] ) ?
$args[0] : false;
777 $user = isset( $args[1] ) ?
$args[1] : false;
778 $password = isset( $args[2] ) ?
$args[2] : false;
779 $dbName = isset( $args[3] ) ?
$args[3] : false;
780 $flags = isset( $args[4] ) ?
$args[4] : 0;
781 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
782 $schema = 'get from global';
783 $foreign = isset( $args[6] ) ?
$args[6] : false;
786 $this->mFlags
= $flags;
787 if ( $this->mFlags
& DBO_DEFAULT
) {
788 if ( $wgCommandLineMode ) {
789 $this->mFlags
&= ~DBO_TRX
;
790 if ( $wgDebugDBTransactions ) {
791 wfDebug( "Implicit transaction open disabled.\n" );
794 $this->mFlags |
= DBO_TRX
;
795 if ( $wgDebugDBTransactions ) {
796 wfDebug( "Implicit transaction open enabled.\n" );
801 /** Get the default table prefix*/
802 if ( $tablePrefix == 'get from global' ) {
803 $this->mTablePrefix
= $wgDBprefix;
805 $this->mTablePrefix
= $tablePrefix;
808 /** Get the database schema*/
809 if ( $schema == 'get from global' ) {
810 $this->mSchema
= $wgDBmwschema;
812 $this->mSchema
= $schema;
815 $this->mForeign
= $foreign;
818 $this->open( $server, $user, $password, $dbName );
823 * Called by serialize. Throw an exception when DB connection is serialized.
824 * This causes problems on some database engines because the connection is
825 * not restored on unserialize.
827 public function __sleep() {
828 throw new MWException( 'Database serialization may cause problems, since ' .
829 'the connection is not restored on wakeup.' );
833 * Given a DB type, construct the name of the appropriate child class of
834 * DatabaseBase. This is designed to replace all of the manual stuff like:
835 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
836 * as well as validate against the canonical list of DB types we have
838 * This factory function is mostly useful for when you need to connect to a
839 * database other than the MediaWiki default (such as for external auth,
840 * an extension, et cetera). Do not use this to connect to the MediaWiki
841 * database. Example uses in core:
842 * @see LoadBalancer::reallyOpenConnection()
843 * @see ForeignDBRepo::getMasterDB()
844 * @see WebInstallerDBConnect::execute()
848 * @param string $dbType A possible DB type
849 * @param array $p An array of options to pass to the constructor.
850 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
851 * @throws MWException If the database driver or extension cannot be found
852 * @return DatabaseBase|null DatabaseBase subclass or null
854 final public static function factory( $dbType, $p = array() ) {
855 $canonicalDBTypes = array(
856 'mysql' => array( 'mysqli', 'mysql' ),
857 'postgres' => array(),
864 $dbType = strtolower( $dbType );
865 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
866 $possibleDrivers = $canonicalDBTypes[$dbType];
867 if ( !empty( $p['driver'] ) ) {
868 if ( in_array( $p['driver'], $possibleDrivers ) ) {
869 $driver = $p['driver'];
871 throw new MWException( __METHOD__
.
872 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
875 foreach ( $possibleDrivers as $posDriver ) {
876 if ( extension_loaded( $posDriver ) ) {
877 $driver = $posDriver;
885 if ( $driver === false ) {
886 throw new MWException( __METHOD__
.
887 " no viable database extension found for type '$dbType'" );
890 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
891 // and everything else doesn't use a schema (e.g. null)
892 // Although postgres and oracle support schemas, we don't use them (yet)
893 // to maintain backwards compatibility
894 $defaultSchemas = array(
899 'mssql' => 'get from global',
902 $class = 'Database' . ucfirst( $driver );
903 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
905 'host' => isset( $p['host'] ) ?
$p['host'] : false,
906 'user' => isset( $p['user'] ) ?
$p['user'] : false,
907 'password' => isset( $p['password'] ) ?
$p['password'] : false,
908 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
909 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
910 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
911 'schema' => isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType],
912 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
915 return new $class( $params );
921 protected function installErrorHandler() {
922 $this->mPHPError
= false;
923 $this->htmlErrors
= ini_set( 'html_errors', '0' );
924 set_error_handler( array( $this, 'connectionErrorHandler' ) );
928 * @return bool|string
930 protected function restoreErrorHandler() {
931 restore_error_handler();
932 if ( $this->htmlErrors
!== false ) {
933 ini_set( 'html_errors', $this->htmlErrors
);
935 if ( $this->mPHPError
) {
936 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
937 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
947 * @param string $errstr
949 public function connectionErrorHandler( $errno, $errstr ) {
950 $this->mPHPError
= $errstr;
954 * Create a log context to pass to wfLogDBError or other logging functions.
956 * @param array $extras Additional data to add to context
959 protected function getLogContext( array $extras = array() ) {
962 'db_server' => $this->mServer
,
963 'db_name' => $this->mDBname
,
964 'db_user' => $this->mUser
,
971 * Closes a database connection.
972 * if it is open : commits any open transactions
974 * @throws MWException
975 * @return bool Operation success. true if already closed.
977 public function close() {
978 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
979 throw new MWException( "Transaction idle callbacks still pending." );
981 if ( $this->mConn
) {
982 if ( $this->trxLevel() ) {
983 if ( !$this->mTrxAutomatic
) {
984 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
985 " performing implicit commit before closing connection!" );
988 $this->commit( __METHOD__
, 'flush' );
991 $closed = $this->closeConnection();
992 $this->mConn
= false;
996 $this->mOpened
= false;
1002 * Closes underlying database connection
1004 * @return bool Whether connection was closed successfully
1006 abstract protected function closeConnection();
1009 * @param string $error Fallback error message, used if none is given by DB
1010 * @throws DBConnectionError
1012 function reportConnectionError( $error = 'Unknown error' ) {
1013 $myError = $this->lastError();
1019 throw new DBConnectionError( $this, $error );
1023 * The DBMS-dependent part of query()
1025 * @param string $sql SQL query.
1026 * @return ResultWrapper|bool Result object to feed to fetchObject,
1027 * fetchRow, ...; or false on failure
1029 abstract protected function doQuery( $sql );
1032 * Determine whether a query writes to the DB.
1033 * Should return true if unsure.
1035 * @param string $sql
1038 public function isWriteQuery( $sql ) {
1039 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1043 * Run an SQL query and return the result. Normally throws a DBQueryError
1044 * on failure. If errors are ignored, returns false instead.
1046 * In new code, the query wrappers select(), insert(), update(), delete(),
1047 * etc. should be used where possible, since they give much better DBMS
1048 * independence and automatically quote or validate user input in a variety
1049 * of contexts. This function is generally only useful for queries which are
1050 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1053 * However, the query wrappers themselves should call this function.
1055 * @param string $sql SQL query
1056 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1057 * comment (you can use __METHOD__ or add some extra info)
1058 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1059 * maybe best to catch the exception instead?
1060 * @throws MWException
1061 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1062 * for a successful read query, or false on failure if $tempIgnore set
1064 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1065 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1067 $this->mLastQuery
= $sql;
1069 $isWriteQuery = $this->isWriteQuery( $sql );
1070 if ( $isWriteQuery ) {
1071 # Set a flag indicating that writes have been done
1072 wfDebug( __METHOD__
. ': Writes done: ' . DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1073 $this->mDoneWrites
= microtime( true );
1076 # Add a comment for easy SHOW PROCESSLIST interpretation
1077 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1078 $userName = $wgUser->getName();
1079 if ( mb_strlen( $userName ) > 15 ) {
1080 $userName = mb_substr( $userName, 0, 15 ) . '...';
1082 $userName = str_replace( '/', '', $userName );
1087 // Add trace comment to the begin of the sql string, right after the operator.
1088 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1089 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1091 # If DBO_TRX is set, start a transaction
1092 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
1093 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1095 # Avoid establishing transactions for SHOW and SET statements too -
1096 # that would delay transaction initializations to once connection
1097 # is really used by application
1098 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1099 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1100 if ( $wgDebugDBTransactions ) {
1101 wfDebug( "Implicit transaction start.\n" );
1103 $this->begin( __METHOD__
. " ($fname)" );
1104 $this->mTrxAutomatic
= true;
1108 # Keep track of whether the transaction has write queries pending
1109 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1110 $this->mTrxDoneWrites
= true;
1111 Profiler
::instance()->getTransactionProfiler()->transactionWritingIn(
1112 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1117 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1119 $profiler = Profiler
::instance();
1120 if ( !$profiler instanceof ProfilerStub
) {
1121 # generalizeSQL will probably cut down the query to reasonable
1122 # logging size most of the time. The substr is really just a sanity check.
1124 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1125 $totalProf = 'DatabaseBase::query-master';
1127 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1128 $totalProf = 'DatabaseBase::query';
1130 # Include query transaction state
1131 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1133 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1134 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1137 if ( $this->debug() ) {
1141 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1143 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1145 $master = $isMaster ?
'master' : 'slave';
1146 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1149 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1151 # Avoid fatals if close() was called
1152 if ( !$this->isOpen() ) {
1153 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1156 # Log the query time and feed it into the DB trx profiler
1157 if ( $queryProf != '' ) {
1158 $queryStartTime = microtime( true );
1159 $queryProfile = new ScopedCallback(
1160 function () use ( $queryStartTime, $queryProf, $isMaster ) {
1161 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1162 $trxProfiler->recordQueryCompletion( $queryProf, $queryStartTime, $isMaster );
1167 # Do the query and handle errors
1168 $ret = $this->doQuery( $commentedSql );
1170 MWDebug
::queryTime( $queryId );
1172 # Try reconnecting if the connection was lost
1173 if ( false === $ret && $this->wasErrorReissuable() ) {
1174 # Transaction is gone, like it or not
1175 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1176 $this->mTrxLevel
= 0;
1177 $this->mTrxIdleCallbacks
= array(); // bug 65263
1178 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1179 wfDebug( "Connection lost, reconnecting...\n" );
1180 # Stash the last error values since ping() might clear them
1181 $lastError = $this->lastError();
1182 $lastErrno = $this->lastErrno();
1183 if ( $this->ping() ) {
1184 wfDebug( "Reconnected\n" );
1185 $server = $this->getServer();
1186 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1187 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1190 # Leave $ret as false and let an error be reported.
1191 # Callers may catch the exception and continue to use the DB.
1192 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1194 # Should be safe to silently retry (no trx and thus no callbacks)
1195 $ret = $this->doQuery( $commentedSql );
1198 wfDebug( "Failed\n" );
1202 if ( false === $ret ) {
1203 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1205 $n = $this->affectedRows();
1206 if ( $isWriteQuery && $n > self
::LOG_WRITE_THRESHOLD
&& PHP_SAPI
!== 'cli' ) {
1207 wfDebugLog( 'DBPerformance',
1208 "Query affected $n rows:\n" .
1209 DatabaseBase
::generalizeSQL( $sql ) . "\n" . wfBacktrace( true ) );
1213 $res = $this->resultObject( $ret );
1215 // Destroy profile sections in the opposite order to their creation
1216 $queryProfSection = false;
1217 $totalProfSection = false;
1223 * Report a query error. Log the error, and if neither the object ignore
1224 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1226 * @param string $error
1228 * @param string $sql
1229 * @param string $fname
1230 * @param bool $tempIgnore
1231 * @throws DBQueryError
1233 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1234 # Ignore errors during error handling to avoid infinite recursion
1235 $ignore = $this->ignoreErrors( true );
1236 ++
$this->mErrorCount
;
1238 if ( $ignore ||
$tempIgnore ) {
1239 wfDebug( "SQL ERROR (ignored): $error\n" );
1240 $this->ignoreErrors( $ignore );
1242 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1244 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1245 $this->getLogContext( array(
1246 'method' => __METHOD__
,
1249 'sql1line' => $sql1line,
1253 wfDebug( "SQL ERROR: " . $error . "\n" );
1254 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1259 * Intended to be compatible with the PEAR::DB wrapper functions.
1260 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1262 * ? = scalar value, quoted as necessary
1263 * ! = raw SQL bit (a function for instance)
1264 * & = filename; reads the file and inserts as a blob
1265 * (we don't use this though...)
1267 * @param string $sql
1268 * @param string $func
1272 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1273 /* MySQL doesn't support prepared statements (yet), so just
1274 * pack up the query for reference. We'll manually replace
1277 return array( 'query' => $sql, 'func' => $func );
1281 * Free a prepared query, generated by prepare().
1282 * @param string $prepared
1284 protected function freePrepared( $prepared ) {
1285 /* No-op by default */
1289 * Execute a prepared query with the various arguments
1290 * @param string $prepared The prepared sql
1291 * @param mixed $args Either an array here, or put scalars as varargs
1293 * @return ResultWrapper
1295 public function execute( $prepared, $args = null ) {
1296 if ( !is_array( $args ) ) {
1298 $args = func_get_args();
1299 array_shift( $args );
1302 $sql = $this->fillPrepared( $prepared['query'], $args );
1304 return $this->query( $sql, $prepared['func'] );
1308 * For faking prepared SQL statements on DBs that don't support it directly.
1310 * @param string $preparedQuery A 'preparable' SQL statement
1311 * @param array $args Array of Arguments to fill it with
1312 * @return string Executable SQL
1314 public function fillPrepared( $preparedQuery, $args ) {
1316 $this->preparedArgs
=& $args;
1318 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1319 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1323 * preg_callback func for fillPrepared()
1324 * The arguments should be in $this->preparedArgs and must not be touched
1325 * while we're doing this.
1327 * @param array $matches
1328 * @throws DBUnexpectedError
1331 protected function fillPreparedArg( $matches ) {
1332 switch ( $matches[1] ) {
1341 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1343 switch ( $matches[1] ) {
1345 return $this->addQuotes( $arg );
1349 # return $this->addQuotes( file_get_contents( $arg ) );
1350 throw new DBUnexpectedError(
1352 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1355 throw new DBUnexpectedError(
1357 'Received invalid match. This should never happen!'
1363 * Free a result object returned by query() or select(). It's usually not
1364 * necessary to call this, just use unset() or let the variable holding
1365 * the result object go out of scope.
1367 * @param mixed $res A SQL result
1369 public function freeResult( $res ) {
1373 * A SELECT wrapper which returns a single field from a single result row.
1375 * Usually throws a DBQueryError on failure. If errors are explicitly
1376 * ignored, returns false on failure.
1378 * If no result rows are returned from the query, false is returned.
1380 * @param string|array $table Table name. See DatabaseBase::select() for details.
1381 * @param string $var The field name to select. This must be a valid SQL
1382 * fragment: do not use unvalidated user input.
1383 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1384 * @param string $fname The function name of the caller.
1385 * @param string|array $options The query options. See DatabaseBase::select() for details.
1387 * @return bool|mixed The value from the field, or false on failure.
1389 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1392 if ( !is_array( $options ) ) {
1393 $options = array( $options );
1396 $options['LIMIT'] = 1;
1398 $res = $this->select( $table, $var, $cond, $fname, $options );
1400 if ( $res === false ||
!$this->numRows( $res ) ) {
1404 $row = $this->fetchRow( $res );
1406 if ( $row !== false ) {
1407 return reset( $row );
1414 * Returns an optional USE INDEX clause to go after the table, and a
1415 * string to go at the end of the query.
1417 * @param array $options Associative array of options to be turned into
1418 * an SQL query, valid keys are listed in the function.
1420 * @see DatabaseBase::select()
1422 public function makeSelectOptions( $options ) {
1423 $preLimitTail = $postLimitTail = '';
1426 $noKeyOptions = array();
1428 foreach ( $options as $key => $option ) {
1429 if ( is_numeric( $key ) ) {
1430 $noKeyOptions[$option] = true;
1434 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1436 $preLimitTail .= $this->makeOrderBy( $options );
1438 // if (isset($options['LIMIT'])) {
1439 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1440 // isset($options['OFFSET']) ? $options['OFFSET']
1444 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1445 $postLimitTail .= ' FOR UPDATE';
1448 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1449 $postLimitTail .= ' LOCK IN SHARE MODE';
1452 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1453 $startOpts .= 'DISTINCT';
1456 # Various MySQL extensions
1457 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1458 $startOpts .= ' /*! STRAIGHT_JOIN */';
1461 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1462 $startOpts .= ' HIGH_PRIORITY';
1465 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1466 $startOpts .= ' SQL_BIG_RESULT';
1469 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1470 $startOpts .= ' SQL_BUFFER_RESULT';
1473 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1474 $startOpts .= ' SQL_SMALL_RESULT';
1477 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1478 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1481 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1482 $startOpts .= ' SQL_CACHE';
1485 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1486 $startOpts .= ' SQL_NO_CACHE';
1489 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1490 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1495 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1499 * Returns an optional GROUP BY with an optional HAVING
1501 * @param array $options Associative array of options
1503 * @see DatabaseBase::select()
1506 public function makeGroupByWithHaving( $options ) {
1508 if ( isset( $options['GROUP BY'] ) ) {
1509 $gb = is_array( $options['GROUP BY'] )
1510 ?
implode( ',', $options['GROUP BY'] )
1511 : $options['GROUP BY'];
1512 $sql .= ' GROUP BY ' . $gb;
1514 if ( isset( $options['HAVING'] ) ) {
1515 $having = is_array( $options['HAVING'] )
1516 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1517 : $options['HAVING'];
1518 $sql .= ' HAVING ' . $having;
1525 * Returns an optional ORDER BY
1527 * @param array $options Associative array of options
1529 * @see DatabaseBase::select()
1532 public function makeOrderBy( $options ) {
1533 if ( isset( $options['ORDER BY'] ) ) {
1534 $ob = is_array( $options['ORDER BY'] )
1535 ?
implode( ',', $options['ORDER BY'] )
1536 : $options['ORDER BY'];
1538 return ' ORDER BY ' . $ob;
1545 * Execute a SELECT query constructed using the various parameters provided.
1546 * See below for full details of the parameters.
1548 * @param string|array $table Table name
1549 * @param string|array $vars Field names
1550 * @param string|array $conds Conditions
1551 * @param string $fname Caller function name
1552 * @param array $options Query options
1553 * @param array $join_conds Join conditions
1556 * @param string|array $table
1558 * May be either an array of table names, or a single string holding a table
1559 * name. If an array is given, table aliases can be specified, for example:
1561 * array( 'a' => 'user' )
1563 * This includes the user table in the query, with the alias "a" available
1564 * for use in field names (e.g. a.user_name).
1566 * All of the table names given here are automatically run through
1567 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1568 * added, and various other table name mappings to be performed.
1571 * @param string|array $vars
1573 * May be either a field name or an array of field names. The field names
1574 * can be complete fragments of SQL, for direct inclusion into the SELECT
1575 * query. If an array is given, field aliases can be specified, for example:
1577 * array( 'maxrev' => 'MAX(rev_id)' )
1579 * This includes an expression with the alias "maxrev" in the query.
1581 * If an expression is given, care must be taken to ensure that it is
1585 * @param string|array $conds
1587 * May be either a string containing a single condition, or an array of
1588 * conditions. If an array is given, the conditions constructed from each
1589 * element are combined with AND.
1591 * Array elements may take one of two forms:
1593 * - Elements with a numeric key are interpreted as raw SQL fragments.
1594 * - Elements with a string key are interpreted as equality conditions,
1595 * where the key is the field name.
1596 * - If the value of such an array element is a scalar (such as a
1597 * string), it will be treated as data and thus quoted appropriately.
1598 * If it is null, an IS NULL clause will be added.
1599 * - If the value is an array, an IN(...) clause will be constructed,
1600 * such that the field name may match any of the elements in the
1601 * array. The elements of the array will be quoted.
1603 * Note that expressions are often DBMS-dependent in their syntax.
1604 * DBMS-independent wrappers are provided for constructing several types of
1605 * expression commonly used in condition queries. See:
1606 * - DatabaseBase::buildLike()
1607 * - DatabaseBase::conditional()
1610 * @param string|array $options
1612 * Optional: Array of query options. Boolean options are specified by
1613 * including them in the array as a string value with a numeric key, for
1616 * array( 'FOR UPDATE' )
1618 * The supported options are:
1620 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1621 * with LIMIT can theoretically be used for paging through a result set,
1622 * but this is discouraged in MediaWiki for performance reasons.
1624 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1625 * and then the first rows are taken until the limit is reached. LIMIT
1626 * is applied to a result set after OFFSET.
1628 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1629 * changed until the next COMMIT.
1631 * - DISTINCT: Boolean: return only unique result rows.
1633 * - GROUP BY: May be either an SQL fragment string naming a field or
1634 * expression to group by, or an array of such SQL fragments.
1636 * - HAVING: May be either an string containing a HAVING clause or an array of
1637 * conditions building the HAVING clause. If an array is given, the conditions
1638 * constructed from each element are combined with AND.
1640 * - ORDER BY: May be either an SQL fragment giving a field name or
1641 * expression to order by, or an array of such SQL fragments.
1643 * - USE INDEX: This may be either a string giving the index name to use
1644 * for the query, or an array. If it is an associative array, each key
1645 * gives the table name (or alias), each value gives the index name to
1646 * use for that table. All strings are SQL fragments and so should be
1647 * validated by the caller.
1649 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1650 * instead of SELECT.
1652 * And also the following boolean MySQL extensions, see the MySQL manual
1653 * for documentation:
1655 * - LOCK IN SHARE MODE
1659 * - SQL_BUFFER_RESULT
1660 * - SQL_SMALL_RESULT
1661 * - SQL_CALC_FOUND_ROWS
1666 * @param string|array $join_conds
1668 * Optional associative array of table-specific join conditions. In the
1669 * most common case, this is unnecessary, since the join condition can be
1670 * in $conds. However, it is useful for doing a LEFT JOIN.
1672 * The key of the array contains the table name or alias. The value is an
1673 * array with two elements, numbered 0 and 1. The first gives the type of
1674 * join, the second is an SQL fragment giving the join condition for that
1675 * table. For example:
1677 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1679 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1680 * with no rows in it will be returned. If there was a query error, a
1681 * DBQueryError exception will be thrown, except if the "ignore errors"
1682 * option was set, in which case false will be returned.
1684 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1685 $options = array(), $join_conds = array() ) {
1686 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1688 return $this->query( $sql, $fname );
1692 * The equivalent of DatabaseBase::select() except that the constructed SQL
1693 * is returned, instead of being immediately executed. This can be useful for
1694 * doing UNION queries, where the SQL text of each query is needed. In general,
1695 * however, callers outside of Database classes should just use select().
1697 * @param string|array $table Table name
1698 * @param string|array $vars Field names
1699 * @param string|array $conds Conditions
1700 * @param string $fname Caller function name
1701 * @param string|array $options Query options
1702 * @param string|array $join_conds Join conditions
1704 * @return string SQL query string.
1705 * @see DatabaseBase::select()
1707 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1708 $options = array(), $join_conds = array()
1710 if ( is_array( $vars ) ) {
1711 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1714 $options = (array)$options;
1715 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1716 ?
$options['USE INDEX']
1719 if ( is_array( $table ) ) {
1721 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1722 } elseif ( $table != '' ) {
1723 if ( $table[0] == ' ' ) {
1724 $from = ' FROM ' . $table;
1727 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1733 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1734 $this->makeSelectOptions( $options );
1736 if ( !empty( $conds ) ) {
1737 if ( is_array( $conds ) ) {
1738 $conds = $this->makeList( $conds, LIST_AND
);
1740 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1742 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1745 if ( isset( $options['LIMIT'] ) ) {
1746 $sql = $this->limitResult( $sql, $options['LIMIT'],
1747 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1749 $sql = "$sql $postLimitTail";
1751 if ( isset( $options['EXPLAIN'] ) ) {
1752 $sql = 'EXPLAIN ' . $sql;
1759 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1760 * that a single row object is returned. If the query returns no rows,
1761 * false is returned.
1763 * @param string|array $table Table name
1764 * @param string|array $vars Field names
1765 * @param array $conds Conditions
1766 * @param string $fname Caller function name
1767 * @param string|array $options Query options
1768 * @param array|string $join_conds Join conditions
1770 * @return stdClass|bool
1772 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1773 $options = array(), $join_conds = array()
1775 $options = (array)$options;
1776 $options['LIMIT'] = 1;
1777 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1779 if ( $res === false ) {
1783 if ( !$this->numRows( $res ) ) {
1787 $obj = $this->fetchObject( $res );
1793 * Estimate the number of rows in dataset
1795 * MySQL allows you to estimate the number of rows that would be returned
1796 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1797 * index cardinality statistics, and is notoriously inaccurate, especially
1798 * when large numbers of rows have recently been added or deleted.
1800 * For DBMSs that don't support fast result size estimation, this function
1801 * will actually perform the SELECT COUNT(*).
1803 * Takes the same arguments as DatabaseBase::select().
1805 * @param string $table Table name
1806 * @param string $vars Unused
1807 * @param array|string $conds Filters on the table
1808 * @param string $fname Function name for profiling
1809 * @param array $options Options for select
1810 * @return int Row count
1812 public function estimateRowCount(
1813 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1816 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1819 $row = $this->fetchRow( $res );
1820 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1827 * Get the number of rows in dataset
1829 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1831 * Takes the same arguments as DatabaseBase::select().
1833 * @param string $table Table name
1834 * @param string $vars Unused
1835 * @param array|string $conds Filters on the table
1836 * @param string $fname Function name for profiling
1837 * @param array $options Options for select
1838 * @return int Row count
1841 public function selectRowCount(
1842 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1845 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1846 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1849 $row = $this->fetchRow( $res );
1850 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1857 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1858 * It's only slightly flawed. Don't use for anything important.
1860 * @param string $sql A SQL Query
1864 static function generalizeSQL( $sql ) {
1865 # This does the same as the regexp below would do, but in such a way
1866 # as to avoid crashing php on some large strings.
1867 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1869 $sql = str_replace( "\\\\", '', $sql );
1870 $sql = str_replace( "\\'", '', $sql );
1871 $sql = str_replace( "\\\"", '', $sql );
1872 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1873 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1875 # All newlines, tabs, etc replaced by single space
1876 $sql = preg_replace( '/\s+/', ' ', $sql );
1879 # except the ones surrounded by characters, e.g. l10n
1880 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1881 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1887 * Determines whether a field exists in a table
1889 * @param string $table Table name
1890 * @param string $field Filed to check on that table
1891 * @param string $fname Calling function name (optional)
1892 * @return bool Whether $table has filed $field
1894 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1895 $info = $this->fieldInfo( $table, $field );
1901 * Determines whether an index exists
1902 * Usually throws a DBQueryError on failure
1903 * If errors are explicitly ignored, returns NULL on failure
1905 * @param string $table
1906 * @param string $index
1907 * @param string $fname
1910 public function indexExists( $table, $index, $fname = __METHOD__
) {
1911 if ( !$this->tableExists( $table ) ) {
1915 $info = $this->indexInfo( $table, $index, $fname );
1916 if ( is_null( $info ) ) {
1919 return $info !== false;
1924 * Query whether a given table exists
1926 * @param string $table
1927 * @param string $fname
1930 public function tableExists( $table, $fname = __METHOD__
) {
1931 $table = $this->tableName( $table );
1932 $old = $this->ignoreErrors( true );
1933 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1934 $this->ignoreErrors( $old );
1940 * Determines if a given index is unique
1942 * @param string $table
1943 * @param string $index
1947 public function indexUnique( $table, $index ) {
1948 $indexInfo = $this->indexInfo( $table, $index );
1950 if ( !$indexInfo ) {
1954 return !$indexInfo[0]->Non_unique
;
1958 * Helper for DatabaseBase::insert().
1960 * @param array $options
1963 protected function makeInsertOptions( $options ) {
1964 return implode( ' ', $options );
1968 * INSERT wrapper, inserts an array into a table.
1972 * - A single associative array. The array keys are the field names, and
1973 * the values are the values to insert. The values are treated as data
1974 * and will be quoted appropriately. If NULL is inserted, this will be
1975 * converted to a database NULL.
1976 * - An array with numeric keys, holding a list of associative arrays.
1977 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1978 * each subarray must be identical to each other, and in the same order.
1980 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1983 * $options is an array of options, with boolean options encoded as values
1984 * with numeric keys, in the same style as $options in
1985 * DatabaseBase::select(). Supported options are:
1987 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1988 * any rows which cause duplicate key errors are not inserted. It's
1989 * possible to determine how many rows were successfully inserted using
1990 * DatabaseBase::affectedRows().
1992 * @param string $table Table name. This will be passed through
1993 * DatabaseBase::tableName().
1994 * @param array $a Array of rows to insert
1995 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1996 * @param array $options Array of options
2000 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2001 # No rows to insert, easy just return now
2002 if ( !count( $a ) ) {
2006 $table = $this->tableName( $table );
2008 if ( !is_array( $options ) ) {
2009 $options = array( $options );
2013 if ( isset( $options['fileHandle'] ) ) {
2014 $fh = $options['fileHandle'];
2016 $options = $this->makeInsertOptions( $options );
2018 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2020 $keys = array_keys( $a[0] );
2023 $keys = array_keys( $a );
2026 $sql = 'INSERT ' . $options .
2027 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2031 foreach ( $a as $row ) {
2037 $sql .= '(' . $this->makeList( $row ) . ')';
2040 $sql .= '(' . $this->makeList( $a ) . ')';
2043 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2045 } elseif ( $fh !== null ) {
2049 return (bool)$this->query( $sql, $fname );
2053 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2055 * @param array $options
2058 protected function makeUpdateOptionsArray( $options ) {
2059 if ( !is_array( $options ) ) {
2060 $options = array( $options );
2065 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2066 $opts[] = $this->lowPriorityOption();
2069 if ( in_array( 'IGNORE', $options ) ) {
2077 * Make UPDATE options for the DatabaseBase::update function
2079 * @param array $options The options passed to DatabaseBase::update
2082 protected function makeUpdateOptions( $options ) {
2083 $opts = $this->makeUpdateOptionsArray( $options );
2085 return implode( ' ', $opts );
2089 * UPDATE wrapper. Takes a condition array and a SET array.
2091 * @param string $table Name of the table to UPDATE. This will be passed through
2092 * DatabaseBase::tableName().
2093 * @param array $values An array of values to SET. For each array element,
2094 * the key gives the field name, and the value gives the data to set
2095 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2096 * @param array $conds An array of conditions (WHERE). See
2097 * DatabaseBase::select() for the details of the format of condition
2098 * arrays. Use '*' to update all rows.
2099 * @param string $fname The function name of the caller (from __METHOD__),
2100 * for logging and profiling.
2101 * @param array $options An array of UPDATE options, can be:
2102 * - IGNORE: Ignore unique key conflicts
2103 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2106 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2107 $table = $this->tableName( $table );
2108 $opts = $this->makeUpdateOptions( $options );
2109 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2111 if ( $conds !== array() && $conds !== '*' ) {
2112 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2115 return $this->query( $sql, $fname );
2119 * Makes an encoded list of strings from an array
2121 * @param array $a Containing the data
2122 * @param int $mode Constant
2123 * - LIST_COMMA: Comma separated, no field names
2124 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2125 * documentation for $conds in DatabaseBase::select().
2126 * - LIST_OR: ORed WHERE clause (without the WHERE)
2127 * - LIST_SET: Comma separated with field names, like a SET clause
2128 * - LIST_NAMES: Comma separated field names
2129 * @throws MWException|DBUnexpectedError
2132 public function makeList( $a, $mode = LIST_COMMA
) {
2133 if ( !is_array( $a ) ) {
2134 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2140 foreach ( $a as $field => $value ) {
2142 if ( $mode == LIST_AND
) {
2144 } elseif ( $mode == LIST_OR
) {
2153 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2154 $list .= "($value)";
2155 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2157 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2158 if ( count( $value ) == 0 ) {
2159 throw new MWException( __METHOD__
. ": empty input for field $field" );
2160 } elseif ( count( $value ) == 1 ) {
2161 // Special-case single values, as IN isn't terribly efficient
2162 // Don't necessarily assume the single key is 0; we don't
2163 // enforce linear numeric ordering on other arrays here.
2164 $value = array_values( $value );
2165 $list .= $field . " = " . $this->addQuotes( $value[0] );
2167 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2169 } elseif ( $value === null ) {
2170 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2171 $list .= "$field IS ";
2172 } elseif ( $mode == LIST_SET
) {
2173 $list .= "$field = ";
2177 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2178 $list .= "$field = ";
2180 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2188 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2189 * The keys on each level may be either integers or strings.
2191 * @param array $data Organized as 2-d
2192 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2193 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2194 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2195 * @return string|bool SQL fragment, or false if no items in array
2197 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2200 foreach ( $data as $base => $sub ) {
2201 if ( count( $sub ) ) {
2202 $conds[] = $this->makeList(
2203 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2209 return $this->makeList( $conds, LIST_OR
);
2211 // Nothing to search for...
2217 * Return aggregated value alias
2219 * @param array $valuedata
2220 * @param string $valuename
2224 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2229 * @param string $field
2232 public function bitNot( $field ) {
2237 * @param string $fieldLeft
2238 * @param string $fieldRight
2241 public function bitAnd( $fieldLeft, $fieldRight ) {
2242 return "($fieldLeft & $fieldRight)";
2246 * @param string $fieldLeft
2247 * @param string $fieldRight
2250 public function bitOr( $fieldLeft, $fieldRight ) {
2251 return "($fieldLeft | $fieldRight)";
2255 * Build a concatenation list to feed into a SQL query
2256 * @param array $stringList List of raw SQL expressions; caller is
2257 * responsible for any quoting
2260 public function buildConcat( $stringList ) {
2261 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2265 * Build a GROUP_CONCAT or equivalent statement for a query.
2267 * This is useful for combining a field for several rows into a single string.
2268 * NULL values will not appear in the output, duplicated values will appear,
2269 * and the resulting delimiter-separated values have no defined sort order.
2270 * Code using the results may need to use the PHP unique() or sort() methods.
2272 * @param string $delim Glue to bind the results together
2273 * @param string|array $table Table name
2274 * @param string $field Field name
2275 * @param string|array $conds Conditions
2276 * @param string|array $join_conds Join conditions
2277 * @return string SQL text
2280 public function buildGroupConcatField(
2281 $delim, $table, $field, $conds = '', $join_conds = array()
2283 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2285 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2289 * Change the current database
2291 * @todo Explain what exactly will fail if this is not overridden.
2295 * @return bool Success or failure
2297 public function selectDB( $db ) {
2298 # Stub. Shouldn't cause serious problems if it's not overridden, but
2299 # if your database engine supports a concept similar to MySQL's
2300 # databases you may as well.
2301 $this->mDBname
= $db;
2307 * Get the current DB name
2310 public function getDBname() {
2311 return $this->mDBname
;
2315 * Get the server hostname or IP address
2318 public function getServer() {
2319 return $this->mServer
;
2323 * Format a table name ready for use in constructing an SQL query
2325 * This does two important things: it quotes the table names to clean them up,
2326 * and it adds a table prefix if only given a table name with no quotes.
2328 * All functions of this object which require a table name call this function
2329 * themselves. Pass the canonical name to such functions. This is only needed
2330 * when calling query() directly.
2332 * @param string $name Database table name
2333 * @param string $format One of:
2334 * quoted - Automatically pass the table name through addIdentifierQuotes()
2335 * so that it can be used in a query.
2336 * raw - Do not add identifier quotes to the table name
2337 * @return string Full database name
2339 public function tableName( $name, $format = 'quoted' ) {
2340 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2341 # Skip the entire process when we have a string quoted on both ends.
2342 # Note that we check the end so that we will still quote any use of
2343 # use of `database`.table. But won't break things if someone wants
2344 # to query a database table with a dot in the name.
2345 if ( $this->isQuotedIdentifier( $name ) ) {
2349 # Lets test for any bits of text that should never show up in a table
2350 # name. Basically anything like JOIN or ON which are actually part of
2351 # SQL queries, but may end up inside of the table value to combine
2352 # sql. Such as how the API is doing.
2353 # Note that we use a whitespace test rather than a \b test to avoid
2354 # any remote case where a word like on may be inside of a table name
2355 # surrounded by symbols which may be considered word breaks.
2356 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2360 # Split database and table into proper variables.
2361 # We reverse the explode so that database.table and table both output
2362 # the correct table.
2363 $dbDetails = explode( '.', $name, 3 );
2364 if ( count( $dbDetails ) == 3 ) {
2365 list( $database, $schema, $table ) = $dbDetails;
2366 # We don't want any prefix added in this case
2368 } elseif ( count( $dbDetails ) == 2 ) {
2369 list( $database, $table ) = $dbDetails;
2370 # We don't want any prefix added in this case
2371 # In dbs that support it, $database may actually be the schema
2372 # but that doesn't affect any of the functionality here
2376 list( $table ) = $dbDetails;
2377 if ( $wgSharedDB !== null # We have a shared database
2378 && $this->mForeign
== false # We're not working on a foreign database
2379 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2380 && in_array( $table, $wgSharedTables ) # A shared table is selected
2382 $database = $wgSharedDB;
2383 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2384 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2387 $schema = $this->mSchema
; # Default schema
2388 $prefix = $this->mTablePrefix
; # Default prefix
2392 # Quote $table and apply the prefix if not quoted.
2393 # $tableName might be empty if this is called from Database::replaceVars()
2394 $tableName = "{$prefix}{$table}";
2395 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2396 $tableName = $this->addIdentifierQuotes( $tableName );
2399 # Quote $schema and merge it with the table name if needed
2400 if ( $schema !== null ) {
2401 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2402 $schema = $this->addIdentifierQuotes( $schema );
2404 $tableName = $schema . '.' . $tableName;
2407 # Quote $database and merge it with the table name if needed
2408 if ( $database !== null ) {
2409 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2410 $database = $this->addIdentifierQuotes( $database );
2412 $tableName = $database . '.' . $tableName;
2419 * Fetch a number of table names into an array
2420 * This is handy when you need to construct SQL for joins
2423 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2424 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2425 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2429 public function tableNames() {
2430 $inArray = func_get_args();
2433 foreach ( $inArray as $name ) {
2434 $retVal[$name] = $this->tableName( $name );
2441 * Fetch a number of table names into an zero-indexed numerical array
2442 * This is handy when you need to construct SQL for joins
2445 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2446 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2447 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2451 public function tableNamesN() {
2452 $inArray = func_get_args();
2455 foreach ( $inArray as $name ) {
2456 $retVal[] = $this->tableName( $name );
2463 * Get an aliased table name
2464 * e.g. tableName AS newTableName
2466 * @param string $name Table name, see tableName()
2467 * @param string|bool $alias Alias (optional)
2468 * @return string SQL name for aliased table. Will not alias a table to its own name
2470 public function tableNameWithAlias( $name, $alias = false ) {
2471 if ( !$alias ||
$alias == $name ) {
2472 return $this->tableName( $name );
2474 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2479 * Gets an array of aliased table names
2481 * @param array $tables Array( [alias] => table )
2482 * @return string[] See tableNameWithAlias()
2484 public function tableNamesWithAlias( $tables ) {
2486 foreach ( $tables as $alias => $table ) {
2487 if ( is_numeric( $alias ) ) {
2490 $retval[] = $this->tableNameWithAlias( $table, $alias );
2497 * Get an aliased field name
2498 * e.g. fieldName AS newFieldName
2500 * @param string $name Field name
2501 * @param string|bool $alias Alias (optional)
2502 * @return string SQL name for aliased field. Will not alias a field to its own name
2504 public function fieldNameWithAlias( $name, $alias = false ) {
2505 if ( !$alias ||
(string)$alias === (string)$name ) {
2508 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2513 * Gets an array of aliased field names
2515 * @param array $fields Array( [alias] => field )
2516 * @return string[] See fieldNameWithAlias()
2518 public function fieldNamesWithAlias( $fields ) {
2520 foreach ( $fields as $alias => $field ) {
2521 if ( is_numeric( $alias ) ) {
2524 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2531 * Get the aliased table name clause for a FROM clause
2532 * which might have a JOIN and/or USE INDEX clause
2534 * @param array $tables ( [alias] => table )
2535 * @param array $use_index Same as for select()
2536 * @param array $join_conds Same as for select()
2539 protected function tableNamesWithUseIndexOrJOIN(
2540 $tables, $use_index = array(), $join_conds = array()
2544 $use_index = (array)$use_index;
2545 $join_conds = (array)$join_conds;
2547 foreach ( $tables as $alias => $table ) {
2548 if ( !is_string( $alias ) ) {
2549 // No alias? Set it equal to the table name
2552 // Is there a JOIN clause for this table?
2553 if ( isset( $join_conds[$alias] ) ) {
2554 list( $joinType, $conds ) = $join_conds[$alias];
2555 $tableClause = $joinType;
2556 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2557 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2558 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2560 $tableClause .= ' ' . $use;
2563 $on = $this->makeList( (array)$conds, LIST_AND
);
2565 $tableClause .= ' ON (' . $on . ')';
2568 $retJOIN[] = $tableClause;
2569 } elseif ( isset( $use_index[$alias] ) ) {
2570 // Is there an INDEX clause for this table?
2571 $tableClause = $this->tableNameWithAlias( $table, $alias );
2572 $tableClause .= ' ' . $this->useIndexClause(
2573 implode( ',', (array)$use_index[$alias] )
2576 $ret[] = $tableClause;
2578 $tableClause = $this->tableNameWithAlias( $table, $alias );
2580 $ret[] = $tableClause;
2584 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2585 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2586 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2588 // Compile our final table clause
2589 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2593 * Get the name of an index in a given table.
2595 * @protected Don't use outside of DatabaseBase and childs
2596 * @param string $index
2599 public function indexName( $index ) {
2600 // @FIXME: Make this protected once we move away from PHP 5.3
2601 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2603 // Backwards-compatibility hack
2605 'ar_usertext_timestamp' => 'usertext_timestamp',
2606 'un_user_id' => 'user_id',
2607 'un_user_ip' => 'user_ip',
2610 if ( isset( $renamed[$index] ) ) {
2611 return $renamed[$index];
2618 * Adds quotes and backslashes.
2623 public function addQuotes( $s ) {
2624 if ( $s === null ) {
2627 # This will also quote numeric values. This should be harmless,
2628 # and protects against weird problems that occur when they really
2629 # _are_ strings such as article titles and string->number->string
2630 # conversion is not 1:1.
2631 return "'" . $this->strencode( $s ) . "'";
2636 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2637 * MySQL uses `backticks` while basically everything else uses double quotes.
2638 * Since MySQL is the odd one out here the double quotes are our generic
2639 * and we implement backticks in DatabaseMysql.
2644 public function addIdentifierQuotes( $s ) {
2645 return '"' . str_replace( '"', '""', $s ) . '"';
2649 * Returns if the given identifier looks quoted or not according to
2650 * the database convention for quoting identifiers .
2652 * @param string $name
2655 public function isQuotedIdentifier( $name ) {
2656 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2663 protected function escapeLikeInternal( $s ) {
2664 return addcslashes( $s, '\%_' );
2668 * LIKE statement wrapper, receives a variable-length argument list with
2669 * parts of pattern to match containing either string literals that will be
2670 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2671 * the function could be provided with an array of aforementioned
2674 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2675 * a LIKE clause that searches for subpages of 'My page title'.
2677 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2678 * $query .= $dbr->buildLike( $pattern );
2681 * @return string Fully built LIKE statement
2683 public function buildLike() {
2684 $params = func_get_args();
2686 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2687 $params = $params[0];
2692 foreach ( $params as $value ) {
2693 if ( $value instanceof LikeMatch
) {
2694 $s .= $value->toString();
2696 $s .= $this->escapeLikeInternal( $value );
2700 return " LIKE {$this->addQuotes( $s )} ";
2704 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2708 public function anyChar() {
2709 return new LikeMatch( '_' );
2713 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2717 public function anyString() {
2718 return new LikeMatch( '%' );
2722 * Returns an appropriately quoted sequence value for inserting a new row.
2723 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2724 * subclass will return an integer, and save the value for insertId()
2726 * Any implementation of this function should *not* involve reusing
2727 * sequence numbers created for rolled-back transactions.
2728 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2729 * @param string $seqName
2732 public function nextSequenceValue( $seqName ) {
2737 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2738 * is only needed because a) MySQL must be as efficient as possible due to
2739 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2740 * which index to pick. Anyway, other databases might have different
2741 * indexes on a given table. So don't bother overriding this unless you're
2743 * @param string $index
2746 public function useIndexClause( $index ) {
2751 * REPLACE query wrapper.
2753 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2754 * except that when there is a duplicate key error, the old row is deleted
2755 * and the new row is inserted in its place.
2757 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2758 * perform the delete, we need to know what the unique indexes are so that
2759 * we know how to find the conflicting rows.
2761 * It may be more efficient to leave off unique indexes which are unlikely
2762 * to collide. However if you do this, you run the risk of encountering
2763 * errors which wouldn't have occurred in MySQL.
2765 * @param string $table The table to replace the row(s) in.
2766 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2767 * a field name or an array of field names
2768 * @param array $rows Can be either a single row to insert, or multiple rows,
2769 * in the same format as for DatabaseBase::insert()
2770 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2772 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2773 $quotedTable = $this->tableName( $table );
2775 if ( count( $rows ) == 0 ) {
2780 if ( !is_array( reset( $rows ) ) ) {
2781 $rows = array( $rows );
2784 foreach ( $rows as $row ) {
2785 # Delete rows which collide
2786 if ( $uniqueIndexes ) {
2787 $sql = "DELETE FROM $quotedTable WHERE ";
2789 foreach ( $uniqueIndexes as $index ) {
2796 if ( is_array( $index ) ) {
2798 foreach ( $index as $col ) {
2804 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2807 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2811 $this->query( $sql, $fname );
2814 # Now insert the row
2815 $this->insert( $table, $row, $fname );
2820 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2823 * @param string $table Table name
2824 * @param array|string $rows Row(s) to insert
2825 * @param string $fname Caller function name
2827 * @return ResultWrapper
2829 protected function nativeReplace( $table, $rows, $fname ) {
2830 $table = $this->tableName( $table );
2833 if ( !is_array( reset( $rows ) ) ) {
2834 $rows = array( $rows );
2837 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2840 foreach ( $rows as $row ) {
2847 $sql .= '(' . $this->makeList( $row ) . ')';
2850 return $this->query( $sql, $fname );
2854 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2856 * This updates any conflicting rows (according to the unique indexes) using
2857 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2859 * $rows may be either:
2860 * - A single associative array. The array keys are the field names, and
2861 * the values are the values to insert. The values are treated as data
2862 * and will be quoted appropriately. If NULL is inserted, this will be
2863 * converted to a database NULL.
2864 * - An array with numeric keys, holding a list of associative arrays.
2865 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2866 * each subarray must be identical to each other, and in the same order.
2868 * It may be more efficient to leave off unique indexes which are unlikely
2869 * to collide. However if you do this, you run the risk of encountering
2870 * errors which wouldn't have occurred in MySQL.
2872 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2877 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2878 * @param array $rows A single row or list of rows to insert
2879 * @param array $uniqueIndexes List of single field names or field name tuples
2880 * @param array $set An array of values to SET. For each array element, the
2881 * key gives the field name, and the value gives the data to set that
2882 * field to. The data will be quoted by DatabaseBase::addQuotes().
2883 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2887 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2890 if ( !count( $rows ) ) {
2891 return true; // nothing to do
2894 if ( !is_array( reset( $rows ) ) ) {
2895 $rows = array( $rows );
2898 if ( count( $uniqueIndexes ) ) {
2899 $clauses = array(); // list WHERE clauses that each identify a single row
2900 foreach ( $rows as $row ) {
2901 foreach ( $uniqueIndexes as $index ) {
2902 $index = is_array( $index ) ?
$index : array( $index ); // columns
2903 $rowKey = array(); // unique key to this row
2904 foreach ( $index as $column ) {
2905 $rowKey[$column] = $row[$column];
2907 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2910 $where = array( $this->makeList( $clauses, LIST_OR
) );
2915 $useTrx = !$this->mTrxLevel
;
2917 $this->begin( $fname );
2920 # Update any existing conflicting row(s)
2921 if ( $where !== false ) {
2922 $ok = $this->update( $table, $set, $where, $fname );
2926 # Now insert any non-conflicting row(s)
2927 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2928 } catch ( Exception
$e ) {
2930 $this->rollback( $fname );
2935 $this->commit( $fname );
2942 * DELETE where the condition is a join.
2944 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2945 * we use sub-selects
2947 * For safety, an empty $conds will not delete everything. If you want to
2948 * delete all rows where the join condition matches, set $conds='*'.
2950 * DO NOT put the join condition in $conds.
2952 * @param string $delTable The table to delete from.
2953 * @param string $joinTable The other table.
2954 * @param string $delVar The variable to join on, in the first table.
2955 * @param string $joinVar The variable to join on, in the second table.
2956 * @param array $conds Condition array of field names mapped to variables,
2957 * ANDed together in the WHERE clause
2958 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2959 * @throws DBUnexpectedError
2961 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2965 throw new DBUnexpectedError( $this,
2966 'DatabaseBase::deleteJoin() called with empty $conds' );
2969 $delTable = $this->tableName( $delTable );
2970 $joinTable = $this->tableName( $joinTable );
2971 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2972 if ( $conds != '*' ) {
2973 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2977 $this->query( $sql, $fname );
2981 * Returns the size of a text field, or -1 for "unlimited"
2983 * @param string $table
2984 * @param string $field
2987 public function textFieldSize( $table, $field ) {
2988 $table = $this->tableName( $table );
2989 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2990 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2991 $row = $this->fetchObject( $res );
2995 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3005 * A string to insert into queries to show that they're low-priority, like
3006 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3007 * string and nothing bad should happen.
3009 * @return string Returns the text of the low priority option if it is
3010 * supported, or a blank string otherwise
3012 public function lowPriorityOption() {
3017 * DELETE query wrapper.
3019 * @param array $table Table name
3020 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3021 * for the format. Use $conds == "*" to delete all rows
3022 * @param string $fname Name of the calling function
3023 * @throws DBUnexpectedError
3024 * @return bool|ResultWrapper
3026 public function delete( $table, $conds, $fname = __METHOD__
) {
3028 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3031 $table = $this->tableName( $table );
3032 $sql = "DELETE FROM $table";
3034 if ( $conds != '*' ) {
3035 if ( is_array( $conds ) ) {
3036 $conds = $this->makeList( $conds, LIST_AND
);
3038 $sql .= ' WHERE ' . $conds;
3041 return $this->query( $sql, $fname );
3045 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3046 * into another table.
3048 * @param string $destTable The table name to insert into
3049 * @param string|array $srcTable May be either a table name, or an array of table names
3050 * to include in a join.
3052 * @param array $varMap Must be an associative array of the form
3053 * array( 'dest1' => 'source1', ...). Source items may be literals
3054 * rather than field names, but strings should be quoted with
3055 * DatabaseBase::addQuotes()
3057 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3058 * the details of the format of condition arrays. May be "*" to copy the
3061 * @param string $fname The function name of the caller, from __METHOD__
3063 * @param array $insertOptions Options for the INSERT part of the query, see
3064 * DatabaseBase::insert() for details.
3065 * @param array $selectOptions Options for the SELECT part of the query, see
3066 * DatabaseBase::select() for details.
3068 * @return ResultWrapper
3070 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3071 $fname = __METHOD__
,
3072 $insertOptions = array(), $selectOptions = array()
3074 $destTable = $this->tableName( $destTable );
3076 if ( !is_array( $insertOptions ) ) {
3077 $insertOptions = array( $insertOptions );
3080 $insertOptions = $this->makeInsertOptions( $insertOptions );
3082 if ( !is_array( $selectOptions ) ) {
3083 $selectOptions = array( $selectOptions );
3086 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3088 if ( is_array( $srcTable ) ) {
3089 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3091 $srcTable = $this->tableName( $srcTable );
3094 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3095 " SELECT $startOpts " . implode( ',', $varMap ) .
3096 " FROM $srcTable $useIndex ";
3098 if ( $conds != '*' ) {
3099 if ( is_array( $conds ) ) {
3100 $conds = $this->makeList( $conds, LIST_AND
);
3102 $sql .= " WHERE $conds";
3105 $sql .= " $tailOpts";
3107 return $this->query( $sql, $fname );
3111 * Construct a LIMIT query with optional offset. This is used for query
3112 * pages. The SQL should be adjusted so that only the first $limit rows
3113 * are returned. If $offset is provided as well, then the first $offset
3114 * rows should be discarded, and the next $limit rows should be returned.
3115 * If the result of the query is not ordered, then the rows to be returned
3116 * are theoretically arbitrary.
3118 * $sql is expected to be a SELECT, if that makes a difference.
3120 * The version provided by default works in MySQL and SQLite. It will very
3121 * likely need to be overridden for most other DBMSes.
3123 * @param string $sql SQL query we will append the limit too
3124 * @param int $limit The SQL limit
3125 * @param int|bool $offset The SQL offset (default false)
3126 * @throws DBUnexpectedError
3129 public function limitResult( $sql, $limit, $offset = false ) {
3130 if ( !is_numeric( $limit ) ) {
3131 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3134 return "$sql LIMIT "
3135 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3140 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3141 * within the UNION construct.
3144 public function unionSupportsOrderAndLimit() {
3145 return true; // True for almost every DB supported
3149 * Construct a UNION query
3150 * This is used for providing overload point for other DB abstractions
3151 * not compatible with the MySQL syntax.
3152 * @param array $sqls SQL statements to combine
3153 * @param bool $all Use UNION ALL
3154 * @return string SQL fragment
3156 public function unionQueries( $sqls, $all ) {
3157 $glue = $all ?
') UNION ALL (' : ') UNION (';
3159 return '(' . implode( $glue, $sqls ) . ')';
3163 * Returns an SQL expression for a simple conditional. This doesn't need
3164 * to be overridden unless CASE isn't supported in your DBMS.
3166 * @param string|array $cond SQL expression which will result in a boolean value
3167 * @param string $trueVal SQL expression to return if true
3168 * @param string $falseVal SQL expression to return if false
3169 * @return string SQL fragment
3171 public function conditional( $cond, $trueVal, $falseVal ) {
3172 if ( is_array( $cond ) ) {
3173 $cond = $this->makeList( $cond, LIST_AND
);
3176 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3180 * Returns a comand for str_replace function in SQL query.
3181 * Uses REPLACE() in MySQL
3183 * @param string $orig Column to modify
3184 * @param string $old Column to seek
3185 * @param string $new Column to replace with
3189 public function strreplace( $orig, $old, $new ) {
3190 return "REPLACE({$orig}, {$old}, {$new})";
3194 * Determines how long the server has been up
3199 public function getServerUptime() {
3204 * Determines if the last failure was due to a deadlock
3209 public function wasDeadlock() {
3214 * Determines if the last failure was due to a lock timeout
3219 public function wasLockTimeout() {
3224 * Determines if the last query error was something that should be dealt
3225 * with by pinging the connection and reissuing the query.
3230 public function wasErrorReissuable() {
3235 * Determines if the last failure was due to the database being read-only.
3240 public function wasReadOnlyError() {
3245 * Perform a deadlock-prone transaction.
3247 * This function invokes a callback function to perform a set of write
3248 * queries. If a deadlock occurs during the processing, the transaction
3249 * will be rolled back and the callback function will be called again.
3252 * $dbw->deadlockLoop( callback, ... );
3254 * Extra arguments are passed through to the specified callback function.
3256 * Returns whatever the callback function returned on its successful,
3257 * iteration, or false on error, for example if the retry limit was
3262 public function deadlockLoop() {
3263 $this->begin( __METHOD__
);
3264 $args = func_get_args();
3265 $function = array_shift( $args );
3266 $oldIgnore = $this->ignoreErrors( true );
3267 $tries = self
::DEADLOCK_TRIES
;
3269 if ( is_array( $function ) ) {
3270 $fname = $function[0];
3276 $retVal = call_user_func_array( $function, $args );
3277 $error = $this->lastError();
3278 $errno = $this->lastErrno();
3279 $sql = $this->lastQuery();
3282 if ( $this->wasDeadlock() ) {
3284 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3286 $this->reportQueryError( $error, $errno, $sql, $fname );
3289 } while ( $this->wasDeadlock() && --$tries > 0 );
3291 $this->ignoreErrors( $oldIgnore );
3293 if ( $tries <= 0 ) {
3294 $this->rollback( __METHOD__
);
3295 $this->reportQueryError( $error, $errno, $sql, $fname );
3299 $this->commit( __METHOD__
);
3306 * Wait for the slave to catch up to a given master position.
3308 * @param DBMasterPos $pos
3309 * @param int $timeout The maximum number of seconds to wait for
3311 * @return int Zero if the slave was past that position already,
3312 * greater than zero if we waited for some period of time, less than
3313 * zero if we timed out.
3315 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3316 # Real waits are implemented in the subclass.
3321 * Get the replication position of this slave
3323 * @return DBMasterPos|bool False if this is not a slave.
3325 public function getSlavePos() {
3331 * Get the position of this master
3333 * @return DBMasterPos|bool False if this is not a master
3335 public function getMasterPos() {
3341 * Run an anonymous function as soon as there is no transaction pending.
3342 * If there is a transaction and it is rolled back, then the callback is cancelled.
3343 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3344 * Callbacks must commit any transactions that they begin.
3346 * This is useful for updates to different systems or when separate transactions are needed.
3347 * For example, one might want to enqueue jobs into a system outside the database, but only
3348 * after the database is updated so that the jobs will see the data when they actually run.
3349 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3351 * @param callable $callback
3354 final public function onTransactionIdle( $callback ) {
3355 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3356 if ( !$this->mTrxLevel
) {
3357 $this->runOnTransactionIdleCallbacks();
3362 * Run an anonymous function before the current transaction commits or now if there is none.
3363 * If there is a transaction and it is rolled back, then the callback is cancelled.
3364 * Callbacks must not start nor commit any transactions.
3366 * This is useful for updates that easily cause deadlocks if locks are held too long
3367 * but where atomicity is strongly desired for these updates and some related updates.
3369 * @param callable $callback
3372 final public function onTransactionPreCommitOrIdle( $callback ) {
3373 if ( $this->mTrxLevel
) {
3374 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3376 $this->onTransactionIdle( $callback ); // this will trigger immediately
3381 * Actually any "on transaction idle" callbacks.
3385 protected function runOnTransactionIdleCallbacks() {
3386 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3388 $e = $ePrior = null; // last exception
3389 do { // callbacks may add callbacks :)
3390 $callbacks = $this->mTrxIdleCallbacks
;
3391 $this->mTrxIdleCallbacks
= array(); // recursion guard
3392 foreach ( $callbacks as $callback ) {
3394 list( $phpCallback ) = $callback;
3395 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3396 call_user_func( $phpCallback );
3397 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3398 } catch ( Exception
$e ) {
3400 MWExceptionHandler
::logException( $ePrior );
3405 } while ( count( $this->mTrxIdleCallbacks
) );
3407 if ( $e instanceof Exception
) {
3408 throw $e; // re-throw any last exception
3413 * Actually any "on transaction pre-commit" callbacks.
3417 protected function runOnTransactionPreCommitCallbacks() {
3418 $e = $ePrior = null; // last exception
3419 do { // callbacks may add callbacks :)
3420 $callbacks = $this->mTrxPreCommitCallbacks
;
3421 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3422 foreach ( $callbacks as $callback ) {
3424 list( $phpCallback ) = $callback;
3425 call_user_func( $phpCallback );
3426 } catch ( Exception
$e ) {
3428 MWExceptionHandler
::logException( $ePrior );
3433 } while ( count( $this->mTrxPreCommitCallbacks
) );
3435 if ( $e instanceof Exception
) {
3436 throw $e; // re-throw any last exception
3441 * Begin an atomic section of statements
3443 * If a transaction has been started already, just keep track of the given
3444 * section name to make sure the transaction is not committed pre-maturely.
3445 * This function can be used in layers (with sub-sections), so use a stack
3446 * to keep track of the different atomic sections. If there is no transaction,
3447 * start one implicitly.
3449 * The goal of this function is to create an atomic section of SQL queries
3450 * without having to start a new transaction if it already exists.
3452 * Atomic sections are more strict than transactions. With transactions,
3453 * attempting to begin a new transaction when one is already running results
3454 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3455 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3456 * and any database transactions cannot be began or committed until all atomic
3457 * levels are closed. There is no such thing as implicitly opening or closing
3458 * an atomic section.
3461 * @param string $fname
3464 final public function startAtomic( $fname = __METHOD__
) {
3465 if ( !$this->mTrxLevel
) {
3466 $this->begin( $fname );
3467 $this->mTrxAutomatic
= true;
3468 $this->mTrxAutomaticAtomic
= true;
3471 $this->mTrxAtomicLevels
->push( $fname );
3475 * Ends an atomic section of SQL statements
3477 * Ends the next section of atomic SQL statements and commits the transaction
3481 * @see DatabaseBase::startAtomic
3482 * @param string $fname
3485 final public function endAtomic( $fname = __METHOD__
) {
3486 if ( !$this->mTrxLevel
) {
3487 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3489 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3490 $this->mTrxAtomicLevels
->pop() !== $fname
3492 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3495 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3496 $this->commit( $fname, 'flush' );
3501 * Begin a transaction. If a transaction is already in progress,
3502 * that transaction will be committed before the new transaction is started.
3504 * Note that when the DBO_TRX flag is set (which is usually the case for web
3505 * requests, but not for maintenance scripts), any previous database query
3506 * will have started a transaction automatically.
3508 * Nesting of transactions is not supported. Attempts to nest transactions
3509 * will cause a warning, unless the current transaction was started
3510 * automatically because of the DBO_TRX flag.
3512 * @param string $fname
3515 final public function begin( $fname = __METHOD__
) {
3516 global $wgDebugDBTransactions;
3518 if ( $this->mTrxLevel
) { // implicit commit
3519 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3520 // If the current transaction was an automatic atomic one, then we definitely have
3521 // a problem. Same if there is any unclosed atomic level.
3522 throw new DBUnexpectedError( $this,
3523 "Attempted to start explicit transaction when atomic levels are still open."
3525 } elseif ( !$this->mTrxAutomatic
) {
3526 // We want to warn about inadvertently nested begin/commit pairs, but not about
3527 // auto-committing implicit transactions that were started by query() via DBO_TRX
3528 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3529 " performing implicit commit!";
3532 $this->getLogContext( array(
3533 'method' => __METHOD__
,
3538 // if the transaction was automatic and has done write operations,
3539 // log it if $wgDebugDBTransactions is enabled.
3540 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3541 wfDebug( "$fname: Automatic transaction with writes in progress" .
3542 " (from {$this->mTrxFname}), performing implicit commit!\n"
3547 $this->runOnTransactionPreCommitCallbacks();
3548 $this->doCommit( $fname );
3549 if ( $this->mTrxDoneWrites
) {
3550 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3551 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3553 $this->runOnTransactionIdleCallbacks();
3556 # Avoid fatals if close() was called
3557 if ( !$this->isOpen() ) {
3558 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3561 $this->doBegin( $fname );
3562 $this->mTrxTimestamp
= microtime( true );
3563 $this->mTrxFname
= $fname;
3564 $this->mTrxDoneWrites
= false;
3565 $this->mTrxAutomatic
= false;
3566 $this->mTrxAutomaticAtomic
= false;
3567 $this->mTrxAtomicLevels
= new SplStack
;
3568 $this->mTrxIdleCallbacks
= array();
3569 $this->mTrxPreCommitCallbacks
= array();
3570 $this->mTrxShortId
= wfRandomString( 12 );
3574 * Issues the BEGIN command to the database server.
3576 * @see DatabaseBase::begin()
3577 * @param string $fname
3579 protected function doBegin( $fname ) {
3580 $this->query( 'BEGIN', $fname );
3581 $this->mTrxLevel
= 1;
3585 * Commits a transaction previously started using begin().
3586 * If no transaction is in progress, a warning is issued.
3588 * Nesting of transactions is not supported.
3590 * @param string $fname
3591 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3592 * explicitly committing implicit transactions, or calling commit when no
3593 * transaction is in progress. This will silently break any ongoing
3594 * explicit transaction. Only set the flush flag if you are sure that it
3595 * is safe to ignore these warnings in your context.
3596 * @throws DBUnexpectedError
3598 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3599 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3600 // There are still atomic sections open. This cannot be ignored
3601 throw new DBUnexpectedError(
3603 "Attempted to commit transaction while atomic sections are still open"
3607 if ( $flush === 'flush' ) {
3608 if ( !$this->mTrxLevel
) {
3609 return; // nothing to do
3610 } elseif ( !$this->mTrxAutomatic
) {
3611 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3614 if ( !$this->mTrxLevel
) {
3615 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3616 return; // nothing to do
3617 } elseif ( $this->mTrxAutomatic
) {
3618 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3622 # Avoid fatals if close() was called
3623 if ( !$this->isOpen() ) {
3624 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3627 $this->runOnTransactionPreCommitCallbacks();
3628 $this->doCommit( $fname );
3629 if ( $this->mTrxDoneWrites
) {
3630 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3631 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3633 $this->runOnTransactionIdleCallbacks();
3637 * Issues the COMMIT command to the database server.
3639 * @see DatabaseBase::commit()
3640 * @param string $fname
3642 protected function doCommit( $fname ) {
3643 if ( $this->mTrxLevel
) {
3644 $this->query( 'COMMIT', $fname );
3645 $this->mTrxLevel
= 0;
3650 * Rollback a transaction previously started using begin().
3651 * If no transaction is in progress, a warning is issued.
3653 * No-op on non-transactional databases.
3655 * @param string $fname
3656 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3657 * calling rollback when no transaction is in progress. This will silently
3658 * break any ongoing explicit transaction. Only set the flush flag if you
3659 * are sure that it is safe to ignore these warnings in your context.
3660 * @since 1.23 Added $flush parameter
3662 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3663 if ( $flush !== 'flush' ) {
3664 if ( !$this->mTrxLevel
) {
3665 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3666 return; // nothing to do
3667 } elseif ( $this->mTrxAutomatic
) {
3668 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3671 if ( !$this->mTrxLevel
) {
3672 return; // nothing to do
3673 } elseif ( !$this->mTrxAutomatic
) {
3674 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3678 # Avoid fatals if close() was called
3679 if ( !$this->isOpen() ) {
3680 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3683 $this->doRollback( $fname );
3684 $this->mTrxIdleCallbacks
= array(); // cancel
3685 $this->mTrxPreCommitCallbacks
= array(); // cancel
3686 $this->mTrxAtomicLevels
= new SplStack
;
3687 if ( $this->mTrxDoneWrites
) {
3688 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3689 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3694 * Issues the ROLLBACK command to the database server.
3696 * @see DatabaseBase::rollback()
3697 * @param string $fname
3699 protected function doRollback( $fname ) {
3700 if ( $this->mTrxLevel
) {
3701 $this->query( 'ROLLBACK', $fname, true );
3702 $this->mTrxLevel
= 0;
3707 * Creates a new table with structure copied from existing table
3708 * Note that unlike most database abstraction functions, this function does not
3709 * automatically append database prefix, because it works at a lower
3710 * abstraction level.
3711 * The table names passed to this function shall not be quoted (this
3712 * function calls addIdentifierQuotes when needed).
3714 * @param string $oldName Name of table whose structure should be copied
3715 * @param string $newName Name of table to be created
3716 * @param bool $temporary Whether the new table should be temporary
3717 * @param string $fname Calling function name
3718 * @throws MWException
3719 * @return bool True if operation was successful
3721 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3724 throw new MWException(
3725 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3729 * List all tables on the database
3731 * @param string $prefix Only show tables with this prefix, e.g. mw_
3732 * @param string $fname Calling function name
3733 * @throws MWException
3735 function listTables( $prefix = null, $fname = __METHOD__
) {
3736 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3740 * Reset the views process cache set by listViews()
3743 final public function clearViewsCache() {
3744 $this->allViews
= null;
3748 * Lists all the VIEWs in the database
3750 * For caching purposes the list of all views should be stored in
3751 * $this->allViews. The process cache can be cleared with clearViewsCache()
3753 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3754 * @param string $fname Name of calling function
3755 * @throws MWException
3758 public function listViews( $prefix = null, $fname = __METHOD__
) {
3759 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3763 * Differentiates between a TABLE and a VIEW
3765 * @param string $name Name of the database-structure to test.
3766 * @throws MWException
3769 public function isView( $name ) {
3770 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3774 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3775 * to the format used for inserting into timestamp fields in this DBMS.
3777 * The result is unquoted, and needs to be passed through addQuotes()
3778 * before it can be included in raw SQL.
3780 * @param string|int $ts
3784 public function timestamp( $ts = 0 ) {
3785 return wfTimestamp( TS_MW
, $ts );
3789 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3790 * to the format used for inserting into timestamp fields in this DBMS. If
3791 * NULL is input, it is passed through, allowing NULL values to be inserted
3792 * into timestamp fields.
3794 * The result is unquoted, and needs to be passed through addQuotes()
3795 * before it can be included in raw SQL.
3797 * @param string|int $ts
3801 public function timestampOrNull( $ts = null ) {
3802 if ( is_null( $ts ) ) {
3805 return $this->timestamp( $ts );
3810 * Take the result from a query, and wrap it in a ResultWrapper if
3811 * necessary. Boolean values are passed through as is, to indicate success
3812 * of write queries or failure.
3814 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3815 * resource, and it was necessary to call this function to convert it to
3816 * a wrapper. Nowadays, raw database objects are never exposed to external
3817 * callers, so this is unnecessary in external code. For compatibility with
3818 * old code, ResultWrapper objects are passed through unaltered.
3820 * @param bool|ResultWrapper|resource $result
3821 * @return bool|ResultWrapper
3823 public function resultObject( $result ) {
3824 if ( empty( $result ) ) {
3826 } elseif ( $result instanceof ResultWrapper
) {
3828 } elseif ( $result === true ) {
3829 // Successful write query
3832 return new ResultWrapper( $this, $result );
3837 * Ping the server and try to reconnect if it there is no connection
3839 * @return bool Success or failure
3841 public function ping() {
3842 # Stub. Not essential to override.
3847 * Get slave lag. Currently supported only by MySQL.
3849 * Note that this function will generate a fatal error on many
3850 * installations. Most callers should use LoadBalancer::safeGetLag()
3853 * @return int Database replication lag in seconds
3855 public function getLag() {
3860 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3864 function maxListLen() {
3869 * Some DBMSs have a special format for inserting into blob fields, they
3870 * don't allow simple quoted strings to be inserted. To insert into such
3871 * a field, pass the data through this function before passing it to
3872 * DatabaseBase::insert().
3877 public function encodeBlob( $b ) {
3882 * Some DBMSs return a special placeholder object representing blob fields
3883 * in result objects. Pass the object through this function to return the
3889 public function decodeBlob( $b ) {
3894 * Override database's default behavior. $options include:
3895 * 'connTimeout' : Set the connection timeout value in seconds.
3896 * May be useful for very long batch queries such as
3897 * full-wiki dumps, where a single query reads out over
3900 * @param array $options
3903 public function setSessionOptions( array $options ) {
3907 * Read and execute SQL commands from a file.
3909 * Returns true on success, error string or exception on failure (depending
3910 * on object's error ignore settings).
3912 * @param string $filename File name to open
3913 * @param bool|callable $lineCallback Optional function called before reading each line
3914 * @param bool|callable $resultCallback Optional function called for each MySQL result
3915 * @param bool|string $fname Calling function name or false if name should be
3916 * generated dynamically using $filename
3917 * @param bool|callable $inputCallback Optional function called for each
3918 * complete line sent
3919 * @throws Exception|MWException
3920 * @return bool|string
3922 public function sourceFile(
3923 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3925 wfSuppressWarnings();
3926 $fp = fopen( $filename, 'r' );
3927 wfRestoreWarnings();
3929 if ( false === $fp ) {
3930 throw new MWException( "Could not open \"{$filename}\".\n" );
3934 $fname = __METHOD__
. "( $filename )";
3938 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3939 } catch ( MWException
$e ) {
3950 * Get the full path of a patch file. Originally based on archive()
3951 * from updaters.inc. Keep in mind this always returns a patch, as
3952 * it fails back to MySQL if no DB-specific patch can be found
3954 * @param string $patch The name of the patch, like patch-something.sql
3955 * @return string Full path to patch file
3957 public function patchPath( $patch ) {
3960 $dbType = $this->getType();
3961 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3962 return "$IP/maintenance/$dbType/archives/$patch";
3964 return "$IP/maintenance/archives/$patch";
3969 * Set variables to be used in sourceFile/sourceStream, in preference to the
3970 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3971 * all. If it's set to false, $GLOBALS will be used.
3973 * @param bool|array $vars Mapping variable name to value.
3975 public function setSchemaVars( $vars ) {
3976 $this->mSchemaVars
= $vars;
3980 * Read and execute commands from an open file handle.
3982 * Returns true on success, error string or exception on failure (depending
3983 * on object's error ignore settings).
3985 * @param resource $fp File handle
3986 * @param bool|callable $lineCallback Optional function called before reading each query
3987 * @param bool|callable $resultCallback Optional function called for each MySQL result
3988 * @param string $fname Calling function name
3989 * @param bool|callable $inputCallback Optional function called for each complete query sent
3990 * @return bool|string
3992 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3993 $fname = __METHOD__
, $inputCallback = false
3997 while ( !feof( $fp ) ) {
3998 if ( $lineCallback ) {
3999 call_user_func( $lineCallback );
4002 $line = trim( fgets( $fp ) );
4004 if ( $line == '' ) {
4008 if ( '-' == $line[0] && '-' == $line[1] ) {
4016 $done = $this->streamStatementEnd( $cmd, $line );
4020 if ( $done ||
feof( $fp ) ) {
4021 $cmd = $this->replaceVars( $cmd );
4023 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4024 $res = $this->query( $cmd, $fname );
4026 if ( $resultCallback ) {
4027 call_user_func( $resultCallback, $res, $this );
4030 if ( false === $res ) {
4031 $err = $this->lastError();
4033 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4044 * Called by sourceStream() to check if we've reached a statement end
4046 * @param string $sql SQL assembled so far
4047 * @param string $newLine New line about to be added to $sql
4048 * @return bool Whether $newLine contains end of the statement
4050 public function streamStatementEnd( &$sql, &$newLine ) {
4051 if ( $this->delimiter
) {
4053 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4054 if ( $newLine != $prev ) {
4063 * Database independent variable replacement. Replaces a set of variables
4064 * in an SQL statement with their contents as given by $this->getSchemaVars().
4066 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4068 * - '{$var}' should be used for text and is passed through the database's
4070 * - `{$var}` should be used for identifiers (e.g. table and database names).
4071 * It is passed through the database's addIdentifierQuotes method which
4072 * can be overridden if the database uses something other than backticks.
4073 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4074 * database's tableName method.
4075 * - / *i* / passes the name that follows through the database's indexName method.
4076 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4077 * its use should be avoided. In 1.24 and older, string encoding was applied.
4079 * @param string $ins SQL statement to replace variables in
4080 * @return string The new SQL statement with variables replaced
4082 protected function replaceVars( $ins ) {
4084 $vars = $this->getSchemaVars();
4085 return preg_replace_callback(
4087 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4088 \'\{\$ (\w+) }\' | # 3. addQuotes
4089 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4090 /\*\$ (\w+) \*/ # 5. leave unencoded
4092 function ( $m ) use ( $that, $vars ) {
4093 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4094 // check for both nonexistent keys *and* the empty string.
4095 if ( isset( $m[1] ) && $m[1] !== '' ) {
4096 if ( $m[1] === 'i' ) {
4097 return $that->indexName( $m[2] );
4099 return $that->tableName( $m[2] );
4101 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4102 return $that->addQuotes( $vars[$m[3]] );
4103 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4104 return $that->addIdentifierQuotes( $vars[$m[4]] );
4105 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4106 return $vars[$m[5]];
4116 * Get schema variables. If none have been set via setSchemaVars(), then
4117 * use some defaults from the current object.
4121 protected function getSchemaVars() {
4122 if ( $this->mSchemaVars
) {
4123 return $this->mSchemaVars
;
4125 return $this->getDefaultSchemaVars();
4130 * Get schema variables to use if none have been set via setSchemaVars().
4132 * Override this in derived classes to provide variables for tables.sql
4133 * and SQL patch files.
4137 protected function getDefaultSchemaVars() {
4142 * Check to see if a named lock is available. This is non-blocking.
4144 * @param string $lockName Name of lock to poll
4145 * @param string $method Name of method calling us
4149 public function lockIsFree( $lockName, $method ) {
4154 * Acquire a named lock
4156 * Abstracted from Filestore::lock() so child classes can implement for
4159 * @param string $lockName Name of lock to aquire
4160 * @param string $method Name of method calling us
4161 * @param int $timeout
4164 public function lock( $lockName, $method, $timeout = 5 ) {
4171 * @param string $lockName Name of lock to release
4172 * @param string $method Name of method calling us
4174 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4175 * by this thread (in which case the lock is not released), and NULL if the named
4176 * lock did not exist
4178 public function unlock( $lockName, $method ) {
4183 * Lock specific tables
4185 * @param array $read Array of tables to lock for read access
4186 * @param array $write Array of tables to lock for write access
4187 * @param string $method Name of caller
4188 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4191 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4196 * Unlock specific tables
4198 * @param string $method The caller
4201 public function unlockTables( $method ) {
4207 * @param string $tableName
4208 * @param string $fName
4209 * @return bool|ResultWrapper
4212 public function dropTable( $tableName, $fName = __METHOD__
) {
4213 if ( !$this->tableExists( $tableName, $fName ) ) {
4216 $sql = "DROP TABLE " . $this->tableName( $tableName );
4217 if ( $this->cascadingDeletes() ) {
4221 return $this->query( $sql, $fName );
4225 * Get search engine class. All subclasses of this need to implement this
4226 * if they wish to use searching.
4230 public function getSearchEngine() {
4231 return 'SearchEngineDummy';
4235 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4236 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4237 * because "i" sorts after all numbers.
4241 public function getInfinity() {
4246 * Encode an expiry time into the DBMS dependent format
4248 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4251 public function encodeExpiry( $expiry ) {
4252 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4253 ?
$this->getInfinity()
4254 : $this->timestamp( $expiry );
4258 * Decode an expiry time into a DBMS independent format
4260 * @param string $expiry DB timestamp field value for expiry
4261 * @param int $format TS_* constant, defaults to TS_MW
4264 public function decodeExpiry( $expiry, $format = TS_MW
) {
4265 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4267 : wfTimestamp( $format, $expiry );
4271 * Allow or deny "big selects" for this session only. This is done by setting
4272 * the sql_big_selects session variable.
4274 * This is a MySQL-specific feature.
4276 * @param bool|string $value True for allow, false for deny, or "default" to
4277 * restore the initial value
4279 public function setBigSelects( $value = true ) {
4287 public function __toString() {
4288 return (string)$this->mConn
;
4292 * Run a few simple sanity checks
4294 public function __destruct() {
4295 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4296 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4298 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4300 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4301 $callers[] = $callbackInfo[1];
4303 $callers = implode( ', ', $callers );
4304 trigger_error( "DB transaction callbacks still pending (from $callers)." );