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 ""
275 * @see DatabaseBase::mTrxLevel
277 protected $mTrxShortId = '';
280 * The UNIX time that the transaction started. Callers can assume that if
281 * snapshot isolation is used, then the data is *at least* up to date to that
282 * point (possibly more up-to-date since the first SELECT defines the snapshot).
285 * @see DatabaseBase::mTrxLevel
287 private $mTrxTimestamp = null;
290 * Remembers the function name given for starting the most recent transaction via begin().
291 * Used to provide additional context for error reporting.
294 * @see DatabaseBase::mTrxLevel
296 private $mTrxFname = null;
299 * Record if possible write queries were done in the last transaction started
302 * @see DatabaseBase::mTrxLevel
304 private $mTrxDoneWrites = false;
307 * Record if the current transaction was started implicitly due to DBO_TRX being set.
310 * @see DatabaseBase::mTrxLevel
312 private $mTrxAutomatic = false;
315 * Array of levels of atomicity within transactions
319 private $mTrxAtomicLevels;
322 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
326 private $mTrxAutomaticAtomic = false;
330 * @var resource File handle for upgrade
332 protected $fileHandle = null;
336 * @var string[] Process cache of VIEWs names in the database
338 protected $allViews = null;
340 # ------------------------------------------------------------------------------
342 # ------------------------------------------------------------------------------
343 # These optionally set a variable and return the previous state
346 * A string describing the current software version, and possibly
347 * other details in a user-friendly way. Will be listed on Special:Version, etc.
348 * Use getServerVersion() to get machine-friendly information.
350 * @return string Version information from the database server
352 public function getServerInfo() {
353 return $this->getServerVersion();
357 * @return string Command delimiter used by this database engine
359 public function getDelimiter() {
360 return $this->delimiter
;
364 * Boolean, controls output of large amounts of debug information.
365 * @param bool|null $debug
366 * - true to enable debugging
367 * - false to disable debugging
368 * - omitted or null to do nothing
370 * @return bool|null Previous value of the flag
372 public function debug( $debug = null ) {
373 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
377 * Turns buffering of SQL result sets on (true) or off (false). Default is
380 * Unbuffered queries are very troublesome in MySQL:
382 * - If another query is executed while the first query is being read
383 * out, the first query is killed. This means you can't call normal
384 * MediaWiki functions while you are reading an unbuffered query result
385 * from a normal wfGetDB() connection.
387 * - Unbuffered queries cause the MySQL server to use large amounts of
388 * memory and to hold broad locks which block other queries.
390 * If you want to limit client-side memory, it's almost always better to
391 * split up queries into batches using a LIMIT clause than to switch off
394 * @param null|bool $buffer
395 * @return null|bool The previous value of the flag
397 public function bufferResults( $buffer = null ) {
398 if ( is_null( $buffer ) ) {
399 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
401 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
406 * Turns on (false) or off (true) the automatic generation and sending
407 * of a "we're sorry, but there has been a database error" page on
408 * database errors. Default is on (false). When turned off, the
409 * code should use lastErrno() and lastError() to handle the
410 * situation as appropriate.
412 * Do not use this function outside of the Database classes.
414 * @param null|bool $ignoreErrors
415 * @return bool The previous value of the flag.
417 public function ignoreErrors( $ignoreErrors = null ) {
418 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
422 * Gets the current transaction level.
424 * Historically, transactions were allowed to be "nested". This is no
425 * longer supported, so this function really only returns a boolean.
427 * @return int The previous value
429 public function trxLevel() {
430 return $this->mTrxLevel
;
434 * Get the UNIX timestamp of the time that the transaction was established
436 * This can be used to reason about the staleness of SELECT data
437 * in REPEATABLE-READ transaction isolation level.
439 * @return float|null Returns null if there is not active transaction
442 public function trxTimestamp() {
443 return $this->mTrxLevel ?
$this->mTrxTimestamp
: null;
447 * Get/set the number of errors logged. Only useful when errors are ignored
448 * @param int $count The count to set, or omitted to leave it unchanged.
449 * @return int The error count
451 public function errorCount( $count = null ) {
452 return wfSetVar( $this->mErrorCount
, $count );
456 * Get/set the table prefix.
457 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
458 * @return string The previous table prefix.
460 public function tablePrefix( $prefix = null ) {
461 return wfSetVar( $this->mTablePrefix
, $prefix );
465 * Get/set the db schema.
466 * @param string $schema The database schema to set, or omitted to leave it unchanged.
467 * @return string The previous db schema.
469 public function dbSchema( $schema = null ) {
470 return wfSetVar( $this->mSchema
, $schema );
474 * Set the filehandle to copy write statements to.
476 * @param resource $fh File handle
478 public function setFileHandle( $fh ) {
479 $this->fileHandle
= $fh;
483 * Get properties passed down from the server info array of the load
486 * @param string $name The entry of the info array to get, or null to get the
489 * @return array|mixed|null
491 public function getLBInfo( $name = null ) {
492 if ( is_null( $name ) ) {
493 return $this->mLBInfo
;
495 if ( array_key_exists( $name, $this->mLBInfo
) ) {
496 return $this->mLBInfo
[$name];
504 * Set the LB info array, or a member of it. If called with one parameter,
505 * the LB info array is set to that parameter. If it is called with two
506 * parameters, the member with the given name is set to the given value.
508 * @param string $name
509 * @param array $value
511 public function setLBInfo( $name, $value = null ) {
512 if ( is_null( $value ) ) {
513 $this->mLBInfo
= $name;
515 $this->mLBInfo
[$name] = $value;
520 * Set lag time in seconds for a fake slave
522 * @param mixed $lag Valid values for this parameter are determined by the
523 * subclass, but should be a PHP scalar or array that would be sensible
524 * as part of $wgLBFactoryConf.
526 public function setFakeSlaveLag( $lag ) {
530 * Make this connection a fake master
532 * @param bool $enabled
534 public function setFakeMaster( $enabled = true ) {
538 * Returns true if this database supports (and uses) cascading deletes
542 public function cascadingDeletes() {
547 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
551 public function cleanupTriggers() {
556 * Returns true if this database is strict about what can be put into an IP field.
557 * Specifically, it uses a NULL value instead of an empty string.
561 public function strictIPs() {
566 * Returns true if this database uses timestamps rather than integers
570 public function realTimestamps() {
575 * Returns true if this database does an implicit sort when doing GROUP BY
579 public function implicitGroupby() {
584 * Returns true if this database does an implicit order by when the column has an index
585 * For example: SELECT page_title FROM page LIMIT 1
589 public function implicitOrderby() {
594 * Returns true if this database can do a native search on IP columns
595 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
599 public function searchableIPs() {
604 * Returns true if this database can use functional indexes
608 public function functionalIndexes() {
613 * Return the last query that went through DatabaseBase::query()
616 public function lastQuery() {
617 return $this->mLastQuery
;
621 * Returns true if the connection may have been used for write queries.
622 * Should return true if unsure.
626 public function doneWrites() {
627 return (bool)$this->mDoneWrites
;
631 * Returns the last time the connection may have been used for write queries.
632 * Should return a timestamp if unsure.
634 * @return int|float UNIX timestamp or false
637 public function lastDoneWrites() {
638 return $this->mDoneWrites ?
: false;
642 * Returns true if there is a transaction open with possible write
643 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
647 public function writesOrCallbacksPending() {
648 return $this->mTrxLevel
&& (
649 $this->mTrxDoneWrites ||
$this->mTrxIdleCallbacks ||
$this->mTrxPreCommitCallbacks
654 * Is a connection to the database open?
657 public function isOpen() {
658 return $this->mOpened
;
662 * Set a flag for this connection
664 * @param int $flag DBO_* constants from Defines.php:
665 * - DBO_DEBUG: output some debug info (same as debug())
666 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
667 * - DBO_TRX: automatically start transactions
668 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
669 * and removes it in command line mode
670 * - DBO_PERSISTENT: use persistant database connection
672 public function setFlag( $flag ) {
673 global $wgDebugDBTransactions;
674 $this->mFlags |
= $flag;
675 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
676 wfDebug( "Implicit transactions are now enabled.\n" );
681 * Clear a flag for this connection
683 * @param int $flag DBO_* constants from Defines.php:
684 * - DBO_DEBUG: output some debug info (same as debug())
685 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
686 * - DBO_TRX: automatically start transactions
687 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
688 * and removes it in command line mode
689 * - DBO_PERSISTENT: use persistant database connection
691 public function clearFlag( $flag ) {
692 global $wgDebugDBTransactions;
693 $this->mFlags
&= ~
$flag;
694 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
695 wfDebug( "Implicit transactions are now disabled.\n" );
700 * Returns a boolean whether the flag $flag is set for this connection
702 * @param int $flag DBO_* constants from Defines.php:
703 * - DBO_DEBUG: output some debug info (same as debug())
704 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
705 * - DBO_TRX: automatically start transactions
706 * - DBO_PERSISTENT: use persistant database connection
709 public function getFlag( $flag ) {
710 return !!( $this->mFlags
& $flag );
714 * General read-only accessor
716 * @param string $name
719 public function getProperty( $name ) {
726 public function getWikiID() {
727 if ( $this->mTablePrefix
) {
728 return "{$this->mDBname}-{$this->mTablePrefix}";
730 return $this->mDBname
;
735 * Return a path to the DBMS-specific SQL file if it exists,
736 * otherwise default SQL file
738 * @param string $filename
741 private function getSqlFilePath( $filename ) {
743 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
744 if ( file_exists( $dbmsSpecificFilePath ) ) {
745 return $dbmsSpecificFilePath;
747 return "$IP/maintenance/$filename";
752 * Return a path to the DBMS-specific schema file,
753 * otherwise default to tables.sql
757 public function getSchemaPath() {
758 return $this->getSqlFilePath( 'tables.sql' );
762 * Return a path to the DBMS-specific update key file,
763 * otherwise default to update-keys.sql
767 public function getUpdateKeysPath() {
768 return $this->getSqlFilePath( 'update-keys.sql' );
771 # ------------------------------------------------------------------------------
773 # ------------------------------------------------------------------------------
778 * FIXME: It is possible to construct a Database object with no associated
779 * connection object, by specifying no parameters to __construct(). This
780 * feature is deprecated and should be removed.
782 * DatabaseBase subclasses should not be constructed directly in external
783 * code. DatabaseBase::factory() should be used instead.
785 * @param array $params Parameters passed from DatabaseBase::factory()
787 function __construct( $params = null ) {
788 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
790 $this->mTrxAtomicLevels
= new SplStack
;
792 if ( is_array( $params ) ) { // MW 1.22
793 $server = $params['host'];
794 $user = $params['user'];
795 $password = $params['password'];
796 $dbName = $params['dbname'];
797 $flags = $params['flags'];
798 $tablePrefix = $params['tablePrefix'];
799 $schema = $params['schema'];
800 $foreign = $params['foreign'];
801 } else { // legacy calling pattern
802 wfDeprecated( __METHOD__
. " method called without parameter array.", "1.23" );
803 $args = func_get_args();
804 $server = isset( $args[0] ) ?
$args[0] : false;
805 $user = isset( $args[1] ) ?
$args[1] : false;
806 $password = isset( $args[2] ) ?
$args[2] : false;
807 $dbName = isset( $args[3] ) ?
$args[3] : false;
808 $flags = isset( $args[4] ) ?
$args[4] : 0;
809 $tablePrefix = isset( $args[5] ) ?
$args[5] : 'get from global';
810 $schema = 'get from global';
811 $foreign = isset( $args[6] ) ?
$args[6] : false;
814 $this->mFlags
= $flags;
815 if ( $this->mFlags
& DBO_DEFAULT
) {
816 if ( $wgCommandLineMode ) {
817 $this->mFlags
&= ~DBO_TRX
;
818 if ( $wgDebugDBTransactions ) {
819 wfDebug( "Implicit transaction open disabled.\n" );
822 $this->mFlags |
= DBO_TRX
;
823 if ( $wgDebugDBTransactions ) {
824 wfDebug( "Implicit transaction open enabled.\n" );
829 /** Get the default table prefix*/
830 if ( $tablePrefix == 'get from global' ) {
831 $this->mTablePrefix
= $wgDBprefix;
833 $this->mTablePrefix
= $tablePrefix;
836 /** Get the database schema*/
837 if ( $schema == 'get from global' ) {
838 $this->mSchema
= $wgDBmwschema;
840 $this->mSchema
= $schema;
843 $this->mForeign
= $foreign;
846 $this->open( $server, $user, $password, $dbName );
851 * Called by serialize. Throw an exception when DB connection is serialized.
852 * This causes problems on some database engines because the connection is
853 * not restored on unserialize.
855 public function __sleep() {
856 throw new MWException( 'Database serialization may cause problems, since ' .
857 'the connection is not restored on wakeup.' );
861 * Given a DB type, construct the name of the appropriate child class of
862 * DatabaseBase. This is designed to replace all of the manual stuff like:
863 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
864 * as well as validate against the canonical list of DB types we have
866 * This factory function is mostly useful for when you need to connect to a
867 * database other than the MediaWiki default (such as for external auth,
868 * an extension, et cetera). Do not use this to connect to the MediaWiki
869 * database. Example uses in core:
870 * @see LoadBalancer::reallyOpenConnection()
871 * @see ForeignDBRepo::getMasterDB()
872 * @see WebInstallerDBConnect::execute()
876 * @param string $dbType A possible DB type
877 * @param array $p An array of options to pass to the constructor.
878 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
879 * @throws MWException If the database driver or extension cannot be found
880 * @return DatabaseBase|null DatabaseBase subclass or null
882 final public static function factory( $dbType, $p = array() ) {
883 $canonicalDBTypes = array(
884 'mysql' => array( 'mysqli', 'mysql' ),
885 'postgres' => array(),
892 $dbType = strtolower( $dbType );
893 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
894 $possibleDrivers = $canonicalDBTypes[$dbType];
895 if ( !empty( $p['driver'] ) ) {
896 if ( in_array( $p['driver'], $possibleDrivers ) ) {
897 $driver = $p['driver'];
899 throw new MWException( __METHOD__
.
900 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
903 foreach ( $possibleDrivers as $posDriver ) {
904 if ( extension_loaded( $posDriver ) ) {
905 $driver = $posDriver;
913 if ( $driver === false ) {
914 throw new MWException( __METHOD__
.
915 " no viable database extension found for type '$dbType'" );
918 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
919 // and everything else doesn't use a schema (e.g. null)
920 // Although postgres and oracle support schemas, we don't use them (yet)
921 // to maintain backwards compatibility
922 $defaultSchemas = array(
927 'mssql' => 'get from global',
930 $class = 'Database' . ucfirst( $driver );
931 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
933 'host' => isset( $p['host'] ) ?
$p['host'] : false,
934 'user' => isset( $p['user'] ) ?
$p['user'] : false,
935 'password' => isset( $p['password'] ) ?
$p['password'] : false,
936 'dbname' => isset( $p['dbname'] ) ?
$p['dbname'] : false,
937 'flags' => isset( $p['flags'] ) ?
$p['flags'] : 0,
938 'tablePrefix' => isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global',
939 'schema' => isset( $p['schema'] ) ?
$p['schema'] : $defaultSchemas[$dbType],
940 'foreign' => isset( $p['foreign'] ) ?
$p['foreign'] : false
943 return new $class( $params );
949 protected function installErrorHandler() {
950 $this->mPHPError
= false;
951 $this->htmlErrors
= ini_set( 'html_errors', '0' );
952 set_error_handler( array( $this, 'connectionErrorHandler' ) );
956 * @return bool|string
958 protected function restoreErrorHandler() {
959 restore_error_handler();
960 if ( $this->htmlErrors
!== false ) {
961 ini_set( 'html_errors', $this->htmlErrors
);
963 if ( $this->mPHPError
) {
964 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
965 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
975 * @param string $errstr
977 public function connectionErrorHandler( $errno, $errstr ) {
978 $this->mPHPError
= $errstr;
982 * Closes a database connection.
983 * if it is open : commits any open transactions
985 * @throws MWException
986 * @return bool Operation success. true if already closed.
988 public function close() {
989 if ( count( $this->mTrxIdleCallbacks
) ) { // sanity
990 throw new MWException( "Transaction idle callbacks still pending." );
992 if ( $this->mConn
) {
993 if ( $this->trxLevel() ) {
994 if ( !$this->mTrxAutomatic
) {
995 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
996 " performing implicit commit before closing connection!" );
999 $this->commit( __METHOD__
, 'flush' );
1002 $closed = $this->closeConnection();
1003 $this->mConn
= false;
1007 $this->mOpened
= false;
1013 * Closes underlying database connection
1015 * @return bool Whether connection was closed successfully
1017 abstract protected function closeConnection();
1020 * @param string $error Fallback error message, used if none is given by DB
1021 * @throws DBConnectionError
1023 function reportConnectionError( $error = 'Unknown error' ) {
1024 $myError = $this->lastError();
1030 throw new DBConnectionError( $this, $error );
1034 * The DBMS-dependent part of query()
1036 * @param string $sql SQL query.
1037 * @return ResultWrapper|bool Result object to feed to fetchObject,
1038 * fetchRow, ...; or false on failure
1040 abstract protected function doQuery( $sql );
1043 * Determine whether a query writes to the DB.
1044 * Should return true if unsure.
1046 * @param string $sql
1049 public function isWriteQuery( $sql ) {
1050 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1054 * Run an SQL query and return the result. Normally throws a DBQueryError
1055 * on failure. If errors are ignored, returns false instead.
1057 * In new code, the query wrappers select(), insert(), update(), delete(),
1058 * etc. should be used where possible, since they give much better DBMS
1059 * independence and automatically quote or validate user input in a variety
1060 * of contexts. This function is generally only useful for queries which are
1061 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1064 * However, the query wrappers themselves should call this function.
1066 * @param string $sql SQL query
1067 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1068 * comment (you can use __METHOD__ or add some extra info)
1069 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1070 * maybe best to catch the exception instead?
1071 * @throws MWException
1072 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1073 * for a successful read query, or false on failure if $tempIgnore set
1075 public function query( $sql, $fname = __METHOD__
, $tempIgnore = false ) {
1076 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1078 $this->mLastQuery
= $sql;
1079 if ( $this->isWriteQuery( $sql ) ) {
1080 # Set a flag indicating that writes have been done
1081 wfDebug( __METHOD__
. ': Writes done: ' . DatabaseBase
::generalizeSQL( $sql ) . "\n" );
1082 $this->mDoneWrites
= microtime( true );
1085 # Add a comment for easy SHOW PROCESSLIST interpretation
1086 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1087 $userName = $wgUser->getName();
1088 if ( mb_strlen( $userName ) > 15 ) {
1089 $userName = mb_substr( $userName, 0, 15 ) . '...';
1091 $userName = str_replace( '/', '', $userName );
1096 // Add trace comment to the begin of the sql string, right after the operator.
1097 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1098 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1100 # If DBO_TRX is set, start a transaction
1101 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
1102 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK'
1104 # Avoid establishing transactions for SHOW and SET statements too -
1105 # that would delay transaction initializations to once connection
1106 # is really used by application
1107 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
1108 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
1109 if ( $wgDebugDBTransactions ) {
1110 wfDebug( "Implicit transaction start.\n" );
1112 $this->begin( __METHOD__
. " ($fname)" );
1113 $this->mTrxAutomatic
= true;
1117 # Keep track of whether the transaction has write queries pending
1118 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
1119 $this->mTrxDoneWrites
= true;
1120 Profiler
::instance()->transactionWritingIn(
1121 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
1126 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1128 if ( !Profiler
::instance()->isStub() ) {
1129 # generalizeSQL will probably cut down the query to reasonable
1130 # logging size most of the time. The substr is really just a sanity check.
1132 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1133 $totalProf = 'DatabaseBase::query-master';
1135 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
1136 $totalProf = 'DatabaseBase::query';
1138 # Include query transaction state
1139 $queryProf .= $this->mTrxShortId ?
" [TRX#{$this->mTrxShortId}]" : "";
1141 $trx = $this->mTrxLevel ?
'TRX=yes' : 'TRX=no';
1142 wfProfileIn( $totalProf );
1143 wfProfileIn( $queryProf );
1146 if ( $this->debug() ) {
1150 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1152 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1154 $master = $isMaster ?
'master' : 'slave';
1155 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1158 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
1160 # Avoid fatals if close() was called
1161 if ( !$this->isOpen() ) {
1162 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1165 # Do the query and handle errors
1166 $ret = $this->doQuery( $commentedSql );
1168 MWDebug
::queryTime( $queryId );
1170 # Try reconnecting if the connection was lost
1171 if ( false === $ret && $this->wasErrorReissuable() ) {
1172 # Transaction is gone, like it or not
1173 $hadTrx = $this->mTrxLevel
; // possible lost transaction
1174 $this->mTrxLevel
= 0;
1175 $this->mTrxIdleCallbacks
= array(); // bug 65263
1176 $this->mTrxPreCommitCallbacks
= array(); // bug 65263
1177 wfDebug( "Connection lost, reconnecting...\n" );
1178 # Stash the last error values since ping() might clear them
1179 $lastError = $this->lastError();
1180 $lastErrno = $this->lastErrno();
1181 if ( $this->ping() ) {
1182 global $wgRequestTime;
1183 wfDebug( "Reconnected\n" );
1184 $sqlx = $wgDebugDumpSqlLength ?
substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1186 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1187 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
1188 if ( $elapsed < 300 ) {
1189 # Not a database error to lose a transaction after a minute or two
1190 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx" );
1193 # Leave $ret as false and let an error be reported.
1194 # Callers may catch the exception and continue to use the DB.
1195 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1197 # Should be safe to silently retry (no trx and thus no callbacks)
1198 $ret = $this->doQuery( $commentedSql );
1201 wfDebug( "Failed\n" );
1205 if ( false === $ret ) {
1206 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1209 if ( !Profiler
::instance()->isStub() ) {
1210 wfProfileOut( $queryProf );
1211 wfProfileOut( $totalProf );
1214 return $this->resultObject( $ret );
1218 * Report a query error. Log the error, and if neither the object ignore
1219 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1221 * @param string $error
1223 * @param string $sql
1224 * @param string $fname
1225 * @param bool $tempIgnore
1226 * @throws DBQueryError
1228 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1229 # Ignore errors during error handling to avoid infinite recursion
1230 $ignore = $this->ignoreErrors( true );
1231 ++
$this->mErrorCount
;
1233 if ( $ignore ||
$tempIgnore ) {
1234 wfDebug( "SQL ERROR (ignored): $error\n" );
1235 $this->ignoreErrors( $ignore );
1237 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1238 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line" );
1239 wfDebug( "SQL ERROR: " . $error . "\n" );
1240 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1245 * Intended to be compatible with the PEAR::DB wrapper functions.
1246 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1248 * ? = scalar value, quoted as necessary
1249 * ! = raw SQL bit (a function for instance)
1250 * & = filename; reads the file and inserts as a blob
1251 * (we don't use this though...)
1253 * @param string $sql
1254 * @param string $func
1258 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1259 /* MySQL doesn't support prepared statements (yet), so just
1260 * pack up the query for reference. We'll manually replace
1263 return array( 'query' => $sql, 'func' => $func );
1267 * Free a prepared query, generated by prepare().
1268 * @param string $prepared
1270 protected function freePrepared( $prepared ) {
1271 /* No-op by default */
1275 * Execute a prepared query with the various arguments
1276 * @param string $prepared The prepared sql
1277 * @param mixed $args Either an array here, or put scalars as varargs
1279 * @return ResultWrapper
1281 public function execute( $prepared, $args = null ) {
1282 if ( !is_array( $args ) ) {
1284 $args = func_get_args();
1285 array_shift( $args );
1288 $sql = $this->fillPrepared( $prepared['query'], $args );
1290 return $this->query( $sql, $prepared['func'] );
1294 * For faking prepared SQL statements on DBs that don't support it directly.
1296 * @param string $preparedQuery A 'preparable' SQL statement
1297 * @param array $args Array of Arguments to fill it with
1298 * @return string Executable SQL
1300 public function fillPrepared( $preparedQuery, $args ) {
1302 $this->preparedArgs
=& $args;
1304 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1305 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1309 * preg_callback func for fillPrepared()
1310 * The arguments should be in $this->preparedArgs and must not be touched
1311 * while we're doing this.
1313 * @param array $matches
1314 * @throws DBUnexpectedError
1317 protected function fillPreparedArg( $matches ) {
1318 switch ( $matches[1] ) {
1327 list( /* $n */, $arg ) = each( $this->preparedArgs
);
1329 switch ( $matches[1] ) {
1331 return $this->addQuotes( $arg );
1335 # return $this->addQuotes( file_get_contents( $arg ) );
1336 throw new DBUnexpectedError(
1338 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1341 throw new DBUnexpectedError(
1343 'Received invalid match. This should never happen!'
1349 * Free a result object returned by query() or select(). It's usually not
1350 * necessary to call this, just use unset() or let the variable holding
1351 * the result object go out of scope.
1353 * @param mixed $res A SQL result
1355 public function freeResult( $res ) {
1359 * A SELECT wrapper which returns a single field from a single result row.
1361 * Usually throws a DBQueryError on failure. If errors are explicitly
1362 * ignored, returns false on failure.
1364 * If no result rows are returned from the query, false is returned.
1366 * @param string|array $table Table name. See DatabaseBase::select() for details.
1367 * @param string $var The field name to select. This must be a valid SQL
1368 * fragment: do not use unvalidated user input.
1369 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1370 * @param string $fname The function name of the caller.
1371 * @param string|array $options The query options. See DatabaseBase::select() for details.
1373 * @return bool|mixed The value from the field, or false on failure.
1375 public function selectField( $table, $var, $cond = '', $fname = __METHOD__
,
1378 if ( !is_array( $options ) ) {
1379 $options = array( $options );
1382 $options['LIMIT'] = 1;
1384 $res = $this->select( $table, $var, $cond, $fname, $options );
1386 if ( $res === false ||
!$this->numRows( $res ) ) {
1390 $row = $this->fetchRow( $res );
1392 if ( $row !== false ) {
1393 return reset( $row );
1400 * Returns an optional USE INDEX clause to go after the table, and a
1401 * string to go at the end of the query.
1403 * @param array $options Associative array of options to be turned into
1404 * an SQL query, valid keys are listed in the function.
1406 * @see DatabaseBase::select()
1408 public function makeSelectOptions( $options ) {
1409 $preLimitTail = $postLimitTail = '';
1412 $noKeyOptions = array();
1414 foreach ( $options as $key => $option ) {
1415 if ( is_numeric( $key ) ) {
1416 $noKeyOptions[$option] = true;
1420 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1422 $preLimitTail .= $this->makeOrderBy( $options );
1424 // if (isset($options['LIMIT'])) {
1425 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1426 // isset($options['OFFSET']) ? $options['OFFSET']
1430 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1431 $postLimitTail .= ' FOR UPDATE';
1434 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1435 $postLimitTail .= ' LOCK IN SHARE MODE';
1438 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1439 $startOpts .= 'DISTINCT';
1442 # Various MySQL extensions
1443 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1444 $startOpts .= ' /*! STRAIGHT_JOIN */';
1447 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1448 $startOpts .= ' HIGH_PRIORITY';
1451 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1452 $startOpts .= ' SQL_BIG_RESULT';
1455 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1456 $startOpts .= ' SQL_BUFFER_RESULT';
1459 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1460 $startOpts .= ' SQL_SMALL_RESULT';
1463 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1464 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1467 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1468 $startOpts .= ' SQL_CACHE';
1471 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1472 $startOpts .= ' SQL_NO_CACHE';
1475 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1476 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1481 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1485 * Returns an optional GROUP BY with an optional HAVING
1487 * @param array $options Associative array of options
1489 * @see DatabaseBase::select()
1492 public function makeGroupByWithHaving( $options ) {
1494 if ( isset( $options['GROUP BY'] ) ) {
1495 $gb = is_array( $options['GROUP BY'] )
1496 ?
implode( ',', $options['GROUP BY'] )
1497 : $options['GROUP BY'];
1498 $sql .= ' GROUP BY ' . $gb;
1500 if ( isset( $options['HAVING'] ) ) {
1501 $having = is_array( $options['HAVING'] )
1502 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1503 : $options['HAVING'];
1504 $sql .= ' HAVING ' . $having;
1511 * Returns an optional ORDER BY
1513 * @param array $options Associative array of options
1515 * @see DatabaseBase::select()
1518 public function makeOrderBy( $options ) {
1519 if ( isset( $options['ORDER BY'] ) ) {
1520 $ob = is_array( $options['ORDER BY'] )
1521 ?
implode( ',', $options['ORDER BY'] )
1522 : $options['ORDER BY'];
1524 return ' ORDER BY ' . $ob;
1531 * Execute a SELECT query constructed using the various parameters provided.
1532 * See below for full details of the parameters.
1534 * @param string|array $table Table name
1535 * @param string|array $vars Field names
1536 * @param string|array $conds Conditions
1537 * @param string $fname Caller function name
1538 * @param array $options Query options
1539 * @param array $join_conds Join conditions
1542 * @param string|array $table
1544 * May be either an array of table names, or a single string holding a table
1545 * name. If an array is given, table aliases can be specified, for example:
1547 * array( 'a' => 'user' )
1549 * This includes the user table in the query, with the alias "a" available
1550 * for use in field names (e.g. a.user_name).
1552 * All of the table names given here are automatically run through
1553 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1554 * added, and various other table name mappings to be performed.
1557 * @param string|array $vars
1559 * May be either a field name or an array of field names. The field names
1560 * can be complete fragments of SQL, for direct inclusion into the SELECT
1561 * query. If an array is given, field aliases can be specified, for example:
1563 * array( 'maxrev' => 'MAX(rev_id)' )
1565 * This includes an expression with the alias "maxrev" in the query.
1567 * If an expression is given, care must be taken to ensure that it is
1571 * @param string|array $conds
1573 * May be either a string containing a single condition, or an array of
1574 * conditions. If an array is given, the conditions constructed from each
1575 * element are combined with AND.
1577 * Array elements may take one of two forms:
1579 * - Elements with a numeric key are interpreted as raw SQL fragments.
1580 * - Elements with a string key are interpreted as equality conditions,
1581 * where the key is the field name.
1582 * - If the value of such an array element is a scalar (such as a
1583 * string), it will be treated as data and thus quoted appropriately.
1584 * If it is null, an IS NULL clause will be added.
1585 * - If the value is an array, an IN(...) clause will be constructed,
1586 * such that the field name may match any of the elements in the
1587 * array. The elements of the array will be quoted.
1589 * Note that expressions are often DBMS-dependent in their syntax.
1590 * DBMS-independent wrappers are provided for constructing several types of
1591 * expression commonly used in condition queries. See:
1592 * - DatabaseBase::buildLike()
1593 * - DatabaseBase::conditional()
1596 * @param string|array $options
1598 * Optional: Array of query options. Boolean options are specified by
1599 * including them in the array as a string value with a numeric key, for
1602 * array( 'FOR UPDATE' )
1604 * The supported options are:
1606 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1607 * with LIMIT can theoretically be used for paging through a result set,
1608 * but this is discouraged in MediaWiki for performance reasons.
1610 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1611 * and then the first rows are taken until the limit is reached. LIMIT
1612 * is applied to a result set after OFFSET.
1614 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1615 * changed until the next COMMIT.
1617 * - DISTINCT: Boolean: return only unique result rows.
1619 * - GROUP BY: May be either an SQL fragment string naming a field or
1620 * expression to group by, or an array of such SQL fragments.
1622 * - HAVING: May be either an string containing a HAVING clause or an array of
1623 * conditions building the HAVING clause. If an array is given, the conditions
1624 * constructed from each element are combined with AND.
1626 * - ORDER BY: May be either an SQL fragment giving a field name or
1627 * expression to order by, or an array of such SQL fragments.
1629 * - USE INDEX: This may be either a string giving the index name to use
1630 * for the query, or an array. If it is an associative array, each key
1631 * gives the table name (or alias), each value gives the index name to
1632 * use for that table. All strings are SQL fragments and so should be
1633 * validated by the caller.
1635 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1636 * instead of SELECT.
1638 * And also the following boolean MySQL extensions, see the MySQL manual
1639 * for documentation:
1641 * - LOCK IN SHARE MODE
1645 * - SQL_BUFFER_RESULT
1646 * - SQL_SMALL_RESULT
1647 * - SQL_CALC_FOUND_ROWS
1652 * @param string|array $join_conds
1654 * Optional associative array of table-specific join conditions. In the
1655 * most common case, this is unnecessary, since the join condition can be
1656 * in $conds. However, it is useful for doing a LEFT JOIN.
1658 * The key of the array contains the table name or alias. The value is an
1659 * array with two elements, numbered 0 and 1. The first gives the type of
1660 * join, the second is an SQL fragment giving the join condition for that
1661 * table. For example:
1663 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1665 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1666 * with no rows in it will be returned. If there was a query error, a
1667 * DBQueryError exception will be thrown, except if the "ignore errors"
1668 * option was set, in which case false will be returned.
1670 public function select( $table, $vars, $conds = '', $fname = __METHOD__
,
1671 $options = array(), $join_conds = array() ) {
1672 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1674 return $this->query( $sql, $fname );
1678 * The equivalent of DatabaseBase::select() except that the constructed SQL
1679 * is returned, instead of being immediately executed. This can be useful for
1680 * doing UNION queries, where the SQL text of each query is needed. In general,
1681 * however, callers outside of Database classes should just use select().
1683 * @param string|array $table Table name
1684 * @param string|array $vars Field names
1685 * @param string|array $conds Conditions
1686 * @param string $fname Caller function name
1687 * @param string|array $options Query options
1688 * @param string|array $join_conds Join conditions
1690 * @return string SQL query string.
1691 * @see DatabaseBase::select()
1693 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__
,
1694 $options = array(), $join_conds = array()
1696 if ( is_array( $vars ) ) {
1697 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1700 $options = (array)$options;
1701 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1702 ?
$options['USE INDEX']
1705 if ( is_array( $table ) ) {
1707 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1708 } elseif ( $table != '' ) {
1709 if ( $table[0] == ' ' ) {
1710 $from = ' FROM ' . $table;
1713 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1719 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1720 $this->makeSelectOptions( $options );
1722 if ( !empty( $conds ) ) {
1723 if ( is_array( $conds ) ) {
1724 $conds = $this->makeList( $conds, LIST_AND
);
1726 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1728 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1731 if ( isset( $options['LIMIT'] ) ) {
1732 $sql = $this->limitResult( $sql, $options['LIMIT'],
1733 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1735 $sql = "$sql $postLimitTail";
1737 if ( isset( $options['EXPLAIN'] ) ) {
1738 $sql = 'EXPLAIN ' . $sql;
1745 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1746 * that a single row object is returned. If the query returns no rows,
1747 * false is returned.
1749 * @param string|array $table Table name
1750 * @param string|array $vars Field names
1751 * @param array $conds Conditions
1752 * @param string $fname Caller function name
1753 * @param string|array $options Query options
1754 * @param array|string $join_conds Join conditions
1756 * @return stdClass|bool
1758 public function selectRow( $table, $vars, $conds, $fname = __METHOD__
,
1759 $options = array(), $join_conds = array()
1761 $options = (array)$options;
1762 $options['LIMIT'] = 1;
1763 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1765 if ( $res === false ) {
1769 if ( !$this->numRows( $res ) ) {
1773 $obj = $this->fetchObject( $res );
1779 * Estimate the number of rows in dataset
1781 * MySQL allows you to estimate the number of rows that would be returned
1782 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1783 * index cardinality statistics, and is notoriously inaccurate, especially
1784 * when large numbers of rows have recently been added or deleted.
1786 * For DBMSs that don't support fast result size estimation, this function
1787 * will actually perform the SELECT COUNT(*).
1789 * Takes the same arguments as DatabaseBase::select().
1791 * @param string $table Table name
1792 * @param string $vars Unused
1793 * @param array|string $conds Filters on the table
1794 * @param string $fname Function name for profiling
1795 * @param array $options Options for select
1796 * @return int Row count
1798 public function estimateRowCount(
1799 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1802 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1805 $row = $this->fetchRow( $res );
1806 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1813 * Get the number of rows in dataset
1815 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1817 * Takes the same arguments as DatabaseBase::select().
1819 * @param string $table Table name
1820 * @param string $vars Unused
1821 * @param array|string $conds Filters on the table
1822 * @param string $fname Function name for profiling
1823 * @param array $options Options for select
1824 * @return int Row count
1827 public function selectRowCount(
1828 $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array()
1831 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1832 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1835 $row = $this->fetchRow( $res );
1836 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1843 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1844 * It's only slightly flawed. Don't use for anything important.
1846 * @param string $sql A SQL Query
1850 static function generalizeSQL( $sql ) {
1851 # This does the same as the regexp below would do, but in such a way
1852 # as to avoid crashing php on some large strings.
1853 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1855 $sql = str_replace( "\\\\", '', $sql );
1856 $sql = str_replace( "\\'", '', $sql );
1857 $sql = str_replace( "\\\"", '', $sql );
1858 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1859 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1861 # All newlines, tabs, etc replaced by single space
1862 $sql = preg_replace( '/\s+/', ' ', $sql );
1865 # except the ones surrounded by characters, e.g. l10n
1866 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1867 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1873 * Determines whether a field exists in a table
1875 * @param string $table Table name
1876 * @param string $field Filed to check on that table
1877 * @param string $fname Calling function name (optional)
1878 * @return bool Whether $table has filed $field
1880 public function fieldExists( $table, $field, $fname = __METHOD__
) {
1881 $info = $this->fieldInfo( $table, $field );
1887 * Determines whether an index exists
1888 * Usually throws a DBQueryError on failure
1889 * If errors are explicitly ignored, returns NULL on failure
1891 * @param string $table
1892 * @param string $index
1893 * @param string $fname
1896 public function indexExists( $table, $index, $fname = __METHOD__
) {
1897 if ( !$this->tableExists( $table ) ) {
1901 $info = $this->indexInfo( $table, $index, $fname );
1902 if ( is_null( $info ) ) {
1905 return $info !== false;
1910 * Query whether a given table exists
1912 * @param string $table
1913 * @param string $fname
1916 public function tableExists( $table, $fname = __METHOD__
) {
1917 $table = $this->tableName( $table );
1918 $old = $this->ignoreErrors( true );
1919 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1920 $this->ignoreErrors( $old );
1926 * Determines if a given index is unique
1928 * @param string $table
1929 * @param string $index
1933 public function indexUnique( $table, $index ) {
1934 $indexInfo = $this->indexInfo( $table, $index );
1936 if ( !$indexInfo ) {
1940 return !$indexInfo[0]->Non_unique
;
1944 * Helper for DatabaseBase::insert().
1946 * @param array $options
1949 protected function makeInsertOptions( $options ) {
1950 return implode( ' ', $options );
1954 * INSERT wrapper, inserts an array into a table.
1958 * - A single associative array. The array keys are the field names, and
1959 * the values are the values to insert. The values are treated as data
1960 * and will be quoted appropriately. If NULL is inserted, this will be
1961 * converted to a database NULL.
1962 * - An array with numeric keys, holding a list of associative arrays.
1963 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1964 * each subarray must be identical to each other, and in the same order.
1966 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1969 * $options is an array of options, with boolean options encoded as values
1970 * with numeric keys, in the same style as $options in
1971 * DatabaseBase::select(). Supported options are:
1973 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1974 * any rows which cause duplicate key errors are not inserted. It's
1975 * possible to determine how many rows were successfully inserted using
1976 * DatabaseBase::affectedRows().
1978 * @param string $table Table name. This will be passed through
1979 * DatabaseBase::tableName().
1980 * @param array $a Array of rows to insert
1981 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1982 * @param array $options Array of options
1986 public function insert( $table, $a, $fname = __METHOD__
, $options = array() ) {
1987 # No rows to insert, easy just return now
1988 if ( !count( $a ) ) {
1992 $table = $this->tableName( $table );
1994 if ( !is_array( $options ) ) {
1995 $options = array( $options );
1999 if ( isset( $options['fileHandle'] ) ) {
2000 $fh = $options['fileHandle'];
2002 $options = $this->makeInsertOptions( $options );
2004 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2006 $keys = array_keys( $a[0] );
2009 $keys = array_keys( $a );
2012 $sql = 'INSERT ' . $options .
2013 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2017 foreach ( $a as $row ) {
2023 $sql .= '(' . $this->makeList( $row ) . ')';
2026 $sql .= '(' . $this->makeList( $a ) . ')';
2029 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2031 } elseif ( $fh !== null ) {
2035 return (bool)$this->query( $sql, $fname );
2039 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2041 * @param array $options
2044 protected function makeUpdateOptionsArray( $options ) {
2045 if ( !is_array( $options ) ) {
2046 $options = array( $options );
2051 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2052 $opts[] = $this->lowPriorityOption();
2055 if ( in_array( 'IGNORE', $options ) ) {
2063 * Make UPDATE options for the DatabaseBase::update function
2065 * @param array $options The options passed to DatabaseBase::update
2068 protected function makeUpdateOptions( $options ) {
2069 $opts = $this->makeUpdateOptionsArray( $options );
2071 return implode( ' ', $opts );
2075 * UPDATE wrapper. Takes a condition array and a SET array.
2077 * @param string $table Name of the table to UPDATE. This will be passed through
2078 * DatabaseBase::tableName().
2079 * @param array $values An array of values to SET. For each array element,
2080 * the key gives the field name, and the value gives the data to set
2081 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2082 * @param array $conds An array of conditions (WHERE). See
2083 * DatabaseBase::select() for the details of the format of condition
2084 * arrays. Use '*' to update all rows.
2085 * @param string $fname The function name of the caller (from __METHOD__),
2086 * for logging and profiling.
2087 * @param array $options An array of UPDATE options, can be:
2088 * - IGNORE: Ignore unique key conflicts
2089 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2092 function update( $table, $values, $conds, $fname = __METHOD__
, $options = array() ) {
2093 $table = $this->tableName( $table );
2094 $opts = $this->makeUpdateOptions( $options );
2095 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
2097 if ( $conds !== array() && $conds !== '*' ) {
2098 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
2101 return $this->query( $sql, $fname );
2105 * Makes an encoded list of strings from an array
2107 * @param array $a Containing the data
2108 * @param int $mode Constant
2109 * - LIST_COMMA: Comma separated, no field names
2110 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2111 * documentation for $conds in DatabaseBase::select().
2112 * - LIST_OR: ORed WHERE clause (without the WHERE)
2113 * - LIST_SET: Comma separated with field names, like a SET clause
2114 * - LIST_NAMES: Comma separated field names
2115 * @throws MWException|DBUnexpectedError
2118 public function makeList( $a, $mode = LIST_COMMA
) {
2119 if ( !is_array( $a ) ) {
2120 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2126 foreach ( $a as $field => $value ) {
2128 if ( $mode == LIST_AND
) {
2130 } elseif ( $mode == LIST_OR
) {
2139 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
2140 $list .= "($value)";
2141 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
2143 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
2144 if ( count( $value ) == 0 ) {
2145 throw new MWException( __METHOD__
. ": empty input for field $field" );
2146 } elseif ( count( $value ) == 1 ) {
2147 // Special-case single values, as IN isn't terribly efficient
2148 // Don't necessarily assume the single key is 0; we don't
2149 // enforce linear numeric ordering on other arrays here.
2150 $value = array_values( $value );
2151 $list .= $field . " = " . $this->addQuotes( $value[0] );
2153 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2155 } elseif ( $value === null ) {
2156 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
2157 $list .= "$field IS ";
2158 } elseif ( $mode == LIST_SET
) {
2159 $list .= "$field = ";
2163 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
2164 $list .= "$field = ";
2166 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
2174 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2175 * The keys on each level may be either integers or strings.
2177 * @param array $data Organized as 2-d
2178 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2179 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2180 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2181 * @return string|bool SQL fragment, or false if no items in array
2183 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2186 foreach ( $data as $base => $sub ) {
2187 if ( count( $sub ) ) {
2188 $conds[] = $this->makeList(
2189 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2195 return $this->makeList( $conds, LIST_OR
);
2197 // Nothing to search for...
2203 * Return aggregated value alias
2205 * @param array $valuedata
2206 * @param string $valuename
2210 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2215 * @param string $field
2218 public function bitNot( $field ) {
2223 * @param string $fieldLeft
2224 * @param string $fieldRight
2227 public function bitAnd( $fieldLeft, $fieldRight ) {
2228 return "($fieldLeft & $fieldRight)";
2232 * @param string $fieldLeft
2233 * @param string $fieldRight
2236 public function bitOr( $fieldLeft, $fieldRight ) {
2237 return "($fieldLeft | $fieldRight)";
2241 * Build a concatenation list to feed into a SQL query
2242 * @param array $stringList List of raw SQL expressions; caller is
2243 * responsible for any quoting
2246 public function buildConcat( $stringList ) {
2247 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2251 * Build a GROUP_CONCAT or equivalent statement for a query.
2253 * This is useful for combining a field for several rows into a single string.
2254 * NULL values will not appear in the output, duplicated values will appear,
2255 * and the resulting delimiter-separated values have no defined sort order.
2256 * Code using the results may need to use the PHP unique() or sort() methods.
2258 * @param string $delim Glue to bind the results together
2259 * @param string|array $table Table name
2260 * @param string $field Field name
2261 * @param string|array $conds Conditions
2262 * @param string|array $join_conds Join conditions
2263 * @return string SQL text
2266 public function buildGroupConcatField(
2267 $delim, $table, $field, $conds = '', $join_conds = array()
2269 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2271 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2275 * Change the current database
2277 * @todo Explain what exactly will fail if this is not overridden.
2281 * @return bool Success or failure
2283 public function selectDB( $db ) {
2284 # Stub. Shouldn't cause serious problems if it's not overridden, but
2285 # if your database engine supports a concept similar to MySQL's
2286 # databases you may as well.
2287 $this->mDBname
= $db;
2293 * Get the current DB name
2296 public function getDBname() {
2297 return $this->mDBname
;
2301 * Get the server hostname or IP address
2304 public function getServer() {
2305 return $this->mServer
;
2309 * Format a table name ready for use in constructing an SQL query
2311 * This does two important things: it quotes the table names to clean them up,
2312 * and it adds a table prefix if only given a table name with no quotes.
2314 * All functions of this object which require a table name call this function
2315 * themselves. Pass the canonical name to such functions. This is only needed
2316 * when calling query() directly.
2318 * @param string $name Database table name
2319 * @param string $format One of:
2320 * quoted - Automatically pass the table name through addIdentifierQuotes()
2321 * so that it can be used in a query.
2322 * raw - Do not add identifier quotes to the table name
2323 * @return string Full database name
2325 public function tableName( $name, $format = 'quoted' ) {
2326 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2327 # Skip the entire process when we have a string quoted on both ends.
2328 # Note that we check the end so that we will still quote any use of
2329 # use of `database`.table. But won't break things if someone wants
2330 # to query a database table with a dot in the name.
2331 if ( $this->isQuotedIdentifier( $name ) ) {
2335 # Lets test for any bits of text that should never show up in a table
2336 # name. Basically anything like JOIN or ON which are actually part of
2337 # SQL queries, but may end up inside of the table value to combine
2338 # sql. Such as how the API is doing.
2339 # Note that we use a whitespace test rather than a \b test to avoid
2340 # any remote case where a word like on may be inside of a table name
2341 # surrounded by symbols which may be considered word breaks.
2342 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2346 # Split database and table into proper variables.
2347 # We reverse the explode so that database.table and table both output
2348 # the correct table.
2349 $dbDetails = explode( '.', $name, 3 );
2350 if ( count( $dbDetails ) == 3 ) {
2351 list( $database, $schema, $table ) = $dbDetails;
2352 # We don't want any prefix added in this case
2354 } elseif ( count( $dbDetails ) == 2 ) {
2355 list( $database, $table ) = $dbDetails;
2356 # We don't want any prefix added in this case
2357 # In dbs that support it, $database may actually be the schema
2358 # but that doesn't affect any of the functionality here
2362 list( $table ) = $dbDetails;
2363 if ( $wgSharedDB !== null # We have a shared database
2364 && $this->mForeign
== false # We're not working on a foreign database
2365 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2366 && in_array( $table, $wgSharedTables ) # A shared table is selected
2368 $database = $wgSharedDB;
2369 $schema = $wgSharedSchema === null ?
$this->mSchema
: $wgSharedSchema;
2370 $prefix = $wgSharedPrefix === null ?
$this->mTablePrefix
: $wgSharedPrefix;
2373 $schema = $this->mSchema
; # Default schema
2374 $prefix = $this->mTablePrefix
; # Default prefix
2378 # Quote $table and apply the prefix if not quoted.
2379 # $tableName might be empty if this is called from Database::replaceVars()
2380 $tableName = "{$prefix}{$table}";
2381 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2382 $tableName = $this->addIdentifierQuotes( $tableName );
2385 # Quote $schema and merge it with the table name if needed
2386 if ( $schema !== null ) {
2387 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2388 $schema = $this->addIdentifierQuotes( $schema );
2390 $tableName = $schema . '.' . $tableName;
2393 # Quote $database and merge it with the table name if needed
2394 if ( $database !== null ) {
2395 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2396 $database = $this->addIdentifierQuotes( $database );
2398 $tableName = $database . '.' . $tableName;
2405 * Fetch a number of table names into an array
2406 * This is handy when you need to construct SQL for joins
2409 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2410 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2411 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2415 public function tableNames() {
2416 $inArray = func_get_args();
2419 foreach ( $inArray as $name ) {
2420 $retVal[$name] = $this->tableName( $name );
2427 * Fetch a number of table names into an zero-indexed numerical array
2428 * This is handy when you need to construct SQL for joins
2431 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2432 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2433 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2437 public function tableNamesN() {
2438 $inArray = func_get_args();
2441 foreach ( $inArray as $name ) {
2442 $retVal[] = $this->tableName( $name );
2449 * Get an aliased table name
2450 * e.g. tableName AS newTableName
2452 * @param string $name Table name, see tableName()
2453 * @param string|bool $alias Alias (optional)
2454 * @return string SQL name for aliased table. Will not alias a table to its own name
2456 public function tableNameWithAlias( $name, $alias = false ) {
2457 if ( !$alias ||
$alias == $name ) {
2458 return $this->tableName( $name );
2460 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2465 * Gets an array of aliased table names
2467 * @param array $tables Array( [alias] => table )
2468 * @return string[] See tableNameWithAlias()
2470 public function tableNamesWithAlias( $tables ) {
2472 foreach ( $tables as $alias => $table ) {
2473 if ( is_numeric( $alias ) ) {
2476 $retval[] = $this->tableNameWithAlias( $table, $alias );
2483 * Get an aliased field name
2484 * e.g. fieldName AS newFieldName
2486 * @param string $name Field name
2487 * @param string|bool $alias Alias (optional)
2488 * @return string SQL name for aliased field. Will not alias a field to its own name
2490 public function fieldNameWithAlias( $name, $alias = false ) {
2491 if ( !$alias ||
(string)$alias === (string)$name ) {
2494 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2499 * Gets an array of aliased field names
2501 * @param array $fields Array( [alias] => field )
2502 * @return string[] See fieldNameWithAlias()
2504 public function fieldNamesWithAlias( $fields ) {
2506 foreach ( $fields as $alias => $field ) {
2507 if ( is_numeric( $alias ) ) {
2510 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2517 * Get the aliased table name clause for a FROM clause
2518 * which might have a JOIN and/or USE INDEX clause
2520 * @param array $tables ( [alias] => table )
2521 * @param array $use_index Same as for select()
2522 * @param array $join_conds Same as for select()
2525 protected function tableNamesWithUseIndexOrJOIN(
2526 $tables, $use_index = array(), $join_conds = array()
2530 $use_index = (array)$use_index;
2531 $join_conds = (array)$join_conds;
2533 foreach ( $tables as $alias => $table ) {
2534 if ( !is_string( $alias ) ) {
2535 // No alias? Set it equal to the table name
2538 // Is there a JOIN clause for this table?
2539 if ( isset( $join_conds[$alias] ) ) {
2540 list( $joinType, $conds ) = $join_conds[$alias];
2541 $tableClause = $joinType;
2542 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2543 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2544 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2546 $tableClause .= ' ' . $use;
2549 $on = $this->makeList( (array)$conds, LIST_AND
);
2551 $tableClause .= ' ON (' . $on . ')';
2554 $retJOIN[] = $tableClause;
2555 } elseif ( isset( $use_index[$alias] ) ) {
2556 // Is there an INDEX clause for this table?
2557 $tableClause = $this->tableNameWithAlias( $table, $alias );
2558 $tableClause .= ' ' . $this->useIndexClause(
2559 implode( ',', (array)$use_index[$alias] )
2562 $ret[] = $tableClause;
2564 $tableClause = $this->tableNameWithAlias( $table, $alias );
2566 $ret[] = $tableClause;
2570 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2571 $implicitJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2572 $explicitJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2574 // Compile our final table clause
2575 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2579 * Get the name of an index in a given table
2581 * @param string $index
2584 protected function indexName( $index ) {
2585 // Backwards-compatibility hack
2587 'ar_usertext_timestamp' => 'usertext_timestamp',
2588 'un_user_id' => 'user_id',
2589 'un_user_ip' => 'user_ip',
2592 if ( isset( $renamed[$index] ) ) {
2593 return $renamed[$index];
2600 * Adds quotes and backslashes.
2605 public function addQuotes( $s ) {
2606 if ( $s === null ) {
2609 # This will also quote numeric values. This should be harmless,
2610 # and protects against weird problems that occur when they really
2611 # _are_ strings such as article titles and string->number->string
2612 # conversion is not 1:1.
2613 return "'" . $this->strencode( $s ) . "'";
2618 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2619 * MySQL uses `backticks` while basically everything else uses double quotes.
2620 * Since MySQL is the odd one out here the double quotes are our generic
2621 * and we implement backticks in DatabaseMysql.
2626 public function addIdentifierQuotes( $s ) {
2627 return '"' . str_replace( '"', '""', $s ) . '"';
2631 * Returns if the given identifier looks quoted or not according to
2632 * the database convention for quoting identifiers .
2634 * @param string $name
2637 public function isQuotedIdentifier( $name ) {
2638 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2645 protected function escapeLikeInternal( $s ) {
2646 return addcslashes( $s, '\%_' );
2650 * LIKE statement wrapper, receives a variable-length argument list with
2651 * parts of pattern to match containing either string literals that will be
2652 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2653 * the function could be provided with an array of aforementioned
2656 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2657 * a LIKE clause that searches for subpages of 'My page title'.
2659 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2660 * $query .= $dbr->buildLike( $pattern );
2663 * @return string Fully built LIKE statement
2665 public function buildLike() {
2666 $params = func_get_args();
2668 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2669 $params = $params[0];
2674 foreach ( $params as $value ) {
2675 if ( $value instanceof LikeMatch
) {
2676 $s .= $value->toString();
2678 $s .= $this->escapeLikeInternal( $value );
2682 return " LIKE {$this->addQuotes( $s )} ";
2686 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2690 public function anyChar() {
2691 return new LikeMatch( '_' );
2695 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2699 public function anyString() {
2700 return new LikeMatch( '%' );
2704 * Returns an appropriately quoted sequence value for inserting a new row.
2705 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2706 * subclass will return an integer, and save the value for insertId()
2708 * Any implementation of this function should *not* involve reusing
2709 * sequence numbers created for rolled-back transactions.
2710 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2711 * @param string $seqName
2714 public function nextSequenceValue( $seqName ) {
2719 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2720 * is only needed because a) MySQL must be as efficient as possible due to
2721 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2722 * which index to pick. Anyway, other databases might have different
2723 * indexes on a given table. So don't bother overriding this unless you're
2725 * @param string $index
2728 public function useIndexClause( $index ) {
2733 * REPLACE query wrapper.
2735 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2736 * except that when there is a duplicate key error, the old row is deleted
2737 * and the new row is inserted in its place.
2739 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2740 * perform the delete, we need to know what the unique indexes are so that
2741 * we know how to find the conflicting rows.
2743 * It may be more efficient to leave off unique indexes which are unlikely
2744 * to collide. However if you do this, you run the risk of encountering
2745 * errors which wouldn't have occurred in MySQL.
2747 * @param string $table The table to replace the row(s) in.
2748 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2749 * a field name or an array of field names
2750 * @param array $rows Can be either a single row to insert, or multiple rows,
2751 * in the same format as for DatabaseBase::insert()
2752 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2754 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
2755 $quotedTable = $this->tableName( $table );
2757 if ( count( $rows ) == 0 ) {
2762 if ( !is_array( reset( $rows ) ) ) {
2763 $rows = array( $rows );
2766 foreach ( $rows as $row ) {
2767 # Delete rows which collide
2768 if ( $uniqueIndexes ) {
2769 $sql = "DELETE FROM $quotedTable WHERE ";
2771 foreach ( $uniqueIndexes as $index ) {
2778 if ( is_array( $index ) ) {
2780 foreach ( $index as $col ) {
2786 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2789 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2793 $this->query( $sql, $fname );
2796 # Now insert the row
2797 $this->insert( $table, $row, $fname );
2802 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2805 * @param string $table Table name
2806 * @param array|string $rows Row(s) to insert
2807 * @param string $fname Caller function name
2809 * @return ResultWrapper
2811 protected function nativeReplace( $table, $rows, $fname ) {
2812 $table = $this->tableName( $table );
2815 if ( !is_array( reset( $rows ) ) ) {
2816 $rows = array( $rows );
2819 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2822 foreach ( $rows as $row ) {
2829 $sql .= '(' . $this->makeList( $row ) . ')';
2832 return $this->query( $sql, $fname );
2836 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2838 * This updates any conflicting rows (according to the unique indexes) using
2839 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2841 * $rows may be either:
2842 * - A single associative array. The array keys are the field names, and
2843 * the values are the values to insert. The values are treated as data
2844 * and will be quoted appropriately. If NULL is inserted, this will be
2845 * converted to a database NULL.
2846 * - An array with numeric keys, holding a list of associative arrays.
2847 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2848 * each subarray must be identical to each other, and in the same order.
2850 * It may be more efficient to leave off unique indexes which are unlikely
2851 * to collide. However if you do this, you run the risk of encountering
2852 * errors which wouldn't have occurred in MySQL.
2854 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2859 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2860 * @param array $rows A single row or list of rows to insert
2861 * @param array $uniqueIndexes List of single field names or field name tuples
2862 * @param array $set An array of values to SET. For each array element, the
2863 * key gives the field name, and the value gives the data to set that
2864 * field to. The data will be quoted by DatabaseBase::addQuotes().
2865 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2869 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2872 if ( !count( $rows ) ) {
2873 return true; // nothing to do
2876 if ( !is_array( reset( $rows ) ) ) {
2877 $rows = array( $rows );
2880 if ( count( $uniqueIndexes ) ) {
2881 $clauses = array(); // list WHERE clauses that each identify a single row
2882 foreach ( $rows as $row ) {
2883 foreach ( $uniqueIndexes as $index ) {
2884 $index = is_array( $index ) ?
$index : array( $index ); // columns
2885 $rowKey = array(); // unique key to this row
2886 foreach ( $index as $column ) {
2887 $rowKey[$column] = $row[$column];
2889 $clauses[] = $this->makeList( $rowKey, LIST_AND
);
2892 $where = array( $this->makeList( $clauses, LIST_OR
) );
2897 $useTrx = !$this->mTrxLevel
;
2899 $this->begin( $fname );
2902 # Update any existing conflicting row(s)
2903 if ( $where !== false ) {
2904 $ok = $this->update( $table, $set, $where, $fname );
2908 # Now insert any non-conflicting row(s)
2909 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2910 } catch ( Exception
$e ) {
2912 $this->rollback( $fname );
2917 $this->commit( $fname );
2924 * DELETE where the condition is a join.
2926 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2927 * we use sub-selects
2929 * For safety, an empty $conds will not delete everything. If you want to
2930 * delete all rows where the join condition matches, set $conds='*'.
2932 * DO NOT put the join condition in $conds.
2934 * @param string $delTable The table to delete from.
2935 * @param string $joinTable The other table.
2936 * @param string $delVar The variable to join on, in the first table.
2937 * @param string $joinVar The variable to join on, in the second table.
2938 * @param array $conds Condition array of field names mapped to variables,
2939 * ANDed together in the WHERE clause
2940 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2941 * @throws DBUnexpectedError
2943 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2947 throw new DBUnexpectedError( $this,
2948 'DatabaseBase::deleteJoin() called with empty $conds' );
2951 $delTable = $this->tableName( $delTable );
2952 $joinTable = $this->tableName( $joinTable );
2953 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2954 if ( $conds != '*' ) {
2955 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2959 $this->query( $sql, $fname );
2963 * Returns the size of a text field, or -1 for "unlimited"
2965 * @param string $table
2966 * @param string $field
2969 public function textFieldSize( $table, $field ) {
2970 $table = $this->tableName( $table );
2971 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2972 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2973 $row = $this->fetchObject( $res );
2977 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2987 * A string to insert into queries to show that they're low-priority, like
2988 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2989 * string and nothing bad should happen.
2991 * @return string Returns the text of the low priority option if it is
2992 * supported, or a blank string otherwise
2994 public function lowPriorityOption() {
2999 * DELETE query wrapper.
3001 * @param array $table Table name
3002 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3003 * for the format. Use $conds == "*" to delete all rows
3004 * @param string $fname Name of the calling function
3005 * @throws DBUnexpectedError
3006 * @return bool|ResultWrapper
3008 public function delete( $table, $conds, $fname = __METHOD__
) {
3010 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3013 $table = $this->tableName( $table );
3014 $sql = "DELETE FROM $table";
3016 if ( $conds != '*' ) {
3017 if ( is_array( $conds ) ) {
3018 $conds = $this->makeList( $conds, LIST_AND
);
3020 $sql .= ' WHERE ' . $conds;
3023 return $this->query( $sql, $fname );
3027 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3028 * into another table.
3030 * @param string $destTable The table name to insert into
3031 * @param string|array $srcTable May be either a table name, or an array of table names
3032 * to include in a join.
3034 * @param array $varMap Must be an associative array of the form
3035 * array( 'dest1' => 'source1', ...). Source items may be literals
3036 * rather than field names, but strings should be quoted with
3037 * DatabaseBase::addQuotes()
3039 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3040 * the details of the format of condition arrays. May be "*" to copy the
3043 * @param string $fname The function name of the caller, from __METHOD__
3045 * @param array $insertOptions Options for the INSERT part of the query, see
3046 * DatabaseBase::insert() for details.
3047 * @param array $selectOptions Options for the SELECT part of the query, see
3048 * DatabaseBase::select() for details.
3050 * @return ResultWrapper
3052 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3053 $fname = __METHOD__
,
3054 $insertOptions = array(), $selectOptions = array()
3056 $destTable = $this->tableName( $destTable );
3058 if ( !is_array( $insertOptions ) ) {
3059 $insertOptions = array( $insertOptions );
3062 $insertOptions = $this->makeInsertOptions( $insertOptions );
3064 if ( !is_array( $selectOptions ) ) {
3065 $selectOptions = array( $selectOptions );
3068 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3070 if ( is_array( $srcTable ) ) {
3071 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3073 $srcTable = $this->tableName( $srcTable );
3076 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3077 " SELECT $startOpts " . implode( ',', $varMap ) .
3078 " FROM $srcTable $useIndex ";
3080 if ( $conds != '*' ) {
3081 if ( is_array( $conds ) ) {
3082 $conds = $this->makeList( $conds, LIST_AND
);
3084 $sql .= " WHERE $conds";
3087 $sql .= " $tailOpts";
3089 return $this->query( $sql, $fname );
3093 * Construct a LIMIT query with optional offset. This is used for query
3094 * pages. The SQL should be adjusted so that only the first $limit rows
3095 * are returned. If $offset is provided as well, then the first $offset
3096 * rows should be discarded, and the next $limit rows should be returned.
3097 * If the result of the query is not ordered, then the rows to be returned
3098 * are theoretically arbitrary.
3100 * $sql is expected to be a SELECT, if that makes a difference.
3102 * The version provided by default works in MySQL and SQLite. It will very
3103 * likely need to be overridden for most other DBMSes.
3105 * @param string $sql SQL query we will append the limit too
3106 * @param int $limit The SQL limit
3107 * @param int|bool $offset The SQL offset (default false)
3108 * @throws DBUnexpectedError
3111 public function limitResult( $sql, $limit, $offset = false ) {
3112 if ( !is_numeric( $limit ) ) {
3113 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3116 return "$sql LIMIT "
3117 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
3122 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3123 * within the UNION construct.
3126 public function unionSupportsOrderAndLimit() {
3127 return true; // True for almost every DB supported
3131 * Construct a UNION query
3132 * This is used for providing overload point for other DB abstractions
3133 * not compatible with the MySQL syntax.
3134 * @param array $sqls SQL statements to combine
3135 * @param bool $all Use UNION ALL
3136 * @return string SQL fragment
3138 public function unionQueries( $sqls, $all ) {
3139 $glue = $all ?
') UNION ALL (' : ') UNION (';
3141 return '(' . implode( $glue, $sqls ) . ')';
3145 * Returns an SQL expression for a simple conditional. This doesn't need
3146 * to be overridden unless CASE isn't supported in your DBMS.
3148 * @param string|array $cond SQL expression which will result in a boolean value
3149 * @param string $trueVal SQL expression to return if true
3150 * @param string $falseVal SQL expression to return if false
3151 * @return string SQL fragment
3153 public function conditional( $cond, $trueVal, $falseVal ) {
3154 if ( is_array( $cond ) ) {
3155 $cond = $this->makeList( $cond, LIST_AND
);
3158 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3162 * Returns a comand for str_replace function in SQL query.
3163 * Uses REPLACE() in MySQL
3165 * @param string $orig Column to modify
3166 * @param string $old Column to seek
3167 * @param string $new Column to replace with
3171 public function strreplace( $orig, $old, $new ) {
3172 return "REPLACE({$orig}, {$old}, {$new})";
3176 * Determines how long the server has been up
3181 public function getServerUptime() {
3186 * Determines if the last failure was due to a deadlock
3191 public function wasDeadlock() {
3196 * Determines if the last failure was due to a lock timeout
3201 public function wasLockTimeout() {
3206 * Determines if the last query error was something that should be dealt
3207 * with by pinging the connection and reissuing the query.
3212 public function wasErrorReissuable() {
3217 * Determines if the last failure was due to the database being read-only.
3222 public function wasReadOnlyError() {
3227 * Perform a deadlock-prone transaction.
3229 * This function invokes a callback function to perform a set of write
3230 * queries. If a deadlock occurs during the processing, the transaction
3231 * will be rolled back and the callback function will be called again.
3234 * $dbw->deadlockLoop( callback, ... );
3236 * Extra arguments are passed through to the specified callback function.
3238 * Returns whatever the callback function returned on its successful,
3239 * iteration, or false on error, for example if the retry limit was
3244 public function deadlockLoop() {
3245 $this->begin( __METHOD__
);
3246 $args = func_get_args();
3247 $function = array_shift( $args );
3248 $oldIgnore = $this->ignoreErrors( true );
3249 $tries = self
::DEADLOCK_TRIES
;
3251 if ( is_array( $function ) ) {
3252 $fname = $function[0];
3258 $retVal = call_user_func_array( $function, $args );
3259 $error = $this->lastError();
3260 $errno = $this->lastErrno();
3261 $sql = $this->lastQuery();
3264 if ( $this->wasDeadlock() ) {
3266 usleep( mt_rand( self
::DEADLOCK_DELAY_MIN
, self
::DEADLOCK_DELAY_MAX
) );
3268 $this->reportQueryError( $error, $errno, $sql, $fname );
3271 } while ( $this->wasDeadlock() && --$tries > 0 );
3273 $this->ignoreErrors( $oldIgnore );
3275 if ( $tries <= 0 ) {
3276 $this->rollback( __METHOD__
);
3277 $this->reportQueryError( $error, $errno, $sql, $fname );
3281 $this->commit( __METHOD__
);
3288 * Wait for the slave to catch up to a given master position.
3290 * @param DBMasterPos $pos
3291 * @param int $timeout The maximum number of seconds to wait for
3293 * @return int Zero if the slave was past that position already,
3294 * greater than zero if we waited for some period of time, less than
3295 * zero if we timed out.
3297 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
3298 # Real waits are implemented in the subclass.
3303 * Get the replication position of this slave
3305 * @return DBMasterPos|bool False if this is not a slave.
3307 public function getSlavePos() {
3313 * Get the position of this master
3315 * @return DBMasterPos|bool False if this is not a master
3317 public function getMasterPos() {
3323 * Run an anonymous function as soon as there is no transaction pending.
3324 * If there is a transaction and it is rolled back, then the callback is cancelled.
3325 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3326 * Callbacks must commit any transactions that they begin.
3328 * This is useful for updates to different systems or when separate transactions are needed.
3329 * For example, one might want to enqueue jobs into a system outside the database, but only
3330 * after the database is updated so that the jobs will see the data when they actually run.
3331 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3333 * @param callable $callback
3336 final public function onTransactionIdle( $callback ) {
3337 $this->mTrxIdleCallbacks
[] = array( $callback, wfGetCaller() );
3338 if ( !$this->mTrxLevel
) {
3339 $this->runOnTransactionIdleCallbacks();
3344 * Run an anonymous function before the current transaction commits or now if there is none.
3345 * If there is a transaction and it is rolled back, then the callback is cancelled.
3346 * Callbacks must not start nor commit any transactions.
3348 * This is useful for updates that easily cause deadlocks if locks are held too long
3349 * but where atomicity is strongly desired for these updates and some related updates.
3351 * @param callable $callback
3354 final public function onTransactionPreCommitOrIdle( $callback ) {
3355 if ( $this->mTrxLevel
) {
3356 $this->mTrxPreCommitCallbacks
[] = array( $callback, wfGetCaller() );
3358 $this->onTransactionIdle( $callback ); // this will trigger immediately
3363 * Actually any "on transaction idle" callbacks.
3367 protected function runOnTransactionIdleCallbacks() {
3368 $autoTrx = $this->getFlag( DBO_TRX
); // automatic begin() enabled?
3370 $e = $ePrior = null; // last exception
3371 do { // callbacks may add callbacks :)
3372 $callbacks = $this->mTrxIdleCallbacks
;
3373 $this->mTrxIdleCallbacks
= array(); // recursion guard
3374 foreach ( $callbacks as $callback ) {
3376 list( $phpCallback ) = $callback;
3377 $this->clearFlag( DBO_TRX
); // make each query its own transaction
3378 call_user_func( $phpCallback );
3379 $this->setFlag( $autoTrx ? DBO_TRX
: 0 ); // restore automatic begin()
3380 } catch ( Exception
$e ) {
3382 MWExceptionHandler
::logException( $ePrior );
3387 } while ( count( $this->mTrxIdleCallbacks
) );
3389 if ( $e instanceof Exception
) {
3390 throw $e; // re-throw any last exception
3395 * Actually any "on transaction pre-commit" callbacks.
3399 protected function runOnTransactionPreCommitCallbacks() {
3400 $e = $ePrior = null; // last exception
3401 do { // callbacks may add callbacks :)
3402 $callbacks = $this->mTrxPreCommitCallbacks
;
3403 $this->mTrxPreCommitCallbacks
= array(); // recursion guard
3404 foreach ( $callbacks as $callback ) {
3406 list( $phpCallback ) = $callback;
3407 call_user_func( $phpCallback );
3408 } catch ( Exception
$e ) {
3410 MWExceptionHandler
::logException( $ePrior );
3415 } while ( count( $this->mTrxPreCommitCallbacks
) );
3417 if ( $e instanceof Exception
) {
3418 throw $e; // re-throw any last exception
3423 * Begin an atomic section of statements
3425 * If a transaction has been started already, just keep track of the given
3426 * section name to make sure the transaction is not committed pre-maturely.
3427 * This function can be used in layers (with sub-sections), so use a stack
3428 * to keep track of the different atomic sections. If there is no transaction,
3429 * start one implicitly.
3431 * The goal of this function is to create an atomic section of SQL queries
3432 * without having to start a new transaction if it already exists.
3434 * Atomic sections are more strict than transactions. With transactions,
3435 * attempting to begin a new transaction when one is already running results
3436 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3437 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3438 * and any database transactions cannot be began or committed until all atomic
3439 * levels are closed. There is no such thing as implicitly opening or closing
3440 * an atomic section.
3443 * @param string $fname
3446 final public function startAtomic( $fname = __METHOD__
) {
3447 if ( !$this->mTrxLevel
) {
3448 $this->begin( $fname );
3449 $this->mTrxAutomatic
= true;
3450 $this->mTrxAutomaticAtomic
= true;
3453 $this->mTrxAtomicLevels
->push( $fname );
3457 * Ends an atomic section of SQL statements
3459 * Ends the next section of atomic SQL statements and commits the transaction
3463 * @see DatabaseBase::startAtomic
3464 * @param string $fname
3467 final public function endAtomic( $fname = __METHOD__
) {
3468 if ( !$this->mTrxLevel
) {
3469 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3471 if ( $this->mTrxAtomicLevels
->isEmpty() ||
3472 $this->mTrxAtomicLevels
->pop() !== $fname
3474 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3477 if ( $this->mTrxAtomicLevels
->isEmpty() && $this->mTrxAutomaticAtomic
) {
3478 $this->commit( $fname, 'flush' );
3483 * Begin a transaction. If a transaction is already in progress,
3484 * that transaction will be committed before the new transaction is started.
3486 * Note that when the DBO_TRX flag is set (which is usually the case for web
3487 * requests, but not for maintenance scripts), any previous database query
3488 * will have started a transaction automatically.
3490 * Nesting of transactions is not supported. Attempts to nest transactions
3491 * will cause a warning, unless the current transaction was started
3492 * automatically because of the DBO_TRX flag.
3494 * @param string $fname
3497 final public function begin( $fname = __METHOD__
) {
3498 global $wgDebugDBTransactions;
3500 if ( $this->mTrxLevel
) { // implicit commit
3501 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3502 // If the current transaction was an automatic atomic one, then we definitely have
3503 // a problem. Same if there is any unclosed atomic level.
3504 throw new DBUnexpectedError( $this,
3505 "Attempted to start explicit transaction when atomic levels are still open."
3507 } elseif ( !$this->mTrxAutomatic
) {
3508 // We want to warn about inadvertently nested begin/commit pairs, but not about
3509 // auto-committing implicit transactions that were started by query() via DBO_TRX
3510 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3511 " performing implicit commit!";
3513 wfLogDBError( $msg );
3515 // if the transaction was automatic and has done write operations,
3516 // log it if $wgDebugDBTransactions is enabled.
3517 if ( $this->mTrxDoneWrites
&& $wgDebugDBTransactions ) {
3518 wfDebug( "$fname: Automatic transaction with writes in progress" .
3519 " (from {$this->mTrxFname}), performing implicit commit!\n"
3524 $this->runOnTransactionPreCommitCallbacks();
3525 $this->doCommit( $fname );
3526 if ( $this->mTrxDoneWrites
) {
3527 Profiler
::instance()->transactionWritingOut(
3528 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3530 $this->runOnTransactionIdleCallbacks();
3533 # Avoid fatals if close() was called
3534 if ( !$this->isOpen() ) {
3535 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3538 $this->doBegin( $fname );
3539 $this->mTrxTimestamp
= microtime( true );
3540 $this->mTrxFname
= $fname;
3541 $this->mTrxDoneWrites
= false;
3542 $this->mTrxAutomatic
= false;
3543 $this->mTrxAutomaticAtomic
= false;
3544 $this->mTrxAtomicLevels
= new SplStack
;
3545 $this->mTrxIdleCallbacks
= array();
3546 $this->mTrxPreCommitCallbacks
= array();
3547 $this->mTrxShortId
= wfRandomString( 12 );
3551 * Issues the BEGIN command to the database server.
3553 * @see DatabaseBase::begin()
3554 * @param string $fname
3556 protected function doBegin( $fname ) {
3557 $this->query( 'BEGIN', $fname );
3558 $this->mTrxLevel
= 1;
3562 * Commits a transaction previously started using begin().
3563 * If no transaction is in progress, a warning is issued.
3565 * Nesting of transactions is not supported.
3567 * @param string $fname
3568 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3569 * explicitly committing implicit transactions, or calling commit when no
3570 * transaction is in progress. This will silently break any ongoing
3571 * explicit transaction. Only set the flush flag if you are sure that it
3572 * is safe to ignore these warnings in your context.
3573 * @throws DBUnexpectedError
3575 final public function commit( $fname = __METHOD__
, $flush = '' ) {
3576 if ( !$this->mTrxAtomicLevels
->isEmpty() ) {
3577 // There are still atomic sections open. This cannot be ignored
3578 throw new DBUnexpectedError(
3580 "Attempted to commit transaction while atomic sections are still open"
3584 if ( $flush === 'flush' ) {
3585 if ( !$this->mTrxLevel
) {
3586 return; // nothing to do
3587 } elseif ( !$this->mTrxAutomatic
) {
3588 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3591 if ( !$this->mTrxLevel
) {
3592 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3593 return; // nothing to do
3594 } elseif ( $this->mTrxAutomatic
) {
3595 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3599 # Avoid fatals if close() was called
3600 if ( !$this->isOpen() ) {
3601 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3604 $this->runOnTransactionPreCommitCallbacks();
3605 $this->doCommit( $fname );
3606 if ( $this->mTrxDoneWrites
) {
3607 Profiler
::instance()->transactionWritingOut(
3608 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3610 $this->runOnTransactionIdleCallbacks();
3614 * Issues the COMMIT command to the database server.
3616 * @see DatabaseBase::commit()
3617 * @param string $fname
3619 protected function doCommit( $fname ) {
3620 if ( $this->mTrxLevel
) {
3621 $this->query( 'COMMIT', $fname );
3622 $this->mTrxLevel
= 0;
3627 * Rollback a transaction previously started using begin().
3628 * If no transaction is in progress, a warning is issued.
3630 * No-op on non-transactional databases.
3632 * @param string $fname
3633 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3634 * calling rollback when no transaction is in progress. This will silently
3635 * break any ongoing explicit transaction. Only set the flush flag if you
3636 * are sure that it is safe to ignore these warnings in your context.
3637 * @since 1.23 Added $flush parameter
3639 final public function rollback( $fname = __METHOD__
, $flush = '' ) {
3640 if ( $flush !== 'flush' ) {
3641 if ( !$this->mTrxLevel
) {
3642 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3643 return; // nothing to do
3644 } elseif ( $this->mTrxAutomatic
) {
3645 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3648 if ( !$this->mTrxLevel
) {
3649 return; // nothing to do
3650 } elseif ( !$this->mTrxAutomatic
) {
3651 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3655 # Avoid fatals if close() was called
3656 if ( !$this->isOpen() ) {
3657 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3660 $this->doRollback( $fname );
3661 $this->mTrxIdleCallbacks
= array(); // cancel
3662 $this->mTrxPreCommitCallbacks
= array(); // cancel
3663 $this->mTrxAtomicLevels
= new SplStack
;
3664 if ( $this->mTrxDoneWrites
) {
3665 Profiler
::instance()->transactionWritingOut(
3666 $this->mServer
, $this->mDBname
, $this->mTrxShortId
);
3671 * Issues the ROLLBACK command to the database server.
3673 * @see DatabaseBase::rollback()
3674 * @param string $fname
3676 protected function doRollback( $fname ) {
3677 if ( $this->mTrxLevel
) {
3678 $this->query( 'ROLLBACK', $fname, true );
3679 $this->mTrxLevel
= 0;
3684 * Creates a new table with structure copied from existing table
3685 * Note that unlike most database abstraction functions, this function does not
3686 * automatically append database prefix, because it works at a lower
3687 * abstraction level.
3688 * The table names passed to this function shall not be quoted (this
3689 * function calls addIdentifierQuotes when needed).
3691 * @param string $oldName Name of table whose structure should be copied
3692 * @param string $newName Name of table to be created
3693 * @param bool $temporary Whether the new table should be temporary
3694 * @param string $fname Calling function name
3695 * @throws MWException
3696 * @return bool True if operation was successful
3698 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3701 throw new MWException(
3702 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3706 * List all tables on the database
3708 * @param string $prefix Only show tables with this prefix, e.g. mw_
3709 * @param string $fname Calling function name
3710 * @throws MWException
3712 function listTables( $prefix = null, $fname = __METHOD__
) {
3713 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3717 * Reset the views process cache set by listViews()
3720 final public function clearViewsCache() {
3721 $this->allViews
= null;
3725 * Lists all the VIEWs in the database
3727 * For caching purposes the list of all views should be stored in
3728 * $this->allViews. The process cache can be cleared with clearViewsCache()
3730 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3731 * @param string $fname Name of calling function
3732 * @throws MWException
3735 public function listViews( $prefix = null, $fname = __METHOD__
) {
3736 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3740 * Differentiates between a TABLE and a VIEW
3742 * @param string $name Name of the database-structure to test.
3743 * @throws MWException
3746 public function isView( $name ) {
3747 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3751 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3752 * to the format used for inserting into timestamp fields in this DBMS.
3754 * The result is unquoted, and needs to be passed through addQuotes()
3755 * before it can be included in raw SQL.
3757 * @param string|int $ts
3761 public function timestamp( $ts = 0 ) {
3762 return wfTimestamp( TS_MW
, $ts );
3766 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3767 * to the format used for inserting into timestamp fields in this DBMS. If
3768 * NULL is input, it is passed through, allowing NULL values to be inserted
3769 * into timestamp fields.
3771 * The result is unquoted, and needs to be passed through addQuotes()
3772 * before it can be included in raw SQL.
3774 * @param string|int $ts
3778 public function timestampOrNull( $ts = null ) {
3779 if ( is_null( $ts ) ) {
3782 return $this->timestamp( $ts );
3787 * Take the result from a query, and wrap it in a ResultWrapper if
3788 * necessary. Boolean values are passed through as is, to indicate success
3789 * of write queries or failure.
3791 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3792 * resource, and it was necessary to call this function to convert it to
3793 * a wrapper. Nowadays, raw database objects are never exposed to external
3794 * callers, so this is unnecessary in external code. For compatibility with
3795 * old code, ResultWrapper objects are passed through unaltered.
3797 * @param bool|ResultWrapper|resource $result
3798 * @return bool|ResultWrapper
3800 public function resultObject( $result ) {
3801 if ( empty( $result ) ) {
3803 } elseif ( $result instanceof ResultWrapper
) {
3805 } elseif ( $result === true ) {
3806 // Successful write query
3809 return new ResultWrapper( $this, $result );
3814 * Ping the server and try to reconnect if it there is no connection
3816 * @return bool Success or failure
3818 public function ping() {
3819 # Stub. Not essential to override.
3824 * Get slave lag. Currently supported only by MySQL.
3826 * Note that this function will generate a fatal error on many
3827 * installations. Most callers should use LoadBalancer::safeGetLag()
3830 * @return int Database replication lag in seconds
3832 public function getLag() {
3837 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3841 function maxListLen() {
3846 * Some DBMSs have a special format for inserting into blob fields, they
3847 * don't allow simple quoted strings to be inserted. To insert into such
3848 * a field, pass the data through this function before passing it to
3849 * DatabaseBase::insert().
3854 public function encodeBlob( $b ) {
3859 * Some DBMSs return a special placeholder object representing blob fields
3860 * in result objects. Pass the object through this function to return the
3866 public function decodeBlob( $b ) {
3871 * Override database's default behavior. $options include:
3872 * 'connTimeout' : Set the connection timeout value in seconds.
3873 * May be useful for very long batch queries such as
3874 * full-wiki dumps, where a single query reads out over
3877 * @param array $options
3880 public function setSessionOptions( array $options ) {
3884 * Read and execute SQL commands from a file.
3886 * Returns true on success, error string or exception on failure (depending
3887 * on object's error ignore settings).
3889 * @param string $filename File name to open
3890 * @param bool|callable $lineCallback Optional function called before reading each line
3891 * @param bool|callable $resultCallback Optional function called for each MySQL result
3892 * @param bool|string $fname Calling function name or false if name should be
3893 * generated dynamically using $filename
3894 * @param bool|callable $inputCallback Optional function called for each
3895 * complete line sent
3896 * @throws Exception|MWException
3897 * @return bool|string
3899 public function sourceFile(
3900 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3902 wfSuppressWarnings();
3903 $fp = fopen( $filename, 'r' );
3904 wfRestoreWarnings();
3906 if ( false === $fp ) {
3907 throw new MWException( "Could not open \"{$filename}\".\n" );
3911 $fname = __METHOD__
. "( $filename )";
3915 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3916 } catch ( MWException
$e ) {
3927 * Get the full path of a patch file. Originally based on archive()
3928 * from updaters.inc. Keep in mind this always returns a patch, as
3929 * it fails back to MySQL if no DB-specific patch can be found
3931 * @param string $patch The name of the patch, like patch-something.sql
3932 * @return string Full path to patch file
3934 public function patchPath( $patch ) {
3937 $dbType = $this->getType();
3938 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3939 return "$IP/maintenance/$dbType/archives/$patch";
3941 return "$IP/maintenance/archives/$patch";
3946 * Set variables to be used in sourceFile/sourceStream, in preference to the
3947 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3948 * all. If it's set to false, $GLOBALS will be used.
3950 * @param bool|array $vars Mapping variable name to value.
3952 public function setSchemaVars( $vars ) {
3953 $this->mSchemaVars
= $vars;
3957 * Read and execute commands from an open file handle.
3959 * Returns true on success, error string or exception on failure (depending
3960 * on object's error ignore settings).
3962 * @param resource $fp File handle
3963 * @param bool|callable $lineCallback Optional function called before reading each query
3964 * @param bool|callable $resultCallback Optional function called for each MySQL result
3965 * @param string $fname Calling function name
3966 * @param bool|callable $inputCallback Optional function called for each complete query sent
3967 * @return bool|string
3969 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3970 $fname = __METHOD__
, $inputCallback = false
3974 while ( !feof( $fp ) ) {
3975 if ( $lineCallback ) {
3976 call_user_func( $lineCallback );
3979 $line = trim( fgets( $fp ) );
3981 if ( $line == '' ) {
3985 if ( '-' == $line[0] && '-' == $line[1] ) {
3993 $done = $this->streamStatementEnd( $cmd, $line );
3997 if ( $done ||
feof( $fp ) ) {
3998 $cmd = $this->replaceVars( $cmd );
4000 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) ||
!$inputCallback ) {
4001 $res = $this->query( $cmd, $fname );
4003 if ( $resultCallback ) {
4004 call_user_func( $resultCallback, $res, $this );
4007 if ( false === $res ) {
4008 $err = $this->lastError();
4010 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4021 * Called by sourceStream() to check if we've reached a statement end
4023 * @param string $sql SQL assembled so far
4024 * @param string $newLine New line about to be added to $sql
4025 * @return bool Whether $newLine contains end of the statement
4027 public function streamStatementEnd( &$sql, &$newLine ) {
4028 if ( $this->delimiter
) {
4030 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
4031 if ( $newLine != $prev ) {
4040 * Database independent variable replacement. Replaces a set of variables
4041 * in an SQL statement with their contents as given by $this->getSchemaVars().
4043 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4045 * - '{$var}' should be used for text and is passed through the database's
4047 * - `{$var}` should be used for identifiers (eg: table and database names),
4048 * it is passed through the database's addIdentifierQuotes method which
4049 * can be overridden if the database uses something other than backticks.
4050 * - / *$var* / is just encoded, besides traditional table prefix and
4051 * table options its use should be avoided.
4053 * @param string $ins SQL statement to replace variables in
4054 * @return string The new SQL statement with variables replaced
4056 protected function replaceSchemaVars( $ins ) {
4057 $vars = $this->getSchemaVars();
4058 foreach ( $vars as $var => $value ) {
4060 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
4062 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
4064 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ), $ins );
4071 * Replace variables in sourced SQL
4073 * @param string $ins
4076 protected function replaceVars( $ins ) {
4077 $ins = $this->replaceSchemaVars( $ins );
4080 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
4081 array( $this, 'tableNameCallback' ), $ins );
4084 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
4085 array( $this, 'indexNameCallback' ), $ins );
4091 * Get schema variables. If none have been set via setSchemaVars(), then
4092 * use some defaults from the current object.
4096 protected function getSchemaVars() {
4097 if ( $this->mSchemaVars
) {
4098 return $this->mSchemaVars
;
4100 return $this->getDefaultSchemaVars();
4105 * Get schema variables to use if none have been set via setSchemaVars().
4107 * Override this in derived classes to provide variables for tables.sql
4108 * and SQL patch files.
4112 protected function getDefaultSchemaVars() {
4117 * Table name callback
4119 * @param array $matches
4122 protected function tableNameCallback( $matches ) {
4123 return $this->tableName( $matches[1] );
4127 * Index name callback
4129 * @param array $matches
4132 protected function indexNameCallback( $matches ) {
4133 return $this->indexName( $matches[1] );
4137 * Check to see if a named lock is available. This is non-blocking.
4139 * @param string $lockName Name of lock to poll
4140 * @param string $method Name of method calling us
4144 public function lockIsFree( $lockName, $method ) {
4149 * Acquire a named lock
4151 * Abstracted from Filestore::lock() so child classes can implement for
4154 * @param string $lockName Name of lock to aquire
4155 * @param string $method Name of method calling us
4156 * @param int $timeout
4159 public function lock( $lockName, $method, $timeout = 5 ) {
4166 * @param string $lockName Name of lock to release
4167 * @param string $method Name of method calling us
4169 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4170 * by this thread (in which case the lock is not released), and NULL if the named
4171 * lock did not exist
4173 public function unlock( $lockName, $method ) {
4178 * Lock specific tables
4180 * @param array $read Array of tables to lock for read access
4181 * @param array $write Array of tables to lock for write access
4182 * @param string $method Name of caller
4183 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4186 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4191 * Unlock specific tables
4193 * @param string $method The caller
4196 public function unlockTables( $method ) {
4202 * @param string $tableName
4203 * @param string $fName
4204 * @return bool|ResultWrapper
4207 public function dropTable( $tableName, $fName = __METHOD__
) {
4208 if ( !$this->tableExists( $tableName, $fName ) ) {
4211 $sql = "DROP TABLE " . $this->tableName( $tableName );
4212 if ( $this->cascadingDeletes() ) {
4216 return $this->query( $sql, $fName );
4220 * Get search engine class. All subclasses of this need to implement this
4221 * if they wish to use searching.
4225 public function getSearchEngine() {
4226 return 'SearchEngineDummy';
4230 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4231 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4232 * because "i" sorts after all numbers.
4236 public function getInfinity() {
4241 * Encode an expiry time into the DBMS dependent format
4243 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4246 public function encodeExpiry( $expiry ) {
4247 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
4248 ?
$this->getInfinity()
4249 : $this->timestamp( $expiry );
4253 * Decode an expiry time into a DBMS independent format
4255 * @param string $expiry DB timestamp field value for expiry
4256 * @param int $format TS_* constant, defaults to TS_MW
4259 public function decodeExpiry( $expiry, $format = TS_MW
) {
4260 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
4262 : wfTimestamp( $format, $expiry );
4266 * Allow or deny "big selects" for this session only. This is done by setting
4267 * the sql_big_selects session variable.
4269 * This is a MySQL-specific feature.
4271 * @param bool|string $value True for allow, false for deny, or "default" to
4272 * restore the initial value
4274 public function setBigSelects( $value = true ) {
4282 public function __toString() {
4283 return (string)$this->mConn
;
4287 * Run a few simple sanity checks
4289 public function __destruct() {
4290 if ( $this->mTrxLevel
&& $this->mTrxDoneWrites
) {
4291 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4293 if ( count( $this->mTrxIdleCallbacks
) ||
count( $this->mTrxPreCommitCallbacks
) ) {
4295 foreach ( $this->mTrxIdleCallbacks
as $callbackInfo ) {
4296 $callers[] = $callbackInfo[1];
4298 $callers = implode( ', ', $callers );
4299 trigger_error( "DB transaction callbacks still pending (from $callers)." );