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 * Determine whether a SQL statement is sensitive to isolation level.
1044 * A SQL statement is considered transactable if its result could vary
1045 * depending on the transaction isolation level. Operational commands
1046 * such as 'SET' and 'SHOW' are not considered to be transactable.
1048 * @param string $sql
1051 public function isTransactableQuery( $sql ) {
1052 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1053 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1057 * Run an SQL query and return the result. Normally throws a DBQueryError
1058 * on failure. If errors are ignored, returns false instead.
1060 * In new code, the query wrappers select(), insert(), update(), delete(),
1061 * etc. should be used where possible, since they give much better DBMS
1062 * independence and automatically quote or validate user input in a variety
1063 * of contexts. This function is generally only useful for queries which are
1064 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1067 * However, the query wrappers themselves should call this function.
1069 * @param string $sql SQL query
1070 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1071 * comment (you can use __METHOD__ or add some extra info)
1072 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1073 * maybe best to catch the exception instead?
1074 * @throws MWException
1075 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1076 * for a successful read query, or false on failure if $tempIgnore set
1078 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1079 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1081 $this->mLastQuery
= $sql;
1083 $isWriteQuery = $this->isWriteQuery( $sql );
1084 if ( $isWriteQuery ) {
1085 # Set a flag indicating that writes have been done
1086 wfDebug( __METHOD__
. ': Writes done: ' . DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1087 $this->mDoneWrites
= microtime( true );
1090 # Add a comment for easy SHOW PROCESSLIST interpretation
1091 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1092 $userName = $wgUser->getName();
1093 if ( mb_strlen( $userName ) > 15 ) {
1094 $userName = mb_substr( $userName, 0, 15 ) . '...';
1096 $userName = str_replace( '/', '', $userName );
1101 // Add trace comment to the begin of the sql string, right after the operator.
1102 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1103 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1105 if ( !$this->mTrxLevel
&& $this->getFlag( DBO_TRX
) && $this->isTransactableQuery( $sql ) ) {
1106 if ( $wgDebugDBTransactions ) {
1107 wfDebug( "Implicit transaction start.\n" );
1109 $this->begin( __METHOD__
. " ($fname)" );
1110 $this->mTrxAutomatic
= true;
1113 # Keep track of whether the transaction has write queries pending
1114 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $isWriteQuery ) {
1115 $this->mTrxDoneWrites
= true;
1116 Profiler
::instance()->getTransactionProfiler()->transactionWritingIn(
1117 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1122 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1124 $profiler = Profiler
::instance();
1125 if ( !$profiler instanceof ProfilerStub
) {
1126 # generalizeSQL will probably cut down the query to reasonable
1127 # logging size most of the time. The substr is really just a sanity check.
1129 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1130 $totalProf = 'DatabaseBase::query-master';
1132 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1133 $totalProf = 'DatabaseBase::query';
1135 # Include query transaction state
1136 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1138 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1139 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1142 if ( $this->debug() ) {
1146 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1148 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1150 $master = $isMaster ?
'master' : 'slave';
1151 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1154 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1156 # Avoid fatals if close() was called
1157 if ( !$this->isOpen() ) {
1158 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1161 # Log the query time and feed it into the DB trx profiler
1162 if ( $queryProf != '' ) {
1163 $queryStartTime = microtime( true );
1164 $queryProfile = new ScopedCallback(
1165 function () use ( $queryStartTime, $queryProf, $isMaster ) {
1166 $trxProfiler = Profiler
::instance()->getTransactionProfiler();
1167 $trxProfiler->recordQueryCompletion( $queryProf, $queryStartTime, $isMaster );
1172 # Do the query and handle errors
1173 $ret = $this->doQuery( $commentedSql );
1175 MWDebug
::queryTime( $queryId );
1177 # Try reconnecting if the connection was lost
1178 if ( false === $ret && $this->wasErrorReissuable() ) {
1179 # Transaction is gone, like it or not
1180 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1181 $this->mTrxLevel
= 0;
1182 $this->mTrxIdleCallbacks
= array(); // bug 65263
1183 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1184 wfDebug( "Connection lost, reconnecting...\n" );
1185 # Stash the last error values since ping() might clear them
1186 $lastError = $this->lastError();
1187 $lastErrno = $this->lastErrno();
1188 if ( $this->ping() ) {
1189 wfDebug( "Reconnected\n" );
1190 $server = $this->getServer();
1191 $msg = __METHOD__
. ": lost connection to $server; reconnected";
1192 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1195 # Leave $ret as false and let an error be reported.
1196 # Callers may catch the exception and continue to use the DB.
1197 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1199 # Should be safe to silently retry (no trx and thus no callbacks)
1200 $ret = $this->doQuery( $commentedSql );
1203 wfDebug( "Failed\n" );
1207 if ( false === $ret ) {
1208 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1210 $n = $this->affectedRows();
1211 if ( $isWriteQuery && $n > self
::LOG_WRITE_THRESHOLD
&& PHP_SAPI
!== 'cli' ) {
1212 wfDebugLog( 'DBPerformance',
1213 "Query affected $n rows:\n" .
1214 DatabaseBase
::generalizeSQL( $sql ) . "\n" . wfBacktrace( true ) );
1218 $res = $this->resultObject( $ret );
1220 // Destroy profile sections in the opposite order to their creation
1221 $queryProfSection = false;
1222 $totalProfSection = false;
1228 * Report a query error. Log the error, and if neither the object ignore
1229 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1231 * @param string $error
1233 * @param string $sql
1234 * @param string $fname
1235 * @param bool $tempIgnore
1236 * @throws DBQueryError
1238 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1239 # Ignore errors during error handling to avoid infinite recursion
1240 $ignore = $this->ignoreErrors( true );
1241 ++
$this->mErrorCount
;
1243 if ( $ignore ||
$tempIgnore ) {
1244 wfDebug( "SQL ERROR (ignored): $error\n" );
1245 $this->ignoreErrors( $ignore );
1247 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1249 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1250 $this->getLogContext( array(
1251 'method' => __METHOD__
,
1254 'sql1line' => $sql1line,
1258 wfDebug( "SQL ERROR: " . $error . "\n" );
1259 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1264 * Intended to be compatible with the PEAR::DB wrapper functions.
1265 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1267 * ? = scalar value, quoted as necessary
1268 * ! = raw SQL bit (a function for instance)
1269 * & = filename; reads the file and inserts as a blob
1270 * (we don't use this though...)
1272 * @param string $sql
1273 * @param string $func
1277 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1278 /* MySQL doesn't support prepared statements (yet), so just
1279 * pack up the query for reference. We'll manually replace
1282 return array( 'query' => $sql, 'func' => $func );
1286 * Free a prepared query, generated by prepare().
1287 * @param string $prepared
1289 protected function freePrepared( $prepared ) {
1290 /* No-op by default */
1294 * Execute a prepared query with the various arguments
1295 * @param string $prepared The prepared sql
1296 * @param mixed $args Either an array here, or put scalars as varargs
1298 * @return ResultWrapper
1300 public function execute( $prepared, $args = null ) {
1301 if ( !is_array( $args ) ) {
1303 $args = func_get_args();
1304 array_shift( $args );
1307 $sql = $this->fillPrepared( $prepared['query'], $args );
1309 return $this->query( $sql, $prepared['func'] );
1313 * For faking prepared SQL statements on DBs that don't support it directly.
1315 * @param string $preparedQuery A 'preparable' SQL statement
1316 * @param array $args Array of Arguments to fill it with
1317 * @return string Executable SQL
1319 public function fillPrepared( $preparedQuery, $args ) {
1321 $this->preparedArgs
=& $args;
1323 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1324 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1328 * preg_callback func for fillPrepared()
1329 * The arguments should be in $this->preparedArgs and must not be touched
1330 * while we're doing this.
1332 * @param array $matches
1333 * @throws DBUnexpectedError
1336 protected function fillPreparedArg( $matches ) {
1337 switch ( $matches[1] ) {
1346 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1348 switch ( $matches[1] ) {
1350 return $this->addQuotes( $arg );
1354 # return $this->addQuotes( file_get_contents( $arg ) );
1355 throw new DBUnexpectedError(
1357 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1360 throw new DBUnexpectedError(
1362 'Received invalid match. This should never happen!'
1368 * Free a result object returned by query() or select(). It's usually not
1369 * necessary to call this, just use unset() or let the variable holding
1370 * the result object go out of scope.
1372 * @param mixed $res A SQL result
1374 public function freeResult( $res ) {
1378 * A SELECT wrapper which returns a single field from a single result row.
1380 * Usually throws a DBQueryError on failure. If errors are explicitly
1381 * ignored, returns false on failure.
1383 * If no result rows are returned from the query, false is returned.
1385 * @param string|array $table Table name. See DatabaseBase::select() for details.
1386 * @param string $var The field name to select. This must be a valid SQL
1387 * fragment: do not use unvalidated user input.
1388 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1389 * @param string $fname The function name of the caller.
1390 * @param string|array $options The query options. See DatabaseBase::select() for details.
1392 * @return bool|mixed The value from the field, or false on failure.
1394 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1397 if ( !is_array( $options ) ) {
1398 $options = array( $options );
1401 $options['LIMIT'] = 1;
1403 $res = $this->select( $table, $var, $cond, $fname, $options );
1405 if ( $res === false ||
!$this->numRows( $res ) ) {
1409 $row = $this->fetchRow( $res );
1411 if ( $row !== false ) {
1412 return reset( $row );
1419 * Returns an optional USE INDEX clause to go after the table, and a
1420 * string to go at the end of the query.
1422 * @param array $options Associative array of options to be turned into
1423 * an SQL query, valid keys are listed in the function.
1425 * @see DatabaseBase::select()
1427 public function makeSelectOptions( $options ) {
1428 $preLimitTail = $postLimitTail = '';
1431 $noKeyOptions = array();
1433 foreach ( $options as $key => $option ) {
1434 if ( is_numeric( $key ) ) {
1435 $noKeyOptions[$option] = true;
1439 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1441 $preLimitTail .= $this->makeOrderBy( $options );
1443 // if (isset($options['LIMIT'])) {
1444 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1445 // isset($options['OFFSET']) ? $options['OFFSET']
1449 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1450 $postLimitTail .= ' FOR UPDATE';
1453 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1454 $postLimitTail .= ' LOCK IN SHARE MODE';
1457 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1458 $startOpts .= 'DISTINCT';
1461 # Various MySQL extensions
1462 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1463 $startOpts .= ' /*! STRAIGHT_JOIN */';
1466 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1467 $startOpts .= ' HIGH_PRIORITY';
1470 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1471 $startOpts .= ' SQL_BIG_RESULT';
1474 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1475 $startOpts .= ' SQL_BUFFER_RESULT';
1478 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1479 $startOpts .= ' SQL_SMALL_RESULT';
1482 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1483 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1486 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1487 $startOpts .= ' SQL_CACHE';
1490 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1491 $startOpts .= ' SQL_NO_CACHE';
1494 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1495 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1500 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1504 * Returns an optional GROUP BY with an optional HAVING
1506 * @param array $options Associative array of options
1508 * @see DatabaseBase::select()
1511 public function makeGroupByWithHaving( $options ) {
1513 if ( isset( $options['GROUP BY'] ) ) {
1514 $gb = is_array( $options['GROUP BY'] )
1515 ?
implode( ',', $options['GROUP BY'] )
1516 : $options['GROUP BY'];
1517 $sql .= ' GROUP BY ' . $gb;
1519 if ( isset( $options['HAVING'] ) ) {
1520 $having = is_array( $options['HAVING'] )
1521 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1522 : $options['HAVING'];
1523 $sql .= ' HAVING ' . $having;
1530 * Returns an optional ORDER BY
1532 * @param array $options Associative array of options
1534 * @see DatabaseBase::select()
1537 public function makeOrderBy( $options ) {
1538 if ( isset( $options['ORDER BY'] ) ) {
1539 $ob = is_array( $options['ORDER BY'] )
1540 ?
implode( ',', $options['ORDER BY'] )
1541 : $options['ORDER BY'];
1543 return ' ORDER BY ' . $ob;
1550 * Execute a SELECT query constructed using the various parameters provided.
1551 * See below for full details of the parameters.
1553 * @param string|array $table Table name
1554 * @param string|array $vars Field names
1555 * @param string|array $conds Conditions
1556 * @param string $fname Caller function name
1557 * @param array $options Query options
1558 * @param array $join_conds Join conditions
1561 * @param string|array $table
1563 * May be either an array of table names, or a single string holding a table
1564 * name. If an array is given, table aliases can be specified, for example:
1566 * array( 'a' => 'user' )
1568 * This includes the user table in the query, with the alias "a" available
1569 * for use in field names (e.g. a.user_name).
1571 * All of the table names given here are automatically run through
1572 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1573 * added, and various other table name mappings to be performed.
1576 * @param string|array $vars
1578 * May be either a field name or an array of field names. The field names
1579 * can be complete fragments of SQL, for direct inclusion into the SELECT
1580 * query. If an array is given, field aliases can be specified, for example:
1582 * array( 'maxrev' => 'MAX(rev_id)' )
1584 * This includes an expression with the alias "maxrev" in the query.
1586 * If an expression is given, care must be taken to ensure that it is
1590 * @param string|array $conds
1592 * May be either a string containing a single condition, or an array of
1593 * conditions. If an array is given, the conditions constructed from each
1594 * element are combined with AND.
1596 * Array elements may take one of two forms:
1598 * - Elements with a numeric key are interpreted as raw SQL fragments.
1599 * - Elements with a string key are interpreted as equality conditions,
1600 * where the key is the field name.
1601 * - If the value of such an array element is a scalar (such as a
1602 * string), it will be treated as data and thus quoted appropriately.
1603 * If it is null, an IS NULL clause will be added.
1604 * - If the value is an array, an IN(...) clause will be constructed,
1605 * such that the field name may match any of the elements in the
1606 * array. The elements of the array will be quoted.
1608 * Note that expressions are often DBMS-dependent in their syntax.
1609 * DBMS-independent wrappers are provided for constructing several types of
1610 * expression commonly used in condition queries. See:
1611 * - DatabaseBase::buildLike()
1612 * - DatabaseBase::conditional()
1615 * @param string|array $options
1617 * Optional: Array of query options. Boolean options are specified by
1618 * including them in the array as a string value with a numeric key, for
1621 * array( 'FOR UPDATE' )
1623 * The supported options are:
1625 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1626 * with LIMIT can theoretically be used for paging through a result set,
1627 * but this is discouraged in MediaWiki for performance reasons.
1629 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1630 * and then the first rows are taken until the limit is reached. LIMIT
1631 * is applied to a result set after OFFSET.
1633 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1634 * changed until the next COMMIT.
1636 * - DISTINCT: Boolean: return only unique result rows.
1638 * - GROUP BY: May be either an SQL fragment string naming a field or
1639 * expression to group by, or an array of such SQL fragments.
1641 * - HAVING: May be either an string containing a HAVING clause or an array of
1642 * conditions building the HAVING clause. If an array is given, the conditions
1643 * constructed from each element are combined with AND.
1645 * - ORDER BY: May be either an SQL fragment giving a field name or
1646 * expression to order by, or an array of such SQL fragments.
1648 * - USE INDEX: This may be either a string giving the index name to use
1649 * for the query, or an array. If it is an associative array, each key
1650 * gives the table name (or alias), each value gives the index name to
1651 * use for that table. All strings are SQL fragments and so should be
1652 * validated by the caller.
1654 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1655 * instead of SELECT.
1657 * And also the following boolean MySQL extensions, see the MySQL manual
1658 * for documentation:
1660 * - LOCK IN SHARE MODE
1664 * - SQL_BUFFER_RESULT
1665 * - SQL_SMALL_RESULT
1666 * - SQL_CALC_FOUND_ROWS
1671 * @param string|array $join_conds
1673 * Optional associative array of table-specific join conditions. In the
1674 * most common case, this is unnecessary, since the join condition can be
1675 * in $conds. However, it is useful for doing a LEFT JOIN.
1677 * The key of the array contains the table name or alias. The value is an
1678 * array with two elements, numbered 0 and 1. The first gives the type of
1679 * join, the second is an SQL fragment giving the join condition for that
1680 * table. For example:
1682 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1684 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1685 * with no rows in it will be returned. If there was a query error, a
1686 * DBQueryError exception will be thrown, except if the "ignore errors"
1687 * option was set, in which case false will be returned.
1689 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1690 $options = array(), $join_conds = array() ) {
1691 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1693 return $this->query( $sql, $fname );
1697 * The equivalent of DatabaseBase::select() except that the constructed SQL
1698 * is returned, instead of being immediately executed. This can be useful for
1699 * doing UNION queries, where the SQL text of each query is needed. In general,
1700 * however, callers outside of Database classes should just use select().
1702 * @param string|array $table Table name
1703 * @param string|array $vars Field names
1704 * @param string|array $conds Conditions
1705 * @param string $fname Caller function name
1706 * @param string|array $options Query options
1707 * @param string|array $join_conds Join conditions
1709 * @return string SQL query string.
1710 * @see DatabaseBase::select()
1712 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1713 $options = array(), $join_conds = array()
1715 if ( is_array( $vars ) ) {
1716 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1719 $options = (array)$options;
1720 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1721 ?
$options['USE INDEX']
1724 if ( is_array( $table ) ) {
1726 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1727 } elseif ( $table != '' ) {
1728 if ( $table[0] == ' ' ) {
1729 $from = ' FROM ' . $table;
1732 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1738 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1739 $this->makeSelectOptions( $options );
1741 if ( !empty( $conds ) ) {
1742 if ( is_array( $conds ) ) {
1743 $conds = $this->makeList( $conds, LIST_AND
);
1745 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1747 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1750 if ( isset( $options['LIMIT'] ) ) {
1751 $sql = $this->limitResult( $sql, $options['LIMIT'],
1752 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1754 $sql = "$sql $postLimitTail";
1756 if ( isset( $options['EXPLAIN'] ) ) {
1757 $sql = 'EXPLAIN ' . $sql;
1764 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1765 * that a single row object is returned. If the query returns no rows,
1766 * false is returned.
1768 * @param string|array $table Table name
1769 * @param string|array $vars Field names
1770 * @param array $conds Conditions
1771 * @param string $fname Caller function name
1772 * @param string|array $options Query options
1773 * @param array|string $join_conds Join conditions
1775 * @return stdClass|bool
1777 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1778 $options = array(), $join_conds = array()
1780 $options = (array)$options;
1781 $options['LIMIT'] = 1;
1782 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1784 if ( $res === false ) {
1788 if ( !$this->numRows( $res ) ) {
1792 $obj = $this->fetchObject( $res );
1798 * Estimate the number of rows in dataset
1800 * MySQL allows you to estimate the number of rows that would be returned
1801 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1802 * index cardinality statistics, and is notoriously inaccurate, especially
1803 * when large numbers of rows have recently been added or deleted.
1805 * For DBMSs that don't support fast result size estimation, this function
1806 * will actually perform the SELECT COUNT(*).
1808 * Takes the same arguments as DatabaseBase::select().
1810 * @param string $table Table name
1811 * @param string $vars Unused
1812 * @param array|string $conds Filters on the table
1813 * @param string $fname Function name for profiling
1814 * @param array $options Options for select
1815 * @return int Row count
1817 public function estimateRowCount(
1818 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1821 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1824 $row = $this->fetchRow( $res );
1825 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1832 * Get the number of rows in dataset
1834 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1836 * Takes the same arguments as DatabaseBase::select().
1838 * @param string $table Table name
1839 * @param string $vars Unused
1840 * @param array|string $conds Filters on the table
1841 * @param string $fname Function name for profiling
1842 * @param array $options Options for select
1843 * @return int Row count
1846 public function selectRowCount(
1847 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1850 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1851 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1854 $row = $this->fetchRow( $res );
1855 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1862 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1863 * It's only slightly flawed. Don't use for anything important.
1865 * @param string $sql A SQL Query
1869 static function generalizeSQL( $sql ) {
1870 # This does the same as the regexp below would do, but in such a way
1871 # as to avoid crashing php on some large strings.
1872 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1874 $sql = str_replace( "\\\\", '', $sql );
1875 $sql = str_replace( "\\'", '', $sql );
1876 $sql = str_replace( "\\\"", '', $sql );
1877 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1878 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1880 # All newlines, tabs, etc replaced by single space
1881 $sql = preg_replace( '/\s+/', ' ', $sql );
1884 # except the ones surrounded by characters, e.g. l10n
1885 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1886 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1892 * Determines whether a field exists in a table
1894 * @param string $table Table name
1895 * @param string $field Filed to check on that table
1896 * @param string $fname Calling function name (optional)
1897 * @return bool Whether $table has filed $field
1899 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1900 $info = $this->fieldInfo( $table, $field );
1906 * Determines whether an index exists
1907 * Usually throws a DBQueryError on failure
1908 * If errors are explicitly ignored, returns NULL on failure
1910 * @param string $table
1911 * @param string $index
1912 * @param string $fname
1915 public function indexExists( $table, $index, $fname = __METHOD__
) {
1916 if ( !$this->tableExists( $table ) ) {
1920 $info = $this->indexInfo( $table, $index, $fname );
1921 if ( is_null( $info ) ) {
1924 return $info !== false;
1929 * Query whether a given table exists
1931 * @param string $table
1932 * @param string $fname
1935 public function tableExists( $table, $fname = __METHOD__
) {
1936 $table = $this->tableName( $table );
1937 $old = $this->ignoreErrors( true );
1938 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1939 $this->ignoreErrors( $old );
1945 * Determines if a given index is unique
1947 * @param string $table
1948 * @param string $index
1952 public function indexUnique( $table, $index ) {
1953 $indexInfo = $this->indexInfo( $table, $index );
1955 if ( !$indexInfo ) {
1959 return !$indexInfo[0]->Non_unique
;
1963 * Helper for DatabaseBase::insert().
1965 * @param array $options
1968 protected function makeInsertOptions( $options ) {
1969 return implode( ' ', $options );
1973 * INSERT wrapper, inserts an array into a table.
1977 * - A single associative array. The array keys are the field names, and
1978 * the values are the values to insert. The values are treated as data
1979 * and will be quoted appropriately. If NULL is inserted, this will be
1980 * converted to a database NULL.
1981 * - An array with numeric keys, holding a list of associative arrays.
1982 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1983 * each subarray must be identical to each other, and in the same order.
1985 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1988 * $options is an array of options, with boolean options encoded as values
1989 * with numeric keys, in the same style as $options in
1990 * DatabaseBase::select(). Supported options are:
1992 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1993 * any rows which cause duplicate key errors are not inserted. It's
1994 * possible to determine how many rows were successfully inserted using
1995 * DatabaseBase::affectedRows().
1997 * @param string $table Table name. This will be passed through
1998 * DatabaseBase::tableName().
1999 * @param array $a Array of rows to insert
2000 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2001 * @param array $options Array of options
2005 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
2006 # No rows to insert, easy just return now
2007 if ( !count( $a ) ) {
2011 $table = $this->tableName( $table );
2013 if ( !is_array( $options ) ) {
2014 $options = array( $options );
2018 if ( isset( $options['fileHandle'] ) ) {
2019 $fh = $options['fileHandle'];
2021 $options = $this->makeInsertOptions( $options );
2023 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2025 $keys = array_keys( $a[0] );
2028 $keys = array_keys( $a );
2031 $sql = 'INSERT ' . $options .
2032 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2036 foreach ( $a as $row ) {
2042 $sql .= '(' . $this->makeList( $row ) . ')';
2045 $sql .= '(' . $this->makeList( $a ) . ')';
2048 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2050 } elseif ( $fh !== null ) {
2054 return (bool)$this->query( $sql, $fname );
2058 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2060 * @param array $options
2063 protected function makeUpdateOptionsArray( $options ) {
2064 if ( !is_array( $options ) ) {
2065 $options = array( $options );
2070 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2071 $opts[] = $this->lowPriorityOption();
2074 if ( in_array( 'IGNORE', $options ) ) {
2082 * Make UPDATE options for the DatabaseBase::update function
2084 * @param array $options The options passed to DatabaseBase::update
2087 protected function makeUpdateOptions( $options ) {
2088 $opts = $this->makeUpdateOptionsArray( $options );
2090 return implode( ' ', $opts );
2094 * UPDATE wrapper. Takes a condition array and a SET array.
2096 * @param string $table Name of the table to UPDATE. This will be passed through
2097 * DatabaseBase::tableName().
2098 * @param array $values An array of values to SET. For each array element,
2099 * the key gives the field name, and the value gives the data to set
2100 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2101 * @param array $conds An array of conditions (WHERE). See
2102 * DatabaseBase::select() for the details of the format of condition
2103 * arrays. Use '*' to update all rows.
2104 * @param string $fname The function name of the caller (from __METHOD__),
2105 * for logging and profiling.
2106 * @param array $options An array of UPDATE options, can be:
2107 * - IGNORE: Ignore unique key conflicts
2108 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2111 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2112 $table = $this->tableName( $table );
2113 $opts = $this->makeUpdateOptions( $options );
2114 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2116 if ( $conds !== array() && $conds !== '*' ) {
2117 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2120 return $this->query( $sql, $fname );
2124 * Makes an encoded list of strings from an array
2126 * @param array $a Containing the data
2127 * @param int $mode Constant
2128 * - LIST_COMMA: Comma separated, no field names
2129 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2130 * documentation for $conds in DatabaseBase::select().
2131 * - LIST_OR: ORed WHERE clause (without the WHERE)
2132 * - LIST_SET: Comma separated with field names, like a SET clause
2133 * - LIST_NAMES: Comma separated field names
2134 * @throws MWException|DBUnexpectedError
2137 public function makeList( $a, $mode = LIST_COMMA
) {
2138 if ( !is_array( $a ) ) {
2139 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2145 foreach ( $a as $field => $value ) {
2147 if ( $mode == LIST_AND
) {
2149 } elseif ( $mode == LIST_OR
) {
2158 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2159 $list .= "($value)";
2160 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2162 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2163 // Remove null from array to be handled separately if found
2164 $includeNull = false;
2165 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2166 $includeNull = true;
2167 unset( $value[$nullKey] );
2169 if ( count( $value ) == 0 && !$includeNull ) {
2170 throw new MWException( __METHOD__
. ": empty input for field $field" );
2171 } elseif ( count( $value ) == 0 ) {
2172 // only check if $field is null
2173 $list .= "$field IS NULL";
2175 // IN clause contains at least one valid element
2176 if ( $includeNull ) {
2177 // Group subconditions to ensure correct precedence
2180 if ( count( $value ) == 1 ) {
2181 // Special-case single values, as IN isn't terribly efficient
2182 // Don't necessarily assume the single key is 0; we don't
2183 // enforce linear numeric ordering on other arrays here.
2184 $value = array_values( $value );
2185 $list .= $field . " = " . $this->addQuotes( $value[0] );
2187 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2189 // if null present in array, append IS NULL
2190 if ( $includeNull ) {
2191 $list .= " OR $field IS NULL)";
2194 } elseif ( $value === null ) {
2195 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2196 $list .= "$field IS ";
2197 } elseif ( $mode == LIST_SET
) {
2198 $list .= "$field = ";
2202 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2203 $list .= "$field = ";
2205 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2213 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2214 * The keys on each level may be either integers or strings.
2216 * @param array $data Organized as 2-d
2217 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2218 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2219 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2220 * @return string|bool SQL fragment, or false if no items in array
2222 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2225 foreach ( $data as $base => $sub ) {
2226 if ( count( $sub ) ) {
2227 $conds[] = $this->makeList(
2228 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2234 return $this->makeList( $conds, LIST_OR
);
2236 // Nothing to search for...
2242 * Return aggregated value alias
2244 * @param array $valuedata
2245 * @param string $valuename
2249 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2254 * @param string $field
2257 public function bitNot( $field ) {
2262 * @param string $fieldLeft
2263 * @param string $fieldRight
2266 public function bitAnd( $fieldLeft, $fieldRight ) {
2267 return "($fieldLeft & $fieldRight)";
2271 * @param string $fieldLeft
2272 * @param string $fieldRight
2275 public function bitOr( $fieldLeft, $fieldRight ) {
2276 return "($fieldLeft | $fieldRight)";
2280 * Build a concatenation list to feed into a SQL query
2281 * @param array $stringList List of raw SQL expressions; caller is
2282 * responsible for any quoting
2285 public function buildConcat( $stringList ) {
2286 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2290 * Build a GROUP_CONCAT or equivalent statement for a query.
2292 * This is useful for combining a field for several rows into a single string.
2293 * NULL values will not appear in the output, duplicated values will appear,
2294 * and the resulting delimiter-separated values have no defined sort order.
2295 * Code using the results may need to use the PHP unique() or sort() methods.
2297 * @param string $delim Glue to bind the results together
2298 * @param string|array $table Table name
2299 * @param string $field Field name
2300 * @param string|array $conds Conditions
2301 * @param string|array $join_conds Join conditions
2302 * @return string SQL text
2305 public function buildGroupConcatField(
2306 $delim, $table, $field, $conds = '', $join_conds = array()
2308 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2310 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2314 * Change the current database
2316 * @todo Explain what exactly will fail if this is not overridden.
2320 * @return bool Success or failure
2322 public function selectDB( $db ) {
2323 # Stub. Shouldn't cause serious problems if it's not overridden, but
2324 # if your database engine supports a concept similar to MySQL's
2325 # databases you may as well.
2326 $this->mDBname
= $db;
2332 * Get the current DB name
2335 public function getDBname() {
2336 return $this->mDBname
;
2340 * Get the server hostname or IP address
2343 public function getServer() {
2344 return $this->mServer
;
2348 * Format a table name ready for use in constructing an SQL query
2350 * This does two important things: it quotes the table names to clean them up,
2351 * and it adds a table prefix if only given a table name with no quotes.
2353 * All functions of this object which require a table name call this function
2354 * themselves. Pass the canonical name to such functions. This is only needed
2355 * when calling query() directly.
2357 * @param string $name Database table name
2358 * @param string $format One of:
2359 * quoted - Automatically pass the table name through addIdentifierQuotes()
2360 * so that it can be used in a query.
2361 * raw - Do not add identifier quotes to the table name
2362 * @return string Full database name
2364 public function tableName( $name, $format = 'quoted' ) {
2365 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2366 # Skip the entire process when we have a string quoted on both ends.
2367 # Note that we check the end so that we will still quote any use of
2368 # use of `database`.table. But won't break things if someone wants
2369 # to query a database table with a dot in the name.
2370 if ( $this->isQuotedIdentifier( $name ) ) {
2374 # Lets test for any bits of text that should never show up in a table
2375 # name. Basically anything like JOIN or ON which are actually part of
2376 # SQL queries, but may end up inside of the table value to combine
2377 # sql. Such as how the API is doing.
2378 # Note that we use a whitespace test rather than a \b test to avoid
2379 # any remote case where a word like on may be inside of a table name
2380 # surrounded by symbols which may be considered word breaks.
2381 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2385 # Split database and table into proper variables.
2386 # We reverse the explode so that database.table and table both output
2387 # the correct table.
2388 $dbDetails = explode( '.', $name, 3 );
2389 if ( count( $dbDetails ) == 3 ) {
2390 list( $database, $schema, $table ) = $dbDetails;
2391 # We don't want any prefix added in this case
2393 } elseif ( count( $dbDetails ) == 2 ) {
2394 list( $database, $table ) = $dbDetails;
2395 # We don't want any prefix added in this case
2396 # In dbs that support it, $database may actually be the schema
2397 # but that doesn't affect any of the functionality here
2401 list( $table ) = $dbDetails;
2402 if ( $wgSharedDB !== null # We have a shared database
2403 && $this->mForeign
== false # We're not working on a foreign database
2404 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2405 && in_array( $table, $wgSharedTables ) # A shared table is selected
2407 $database = $wgSharedDB;
2408 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2409 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2412 $schema = $this->mSchema
; # Default schema
2413 $prefix = $this->mTablePrefix
; # Default prefix
2417 # Quote $table and apply the prefix if not quoted.
2418 # $tableName might be empty if this is called from Database::replaceVars()
2419 $tableName = "{$prefix}{$table}";
2420 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2421 $tableName = $this->addIdentifierQuotes( $tableName );
2424 # Quote $schema and merge it with the table name if needed
2425 if ( $schema !== null ) {
2426 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2427 $schema = $this->addIdentifierQuotes( $schema );
2429 $tableName = $schema . '.' . $tableName;
2432 # Quote $database and merge it with the table name if needed
2433 if ( $database !== null ) {
2434 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2435 $database = $this->addIdentifierQuotes( $database );
2437 $tableName = $database . '.' . $tableName;
2444 * Fetch a number of table names into an array
2445 * This is handy when you need to construct SQL for joins
2448 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2449 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2450 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2454 public function tableNames() {
2455 $inArray = func_get_args();
2458 foreach ( $inArray as $name ) {
2459 $retVal[$name] = $this->tableName( $name );
2466 * Fetch a number of table names into an zero-indexed numerical array
2467 * This is handy when you need to construct SQL for joins
2470 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2471 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2472 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2476 public function tableNamesN() {
2477 $inArray = func_get_args();
2480 foreach ( $inArray as $name ) {
2481 $retVal[] = $this->tableName( $name );
2488 * Get an aliased table name
2489 * e.g. tableName AS newTableName
2491 * @param string $name Table name, see tableName()
2492 * @param string|bool $alias Alias (optional)
2493 * @return string SQL name for aliased table. Will not alias a table to its own name
2495 public function tableNameWithAlias( $name, $alias = false ) {
2496 if ( !$alias ||
$alias == $name ) {
2497 return $this->tableName( $name );
2499 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2504 * Gets an array of aliased table names
2506 * @param array $tables Array( [alias] => table )
2507 * @return string[] See tableNameWithAlias()
2509 public function tableNamesWithAlias( $tables ) {
2511 foreach ( $tables as $alias => $table ) {
2512 if ( is_numeric( $alias ) ) {
2515 $retval[] = $this->tableNameWithAlias( $table, $alias );
2522 * Get an aliased field name
2523 * e.g. fieldName AS newFieldName
2525 * @param string $name Field name
2526 * @param string|bool $alias Alias (optional)
2527 * @return string SQL name for aliased field. Will not alias a field to its own name
2529 public function fieldNameWithAlias( $name, $alias = false ) {
2530 if ( !$alias ||
(string)$alias === (string)$name ) {
2533 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2538 * Gets an array of aliased field names
2540 * @param array $fields Array( [alias] => field )
2541 * @return string[] See fieldNameWithAlias()
2543 public function fieldNamesWithAlias( $fields ) {
2545 foreach ( $fields as $alias => $field ) {
2546 if ( is_numeric( $alias ) ) {
2549 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2556 * Get the aliased table name clause for a FROM clause
2557 * which might have a JOIN and/or USE INDEX clause
2559 * @param array $tables ( [alias] => table )
2560 * @param array $use_index Same as for select()
2561 * @param array $join_conds Same as for select()
2564 protected function tableNamesWithUseIndexOrJOIN(
2565 $tables, $use_index = array(), $join_conds = array()
2569 $use_index = (array)$use_index;
2570 $join_conds = (array)$join_conds;
2572 foreach ( $tables as $alias => $table ) {
2573 if ( !is_string( $alias ) ) {
2574 // No alias? Set it equal to the table name
2577 // Is there a JOIN clause for this table?
2578 if ( isset( $join_conds[$alias] ) ) {
2579 list( $joinType, $conds ) = $join_conds[$alias];
2580 $tableClause = $joinType;
2581 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2582 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2583 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2585 $tableClause .= ' ' . $use;
2588 $on = $this->makeList( (array)$conds, LIST_AND
);
2590 $tableClause .= ' ON (' . $on . ')';
2593 $retJOIN[] = $tableClause;
2594 } elseif ( isset( $use_index[$alias] ) ) {
2595 // Is there an INDEX clause for this table?
2596 $tableClause = $this->tableNameWithAlias( $table, $alias );
2597 $tableClause .= ' ' . $this->useIndexClause(
2598 implode( ',', (array)$use_index[$alias] )
2601 $ret[] = $tableClause;
2603 $tableClause = $this->tableNameWithAlias( $table, $alias );
2605 $ret[] = $tableClause;
2609 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2610 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2611 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2613 // Compile our final table clause
2614 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2618 * Get the name of an index in a given table.
2620 * @protected Don't use outside of DatabaseBase and childs
2621 * @param string $index
2624 public function indexName( $index ) {
2625 // @FIXME: Make this protected once we move away from PHP 5.3
2626 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2628 // Backwards-compatibility hack
2630 'ar_usertext_timestamp' => 'usertext_timestamp',
2631 'un_user_id' => 'user_id',
2632 'un_user_ip' => 'user_ip',
2635 if ( isset( $renamed[$index] ) ) {
2636 return $renamed[$index];
2643 * Adds quotes and backslashes.
2648 public function addQuotes( $s ) {
2649 if ( $s === null ) {
2652 # This will also quote numeric values. This should be harmless,
2653 # and protects against weird problems that occur when they really
2654 # _are_ strings such as article titles and string->number->string
2655 # conversion is not 1:1.
2656 return "'" . $this->strencode( $s ) . "'";
2661 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2662 * MySQL uses `backticks` while basically everything else uses double quotes.
2663 * Since MySQL is the odd one out here the double quotes are our generic
2664 * and we implement backticks in DatabaseMysql.
2669 public function addIdentifierQuotes( $s ) {
2670 return '"' . str_replace( '"', '""', $s ) . '"';
2674 * Returns if the given identifier looks quoted or not according to
2675 * the database convention for quoting identifiers .
2677 * @param string $name
2680 public function isQuotedIdentifier( $name ) {
2681 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2688 protected function escapeLikeInternal( $s ) {
2689 return addcslashes( $s, '\%_' );
2693 * LIKE statement wrapper, receives a variable-length argument list with
2694 * parts of pattern to match containing either string literals that will be
2695 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2696 * the function could be provided with an array of aforementioned
2699 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2700 * a LIKE clause that searches for subpages of 'My page title'.
2702 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2703 * $query .= $dbr->buildLike( $pattern );
2706 * @return string Fully built LIKE statement
2708 public function buildLike() {
2709 $params = func_get_args();
2711 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2712 $params = $params[0];
2717 foreach ( $params as $value ) {
2718 if ( $value instanceof LikeMatch
) {
2719 $s .= $value->toString();
2721 $s .= $this->escapeLikeInternal( $value );
2725 return " LIKE {$this->addQuotes( $s )} ";
2729 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2733 public function anyChar() {
2734 return new LikeMatch( '_' );
2738 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2742 public function anyString() {
2743 return new LikeMatch( '%' );
2747 * Returns an appropriately quoted sequence value for inserting a new row.
2748 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2749 * subclass will return an integer, and save the value for insertId()
2751 * Any implementation of this function should *not* involve reusing
2752 * sequence numbers created for rolled-back transactions.
2753 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2754 * @param string $seqName
2757 public function nextSequenceValue( $seqName ) {
2762 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2763 * is only needed because a) MySQL must be as efficient as possible due to
2764 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2765 * which index to pick. Anyway, other databases might have different
2766 * indexes on a given table. So don't bother overriding this unless you're
2768 * @param string $index
2771 public function useIndexClause( $index ) {
2776 * REPLACE query wrapper.
2778 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2779 * except that when there is a duplicate key error, the old row is deleted
2780 * and the new row is inserted in its place.
2782 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2783 * perform the delete, we need to know what the unique indexes are so that
2784 * we know how to find the conflicting rows.
2786 * It may be more efficient to leave off unique indexes which are unlikely
2787 * to collide. However if you do this, you run the risk of encountering
2788 * errors which wouldn't have occurred in MySQL.
2790 * @param string $table The table to replace the row(s) in.
2791 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2792 * a field name or an array of field names
2793 * @param array $rows Can be either a single row to insert, or multiple rows,
2794 * in the same format as for DatabaseBase::insert()
2795 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2797 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2798 $quotedTable = $this->tableName( $table );
2800 if ( count( $rows ) == 0 ) {
2805 if ( !is_array( reset( $rows ) ) ) {
2806 $rows = array( $rows );
2809 foreach ( $rows as $row ) {
2810 # Delete rows which collide
2811 if ( $uniqueIndexes ) {
2812 $sql = "DELETE FROM $quotedTable WHERE ";
2814 foreach ( $uniqueIndexes as $index ) {
2821 if ( is_array( $index ) ) {
2823 foreach ( $index as $col ) {
2829 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2832 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2836 $this->query( $sql, $fname );
2839 # Now insert the row
2840 $this->insert( $table, $row, $fname );
2845 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2848 * @param string $table Table name
2849 * @param array|string $rows Row(s) to insert
2850 * @param string $fname Caller function name
2852 * @return ResultWrapper
2854 protected function nativeReplace( $table, $rows, $fname ) {
2855 $table = $this->tableName( $table );
2858 if ( !is_array( reset( $rows ) ) ) {
2859 $rows = array( $rows );
2862 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2865 foreach ( $rows as $row ) {
2872 $sql .= '(' . $this->makeList( $row ) . ')';
2875 return $this->query( $sql, $fname );
2879 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2881 * This updates any conflicting rows (according to the unique indexes) using
2882 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2884 * $rows may be either:
2885 * - A single associative array. The array keys are the field names, and
2886 * the values are the values to insert. The values are treated as data
2887 * and will be quoted appropriately. If NULL is inserted, this will be
2888 * converted to a database NULL.
2889 * - An array with numeric keys, holding a list of associative arrays.
2890 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2891 * each subarray must be identical to each other, and in the same order.
2893 * It may be more efficient to leave off unique indexes which are unlikely
2894 * to collide. However if you do this, you run the risk of encountering
2895 * errors which wouldn't have occurred in MySQL.
2897 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2902 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2903 * @param array $rows A single row or list of rows to insert
2904 * @param array $uniqueIndexes List of single field names or field name tuples
2905 * @param array $set An array of values to SET. For each array element, the
2906 * key gives the field name, and the value gives the data to set that
2907 * field to. The data will be quoted by DatabaseBase::addQuotes().
2908 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2912 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2915 if ( !count( $rows ) ) {
2916 return true; // nothing to do
2919 if ( !is_array( reset( $rows ) ) ) {
2920 $rows = array( $rows );
2923 if ( count( $uniqueIndexes ) ) {
2924 $clauses = array(); // list WHERE clauses that each identify a single row
2925 foreach ( $rows as $row ) {
2926 foreach ( $uniqueIndexes as $index ) {
2927 $index = is_array( $index ) ?
$index : array( $index ); // columns
2928 $rowKey = array(); // unique key to this row
2929 foreach ( $index as $column ) {
2930 $rowKey[$column] = $row[$column];
2932 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2935 $where = array( $this->makeList( $clauses, LIST_OR
) );
2940 $useTrx = !$this->mTrxLevel
;
2942 $this->begin( $fname );
2945 # Update any existing conflicting row(s)
2946 if ( $where !== false ) {
2947 $ok = $this->update( $table, $set, $where, $fname );
2951 # Now insert any non-conflicting row(s)
2952 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2953 } catch ( Exception
$e ) {
2955 $this->rollback( $fname );
2960 $this->commit( $fname );
2967 * DELETE where the condition is a join.
2969 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2970 * we use sub-selects
2972 * For safety, an empty $conds will not delete everything. If you want to
2973 * delete all rows where the join condition matches, set $conds='*'.
2975 * DO NOT put the join condition in $conds.
2977 * @param string $delTable The table to delete from.
2978 * @param string $joinTable The other table.
2979 * @param string $delVar The variable to join on, in the first table.
2980 * @param string $joinVar The variable to join on, in the second table.
2981 * @param array $conds Condition array of field names mapped to variables,
2982 * ANDed together in the WHERE clause
2983 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2984 * @throws DBUnexpectedError
2986 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2990 throw new DBUnexpectedError( $this,
2991 'DatabaseBase::deleteJoin() called with empty $conds' );
2994 $delTable = $this->tableName( $delTable );
2995 $joinTable = $this->tableName( $joinTable );
2996 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2997 if ( $conds != '*' ) {
2998 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
3002 $this->query( $sql, $fname );
3006 * Returns the size of a text field, or -1 for "unlimited"
3008 * @param string $table
3009 * @param string $field
3012 public function textFieldSize( $table, $field ) {
3013 $table = $this->tableName( $table );
3014 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3015 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3016 $row = $this->fetchObject( $res );
3020 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
3030 * A string to insert into queries to show that they're low-priority, like
3031 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3032 * string and nothing bad should happen.
3034 * @return string Returns the text of the low priority option if it is
3035 * supported, or a blank string otherwise
3037 public function lowPriorityOption() {
3042 * DELETE query wrapper.
3044 * @param array $table Table name
3045 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3046 * for the format. Use $conds == "*" to delete all rows
3047 * @param string $fname Name of the calling function
3048 * @throws DBUnexpectedError
3049 * @return bool|ResultWrapper
3051 public function delete( $table, $conds, $fname = __METHOD__
) {
3053 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3056 $table = $this->tableName( $table );
3057 $sql = "DELETE FROM $table";
3059 if ( $conds != '*' ) {
3060 if ( is_array( $conds ) ) {
3061 $conds = $this->makeList( $conds, LIST_AND
);
3063 $sql .= ' WHERE ' . $conds;
3066 return $this->query( $sql, $fname );
3070 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3071 * into another table.
3073 * @param string $destTable The table name to insert into
3074 * @param string|array $srcTable May be either a table name, or an array of table names
3075 * to include in a join.
3077 * @param array $varMap Must be an associative array of the form
3078 * array( 'dest1' => 'source1', ...). Source items may be literals
3079 * rather than field names, but strings should be quoted with
3080 * DatabaseBase::addQuotes()
3082 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3083 * the details of the format of condition arrays. May be "*" to copy the
3086 * @param string $fname The function name of the caller, from __METHOD__
3088 * @param array $insertOptions Options for the INSERT part of the query, see
3089 * DatabaseBase::insert() for details.
3090 * @param array $selectOptions Options for the SELECT part of the query, see
3091 * DatabaseBase::select() for details.
3093 * @return ResultWrapper
3095 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3096 $fname = __METHOD__
,
3097 $insertOptions = array(), $selectOptions = array()
3099 $destTable = $this->tableName( $destTable );
3101 if ( !is_array( $insertOptions ) ) {
3102 $insertOptions = array( $insertOptions );
3105 $insertOptions = $this->makeInsertOptions( $insertOptions );
3107 if ( !is_array( $selectOptions ) ) {
3108 $selectOptions = array( $selectOptions );
3111 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3113 if ( is_array( $srcTable ) ) {
3114 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3116 $srcTable = $this->tableName( $srcTable );
3119 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3120 " SELECT $startOpts " . implode( ',', $varMap ) .
3121 " FROM $srcTable $useIndex ";
3123 if ( $conds != '*' ) {
3124 if ( is_array( $conds ) ) {
3125 $conds = $this->makeList( $conds, LIST_AND
);
3127 $sql .= " WHERE $conds";
3130 $sql .= " $tailOpts";
3132 return $this->query( $sql, $fname );
3136 * Construct a LIMIT query with optional offset. This is used for query
3137 * pages. The SQL should be adjusted so that only the first $limit rows
3138 * are returned. If $offset is provided as well, then the first $offset
3139 * rows should be discarded, and the next $limit rows should be returned.
3140 * If the result of the query is not ordered, then the rows to be returned
3141 * are theoretically arbitrary.
3143 * $sql is expected to be a SELECT, if that makes a difference.
3145 * The version provided by default works in MySQL and SQLite. It will very
3146 * likely need to be overridden for most other DBMSes.
3148 * @param string $sql SQL query we will append the limit too
3149 * @param int $limit The SQL limit
3150 * @param int|bool $offset The SQL offset (default false)
3151 * @throws DBUnexpectedError
3154 public function limitResult( $sql, $limit, $offset = false ) {
3155 if ( !is_numeric( $limit ) ) {
3156 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3159 return "$sql LIMIT "
3160 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3165 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3166 * within the UNION construct.
3169 public function unionSupportsOrderAndLimit() {
3170 return true; // True for almost every DB supported
3174 * Construct a UNION query
3175 * This is used for providing overload point for other DB abstractions
3176 * not compatible with the MySQL syntax.
3177 * @param array $sqls SQL statements to combine
3178 * @param bool $all Use UNION ALL
3179 * @return string SQL fragment
3181 public function unionQueries( $sqls, $all ) {
3182 $glue = $all ?
') UNION ALL (' : ') UNION (';
3184 return '(' . implode( $glue, $sqls ) . ')';
3188 * Returns an SQL expression for a simple conditional. This doesn't need
3189 * to be overridden unless CASE isn't supported in your DBMS.
3191 * @param string|array $cond SQL expression which will result in a boolean value
3192 * @param string $trueVal SQL expression to return if true
3193 * @param string $falseVal SQL expression to return if false
3194 * @return string SQL fragment
3196 public function conditional( $cond, $trueVal, $falseVal ) {
3197 if ( is_array( $cond ) ) {
3198 $cond = $this->makeList( $cond, LIST_AND
);
3201 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3205 * Returns a comand for str_replace function in SQL query.
3206 * Uses REPLACE() in MySQL
3208 * @param string $orig Column to modify
3209 * @param string $old Column to seek
3210 * @param string $new Column to replace with
3214 public function strreplace( $orig, $old, $new ) {
3215 return "REPLACE({$orig}, {$old}, {$new})";
3219 * Determines how long the server has been up
3224 public function getServerUptime() {
3229 * Determines if the last failure was due to a deadlock
3234 public function wasDeadlock() {
3239 * Determines if the last failure was due to a lock timeout
3244 public function wasLockTimeout() {
3249 * Determines if the last query error was something that should be dealt
3250 * with by pinging the connection and reissuing the query.
3255 public function wasErrorReissuable() {
3260 * Determines if the last failure was due to the database being read-only.
3265 public function wasReadOnlyError() {
3270 * Perform a deadlock-prone transaction.
3272 * This function invokes a callback function to perform a set of write
3273 * queries. If a deadlock occurs during the processing, the transaction
3274 * will be rolled back and the callback function will be called again.
3277 * $dbw->deadlockLoop( callback, ... );
3279 * Extra arguments are passed through to the specified callback function.
3281 * Returns whatever the callback function returned on its successful,
3282 * iteration, or false on error, for example if the retry limit was
3287 public function deadlockLoop() {
3288 $this->begin( __METHOD__
);
3289 $args = func_get_args();
3290 $function = array_shift( $args );
3291 $oldIgnore = $this->ignoreErrors( true );
3292 $tries = self
::DEADLOCK_TRIES
;
3294 if ( is_array( $function ) ) {
3295 $fname = $function[0];
3301 $retVal = call_user_func_array( $function, $args );
3302 $error = $this->lastError();
3303 $errno = $this->lastErrno();
3304 $sql = $this->lastQuery();
3307 if ( $this->wasDeadlock() ) {
3309 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3311 $this->reportQueryError( $error, $errno, $sql, $fname );
3314 } while ( $this->wasDeadlock() && --$tries > 0 );
3316 $this->ignoreErrors( $oldIgnore );
3318 if ( $tries <= 0 ) {
3319 $this->rollback( __METHOD__
);
3320 $this->reportQueryError( $error, $errno, $sql, $fname );
3324 $this->commit( __METHOD__
);
3331 * Wait for the slave to catch up to a given master position.
3333 * @param DBMasterPos $pos
3334 * @param int $timeout The maximum number of seconds to wait for
3336 * @return int Zero if the slave was past that position already,
3337 * greater than zero if we waited for some period of time, less than
3338 * zero if we timed out.
3340 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3341 # Real waits are implemented in the subclass.
3346 * Get the replication position of this slave
3348 * @return DBMasterPos|bool False if this is not a slave.
3350 public function getSlavePos() {
3356 * Get the position of this master
3358 * @return DBMasterPos|bool False if this is not a master
3360 public function getMasterPos() {
3366 * Run an anonymous function as soon as there is no transaction pending.
3367 * If there is a transaction and it is rolled back, then the callback is cancelled.
3368 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3369 * Callbacks must commit any transactions that they begin.
3371 * This is useful for updates to different systems or when separate transactions are needed.
3372 * For example, one might want to enqueue jobs into a system outside the database, but only
3373 * after the database is updated so that the jobs will see the data when they actually run.
3374 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3376 * @param callable $callback
3379 final public function onTransactionIdle( $callback ) {
3380 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3381 if ( !$this->mTrxLevel
) {
3382 $this->runOnTransactionIdleCallbacks();
3387 * Run an anonymous function before the current transaction commits or now if there is none.
3388 * If there is a transaction and it is rolled back, then the callback is cancelled.
3389 * Callbacks must not start nor commit any transactions.
3391 * This is useful for updates that easily cause deadlocks if locks are held too long
3392 * but where atomicity is strongly desired for these updates and some related updates.
3394 * @param callable $callback
3397 final public function onTransactionPreCommitOrIdle( $callback ) {
3398 if ( $this->mTrxLevel
) {
3399 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3401 $this->onTransactionIdle( $callback ); // this will trigger immediately
3406 * Actually any "on transaction idle" callbacks.
3410 protected function runOnTransactionIdleCallbacks() {
3411 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3413 $e = $ePrior = null; // last exception
3414 do { // callbacks may add callbacks :)
3415 $callbacks = $this->mTrxIdleCallbacks
;
3416 $this->mTrxIdleCallbacks
= array(); // recursion guard
3417 foreach ( $callbacks as $callback ) {
3419 list( $phpCallback ) = $callback;
3420 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3421 call_user_func( $phpCallback );
3422 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3423 } catch ( Exception
$e ) {
3425 MWExceptionHandler
::logException( $ePrior );
3430 } while ( count( $this->mTrxIdleCallbacks
) );
3432 if ( $e instanceof Exception
) {
3433 throw $e; // re-throw any last exception
3438 * Actually any "on transaction pre-commit" callbacks.
3442 protected function runOnTransactionPreCommitCallbacks() {
3443 $e = $ePrior = null; // last exception
3444 do { // callbacks may add callbacks :)
3445 $callbacks = $this->mTrxPreCommitCallbacks
;
3446 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3447 foreach ( $callbacks as $callback ) {
3449 list( $phpCallback ) = $callback;
3450 call_user_func( $phpCallback );
3451 } catch ( Exception
$e ) {
3453 MWExceptionHandler
::logException( $ePrior );
3458 } while ( count( $this->mTrxPreCommitCallbacks
) );
3460 if ( $e instanceof Exception
) {
3461 throw $e; // re-throw any last exception
3466 * Begin an atomic section of statements
3468 * If a transaction has been started already, just keep track of the given
3469 * section name to make sure the transaction is not committed pre-maturely.
3470 * This function can be used in layers (with sub-sections), so use a stack
3471 * to keep track of the different atomic sections. If there is no transaction,
3472 * start one implicitly.
3474 * The goal of this function is to create an atomic section of SQL queries
3475 * without having to start a new transaction if it already exists.
3477 * Atomic sections are more strict than transactions. With transactions,
3478 * attempting to begin a new transaction when one is already running results
3479 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3480 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3481 * and any database transactions cannot be began or committed until all atomic
3482 * levels are closed. There is no such thing as implicitly opening or closing
3483 * an atomic section.
3486 * @param string $fname
3489 final public function startAtomic( $fname = __METHOD__
) {
3490 if ( !$this->mTrxLevel
) {
3491 $this->begin( $fname );
3492 $this->mTrxAutomatic
= true;
3493 $this->mTrxAutomaticAtomic
= true;
3496 $this->mTrxAtomicLevels
->push( $fname );
3500 * Ends an atomic section of SQL statements
3502 * Ends the next section of atomic SQL statements and commits the transaction
3506 * @see DatabaseBase::startAtomic
3507 * @param string $fname
3510 final public function endAtomic( $fname = __METHOD__
) {
3511 if ( !$this->mTrxLevel
) {
3512 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3514 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3515 $this->mTrxAtomicLevels
->pop() !== $fname
3517 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3520 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3521 $this->commit( $fname, 'flush' );
3526 * Begin a transaction. If a transaction is already in progress,
3527 * that transaction will be committed before the new transaction is started.
3529 * Note that when the DBO_TRX flag is set (which is usually the case for web
3530 * requests, but not for maintenance scripts), any previous database query
3531 * will have started a transaction automatically.
3533 * Nesting of transactions is not supported. Attempts to nest transactions
3534 * will cause a warning, unless the current transaction was started
3535 * automatically because of the DBO_TRX flag.
3537 * @param string $fname
3540 final public function begin( $fname = __METHOD__
) {
3541 global $wgDebugDBTransactions;
3543 if ( $this->mTrxLevel
) { // implicit commit
3544 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3545 // If the current transaction was an automatic atomic one, then we definitely have
3546 // a problem. Same if there is any unclosed atomic level.
3547 throw new DBUnexpectedError( $this,
3548 "Attempted to start explicit transaction when atomic levels are still open."
3550 } elseif ( !$this->mTrxAutomatic
) {
3551 // We want to warn about inadvertently nested begin/commit pairs, but not about
3552 // auto-committing implicit transactions that were started by query() via DBO_TRX
3553 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3554 " performing implicit commit!";
3557 $this->getLogContext( array(
3558 'method' => __METHOD__
,
3563 // if the transaction was automatic and has done write operations,
3564 // log it if $wgDebugDBTransactions is enabled.
3565 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3566 wfDebug( "$fname: Automatic transaction with writes in progress" .
3567 " (from {$this->mTrxFname}), performing implicit commit!\n"
3572 $this->runOnTransactionPreCommitCallbacks();
3573 $this->doCommit( $fname );
3574 if ( $this->mTrxDoneWrites
) {
3575 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3576 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3578 $this->runOnTransactionIdleCallbacks();
3581 # Avoid fatals if close() was called
3582 if ( !$this->isOpen() ) {
3583 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3586 $this->doBegin( $fname );
3587 $this->mTrxTimestamp
= microtime( true );
3588 $this->mTrxFname
= $fname;
3589 $this->mTrxDoneWrites
= false;
3590 $this->mTrxAutomatic
= false;
3591 $this->mTrxAutomaticAtomic
= false;
3592 $this->mTrxAtomicLevels
= new SplStack
;
3593 $this->mTrxIdleCallbacks
= array();
3594 $this->mTrxPreCommitCallbacks
= array();
3595 $this->mTrxShortId
= wfRandomString( 12 );
3599 * Issues the BEGIN command to the database server.
3601 * @see DatabaseBase::begin()
3602 * @param string $fname
3604 protected function doBegin( $fname ) {
3605 $this->query( 'BEGIN', $fname );
3606 $this->mTrxLevel
= 1;
3610 * Commits a transaction previously started using begin().
3611 * If no transaction is in progress, a warning is issued.
3613 * Nesting of transactions is not supported.
3615 * @param string $fname
3616 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3617 * explicitly committing implicit transactions, or calling commit when no
3618 * transaction is in progress. This will silently break any ongoing
3619 * explicit transaction. Only set the flush flag if you are sure that it
3620 * is safe to ignore these warnings in your context.
3621 * @throws DBUnexpectedError
3623 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3624 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3625 // There are still atomic sections open. This cannot be ignored
3626 throw new DBUnexpectedError(
3628 "Attempted to commit transaction while atomic sections are still open"
3632 if ( $flush === 'flush' ) {
3633 if ( !$this->mTrxLevel
) {
3634 return; // nothing to do
3635 } elseif ( !$this->mTrxAutomatic
) {
3636 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3639 if ( !$this->mTrxLevel
) {
3640 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3641 return; // nothing to do
3642 } elseif ( $this->mTrxAutomatic
) {
3643 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3647 # Avoid fatals if close() was called
3648 if ( !$this->isOpen() ) {
3649 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3652 $this->runOnTransactionPreCommitCallbacks();
3653 $this->doCommit( $fname );
3654 if ( $this->mTrxDoneWrites
) {
3655 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3656 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3658 $this->runOnTransactionIdleCallbacks();
3662 * Issues the COMMIT command to the database server.
3664 * @see DatabaseBase::commit()
3665 * @param string $fname
3667 protected function doCommit( $fname ) {
3668 if ( $this->mTrxLevel
) {
3669 $this->query( 'COMMIT', $fname );
3670 $this->mTrxLevel
= 0;
3675 * Rollback a transaction previously started using begin().
3676 * If no transaction is in progress, a warning is issued.
3678 * No-op on non-transactional databases.
3680 * @param string $fname
3681 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3682 * calling rollback when no transaction is in progress. This will silently
3683 * break any ongoing explicit transaction. Only set the flush flag if you
3684 * are sure that it is safe to ignore these warnings in your context.
3685 * @throws DBUnexpectedError
3686 * @since 1.23 Added $flush parameter
3688 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3689 if ( $flush !== 'flush' ) {
3690 if ( !$this->mTrxLevel
) {
3691 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3692 return; // nothing to do
3693 } elseif ( $this->mTrxAutomatic
) {
3694 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3697 if ( !$this->mTrxLevel
) {
3698 return; // nothing to do
3699 } elseif ( !$this->mTrxAutomatic
) {
3700 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3704 # Avoid fatals if close() was called
3705 if ( !$this->isOpen() ) {
3706 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3709 $this->doRollback( $fname );
3710 $this->mTrxIdleCallbacks
= array(); // cancel
3711 $this->mTrxPreCommitCallbacks
= array(); // cancel
3712 $this->mTrxAtomicLevels
= new SplStack
;
3713 if ( $this->mTrxDoneWrites
) {
3714 Profiler
::instance()->getTransactionProfiler()->transactionWritingOut(
3715 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3720 * Issues the ROLLBACK command to the database server.
3722 * @see DatabaseBase::rollback()
3723 * @param string $fname
3725 protected function doRollback( $fname ) {
3726 if ( $this->mTrxLevel
) {
3727 $this->query( 'ROLLBACK', $fname, true );
3728 $this->mTrxLevel
= 0;
3733 * Creates a new table with structure copied from existing table
3734 * Note that unlike most database abstraction functions, this function does not
3735 * automatically append database prefix, because it works at a lower
3736 * abstraction level.
3737 * The table names passed to this function shall not be quoted (this
3738 * function calls addIdentifierQuotes when needed).
3740 * @param string $oldName Name of table whose structure should be copied
3741 * @param string $newName Name of table to be created
3742 * @param bool $temporary Whether the new table should be temporary
3743 * @param string $fname Calling function name
3744 * @throws MWException
3745 * @return bool True if operation was successful
3747 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3750 throw new MWException(
3751 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3755 * List all tables on the database
3757 * @param string $prefix Only show tables with this prefix, e.g. mw_
3758 * @param string $fname Calling function name
3759 * @throws MWException
3761 function listTables( $prefix = null, $fname = __METHOD__
) {
3762 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3766 * Reset the views process cache set by listViews()
3769 final public function clearViewsCache() {
3770 $this->allViews
= null;
3774 * Lists all the VIEWs in the database
3776 * For caching purposes the list of all views should be stored in
3777 * $this->allViews. The process cache can be cleared with clearViewsCache()
3779 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3780 * @param string $fname Name of calling function
3781 * @throws MWException
3784 public function listViews( $prefix = null, $fname = __METHOD__
) {
3785 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3789 * Differentiates between a TABLE and a VIEW
3791 * @param string $name Name of the database-structure to test.
3792 * @throws MWException
3795 public function isView( $name ) {
3796 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3800 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3801 * to the format used for inserting into timestamp fields in this DBMS.
3803 * The result is unquoted, and needs to be passed through addQuotes()
3804 * before it can be included in raw SQL.
3806 * @param string|int $ts
3810 public function timestamp( $ts = 0 ) {
3811 return wfTimestamp( TS_MW
, $ts );
3815 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3816 * to the format used for inserting into timestamp fields in this DBMS. If
3817 * NULL is input, it is passed through, allowing NULL values to be inserted
3818 * into timestamp fields.
3820 * The result is unquoted, and needs to be passed through addQuotes()
3821 * before it can be included in raw SQL.
3823 * @param string|int $ts
3827 public function timestampOrNull( $ts = null ) {
3828 if ( is_null( $ts ) ) {
3831 return $this->timestamp( $ts );
3836 * Take the result from a query, and wrap it in a ResultWrapper if
3837 * necessary. Boolean values are passed through as is, to indicate success
3838 * of write queries or failure.
3840 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3841 * resource, and it was necessary to call this function to convert it to
3842 * a wrapper. Nowadays, raw database objects are never exposed to external
3843 * callers, so this is unnecessary in external code. For compatibility with
3844 * old code, ResultWrapper objects are passed through unaltered.
3846 * @param bool|ResultWrapper|resource $result
3847 * @return bool|ResultWrapper
3849 public function resultObject( $result ) {
3850 if ( empty( $result ) ) {
3852 } elseif ( $result instanceof ResultWrapper
) {
3854 } elseif ( $result === true ) {
3855 // Successful write query
3858 return new ResultWrapper( $this, $result );
3863 * Ping the server and try to reconnect if it there is no connection
3865 * @return bool Success or failure
3867 public function ping() {
3868 # Stub. Not essential to override.
3873 * Get slave lag. Currently supported only by MySQL.
3875 * Note that this function will generate a fatal error on many
3876 * installations. Most callers should use LoadBalancer::safeGetLag()
3879 * @return int Database replication lag in seconds
3881 public function getLag() {
3886 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3890 function maxListLen() {
3895 * Some DBMSs have a special format for inserting into blob fields, they
3896 * don't allow simple quoted strings to be inserted. To insert into such
3897 * a field, pass the data through this function before passing it to
3898 * DatabaseBase::insert().
3903 public function encodeBlob( $b ) {
3908 * Some DBMSs return a special placeholder object representing blob fields
3909 * in result objects. Pass the object through this function to return the
3915 public function decodeBlob( $b ) {
3920 * Override database's default behavior. $options include:
3921 * 'connTimeout' : Set the connection timeout value in seconds.
3922 * May be useful for very long batch queries such as
3923 * full-wiki dumps, where a single query reads out over
3926 * @param array $options
3929 public function setSessionOptions( array $options ) {
3933 * Read and execute SQL commands from a file.
3935 * Returns true on success, error string or exception on failure (depending
3936 * on object's error ignore settings).
3938 * @param string $filename File name to open
3939 * @param bool|callable $lineCallback Optional function called before reading each line
3940 * @param bool|callable $resultCallback Optional function called for each MySQL result
3941 * @param bool|string $fname Calling function name or false if name should be
3942 * generated dynamically using $filename
3943 * @param bool|callable $inputCallback Optional function called for each
3944 * complete line sent
3945 * @throws Exception|MWException
3946 * @return bool|string
3948 public function sourceFile(
3949 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3951 wfSuppressWarnings();
3952 $fp = fopen( $filename, 'r' );
3953 wfRestoreWarnings();
3955 if ( false === $fp ) {
3956 throw new MWException( "Could not open \"{$filename}\".\n" );
3960 $fname = __METHOD__
. "( $filename )";
3964 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3965 } catch ( MWException
$e ) {
3976 * Get the full path of a patch file. Originally based on archive()
3977 * from updaters.inc. Keep in mind this always returns a patch, as
3978 * it fails back to MySQL if no DB-specific patch can be found
3980 * @param string $patch The name of the patch, like patch-something.sql
3981 * @return string Full path to patch file
3983 public function patchPath( $patch ) {
3986 $dbType = $this->getType();
3987 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3988 return "$IP/maintenance/$dbType/archives/$patch";
3990 return "$IP/maintenance/archives/$patch";
3995 * Set variables to be used in sourceFile/sourceStream, in preference to the
3996 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3997 * all. If it's set to false, $GLOBALS will be used.
3999 * @param bool|array $vars Mapping variable name to value.
4001 public function setSchemaVars( $vars ) {
4002 $this->mSchemaVars
= $vars;
4006 * Read and execute commands from an open file handle.
4008 * Returns true on success, error string or exception on failure (depending
4009 * on object's error ignore settings).
4011 * @param resource $fp File handle
4012 * @param bool|callable $lineCallback Optional function called before reading each query
4013 * @param bool|callable $resultCallback Optional function called for each MySQL result
4014 * @param string $fname Calling function name
4015 * @param bool|callable $inputCallback Optional function called for each complete query sent
4016 * @return bool|string
4018 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4019 $fname = __METHOD__
, $inputCallback = false
4023 while ( !feof( $fp ) ) {
4024 if ( $lineCallback ) {
4025 call_user_func( $lineCallback );
4028 $line = trim( fgets( $fp ) );
4030 if ( $line == '' ) {
4034 if ( '-' == $line[0] && '-' == $line[1] ) {
4042 $done = $this->streamStatementEnd( $cmd, $line );
4046 if ( $done ||
feof( $fp ) ) {
4047 $cmd = $this->replaceVars( $cmd );
4049 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4050 $res = $this->query( $cmd, $fname );
4052 if ( $resultCallback ) {
4053 call_user_func( $resultCallback, $res, $this );
4056 if ( false === $res ) {
4057 $err = $this->lastError();
4059 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4070 * Called by sourceStream() to check if we've reached a statement end
4072 * @param string $sql SQL assembled so far
4073 * @param string $newLine New line about to be added to $sql
4074 * @return bool Whether $newLine contains end of the statement
4076 public function streamStatementEnd( &$sql, &$newLine ) {
4077 if ( $this->delimiter
) {
4079 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4080 if ( $newLine != $prev ) {
4089 * Database independent variable replacement. Replaces a set of variables
4090 * in an SQL statement with their contents as given by $this->getSchemaVars().
4092 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4094 * - '{$var}' should be used for text and is passed through the database's
4096 * - `{$var}` should be used for identifiers (e.g. table and database names).
4097 * It is passed through the database's addIdentifierQuotes method which
4098 * can be overridden if the database uses something other than backticks.
4099 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4100 * database's tableName method.
4101 * - / *i* / passes the name that follows through the database's indexName method.
4102 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4103 * its use should be avoided. In 1.24 and older, string encoding was applied.
4105 * @param string $ins SQL statement to replace variables in
4106 * @return string The new SQL statement with variables replaced
4108 protected function replaceVars( $ins ) {
4110 $vars = $this->getSchemaVars();
4111 return preg_replace_callback(
4113 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4114 \'\{\$ (\w+) }\' | # 3. addQuotes
4115 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4116 /\*\$ (\w+) \*/ # 5. leave unencoded
4118 function ( $m ) use ( $that, $vars ) {
4119 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4120 // check for both nonexistent keys *and* the empty string.
4121 if ( isset( $m[1] ) && $m[1] !== '' ) {
4122 if ( $m[1] === 'i' ) {
4123 return $that->indexName( $m[2] );
4125 return $that->tableName( $m[2] );
4127 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4128 return $that->addQuotes( $vars[$m[3]] );
4129 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4130 return $that->addIdentifierQuotes( $vars[$m[4]] );
4131 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4132 return $vars[$m[5]];
4142 * Get schema variables. If none have been set via setSchemaVars(), then
4143 * use some defaults from the current object.
4147 protected function getSchemaVars() {
4148 if ( $this->mSchemaVars
) {
4149 return $this->mSchemaVars
;
4151 return $this->getDefaultSchemaVars();
4156 * Get schema variables to use if none have been set via setSchemaVars().
4158 * Override this in derived classes to provide variables for tables.sql
4159 * and SQL patch files.
4163 protected function getDefaultSchemaVars() {
4168 * Check to see if a named lock is available. This is non-blocking.
4170 * @param string $lockName Name of lock to poll
4171 * @param string $method Name of method calling us
4175 public function lockIsFree( $lockName, $method ) {
4180 * Acquire a named lock
4182 * Abstracted from Filestore::lock() so child classes can implement for
4185 * @param string $lockName Name of lock to aquire
4186 * @param string $method Name of method calling us
4187 * @param int $timeout
4190 public function lock( $lockName, $method, $timeout = 5 ) {
4197 * @param string $lockName Name of lock to release
4198 * @param string $method Name of method calling us
4200 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4201 * by this thread (in which case the lock is not released), and NULL if the named
4202 * lock did not exist
4204 public function unlock( $lockName, $method ) {
4209 * Lock specific tables
4211 * @param array $read Array of tables to lock for read access
4212 * @param array $write Array of tables to lock for write access
4213 * @param string $method Name of caller
4214 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4217 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4222 * Unlock specific tables
4224 * @param string $method The caller
4227 public function unlockTables( $method ) {
4233 * @param string $tableName
4234 * @param string $fName
4235 * @return bool|ResultWrapper
4238 public function dropTable( $tableName, $fName = __METHOD__
) {
4239 if ( !$this->tableExists( $tableName, $fName ) ) {
4242 $sql = "DROP TABLE " . $this->tableName( $tableName );
4243 if ( $this->cascadingDeletes() ) {
4247 return $this->query( $sql, $fName );
4251 * Get search engine class. All subclasses of this need to implement this
4252 * if they wish to use searching.
4256 public function getSearchEngine() {
4257 return 'SearchEngineDummy';
4261 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4262 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4263 * because "i" sorts after all numbers.
4267 public function getInfinity() {
4272 * Encode an expiry time into the DBMS dependent format
4274 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4277 public function encodeExpiry( $expiry ) {
4278 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4279 ?
$this->getInfinity()
4280 : $this->timestamp( $expiry );
4284 * Decode an expiry time into a DBMS independent format
4286 * @param string $expiry DB timestamp field value for expiry
4287 * @param int $format TS_* constant, defaults to TS_MW
4290 public function decodeExpiry( $expiry, $format = TS_MW
) {
4291 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4293 : wfTimestamp( $format, $expiry );
4297 * Allow or deny "big selects" for this session only. This is done by setting
4298 * the sql_big_selects session variable.
4300 * This is a MySQL-specific feature.
4302 * @param bool|string $value True for allow, false for deny, or "default" to
4303 * restore the initial value
4305 public function setBigSelects( $value = true ) {
4313 public function __toString() {
4314 return (string)$this->mConn
;
4318 * Run a few simple sanity checks
4320 public function __destruct() {
4321 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4322 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4324 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4326 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4327 $callers[] = $callbackInfo[1];
4329 $callers = implode( ', ', $callers );
4330 trigger_error( "DB transaction callbacks still pending (from $callers)." );