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_DEFAULT: automatically sets DBO_TRX if not in command line mode
683 * and removes it in command line mode
684 * - DBO_PERSISTENT: use persistant database connection
687 public function getFlag( $flag ) {
688 return !!( $this->mFlags
& $flag );
692 * General read-only accessor
694 * @param string $name
697 public function getProperty( $name ) {
704 public function getWikiID() {
705 if ( $this->mTablePrefix
) {
706 return "{$this->mDBname}-{$this->mTablePrefix}";
708 return $this->mDBname
;
713 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
717 public function getSchemaPath() {
719 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
720 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
722 return "$IP/maintenance/tables.sql";
726 # ------------------------------------------------------------------------------
728 # ------------------------------------------------------------------------------
733 * FIXME: It is possible to construct a Database object with no associated
734 * connection object, by specifying no parameters to __construct(). This
735 * feature is deprecated and should be removed.
737 * DatabaseBase subclasses should not be constructed directly in external
738 * code. DatabaseBase::factory() should be used instead.
740 * @param array $params Parameters passed from DatabaseBase::factory()
742 function __construct( $params = null ) {
743 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
745 $this->mTrxAtomicLevels
= new SplStack
;
747 if ( is_array( $params ) ) { // MW 1.22
748 $server = $params['host'];
749 $user = $params['user'];
750 $password = $params['password'];
751 $dbName = $params['dbname'];
752 $flags = $params['flags'];
753 $tablePrefix = $params['tablePrefix'];
754 $schema = $params['schema'];
755 $foreign = $params['foreign'];
756 } else { // legacy calling pattern
757 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
758 $args = func_get_args();
759 $server = isset( $args[0] ) ?
$args[0] : false;
760 $user = isset( $args[1] ) ?
$args[1] : false;
761 $password = isset( $args[2] ) ?
$args[2] : false;
762 $dbName = isset( $args[3] ) ?
$args[3] : false;
763 $flags = isset( $args[4] ) ?
$args[4] : 0;
764 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
765 $schema = 'get from global';
766 $foreign = isset( $args[6] ) ?
$args[6] : false;
769 $this->mFlags
= $flags;
770 if ( $this->mFlags
& DBO_DEFAULT
) {
771 if ( $wgCommandLineMode ) {
772 $this->mFlags
&= ~DBO_TRX
;
773 if ( $wgDebugDBTransactions ) {
774 wfDebug( "Implicit transaction open disabled.\n" );
777 $this->mFlags |
= DBO_TRX
;
778 if ( $wgDebugDBTransactions ) {
779 wfDebug( "Implicit transaction open enabled.\n" );
784 /** Get the default table prefix*/
785 if ( $tablePrefix == 'get from global' ) {
786 $this->mTablePrefix
= $wgDBprefix;
788 $this->mTablePrefix
= $tablePrefix;
791 /** Get the database schema*/
792 if ( $schema == 'get from global' ) {
793 $this->mSchema
= $wgDBmwschema;
795 $this->mSchema
= $schema;
798 $this->mForeign
= $foreign;
801 $this->open( $server, $user, $password, $dbName );
806 * Called by serialize. Throw an exception when DB connection is serialized.
807 * This causes problems on some database engines because the connection is
808 * not restored on unserialize.
810 public function __sleep() {
811 throw new MWException( 'Database serialization may cause problems, since ' .
812 'the connection is not restored on wakeup.' );
816 * Given a DB type, construct the name of the appropriate child class of
817 * DatabaseBase. This is designed to replace all of the manual stuff like:
818 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
819 * as well as validate against the canonical list of DB types we have
821 * This factory function is mostly useful for when you need to connect to a
822 * database other than the MediaWiki default (such as for external auth,
823 * an extension, et cetera). Do not use this to connect to the MediaWiki
824 * database. Example uses in core:
825 * @see LoadBalancer::reallyOpenConnection()
826 * @see ForeignDBRepo::getMasterDB()
827 * @see WebInstallerDBConnect::execute()
831 * @param string $dbType A possible DB type
832 * @param array $p An array of options to pass to the constructor.
833 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
834 * @throws MWException If the database driver or extension cannot be found
835 * @return DatabaseBase|null DatabaseBase subclass or null
837 final public static function factory( $dbType, $p = array() ) {
838 $canonicalDBTypes = array(
839 'mysql' => array( 'mysqli', 'mysql' ),
840 'postgres' => array(),
847 $dbType = strtolower( $dbType );
848 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
849 $possibleDrivers = $canonicalDBTypes[$dbType];
850 if ( !empty( $p['driver'] ) ) {
851 if ( in_array( $p['driver'], $possibleDrivers ) ) {
852 $driver = $p['driver'];
854 throw new MWException( __METHOD__
.
855 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
858 foreach ( $possibleDrivers as $posDriver ) {
859 if ( extension_loaded( $posDriver ) ) {
860 $driver = $posDriver;
868 if ( $driver === false ) {
869 throw new MWException( __METHOD__
.
870 " no viable database extension found for type '$dbType'" );
873 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
874 // and everything else doesn't use a schema (e.g. null)
875 // Although postgres and oracle support schemas, we don't use them (yet)
876 // to maintain backwards compatibility
877 $defaultSchemas = array(
882 'mssql' => 'get from global',
885 $class = 'Database' . ucfirst( $driver );
886 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
888 'host' => isset( $p['host'] ) ?
$p['host'] : false,
889 'user' => isset( $p['user'] ) ?
$p['user'] : false,
890 'password' => isset( $p['password'] ) ?
$p['password'] : false,
891 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
892 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
893 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
894 'schema' => isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType],
895 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
898 return new $class( $params );
904 protected function installErrorHandler() {
905 $this->mPHPError
= false;
906 $this->htmlErrors
= ini_set( 'html_errors', '0' );
907 set_error_handler( array( $this, 'connectionErrorHandler' ) );
911 * @return bool|string
913 protected function restoreErrorHandler() {
914 restore_error_handler();
915 if ( $this->htmlErrors
!== false ) {
916 ini_set( 'html_errors', $this->htmlErrors
);
918 if ( $this->mPHPError
) {
919 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
920 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
930 * @param string $errstr
932 public function connectionErrorHandler( $errno, $errstr ) {
933 $this->mPHPError
= $errstr;
937 * Closes a database connection.
938 * if it is open : commits any open transactions
940 * @throws MWException
941 * @return bool Operation success. true if already closed.
943 public function close() {
944 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
945 throw new MWException( "Transaction idle callbacks still pending." );
947 if ( $this->mConn
) {
948 if ( $this->trxLevel() ) {
949 if ( !$this->mTrxAutomatic
) {
950 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
951 " performing implicit commit before closing connection!" );
954 $this->commit( __METHOD__
, 'flush' );
957 $closed = $this->closeConnection();
958 $this->mConn
= false;
962 $this->mOpened
= false;
968 * Closes underlying database connection
970 * @return bool Whether connection was closed successfully
972 abstract protected function closeConnection();
975 * @param string $error Fallback error message, used if none is given by DB
976 * @throws DBConnectionError
978 function reportConnectionError( $error = 'Unknown error' ) {
979 $myError = $this->lastError();
985 throw new DBConnectionError( $this, $error );
989 * The DBMS-dependent part of query()
991 * @param string $sql SQL query.
992 * @return ResultWrapper|bool Result object to feed to fetchObject,
993 * fetchRow, ...; or false on failure
995 abstract protected function doQuery( $sql );
998 * Determine whether a query writes to the DB.
999 * Should return true if unsure.
1001 * @param string $sql
1004 public function isWriteQuery( $sql ) {
1005 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1009 * Run an SQL query and return the result. Normally throws a DBQueryError
1010 * on failure. If errors are ignored, returns false instead.
1012 * In new code, the query wrappers select(), insert(), update(), delete(),
1013 * etc. should be used where possible, since they give much better DBMS
1014 * independence and automatically quote or validate user input in a variety
1015 * of contexts. This function is generally only useful for queries which are
1016 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1019 * However, the query wrappers themselves should call this function.
1021 * @param string $sql SQL query
1022 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1023 * comment (you can use __METHOD__ or add some extra info)
1024 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1025 * maybe best to catch the exception instead?
1026 * @throws MWException
1027 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1028 * for a successful read query, or false on failure if $tempIgnore set
1030 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1031 global $wgUser, $wgDebugDBTransactions;
1033 $this->mLastQuery
= $sql;
1034 if ( $this->isWriteQuery( $sql ) ) {
1035 # Set a flag indicating that writes have been done
1036 wfDebug( __METHOD__
. ': Writes done: ' . DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1037 $this->mDoneWrites
= microtime( true );
1040 # Add a comment for easy SHOW PROCESSLIST interpretation
1041 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1042 $userName = $wgUser->getName();
1043 if ( mb_strlen( $userName ) > 15 ) {
1044 $userName = mb_substr( $userName, 0, 15 ) . '...';
1046 $userName = str_replace( '/', '', $userName );
1051 // Add trace comment to the begin of the sql string, right after the operator.
1052 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1053 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1055 # If DBO_TRX is set, start a transaction
1056 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
1057 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1059 # Avoid establishing transactions for SHOW and SET statements too -
1060 # that would delay transaction initializations to once connection
1061 # is really used by application
1062 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1063 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1064 if ( $wgDebugDBTransactions ) {
1065 wfDebug( "Implicit transaction start.\n" );
1067 $this->begin( __METHOD__
. " ($fname)" );
1068 $this->mTrxAutomatic
= true;
1072 # Keep track of whether the transaction has write queries pending
1073 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1074 $this->mTrxDoneWrites
= true;
1075 Profiler
::instance()->transactionWritingIn(
1076 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1081 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1083 if ( !Profiler
::instance()->isStub() ) {
1084 # generalizeSQL will probably cut down the query to reasonable
1085 # logging size most of the time. The substr is really just a sanity check.
1087 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1088 $totalProf = 'DatabaseBase::query-master';
1090 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1091 $totalProf = 'DatabaseBase::query';
1093 # Include query transaction state
1094 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1096 $trx = $this->mTrxLevel ?
'TRX=yes' : 'TRX=no';
1097 wfProfileIn( $totalProf );
1098 wfProfileIn( $queryProf );
1101 if ( $this->debug() ) {
1105 $sqlx = substr( $commentedSql, 0, 500 );
1106 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1108 $master = $isMaster ?
'master' : 'slave';
1109 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1112 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1114 # Avoid fatals if close() was called
1115 if ( !$this->isOpen() ) {
1116 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1119 # Do the query and handle errors
1120 $ret = $this->doQuery( $commentedSql );
1122 MWDebug
::queryTime( $queryId );
1124 # Try reconnecting if the connection was lost
1125 if ( false === $ret && $this->wasErrorReissuable() ) {
1126 # Transaction is gone, like it or not
1127 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1128 $this->mTrxLevel
= 0;
1129 $this->mTrxIdleCallbacks
= array(); // bug 65263
1130 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1131 wfDebug( "Connection lost, reconnecting...\n" );
1133 if ( $this->ping() ) {
1134 global $wgRequestTime;
1135 wfDebug( "Reconnected\n" );
1136 $sqlx = substr( $commentedSql, 0, 500 );
1137 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1138 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1139 if ( $elapsed < 300 ) {
1140 # Not a database error to lose a transaction after a minute or two
1141 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
1144 # Leave $ret as false and let an error be reported.
1145 # Callers may catch the exception and continue to use the DB.
1147 # Should be safe to silently retry (no trx and thus no callbacks)
1148 $ret = $this->doQuery( $commentedSql );
1151 wfDebug( "Failed\n" );
1155 if ( false === $ret ) {
1156 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1159 if ( !Profiler
::instance()->isStub() ) {
1160 wfProfileOut( $queryProf );
1161 wfProfileOut( $totalProf );
1164 return $this->resultObject( $ret );
1168 * Report a query error. Log the error, and if neither the object ignore
1169 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1171 * @param string $error
1173 * @param string $sql
1174 * @param string $fname
1175 * @param bool $tempIgnore
1176 * @throws DBQueryError
1178 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1179 # Ignore errors during error handling to avoid infinite recursion
1180 $ignore = $this->ignoreErrors( true );
1181 ++
$this->mErrorCount
;
1183 if ( $ignore ||
$tempIgnore ) {
1184 wfDebug( "SQL ERROR (ignored): $error\n" );
1185 $this->ignoreErrors( $ignore );
1187 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1188 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
1189 wfDebug( "SQL ERROR: " . $error . "\n" );
1190 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1195 * Intended to be compatible with the PEAR::DB wrapper functions.
1196 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1198 * ? = scalar value, quoted as necessary
1199 * ! = raw SQL bit (a function for instance)
1200 * & = filename; reads the file and inserts as a blob
1201 * (we don't use this though...)
1203 * @param string $sql
1204 * @param string $func
1208 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1209 /* MySQL doesn't support prepared statements (yet), so just
1210 * pack up the query for reference. We'll manually replace
1213 return array( 'query' => $sql, 'func' => $func );
1217 * Free a prepared query, generated by prepare().
1218 * @param string $prepared
1220 protected function freePrepared( $prepared ) {
1221 /* No-op by default */
1225 * Execute a prepared query with the various arguments
1226 * @param string $prepared The prepared sql
1227 * @param mixed $args Either an array here, or put scalars as varargs
1229 * @return ResultWrapper
1231 public function execute( $prepared, $args = null ) {
1232 if ( !is_array( $args ) ) {
1234 $args = func_get_args();
1235 array_shift( $args );
1238 $sql = $this->fillPrepared( $prepared['query'], $args );
1240 return $this->query( $sql, $prepared['func'] );
1244 * For faking prepared SQL statements on DBs that don't support it directly.
1246 * @param string $preparedQuery A 'preparable' SQL statement
1247 * @param array $args Array of Arguments to fill it with
1248 * @return string Executable SQL
1250 public function fillPrepared( $preparedQuery, $args ) {
1252 $this->preparedArgs
=& $args;
1254 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1255 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1259 * preg_callback func for fillPrepared()
1260 * The arguments should be in $this->preparedArgs and must not be touched
1261 * while we're doing this.
1263 * @param array $matches
1264 * @throws DBUnexpectedError
1267 protected function fillPreparedArg( $matches ) {
1268 switch ( $matches[1] ) {
1277 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1279 switch ( $matches[1] ) {
1281 return $this->addQuotes( $arg );
1285 # return $this->addQuotes( file_get_contents( $arg ) );
1286 throw new DBUnexpectedError(
1288 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1291 throw new DBUnexpectedError(
1293 'Received invalid match. This should never happen!'
1299 * Free a result object returned by query() or select(). It's usually not
1300 * necessary to call this, just use unset() or let the variable holding
1301 * the result object go out of scope.
1303 * @param mixed $res A SQL result
1305 public function freeResult( $res ) {
1309 * A SELECT wrapper which returns a single field from a single result row.
1311 * Usually throws a DBQueryError on failure. If errors are explicitly
1312 * ignored, returns false on failure.
1314 * If no result rows are returned from the query, false is returned.
1316 * @param string|array $table Table name. See DatabaseBase::select() for details.
1317 * @param string $var The field name to select. This must be a valid SQL
1318 * fragment: do not use unvalidated user input.
1319 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1320 * @param string $fname The function name of the caller.
1321 * @param string|array $options The query options. See DatabaseBase::select() for details.
1323 * @return bool|mixed The value from the field, or false on failure.
1325 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1328 if ( !is_array( $options ) ) {
1329 $options = array( $options );
1332 $options['LIMIT'] = 1;
1334 $res = $this->select( $table, $var, $cond, $fname, $options );
1336 if ( $res === false ||
!$this->numRows( $res ) ) {
1340 $row = $this->fetchRow( $res );
1342 if ( $row !== false ) {
1343 return reset( $row );
1350 * Returns an optional USE INDEX clause to go after the table, and a
1351 * string to go at the end of the query.
1353 * @param array $options Associative array of options to be turned into
1354 * an SQL query, valid keys are listed in the function.
1356 * @see DatabaseBase::select()
1358 public function makeSelectOptions( $options ) {
1359 $preLimitTail = $postLimitTail = '';
1362 $noKeyOptions = array();
1364 foreach ( $options as $key => $option ) {
1365 if ( is_numeric( $key ) ) {
1366 $noKeyOptions[$option] = true;
1370 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1372 $preLimitTail .= $this->makeOrderBy( $options );
1374 // if (isset($options['LIMIT'])) {
1375 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1376 // isset($options['OFFSET']) ? $options['OFFSET']
1380 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1381 $postLimitTail .= ' FOR UPDATE';
1384 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1385 $postLimitTail .= ' LOCK IN SHARE MODE';
1388 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1389 $startOpts .= 'DISTINCT';
1392 # Various MySQL extensions
1393 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1394 $startOpts .= ' /*! STRAIGHT_JOIN */';
1397 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1398 $startOpts .= ' HIGH_PRIORITY';
1401 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1402 $startOpts .= ' SQL_BIG_RESULT';
1405 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1406 $startOpts .= ' SQL_BUFFER_RESULT';
1409 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1410 $startOpts .= ' SQL_SMALL_RESULT';
1413 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1414 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1417 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1418 $startOpts .= ' SQL_CACHE';
1421 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1422 $startOpts .= ' SQL_NO_CACHE';
1425 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1426 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1431 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1435 * Returns an optional GROUP BY with an optional HAVING
1437 * @param array $options Associative array of options
1439 * @see DatabaseBase::select()
1442 public function makeGroupByWithHaving( $options ) {
1444 if ( isset( $options['GROUP BY'] ) ) {
1445 $gb = is_array( $options['GROUP BY'] )
1446 ?
implode( ',', $options['GROUP BY'] )
1447 : $options['GROUP BY'];
1448 $sql .= ' GROUP BY ' . $gb;
1450 if ( isset( $options['HAVING'] ) ) {
1451 $having = is_array( $options['HAVING'] )
1452 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1453 : $options['HAVING'];
1454 $sql .= ' HAVING ' . $having;
1461 * Returns an optional ORDER BY
1463 * @param array $options Associative array of options
1465 * @see DatabaseBase::select()
1468 public function makeOrderBy( $options ) {
1469 if ( isset( $options['ORDER BY'] ) ) {
1470 $ob = is_array( $options['ORDER BY'] )
1471 ?
implode( ',', $options['ORDER BY'] )
1472 : $options['ORDER BY'];
1474 return ' ORDER BY ' . $ob;
1481 * Execute a SELECT query constructed using the various parameters provided.
1482 * See below for full details of the parameters.
1484 * @param string|array $table Table name
1485 * @param string|array $vars Field names
1486 * @param string|array $conds Conditions
1487 * @param string $fname Caller function name
1488 * @param array $options Query options
1489 * @param array $join_conds Join conditions
1491 * @param string|array $table
1493 * May be either an array of table names, or a single string holding a table
1494 * name. If an array is given, table aliases can be specified, for example:
1496 * array( 'a' => 'user' )
1498 * This includes the user table in the query, with the alias "a" available
1499 * for use in field names (e.g. a.user_name).
1501 * All of the table names given here are automatically run through
1502 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1503 * added, and various other table name mappings to be performed.
1506 * @param string|array $vars
1508 * May be either a field name or an array of field names. The field names
1509 * can be complete fragments of SQL, for direct inclusion into the SELECT
1510 * query. If an array is given, field aliases can be specified, for example:
1512 * array( 'maxrev' => 'MAX(rev_id)' )
1514 * This includes an expression with the alias "maxrev" in the query.
1516 * If an expression is given, care must be taken to ensure that it is
1520 * @param string|array $conds
1522 * May be either a string containing a single condition, or an array of
1523 * conditions. If an array is given, the conditions constructed from each
1524 * element are combined with AND.
1526 * Array elements may take one of two forms:
1528 * - Elements with a numeric key are interpreted as raw SQL fragments.
1529 * - Elements with a string key are interpreted as equality conditions,
1530 * where the key is the field name.
1531 * - If the value of such an array element is a scalar (such as a
1532 * string), it will be treated as data and thus quoted appropriately.
1533 * If it is null, an IS NULL clause will be added.
1534 * - If the value is an array, an IN(...) clause will be constructed,
1535 * such that the field name may match any of the elements in the
1536 * array. The elements of the array will be quoted.
1538 * Note that expressions are often DBMS-dependent in their syntax.
1539 * DBMS-independent wrappers are provided for constructing several types of
1540 * expression commonly used in condition queries. See:
1541 * - DatabaseBase::buildLike()
1542 * - DatabaseBase::conditional()
1545 * @param string|array $options
1547 * Optional: Array of query options. Boolean options are specified by
1548 * including them in the array as a string value with a numeric key, for
1551 * array( 'FOR UPDATE' )
1553 * The supported options are:
1555 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1556 * with LIMIT can theoretically be used for paging through a result set,
1557 * but this is discouraged in MediaWiki for performance reasons.
1559 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1560 * and then the first rows are taken until the limit is reached. LIMIT
1561 * is applied to a result set after OFFSET.
1563 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1564 * changed until the next COMMIT.
1566 * - DISTINCT: Boolean: return only unique result rows.
1568 * - GROUP BY: May be either an SQL fragment string naming a field or
1569 * expression to group by, or an array of such SQL fragments.
1571 * - HAVING: May be either an string containing a HAVING clause or an array of
1572 * conditions building the HAVING clause. If an array is given, the conditions
1573 * constructed from each element are combined with AND.
1575 * - ORDER BY: May be either an SQL fragment giving a field name or
1576 * expression to order by, or an array of such SQL fragments.
1578 * - USE INDEX: This may be either a string giving the index name to use
1579 * for the query, or an array. If it is an associative array, each key
1580 * gives the table name (or alias), each value gives the index name to
1581 * use for that table. All strings are SQL fragments and so should be
1582 * validated by the caller.
1584 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1585 * instead of SELECT.
1587 * And also the following boolean MySQL extensions, see the MySQL manual
1588 * for documentation:
1590 * - LOCK IN SHARE MODE
1594 * - SQL_BUFFER_RESULT
1595 * - SQL_SMALL_RESULT
1596 * - SQL_CALC_FOUND_ROWS
1601 * @param string|array $join_conds
1603 * Optional associative array of table-specific join conditions. In the
1604 * most common case, this is unnecessary, since the join condition can be
1605 * in $conds. However, it is useful for doing a LEFT JOIN.
1607 * The key of the array contains the table name or alias. The value is an
1608 * array with two elements, numbered 0 and 1. The first gives the type of
1609 * join, the second is an SQL fragment giving the join condition for that
1610 * table. For example:
1612 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1614 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1615 * with no rows in it will be returned. If there was a query error, a
1616 * DBQueryError exception will be thrown, except if the "ignore errors"
1617 * option was set, in which case false will be returned.
1619 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1620 $options = array(), $join_conds = array() ) {
1621 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1623 return $this->query( $sql, $fname );
1627 * The equivalent of DatabaseBase::select() except that the constructed SQL
1628 * is returned, instead of being immediately executed. This can be useful for
1629 * doing UNION queries, where the SQL text of each query is needed. In general,
1630 * however, callers outside of Database classes should just use select().
1632 * @param string|array $table Table name
1633 * @param string|array $vars Field names
1634 * @param string|array $conds Conditions
1635 * @param string $fname Caller function name
1636 * @param string|array $options Query options
1637 * @param string|array $join_conds Join conditions
1639 * @return string SQL query string.
1640 * @see DatabaseBase::select()
1642 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1643 $options = array(), $join_conds = array()
1645 if ( is_array( $vars ) ) {
1646 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1649 $options = (array)$options;
1650 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1651 ?
$options['USE INDEX']
1654 if ( is_array( $table ) ) {
1656 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1657 } elseif ( $table != '' ) {
1658 if ( $table[0] == ' ' ) {
1659 $from = ' FROM ' . $table;
1662 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1668 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1669 $this->makeSelectOptions( $options );
1671 if ( !empty( $conds ) ) {
1672 if ( is_array( $conds ) ) {
1673 $conds = $this->makeList( $conds, LIST_AND
);
1675 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1677 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1680 if ( isset( $options['LIMIT'] ) ) {
1681 $sql = $this->limitResult( $sql, $options['LIMIT'],
1682 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1684 $sql = "$sql $postLimitTail";
1686 if ( isset( $options['EXPLAIN'] ) ) {
1687 $sql = 'EXPLAIN ' . $sql;
1694 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1695 * that a single row object is returned. If the query returns no rows,
1696 * false is returned.
1698 * @param string|array $table Table name
1699 * @param string|array $vars Field names
1700 * @param array $conds Conditions
1701 * @param string $fname Caller function name
1702 * @param string|array $options Query options
1703 * @param array|string $join_conds Join conditions
1705 * @return stdClass|bool
1707 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1708 $options = array(), $join_conds = array()
1710 $options = (array)$options;
1711 $options['LIMIT'] = 1;
1712 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1714 if ( $res === false ) {
1718 if ( !$this->numRows( $res ) ) {
1722 $obj = $this->fetchObject( $res );
1728 * Estimate rows in dataset.
1730 * MySQL allows you to estimate the number of rows that would be returned
1731 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1732 * index cardinality statistics, and is notoriously inaccurate, especially
1733 * when large numbers of rows have recently been added or deleted.
1735 * For DBMSs that don't support fast result size estimation, this function
1736 * will actually perform the SELECT COUNT(*).
1738 * Takes the same arguments as DatabaseBase::select().
1740 * @param string $table Table name
1741 * @param string $vars Unused
1742 * @param array|string $conds Filters on the table
1743 * @param string $fname Function name for profiling
1744 * @param array $options Options for select
1745 * @return int Row count
1747 public function estimateRowCount( $table, $vars = '*', $conds = '',
1748 $fname = __METHOD__
, $options = array()
1751 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1754 $row = $this->fetchRow( $res );
1755 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1762 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1763 * It's only slightly flawed. Don't use for anything important.
1765 * @param string $sql A SQL Query
1769 static function generalizeSQL( $sql ) {
1770 # This does the same as the regexp below would do, but in such a way
1771 # as to avoid crashing php on some large strings.
1772 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1774 $sql = str_replace( "\\\\", '', $sql );
1775 $sql = str_replace( "\\'", '', $sql );
1776 $sql = str_replace( "\\\"", '', $sql );
1777 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1778 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1780 # All newlines, tabs, etc replaced by single space
1781 $sql = preg_replace( '/\s+/', ' ', $sql );
1784 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1785 $sql = preg_replace( '/-?\d+/s', 'N', $sql );
1791 * Determines whether a field exists in a table
1793 * @param string $table Table name
1794 * @param string $field Filed to check on that table
1795 * @param string $fname Calling function name (optional)
1796 * @return bool Whether $table has filed $field
1798 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1799 $info = $this->fieldInfo( $table, $field );
1805 * Determines whether an index exists
1806 * Usually throws a DBQueryError on failure
1807 * If errors are explicitly ignored, returns NULL on failure
1809 * @param string $table
1810 * @param string $index
1811 * @param string $fname
1814 public function indexExists( $table, $index, $fname = __METHOD__
) {
1815 if ( !$this->tableExists( $table ) ) {
1819 $info = $this->indexInfo( $table, $index, $fname );
1820 if ( is_null( $info ) ) {
1823 return $info !== false;
1828 * Query whether a given table exists
1830 * @param string $table
1831 * @param string $fname
1834 public function tableExists( $table, $fname = __METHOD__
) {
1835 $table = $this->tableName( $table );
1836 $old = $this->ignoreErrors( true );
1837 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1838 $this->ignoreErrors( $old );
1844 * Determines if a given index is unique
1846 * @param string $table
1847 * @param string $index
1851 public function indexUnique( $table, $index ) {
1852 $indexInfo = $this->indexInfo( $table, $index );
1854 if ( !$indexInfo ) {
1858 return !$indexInfo[0]->Non_unique
;
1862 * Helper for DatabaseBase::insert().
1864 * @param array $options
1867 protected function makeInsertOptions( $options ) {
1868 return implode( ' ', $options );
1872 * INSERT wrapper, inserts an array into a table.
1876 * - A single associative array. The array keys are the field names, and
1877 * the values are the values to insert. The values are treated as data
1878 * and will be quoted appropriately. If NULL is inserted, this will be
1879 * converted to a database NULL.
1880 * - An array with numeric keys, holding a list of associative arrays.
1881 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1882 * each subarray must be identical to each other, and in the same order.
1884 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1887 * $options is an array of options, with boolean options encoded as values
1888 * with numeric keys, in the same style as $options in
1889 * DatabaseBase::select(). Supported options are:
1891 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1892 * any rows which cause duplicate key errors are not inserted. It's
1893 * possible to determine how many rows were successfully inserted using
1894 * DatabaseBase::affectedRows().
1896 * @param string $table Table name. This will be passed through
1897 * DatabaseBase::tableName().
1898 * @param array $a Array of rows to insert
1899 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1900 * @param array $options of options
1904 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1905 # No rows to insert, easy just return now
1906 if ( !count( $a ) ) {
1910 $table = $this->tableName( $table );
1912 if ( !is_array( $options ) ) {
1913 $options = array( $options );
1917 if ( isset( $options['fileHandle'] ) ) {
1918 $fh = $options['fileHandle'];
1920 $options = $this->makeInsertOptions( $options );
1922 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1924 $keys = array_keys( $a[0] );
1927 $keys = array_keys( $a );
1930 $sql = 'INSERT ' . $options .
1931 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1935 foreach ( $a as $row ) {
1941 $sql .= '(' . $this->makeList( $row ) . ')';
1944 $sql .= '(' . $this->makeList( $a ) . ')';
1947 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1949 } elseif ( $fh !== null ) {
1953 return (bool)$this->query( $sql, $fname );
1957 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1959 * @param array $options
1962 protected function makeUpdateOptionsArray( $options ) {
1963 if ( !is_array( $options ) ) {
1964 $options = array( $options );
1969 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1970 $opts[] = $this->lowPriorityOption();
1973 if ( in_array( 'IGNORE', $options ) ) {
1981 * Make UPDATE options for the DatabaseBase::update function
1983 * @param array $options The options passed to DatabaseBase::update
1986 protected function makeUpdateOptions( $options ) {
1987 $opts = $this->makeUpdateOptionsArray( $options );
1989 return implode( ' ', $opts );
1993 * UPDATE wrapper. Takes a condition array and a SET array.
1995 * @param string $table Name of the table to UPDATE. This will be passed through
1996 * DatabaseBase::tableName().
1997 * @param array $values An array of values to SET. For each array element,
1998 * the key gives the field name, and the value gives the data to set
1999 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2000 * @param array $conds An array of conditions (WHERE). See
2001 * DatabaseBase::select() for the details of the format of condition
2002 * arrays. Use '*' to update all rows.
2003 * @param string $fname The function name of the caller (from __METHOD__),
2004 * for logging and profiling.
2005 * @param array $options An array of UPDATE options, can be:
2006 * - IGNORE: Ignore unique key conflicts
2007 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2010 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2011 $table = $this->tableName( $table );
2012 $opts = $this->makeUpdateOptions( $options );
2013 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2015 if ( $conds !== array() && $conds !== '*' ) {
2016 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2019 return $this->query( $sql, $fname );
2023 * Makes an encoded list of strings from an array
2025 * @param array $a Containing the data
2026 * @param int $mode Constant
2027 * - LIST_COMMA: Comma separated, no field names
2028 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2029 * documentation for $conds in DatabaseBase::select().
2030 * - LIST_OR: ORed WHERE clause (without the WHERE)
2031 * - LIST_SET: Comma separated with field names, like a SET clause
2032 * - LIST_NAMES: Comma separated field names
2033 * @throws MWException|DBUnexpectedError
2036 public function makeList( $a, $mode = LIST_COMMA
) {
2037 if ( !is_array( $a ) ) {
2038 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2044 foreach ( $a as $field => $value ) {
2046 if ( $mode == LIST_AND
) {
2048 } elseif ( $mode == LIST_OR
) {
2057 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2058 $list .= "($value)";
2059 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2061 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2062 if ( count( $value ) == 0 ) {
2063 throw new MWException( __METHOD__
. ": empty input for field $field" );
2064 } elseif ( count( $value ) == 1 ) {
2065 // Special-case single values, as IN isn't terribly efficient
2066 // Don't necessarily assume the single key is 0; we don't
2067 // enforce linear numeric ordering on other arrays here.
2068 $value = array_values( $value );
2069 $list .= $field . " = " . $this->addQuotes( $value[0] );
2071 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2073 } elseif ( $value === null ) {
2074 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2075 $list .= "$field IS ";
2076 } elseif ( $mode == LIST_SET
) {
2077 $list .= "$field = ";
2081 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2082 $list .= "$field = ";
2084 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2092 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2093 * The keys on each level may be either integers or strings.
2095 * @param array $data organized as 2-d
2096 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2097 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2098 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2099 * @return string|bool string SQL fragment, or false if no items in array.
2101 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2104 foreach ( $data as $base => $sub ) {
2105 if ( count( $sub ) ) {
2106 $conds[] = $this->makeList(
2107 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2113 return $this->makeList( $conds, LIST_OR
);
2115 // Nothing to search for...
2121 * Return aggregated value alias
2123 * @param array $valuedata
2124 * @param string $valuename
2128 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2133 * @param string $field
2136 public function bitNot( $field ) {
2141 * @param string $fieldLeft
2142 * @param string $fieldRight
2145 public function bitAnd( $fieldLeft, $fieldRight ) {
2146 return "($fieldLeft & $fieldRight)";
2150 * @param string $fieldLeft
2151 * @param string $fieldRight
2154 public function bitOr( $fieldLeft, $fieldRight ) {
2155 return "($fieldLeft | $fieldRight)";
2159 * Build a concatenation list to feed into a SQL query
2160 * @param array $stringList List of raw SQL expressions; caller is
2161 * responsible for any quoting
2164 public function buildConcat( $stringList ) {
2165 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2169 * Build a GROUP_CONCAT or equivalent statement for a query.
2171 * This is useful for combining a field for several rows into a single string.
2172 * NULL values will not appear in the output, duplicated values will appear,
2173 * and the resulting delimiter-separated values have no defined sort order.
2174 * Code using the results may need to use the PHP unique() or sort() methods.
2176 * @param string $delim Glue to bind the results together
2177 * @param string|array $table Table name
2178 * @param string $field Field name
2179 * @param string|array $conds Conditions
2180 * @param string|array $join_conds Join conditions
2181 * @return string SQL text
2184 public function buildGroupConcatField(
2185 $delim, $table, $field, $conds = '', $join_conds = array()
2187 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2189 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2193 * Change the current database
2195 * @todo Explain what exactly will fail if this is not overridden.
2199 * @return bool Success or failure
2201 public function selectDB( $db ) {
2202 # Stub. Shouldn't cause serious problems if it's not overridden, but
2203 # if your database engine supports a concept similar to MySQL's
2204 # databases you may as well.
2205 $this->mDBname
= $db;
2211 * Get the current DB name
2214 public function getDBname() {
2215 return $this->mDBname
;
2219 * Get the server hostname or IP address
2222 public function getServer() {
2223 return $this->mServer
;
2227 * Format a table name ready for use in constructing an SQL query
2229 * This does two important things: it quotes the table names to clean them up,
2230 * and it adds a table prefix if only given a table name with no quotes.
2232 * All functions of this object which require a table name call this function
2233 * themselves. Pass the canonical name to such functions. This is only needed
2234 * when calling query() directly.
2236 * @param string $name Database table name
2237 * @param string $format One of:
2238 * quoted - Automatically pass the table name through addIdentifierQuotes()
2239 * so that it can be used in a query.
2240 * raw - Do not add identifier quotes to the table name
2241 * @return string Full database name
2243 public function tableName( $name, $format = 'quoted' ) {
2244 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2245 # Skip the entire process when we have a string quoted on both ends.
2246 # Note that we check the end so that we will still quote any use of
2247 # use of `database`.table. But won't break things if someone wants
2248 # to query a database table with a dot in the name.
2249 if ( $this->isQuotedIdentifier( $name ) ) {
2253 # Lets test for any bits of text that should never show up in a table
2254 # name. Basically anything like JOIN or ON which are actually part of
2255 # SQL queries, but may end up inside of the table value to combine
2256 # sql. Such as how the API is doing.
2257 # Note that we use a whitespace test rather than a \b test to avoid
2258 # any remote case where a word like on may be inside of a table name
2259 # surrounded by symbols which may be considered word breaks.
2260 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2264 # Split database and table into proper variables.
2265 # We reverse the explode so that database.table and table both output
2266 # the correct table.
2267 $dbDetails = explode( '.', $name, 2 );
2268 if ( count( $dbDetails ) == 3 ) {
2269 list( $database, $schema, $table ) = $dbDetails;
2270 # We don't want any prefix added in this case
2272 } elseif ( count( $dbDetails ) == 2 ) {
2273 list( $database, $table ) = $dbDetails;
2274 # We don't want any prefix added in this case
2275 # In dbs that support it, $database may actually be the schema
2276 # but that doesn't affect any of the functionality here
2280 list( $table ) = $dbDetails;
2281 if ( $wgSharedDB !== null # We have a shared database
2282 && $this->mForeign
== false # We're not working on a foreign database
2283 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2284 && in_array( $table, $wgSharedTables ) # A shared table is selected
2286 $database = $wgSharedDB;
2287 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2288 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2291 $schema = $this->mSchema
; # Default schema
2292 $prefix = $this->mTablePrefix
; # Default prefix
2296 # Quote $table and apply the prefix if not quoted.
2297 # $tableName might be empty if this is called from Database::replaceVars()
2298 $tableName = "{$prefix}{$table}";
2299 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2300 $tableName = $this->addIdentifierQuotes( $tableName );
2303 # Quote $schema and merge it with the table name if needed
2304 if ( $schema !== null ) {
2305 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2306 $schema = $this->addIdentifierQuotes( $schema );
2308 $tableName = $schema . '.' . $tableName;
2311 # Quote $database and merge it with the table name if needed
2312 if ( $database !== null ) {
2313 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2314 $database = $this->addIdentifierQuotes( $database );
2316 $tableName = $database . '.' . $tableName;
2323 * Fetch a number of table names into an array
2324 * This is handy when you need to construct SQL for joins
2327 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2328 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2329 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2333 public function tableNames() {
2334 $inArray = func_get_args();
2337 foreach ( $inArray as $name ) {
2338 $retVal[$name] = $this->tableName( $name );
2345 * Fetch a number of table names into an zero-indexed numerical array
2346 * This is handy when you need to construct SQL for joins
2349 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2350 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2351 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2355 public function tableNamesN() {
2356 $inArray = func_get_args();
2359 foreach ( $inArray as $name ) {
2360 $retVal[] = $this->tableName( $name );
2367 * Get an aliased table name
2368 * e.g. tableName AS newTableName
2370 * @param string $name Table name, see tableName()
2371 * @param string|bool $alias Alias (optional)
2372 * @return string SQL name for aliased table. Will not alias a table to its own name
2374 public function tableNameWithAlias( $name, $alias = false ) {
2375 if ( !$alias ||
$alias == $name ) {
2376 return $this->tableName( $name );
2378 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2383 * Gets an array of aliased table names
2385 * @param array $tables array( [alias] => table )
2386 * @return string[] See tableNameWithAlias()
2388 public function tableNamesWithAlias( $tables ) {
2390 foreach ( $tables as $alias => $table ) {
2391 if ( is_numeric( $alias ) ) {
2394 $retval[] = $this->tableNameWithAlias( $table, $alias );
2401 * Get an aliased field name
2402 * e.g. fieldName AS newFieldName
2404 * @param string $name Field name
2405 * @param string|bool $alias Alias (optional)
2406 * @return string SQL name for aliased field. Will not alias a field to its own name
2408 public function fieldNameWithAlias( $name, $alias = false ) {
2409 if ( !$alias ||
(string)$alias === (string)$name ) {
2412 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2417 * Gets an array of aliased field names
2419 * @param array $fields array( [alias] => field )
2420 * @return string[] See fieldNameWithAlias()
2422 public function fieldNamesWithAlias( $fields ) {
2424 foreach ( $fields as $alias => $field ) {
2425 if ( is_numeric( $alias ) ) {
2428 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2435 * Get the aliased table name clause for a FROM clause
2436 * which might have a JOIN and/or USE INDEX clause
2438 * @param array $tables ( [alias] => table )
2439 * @param array $use_index Same as for select()
2440 * @param array $join_conds Same as for select()
2443 protected function tableNamesWithUseIndexOrJOIN(
2444 $tables, $use_index = array(), $join_conds = array()
2448 $use_index = (array)$use_index;
2449 $join_conds = (array)$join_conds;
2451 foreach ( $tables as $alias => $table ) {
2452 if ( !is_string( $alias ) ) {
2453 // No alias? Set it equal to the table name
2456 // Is there a JOIN clause for this table?
2457 if ( isset( $join_conds[$alias] ) ) {
2458 list( $joinType, $conds ) = $join_conds[$alias];
2459 $tableClause = $joinType;
2460 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2461 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2462 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2464 $tableClause .= ' ' . $use;
2467 $on = $this->makeList( (array)$conds, LIST_AND
);
2469 $tableClause .= ' ON (' . $on . ')';
2472 $retJOIN[] = $tableClause;
2473 } elseif ( isset( $use_index[$alias] ) ) {
2474 // Is there an INDEX clause for this table?
2475 $tableClause = $this->tableNameWithAlias( $table, $alias );
2476 $tableClause .= ' ' . $this->useIndexClause(
2477 implode( ',', (array)$use_index[$alias] )
2480 $ret[] = $tableClause;
2482 $tableClause = $this->tableNameWithAlias( $table, $alias );
2484 $ret[] = $tableClause;
2488 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2489 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2490 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2492 // Compile our final table clause
2493 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2497 * Get the name of an index in a given table
2499 * @param string $index
2502 protected function indexName( $index ) {
2503 // Backwards-compatibility hack
2505 'ar_usertext_timestamp' => 'usertext_timestamp',
2506 'un_user_id' => 'user_id',
2507 'un_user_ip' => 'user_ip',
2510 if ( isset( $renamed[$index] ) ) {
2511 return $renamed[$index];
2518 * Adds quotes and backslashes.
2523 public function addQuotes( $s ) {
2524 if ( $s === null ) {
2527 # This will also quote numeric values. This should be harmless,
2528 # and protects against weird problems that occur when they really
2529 # _are_ strings such as article titles and string->number->string
2530 # conversion is not 1:1.
2531 return "'" . $this->strencode( $s ) . "'";
2536 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2537 * MySQL uses `backticks` while basically everything else uses double quotes.
2538 * Since MySQL is the odd one out here the double quotes are our generic
2539 * and we implement backticks in DatabaseMysql.
2544 public function addIdentifierQuotes( $s ) {
2545 return '"' . str_replace( '"', '""', $s ) . '"';
2549 * Returns if the given identifier looks quoted or not according to
2550 * the database convention for quoting identifiers .
2552 * @param string $name
2555 public function isQuotedIdentifier( $name ) {
2556 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2563 protected function escapeLikeInternal( $s ) {
2564 return addcslashes( $s, '\%_' );
2568 * LIKE statement wrapper, receives a variable-length argument list with
2569 * parts of pattern to match containing either string literals that will be
2570 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2571 * the function could be provided with an array of aforementioned
2574 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2575 * a LIKE clause that searches for subpages of 'My page title'.
2577 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2578 * $query .= $dbr->buildLike( $pattern );
2581 * @return string Fully built LIKE statement
2583 public function buildLike() {
2584 $params = func_get_args();
2586 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2587 $params = $params[0];
2592 foreach ( $params as $value ) {
2593 if ( $value instanceof LikeMatch
) {
2594 $s .= $value->toString();
2596 $s .= $this->escapeLikeInternal( $value );
2600 return " LIKE {$this->addQuotes( $s )} ";
2604 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2608 public function anyChar() {
2609 return new LikeMatch( '_' );
2613 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2617 public function anyString() {
2618 return new LikeMatch( '%' );
2622 * Returns an appropriately quoted sequence value for inserting a new row.
2623 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2624 * subclass will return an integer, and save the value for insertId()
2626 * Any implementation of this function should *not* involve reusing
2627 * sequence numbers created for rolled-back transactions.
2628 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2629 * @param string $seqName
2632 public function nextSequenceValue( $seqName ) {
2637 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2638 * is only needed because a) MySQL must be as efficient as possible due to
2639 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2640 * which index to pick. Anyway, other databases might have different
2641 * indexes on a given table. So don't bother overriding this unless you're
2643 * @param string $index
2646 public function useIndexClause( $index ) {
2651 * REPLACE query wrapper.
2653 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2654 * except that when there is a duplicate key error, the old row is deleted
2655 * and the new row is inserted in its place.
2657 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2658 * perform the delete, we need to know what the unique indexes are so that
2659 * we know how to find the conflicting rows.
2661 * It may be more efficient to leave off unique indexes which are unlikely
2662 * to collide. However if you do this, you run the risk of encountering
2663 * errors which wouldn't have occurred in MySQL.
2665 * @param string $table The table to replace the row(s) in.
2666 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2667 * a field name or an array of field names
2668 * @param array $rows Can be either a single row to insert, or multiple rows,
2669 * in the same format as for DatabaseBase::insert()
2670 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2672 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2673 $quotedTable = $this->tableName( $table );
2675 if ( count( $rows ) == 0 ) {
2680 if ( !is_array( reset( $rows ) ) ) {
2681 $rows = array( $rows );
2684 foreach ( $rows as $row ) {
2685 # Delete rows which collide
2686 if ( $uniqueIndexes ) {
2687 $sql = "DELETE FROM $quotedTable WHERE ";
2689 foreach ( $uniqueIndexes as $index ) {
2696 if ( is_array( $index ) ) {
2698 foreach ( $index as $col ) {
2704 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2707 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2711 $this->query( $sql, $fname );
2714 # Now insert the row
2715 $this->insert( $table, $row, $fname );
2720 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2723 * @param string $table Table name
2724 * @param array|string $rows Row(s) to insert
2725 * @param string $fname Caller function name
2727 * @return ResultWrapper
2729 protected function nativeReplace( $table, $rows, $fname ) {
2730 $table = $this->tableName( $table );
2733 if ( !is_array( reset( $rows ) ) ) {
2734 $rows = array( $rows );
2737 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2740 foreach ( $rows as $row ) {
2747 $sql .= '(' . $this->makeList( $row ) . ')';
2750 return $this->query( $sql, $fname );
2754 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2756 * This updates any conflicting rows (according to the unique indexes) using
2757 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2759 * $rows may be either:
2760 * - A single associative array. The array keys are the field names, and
2761 * the values are the values to insert. The values are treated as data
2762 * and will be quoted appropriately. If NULL is inserted, this will be
2763 * converted to a database NULL.
2764 * - An array with numeric keys, holding a list of associative arrays.
2765 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2766 * each subarray must be identical to each other, and in the same order.
2768 * It may be more efficient to leave off unique indexes which are unlikely
2769 * to collide. However if you do this, you run the risk of encountering
2770 * errors which wouldn't have occurred in MySQL.
2772 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2777 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2778 * @param array $rows A single row or list of rows to insert
2779 * @param array $uniqueIndexes List of single field names or field name tuples
2780 * @param array $set An array of values to SET. For each array element, the
2781 * key gives the field name, and the value gives the data to set that
2782 * field to. The data will be quoted by DatabaseBase::addQuotes().
2783 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2787 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2790 if ( !count( $rows ) ) {
2791 return true; // nothing to do
2794 if ( !is_array( reset( $rows ) ) ) {
2795 $rows = array( $rows );
2798 if ( count( $uniqueIndexes ) ) {
2799 $clauses = array(); // list WHERE clauses that each identify a single row
2800 foreach ( $rows as $row ) {
2801 foreach ( $uniqueIndexes as $index ) {
2802 $index = is_array( $index ) ?
$index : array( $index ); // columns
2803 $rowKey = array(); // unique key to this row
2804 foreach ( $index as $column ) {
2805 $rowKey[$column] = $row[$column];
2807 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2810 $where = array( $this->makeList( $clauses, LIST_OR
) );
2815 $useTrx = !$this->mTrxLevel
;
2817 $this->begin( $fname );
2820 # Update any existing conflicting row(s)
2821 if ( $where !== false ) {
2822 $ok = $this->update( $table, $set, $where, $fname );
2826 # Now insert any non-conflicting row(s)
2827 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2828 } catch ( Exception
$e ) {
2830 $this->rollback( $fname );
2835 $this->commit( $fname );
2842 * DELETE where the condition is a join.
2844 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2845 * we use sub-selects
2847 * For safety, an empty $conds will not delete everything. If you want to
2848 * delete all rows where the join condition matches, set $conds='*'.
2850 * DO NOT put the join condition in $conds.
2852 * @param string $delTable The table to delete from.
2853 * @param string $joinTable The other table.
2854 * @param string $delVar The variable to join on, in the first table.
2855 * @param string $joinVar The variable to join on, in the second table.
2856 * @param array $conds Condition array of field names mapped to variables,
2857 * ANDed together in the WHERE clause
2858 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2859 * @throws DBUnexpectedError
2861 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2865 throw new DBUnexpectedError( $this,
2866 'DatabaseBase::deleteJoin() called with empty $conds' );
2869 $delTable = $this->tableName( $delTable );
2870 $joinTable = $this->tableName( $joinTable );
2871 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2872 if ( $conds != '*' ) {
2873 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2877 $this->query( $sql, $fname );
2881 * Returns the size of a text field, or -1 for "unlimited"
2883 * @param string $table
2884 * @param string $field
2887 public function textFieldSize( $table, $field ) {
2888 $table = $this->tableName( $table );
2889 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2890 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2891 $row = $this->fetchObject( $res );
2895 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2905 * A string to insert into queries to show that they're low-priority, like
2906 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2907 * string and nothing bad should happen.
2909 * @return string Returns the text of the low priority option if it is
2910 * supported, or a blank string otherwise
2912 public function lowPriorityOption() {
2917 * DELETE query wrapper.
2919 * @param array $table Table name
2920 * @param string|array $conds of conditions. See $conds in DatabaseBase::select()
2921 * for the format. Use $conds == "*" to delete all rows
2922 * @param string $fname name of the calling function
2923 * @throws DBUnexpectedError
2924 * @return bool|ResultWrapper
2926 public function delete( $table, $conds, $fname = __METHOD__
) {
2928 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2931 $table = $this->tableName( $table );
2932 $sql = "DELETE FROM $table";
2934 if ( $conds != '*' ) {
2935 if ( is_array( $conds ) ) {
2936 $conds = $this->makeList( $conds, LIST_AND
);
2938 $sql .= ' WHERE ' . $conds;
2941 return $this->query( $sql, $fname );
2945 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2946 * into another table.
2948 * @param string $destTable The table name to insert into
2949 * @param string|array $srcTable May be either a table name, or an array of table names
2950 * to include in a join.
2952 * @param array $varMap Must be an associative array of the form
2953 * array( 'dest1' => 'source1', ...). Source items may be literals
2954 * rather than field names, but strings should be quoted with
2955 * DatabaseBase::addQuotes()
2957 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2958 * the details of the format of condition arrays. May be "*" to copy the
2961 * @param string $fname The function name of the caller, from __METHOD__
2963 * @param array $insertOptions Options for the INSERT part of the query, see
2964 * DatabaseBase::insert() for details.
2965 * @param array $selectOptions Options for the SELECT part of the query, see
2966 * DatabaseBase::select() for details.
2968 * @return ResultWrapper
2970 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2971 $fname = __METHOD__
,
2972 $insertOptions = array(), $selectOptions = array()
2974 $destTable = $this->tableName( $destTable );
2976 if ( !is_array( $insertOptions ) ) {
2977 $insertOptions = array( $insertOptions );
2980 $insertOptions = $this->makeInsertOptions( $insertOptions );
2982 if ( !is_array( $selectOptions ) ) {
2983 $selectOptions = array( $selectOptions );
2986 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2988 if ( is_array( $srcTable ) ) {
2989 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2991 $srcTable = $this->tableName( $srcTable );
2994 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2995 " SELECT $startOpts " . implode( ',', $varMap ) .
2996 " FROM $srcTable $useIndex ";
2998 if ( $conds != '*' ) {
2999 if ( is_array( $conds ) ) {
3000 $conds = $this->makeList( $conds, LIST_AND
);
3002 $sql .= " WHERE $conds";
3005 $sql .= " $tailOpts";
3007 return $this->query( $sql, $fname );
3011 * Construct a LIMIT query with optional offset. This is used for query
3012 * pages. The SQL should be adjusted so that only the first $limit rows
3013 * are returned. If $offset is provided as well, then the first $offset
3014 * rows should be discarded, and the next $limit rows should be returned.
3015 * If the result of the query is not ordered, then the rows to be returned
3016 * are theoretically arbitrary.
3018 * $sql is expected to be a SELECT, if that makes a difference.
3020 * The version provided by default works in MySQL and SQLite. It will very
3021 * likely need to be overridden for most other DBMSes.
3023 * @param string $sql SQL query we will append the limit too
3024 * @param int $limit The SQL limit
3025 * @param int|bool $offset The SQL offset (default false)
3026 * @throws DBUnexpectedError
3029 public function limitResult( $sql, $limit, $offset = false ) {
3030 if ( !is_numeric( $limit ) ) {
3031 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3034 return "$sql LIMIT "
3035 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3040 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3041 * within the UNION construct.
3044 public function unionSupportsOrderAndLimit() {
3045 return true; // True for almost every DB supported
3049 * Construct a UNION query
3050 * This is used for providing overload point for other DB abstractions
3051 * not compatible with the MySQL syntax.
3052 * @param array $sqls SQL statements to combine
3053 * @param bool $all Use UNION ALL
3054 * @return string SQL fragment
3056 public function unionQueries( $sqls, $all ) {
3057 $glue = $all ?
') UNION ALL (' : ') UNION (';
3059 return '(' . implode( $glue, $sqls ) . ')';
3063 * Returns an SQL expression for a simple conditional. This doesn't need
3064 * to be overridden unless CASE isn't supported in your DBMS.
3066 * @param string|array $cond SQL expression which will result in a boolean value
3067 * @param string $trueVal SQL expression to return if true
3068 * @param string $falseVal SQL expression to return if false
3069 * @return string SQL fragment
3071 public function conditional( $cond, $trueVal, $falseVal ) {
3072 if ( is_array( $cond ) ) {
3073 $cond = $this->makeList( $cond, LIST_AND
);
3076 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3080 * Returns a comand for str_replace function in SQL query.
3081 * Uses REPLACE() in MySQL
3083 * @param string $orig Column to modify
3084 * @param string $old Column to seek
3085 * @param string $new Column to replace with
3089 public function strreplace( $orig, $old, $new ) {
3090 return "REPLACE({$orig}, {$old}, {$new})";
3094 * Determines how long the server has been up
3099 public function getServerUptime() {
3104 * Determines if the last failure was due to a deadlock
3109 public function wasDeadlock() {
3114 * Determines if the last failure was due to a lock timeout
3119 public function wasLockTimeout() {
3124 * Determines if the last query error was something that should be dealt
3125 * with by pinging the connection and reissuing the query.
3130 public function wasErrorReissuable() {
3135 * Determines if the last failure was due to the database being read-only.
3140 public function wasReadOnlyError() {
3145 * Perform a deadlock-prone transaction.
3147 * This function invokes a callback function to perform a set of write
3148 * queries. If a deadlock occurs during the processing, the transaction
3149 * will be rolled back and the callback function will be called again.
3152 * $dbw->deadlockLoop( callback, ... );
3154 * Extra arguments are passed through to the specified callback function.
3156 * Returns whatever the callback function returned on its successful,
3157 * iteration, or false on error, for example if the retry limit was
3162 public function deadlockLoop() {
3163 $this->begin( __METHOD__
);
3164 $args = func_get_args();
3165 $function = array_shift( $args );
3166 $oldIgnore = $this->ignoreErrors( true );
3167 $tries = self
::DEADLOCK_TRIES
;
3169 if ( is_array( $function ) ) {
3170 $fname = $function[0];
3176 $retVal = call_user_func_array( $function, $args );
3177 $error = $this->lastError();
3178 $errno = $this->lastErrno();
3179 $sql = $this->lastQuery();
3182 if ( $this->wasDeadlock() ) {
3184 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3186 $this->reportQueryError( $error, $errno, $sql, $fname );
3189 } while ( $this->wasDeadlock() && --$tries > 0 );
3191 $this->ignoreErrors( $oldIgnore );
3193 if ( $tries <= 0 ) {
3194 $this->rollback( __METHOD__
);
3195 $this->reportQueryError( $error, $errno, $sql, $fname );
3199 $this->commit( __METHOD__
);
3206 * Wait for the slave to catch up to a given master position.
3208 * @param DBMasterPos $pos
3209 * @param int $timeout The maximum number of seconds to wait for
3211 * @return int Zzero if the slave was past that position already,
3212 * greater than zero if we waited for some period of time, less than
3213 * zero if we timed out.
3215 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3216 # Real waits are implemented in the subclass.
3221 * Get the replication position of this slave
3223 * @return DBMasterPos|bool False if this is not a slave.
3225 public function getSlavePos() {
3231 * Get the position of this master
3233 * @return DBMasterPos|bool False if this is not a master
3235 public function getMasterPos() {
3241 * Run an anonymous function as soon as there is no transaction pending.
3242 * If there is a transaction and it is rolled back, then the callback is cancelled.
3243 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3244 * Callbacks must commit any transactions that they begin.
3246 * This is useful for updates to different systems or when separate transactions are needed.
3247 * For example, one might want to enqueue jobs into a system outside the database, but only
3248 * after the database is updated so that the jobs will see the data when they actually run.
3249 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3251 * @param callable $callback
3254 final public function onTransactionIdle( $callback ) {
3255 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3256 if ( !$this->mTrxLevel
) {
3257 $this->runOnTransactionIdleCallbacks();
3262 * Run an anonymous function before the current transaction commits or now if there is none.
3263 * If there is a transaction and it is rolled back, then the callback is cancelled.
3264 * Callbacks must not start nor commit any transactions.
3266 * This is useful for updates that easily cause deadlocks if locks are held too long
3267 * but where atomicity is strongly desired for these updates and some related updates.
3269 * @param callable $callback
3272 final public function onTransactionPreCommitOrIdle( $callback ) {
3273 if ( $this->mTrxLevel
) {
3274 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3276 $this->onTransactionIdle( $callback ); // this will trigger immediately
3281 * Actually any "on transaction idle" callbacks.
3285 protected function runOnTransactionIdleCallbacks() {
3286 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3288 $e = null; // last exception
3289 do { // callbacks may add callbacks :)
3290 $callbacks = $this->mTrxIdleCallbacks
;
3291 $this->mTrxIdleCallbacks
= array(); // recursion guard
3292 foreach ( $callbacks as $callback ) {
3294 list( $phpCallback ) = $callback;
3295 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3296 call_user_func( $phpCallback );
3297 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3298 } catch ( Exception
$e ) {
3301 } while ( count( $this->mTrxIdleCallbacks
) );
3303 if ( $e instanceof Exception
) {
3304 throw $e; // re-throw any last exception
3309 * Actually any "on transaction pre-commit" callbacks.
3313 protected function runOnTransactionPreCommitCallbacks() {
3314 $e = null; // last exception
3315 do { // callbacks may add callbacks :)
3316 $callbacks = $this->mTrxPreCommitCallbacks
;
3317 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3318 foreach ( $callbacks as $callback ) {
3320 list( $phpCallback ) = $callback;
3321 call_user_func( $phpCallback );
3322 } catch ( Exception
$e ) {
3325 } while ( count( $this->mTrxPreCommitCallbacks
) );
3327 if ( $e instanceof Exception
) {
3328 throw $e; // re-throw any last exception
3333 * Begin an atomic section of statements
3335 * If a transaction has been started already, just keep track of the given
3336 * section name to make sure the transaction is not committed pre-maturely.
3337 * This function can be used in layers (with sub-sections), so use a stack
3338 * to keep track of the different atomic sections. If there is no transaction,
3339 * start one implicitly.
3341 * The goal of this function is to create an atomic section of SQL queries
3342 * without having to start a new transaction if it already exists.
3344 * Atomic sections are more strict than transactions. With transactions,
3345 * attempting to begin a new transaction when one is already running results
3346 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3347 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3348 * and any database transactions cannot be began or committed until all atomic
3349 * levels are closed. There is no such thing as implicitly opening or closing
3350 * an atomic section.
3353 * @param string $fname
3356 final public function startAtomic( $fname = __METHOD__
) {
3357 if ( !$this->mTrxLevel
) {
3358 $this->begin( $fname );
3359 $this->mTrxAutomatic
= true;
3360 $this->mTrxAutomaticAtomic
= true;
3363 $this->mTrxAtomicLevels
->push( $fname );
3367 * Ends an atomic section of SQL statements
3369 * Ends the next section of atomic SQL statements and commits the transaction
3373 * @see DatabaseBase::startAtomic
3374 * @param string $fname
3377 final public function endAtomic( $fname = __METHOD__
) {
3378 if ( !$this->mTrxLevel
) {
3379 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3381 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3382 $this->mTrxAtomicLevels
->pop() !== $fname
3384 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3387 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3388 $this->commit( $fname, 'flush' );
3393 * Begin a transaction. If a transaction is already in progress,
3394 * that transaction will be committed before the new transaction is started.
3396 * Note that when the DBO_TRX flag is set (which is usually the case for web
3397 * requests, but not for maintenance scripts), any previous database query
3398 * will have started a transaction automatically.
3400 * Nesting of transactions is not supported. Attempts to nest transactions
3401 * will cause a warning, unless the current transaction was started
3402 * automatically because of the DBO_TRX flag.
3404 * @param string $fname
3407 final public function begin( $fname = __METHOD__
) {
3408 global $wgDebugDBTransactions;
3410 if ( $this->mTrxLevel
) { // implicit commit
3411 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3412 // If the current transaction was an automatic atomic one, then we definitely have
3413 // a problem. Same if there is any unclosed atomic level.
3414 throw new DBUnexpectedError( $this,
3415 "Attempted to start explicit transaction when atomic levels are still open."
3417 } elseif ( !$this->mTrxAutomatic
) {
3418 // We want to warn about inadvertently nested begin/commit pairs, but not about
3419 // auto-committing implicit transactions that were started by query() via DBO_TRX
3420 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3421 " performing implicit commit!";
3423 wfLogDBError( $msg );
3425 // if the transaction was automatic and has done write operations,
3426 // log it if $wgDebugDBTransactions is enabled.
3427 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3428 wfDebug( "$fname: Automatic transaction with writes in progress" .
3429 " (from {$this->mTrxFname}), performing implicit commit!\n"
3434 $this->runOnTransactionPreCommitCallbacks();
3435 $this->doCommit( $fname );
3436 if ( $this->mTrxDoneWrites
) {
3437 Profiler
::instance()->transactionWritingOut(
3438 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3440 $this->runOnTransactionIdleCallbacks();
3443 # Avoid fatals if close() was called
3444 if ( !$this->isOpen() ) {
3445 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3448 $this->doBegin( $fname );
3449 $this->mTrxFname
= $fname;
3450 $this->mTrxDoneWrites
= false;
3451 $this->mTrxAutomatic
= false;
3452 $this->mTrxAutomaticAtomic
= false;
3453 $this->mTrxAtomicLevels
= new SplStack
;
3454 $this->mTrxIdleCallbacks
= array();
3455 $this->mTrxPreCommitCallbacks
= array();
3456 $this->mTrxShortId
= wfRandomString( 12 );
3460 * Issues the BEGIN command to the database server.
3462 * @see DatabaseBase::begin()
3463 * @param string $fname
3465 protected function doBegin( $fname ) {
3466 $this->query( 'BEGIN', $fname );
3467 $this->mTrxLevel
= 1;
3471 * Commits a transaction previously started using begin().
3472 * If no transaction is in progress, a warning is issued.
3474 * Nesting of transactions is not supported.
3476 * @param string $fname
3477 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3478 * explicitly committing implicit transactions, or calling commit when no
3479 * transaction is in progress. This will silently break any ongoing
3480 * explicit transaction. Only set the flush flag if you are sure that it
3481 * is safe to ignore these warnings in your context.
3482 * @throws DBUnexpectedError
3484 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3485 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3486 // There are still atomic sections open. This cannot be ignored
3487 throw new DBUnexpectedError(
3489 "Attempted to commit transaction while atomic sections are still open"
3493 if ( $flush === 'flush' ) {
3494 if ( !$this->mTrxLevel
) {
3495 return; // nothing to do
3496 } elseif ( !$this->mTrxAutomatic
) {
3497 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3500 if ( !$this->mTrxLevel
) {
3501 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3502 return; // nothing to do
3503 } elseif ( $this->mTrxAutomatic
) {
3504 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3508 # Avoid fatals if close() was called
3509 if ( !$this->isOpen() ) {
3510 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3513 $this->runOnTransactionPreCommitCallbacks();
3514 $this->doCommit( $fname );
3515 if ( $this->mTrxDoneWrites
) {
3516 Profiler
::instance()->transactionWritingOut(
3517 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3519 $this->runOnTransactionIdleCallbacks();
3523 * Issues the COMMIT command to the database server.
3525 * @see DatabaseBase::commit()
3526 * @param string $fname
3528 protected function doCommit( $fname ) {
3529 if ( $this->mTrxLevel
) {
3530 $this->query( 'COMMIT', $fname );
3531 $this->mTrxLevel
= 0;
3536 * Rollback a transaction previously started using begin().
3537 * If no transaction is in progress, a warning is issued.
3539 * No-op on non-transactional databases.
3541 * @param string $fname
3542 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3543 * calling rollback when no transaction is in progress. This will silently
3544 * break any ongoing explicit transaction. Only set the flush flag if you
3545 * are sure that it is safe to ignore these warnings in your context.
3546 * @since 1.23 Added $flush parameter
3548 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3549 if ( $flush !== 'flush' ) {
3550 if ( !$this->mTrxLevel
) {
3551 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3552 return; // nothing to do
3553 } elseif ( $this->mTrxAutomatic
) {
3554 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3557 if ( !$this->mTrxLevel
) {
3558 return; // nothing to do
3559 } elseif ( !$this->mTrxAutomatic
) {
3560 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3564 # Avoid fatals if close() was called
3565 if ( !$this->isOpen() ) {
3566 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3569 $this->doRollback( $fname );
3570 $this->mTrxIdleCallbacks
= array(); // cancel
3571 $this->mTrxPreCommitCallbacks
= array(); // cancel
3572 $this->mTrxAtomicLevels
= new SplStack
;
3573 if ( $this->mTrxDoneWrites
) {
3574 Profiler
::instance()->transactionWritingOut(
3575 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3580 * Issues the ROLLBACK command to the database server.
3582 * @see DatabaseBase::rollback()
3583 * @param string $fname
3585 protected function doRollback( $fname ) {
3586 if ( $this->mTrxLevel
) {
3587 $this->query( 'ROLLBACK', $fname, true );
3588 $this->mTrxLevel
= 0;
3593 * Creates a new table with structure copied from existing table
3594 * Note that unlike most database abstraction functions, this function does not
3595 * automatically append database prefix, because it works at a lower
3596 * abstraction level.
3597 * The table names passed to this function shall not be quoted (this
3598 * function calls addIdentifierQuotes when needed).
3600 * @param string $oldName Name of table whose structure should be copied
3601 * @param string $newName Name of table to be created
3602 * @param bool $temporary Whether the new table should be temporary
3603 * @param string $fname Calling function name
3604 * @throws MWException
3605 * @return bool True if operation was successful
3607 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3610 throw new MWException(
3611 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3615 * List all tables on the database
3617 * @param string $prefix Only show tables with this prefix, e.g. mw_
3618 * @param string $fname Calling function name
3619 * @throws MWException
3621 function listTables( $prefix = null, $fname = __METHOD__
) {
3622 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3626 * Reset the views process cache set by listViews()
3629 final public function clearViewsCache() {
3630 $this->allViews
= null;
3634 * Lists all the VIEWs in the database
3636 * For caching purposes the list of all views should be stored in
3637 * $this->allViews. The process cache can be cleared with clearViewsCache()
3639 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3640 * @param string $fname Name of calling function
3641 * @throws MWException
3644 public function listViews( $prefix = null, $fname = __METHOD__
) {
3645 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3649 * Differentiates between a TABLE and a VIEW
3651 * @param string $name Name of the database-structure to test.
3652 * @throws MWException
3655 public function isView( $name ) {
3656 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3660 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3661 * to the format used for inserting into timestamp fields in this DBMS.
3663 * The result is unquoted, and needs to be passed through addQuotes()
3664 * before it can be included in raw SQL.
3666 * @param string|int $ts
3670 public function timestamp( $ts = 0 ) {
3671 return wfTimestamp( TS_MW
, $ts );
3675 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3676 * to the format used for inserting into timestamp fields in this DBMS. If
3677 * NULL is input, it is passed through, allowing NULL values to be inserted
3678 * into timestamp fields.
3680 * The result is unquoted, and needs to be passed through addQuotes()
3681 * before it can be included in raw SQL.
3683 * @param string|int $ts
3687 public function timestampOrNull( $ts = null ) {
3688 if ( is_null( $ts ) ) {
3691 return $this->timestamp( $ts );
3696 * Take the result from a query, and wrap it in a ResultWrapper if
3697 * necessary. Boolean values are passed through as is, to indicate success
3698 * of write queries or failure.
3700 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3701 * resource, and it was necessary to call this function to convert it to
3702 * a wrapper. Nowadays, raw database objects are never exposed to external
3703 * callers, so this is unnecessary in external code. For compatibility with
3704 * old code, ResultWrapper objects are passed through unaltered.
3706 * @param bool|ResultWrapper|resource $result
3707 * @return bool|ResultWrapper
3709 public function resultObject( $result ) {
3710 if ( empty( $result ) ) {
3712 } elseif ( $result instanceof ResultWrapper
) {
3714 } elseif ( $result === true ) {
3715 // Successful write query
3718 return new ResultWrapper( $this, $result );
3723 * Ping the server and try to reconnect if it there is no connection
3725 * @return bool Success or failure
3727 public function ping() {
3728 # Stub. Not essential to override.
3733 * Get slave lag. Currently supported only by MySQL.
3735 * Note that this function will generate a fatal error on many
3736 * installations. Most callers should use LoadBalancer::safeGetLag()
3739 * @return int Database replication lag in seconds
3741 public function getLag() {
3746 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3750 function maxListLen() {
3755 * Some DBMSs have a special format for inserting into blob fields, they
3756 * don't allow simple quoted strings to be inserted. To insert into such
3757 * a field, pass the data through this function before passing it to
3758 * DatabaseBase::insert().
3763 public function encodeBlob( $b ) {
3768 * Some DBMSs return a special placeholder object representing blob fields
3769 * in result objects. Pass the object through this function to return the
3775 public function decodeBlob( $b ) {
3780 * Override database's default behavior. $options include:
3781 * 'connTimeout' : Set the connection timeout value in seconds.
3782 * May be useful for very long batch queries such as
3783 * full-wiki dumps, where a single query reads out over
3786 * @param array $options
3789 public function setSessionOptions( array $options ) {
3793 * Read and execute SQL commands from a file.
3795 * Returns true on success, error string or exception on failure (depending
3796 * on object's error ignore settings).
3798 * @param string $filename File name to open
3799 * @param bool|callable $lineCallback Optional function called before reading each line
3800 * @param bool|callable $resultCallback Optional function called for each MySQL result
3801 * @param bool|string $fname Calling function name or false if name should be
3802 * generated dynamically using $filename
3803 * @param bool|callable $inputCallback Optional function called for each
3804 * complete line sent
3805 * @throws Exception|MWException
3806 * @return bool|string
3808 public function sourceFile(
3809 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3811 wfSuppressWarnings();
3812 $fp = fopen( $filename, 'r' );
3813 wfRestoreWarnings();
3815 if ( false === $fp ) {
3816 throw new MWException( "Could not open \"{$filename}\".\n" );
3820 $fname = __METHOD__
. "( $filename )";
3824 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3825 } catch ( MWException
$e ) {
3836 * Get the full path of a patch file. Originally based on archive()
3837 * from updaters.inc. Keep in mind this always returns a patch, as
3838 * it fails back to MySQL if no DB-specific patch can be found
3840 * @param string $patch The name of the patch, like patch-something.sql
3841 * @return string Full path to patch file
3843 public function patchPath( $patch ) {
3846 $dbType = $this->getType();
3847 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3848 return "$IP/maintenance/$dbType/archives/$patch";
3850 return "$IP/maintenance/archives/$patch";
3855 * Set variables to be used in sourceFile/sourceStream, in preference to the
3856 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3857 * all. If it's set to false, $GLOBALS will be used.
3859 * @param bool|array $vars Mapping variable name to value.
3861 public function setSchemaVars( $vars ) {
3862 $this->mSchemaVars
= $vars;
3866 * Read and execute commands from an open file handle.
3868 * Returns true on success, error string or exception on failure (depending
3869 * on object's error ignore settings).
3871 * @param resource $fp File handle
3872 * @param bool|callable $lineCallback Optional function called before reading each query
3873 * @param bool|callable $resultCallback Optional function called for each MySQL result
3874 * @param string $fname Calling function name
3875 * @param bool|callable $inputCallback Optional function called for each complete query sent
3876 * @return bool|string
3878 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3879 $fname = __METHOD__
, $inputCallback = false
3883 while ( !feof( $fp ) ) {
3884 if ( $lineCallback ) {
3885 call_user_func( $lineCallback );
3888 $line = trim( fgets( $fp ) );
3890 if ( $line == '' ) {
3894 if ( '-' == $line[0] && '-' == $line[1] ) {
3902 $done = $this->streamStatementEnd( $cmd, $line );
3906 if ( $done ||
feof( $fp ) ) {
3907 $cmd = $this->replaceVars( $cmd );
3909 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
3910 $res = $this->query( $cmd, $fname );
3912 if ( $resultCallback ) {
3913 call_user_func( $resultCallback, $res, $this );
3916 if ( false === $res ) {
3917 $err = $this->lastError();
3919 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3930 * Called by sourceStream() to check if we've reached a statement end
3932 * @param string $sql SQL assembled so far
3933 * @param string $newLine New line about to be added to $sql
3934 * @return bool Whether $newLine contains end of the statement
3936 public function streamStatementEnd( &$sql, &$newLine ) {
3937 if ( $this->delimiter
) {
3939 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3940 if ( $newLine != $prev ) {
3949 * Database independent variable replacement. Replaces a set of variables
3950 * in an SQL statement with their contents as given by $this->getSchemaVars().
3952 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3954 * - '{$var}' should be used for text and is passed through the database's
3956 * - `{$var}` should be used for identifiers (eg: table and database names),
3957 * it is passed through the database's addIdentifierQuotes method which
3958 * can be overridden if the database uses something other than backticks.
3959 * - / *$var* / is just encoded, besides traditional table prefix and
3960 * table options its use should be avoided.
3962 * @param string $ins SQL statement to replace variables in
3963 * @return string The new SQL statement with variables replaced
3965 protected function replaceSchemaVars( $ins ) {
3966 $vars = $this->getSchemaVars();
3967 foreach ( $vars as $var => $value ) {
3969 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3971 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3973 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
3980 * Replace variables in sourced SQL
3982 * @param string $ins
3985 protected function replaceVars( $ins ) {
3986 $ins = $this->replaceSchemaVars( $ins );
3989 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3990 array( $this, 'tableNameCallback' ), $ins );
3993 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3994 array( $this, 'indexNameCallback' ), $ins );
4000 * Get schema variables. If none have been set via setSchemaVars(), then
4001 * use some defaults from the current object.
4005 protected function getSchemaVars() {
4006 if ( $this->mSchemaVars
) {
4007 return $this->mSchemaVars
;
4009 return $this->getDefaultSchemaVars();
4014 * Get schema variables to use if none have been set via setSchemaVars().
4016 * Override this in derived classes to provide variables for tables.sql
4017 * and SQL patch files.
4021 protected function getDefaultSchemaVars() {
4026 * Table name callback
4028 * @param array $matches
4031 protected function tableNameCallback( $matches ) {
4032 return $this->tableName( $matches[1] );
4036 * Index name callback
4038 * @param array $matches
4041 protected function indexNameCallback( $matches ) {
4042 return $this->indexName( $matches[1] );
4046 * Check to see if a named lock is available. This is non-blocking.
4048 * @param string $lockName Name of lock to poll
4049 * @param string $method Name of method calling us
4053 public function lockIsFree( $lockName, $method ) {
4058 * Acquire a named lock
4060 * Abstracted from Filestore::lock() so child classes can implement for
4063 * @param string $lockName Name of lock to aquire
4064 * @param string $method Name of method calling us
4065 * @param int $timeout
4068 public function lock( $lockName, $method, $timeout = 5 ) {
4075 * @param string $lockName Name of lock to release
4076 * @param string $method Name of method calling us
4078 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4079 * by this thread (in which case the lock is not released), and NULL if the named
4080 * lock did not exist
4082 public function unlock( $lockName, $method ) {
4087 * Lock specific tables
4089 * @param array $read Array of tables to lock for read access
4090 * @param array $write Array of tables to lock for write access
4091 * @param string $method Name of caller
4092 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4095 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4100 * Unlock specific tables
4102 * @param string $method The caller
4105 public function unlockTables( $method ) {
4111 * @param string $tableName
4112 * @param string $fName
4113 * @return bool|ResultWrapper
4116 public function dropTable( $tableName, $fName = __METHOD__
) {
4117 if ( !$this->tableExists( $tableName, $fName ) ) {
4120 $sql = "DROP TABLE " . $this->tableName( $tableName );
4121 if ( $this->cascadingDeletes() ) {
4125 return $this->query( $sql, $fName );
4129 * Get search engine class. All subclasses of this need to implement this
4130 * if they wish to use searching.
4134 public function getSearchEngine() {
4135 return 'SearchEngineDummy';
4139 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4140 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4141 * because "i" sorts after all numbers.
4145 public function getInfinity() {
4150 * Encode an expiry time into the DBMS dependent format
4152 * @param string $expiry timestamp for expiry, or the 'infinity' string
4155 public function encodeExpiry( $expiry ) {
4156 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4157 ?
$this->getInfinity()
4158 : $this->timestamp( $expiry );
4162 * Decode an expiry time into a DBMS independent format
4164 * @param string $expiry DB timestamp field value for expiry
4165 * @param int $format TS_* constant, defaults to TS_MW
4168 public function decodeExpiry( $expiry, $format = TS_MW
) {
4169 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4171 : wfTimestamp( $format, $expiry );
4175 * Allow or deny "big selects" for this session only. This is done by setting
4176 * the sql_big_selects session variable.
4178 * This is a MySQL-specific feature.
4180 * @param bool|string $value True for allow, false for deny, or "default" to
4181 * restore the initial value
4183 public function setBigSelects( $value = true ) {
4190 public function __toString() {
4191 return (string)$this->mConn
;
4195 * Run a few simple sanity checks
4197 public function __destruct() {
4198 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4199 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4201 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4203 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4204 $callers[] = $callbackInfo[1];
4206 $callers = implode( ', ', $callers );
4207 trigger_error( "DB transaction callbacks still pending (from $callers)." );