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 * Base interface for all DBMS-specific code. At a bare minimum, all of the
30 * following must be implemented to support MediaWiki
35 interface DatabaseType
{
37 * Get the type of the DBMS, as it appears in $wgDBtype.
44 * Open a connection to the database. Usually aborts on failure
46 * @param string $server Database server host
47 * @param string $user Database user name
48 * @param string $password Database user password
49 * @param string $dbName Database name
51 * @throws DBConnectionError
53 function open( $server, $user, $password, $dbName );
56 * Fetch the next row from the given result object, in object form.
57 * Fields can be retrieved with $row->fieldname, with fields acting like
59 * If no more rows are available, false is returned.
61 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
62 * @return stdClass|bool
63 * @throws DBUnexpectedError Thrown if the database returns an error
65 function fetchObject( $res );
68 * Fetch the next row from the given result object, in associative array
69 * form. Fields are retrieved with $row['fieldname'].
70 * If no more rows are available, false is returned.
72 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
74 * @throws DBUnexpectedError Thrown if the database returns an error
76 function fetchRow( $res );
79 * Get the number of rows in a result object
81 * @param mixed $res A SQL result
84 function numRows( $res );
87 * Get the number of fields in a result object
88 * @see http://www.php.net/mysql_num_fields
90 * @param mixed $res A SQL result
93 function numFields( $res );
96 * Get a field name in a result object
97 * @see http://www.php.net/mysql_field_name
99 * @param mixed $res A SQL result
103 function fieldName( $res, $n );
106 * Get the inserted value of an auto-increment row
108 * The value inserted should be fetched from nextSequenceValue()
111 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
112 * $dbw->insert( 'page', array( 'page_id' => $id ) );
113 * $id = $dbw->insertId();
120 * Change the position of the cursor in a result object
121 * @see http://www.php.net/mysql_data_seek
123 * @param mixed $res A SQL result
126 function dataSeek( $res, $row );
129 * Get the last error number
130 * @see http://www.php.net/mysql_errno
134 function lastErrno();
137 * Get a description of the last error
138 * @see http://www.php.net/mysql_error
142 function lastError();
145 * mysql_fetch_field() wrapper
146 * Returns false if the field doesn't exist
148 * @param string $table Table name
149 * @param string $field Field name
153 function fieldInfo( $table, $field );
156 * Get information about an index into an object
157 * @param string $table Table name
158 * @param string $index Index name
159 * @param string $fname Calling function name
160 * @return mixed Database-specific index description class or false if the index does not exist
162 function indexInfo( $table, $index, $fname = __METHOD__
);
165 * Get the number of rows affected by the last write query
166 * @see http://www.php.net/mysql_affected_rows
170 function affectedRows();
173 * Wrapper for addslashes()
175 * @param string $s String to be slashed.
176 * @return string Slashed string.
178 function strencode( $s );
181 * Returns a wikitext link to the DB's website, e.g.,
182 * return "[http://www.mysql.com/ MySQL]";
183 * Should at least contain plain text, if for some reason
184 * your database has no website.
186 * @return string Wikitext of a link to the server software's web site
188 function getSoftwareLink();
191 * A string describing the current software version, like from
192 * mysql_get_server_info().
194 * @return string Version information from the database server.
196 function getServerVersion();
199 * A string describing the current software version, and possibly
200 * other details in a user-friendly way. Will be listed on Special:Version, etc.
201 * Use getServerVersion() to get machine-friendly information.
203 * @return string Version information from the database server
205 function getServerInfo();
209 * Interface for classes that implement or wrap DatabaseBase
212 interface IDatabase
{
216 * Database abstraction object
219 abstract class DatabaseBase
implements IDatabase
, DatabaseType
{
220 /** Number of times to re-try an operation in case of deadlock */
221 const DEADLOCK_TRIES
= 4;
223 /** Minimum time to wait before retry, in microseconds */
224 const DEADLOCK_DELAY_MIN
= 500000;
226 /** Maximum time to wait before retry */
227 const DEADLOCK_DELAY_MAX
= 1500000;
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
233 protected $mLastQuery = '';
234 protected $mDoneWrites = false;
235 protected $mPHPError = false;
237 protected $mServer, $mUser, $mPassword, $mDBname;
239 /** @var resource Database connection */
240 protected $mConn = null;
241 protected $mOpened = false;
243 /** @var callable[] */
244 protected $mTrxIdleCallbacks = array();
245 /** @var callable[] */
246 protected $mTrxPreCommitCallbacks = array();
248 protected $mTablePrefix;
252 protected $mErrorCount = 0;
253 protected $mLBInfo = array();
254 protected $mDefaultBigSelects = null;
255 protected $mSchemaVars = false;
257 protected $preparedArgs;
259 protected $htmlErrors;
261 protected $delimiter = ';';
264 * Either 1 if a transaction is active or 0 otherwise.
265 * The other Trx fields may not be meaningfull if this is 0.
269 protected $mTrxLevel = 0;
272 * Either a short hexidecimal string if a transaction is active or ""
276 protected $mTrxShortId = '';
279 * Remembers the function name given for starting the most recent transaction via begin().
280 * Used to provide additional context for error reporting.
283 * @see DatabaseBase::mTrxLevel
285 private $mTrxFname = null;
288 * Record if possible write queries were done in the last transaction started
291 * @see DatabaseBase::mTrxLevel
293 private $mTrxDoneWrites = false;
296 * Record if the current transaction was started implicitly due to DBO_TRX being set.
299 * @see DatabaseBase::mTrxLevel
301 private $mTrxAutomatic = false;
304 * Array of levels of atomicity within transactions
308 private $mTrxAtomicLevels;
311 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
315 private $mTrxAutomaticAtomic = false;
319 * @var resource File handle for upgrade
321 protected $fileHandle = null;
325 * @var string[] Process cache of VIEWs names in the database
327 protected $allViews = null;
329 # ------------------------------------------------------------------------------
331 # ------------------------------------------------------------------------------
332 # These optionally set a variable and return the previous state
335 * A string describing the current software version, and possibly
336 * other details in a user-friendly way. Will be listed on Special:Version, etc.
337 * Use getServerVersion() to get machine-friendly information.
339 * @return string Version information from the database server
341 public function getServerInfo() {
342 return $this->getServerVersion();
346 * @return string Command delimiter used by this database engine
348 public function getDelimiter() {
349 return $this->delimiter
;
353 * Boolean, controls output of large amounts of debug information.
354 * @param bool|null $debug
355 * - true to enable debugging
356 * - false to disable debugging
357 * - omitted or null to do nothing
359 * @return bool|null Previous value of the flag
361 public function debug( $debug = null ) {
362 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
366 * Turns buffering of SQL result sets on (true) or off (false). Default is
369 * Unbuffered queries are very troublesome in MySQL:
371 * - If another query is executed while the first query is being read
372 * out, the first query is killed. This means you can't call normal
373 * MediaWiki functions while you are reading an unbuffered query result
374 * from a normal wfGetDB() connection.
376 * - Unbuffered queries cause the MySQL server to use large amounts of
377 * memory and to hold broad locks which block other queries.
379 * If you want to limit client-side memory, it's almost always better to
380 * split up queries into batches using a LIMIT clause than to switch off
383 * @param null|bool $buffer
384 * @return null|bool The previous value of the flag
386 public function bufferResults( $buffer = null ) {
387 if ( is_null( $buffer ) ) {
388 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
390 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
395 * Turns on (false) or off (true) the automatic generation and sending
396 * of a "we're sorry, but there has been a database error" page on
397 * database errors. Default is on (false). When turned off, the
398 * code should use lastErrno() and lastError() to handle the
399 * situation as appropriate.
401 * Do not use this function outside of the Database classes.
403 * @param null|bool $ignoreErrors
404 * @return bool The previous value of the flag.
406 public function ignoreErrors( $ignoreErrors = null ) {
407 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
411 * Gets the current transaction level.
413 * Historically, transactions were allowed to be "nested". This is no
414 * longer supported, so this function really only returns a boolean.
416 * @return int The previous value
418 public function trxLevel() {
419 return $this->mTrxLevel
;
423 * Get/set the number of errors logged. Only useful when errors are ignored
424 * @param int $count The count to set, or omitted to leave it unchanged.
425 * @return int The error count
427 public function errorCount( $count = null ) {
428 return wfSetVar( $this->mErrorCount
, $count );
432 * Get/set the table prefix.
433 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
434 * @return string The previous table prefix.
436 public function tablePrefix( $prefix = null ) {
437 return wfSetVar( $this->mTablePrefix
, $prefix );
441 * Get/set the db schema.
442 * @param string $schema The database schema to set, or omitted to leave it unchanged.
443 * @return string The previous db schema.
445 public function dbSchema( $schema = null ) {
446 return wfSetVar( $this->mSchema
, $schema );
450 * Set the filehandle to copy write statements to.
452 * @param resource $fh File handle
454 public function setFileHandle( $fh ) {
455 $this->fileHandle
= $fh;
459 * Get properties passed down from the server info array of the load
462 * @param string $name The entry of the info array to get, or null to get the
465 * @return array|mixed|null
467 public function getLBInfo( $name = null ) {
468 if ( is_null( $name ) ) {
469 return $this->mLBInfo
;
471 if ( array_key_exists( $name, $this->mLBInfo
) ) {
472 return $this->mLBInfo
[$name];
480 * Set the LB info array, or a member of it. If called with one parameter,
481 * the LB info array is set to that parameter. If it is called with two
482 * parameters, the member with the given name is set to the given value.
484 * @param string $name
485 * @param array $value
487 public function setLBInfo( $name, $value = null ) {
488 if ( is_null( $value ) ) {
489 $this->mLBInfo
= $name;
491 $this->mLBInfo
[$name] = $value;
496 * Set lag time in seconds for a fake slave
498 * @param mixed $lag Valid values for this parameter are determined by the
499 * subclass, but should be a PHP scalar or array that would be sensible
500 * as part of $wgLBFactoryConf.
502 public function setFakeSlaveLag( $lag ) {
506 * Make this connection a fake master
508 * @param bool $enabled
510 public function setFakeMaster( $enabled = true ) {
514 * Returns true if this database supports (and uses) cascading deletes
518 public function cascadingDeletes() {
523 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
527 public function cleanupTriggers() {
532 * Returns true if this database is strict about what can be put into an IP field.
533 * Specifically, it uses a NULL value instead of an empty string.
537 public function strictIPs() {
542 * Returns true if this database uses timestamps rather than integers
546 public function realTimestamps() {
551 * Returns true if this database does an implicit sort when doing GROUP BY
555 public function implicitGroupby() {
560 * Returns true if this database does an implicit order by when the column has an index
561 * For example: SELECT page_title FROM page LIMIT 1
565 public function implicitOrderby() {
570 * Returns true if this database can do a native search on IP columns
571 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
575 public function searchableIPs() {
580 * Returns true if this database can use functional indexes
584 public function functionalIndexes() {
589 * Return the last query that went through DatabaseBase::query()
592 public function lastQuery() {
593 return $this->mLastQuery
;
597 * Returns true if the connection may have been used for write queries.
598 * Should return true if unsure.
602 public function doneWrites() {
603 return (bool)$this->mDoneWrites
;
607 * Returns the last time the connection may have been used for write queries.
608 * Should return a timestamp if unsure.
610 * @return int|float UNIX timestamp or false
613 public function lastDoneWrites() {
614 return $this->mDoneWrites ?
: false;
618 * Returns true if there is a transaction open with possible write
619 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
623 public function writesOrCallbacksPending() {
624 return $this->mTrxLevel
&& (
625 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
630 * Is a connection to the database open?
633 public function isOpen() {
634 return $this->mOpened
;
638 * Set a flag for this connection
640 * @param int $flag DBO_* constants from Defines.php:
641 * - DBO_DEBUG: output some debug info (same as debug())
642 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
643 * - DBO_TRX: automatically start transactions
644 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
645 * and removes it in command line mode
646 * - DBO_PERSISTENT: use persistant database connection
648 public function setFlag( $flag ) {
649 global $wgDebugDBTransactions;
650 $this->mFlags |
= $flag;
651 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
652 wfDebug( "Implicit transactions are now enabled.\n" );
657 * Clear a flag for this connection
659 * @param int $flag DBO_* constants from Defines.php:
660 * - DBO_DEBUG: output some debug info (same as debug())
661 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
662 * - DBO_TRX: automatically start transactions
663 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
664 * and removes it in command line mode
665 * - DBO_PERSISTENT: use persistant database connection
667 public function clearFlag( $flag ) {
668 global $wgDebugDBTransactions;
669 $this->mFlags
&= ~
$flag;
670 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
671 wfDebug( "Implicit transactions are now disabled.\n" );
676 * Returns a boolean whether the flag $flag is set for this connection
678 * @param int $flag DBO_* constants from Defines.php:
679 * - DBO_DEBUG: output some debug info (same as debug())
680 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
681 * - DBO_TRX: automatically start transactions
682 * - DBO_PERSISTENT: use persistant database connection
685 public function getFlag( $flag ) {
686 return !!( $this->mFlags
& $flag );
690 * General read-only accessor
692 * @param string $name
695 public function getProperty( $name ) {
702 public function getWikiID() {
703 if ( $this->mTablePrefix
) {
704 return "{$this->mDBname}-{$this->mTablePrefix}";
706 return $this->mDBname
;
711 * Return a path to the DBMS-specific SQL file if it exists,
712 * otherwise default SQL file
714 * @param string $filename
717 private function getSqlFilePath( $filename ) {
719 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
720 if ( file_exists( $dbmsSpecificFilePath ) ) {
721 return $dbmsSpecificFilePath;
723 return "$IP/maintenance/$filename";
728 * Return a path to the DBMS-specific schema file,
729 * otherwise default to tables.sql
733 public function getSchemaPath() {
734 return $this->getSqlFilePath( 'tables.sql' );
738 * Return a path to the DBMS-specific update key file,
739 * otherwise default to update-keys.sql
743 public function getUpdateKeysPath() {
744 return $this->getSqlFilePath( 'update-keys.sql' );
747 # ------------------------------------------------------------------------------
749 # ------------------------------------------------------------------------------
754 * FIXME: It is possible to construct a Database object with no associated
755 * connection object, by specifying no parameters to __construct(). This
756 * feature is deprecated and should be removed.
758 * DatabaseBase subclasses should not be constructed directly in external
759 * code. DatabaseBase::factory() should be used instead.
761 * @param array $params Parameters passed from DatabaseBase::factory()
763 function __construct( $params = null ) {
764 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
766 $this->mTrxAtomicLevels
= new SplStack
;
768 if ( is_array( $params ) ) { // MW 1.22
769 $server = $params['host'];
770 $user = $params['user'];
771 $password = $params['password'];
772 $dbName = $params['dbname'];
773 $flags = $params['flags'];
774 $tablePrefix = $params['tablePrefix'];
775 $schema = $params['schema'];
776 $foreign = $params['foreign'];
777 } else { // legacy calling pattern
778 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
779 $args = func_get_args();
780 $server = isset( $args[0] ) ?
$args[0] : false;
781 $user = isset( $args[1] ) ?
$args[1] : false;
782 $password = isset( $args[2] ) ?
$args[2] : false;
783 $dbName = isset( $args[3] ) ?
$args[3] : false;
784 $flags = isset( $args[4] ) ?
$args[4] : 0;
785 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
786 $schema = 'get from global';
787 $foreign = isset( $args[6] ) ?
$args[6] : false;
790 $this->mFlags
= $flags;
791 if ( $this->mFlags
& DBO_DEFAULT
) {
792 if ( $wgCommandLineMode ) {
793 $this->mFlags
&= ~DBO_TRX
;
794 if ( $wgDebugDBTransactions ) {
795 wfDebug( "Implicit transaction open disabled.\n" );
798 $this->mFlags |
= DBO_TRX
;
799 if ( $wgDebugDBTransactions ) {
800 wfDebug( "Implicit transaction open enabled.\n" );
805 /** Get the default table prefix*/
806 if ( $tablePrefix == 'get from global' ) {
807 $this->mTablePrefix
= $wgDBprefix;
809 $this->mTablePrefix
= $tablePrefix;
812 /** Get the database schema*/
813 if ( $schema == 'get from global' ) {
814 $this->mSchema
= $wgDBmwschema;
816 $this->mSchema
= $schema;
819 $this->mForeign
= $foreign;
822 $this->open( $server, $user, $password, $dbName );
827 * Called by serialize. Throw an exception when DB connection is serialized.
828 * This causes problems on some database engines because the connection is
829 * not restored on unserialize.
831 public function __sleep() {
832 throw new MWException( 'Database serialization may cause problems, since ' .
833 'the connection is not restored on wakeup.' );
837 * Given a DB type, construct the name of the appropriate child class of
838 * DatabaseBase. This is designed to replace all of the manual stuff like:
839 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
840 * as well as validate against the canonical list of DB types we have
842 * This factory function is mostly useful for when you need to connect to a
843 * database other than the MediaWiki default (such as for external auth,
844 * an extension, et cetera). Do not use this to connect to the MediaWiki
845 * database. Example uses in core:
846 * @see LoadBalancer::reallyOpenConnection()
847 * @see ForeignDBRepo::getMasterDB()
848 * @see WebInstallerDBConnect::execute()
852 * @param string $dbType A possible DB type
853 * @param array $p An array of options to pass to the constructor.
854 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
855 * @throws MWException If the database driver or extension cannot be found
856 * @return DatabaseBase|null DatabaseBase subclass or null
858 final public static function factory( $dbType, $p = array() ) {
859 $canonicalDBTypes = array(
860 'mysql' => array( 'mysqli', 'mysql' ),
861 'postgres' => array(),
868 $dbType = strtolower( $dbType );
869 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
870 $possibleDrivers = $canonicalDBTypes[$dbType];
871 if ( !empty( $p['driver'] ) ) {
872 if ( in_array( $p['driver'], $possibleDrivers ) ) {
873 $driver = $p['driver'];
875 throw new MWException( __METHOD__
.
876 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
879 foreach ( $possibleDrivers as $posDriver ) {
880 if ( extension_loaded( $posDriver ) ) {
881 $driver = $posDriver;
889 if ( $driver === false ) {
890 throw new MWException( __METHOD__
.
891 " no viable database extension found for type '$dbType'" );
894 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
895 // and everything else doesn't use a schema (e.g. null)
896 // Although postgres and oracle support schemas, we don't use them (yet)
897 // to maintain backwards compatibility
898 $defaultSchemas = array(
903 'mssql' => 'get from global',
906 $class = 'Database' . ucfirst( $driver );
907 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
909 'host' => isset( $p['host'] ) ?
$p['host'] : false,
910 'user' => isset( $p['user'] ) ?
$p['user'] : false,
911 'password' => isset( $p['password'] ) ?
$p['password'] : false,
912 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
913 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
914 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
915 'schema' => isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType],
916 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
919 return new $class( $params );
925 protected function installErrorHandler() {
926 $this->mPHPError
= false;
927 $this->htmlErrors
= ini_set( 'html_errors', '0' );
928 set_error_handler( array( $this, 'connectionErrorHandler' ) );
932 * @return bool|string
934 protected function restoreErrorHandler() {
935 restore_error_handler();
936 if ( $this->htmlErrors
!== false ) {
937 ini_set( 'html_errors', $this->htmlErrors
);
939 if ( $this->mPHPError
) {
940 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
941 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
951 * @param string $errstr
953 public function connectionErrorHandler( $errno, $errstr ) {
954 $this->mPHPError
= $errstr;
958 * Closes a database connection.
959 * if it is open : commits any open transactions
961 * @throws MWException
962 * @return bool Operation success. true if already closed.
964 public function close() {
965 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
966 throw new MWException( "Transaction idle callbacks still pending." );
968 if ( $this->mConn
) {
969 if ( $this->trxLevel() ) {
970 if ( !$this->mTrxAutomatic
) {
971 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
972 " performing implicit commit before closing connection!" );
975 $this->commit( __METHOD__
, 'flush' );
978 $closed = $this->closeConnection();
979 $this->mConn
= false;
983 $this->mOpened
= false;
989 * Closes underlying database connection
991 * @return bool Whether connection was closed successfully
993 abstract protected function closeConnection();
996 * @param string $error Fallback error message, used if none is given by DB
997 * @throws DBConnectionError
999 function reportConnectionError( $error = 'Unknown error' ) {
1000 $myError = $this->lastError();
1006 throw new DBConnectionError( $this, $error );
1010 * The DBMS-dependent part of query()
1012 * @param string $sql SQL query.
1013 * @return ResultWrapper|bool Result object to feed to fetchObject,
1014 * fetchRow, ...; or false on failure
1016 abstract protected function doQuery( $sql );
1019 * Determine whether a query writes to the DB.
1020 * Should return true if unsure.
1022 * @param string $sql
1025 public function isWriteQuery( $sql ) {
1026 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1030 * Run an SQL query and return the result. Normally throws a DBQueryError
1031 * on failure. If errors are ignored, returns false instead.
1033 * In new code, the query wrappers select(), insert(), update(), delete(),
1034 * etc. should be used where possible, since they give much better DBMS
1035 * independence and automatically quote or validate user input in a variety
1036 * of contexts. This function is generally only useful for queries which are
1037 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1040 * However, the query wrappers themselves should call this function.
1042 * @param string $sql SQL query
1043 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1044 * comment (you can use __METHOD__ or add some extra info)
1045 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1046 * maybe best to catch the exception instead?
1047 * @throws MWException
1048 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1049 * for a successful read query, or false on failure if $tempIgnore set
1051 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1052 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1054 $this->mLastQuery
= $sql;
1055 if ( $this->isWriteQuery( $sql ) ) {
1056 # Set a flag indicating that writes have been done
1057 wfDebug( __METHOD__
. ': Writes done: ' . DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1058 $this->mDoneWrites
= microtime( true );
1061 # Add a comment for easy SHOW PROCESSLIST interpretation
1062 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1063 $userName = $wgUser->getName();
1064 if ( mb_strlen( $userName ) > 15 ) {
1065 $userName = mb_substr( $userName, 0, 15 ) . '...';
1067 $userName = str_replace( '/', '', $userName );
1072 // Add trace comment to the begin of the sql string, right after the operator.
1073 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1074 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1076 # If DBO_TRX is set, start a transaction
1077 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
1078 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1080 # Avoid establishing transactions for SHOW and SET statements too -
1081 # that would delay transaction initializations to once connection
1082 # is really used by application
1083 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1084 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1085 if ( $wgDebugDBTransactions ) {
1086 wfDebug( "Implicit transaction start.\n" );
1088 $this->begin( __METHOD__
. " ($fname)" );
1089 $this->mTrxAutomatic
= true;
1093 # Keep track of whether the transaction has write queries pending
1094 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1095 $this->mTrxDoneWrites
= true;
1096 Profiler
::instance()->transactionWritingIn(
1097 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1102 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1104 if ( !Profiler
::instance()->isStub() ) {
1105 # generalizeSQL will probably cut down the query to reasonable
1106 # logging size most of the time. The substr is really just a sanity check.
1108 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1109 $totalProf = 'DatabaseBase::query-master';
1111 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1112 $totalProf = 'DatabaseBase::query';
1114 # Include query transaction state
1115 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1117 $trx = $this->mTrxLevel ?
'TRX=yes' : 'TRX=no';
1118 wfProfileIn( $totalProf );
1119 wfProfileIn( $queryProf );
1122 if ( $this->debug() ) {
1126 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1128 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1130 $master = $isMaster ?
'master' : 'slave';
1131 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1134 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1136 # Avoid fatals if close() was called
1137 if ( !$this->isOpen() ) {
1138 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1141 # Do the query and handle errors
1142 $ret = $this->doQuery( $commentedSql );
1144 MWDebug
::queryTime( $queryId );
1146 # Try reconnecting if the connection was lost
1147 if ( false === $ret && $this->wasErrorReissuable() ) {
1148 # Transaction is gone, like it or not
1149 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1150 $this->mTrxLevel
= 0;
1151 $this->mTrxIdleCallbacks
= array(); // bug 65263
1152 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1153 wfDebug( "Connection lost, reconnecting...\n" );
1154 # Stash the last error values since ping() might clear them
1155 $lastError = $this->lastError();
1156 $lastErrno = $this->lastErrno();
1157 if ( $this->ping() ) {
1158 global $wgRequestTime;
1159 wfDebug( "Reconnected\n" );
1160 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1162 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1163 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1164 if ( $elapsed < 300 ) {
1165 # Not a database error to lose a transaction after a minute or two
1166 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
1169 # Leave $ret as false and let an error be reported.
1170 # Callers may catch the exception and continue to use the DB.
1171 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1173 # Should be safe to silently retry (no trx and thus no callbacks)
1174 $ret = $this->doQuery( $commentedSql );
1177 wfDebug( "Failed\n" );
1181 if ( false === $ret ) {
1182 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1185 if ( !Profiler
::instance()->isStub() ) {
1186 wfProfileOut( $queryProf );
1187 wfProfileOut( $totalProf );
1190 return $this->resultObject( $ret );
1194 * Report a query error. Log the error, and if neither the object ignore
1195 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1197 * @param string $error
1199 * @param string $sql
1200 * @param string $fname
1201 * @param bool $tempIgnore
1202 * @throws DBQueryError
1204 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1205 # Ignore errors during error handling to avoid infinite recursion
1206 $ignore = $this->ignoreErrors( true );
1207 ++
$this->mErrorCount
;
1209 if ( $ignore ||
$tempIgnore ) {
1210 wfDebug( "SQL ERROR (ignored): $error\n" );
1211 $this->ignoreErrors( $ignore );
1213 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1214 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
1215 wfDebug( "SQL ERROR: " . $error . "\n" );
1216 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1221 * Intended to be compatible with the PEAR::DB wrapper functions.
1222 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1224 * ? = scalar value, quoted as necessary
1225 * ! = raw SQL bit (a function for instance)
1226 * & = filename; reads the file and inserts as a blob
1227 * (we don't use this though...)
1229 * @param string $sql
1230 * @param string $func
1234 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1235 /* MySQL doesn't support prepared statements (yet), so just
1236 * pack up the query for reference. We'll manually replace
1239 return array( 'query' => $sql, 'func' => $func );
1243 * Free a prepared query, generated by prepare().
1244 * @param string $prepared
1246 protected function freePrepared( $prepared ) {
1247 /* No-op by default */
1251 * Execute a prepared query with the various arguments
1252 * @param string $prepared The prepared sql
1253 * @param mixed $args Either an array here, or put scalars as varargs
1255 * @return ResultWrapper
1257 public function execute( $prepared, $args = null ) {
1258 if ( !is_array( $args ) ) {
1260 $args = func_get_args();
1261 array_shift( $args );
1264 $sql = $this->fillPrepared( $prepared['query'], $args );
1266 return $this->query( $sql, $prepared['func'] );
1270 * For faking prepared SQL statements on DBs that don't support it directly.
1272 * @param string $preparedQuery A 'preparable' SQL statement
1273 * @param array $args Array of Arguments to fill it with
1274 * @return string Executable SQL
1276 public function fillPrepared( $preparedQuery, $args ) {
1278 $this->preparedArgs
=& $args;
1280 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1281 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1285 * preg_callback func for fillPrepared()
1286 * The arguments should be in $this->preparedArgs and must not be touched
1287 * while we're doing this.
1289 * @param array $matches
1290 * @throws DBUnexpectedError
1293 protected function fillPreparedArg( $matches ) {
1294 switch ( $matches[1] ) {
1303 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1305 switch ( $matches[1] ) {
1307 return $this->addQuotes( $arg );
1311 # return $this->addQuotes( file_get_contents( $arg ) );
1312 throw new DBUnexpectedError(
1314 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1317 throw new DBUnexpectedError(
1319 'Received invalid match. This should never happen!'
1325 * Free a result object returned by query() or select(). It's usually not
1326 * necessary to call this, just use unset() or let the variable holding
1327 * the result object go out of scope.
1329 * @param mixed $res A SQL result
1331 public function freeResult( $res ) {
1335 * A SELECT wrapper which returns a single field from a single result row.
1337 * Usually throws a DBQueryError on failure. If errors are explicitly
1338 * ignored, returns false on failure.
1340 * If no result rows are returned from the query, false is returned.
1342 * @param string|array $table Table name. See DatabaseBase::select() for details.
1343 * @param string $var The field name to select. This must be a valid SQL
1344 * fragment: do not use unvalidated user input.
1345 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1346 * @param string $fname The function name of the caller.
1347 * @param string|array $options The query options. See DatabaseBase::select() for details.
1349 * @return bool|mixed The value from the field, or false on failure.
1351 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1354 if ( !is_array( $options ) ) {
1355 $options = array( $options );
1358 $options['LIMIT'] = 1;
1360 $res = $this->select( $table, $var, $cond, $fname, $options );
1362 if ( $res === false ||
!$this->numRows( $res ) ) {
1366 $row = $this->fetchRow( $res );
1368 if ( $row !== false ) {
1369 return reset( $row );
1376 * Returns an optional USE INDEX clause to go after the table, and a
1377 * string to go at the end of the query.
1379 * @param array $options Associative array of options to be turned into
1380 * an SQL query, valid keys are listed in the function.
1382 * @see DatabaseBase::select()
1384 public function makeSelectOptions( $options ) {
1385 $preLimitTail = $postLimitTail = '';
1388 $noKeyOptions = array();
1390 foreach ( $options as $key => $option ) {
1391 if ( is_numeric( $key ) ) {
1392 $noKeyOptions[$option] = true;
1396 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1398 $preLimitTail .= $this->makeOrderBy( $options );
1400 // if (isset($options['LIMIT'])) {
1401 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1402 // isset($options['OFFSET']) ? $options['OFFSET']
1406 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1407 $postLimitTail .= ' FOR UPDATE';
1410 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1411 $postLimitTail .= ' LOCK IN SHARE MODE';
1414 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1415 $startOpts .= 'DISTINCT';
1418 # Various MySQL extensions
1419 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1420 $startOpts .= ' /*! STRAIGHT_JOIN */';
1423 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1424 $startOpts .= ' HIGH_PRIORITY';
1427 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1428 $startOpts .= ' SQL_BIG_RESULT';
1431 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1432 $startOpts .= ' SQL_BUFFER_RESULT';
1435 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1436 $startOpts .= ' SQL_SMALL_RESULT';
1439 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1440 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1443 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1444 $startOpts .= ' SQL_CACHE';
1447 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1448 $startOpts .= ' SQL_NO_CACHE';
1451 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1452 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1457 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1461 * Returns an optional GROUP BY with an optional HAVING
1463 * @param array $options Associative array of options
1465 * @see DatabaseBase::select()
1468 public function makeGroupByWithHaving( $options ) {
1470 if ( isset( $options['GROUP BY'] ) ) {
1471 $gb = is_array( $options['GROUP BY'] )
1472 ?
implode( ',', $options['GROUP BY'] )
1473 : $options['GROUP BY'];
1474 $sql .= ' GROUP BY ' . $gb;
1476 if ( isset( $options['HAVING'] ) ) {
1477 $having = is_array( $options['HAVING'] )
1478 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1479 : $options['HAVING'];
1480 $sql .= ' HAVING ' . $having;
1487 * Returns an optional ORDER BY
1489 * @param array $options Associative array of options
1491 * @see DatabaseBase::select()
1494 public function makeOrderBy( $options ) {
1495 if ( isset( $options['ORDER BY'] ) ) {
1496 $ob = is_array( $options['ORDER BY'] )
1497 ?
implode( ',', $options['ORDER BY'] )
1498 : $options['ORDER BY'];
1500 return ' ORDER BY ' . $ob;
1507 * Execute a SELECT query constructed using the various parameters provided.
1508 * See below for full details of the parameters.
1510 * @param string|array $table Table name
1511 * @param string|array $vars Field names
1512 * @param string|array $conds Conditions
1513 * @param string $fname Caller function name
1514 * @param array $options Query options
1515 * @param array $join_conds Join conditions
1518 * @param string|array $table
1520 * May be either an array of table names, or a single string holding a table
1521 * name. If an array is given, table aliases can be specified, for example:
1523 * array( 'a' => 'user' )
1525 * This includes the user table in the query, with the alias "a" available
1526 * for use in field names (e.g. a.user_name).
1528 * All of the table names given here are automatically run through
1529 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1530 * added, and various other table name mappings to be performed.
1533 * @param string|array $vars
1535 * May be either a field name or an array of field names. The field names
1536 * can be complete fragments of SQL, for direct inclusion into the SELECT
1537 * query. If an array is given, field aliases can be specified, for example:
1539 * array( 'maxrev' => 'MAX(rev_id)' )
1541 * This includes an expression with the alias "maxrev" in the query.
1543 * If an expression is given, care must be taken to ensure that it is
1547 * @param string|array $conds
1549 * May be either a string containing a single condition, or an array of
1550 * conditions. If an array is given, the conditions constructed from each
1551 * element are combined with AND.
1553 * Array elements may take one of two forms:
1555 * - Elements with a numeric key are interpreted as raw SQL fragments.
1556 * - Elements with a string key are interpreted as equality conditions,
1557 * where the key is the field name.
1558 * - If the value of such an array element is a scalar (such as a
1559 * string), it will be treated as data and thus quoted appropriately.
1560 * If it is null, an IS NULL clause will be added.
1561 * - If the value is an array, an IN(...) clause will be constructed,
1562 * such that the field name may match any of the elements in the
1563 * array. The elements of the array will be quoted.
1565 * Note that expressions are often DBMS-dependent in their syntax.
1566 * DBMS-independent wrappers are provided for constructing several types of
1567 * expression commonly used in condition queries. See:
1568 * - DatabaseBase::buildLike()
1569 * - DatabaseBase::conditional()
1572 * @param string|array $options
1574 * Optional: Array of query options. Boolean options are specified by
1575 * including them in the array as a string value with a numeric key, for
1578 * array( 'FOR UPDATE' )
1580 * The supported options are:
1582 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1583 * with LIMIT can theoretically be used for paging through a result set,
1584 * but this is discouraged in MediaWiki for performance reasons.
1586 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1587 * and then the first rows are taken until the limit is reached. LIMIT
1588 * is applied to a result set after OFFSET.
1590 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1591 * changed until the next COMMIT.
1593 * - DISTINCT: Boolean: return only unique result rows.
1595 * - GROUP BY: May be either an SQL fragment string naming a field or
1596 * expression to group by, or an array of such SQL fragments.
1598 * - HAVING: May be either an string containing a HAVING clause or an array of
1599 * conditions building the HAVING clause. If an array is given, the conditions
1600 * constructed from each element are combined with AND.
1602 * - ORDER BY: May be either an SQL fragment giving a field name or
1603 * expression to order by, or an array of such SQL fragments.
1605 * - USE INDEX: This may be either a string giving the index name to use
1606 * for the query, or an array. If it is an associative array, each key
1607 * gives the table name (or alias), each value gives the index name to
1608 * use for that table. All strings are SQL fragments and so should be
1609 * validated by the caller.
1611 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1612 * instead of SELECT.
1614 * And also the following boolean MySQL extensions, see the MySQL manual
1615 * for documentation:
1617 * - LOCK IN SHARE MODE
1621 * - SQL_BUFFER_RESULT
1622 * - SQL_SMALL_RESULT
1623 * - SQL_CALC_FOUND_ROWS
1628 * @param string|array $join_conds
1630 * Optional associative array of table-specific join conditions. In the
1631 * most common case, this is unnecessary, since the join condition can be
1632 * in $conds. However, it is useful for doing a LEFT JOIN.
1634 * The key of the array contains the table name or alias. The value is an
1635 * array with two elements, numbered 0 and 1. The first gives the type of
1636 * join, the second is an SQL fragment giving the join condition for that
1637 * table. For example:
1639 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1641 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1642 * with no rows in it will be returned. If there was a query error, a
1643 * DBQueryError exception will be thrown, except if the "ignore errors"
1644 * option was set, in which case false will be returned.
1646 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1647 $options = array(), $join_conds = array() ) {
1648 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1650 return $this->query( $sql, $fname );
1654 * The equivalent of DatabaseBase::select() except that the constructed SQL
1655 * is returned, instead of being immediately executed. This can be useful for
1656 * doing UNION queries, where the SQL text of each query is needed. In general,
1657 * however, callers outside of Database classes should just use select().
1659 * @param string|array $table Table name
1660 * @param string|array $vars Field names
1661 * @param string|array $conds Conditions
1662 * @param string $fname Caller function name
1663 * @param string|array $options Query options
1664 * @param string|array $join_conds Join conditions
1666 * @return string SQL query string.
1667 * @see DatabaseBase::select()
1669 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1670 $options = array(), $join_conds = array()
1672 if ( is_array( $vars ) ) {
1673 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1676 $options = (array)$options;
1677 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1678 ?
$options['USE INDEX']
1681 if ( is_array( $table ) ) {
1683 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1684 } elseif ( $table != '' ) {
1685 if ( $table[0] == ' ' ) {
1686 $from = ' FROM ' . $table;
1689 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1695 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1696 $this->makeSelectOptions( $options );
1698 if ( !empty( $conds ) ) {
1699 if ( is_array( $conds ) ) {
1700 $conds = $this->makeList( $conds, LIST_AND
);
1702 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1704 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1707 if ( isset( $options['LIMIT'] ) ) {
1708 $sql = $this->limitResult( $sql, $options['LIMIT'],
1709 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1711 $sql = "$sql $postLimitTail";
1713 if ( isset( $options['EXPLAIN'] ) ) {
1714 $sql = 'EXPLAIN ' . $sql;
1721 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1722 * that a single row object is returned. If the query returns no rows,
1723 * false is returned.
1725 * @param string|array $table Table name
1726 * @param string|array $vars Field names
1727 * @param array $conds Conditions
1728 * @param string $fname Caller function name
1729 * @param string|array $options Query options
1730 * @param array|string $join_conds Join conditions
1732 * @return stdClass|bool
1734 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1735 $options = array(), $join_conds = array()
1737 $options = (array)$options;
1738 $options['LIMIT'] = 1;
1739 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1741 if ( $res === false ) {
1745 if ( !$this->numRows( $res ) ) {
1749 $obj = $this->fetchObject( $res );
1755 * Estimate rows in dataset.
1757 * MySQL allows you to estimate the number of rows that would be returned
1758 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1759 * index cardinality statistics, and is notoriously inaccurate, especially
1760 * when large numbers of rows have recently been added or deleted.
1762 * For DBMSs that don't support fast result size estimation, this function
1763 * will actually perform the SELECT COUNT(*).
1765 * Takes the same arguments as DatabaseBase::select().
1767 * @param string $table Table name
1768 * @param string $vars Unused
1769 * @param array|string $conds Filters on the table
1770 * @param string $fname Function name for profiling
1771 * @param array $options Options for select
1772 * @return int Row count
1774 public function estimateRowCount( $table, $vars = '*', $conds = '',
1775 $fname = __METHOD__
, $options = array()
1778 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1781 $row = $this->fetchRow( $res );
1782 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1789 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1790 * It's only slightly flawed. Don't use for anything important.
1792 * @param string $sql A SQL Query
1796 static function generalizeSQL( $sql ) {
1797 # This does the same as the regexp below would do, but in such a way
1798 # as to avoid crashing php on some large strings.
1799 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1801 $sql = str_replace( "\\\\", '', $sql );
1802 $sql = str_replace( "\\'", '', $sql );
1803 $sql = str_replace( "\\\"", '', $sql );
1804 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1805 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1807 # All newlines, tabs, etc replaced by single space
1808 $sql = preg_replace( '/\s+/', ' ', $sql );
1811 # except the ones surrounded by characters, e.g. l10n
1812 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1813 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1819 * Determines whether a field exists in a table
1821 * @param string $table Table name
1822 * @param string $field Filed to check on that table
1823 * @param string $fname Calling function name (optional)
1824 * @return bool Whether $table has filed $field
1826 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1827 $info = $this->fieldInfo( $table, $field );
1833 * Determines whether an index exists
1834 * Usually throws a DBQueryError on failure
1835 * If errors are explicitly ignored, returns NULL on failure
1837 * @param string $table
1838 * @param string $index
1839 * @param string $fname
1842 public function indexExists( $table, $index, $fname = __METHOD__
) {
1843 if ( !$this->tableExists( $table ) ) {
1847 $info = $this->indexInfo( $table, $index, $fname );
1848 if ( is_null( $info ) ) {
1851 return $info !== false;
1856 * Query whether a given table exists
1858 * @param string $table
1859 * @param string $fname
1862 public function tableExists( $table, $fname = __METHOD__
) {
1863 $table = $this->tableName( $table );
1864 $old = $this->ignoreErrors( true );
1865 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1866 $this->ignoreErrors( $old );
1872 * Determines if a given index is unique
1874 * @param string $table
1875 * @param string $index
1879 public function indexUnique( $table, $index ) {
1880 $indexInfo = $this->indexInfo( $table, $index );
1882 if ( !$indexInfo ) {
1886 return !$indexInfo[0]->Non_unique
;
1890 * Helper for DatabaseBase::insert().
1892 * @param array $options
1895 protected function makeInsertOptions( $options ) {
1896 return implode( ' ', $options );
1900 * INSERT wrapper, inserts an array into a table.
1904 * - A single associative array. The array keys are the field names, and
1905 * the values are the values to insert. The values are treated as data
1906 * and will be quoted appropriately. If NULL is inserted, this will be
1907 * converted to a database NULL.
1908 * - An array with numeric keys, holding a list of associative arrays.
1909 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1910 * each subarray must be identical to each other, and in the same order.
1912 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1915 * $options is an array of options, with boolean options encoded as values
1916 * with numeric keys, in the same style as $options in
1917 * DatabaseBase::select(). Supported options are:
1919 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1920 * any rows which cause duplicate key errors are not inserted. It's
1921 * possible to determine how many rows were successfully inserted using
1922 * DatabaseBase::affectedRows().
1924 * @param string $table Table name. This will be passed through
1925 * DatabaseBase::tableName().
1926 * @param array $a Array of rows to insert
1927 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1928 * @param array $options Array of options
1932 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1933 # No rows to insert, easy just return now
1934 if ( !count( $a ) ) {
1938 $table = $this->tableName( $table );
1940 if ( !is_array( $options ) ) {
1941 $options = array( $options );
1945 if ( isset( $options['fileHandle'] ) ) {
1946 $fh = $options['fileHandle'];
1948 $options = $this->makeInsertOptions( $options );
1950 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1952 $keys = array_keys( $a[0] );
1955 $keys = array_keys( $a );
1958 $sql = 'INSERT ' . $options .
1959 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1963 foreach ( $a as $row ) {
1969 $sql .= '(' . $this->makeList( $row ) . ')';
1972 $sql .= '(' . $this->makeList( $a ) . ')';
1975 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1977 } elseif ( $fh !== null ) {
1981 return (bool)$this->query( $sql, $fname );
1985 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1987 * @param array $options
1990 protected function makeUpdateOptionsArray( $options ) {
1991 if ( !is_array( $options ) ) {
1992 $options = array( $options );
1997 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1998 $opts[] = $this->lowPriorityOption();
2001 if ( in_array( 'IGNORE', $options ) ) {
2009 * Make UPDATE options for the DatabaseBase::update function
2011 * @param array $options The options passed to DatabaseBase::update
2014 protected function makeUpdateOptions( $options ) {
2015 $opts = $this->makeUpdateOptionsArray( $options );
2017 return implode( ' ', $opts );
2021 * UPDATE wrapper. Takes a condition array and a SET array.
2023 * @param string $table Name of the table to UPDATE. This will be passed through
2024 * DatabaseBase::tableName().
2025 * @param array $values An array of values to SET. For each array element,
2026 * the key gives the field name, and the value gives the data to set
2027 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2028 * @param array $conds An array of conditions (WHERE). See
2029 * DatabaseBase::select() for the details of the format of condition
2030 * arrays. Use '*' to update all rows.
2031 * @param string $fname The function name of the caller (from __METHOD__),
2032 * for logging and profiling.
2033 * @param array $options An array of UPDATE options, can be:
2034 * - IGNORE: Ignore unique key conflicts
2035 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2038 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2039 $table = $this->tableName( $table );
2040 $opts = $this->makeUpdateOptions( $options );
2041 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2043 if ( $conds !== array() && $conds !== '*' ) {
2044 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2047 return $this->query( $sql, $fname );
2051 * Makes an encoded list of strings from an array
2053 * @param array $a Containing the data
2054 * @param int $mode Constant
2055 * - LIST_COMMA: Comma separated, no field names
2056 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2057 * documentation for $conds in DatabaseBase::select().
2058 * - LIST_OR: ORed WHERE clause (without the WHERE)
2059 * - LIST_SET: Comma separated with field names, like a SET clause
2060 * - LIST_NAMES: Comma separated field names
2061 * @throws MWException|DBUnexpectedError
2064 public function makeList( $a, $mode = LIST_COMMA
) {
2065 if ( !is_array( $a ) ) {
2066 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2072 foreach ( $a as $field => $value ) {
2074 if ( $mode == LIST_AND
) {
2076 } elseif ( $mode == LIST_OR
) {
2085 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2086 $list .= "($value)";
2087 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2089 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2090 if ( count( $value ) == 0 ) {
2091 throw new MWException( __METHOD__
. ": empty input for field $field" );
2092 } elseif ( count( $value ) == 1 ) {
2093 // Special-case single values, as IN isn't terribly efficient
2094 // Don't necessarily assume the single key is 0; we don't
2095 // enforce linear numeric ordering on other arrays here.
2096 $value = array_values( $value );
2097 $list .= $field . " = " . $this->addQuotes( $value[0] );
2099 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2101 } elseif ( $value === null ) {
2102 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2103 $list .= "$field IS ";
2104 } elseif ( $mode == LIST_SET
) {
2105 $list .= "$field = ";
2109 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2110 $list .= "$field = ";
2112 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2120 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2121 * The keys on each level may be either integers or strings.
2123 * @param array $data Organized as 2-d
2124 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2125 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2126 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2127 * @return string|bool SQL fragment, or false if no items in array
2129 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2132 foreach ( $data as $base => $sub ) {
2133 if ( count( $sub ) ) {
2134 $conds[] = $this->makeList(
2135 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2141 return $this->makeList( $conds, LIST_OR
);
2143 // Nothing to search for...
2149 * Return aggregated value alias
2151 * @param array $valuedata
2152 * @param string $valuename
2156 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2161 * @param string $field
2164 public function bitNot( $field ) {
2169 * @param string $fieldLeft
2170 * @param string $fieldRight
2173 public function bitAnd( $fieldLeft, $fieldRight ) {
2174 return "($fieldLeft & $fieldRight)";
2178 * @param string $fieldLeft
2179 * @param string $fieldRight
2182 public function bitOr( $fieldLeft, $fieldRight ) {
2183 return "($fieldLeft | $fieldRight)";
2187 * Build a concatenation list to feed into a SQL query
2188 * @param array $stringList List of raw SQL expressions; caller is
2189 * responsible for any quoting
2192 public function buildConcat( $stringList ) {
2193 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2197 * Build a GROUP_CONCAT or equivalent statement for a query.
2199 * This is useful for combining a field for several rows into a single string.
2200 * NULL values will not appear in the output, duplicated values will appear,
2201 * and the resulting delimiter-separated values have no defined sort order.
2202 * Code using the results may need to use the PHP unique() or sort() methods.
2204 * @param string $delim Glue to bind the results together
2205 * @param string|array $table Table name
2206 * @param string $field Field name
2207 * @param string|array $conds Conditions
2208 * @param string|array $join_conds Join conditions
2209 * @return string SQL text
2212 public function buildGroupConcatField(
2213 $delim, $table, $field, $conds = '', $join_conds = array()
2215 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2217 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2221 * Change the current database
2223 * @todo Explain what exactly will fail if this is not overridden.
2227 * @return bool Success or failure
2229 public function selectDB( $db ) {
2230 # Stub. Shouldn't cause serious problems if it's not overridden, but
2231 # if your database engine supports a concept similar to MySQL's
2232 # databases you may as well.
2233 $this->mDBname
= $db;
2239 * Get the current DB name
2242 public function getDBname() {
2243 return $this->mDBname
;
2247 * Get the server hostname or IP address
2250 public function getServer() {
2251 return $this->mServer
;
2255 * Format a table name ready for use in constructing an SQL query
2257 * This does two important things: it quotes the table names to clean them up,
2258 * and it adds a table prefix if only given a table name with no quotes.
2260 * All functions of this object which require a table name call this function
2261 * themselves. Pass the canonical name to such functions. This is only needed
2262 * when calling query() directly.
2264 * @param string $name Database table name
2265 * @param string $format One of:
2266 * quoted - Automatically pass the table name through addIdentifierQuotes()
2267 * so that it can be used in a query.
2268 * raw - Do not add identifier quotes to the table name
2269 * @return string Full database name
2271 public function tableName( $name, $format = 'quoted' ) {
2272 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2273 # Skip the entire process when we have a string quoted on both ends.
2274 # Note that we check the end so that we will still quote any use of
2275 # use of `database`.table. But won't break things if someone wants
2276 # to query a database table with a dot in the name.
2277 if ( $this->isQuotedIdentifier( $name ) ) {
2281 # Lets test for any bits of text that should never show up in a table
2282 # name. Basically anything like JOIN or ON which are actually part of
2283 # SQL queries, but may end up inside of the table value to combine
2284 # sql. Such as how the API is doing.
2285 # Note that we use a whitespace test rather than a \b test to avoid
2286 # any remote case where a word like on may be inside of a table name
2287 # surrounded by symbols which may be considered word breaks.
2288 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2292 # Split database and table into proper variables.
2293 # We reverse the explode so that database.table and table both output
2294 # the correct table.
2295 $dbDetails = explode( '.', $name, 2 );
2296 if ( count( $dbDetails ) == 3 ) {
2297 list( $database, $schema, $table ) = $dbDetails;
2298 # We don't want any prefix added in this case
2300 } elseif ( count( $dbDetails ) == 2 ) {
2301 list( $database, $table ) = $dbDetails;
2302 # We don't want any prefix added in this case
2303 # In dbs that support it, $database may actually be the schema
2304 # but that doesn't affect any of the functionality here
2308 list( $table ) = $dbDetails;
2309 if ( $wgSharedDB !== null # We have a shared database
2310 && $this->mForeign
== false # We're not working on a foreign database
2311 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2312 && in_array( $table, $wgSharedTables ) # A shared table is selected
2314 $database = $wgSharedDB;
2315 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2316 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2319 $schema = $this->mSchema
; # Default schema
2320 $prefix = $this->mTablePrefix
; # Default prefix
2324 # Quote $table and apply the prefix if not quoted.
2325 # $tableName might be empty if this is called from Database::replaceVars()
2326 $tableName = "{$prefix}{$table}";
2327 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2328 $tableName = $this->addIdentifierQuotes( $tableName );
2331 # Quote $schema and merge it with the table name if needed
2332 if ( $schema !== null ) {
2333 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2334 $schema = $this->addIdentifierQuotes( $schema );
2336 $tableName = $schema . '.' . $tableName;
2339 # Quote $database and merge it with the table name if needed
2340 if ( $database !== null ) {
2341 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2342 $database = $this->addIdentifierQuotes( $database );
2344 $tableName = $database . '.' . $tableName;
2351 * Fetch a number of table names into an array
2352 * This is handy when you need to construct SQL for joins
2355 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2356 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2357 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2361 public function tableNames() {
2362 $inArray = func_get_args();
2365 foreach ( $inArray as $name ) {
2366 $retVal[$name] = $this->tableName( $name );
2373 * Fetch a number of table names into an zero-indexed numerical array
2374 * This is handy when you need to construct SQL for joins
2377 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2378 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2379 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2383 public function tableNamesN() {
2384 $inArray = func_get_args();
2387 foreach ( $inArray as $name ) {
2388 $retVal[] = $this->tableName( $name );
2395 * Get an aliased table name
2396 * e.g. tableName AS newTableName
2398 * @param string $name Table name, see tableName()
2399 * @param string|bool $alias Alias (optional)
2400 * @return string SQL name for aliased table. Will not alias a table to its own name
2402 public function tableNameWithAlias( $name, $alias = false ) {
2403 if ( !$alias ||
$alias == $name ) {
2404 return $this->tableName( $name );
2406 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2411 * Gets an array of aliased table names
2413 * @param array $tables Array( [alias] => table )
2414 * @return string[] See tableNameWithAlias()
2416 public function tableNamesWithAlias( $tables ) {
2418 foreach ( $tables as $alias => $table ) {
2419 if ( is_numeric( $alias ) ) {
2422 $retval[] = $this->tableNameWithAlias( $table, $alias );
2429 * Get an aliased field name
2430 * e.g. fieldName AS newFieldName
2432 * @param string $name Field name
2433 * @param string|bool $alias Alias (optional)
2434 * @return string SQL name for aliased field. Will not alias a field to its own name
2436 public function fieldNameWithAlias( $name, $alias = false ) {
2437 if ( !$alias ||
(string)$alias === (string)$name ) {
2440 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2445 * Gets an array of aliased field names
2447 * @param array $fields Array( [alias] => field )
2448 * @return string[] See fieldNameWithAlias()
2450 public function fieldNamesWithAlias( $fields ) {
2452 foreach ( $fields as $alias => $field ) {
2453 if ( is_numeric( $alias ) ) {
2456 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2463 * Get the aliased table name clause for a FROM clause
2464 * which might have a JOIN and/or USE INDEX clause
2466 * @param array $tables ( [alias] => table )
2467 * @param array $use_index Same as for select()
2468 * @param array $join_conds Same as for select()
2471 protected function tableNamesWithUseIndexOrJOIN(
2472 $tables, $use_index = array(), $join_conds = array()
2476 $use_index = (array)$use_index;
2477 $join_conds = (array)$join_conds;
2479 foreach ( $tables as $alias => $table ) {
2480 if ( !is_string( $alias ) ) {
2481 // No alias? Set it equal to the table name
2484 // Is there a JOIN clause for this table?
2485 if ( isset( $join_conds[$alias] ) ) {
2486 list( $joinType, $conds ) = $join_conds[$alias];
2487 $tableClause = $joinType;
2488 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2489 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2490 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2492 $tableClause .= ' ' . $use;
2495 $on = $this->makeList( (array)$conds, LIST_AND
);
2497 $tableClause .= ' ON (' . $on . ')';
2500 $retJOIN[] = $tableClause;
2501 } elseif ( isset( $use_index[$alias] ) ) {
2502 // Is there an INDEX clause for this table?
2503 $tableClause = $this->tableNameWithAlias( $table, $alias );
2504 $tableClause .= ' ' . $this->useIndexClause(
2505 implode( ',', (array)$use_index[$alias] )
2508 $ret[] = $tableClause;
2510 $tableClause = $this->tableNameWithAlias( $table, $alias );
2512 $ret[] = $tableClause;
2516 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2517 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2518 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2520 // Compile our final table clause
2521 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2525 * Get the name of an index in a given table
2527 * @param string $index
2530 protected function indexName( $index ) {
2531 // Backwards-compatibility hack
2533 'ar_usertext_timestamp' => 'usertext_timestamp',
2534 'un_user_id' => 'user_id',
2535 'un_user_ip' => 'user_ip',
2538 if ( isset( $renamed[$index] ) ) {
2539 return $renamed[$index];
2546 * Adds quotes and backslashes.
2551 public function addQuotes( $s ) {
2552 if ( $s === null ) {
2555 # This will also quote numeric values. This should be harmless,
2556 # and protects against weird problems that occur when they really
2557 # _are_ strings such as article titles and string->number->string
2558 # conversion is not 1:1.
2559 return "'" . $this->strencode( $s ) . "'";
2564 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2565 * MySQL uses `backticks` while basically everything else uses double quotes.
2566 * Since MySQL is the odd one out here the double quotes are our generic
2567 * and we implement backticks in DatabaseMysql.
2572 public function addIdentifierQuotes( $s ) {
2573 return '"' . str_replace( '"', '""', $s ) . '"';
2577 * Returns if the given identifier looks quoted or not according to
2578 * the database convention for quoting identifiers .
2580 * @param string $name
2583 public function isQuotedIdentifier( $name ) {
2584 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2591 protected function escapeLikeInternal( $s ) {
2592 return addcslashes( $s, '\%_' );
2596 * LIKE statement wrapper, receives a variable-length argument list with
2597 * parts of pattern to match containing either string literals that will be
2598 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2599 * the function could be provided with an array of aforementioned
2602 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2603 * a LIKE clause that searches for subpages of 'My page title'.
2605 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2606 * $query .= $dbr->buildLike( $pattern );
2609 * @return string Fully built LIKE statement
2611 public function buildLike() {
2612 $params = func_get_args();
2614 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2615 $params = $params[0];
2620 foreach ( $params as $value ) {
2621 if ( $value instanceof LikeMatch
) {
2622 $s .= $value->toString();
2624 $s .= $this->escapeLikeInternal( $value );
2628 return " LIKE {$this->addQuotes( $s )} ";
2632 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2636 public function anyChar() {
2637 return new LikeMatch( '_' );
2641 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2645 public function anyString() {
2646 return new LikeMatch( '%' );
2650 * Returns an appropriately quoted sequence value for inserting a new row.
2651 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2652 * subclass will return an integer, and save the value for insertId()
2654 * Any implementation of this function should *not* involve reusing
2655 * sequence numbers created for rolled-back transactions.
2656 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2657 * @param string $seqName
2660 public function nextSequenceValue( $seqName ) {
2665 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2666 * is only needed because a) MySQL must be as efficient as possible due to
2667 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2668 * which index to pick. Anyway, other databases might have different
2669 * indexes on a given table. So don't bother overriding this unless you're
2671 * @param string $index
2674 public function useIndexClause( $index ) {
2679 * REPLACE query wrapper.
2681 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2682 * except that when there is a duplicate key error, the old row is deleted
2683 * and the new row is inserted in its place.
2685 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2686 * perform the delete, we need to know what the unique indexes are so that
2687 * we know how to find the conflicting rows.
2689 * It may be more efficient to leave off unique indexes which are unlikely
2690 * to collide. However if you do this, you run the risk of encountering
2691 * errors which wouldn't have occurred in MySQL.
2693 * @param string $table The table to replace the row(s) in.
2694 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2695 * a field name or an array of field names
2696 * @param array $rows Can be either a single row to insert, or multiple rows,
2697 * in the same format as for DatabaseBase::insert()
2698 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2700 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2701 $quotedTable = $this->tableName( $table );
2703 if ( count( $rows ) == 0 ) {
2708 if ( !is_array( reset( $rows ) ) ) {
2709 $rows = array( $rows );
2712 foreach ( $rows as $row ) {
2713 # Delete rows which collide
2714 if ( $uniqueIndexes ) {
2715 $sql = "DELETE FROM $quotedTable WHERE ";
2717 foreach ( $uniqueIndexes as $index ) {
2724 if ( is_array( $index ) ) {
2726 foreach ( $index as $col ) {
2732 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2735 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2739 $this->query( $sql, $fname );
2742 # Now insert the row
2743 $this->insert( $table, $row, $fname );
2748 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2751 * @param string $table Table name
2752 * @param array|string $rows Row(s) to insert
2753 * @param string $fname Caller function name
2755 * @return ResultWrapper
2757 protected function nativeReplace( $table, $rows, $fname ) {
2758 $table = $this->tableName( $table );
2761 if ( !is_array( reset( $rows ) ) ) {
2762 $rows = array( $rows );
2765 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2768 foreach ( $rows as $row ) {
2775 $sql .= '(' . $this->makeList( $row ) . ')';
2778 return $this->query( $sql, $fname );
2782 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2784 * This updates any conflicting rows (according to the unique indexes) using
2785 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2787 * $rows may be either:
2788 * - A single associative array. The array keys are the field names, and
2789 * the values are the values to insert. The values are treated as data
2790 * and will be quoted appropriately. If NULL is inserted, this will be
2791 * converted to a database NULL.
2792 * - An array with numeric keys, holding a list of associative arrays.
2793 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2794 * each subarray must be identical to each other, and in the same order.
2796 * It may be more efficient to leave off unique indexes which are unlikely
2797 * to collide. However if you do this, you run the risk of encountering
2798 * errors which wouldn't have occurred in MySQL.
2800 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2805 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2806 * @param array $rows A single row or list of rows to insert
2807 * @param array $uniqueIndexes List of single field names or field name tuples
2808 * @param array $set An array of values to SET. For each array element, the
2809 * key gives the field name, and the value gives the data to set that
2810 * field to. The data will be quoted by DatabaseBase::addQuotes().
2811 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2815 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2818 if ( !count( $rows ) ) {
2819 return true; // nothing to do
2822 if ( !is_array( reset( $rows ) ) ) {
2823 $rows = array( $rows );
2826 if ( count( $uniqueIndexes ) ) {
2827 $clauses = array(); // list WHERE clauses that each identify a single row
2828 foreach ( $rows as $row ) {
2829 foreach ( $uniqueIndexes as $index ) {
2830 $index = is_array( $index ) ?
$index : array( $index ); // columns
2831 $rowKey = array(); // unique key to this row
2832 foreach ( $index as $column ) {
2833 $rowKey[$column] = $row[$column];
2835 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2838 $where = array( $this->makeList( $clauses, LIST_OR
) );
2843 $useTrx = !$this->mTrxLevel
;
2845 $this->begin( $fname );
2848 # Update any existing conflicting row(s)
2849 if ( $where !== false ) {
2850 $ok = $this->update( $table, $set, $where, $fname );
2854 # Now insert any non-conflicting row(s)
2855 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2856 } catch ( Exception
$e ) {
2858 $this->rollback( $fname );
2863 $this->commit( $fname );
2870 * DELETE where the condition is a join.
2872 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2873 * we use sub-selects
2875 * For safety, an empty $conds will not delete everything. If you want to
2876 * delete all rows where the join condition matches, set $conds='*'.
2878 * DO NOT put the join condition in $conds.
2880 * @param string $delTable The table to delete from.
2881 * @param string $joinTable The other table.
2882 * @param string $delVar The variable to join on, in the first table.
2883 * @param string $joinVar The variable to join on, in the second table.
2884 * @param array $conds Condition array of field names mapped to variables,
2885 * ANDed together in the WHERE clause
2886 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2887 * @throws DBUnexpectedError
2889 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2893 throw new DBUnexpectedError( $this,
2894 'DatabaseBase::deleteJoin() called with empty $conds' );
2897 $delTable = $this->tableName( $delTable );
2898 $joinTable = $this->tableName( $joinTable );
2899 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2900 if ( $conds != '*' ) {
2901 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2905 $this->query( $sql, $fname );
2909 * Returns the size of a text field, or -1 for "unlimited"
2911 * @param string $table
2912 * @param string $field
2915 public function textFieldSize( $table, $field ) {
2916 $table = $this->tableName( $table );
2917 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2918 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2919 $row = $this->fetchObject( $res );
2923 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2933 * A string to insert into queries to show that they're low-priority, like
2934 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2935 * string and nothing bad should happen.
2937 * @return string Returns the text of the low priority option if it is
2938 * supported, or a blank string otherwise
2940 public function lowPriorityOption() {
2945 * DELETE query wrapper.
2947 * @param array $table Table name
2948 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2949 * for the format. Use $conds == "*" to delete all rows
2950 * @param string $fname Name of the calling function
2951 * @throws DBUnexpectedError
2952 * @return bool|ResultWrapper
2954 public function delete( $table, $conds, $fname = __METHOD__
) {
2956 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2959 $table = $this->tableName( $table );
2960 $sql = "DELETE FROM $table";
2962 if ( $conds != '*' ) {
2963 if ( is_array( $conds ) ) {
2964 $conds = $this->makeList( $conds, LIST_AND
);
2966 $sql .= ' WHERE ' . $conds;
2969 return $this->query( $sql, $fname );
2973 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2974 * into another table.
2976 * @param string $destTable The table name to insert into
2977 * @param string|array $srcTable May be either a table name, or an array of table names
2978 * to include in a join.
2980 * @param array $varMap Must be an associative array of the form
2981 * array( 'dest1' => 'source1', ...). Source items may be literals
2982 * rather than field names, but strings should be quoted with
2983 * DatabaseBase::addQuotes()
2985 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2986 * the details of the format of condition arrays. May be "*" to copy the
2989 * @param string $fname The function name of the caller, from __METHOD__
2991 * @param array $insertOptions Options for the INSERT part of the query, see
2992 * DatabaseBase::insert() for details.
2993 * @param array $selectOptions Options for the SELECT part of the query, see
2994 * DatabaseBase::select() for details.
2996 * @return ResultWrapper
2998 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2999 $fname = __METHOD__
,
3000 $insertOptions = array(), $selectOptions = array()
3002 $destTable = $this->tableName( $destTable );
3004 if ( !is_array( $insertOptions ) ) {
3005 $insertOptions = array( $insertOptions );
3008 $insertOptions = $this->makeInsertOptions( $insertOptions );
3010 if ( !is_array( $selectOptions ) ) {
3011 $selectOptions = array( $selectOptions );
3014 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3016 if ( is_array( $srcTable ) ) {
3017 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3019 $srcTable = $this->tableName( $srcTable );
3022 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3023 " SELECT $startOpts " . implode( ',', $varMap ) .
3024 " FROM $srcTable $useIndex ";
3026 if ( $conds != '*' ) {
3027 if ( is_array( $conds ) ) {
3028 $conds = $this->makeList( $conds, LIST_AND
);
3030 $sql .= " WHERE $conds";
3033 $sql .= " $tailOpts";
3035 return $this->query( $sql, $fname );
3039 * Construct a LIMIT query with optional offset. This is used for query
3040 * pages. The SQL should be adjusted so that only the first $limit rows
3041 * are returned. If $offset is provided as well, then the first $offset
3042 * rows should be discarded, and the next $limit rows should be returned.
3043 * If the result of the query is not ordered, then the rows to be returned
3044 * are theoretically arbitrary.
3046 * $sql is expected to be a SELECT, if that makes a difference.
3048 * The version provided by default works in MySQL and SQLite. It will very
3049 * likely need to be overridden for most other DBMSes.
3051 * @param string $sql SQL query we will append the limit too
3052 * @param int $limit The SQL limit
3053 * @param int|bool $offset The SQL offset (default false)
3054 * @throws DBUnexpectedError
3057 public function limitResult( $sql, $limit, $offset = false ) {
3058 if ( !is_numeric( $limit ) ) {
3059 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3062 return "$sql LIMIT "
3063 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3068 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3069 * within the UNION construct.
3072 public function unionSupportsOrderAndLimit() {
3073 return true; // True for almost every DB supported
3077 * Construct a UNION query
3078 * This is used for providing overload point for other DB abstractions
3079 * not compatible with the MySQL syntax.
3080 * @param array $sqls SQL statements to combine
3081 * @param bool $all Use UNION ALL
3082 * @return string SQL fragment
3084 public function unionQueries( $sqls, $all ) {
3085 $glue = $all ?
') UNION ALL (' : ') UNION (';
3087 return '(' . implode( $glue, $sqls ) . ')';
3091 * Returns an SQL expression for a simple conditional. This doesn't need
3092 * to be overridden unless CASE isn't supported in your DBMS.
3094 * @param string|array $cond SQL expression which will result in a boolean value
3095 * @param string $trueVal SQL expression to return if true
3096 * @param string $falseVal SQL expression to return if false
3097 * @return string SQL fragment
3099 public function conditional( $cond, $trueVal, $falseVal ) {
3100 if ( is_array( $cond ) ) {
3101 $cond = $this->makeList( $cond, LIST_AND
);
3104 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3108 * Returns a comand for str_replace function in SQL query.
3109 * Uses REPLACE() in MySQL
3111 * @param string $orig Column to modify
3112 * @param string $old Column to seek
3113 * @param string $new Column to replace with
3117 public function strreplace( $orig, $old, $new ) {
3118 return "REPLACE({$orig}, {$old}, {$new})";
3122 * Determines how long the server has been up
3127 public function getServerUptime() {
3132 * Determines if the last failure was due to a deadlock
3137 public function wasDeadlock() {
3142 * Determines if the last failure was due to a lock timeout
3147 public function wasLockTimeout() {
3152 * Determines if the last query error was something that should be dealt
3153 * with by pinging the connection and reissuing the query.
3158 public function wasErrorReissuable() {
3163 * Determines if the last failure was due to the database being read-only.
3168 public function wasReadOnlyError() {
3173 * Perform a deadlock-prone transaction.
3175 * This function invokes a callback function to perform a set of write
3176 * queries. If a deadlock occurs during the processing, the transaction
3177 * will be rolled back and the callback function will be called again.
3180 * $dbw->deadlockLoop( callback, ... );
3182 * Extra arguments are passed through to the specified callback function.
3184 * Returns whatever the callback function returned on its successful,
3185 * iteration, or false on error, for example if the retry limit was
3190 public function deadlockLoop() {
3191 $this->begin( __METHOD__
);
3192 $args = func_get_args();
3193 $function = array_shift( $args );
3194 $oldIgnore = $this->ignoreErrors( true );
3195 $tries = self
::DEADLOCK_TRIES
;
3197 if ( is_array( $function ) ) {
3198 $fname = $function[0];
3204 $retVal = call_user_func_array( $function, $args );
3205 $error = $this->lastError();
3206 $errno = $this->lastErrno();
3207 $sql = $this->lastQuery();
3210 if ( $this->wasDeadlock() ) {
3212 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3214 $this->reportQueryError( $error, $errno, $sql, $fname );
3217 } while ( $this->wasDeadlock() && --$tries > 0 );
3219 $this->ignoreErrors( $oldIgnore );
3221 if ( $tries <= 0 ) {
3222 $this->rollback( __METHOD__
);
3223 $this->reportQueryError( $error, $errno, $sql, $fname );
3227 $this->commit( __METHOD__
);
3234 * Wait for the slave to catch up to a given master position.
3236 * @param DBMasterPos $pos
3237 * @param int $timeout The maximum number of seconds to wait for
3239 * @return int Zero if the slave was past that position already,
3240 * greater than zero if we waited for some period of time, less than
3241 * zero if we timed out.
3243 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3244 # Real waits are implemented in the subclass.
3249 * Get the replication position of this slave
3251 * @return DBMasterPos|bool False if this is not a slave.
3253 public function getSlavePos() {
3259 * Get the position of this master
3261 * @return DBMasterPos|bool False if this is not a master
3263 public function getMasterPos() {
3269 * Run an anonymous function as soon as there is no transaction pending.
3270 * If there is a transaction and it is rolled back, then the callback is cancelled.
3271 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3272 * Callbacks must commit any transactions that they begin.
3274 * This is useful for updates to different systems or when separate transactions are needed.
3275 * For example, one might want to enqueue jobs into a system outside the database, but only
3276 * after the database is updated so that the jobs will see the data when they actually run.
3277 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3279 * @param callable $callback
3282 final public function onTransactionIdle( $callback ) {
3283 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3284 if ( !$this->mTrxLevel
) {
3285 $this->runOnTransactionIdleCallbacks();
3290 * Run an anonymous function before the current transaction commits or now if there is none.
3291 * If there is a transaction and it is rolled back, then the callback is cancelled.
3292 * Callbacks must not start nor commit any transactions.
3294 * This is useful for updates that easily cause deadlocks if locks are held too long
3295 * but where atomicity is strongly desired for these updates and some related updates.
3297 * @param callable $callback
3300 final public function onTransactionPreCommitOrIdle( $callback ) {
3301 if ( $this->mTrxLevel
) {
3302 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3304 $this->onTransactionIdle( $callback ); // this will trigger immediately
3309 * Actually any "on transaction idle" callbacks.
3313 protected function runOnTransactionIdleCallbacks() {
3314 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3316 $e = $ePrior = null; // last exception
3317 do { // callbacks may add callbacks :)
3318 $callbacks = $this->mTrxIdleCallbacks
;
3319 $this->mTrxIdleCallbacks
= array(); // recursion guard
3320 foreach ( $callbacks as $callback ) {
3322 list( $phpCallback ) = $callback;
3323 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3324 call_user_func( $phpCallback );
3325 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3326 } catch ( Exception
$e ) {
3328 MWExceptionHandler
::logException( $ePrior );
3333 } while ( count( $this->mTrxIdleCallbacks
) );
3335 if ( $e instanceof Exception
) {
3336 throw $e; // re-throw any last exception
3341 * Actually any "on transaction pre-commit" callbacks.
3345 protected function runOnTransactionPreCommitCallbacks() {
3346 $e = $ePrior = null; // last exception
3347 do { // callbacks may add callbacks :)
3348 $callbacks = $this->mTrxPreCommitCallbacks
;
3349 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3350 foreach ( $callbacks as $callback ) {
3352 list( $phpCallback ) = $callback;
3353 call_user_func( $phpCallback );
3354 } catch ( Exception
$e ) {
3356 MWExceptionHandler
::logException( $ePrior );
3361 } while ( count( $this->mTrxPreCommitCallbacks
) );
3363 if ( $e instanceof Exception
) {
3364 throw $e; // re-throw any last exception
3369 * Begin an atomic section of statements
3371 * If a transaction has been started already, just keep track of the given
3372 * section name to make sure the transaction is not committed pre-maturely.
3373 * This function can be used in layers (with sub-sections), so use a stack
3374 * to keep track of the different atomic sections. If there is no transaction,
3375 * start one implicitly.
3377 * The goal of this function is to create an atomic section of SQL queries
3378 * without having to start a new transaction if it already exists.
3380 * Atomic sections are more strict than transactions. With transactions,
3381 * attempting to begin a new transaction when one is already running results
3382 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3383 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3384 * and any database transactions cannot be began or committed until all atomic
3385 * levels are closed. There is no such thing as implicitly opening or closing
3386 * an atomic section.
3389 * @param string $fname
3392 final public function startAtomic( $fname = __METHOD__
) {
3393 if ( !$this->mTrxLevel
) {
3394 $this->begin( $fname );
3395 $this->mTrxAutomatic
= true;
3396 $this->mTrxAutomaticAtomic
= true;
3399 $this->mTrxAtomicLevels
->push( $fname );
3403 * Ends an atomic section of SQL statements
3405 * Ends the next section of atomic SQL statements and commits the transaction
3409 * @see DatabaseBase::startAtomic
3410 * @param string $fname
3413 final public function endAtomic( $fname = __METHOD__
) {
3414 if ( !$this->mTrxLevel
) {
3415 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3417 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3418 $this->mTrxAtomicLevels
->pop() !== $fname
3420 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3423 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3424 $this->commit( $fname, 'flush' );
3429 * Begin a transaction. If a transaction is already in progress,
3430 * that transaction will be committed before the new transaction is started.
3432 * Note that when the DBO_TRX flag is set (which is usually the case for web
3433 * requests, but not for maintenance scripts), any previous database query
3434 * will have started a transaction automatically.
3436 * Nesting of transactions is not supported. Attempts to nest transactions
3437 * will cause a warning, unless the current transaction was started
3438 * automatically because of the DBO_TRX flag.
3440 * @param string $fname
3443 final public function begin( $fname = __METHOD__
) {
3444 global $wgDebugDBTransactions;
3446 if ( $this->mTrxLevel
) { // implicit commit
3447 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3448 // If the current transaction was an automatic atomic one, then we definitely have
3449 // a problem. Same if there is any unclosed atomic level.
3450 throw new DBUnexpectedError( $this,
3451 "Attempted to start explicit transaction when atomic levels are still open."
3453 } elseif ( !$this->mTrxAutomatic
) {
3454 // We want to warn about inadvertently nested begin/commit pairs, but not about
3455 // auto-committing implicit transactions that were started by query() via DBO_TRX
3456 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3457 " performing implicit commit!";
3459 wfLogDBError( $msg );
3461 // if the transaction was automatic and has done write operations,
3462 // log it if $wgDebugDBTransactions is enabled.
3463 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3464 wfDebug( "$fname: Automatic transaction with writes in progress" .
3465 " (from {$this->mTrxFname}), performing implicit commit!\n"
3470 $this->runOnTransactionPreCommitCallbacks();
3471 $this->doCommit( $fname );
3472 if ( $this->mTrxDoneWrites
) {
3473 Profiler
::instance()->transactionWritingOut(
3474 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3476 $this->runOnTransactionIdleCallbacks();
3479 # Avoid fatals if close() was called
3480 if ( !$this->isOpen() ) {
3481 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3484 $this->doBegin( $fname );
3485 $this->mTrxFname
= $fname;
3486 $this->mTrxDoneWrites
= false;
3487 $this->mTrxAutomatic
= false;
3488 $this->mTrxAutomaticAtomic
= false;
3489 $this->mTrxAtomicLevels
= new SplStack
;
3490 $this->mTrxIdleCallbacks
= array();
3491 $this->mTrxPreCommitCallbacks
= array();
3492 $this->mTrxShortId
= wfRandomString( 12 );
3496 * Issues the BEGIN command to the database server.
3498 * @see DatabaseBase::begin()
3499 * @param string $fname
3501 protected function doBegin( $fname ) {
3502 $this->query( 'BEGIN', $fname );
3503 $this->mTrxLevel
= 1;
3507 * Commits a transaction previously started using begin().
3508 * If no transaction is in progress, a warning is issued.
3510 * Nesting of transactions is not supported.
3512 * @param string $fname
3513 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3514 * explicitly committing implicit transactions, or calling commit when no
3515 * transaction is in progress. This will silently break any ongoing
3516 * explicit transaction. Only set the flush flag if you are sure that it
3517 * is safe to ignore these warnings in your context.
3518 * @throws DBUnexpectedError
3520 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3521 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3522 // There are still atomic sections open. This cannot be ignored
3523 throw new DBUnexpectedError(
3525 "Attempted to commit transaction while atomic sections are still open"
3529 if ( $flush === 'flush' ) {
3530 if ( !$this->mTrxLevel
) {
3531 return; // nothing to do
3532 } elseif ( !$this->mTrxAutomatic
) {
3533 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3536 if ( !$this->mTrxLevel
) {
3537 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3538 return; // nothing to do
3539 } elseif ( $this->mTrxAutomatic
) {
3540 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3544 # Avoid fatals if close() was called
3545 if ( !$this->isOpen() ) {
3546 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3549 $this->runOnTransactionPreCommitCallbacks();
3550 $this->doCommit( $fname );
3551 if ( $this->mTrxDoneWrites
) {
3552 Profiler
::instance()->transactionWritingOut(
3553 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3555 $this->runOnTransactionIdleCallbacks();
3559 * Issues the COMMIT command to the database server.
3561 * @see DatabaseBase::commit()
3562 * @param string $fname
3564 protected function doCommit( $fname ) {
3565 if ( $this->mTrxLevel
) {
3566 $this->query( 'COMMIT', $fname );
3567 $this->mTrxLevel
= 0;
3572 * Rollback a transaction previously started using begin().
3573 * If no transaction is in progress, a warning is issued.
3575 * No-op on non-transactional databases.
3577 * @param string $fname
3578 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3579 * calling rollback when no transaction is in progress. This will silently
3580 * break any ongoing explicit transaction. Only set the flush flag if you
3581 * are sure that it is safe to ignore these warnings in your context.
3582 * @since 1.23 Added $flush parameter
3584 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3585 if ( $flush !== 'flush' ) {
3586 if ( !$this->mTrxLevel
) {
3587 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3588 return; // nothing to do
3589 } elseif ( $this->mTrxAutomatic
) {
3590 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3593 if ( !$this->mTrxLevel
) {
3594 return; // nothing to do
3595 } elseif ( !$this->mTrxAutomatic
) {
3596 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3600 # Avoid fatals if close() was called
3601 if ( !$this->isOpen() ) {
3602 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3605 $this->doRollback( $fname );
3606 $this->mTrxIdleCallbacks
= array(); // cancel
3607 $this->mTrxPreCommitCallbacks
= array(); // cancel
3608 $this->mTrxAtomicLevels
= new SplStack
;
3609 if ( $this->mTrxDoneWrites
) {
3610 Profiler
::instance()->transactionWritingOut(
3611 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3616 * Issues the ROLLBACK command to the database server.
3618 * @see DatabaseBase::rollback()
3619 * @param string $fname
3621 protected function doRollback( $fname ) {
3622 if ( $this->mTrxLevel
) {
3623 $this->query( 'ROLLBACK', $fname, true );
3624 $this->mTrxLevel
= 0;
3629 * Creates a new table with structure copied from existing table
3630 * Note that unlike most database abstraction functions, this function does not
3631 * automatically append database prefix, because it works at a lower
3632 * abstraction level.
3633 * The table names passed to this function shall not be quoted (this
3634 * function calls addIdentifierQuotes when needed).
3636 * @param string $oldName Name of table whose structure should be copied
3637 * @param string $newName Name of table to be created
3638 * @param bool $temporary Whether the new table should be temporary
3639 * @param string $fname Calling function name
3640 * @throws MWException
3641 * @return bool True if operation was successful
3643 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3646 throw new MWException(
3647 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3651 * List all tables on the database
3653 * @param string $prefix Only show tables with this prefix, e.g. mw_
3654 * @param string $fname Calling function name
3655 * @throws MWException
3657 function listTables( $prefix = null, $fname = __METHOD__
) {
3658 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3662 * Reset the views process cache set by listViews()
3665 final public function clearViewsCache() {
3666 $this->allViews
= null;
3670 * Lists all the VIEWs in the database
3672 * For caching purposes the list of all views should be stored in
3673 * $this->allViews. The process cache can be cleared with clearViewsCache()
3675 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3676 * @param string $fname Name of calling function
3677 * @throws MWException
3680 public function listViews( $prefix = null, $fname = __METHOD__
) {
3681 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3685 * Differentiates between a TABLE and a VIEW
3687 * @param string $name Name of the database-structure to test.
3688 * @throws MWException
3691 public function isView( $name ) {
3692 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3696 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3697 * to the format used for inserting into timestamp fields in this DBMS.
3699 * The result is unquoted, and needs to be passed through addQuotes()
3700 * before it can be included in raw SQL.
3702 * @param string|int $ts
3706 public function timestamp( $ts = 0 ) {
3707 return wfTimestamp( TS_MW
, $ts );
3711 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3712 * to the format used for inserting into timestamp fields in this DBMS. If
3713 * NULL is input, it is passed through, allowing NULL values to be inserted
3714 * into timestamp fields.
3716 * The result is unquoted, and needs to be passed through addQuotes()
3717 * before it can be included in raw SQL.
3719 * @param string|int $ts
3723 public function timestampOrNull( $ts = null ) {
3724 if ( is_null( $ts ) ) {
3727 return $this->timestamp( $ts );
3732 * Take the result from a query, and wrap it in a ResultWrapper if
3733 * necessary. Boolean values are passed through as is, to indicate success
3734 * of write queries or failure.
3736 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3737 * resource, and it was necessary to call this function to convert it to
3738 * a wrapper. Nowadays, raw database objects are never exposed to external
3739 * callers, so this is unnecessary in external code. For compatibility with
3740 * old code, ResultWrapper objects are passed through unaltered.
3742 * @param bool|ResultWrapper|resource $result
3743 * @return bool|ResultWrapper
3745 public function resultObject( $result ) {
3746 if ( empty( $result ) ) {
3748 } elseif ( $result instanceof ResultWrapper
) {
3750 } elseif ( $result === true ) {
3751 // Successful write query
3754 return new ResultWrapper( $this, $result );
3759 * Ping the server and try to reconnect if it there is no connection
3761 * @return bool Success or failure
3763 public function ping() {
3764 # Stub. Not essential to override.
3769 * Get slave lag. Currently supported only by MySQL.
3771 * Note that this function will generate a fatal error on many
3772 * installations. Most callers should use LoadBalancer::safeGetLag()
3775 * @return int Database replication lag in seconds
3777 public function getLag() {
3782 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3786 function maxListLen() {
3791 * Some DBMSs have a special format for inserting into blob fields, they
3792 * don't allow simple quoted strings to be inserted. To insert into such
3793 * a field, pass the data through this function before passing it to
3794 * DatabaseBase::insert().
3799 public function encodeBlob( $b ) {
3804 * Some DBMSs return a special placeholder object representing blob fields
3805 * in result objects. Pass the object through this function to return the
3811 public function decodeBlob( $b ) {
3816 * Override database's default behavior. $options include:
3817 * 'connTimeout' : Set the connection timeout value in seconds.
3818 * May be useful for very long batch queries such as
3819 * full-wiki dumps, where a single query reads out over
3822 * @param array $options
3825 public function setSessionOptions( array $options ) {
3829 * Read and execute SQL commands from a file.
3831 * Returns true on success, error string or exception on failure (depending
3832 * on object's error ignore settings).
3834 * @param string $filename File name to open
3835 * @param bool|callable $lineCallback Optional function called before reading each line
3836 * @param bool|callable $resultCallback Optional function called for each MySQL result
3837 * @param bool|string $fname Calling function name or false if name should be
3838 * generated dynamically using $filename
3839 * @param bool|callable $inputCallback Optional function called for each
3840 * complete line sent
3841 * @throws Exception|MWException
3842 * @return bool|string
3844 public function sourceFile(
3845 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3847 wfSuppressWarnings();
3848 $fp = fopen( $filename, 'r' );
3849 wfRestoreWarnings();
3851 if ( false === $fp ) {
3852 throw new MWException( "Could not open \"{$filename}\".\n" );
3856 $fname = __METHOD__
. "( $filename )";
3860 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3861 } catch ( MWException
$e ) {
3872 * Get the full path of a patch file. Originally based on archive()
3873 * from updaters.inc. Keep in mind this always returns a patch, as
3874 * it fails back to MySQL if no DB-specific patch can be found
3876 * @param string $patch The name of the patch, like patch-something.sql
3877 * @return string Full path to patch file
3879 public function patchPath( $patch ) {
3882 $dbType = $this->getType();
3883 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3884 return "$IP/maintenance/$dbType/archives/$patch";
3886 return "$IP/maintenance/archives/$patch";
3891 * Set variables to be used in sourceFile/sourceStream, in preference to the
3892 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3893 * all. If it's set to false, $GLOBALS will be used.
3895 * @param bool|array $vars Mapping variable name to value.
3897 public function setSchemaVars( $vars ) {
3898 $this->mSchemaVars
= $vars;
3902 * Read and execute commands from an open file handle.
3904 * Returns true on success, error string or exception on failure (depending
3905 * on object's error ignore settings).
3907 * @param resource $fp File handle
3908 * @param bool|callable $lineCallback Optional function called before reading each query
3909 * @param bool|callable $resultCallback Optional function called for each MySQL result
3910 * @param string $fname Calling function name
3911 * @param bool|callable $inputCallback Optional function called for each complete query sent
3912 * @return bool|string
3914 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3915 $fname = __METHOD__
, $inputCallback = false
3919 while ( !feof( $fp ) ) {
3920 if ( $lineCallback ) {
3921 call_user_func( $lineCallback );
3924 $line = trim( fgets( $fp ) );
3926 if ( $line == '' ) {
3930 if ( '-' == $line[0] && '-' == $line[1] ) {
3938 $done = $this->streamStatementEnd( $cmd, $line );
3942 if ( $done ||
feof( $fp ) ) {
3943 $cmd = $this->replaceVars( $cmd );
3945 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3946 $res = $this->query( $cmd, $fname );
3948 if ( $resultCallback ) {
3949 call_user_func( $resultCallback, $res, $this );
3952 if ( false === $res ) {
3953 $err = $this->lastError();
3955 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3966 * Called by sourceStream() to check if we've reached a statement end
3968 * @param string $sql SQL assembled so far
3969 * @param string $newLine New line about to be added to $sql
3970 * @return bool Whether $newLine contains end of the statement
3972 public function streamStatementEnd( &$sql, &$newLine ) {
3973 if ( $this->delimiter
) {
3975 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3976 if ( $newLine != $prev ) {
3985 * Database independent variable replacement. Replaces a set of variables
3986 * in an SQL statement with their contents as given by $this->getSchemaVars().
3988 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3990 * - '{$var}' should be used for text and is passed through the database's
3992 * - `{$var}` should be used for identifiers (eg: table and database names),
3993 * it is passed through the database's addIdentifierQuotes method which
3994 * can be overridden if the database uses something other than backticks.
3995 * - / *$var* / is just encoded, besides traditional table prefix and
3996 * table options its use should be avoided.
3998 * @param string $ins SQL statement to replace variables in
3999 * @return string The new SQL statement with variables replaced
4001 protected function replaceSchemaVars( $ins ) {
4002 $vars = $this->getSchemaVars();
4003 foreach ( $vars as $var => $value ) {
4005 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
4007 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
4009 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
4016 * Replace variables in sourced SQL
4018 * @param string $ins
4021 protected function replaceVars( $ins ) {
4022 $ins = $this->replaceSchemaVars( $ins );
4025 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
4026 array( $this, 'tableNameCallback' ), $ins );
4029 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
4030 array( $this, 'indexNameCallback' ), $ins );
4036 * Get schema variables. If none have been set via setSchemaVars(), then
4037 * use some defaults from the current object.
4041 protected function getSchemaVars() {
4042 if ( $this->mSchemaVars
) {
4043 return $this->mSchemaVars
;
4045 return $this->getDefaultSchemaVars();
4050 * Get schema variables to use if none have been set via setSchemaVars().
4052 * Override this in derived classes to provide variables for tables.sql
4053 * and SQL patch files.
4057 protected function getDefaultSchemaVars() {
4062 * Table name callback
4064 * @param array $matches
4067 protected function tableNameCallback( $matches ) {
4068 return $this->tableName( $matches[1] );
4072 * Index name callback
4074 * @param array $matches
4077 protected function indexNameCallback( $matches ) {
4078 return $this->indexName( $matches[1] );
4082 * Check to see if a named lock is available. This is non-blocking.
4084 * @param string $lockName Name of lock to poll
4085 * @param string $method Name of method calling us
4089 public function lockIsFree( $lockName, $method ) {
4094 * Acquire a named lock
4096 * Abstracted from Filestore::lock() so child classes can implement for
4099 * @param string $lockName Name of lock to aquire
4100 * @param string $method Name of method calling us
4101 * @param int $timeout
4104 public function lock( $lockName, $method, $timeout = 5 ) {
4111 * @param string $lockName Name of lock to release
4112 * @param string $method Name of method calling us
4114 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4115 * by this thread (in which case the lock is not released), and NULL if the named
4116 * lock did not exist
4118 public function unlock( $lockName, $method ) {
4123 * Lock specific tables
4125 * @param array $read Array of tables to lock for read access
4126 * @param array $write Array of tables to lock for write access
4127 * @param string $method Name of caller
4128 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4131 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4136 * Unlock specific tables
4138 * @param string $method The caller
4141 public function unlockTables( $method ) {
4147 * @param string $tableName
4148 * @param string $fName
4149 * @return bool|ResultWrapper
4152 public function dropTable( $tableName, $fName = __METHOD__
) {
4153 if ( !$this->tableExists( $tableName, $fName ) ) {
4156 $sql = "DROP TABLE " . $this->tableName( $tableName );
4157 if ( $this->cascadingDeletes() ) {
4161 return $this->query( $sql, $fName );
4165 * Get search engine class. All subclasses of this need to implement this
4166 * if they wish to use searching.
4170 public function getSearchEngine() {
4171 return 'SearchEngineDummy';
4175 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4176 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4177 * because "i" sorts after all numbers.
4181 public function getInfinity() {
4186 * Encode an expiry time into the DBMS dependent format
4188 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4191 public function encodeExpiry( $expiry ) {
4192 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4193 ?
$this->getInfinity()
4194 : $this->timestamp( $expiry );
4198 * Decode an expiry time into a DBMS independent format
4200 * @param string $expiry DB timestamp field value for expiry
4201 * @param int $format TS_* constant, defaults to TS_MW
4204 public function decodeExpiry( $expiry, $format = TS_MW
) {
4205 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4207 : wfTimestamp( $format, $expiry );
4211 * Allow or deny "big selects" for this session only. This is done by setting
4212 * the sql_big_selects session variable.
4214 * This is a MySQL-specific feature.
4216 * @param bool|string $value True for allow, false for deny, or "default" to
4217 * restore the initial value
4219 public function setBigSelects( $value = true ) {
4227 public function __toString() {
4228 return (string)$this->mConn
;
4232 * Run a few simple sanity checks
4234 public function __destruct() {
4235 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4236 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4238 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4240 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4241 $callers[] = $callbackInfo[1];
4243 $callers = implode( ', ', $callers );
4244 trigger_error( "DB transaction callbacks still pending (from $callers)." );