Merge "resourceloader: Fix RLQ script to support IE8 quirk"
[mediawiki.git] / includes / db / Database.php
blob2ee45451d3d2efafb4b6ddbc2d1e4becb864dcb4
1 <?php
3 /**
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
24 * @file
25 * @ingroup Database
28 /**
29 * Database abstraction object
30 * @ingroup Database
32 abstract class DatabaseBase implements IDatabase {
33 /** Number of times to re-try an operation in case of deadlock */
34 const DEADLOCK_TRIES = 4;
36 /** Minimum time to wait before retry, in microseconds */
37 const DEADLOCK_DELAY_MIN = 500000;
39 /** Maximum time to wait before retry */
40 const DEADLOCK_DELAY_MAX = 1500000;
42 protected $mLastQuery = '';
43 protected $mDoneWrites = false;
44 protected $mPHPError = false;
46 protected $mServer, $mUser, $mPassword, $mDBname;
48 /** @var resource Database connection */
49 protected $mConn = null;
50 protected $mOpened = false;
52 /** @var callable[] */
53 protected $mTrxIdleCallbacks = array();
54 /** @var callable[] */
55 protected $mTrxPreCommitCallbacks = array();
57 protected $mTablePrefix;
58 protected $mSchema;
59 protected $mFlags;
60 protected $mForeign;
61 protected $mErrorCount = 0;
62 protected $mLBInfo = array();
63 protected $mDefaultBigSelects = null;
64 protected $mSchemaVars = false;
65 /** @var array */
66 protected $mSessionVars = array();
68 protected $preparedArgs;
70 protected $htmlErrors;
72 protected $delimiter = ';';
74 /**
75 * Either 1 if a transaction is active or 0 otherwise.
76 * The other Trx fields may not be meaningfull if this is 0.
78 * @var int
80 protected $mTrxLevel = 0;
82 /**
83 * Either a short hexidecimal string if a transaction is active or ""
85 * @var string
86 * @see DatabaseBase::mTrxLevel
88 protected $mTrxShortId = '';
90 /**
91 * The UNIX time that the transaction started. Callers can assume that if
92 * snapshot isolation is used, then the data is *at least* up to date to that
93 * point (possibly more up-to-date since the first SELECT defines the snapshot).
95 * @var float|null
96 * @see DatabaseBase::mTrxLevel
98 private $mTrxTimestamp = null;
101 * Remembers the function name given for starting the most recent transaction via begin().
102 * Used to provide additional context for error reporting.
104 * @var string
105 * @see DatabaseBase::mTrxLevel
107 private $mTrxFname = null;
110 * Record if possible write queries were done in the last transaction started
112 * @var bool
113 * @see DatabaseBase::mTrxLevel
115 private $mTrxDoneWrites = false;
118 * Record if the current transaction was started implicitly due to DBO_TRX being set.
120 * @var bool
121 * @see DatabaseBase::mTrxLevel
123 private $mTrxAutomatic = false;
126 * Array of levels of atomicity within transactions
128 * @var SplStack
130 private $mTrxAtomicLevels;
133 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
135 * @var bool
137 private $mTrxAutomaticAtomic = false;
140 * Track the seconds spent in write queries for the current transaction
142 * @var float
144 private $mTrxWriteDuration = 0.0;
147 * @since 1.21
148 * @var resource File handle for upgrade
150 protected $fileHandle = null;
153 * @since 1.22
154 * @var string[] Process cache of VIEWs names in the database
156 protected $allViews = null;
158 /** @var TransactionProfiler */
159 protected $trxProfiler;
162 * A string describing the current software version, and possibly
163 * other details in a user-friendly way. Will be listed on Special:Version, etc.
164 * Use getServerVersion() to get machine-friendly information.
166 * @return string Version information from the database server
168 public function getServerInfo() {
169 return $this->getServerVersion();
173 * @return string Command delimiter used by this database engine
175 public function getDelimiter() {
176 return $this->delimiter;
180 * Boolean, controls output of large amounts of debug information.
181 * @param bool|null $debug
182 * - true to enable debugging
183 * - false to disable debugging
184 * - omitted or null to do nothing
186 * @return bool|null Previous value of the flag
188 public function debug( $debug = null ) {
189 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
193 * Turns buffering of SQL result sets on (true) or off (false). Default is
194 * "on".
196 * Unbuffered queries are very troublesome in MySQL:
198 * - If another query is executed while the first query is being read
199 * out, the first query is killed. This means you can't call normal
200 * MediaWiki functions while you are reading an unbuffered query result
201 * from a normal wfGetDB() connection.
203 * - Unbuffered queries cause the MySQL server to use large amounts of
204 * memory and to hold broad locks which block other queries.
206 * If you want to limit client-side memory, it's almost always better to
207 * split up queries into batches using a LIMIT clause than to switch off
208 * buffering.
210 * @param null|bool $buffer
211 * @return null|bool The previous value of the flag
213 public function bufferResults( $buffer = null ) {
214 if ( is_null( $buffer ) ) {
215 return !(bool)( $this->mFlags & DBO_NOBUFFER );
216 } else {
217 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
222 * Turns on (false) or off (true) the automatic generation and sending
223 * of a "we're sorry, but there has been a database error" page on
224 * database errors. Default is on (false). When turned off, the
225 * code should use lastErrno() and lastError() to handle the
226 * situation as appropriate.
228 * Do not use this function outside of the Database classes.
230 * @param null|bool $ignoreErrors
231 * @return bool The previous value of the flag.
233 protected function ignoreErrors( $ignoreErrors = null ) {
234 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
238 * Gets the current transaction level.
240 * Historically, transactions were allowed to be "nested". This is no
241 * longer supported, so this function really only returns a boolean.
243 * @return int The previous value
245 public function trxLevel() {
246 return $this->mTrxLevel;
250 * Get the UNIX timestamp of the time that the transaction was established
252 * This can be used to reason about the staleness of SELECT data
253 * in REPEATABLE-READ transaction isolation level.
255 * @return float|null Returns null if there is not active transaction
256 * @since 1.25
258 public function trxTimestamp() {
259 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
263 * Get/set the number of errors logged. Only useful when errors are ignored
264 * @param int $count The count to set, or omitted to leave it unchanged.
265 * @return int The error count
267 public function errorCount( $count = null ) {
268 return wfSetVar( $this->mErrorCount, $count );
272 * Get/set the table prefix.
273 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
274 * @return string The previous table prefix.
276 public function tablePrefix( $prefix = null ) {
277 return wfSetVar( $this->mTablePrefix, $prefix );
281 * Get/set the db schema.
282 * @param string $schema The database schema to set, or omitted to leave it unchanged.
283 * @return string The previous db schema.
285 public function dbSchema( $schema = null ) {
286 return wfSetVar( $this->mSchema, $schema );
290 * Set the filehandle to copy write statements to.
292 * @param resource $fh File handle
294 public function setFileHandle( $fh ) {
295 $this->fileHandle = $fh;
299 * Get properties passed down from the server info array of the load
300 * balancer.
302 * @param string $name The entry of the info array to get, or null to get the
303 * whole array
305 * @return array|mixed|null
307 public function getLBInfo( $name = null ) {
308 if ( is_null( $name ) ) {
309 return $this->mLBInfo;
310 } else {
311 if ( array_key_exists( $name, $this->mLBInfo ) ) {
312 return $this->mLBInfo[$name];
313 } else {
314 return null;
320 * Set the LB info array, or a member of it. If called with one parameter,
321 * the LB info array is set to that parameter. If it is called with two
322 * parameters, the member with the given name is set to the given value.
324 * @param string $name
325 * @param array $value
327 public function setLBInfo( $name, $value = null ) {
328 if ( is_null( $value ) ) {
329 $this->mLBInfo = $name;
330 } else {
331 $this->mLBInfo[$name] = $value;
336 * Set lag time in seconds for a fake slave
338 * @param mixed $lag Valid values for this parameter are determined by the
339 * subclass, but should be a PHP scalar or array that would be sensible
340 * as part of $wgLBFactoryConf.
342 public function setFakeSlaveLag( $lag ) {
346 * Make this connection a fake master
348 * @param bool $enabled
350 public function setFakeMaster( $enabled = true ) {
354 * @return TransactionProfiler
356 protected function getTransactionProfiler() {
357 return $this->trxProfiler
358 ? $this->trxProfiler
359 : Profiler::instance()->getTransactionProfiler();
363 * Returns true if this database supports (and uses) cascading deletes
365 * @return bool
367 public function cascadingDeletes() {
368 return false;
372 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
374 * @return bool
376 public function cleanupTriggers() {
377 return false;
381 * Returns true if this database is strict about what can be put into an IP field.
382 * Specifically, it uses a NULL value instead of an empty string.
384 * @return bool
386 public function strictIPs() {
387 return false;
391 * Returns true if this database uses timestamps rather than integers
393 * @return bool
395 public function realTimestamps() {
396 return false;
400 * Returns true if this database does an implicit sort when doing GROUP BY
402 * @return bool
404 public function implicitGroupby() {
405 return true;
409 * Returns true if this database does an implicit order by when the column has an index
410 * For example: SELECT page_title FROM page LIMIT 1
412 * @return bool
414 public function implicitOrderby() {
415 return true;
419 * Returns true if this database can do a native search on IP columns
420 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
422 * @return bool
424 public function searchableIPs() {
425 return false;
429 * Returns true if this database can use functional indexes
431 * @return bool
433 public function functionalIndexes() {
434 return false;
438 * Return the last query that went through DatabaseBase::query()
439 * @return string
441 public function lastQuery() {
442 return $this->mLastQuery;
446 * Returns true if the connection may have been used for write queries.
447 * Should return true if unsure.
449 * @return bool
451 public function doneWrites() {
452 return (bool)$this->mDoneWrites;
456 * Returns the last time the connection may have been used for write queries.
457 * Should return a timestamp if unsure.
459 * @return int|float UNIX timestamp or false
460 * @since 1.24
462 public function lastDoneWrites() {
463 return $this->mDoneWrites ?: false;
467 * Returns true if there is a transaction open with possible write
468 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
470 * @return bool
472 public function writesOrCallbacksPending() {
473 return $this->mTrxLevel && (
474 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
479 * Get the time spend running write queries for this
481 * High times could be due to scanning, updates, locking, and such
483 * @return float|bool Returns false if not transaction is active
484 * @since 1.26
486 public function pendingWriteQueryDuration() {
487 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
491 * Is a connection to the database open?
492 * @return bool
494 public function isOpen() {
495 return $this->mOpened;
499 * Set a flag for this connection
501 * @param int $flag DBO_* constants from Defines.php:
502 * - DBO_DEBUG: output some debug info (same as debug())
503 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
504 * - DBO_TRX: automatically start transactions
505 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
506 * and removes it in command line mode
507 * - DBO_PERSISTENT: use persistant database connection
509 public function setFlag( $flag ) {
510 global $wgDebugDBTransactions;
511 $this->mFlags |= $flag;
512 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
513 wfDebug( "Implicit transactions are now enabled.\n" );
518 * Clear a flag for this connection
520 * @param int $flag DBO_* constants from Defines.php:
521 * - DBO_DEBUG: output some debug info (same as debug())
522 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
523 * - DBO_TRX: automatically start transactions
524 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
525 * and removes it in command line mode
526 * - DBO_PERSISTENT: use persistant database connection
528 public function clearFlag( $flag ) {
529 global $wgDebugDBTransactions;
530 $this->mFlags &= ~$flag;
531 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
532 wfDebug( "Implicit transactions are now disabled.\n" );
537 * Returns a boolean whether the flag $flag is set for this connection
539 * @param int $flag DBO_* constants from Defines.php:
540 * - DBO_DEBUG: output some debug info (same as debug())
541 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
542 * - DBO_TRX: automatically start transactions
543 * - DBO_PERSISTENT: use persistant database connection
544 * @return bool
546 public function getFlag( $flag ) {
547 return !!( $this->mFlags & $flag );
551 * General read-only accessor
553 * @param string $name
554 * @return string
556 public function getProperty( $name ) {
557 return $this->$name;
561 * @return string
563 public function getWikiID() {
564 if ( $this->mTablePrefix ) {
565 return "{$this->mDBname}-{$this->mTablePrefix}";
566 } else {
567 return $this->mDBname;
572 * Return a path to the DBMS-specific SQL file if it exists,
573 * otherwise default SQL file
575 * @param string $filename
576 * @return string
578 private function getSqlFilePath( $filename ) {
579 global $IP;
580 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
581 if ( file_exists( $dbmsSpecificFilePath ) ) {
582 return $dbmsSpecificFilePath;
583 } else {
584 return "$IP/maintenance/$filename";
589 * Return a path to the DBMS-specific schema file,
590 * otherwise default to tables.sql
592 * @return string
594 public function getSchemaPath() {
595 return $this->getSqlFilePath( 'tables.sql' );
599 * Return a path to the DBMS-specific update key file,
600 * otherwise default to update-keys.sql
602 * @return string
604 public function getUpdateKeysPath() {
605 return $this->getSqlFilePath( 'update-keys.sql' );
609 * Get information about an index into an object
610 * @param string $table Table name
611 * @param string $index Index name
612 * @param string $fname Calling function name
613 * @return mixed Database-specific index description class or false if the index does not exist
615 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
618 * Wrapper for addslashes()
620 * @param string $s String to be slashed.
621 * @return string Slashed string.
623 abstract function strencode( $s );
626 * Constructor.
628 * FIXME: It is possible to construct a Database object with no associated
629 * connection object, by specifying no parameters to __construct(). This
630 * feature is deprecated and should be removed.
632 * DatabaseBase subclasses should not be constructed directly in external
633 * code. DatabaseBase::factory() should be used instead.
635 * @param array $params Parameters passed from DatabaseBase::factory()
637 function __construct( array $params ) {
638 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
640 $this->mTrxAtomicLevels = new SplStack;
642 $server = $params['host'];
643 $user = $params['user'];
644 $password = $params['password'];
645 $dbName = $params['dbname'];
646 $flags = $params['flags'];
647 $tablePrefix = $params['tablePrefix'];
648 $schema = $params['schema'];
649 $foreign = $params['foreign'];
651 $this->mFlags = $flags;
652 if ( $this->mFlags & DBO_DEFAULT ) {
653 if ( $wgCommandLineMode ) {
654 $this->mFlags &= ~DBO_TRX;
655 if ( $wgDebugDBTransactions ) {
656 wfDebug( "Implicit transaction open disabled.\n" );
658 } else {
659 $this->mFlags |= DBO_TRX;
660 if ( $wgDebugDBTransactions ) {
661 wfDebug( "Implicit transaction open enabled.\n" );
666 $this->mSessionVars = $params['variables'];
668 /** Get the default table prefix*/
669 if ( $tablePrefix === 'get from global' ) {
670 $this->mTablePrefix = $wgDBprefix;
671 } else {
672 $this->mTablePrefix = $tablePrefix;
675 /** Get the database schema*/
676 if ( $schema === 'get from global' ) {
677 $this->mSchema = $wgDBmwschema;
678 } else {
679 $this->mSchema = $schema;
682 $this->mForeign = $foreign;
684 if ( isset( $params['trxProfiler'] ) ) {
685 $this->trxProfiler = $params['trxProfiler']; // override
688 if ( $user ) {
689 $this->open( $server, $user, $password, $dbName );
694 * Called by serialize. Throw an exception when DB connection is serialized.
695 * This causes problems on some database engines because the connection is
696 * not restored on unserialize.
698 public function __sleep() {
699 throw new MWException( 'Database serialization may cause problems, since ' .
700 'the connection is not restored on wakeup.' );
704 * Given a DB type, construct the name of the appropriate child class of
705 * DatabaseBase. This is designed to replace all of the manual stuff like:
706 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
707 * as well as validate against the canonical list of DB types we have
709 * This factory function is mostly useful for when you need to connect to a
710 * database other than the MediaWiki default (such as for external auth,
711 * an extension, et cetera). Do not use this to connect to the MediaWiki
712 * database. Example uses in core:
713 * @see LoadBalancer::reallyOpenConnection()
714 * @see ForeignDBRepo::getMasterDB()
715 * @see WebInstallerDBConnect::execute()
717 * @since 1.18
719 * @param string $dbType A possible DB type
720 * @param array $p An array of options to pass to the constructor.
721 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
722 * @throws MWException If the database driver or extension cannot be found
723 * @return DatabaseBase|null DatabaseBase subclass or null
725 final public static function factory( $dbType, $p = array() ) {
726 $canonicalDBTypes = array(
727 'mysql' => array( 'mysqli', 'mysql' ),
728 'postgres' => array(),
729 'sqlite' => array(),
730 'oracle' => array(),
731 'mssql' => array(),
734 $driver = false;
735 $dbType = strtolower( $dbType );
736 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
737 $possibleDrivers = $canonicalDBTypes[$dbType];
738 if ( !empty( $p['driver'] ) ) {
739 if ( in_array( $p['driver'], $possibleDrivers ) ) {
740 $driver = $p['driver'];
741 } else {
742 throw new MWException( __METHOD__ .
743 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
745 } else {
746 foreach ( $possibleDrivers as $posDriver ) {
747 if ( extension_loaded( $posDriver ) ) {
748 $driver = $posDriver;
749 break;
753 } else {
754 $driver = $dbType;
756 if ( $driver === false ) {
757 throw new MWException( __METHOD__ .
758 " no viable database extension found for type '$dbType'" );
761 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
762 // and everything else doesn't use a schema (e.g. null)
763 // Although postgres and oracle support schemas, we don't use them (yet)
764 // to maintain backwards compatibility
765 $defaultSchemas = array(
766 'mssql' => 'get from global',
769 $class = 'Database' . ucfirst( $driver );
770 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
771 // Resolve some defaults for b/c
772 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
773 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
774 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
775 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
776 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
777 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
778 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
779 if ( !isset( $p['schema'] ) ) {
780 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
782 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
784 return new $class( $p );
785 } else {
786 return null;
790 protected function installErrorHandler() {
791 $this->mPHPError = false;
792 $this->htmlErrors = ini_set( 'html_errors', '0' );
793 set_error_handler( array( $this, 'connectionErrorHandler' ) );
797 * @return bool|string
799 protected function restoreErrorHandler() {
800 restore_error_handler();
801 if ( $this->htmlErrors !== false ) {
802 ini_set( 'html_errors', $this->htmlErrors );
804 if ( $this->mPHPError ) {
805 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
806 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
808 return $error;
809 } else {
810 return false;
815 * @param int $errno
816 * @param string $errstr
818 public function connectionErrorHandler( $errno, $errstr ) {
819 $this->mPHPError = $errstr;
823 * Create a log context to pass to wfLogDBError or other logging functions.
825 * @param array $extras Additional data to add to context
826 * @return array
828 protected function getLogContext( array $extras = array() ) {
829 return array_merge(
830 array(
831 'db_server' => $this->mServer,
832 'db_name' => $this->mDBname,
833 'db_user' => $this->mUser,
835 $extras
840 * Closes a database connection.
841 * if it is open : commits any open transactions
843 * @throws MWException
844 * @return bool Operation success. true if already closed.
846 public function close() {
847 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
848 throw new MWException( "Transaction idle callbacks still pending." );
850 if ( $this->mConn ) {
851 if ( $this->trxLevel() ) {
852 if ( !$this->mTrxAutomatic ) {
853 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
854 " performing implicit commit before closing connection!" );
857 $this->commit( __METHOD__, 'flush' );
860 $closed = $this->closeConnection();
861 $this->mConn = false;
862 } else {
863 $closed = true;
865 $this->mOpened = false;
867 return $closed;
871 * Make sure isOpen() returns true as a sanity check
873 * @throws DBUnexpectedError
875 protected function assertOpen() {
876 if ( !$this->isOpen() ) {
877 throw new DBUnexpectedError( $this, "DB connection was already closed." );
882 * Closes underlying database connection
883 * @since 1.20
884 * @return bool Whether connection was closed successfully
886 abstract protected function closeConnection();
889 * @param string $error Fallback error message, used if none is given by DB
890 * @throws DBConnectionError
892 function reportConnectionError( $error = 'Unknown error' ) {
893 $myError = $this->lastError();
894 if ( $myError ) {
895 $error = $myError;
898 # New method
899 throw new DBConnectionError( $this, $error );
903 * The DBMS-dependent part of query()
905 * @param string $sql SQL query.
906 * @return ResultWrapper|bool Result object to feed to fetchObject,
907 * fetchRow, ...; or false on failure
909 abstract protected function doQuery( $sql );
912 * Determine whether a query writes to the DB.
913 * Should return true if unsure.
915 * @param string $sql
916 * @return bool
918 protected function isWriteQuery( $sql ) {
919 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
923 * Determine whether a SQL statement is sensitive to isolation level.
924 * A SQL statement is considered transactable if its result could vary
925 * depending on the transaction isolation level. Operational commands
926 * such as 'SET' and 'SHOW' are not considered to be transactable.
928 * @param string $sql
929 * @return bool
931 protected function isTransactableQuery( $sql ) {
932 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
933 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
937 * Run an SQL query and return the result. Normally throws a DBQueryError
938 * on failure. If errors are ignored, returns false instead.
940 * In new code, the query wrappers select(), insert(), update(), delete(),
941 * etc. should be used where possible, since they give much better DBMS
942 * independence and automatically quote or validate user input in a variety
943 * of contexts. This function is generally only useful for queries which are
944 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
945 * as CREATE TABLE.
947 * However, the query wrappers themselves should call this function.
949 * @param string $sql SQL query
950 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
951 * comment (you can use __METHOD__ or add some extra info)
952 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
953 * maybe best to catch the exception instead?
954 * @throws MWException
955 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
956 * for a successful read query, or false on failure if $tempIgnore set
958 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
959 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
961 $this->mLastQuery = $sql;
963 $isWriteQuery = $this->isWriteQuery( $sql );
964 if ( $isWriteQuery ) {
965 if ( !$this->mDoneWrites ) {
966 wfDebug( __METHOD__ . ': Writes done: ' .
967 DatabaseBase::generalizeSQL( $sql ) . "\n" );
969 # Set a flag indicating that writes have been done
970 $this->mDoneWrites = microtime( true );
973 # Add a comment for easy SHOW PROCESSLIST interpretation
974 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
975 $userName = $wgUser->getName();
976 if ( mb_strlen( $userName ) > 15 ) {
977 $userName = mb_substr( $userName, 0, 15 ) . '...';
979 $userName = str_replace( '/', '', $userName );
980 } else {
981 $userName = '';
984 // Add trace comment to the begin of the sql string, right after the operator.
985 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
986 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
988 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
989 if ( $wgDebugDBTransactions ) {
990 wfDebug( "Implicit transaction start.\n" );
992 $this->begin( __METHOD__ . " ($fname)" );
993 $this->mTrxAutomatic = true;
996 # Keep track of whether the transaction has write queries pending
997 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
998 $this->mTrxDoneWrites = true;
999 $this->getTransactionProfiler()->transactionWritingIn(
1000 $this->mServer, $this->mDBname, $this->mTrxShortId );
1003 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1004 # generalizeSQL will probably cut down the query to reasonable
1005 # logging size most of the time. The substr is really just a sanity check.
1006 if ( $isMaster ) {
1007 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1008 $totalProf = 'DatabaseBase::query-master';
1009 } else {
1010 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1011 $totalProf = 'DatabaseBase::query';
1013 # Include query transaction state
1014 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1016 $profiler = Profiler::instance();
1017 if ( !$profiler instanceof ProfilerStub ) {
1018 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1019 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1022 if ( $this->debug() ) {
1023 static $cnt = 0;
1025 $cnt++;
1026 $sqlx = $wgDebugDumpSqlLength ? substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1027 : $commentedSql;
1028 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1030 $master = $isMaster ? 'master' : 'slave';
1031 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1034 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1036 # Avoid fatals if close() was called
1037 $this->assertOpen();
1039 # Do the query and handle errors
1040 $startTime = microtime( true );
1041 $ret = $this->doQuery( $commentedSql );
1042 $queryRuntime = microtime( true ) - $startTime;
1043 # Log the query time and feed it into the DB trx profiler
1044 $this->getTransactionProfiler()->recordQueryCompletion(
1045 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1047 MWDebug::queryTime( $queryId );
1049 # Try reconnecting if the connection was lost
1050 if ( false === $ret && $this->wasErrorReissuable() ) {
1051 # Transaction is gone, like it or not
1052 $hadTrx = $this->mTrxLevel; // possible lost transaction
1053 $this->mTrxLevel = 0;
1054 $this->mTrxIdleCallbacks = array(); // bug 65263
1055 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1056 wfDebug( "Connection lost, reconnecting...\n" );
1057 # Stash the last error values since ping() might clear them
1058 $lastError = $this->lastError();
1059 $lastErrno = $this->lastErrno();
1060 if ( $this->ping() ) {
1061 wfDebug( "Reconnected\n" );
1062 $server = $this->getServer();
1063 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1064 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1066 if ( $hadTrx ) {
1067 # Leave $ret as false and let an error be reported.
1068 # Callers may catch the exception and continue to use the DB.
1069 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1070 } else {
1071 # Should be safe to silently retry (no trx and thus no callbacks)
1072 $startTime = microtime( true );
1073 $ret = $this->doQuery( $commentedSql );
1074 $queryRuntime = microtime( true ) - $startTime;
1075 # Log the query time and feed it into the DB trx profiler
1076 $this->getTransactionProfiler()->recordQueryCompletion(
1077 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1079 } else {
1080 wfDebug( "Failed\n" );
1084 if ( false === $ret ) {
1085 $this->reportQueryError(
1086 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1089 $res = $this->resultObject( $ret );
1091 // Destroy profile sections in the opposite order to their creation
1092 $queryProfSection = false;
1093 $totalProfSection = false;
1095 if ( $isWriteQuery && $this->mTrxLevel ) {
1096 $this->mTrxWriteDuration += $queryRuntime;
1099 return $res;
1103 * Report a query error. Log the error, and if neither the object ignore
1104 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1106 * @param string $error
1107 * @param int $errno
1108 * @param string $sql
1109 * @param string $fname
1110 * @param bool $tempIgnore
1111 * @throws DBQueryError
1113 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1114 ++$this->mErrorCount;
1116 if ( $this->ignoreErrors() || $tempIgnore ) {
1117 wfDebug( "SQL ERROR (ignored): $error\n" );
1118 } else {
1119 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1120 wfLogDBError(
1121 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1122 $this->getLogContext( array(
1123 'method' => __METHOD__,
1124 'errno' => $errno,
1125 'error' => $error,
1126 'sql1line' => $sql1line,
1127 'fname' => $fname,
1130 wfDebug( "SQL ERROR: " . $error . "\n" );
1131 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1136 * Intended to be compatible with the PEAR::DB wrapper functions.
1137 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1139 * ? = scalar value, quoted as necessary
1140 * ! = raw SQL bit (a function for instance)
1141 * & = filename; reads the file and inserts as a blob
1142 * (we don't use this though...)
1144 * @param string $sql
1145 * @param string $func
1147 * @return array
1149 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1150 /* MySQL doesn't support prepared statements (yet), so just
1151 * pack up the query for reference. We'll manually replace
1152 * the bits later.
1154 return array( 'query' => $sql, 'func' => $func );
1158 * Free a prepared query, generated by prepare().
1159 * @param string $prepared
1161 protected function freePrepared( $prepared ) {
1162 /* No-op by default */
1166 * Execute a prepared query with the various arguments
1167 * @param string $prepared The prepared sql
1168 * @param mixed $args Either an array here, or put scalars as varargs
1170 * @return ResultWrapper
1172 public function execute( $prepared, $args = null ) {
1173 if ( !is_array( $args ) ) {
1174 # Pull the var args
1175 $args = func_get_args();
1176 array_shift( $args );
1179 $sql = $this->fillPrepared( $prepared['query'], $args );
1181 return $this->query( $sql, $prepared['func'] );
1185 * For faking prepared SQL statements on DBs that don't support it directly.
1187 * @param string $preparedQuery A 'preparable' SQL statement
1188 * @param array $args Array of Arguments to fill it with
1189 * @return string Executable SQL
1191 public function fillPrepared( $preparedQuery, $args ) {
1192 reset( $args );
1193 $this->preparedArgs =& $args;
1195 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1196 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1200 * preg_callback func for fillPrepared()
1201 * The arguments should be in $this->preparedArgs and must not be touched
1202 * while we're doing this.
1204 * @param array $matches
1205 * @throws DBUnexpectedError
1206 * @return string
1208 protected function fillPreparedArg( $matches ) {
1209 switch ( $matches[1] ) {
1210 case '\\?':
1211 return '?';
1212 case '\\!':
1213 return '!';
1214 case '\\&':
1215 return '&';
1218 list( /* $n */, $arg ) = each( $this->preparedArgs );
1220 switch ( $matches[1] ) {
1221 case '?':
1222 return $this->addQuotes( $arg );
1223 case '!':
1224 return $arg;
1225 case '&':
1226 # return $this->addQuotes( file_get_contents( $arg ) );
1227 throw new DBUnexpectedError(
1228 $this,
1229 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1231 default:
1232 throw new DBUnexpectedError(
1233 $this,
1234 'Received invalid match. This should never happen!'
1240 * Free a result object returned by query() or select(). It's usually not
1241 * necessary to call this, just use unset() or let the variable holding
1242 * the result object go out of scope.
1244 * @param mixed $res A SQL result
1246 public function freeResult( $res ) {
1250 * A SELECT wrapper which returns a single field from a single result row.
1252 * Usually throws a DBQueryError on failure. If errors are explicitly
1253 * ignored, returns false on failure.
1255 * If no result rows are returned from the query, false is returned.
1257 * @param string|array $table Table name. See DatabaseBase::select() for details.
1258 * @param string $var The field name to select. This must be a valid SQL
1259 * fragment: do not use unvalidated user input.
1260 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1261 * @param string $fname The function name of the caller.
1262 * @param string|array $options The query options. See DatabaseBase::select() for details.
1264 * @return bool|mixed The value from the field, or false on failure.
1266 public function selectField(
1267 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1269 if ( $var === '*' ) { // sanity
1270 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1273 if ( !is_array( $options ) ) {
1274 $options = array( $options );
1277 $options['LIMIT'] = 1;
1279 $res = $this->select( $table, $var, $cond, $fname, $options );
1280 if ( $res === false || !$this->numRows( $res ) ) {
1281 return false;
1284 $row = $this->fetchRow( $res );
1286 if ( $row !== false ) {
1287 return reset( $row );
1288 } else {
1289 return false;
1294 * A SELECT wrapper which returns a list of single field values from result rows.
1296 * Usually throws a DBQueryError on failure. If errors are explicitly
1297 * ignored, returns false on failure.
1299 * If no result rows are returned from the query, false is returned.
1301 * @param string|array $table Table name. See DatabaseBase::select() for details.
1302 * @param string $var The field name to select. This must be a valid SQL
1303 * fragment: do not use unvalidated user input.
1304 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1305 * @param string $fname The function name of the caller.
1306 * @param string|array $options The query options. See DatabaseBase::select() for details.
1308 * @return bool|array The values from the field, or false on failure
1309 * @throws DBUnexpectedError
1310 * @since 1.25
1312 public function selectFieldValues(
1313 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1315 if ( $var === '*' ) { // sanity
1316 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1319 if ( !is_array( $options ) ) {
1320 $options = array( $options );
1323 $res = $this->select( $table, $var, $cond, $fname, $options );
1324 if ( $res === false ) {
1325 return false;
1328 $values = array();
1329 foreach ( $res as $row ) {
1330 $values[] = $row->$var;
1333 return $values;
1337 * Returns an optional USE INDEX clause to go after the table, and a
1338 * string to go at the end of the query.
1340 * @param array $options Associative array of options to be turned into
1341 * an SQL query, valid keys are listed in the function.
1342 * @return array
1343 * @see DatabaseBase::select()
1345 public function makeSelectOptions( $options ) {
1346 $preLimitTail = $postLimitTail = '';
1347 $startOpts = '';
1349 $noKeyOptions = array();
1351 foreach ( $options as $key => $option ) {
1352 if ( is_numeric( $key ) ) {
1353 $noKeyOptions[$option] = true;
1357 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1359 $preLimitTail .= $this->makeOrderBy( $options );
1361 // if (isset($options['LIMIT'])) {
1362 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1363 // isset($options['OFFSET']) ? $options['OFFSET']
1364 // : false);
1365 // }
1367 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1368 $postLimitTail .= ' FOR UPDATE';
1371 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1372 $postLimitTail .= ' LOCK IN SHARE MODE';
1375 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1376 $startOpts .= 'DISTINCT';
1379 # Various MySQL extensions
1380 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1381 $startOpts .= ' /*! STRAIGHT_JOIN */';
1384 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1385 $startOpts .= ' HIGH_PRIORITY';
1388 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1389 $startOpts .= ' SQL_BIG_RESULT';
1392 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1393 $startOpts .= ' SQL_BUFFER_RESULT';
1396 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1397 $startOpts .= ' SQL_SMALL_RESULT';
1400 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1401 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1404 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1405 $startOpts .= ' SQL_CACHE';
1408 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1409 $startOpts .= ' SQL_NO_CACHE';
1412 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1413 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1414 } else {
1415 $useIndex = '';
1418 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1422 * Returns an optional GROUP BY with an optional HAVING
1424 * @param array $options Associative array of options
1425 * @return string
1426 * @see DatabaseBase::select()
1427 * @since 1.21
1429 public function makeGroupByWithHaving( $options ) {
1430 $sql = '';
1431 if ( isset( $options['GROUP BY'] ) ) {
1432 $gb = is_array( $options['GROUP BY'] )
1433 ? implode( ',', $options['GROUP BY'] )
1434 : $options['GROUP BY'];
1435 $sql .= ' GROUP BY ' . $gb;
1437 if ( isset( $options['HAVING'] ) ) {
1438 $having = is_array( $options['HAVING'] )
1439 ? $this->makeList( $options['HAVING'], LIST_AND )
1440 : $options['HAVING'];
1441 $sql .= ' HAVING ' . $having;
1444 return $sql;
1448 * Returns an optional ORDER BY
1450 * @param array $options Associative array of options
1451 * @return string
1452 * @see DatabaseBase::select()
1453 * @since 1.21
1455 public function makeOrderBy( $options ) {
1456 if ( isset( $options['ORDER BY'] ) ) {
1457 $ob = is_array( $options['ORDER BY'] )
1458 ? implode( ',', $options['ORDER BY'] )
1459 : $options['ORDER BY'];
1461 return ' ORDER BY ' . $ob;
1464 return '';
1468 * Execute a SELECT query constructed using the various parameters provided.
1469 * See below for full details of the parameters.
1471 * @param string|array $table Table name
1472 * @param string|array $vars Field names
1473 * @param string|array $conds Conditions
1474 * @param string $fname Caller function name
1475 * @param array $options Query options
1476 * @param array $join_conds Join conditions
1479 * @param string|array $table
1481 * May be either an array of table names, or a single string holding a table
1482 * name. If an array is given, table aliases can be specified, for example:
1484 * array( 'a' => 'user' )
1486 * This includes the user table in the query, with the alias "a" available
1487 * for use in field names (e.g. a.user_name).
1489 * All of the table names given here are automatically run through
1490 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1491 * added, and various other table name mappings to be performed.
1494 * @param string|array $vars
1496 * May be either a field name or an array of field names. The field names
1497 * can be complete fragments of SQL, for direct inclusion into the SELECT
1498 * query. If an array is given, field aliases can be specified, for example:
1500 * array( 'maxrev' => 'MAX(rev_id)' )
1502 * This includes an expression with the alias "maxrev" in the query.
1504 * If an expression is given, care must be taken to ensure that it is
1505 * DBMS-independent.
1508 * @param string|array $conds
1510 * May be either a string containing a single condition, or an array of
1511 * conditions. If an array is given, the conditions constructed from each
1512 * element are combined with AND.
1514 * Array elements may take one of two forms:
1516 * - Elements with a numeric key are interpreted as raw SQL fragments.
1517 * - Elements with a string key are interpreted as equality conditions,
1518 * where the key is the field name.
1519 * - If the value of such an array element is a scalar (such as a
1520 * string), it will be treated as data and thus quoted appropriately.
1521 * If it is null, an IS NULL clause will be added.
1522 * - If the value is an array, an IN (...) clause will be constructed
1523 * from its non-null elements, and an IS NULL clause will be added
1524 * if null is present, such that the field may match any of the
1525 * elements in the array. The non-null elements will be quoted.
1527 * Note that expressions are often DBMS-dependent in their syntax.
1528 * DBMS-independent wrappers are provided for constructing several types of
1529 * expression commonly used in condition queries. See:
1530 * - DatabaseBase::buildLike()
1531 * - DatabaseBase::conditional()
1534 * @param string|array $options
1536 * Optional: Array of query options. Boolean options are specified by
1537 * including them in the array as a string value with a numeric key, for
1538 * example:
1540 * array( 'FOR UPDATE' )
1542 * The supported options are:
1544 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1545 * with LIMIT can theoretically be used for paging through a result set,
1546 * but this is discouraged in MediaWiki for performance reasons.
1548 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1549 * and then the first rows are taken until the limit is reached. LIMIT
1550 * is applied to a result set after OFFSET.
1552 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1553 * changed until the next COMMIT.
1555 * - DISTINCT: Boolean: return only unique result rows.
1557 * - GROUP BY: May be either an SQL fragment string naming a field or
1558 * expression to group by, or an array of such SQL fragments.
1560 * - HAVING: May be either an string containing a HAVING clause or an array of
1561 * conditions building the HAVING clause. If an array is given, the conditions
1562 * constructed from each element are combined with AND.
1564 * - ORDER BY: May be either an SQL fragment giving a field name or
1565 * expression to order by, or an array of such SQL fragments.
1567 * - USE INDEX: This may be either a string giving the index name to use
1568 * for the query, or an array. If it is an associative array, each key
1569 * gives the table name (or alias), each value gives the index name to
1570 * use for that table. All strings are SQL fragments and so should be
1571 * validated by the caller.
1573 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1574 * instead of SELECT.
1576 * And also the following boolean MySQL extensions, see the MySQL manual
1577 * for documentation:
1579 * - LOCK IN SHARE MODE
1580 * - STRAIGHT_JOIN
1581 * - HIGH_PRIORITY
1582 * - SQL_BIG_RESULT
1583 * - SQL_BUFFER_RESULT
1584 * - SQL_SMALL_RESULT
1585 * - SQL_CALC_FOUND_ROWS
1586 * - SQL_CACHE
1587 * - SQL_NO_CACHE
1590 * @param string|array $join_conds
1592 * Optional associative array of table-specific join conditions. In the
1593 * most common case, this is unnecessary, since the join condition can be
1594 * in $conds. However, it is useful for doing a LEFT JOIN.
1596 * The key of the array contains the table name or alias. The value is an
1597 * array with two elements, numbered 0 and 1. The first gives the type of
1598 * join, the second is an SQL fragment giving the join condition for that
1599 * table. For example:
1601 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1603 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1604 * with no rows in it will be returned. If there was a query error, a
1605 * DBQueryError exception will be thrown, except if the "ignore errors"
1606 * option was set, in which case false will be returned.
1608 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1609 $options = array(), $join_conds = array() ) {
1610 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1612 return $this->query( $sql, $fname );
1616 * The equivalent of DatabaseBase::select() except that the constructed SQL
1617 * is returned, instead of being immediately executed. This can be useful for
1618 * doing UNION queries, where the SQL text of each query is needed. In general,
1619 * however, callers outside of Database classes should just use select().
1621 * @param string|array $table Table name
1622 * @param string|array $vars Field names
1623 * @param string|array $conds Conditions
1624 * @param string $fname Caller function name
1625 * @param string|array $options Query options
1626 * @param string|array $join_conds Join conditions
1628 * @return string SQL query string.
1629 * @see DatabaseBase::select()
1631 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1632 $options = array(), $join_conds = array()
1634 if ( is_array( $vars ) ) {
1635 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1638 $options = (array)$options;
1639 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1640 ? $options['USE INDEX']
1641 : array();
1643 if ( is_array( $table ) ) {
1644 $from = ' FROM ' .
1645 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1646 } elseif ( $table != '' ) {
1647 if ( $table[0] == ' ' ) {
1648 $from = ' FROM ' . $table;
1649 } else {
1650 $from = ' FROM ' .
1651 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1653 } else {
1654 $from = '';
1657 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1658 $this->makeSelectOptions( $options );
1660 if ( !empty( $conds ) ) {
1661 if ( is_array( $conds ) ) {
1662 $conds = $this->makeList( $conds, LIST_AND );
1664 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1665 } else {
1666 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1669 if ( isset( $options['LIMIT'] ) ) {
1670 $sql = $this->limitResult( $sql, $options['LIMIT'],
1671 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1673 $sql = "$sql $postLimitTail";
1675 if ( isset( $options['EXPLAIN'] ) ) {
1676 $sql = 'EXPLAIN ' . $sql;
1679 return $sql;
1683 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1684 * that a single row object is returned. If the query returns no rows,
1685 * false is returned.
1687 * @param string|array $table Table name
1688 * @param string|array $vars Field names
1689 * @param array $conds Conditions
1690 * @param string $fname Caller function name
1691 * @param string|array $options Query options
1692 * @param array|string $join_conds Join conditions
1694 * @return stdClass|bool
1696 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1697 $options = array(), $join_conds = array()
1699 $options = (array)$options;
1700 $options['LIMIT'] = 1;
1701 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1703 if ( $res === false ) {
1704 return false;
1707 if ( !$this->numRows( $res ) ) {
1708 return false;
1711 $obj = $this->fetchObject( $res );
1713 return $obj;
1717 * Estimate the number of rows in dataset
1719 * MySQL allows you to estimate the number of rows that would be returned
1720 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1721 * index cardinality statistics, and is notoriously inaccurate, especially
1722 * when large numbers of rows have recently been added or deleted.
1724 * For DBMSs that don't support fast result size estimation, this function
1725 * will actually perform the SELECT COUNT(*).
1727 * Takes the same arguments as DatabaseBase::select().
1729 * @param string $table Table name
1730 * @param string $vars Unused
1731 * @param array|string $conds Filters on the table
1732 * @param string $fname Function name for profiling
1733 * @param array $options Options for select
1734 * @return int Row count
1736 public function estimateRowCount(
1737 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1739 $rows = 0;
1740 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1742 if ( $res ) {
1743 $row = $this->fetchRow( $res );
1744 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1747 return $rows;
1751 * Get the number of rows in dataset
1753 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1755 * Takes the same arguments as DatabaseBase::select().
1757 * @param string $table Table name
1758 * @param string $vars Unused
1759 * @param array|string $conds Filters on the table
1760 * @param string $fname Function name for profiling
1761 * @param array $options Options for select
1762 * @return int Row count
1763 * @since 1.24
1765 public function selectRowCount(
1766 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1768 $rows = 0;
1769 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1770 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1772 if ( $res ) {
1773 $row = $this->fetchRow( $res );
1774 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1777 return $rows;
1781 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1782 * It's only slightly flawed. Don't use for anything important.
1784 * @param string $sql A SQL Query
1786 * @return string
1788 static function generalizeSQL( $sql ) {
1789 # This does the same as the regexp below would do, but in such a way
1790 # as to avoid crashing php on some large strings.
1791 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1793 $sql = str_replace( "\\\\", '', $sql );
1794 $sql = str_replace( "\\'", '', $sql );
1795 $sql = str_replace( "\\\"", '', $sql );
1796 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1797 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1799 # All newlines, tabs, etc replaced by single space
1800 $sql = preg_replace( '/\s+/', ' ', $sql );
1802 # All numbers => N,
1803 # except the ones surrounded by characters, e.g. l10n
1804 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1805 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1807 return $sql;
1811 * Determines whether a field exists in a table
1813 * @param string $table Table name
1814 * @param string $field Filed to check on that table
1815 * @param string $fname Calling function name (optional)
1816 * @return bool Whether $table has filed $field
1818 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1819 $info = $this->fieldInfo( $table, $field );
1821 return (bool)$info;
1825 * Determines whether an index exists
1826 * Usually throws a DBQueryError on failure
1827 * If errors are explicitly ignored, returns NULL on failure
1829 * @param string $table
1830 * @param string $index
1831 * @param string $fname
1832 * @return bool|null
1834 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1835 if ( !$this->tableExists( $table ) ) {
1836 return null;
1839 $info = $this->indexInfo( $table, $index, $fname );
1840 if ( is_null( $info ) ) {
1841 return null;
1842 } else {
1843 return $info !== false;
1848 * Query whether a given table exists
1850 * @param string $table
1851 * @param string $fname
1852 * @return bool
1854 public function tableExists( $table, $fname = __METHOD__ ) {
1855 $table = $this->tableName( $table );
1856 $old = $this->ignoreErrors( true );
1857 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1858 $this->ignoreErrors( $old );
1860 return (bool)$res;
1864 * Determines if a given index is unique
1866 * @param string $table
1867 * @param string $index
1869 * @return bool
1871 public function indexUnique( $table, $index ) {
1872 $indexInfo = $this->indexInfo( $table, $index );
1874 if ( !$indexInfo ) {
1875 return null;
1878 return !$indexInfo[0]->Non_unique;
1882 * Helper for DatabaseBase::insert().
1884 * @param array $options
1885 * @return string
1887 protected function makeInsertOptions( $options ) {
1888 return implode( ' ', $options );
1892 * INSERT wrapper, inserts an array into a table.
1894 * $a may be either:
1896 * - A single associative array. The array keys are the field names, and
1897 * the values are the values to insert. The values are treated as data
1898 * and will be quoted appropriately. If NULL is inserted, this will be
1899 * converted to a database NULL.
1900 * - An array with numeric keys, holding a list of associative arrays.
1901 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1902 * each subarray must be identical to each other, and in the same order.
1904 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1905 * returns success.
1907 * $options is an array of options, with boolean options encoded as values
1908 * with numeric keys, in the same style as $options in
1909 * DatabaseBase::select(). Supported options are:
1911 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1912 * any rows which cause duplicate key errors are not inserted. It's
1913 * possible to determine how many rows were successfully inserted using
1914 * DatabaseBase::affectedRows().
1916 * @param string $table Table name. This will be passed through
1917 * DatabaseBase::tableName().
1918 * @param array $a Array of rows to insert
1919 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1920 * @param array $options Array of options
1922 * @return bool
1924 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1925 # No rows to insert, easy just return now
1926 if ( !count( $a ) ) {
1927 return true;
1930 $table = $this->tableName( $table );
1932 if ( !is_array( $options ) ) {
1933 $options = array( $options );
1936 $fh = null;
1937 if ( isset( $options['fileHandle'] ) ) {
1938 $fh = $options['fileHandle'];
1940 $options = $this->makeInsertOptions( $options );
1942 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1943 $multi = true;
1944 $keys = array_keys( $a[0] );
1945 } else {
1946 $multi = false;
1947 $keys = array_keys( $a );
1950 $sql = 'INSERT ' . $options .
1951 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1953 if ( $multi ) {
1954 $first = true;
1955 foreach ( $a as $row ) {
1956 if ( $first ) {
1957 $first = false;
1958 } else {
1959 $sql .= ',';
1961 $sql .= '(' . $this->makeList( $row ) . ')';
1963 } else {
1964 $sql .= '(' . $this->makeList( $a ) . ')';
1967 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1968 return false;
1969 } elseif ( $fh !== null ) {
1970 return true;
1973 return (bool)$this->query( $sql, $fname );
1977 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1979 * @param array $options
1980 * @return array
1982 protected function makeUpdateOptionsArray( $options ) {
1983 if ( !is_array( $options ) ) {
1984 $options = array( $options );
1987 $opts = array();
1989 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1990 $opts[] = $this->lowPriorityOption();
1993 if ( in_array( 'IGNORE', $options ) ) {
1994 $opts[] = 'IGNORE';
1997 return $opts;
2001 * Make UPDATE options for the DatabaseBase::update function
2003 * @param array $options The options passed to DatabaseBase::update
2004 * @return string
2006 protected function makeUpdateOptions( $options ) {
2007 $opts = $this->makeUpdateOptionsArray( $options );
2009 return implode( ' ', $opts );
2013 * UPDATE wrapper. Takes a condition array and a SET array.
2015 * @param string $table Name of the table to UPDATE. This will be passed through
2016 * DatabaseBase::tableName().
2017 * @param array $values An array of values to SET. For each array element,
2018 * the key gives the field name, and the value gives the data to set
2019 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2020 * @param array $conds An array of conditions (WHERE). See
2021 * DatabaseBase::select() for the details of the format of condition
2022 * arrays. Use '*' to update all rows.
2023 * @param string $fname The function name of the caller (from __METHOD__),
2024 * for logging and profiling.
2025 * @param array $options An array of UPDATE options, can be:
2026 * - IGNORE: Ignore unique key conflicts
2027 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2028 * @return bool
2030 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
2031 $table = $this->tableName( $table );
2032 $opts = $this->makeUpdateOptions( $options );
2033 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
2035 if ( $conds !== array() && $conds !== '*' ) {
2036 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2039 return $this->query( $sql, $fname );
2043 * Makes an encoded list of strings from an array
2045 * @param array $a Containing the data
2046 * @param int $mode Constant
2047 * - LIST_COMMA: Comma separated, no field names
2048 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2049 * documentation for $conds in DatabaseBase::select().
2050 * - LIST_OR: ORed WHERE clause (without the WHERE)
2051 * - LIST_SET: Comma separated with field names, like a SET clause
2052 * - LIST_NAMES: Comma separated field names
2053 * @throws MWException|DBUnexpectedError
2054 * @return string
2056 public function makeList( $a, $mode = LIST_COMMA ) {
2057 if ( !is_array( $a ) ) {
2058 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2061 $first = true;
2062 $list = '';
2064 foreach ( $a as $field => $value ) {
2065 if ( !$first ) {
2066 if ( $mode == LIST_AND ) {
2067 $list .= ' AND ';
2068 } elseif ( $mode == LIST_OR ) {
2069 $list .= ' OR ';
2070 } else {
2071 $list .= ',';
2073 } else {
2074 $first = false;
2077 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2078 $list .= "($value)";
2079 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2080 $list .= "$value";
2081 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2082 // Remove null from array to be handled separately if found
2083 $includeNull = false;
2084 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2085 $includeNull = true;
2086 unset( $value[$nullKey] );
2088 if ( count( $value ) == 0 && !$includeNull ) {
2089 throw new MWException( __METHOD__ . ": empty input for field $field" );
2090 } elseif ( count( $value ) == 0 ) {
2091 // only check if $field is null
2092 $list .= "$field IS NULL";
2093 } else {
2094 // IN clause contains at least one valid element
2095 if ( $includeNull ) {
2096 // Group subconditions to ensure correct precedence
2097 $list .= '(';
2099 if ( count( $value ) == 1 ) {
2100 // Special-case single values, as IN isn't terribly efficient
2101 // Don't necessarily assume the single key is 0; we don't
2102 // enforce linear numeric ordering on other arrays here.
2103 $value = array_values( $value );
2104 $list .= $field . " = " . $this->addQuotes( $value[0] );
2105 } else {
2106 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2108 // if null present in array, append IS NULL
2109 if ( $includeNull ) {
2110 $list .= " OR $field IS NULL)";
2113 } elseif ( $value === null ) {
2114 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2115 $list .= "$field IS ";
2116 } elseif ( $mode == LIST_SET ) {
2117 $list .= "$field = ";
2119 $list .= 'NULL';
2120 } else {
2121 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2122 $list .= "$field = ";
2124 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2128 return $list;
2132 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2133 * The keys on each level may be either integers or strings.
2135 * @param array $data Organized as 2-d
2136 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2137 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2138 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2139 * @return string|bool SQL fragment, or false if no items in array
2141 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2142 $conds = array();
2144 foreach ( $data as $base => $sub ) {
2145 if ( count( $sub ) ) {
2146 $conds[] = $this->makeList(
2147 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2148 LIST_AND );
2152 if ( $conds ) {
2153 return $this->makeList( $conds, LIST_OR );
2154 } else {
2155 // Nothing to search for...
2156 return false;
2161 * Return aggregated value alias
2163 * @param array $valuedata
2164 * @param string $valuename
2166 * @return string
2168 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2169 return $valuename;
2173 * @param string $field
2174 * @return string
2176 public function bitNot( $field ) {
2177 return "(~$field)";
2181 * @param string $fieldLeft
2182 * @param string $fieldRight
2183 * @return string
2185 public function bitAnd( $fieldLeft, $fieldRight ) {
2186 return "($fieldLeft & $fieldRight)";
2190 * @param string $fieldLeft
2191 * @param string $fieldRight
2192 * @return string
2194 public function bitOr( $fieldLeft, $fieldRight ) {
2195 return "($fieldLeft | $fieldRight)";
2199 * Build a concatenation list to feed into a SQL query
2200 * @param array $stringList List of raw SQL expressions; caller is
2201 * responsible for any quoting
2202 * @return string
2204 public function buildConcat( $stringList ) {
2205 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2209 * Build a GROUP_CONCAT or equivalent statement for a query.
2211 * This is useful for combining a field for several rows into a single string.
2212 * NULL values will not appear in the output, duplicated values will appear,
2213 * and the resulting delimiter-separated values have no defined sort order.
2214 * Code using the results may need to use the PHP unique() or sort() methods.
2216 * @param string $delim Glue to bind the results together
2217 * @param string|array $table Table name
2218 * @param string $field Field name
2219 * @param string|array $conds Conditions
2220 * @param string|array $join_conds Join conditions
2221 * @return string SQL text
2222 * @since 1.23
2224 public function buildGroupConcatField(
2225 $delim, $table, $field, $conds = '', $join_conds = array()
2227 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2229 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2233 * Change the current database
2235 * @todo Explain what exactly will fail if this is not overridden.
2237 * @param string $db
2239 * @return bool Success or failure
2241 public function selectDB( $db ) {
2242 # Stub. Shouldn't cause serious problems if it's not overridden, but
2243 # if your database engine supports a concept similar to MySQL's
2244 # databases you may as well.
2245 $this->mDBname = $db;
2247 return true;
2251 * Get the current DB name
2252 * @return string
2254 public function getDBname() {
2255 return $this->mDBname;
2259 * Get the server hostname or IP address
2260 * @return string
2262 public function getServer() {
2263 return $this->mServer;
2267 * Format a table name ready for use in constructing an SQL query
2269 * This does two important things: it quotes the table names to clean them up,
2270 * and it adds a table prefix if only given a table name with no quotes.
2272 * All functions of this object which require a table name call this function
2273 * themselves. Pass the canonical name to such functions. This is only needed
2274 * when calling query() directly.
2276 * @param string $name Database table name
2277 * @param string $format One of:
2278 * quoted - Automatically pass the table name through addIdentifierQuotes()
2279 * so that it can be used in a query.
2280 * raw - Do not add identifier quotes to the table name
2281 * @return string Full database name
2283 public function tableName( $name, $format = 'quoted' ) {
2284 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2285 # Skip the entire process when we have a string quoted on both ends.
2286 # Note that we check the end so that we will still quote any use of
2287 # use of `database`.table. But won't break things if someone wants
2288 # to query a database table with a dot in the name.
2289 if ( $this->isQuotedIdentifier( $name ) ) {
2290 return $name;
2293 # Lets test for any bits of text that should never show up in a table
2294 # name. Basically anything like JOIN or ON which are actually part of
2295 # SQL queries, but may end up inside of the table value to combine
2296 # sql. Such as how the API is doing.
2297 # Note that we use a whitespace test rather than a \b test to avoid
2298 # any remote case where a word like on may be inside of a table name
2299 # surrounded by symbols which may be considered word breaks.
2300 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2301 return $name;
2304 # Split database and table into proper variables.
2305 # We reverse the explode so that database.table and table both output
2306 # the correct table.
2307 $dbDetails = explode( '.', $name, 3 );
2308 if ( count( $dbDetails ) == 3 ) {
2309 list( $database, $schema, $table ) = $dbDetails;
2310 # We don't want any prefix added in this case
2311 $prefix = '';
2312 } elseif ( count( $dbDetails ) == 2 ) {
2313 list( $database, $table ) = $dbDetails;
2314 # We don't want any prefix added in this case
2315 # In dbs that support it, $database may actually be the schema
2316 # but that doesn't affect any of the functionality here
2317 $prefix = '';
2318 $schema = null;
2319 } else {
2320 list( $table ) = $dbDetails;
2321 if ( $wgSharedDB !== null # We have a shared database
2322 && $this->mForeign == false # We're not working on a foreign database
2323 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2324 && in_array( $table, $wgSharedTables ) # A shared table is selected
2326 $database = $wgSharedDB;
2327 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2328 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2329 } else {
2330 $database = null;
2331 $schema = $this->mSchema; # Default schema
2332 $prefix = $this->mTablePrefix; # Default prefix
2336 # Quote $table and apply the prefix if not quoted.
2337 # $tableName might be empty if this is called from Database::replaceVars()
2338 $tableName = "{$prefix}{$table}";
2339 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2340 $tableName = $this->addIdentifierQuotes( $tableName );
2343 # Quote $schema and merge it with the table name if needed
2344 if ( strlen( $schema ) ) {
2345 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2346 $schema = $this->addIdentifierQuotes( $schema );
2348 $tableName = $schema . '.' . $tableName;
2351 # Quote $database and merge it with the table name if needed
2352 if ( $database !== null ) {
2353 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2354 $database = $this->addIdentifierQuotes( $database );
2356 $tableName = $database . '.' . $tableName;
2359 return $tableName;
2363 * Fetch a number of table names into an array
2364 * This is handy when you need to construct SQL for joins
2366 * Example:
2367 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2368 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2369 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2371 * @return array
2373 public function tableNames() {
2374 $inArray = func_get_args();
2375 $retVal = array();
2377 foreach ( $inArray as $name ) {
2378 $retVal[$name] = $this->tableName( $name );
2381 return $retVal;
2385 * Fetch a number of table names into an zero-indexed numerical array
2386 * This is handy when you need to construct SQL for joins
2388 * Example:
2389 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2390 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2391 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2393 * @return array
2395 public function tableNamesN() {
2396 $inArray = func_get_args();
2397 $retVal = array();
2399 foreach ( $inArray as $name ) {
2400 $retVal[] = $this->tableName( $name );
2403 return $retVal;
2407 * Get an aliased table name
2408 * e.g. tableName AS newTableName
2410 * @param string $name Table name, see tableName()
2411 * @param string|bool $alias Alias (optional)
2412 * @return string SQL name for aliased table. Will not alias a table to its own name
2414 public function tableNameWithAlias( $name, $alias = false ) {
2415 if ( !$alias || $alias == $name ) {
2416 return $this->tableName( $name );
2417 } else {
2418 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2423 * Gets an array of aliased table names
2425 * @param array $tables Array( [alias] => table )
2426 * @return string[] See tableNameWithAlias()
2428 public function tableNamesWithAlias( $tables ) {
2429 $retval = array();
2430 foreach ( $tables as $alias => $table ) {
2431 if ( is_numeric( $alias ) ) {
2432 $alias = $table;
2434 $retval[] = $this->tableNameWithAlias( $table, $alias );
2437 return $retval;
2441 * Get an aliased field name
2442 * e.g. fieldName AS newFieldName
2444 * @param string $name Field name
2445 * @param string|bool $alias Alias (optional)
2446 * @return string SQL name for aliased field. Will not alias a field to its own name
2448 public function fieldNameWithAlias( $name, $alias = false ) {
2449 if ( !$alias || (string)$alias === (string)$name ) {
2450 return $name;
2451 } else {
2452 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2457 * Gets an array of aliased field names
2459 * @param array $fields Array( [alias] => field )
2460 * @return string[] See fieldNameWithAlias()
2462 public function fieldNamesWithAlias( $fields ) {
2463 $retval = array();
2464 foreach ( $fields as $alias => $field ) {
2465 if ( is_numeric( $alias ) ) {
2466 $alias = $field;
2468 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2471 return $retval;
2475 * Get the aliased table name clause for a FROM clause
2476 * which might have a JOIN and/or USE INDEX clause
2478 * @param array $tables ( [alias] => table )
2479 * @param array $use_index Same as for select()
2480 * @param array $join_conds Same as for select()
2481 * @return string
2483 protected function tableNamesWithUseIndexOrJOIN(
2484 $tables, $use_index = array(), $join_conds = array()
2486 $ret = array();
2487 $retJOIN = array();
2488 $use_index = (array)$use_index;
2489 $join_conds = (array)$join_conds;
2491 foreach ( $tables as $alias => $table ) {
2492 if ( !is_string( $alias ) ) {
2493 // No alias? Set it equal to the table name
2494 $alias = $table;
2496 // Is there a JOIN clause for this table?
2497 if ( isset( $join_conds[$alias] ) ) {
2498 list( $joinType, $conds ) = $join_conds[$alias];
2499 $tableClause = $joinType;
2500 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2501 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2502 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2503 if ( $use != '' ) {
2504 $tableClause .= ' ' . $use;
2507 $on = $this->makeList( (array)$conds, LIST_AND );
2508 if ( $on != '' ) {
2509 $tableClause .= ' ON (' . $on . ')';
2512 $retJOIN[] = $tableClause;
2513 } elseif ( isset( $use_index[$alias] ) ) {
2514 // Is there an INDEX clause for this table?
2515 $tableClause = $this->tableNameWithAlias( $table, $alias );
2516 $tableClause .= ' ' . $this->useIndexClause(
2517 implode( ',', (array)$use_index[$alias] )
2520 $ret[] = $tableClause;
2521 } else {
2522 $tableClause = $this->tableNameWithAlias( $table, $alias );
2524 $ret[] = $tableClause;
2528 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2529 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2530 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2532 // Compile our final table clause
2533 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2537 * Get the name of an index in a given table.
2539 * @protected Don't use outside of DatabaseBase and childs
2540 * @param string $index
2541 * @return string
2543 public function indexName( $index ) {
2544 // @FIXME: Make this protected once we move away from PHP 5.3
2545 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2547 // Backwards-compatibility hack
2548 $renamed = array(
2549 'ar_usertext_timestamp' => 'usertext_timestamp',
2550 'un_user_id' => 'user_id',
2551 'un_user_ip' => 'user_ip',
2554 if ( isset( $renamed[$index] ) ) {
2555 return $renamed[$index];
2556 } else {
2557 return $index;
2562 * Adds quotes and backslashes.
2564 * @param string|Blob $s
2565 * @return string
2567 public function addQuotes( $s ) {
2568 if ( $s instanceof Blob ) {
2569 $s = $s->fetch();
2571 if ( $s === null ) {
2572 return 'NULL';
2573 } else {
2574 # This will also quote numeric values. This should be harmless,
2575 # and protects against weird problems that occur when they really
2576 # _are_ strings such as article titles and string->number->string
2577 # conversion is not 1:1.
2578 return "'" . $this->strencode( $s ) . "'";
2583 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2584 * MySQL uses `backticks` while basically everything else uses double quotes.
2585 * Since MySQL is the odd one out here the double quotes are our generic
2586 * and we implement backticks in DatabaseMysql.
2588 * @param string $s
2589 * @return string
2591 public function addIdentifierQuotes( $s ) {
2592 return '"' . str_replace( '"', '""', $s ) . '"';
2596 * Returns if the given identifier looks quoted or not according to
2597 * the database convention for quoting identifiers .
2599 * @param string $name
2600 * @return bool
2602 public function isQuotedIdentifier( $name ) {
2603 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2607 * @param string $s
2608 * @return string
2610 protected function escapeLikeInternal( $s ) {
2611 return addcslashes( $s, '\%_' );
2615 * LIKE statement wrapper, receives a variable-length argument list with
2616 * parts of pattern to match containing either string literals that will be
2617 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2618 * the function could be provided with an array of aforementioned
2619 * parameters.
2621 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2622 * a LIKE clause that searches for subpages of 'My page title'.
2623 * Alternatively:
2624 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2625 * $query .= $dbr->buildLike( $pattern );
2627 * @since 1.16
2628 * @return string Fully built LIKE statement
2630 public function buildLike() {
2631 $params = func_get_args();
2633 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2634 $params = $params[0];
2637 $s = '';
2639 foreach ( $params as $value ) {
2640 if ( $value instanceof LikeMatch ) {
2641 $s .= $value->toString();
2642 } else {
2643 $s .= $this->escapeLikeInternal( $value );
2647 return " LIKE {$this->addQuotes( $s )} ";
2651 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2653 * @return LikeMatch
2655 public function anyChar() {
2656 return new LikeMatch( '_' );
2660 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2662 * @return LikeMatch
2664 public function anyString() {
2665 return new LikeMatch( '%' );
2669 * Returns an appropriately quoted sequence value for inserting a new row.
2670 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2671 * subclass will return an integer, and save the value for insertId()
2673 * Any implementation of this function should *not* involve reusing
2674 * sequence numbers created for rolled-back transactions.
2675 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2676 * @param string $seqName
2677 * @return null|int
2679 public function nextSequenceValue( $seqName ) {
2680 return null;
2684 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2685 * is only needed because a) MySQL must be as efficient as possible due to
2686 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2687 * which index to pick. Anyway, other databases might have different
2688 * indexes on a given table. So don't bother overriding this unless you're
2689 * MySQL.
2690 * @param string $index
2691 * @return string
2693 public function useIndexClause( $index ) {
2694 return '';
2698 * REPLACE query wrapper.
2700 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2701 * except that when there is a duplicate key error, the old row is deleted
2702 * and the new row is inserted in its place.
2704 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2705 * perform the delete, we need to know what the unique indexes are so that
2706 * we know how to find the conflicting rows.
2708 * It may be more efficient to leave off unique indexes which are unlikely
2709 * to collide. However if you do this, you run the risk of encountering
2710 * errors which wouldn't have occurred in MySQL.
2712 * @param string $table The table to replace the row(s) in.
2713 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2714 * a field name or an array of field names
2715 * @param array $rows Can be either a single row to insert, or multiple rows,
2716 * in the same format as for DatabaseBase::insert()
2717 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2719 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2720 $quotedTable = $this->tableName( $table );
2722 if ( count( $rows ) == 0 ) {
2723 return;
2726 # Single row case
2727 if ( !is_array( reset( $rows ) ) ) {
2728 $rows = array( $rows );
2731 // @FXIME: this is not atomic, but a trx would break affectedRows()
2732 foreach ( $rows as $row ) {
2733 # Delete rows which collide
2734 if ( $uniqueIndexes ) {
2735 $sql = "DELETE FROM $quotedTable WHERE ";
2736 $first = true;
2737 foreach ( $uniqueIndexes as $index ) {
2738 if ( $first ) {
2739 $first = false;
2740 $sql .= '( ';
2741 } else {
2742 $sql .= ' ) OR ( ';
2744 if ( is_array( $index ) ) {
2745 $first2 = true;
2746 foreach ( $index as $col ) {
2747 if ( $first2 ) {
2748 $first2 = false;
2749 } else {
2750 $sql .= ' AND ';
2752 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2754 } else {
2755 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2758 $sql .= ' )';
2759 $this->query( $sql, $fname );
2762 # Now insert the row
2763 $this->insert( $table, $row, $fname );
2768 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2769 * statement.
2771 * @param string $table Table name
2772 * @param array|string $rows Row(s) to insert
2773 * @param string $fname Caller function name
2775 * @return ResultWrapper
2777 protected function nativeReplace( $table, $rows, $fname ) {
2778 $table = $this->tableName( $table );
2780 # Single row case
2781 if ( !is_array( reset( $rows ) ) ) {
2782 $rows = array( $rows );
2785 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2786 $first = true;
2788 foreach ( $rows as $row ) {
2789 if ( $first ) {
2790 $first = false;
2791 } else {
2792 $sql .= ',';
2795 $sql .= '(' . $this->makeList( $row ) . ')';
2798 return $this->query( $sql, $fname );
2802 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2804 * This updates any conflicting rows (according to the unique indexes) using
2805 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2807 * $rows may be either:
2808 * - A single associative array. The array keys are the field names, and
2809 * the values are the values to insert. The values are treated as data
2810 * and will be quoted appropriately. If NULL is inserted, this will be
2811 * converted to a database NULL.
2812 * - An array with numeric keys, holding a list of associative arrays.
2813 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2814 * each subarray must be identical to each other, and in the same order.
2816 * It may be more efficient to leave off unique indexes which are unlikely
2817 * to collide. However if you do this, you run the risk of encountering
2818 * errors which wouldn't have occurred in MySQL.
2820 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2821 * returns success.
2823 * @since 1.22
2825 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2826 * @param array $rows A single row or list of rows to insert
2827 * @param array $uniqueIndexes List of single field names or field name tuples
2828 * @param array $set An array of values to SET. For each array element, the
2829 * key gives the field name, and the value gives the data to set that
2830 * field to. The data will be quoted by DatabaseBase::addQuotes().
2831 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2832 * @throws Exception
2833 * @return bool
2835 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2836 $fname = __METHOD__
2838 if ( !count( $rows ) ) {
2839 return true; // nothing to do
2842 if ( !is_array( reset( $rows ) ) ) {
2843 $rows = array( $rows );
2846 if ( count( $uniqueIndexes ) ) {
2847 $clauses = array(); // list WHERE clauses that each identify a single row
2848 foreach ( $rows as $row ) {
2849 foreach ( $uniqueIndexes as $index ) {
2850 $index = is_array( $index ) ? $index : array( $index ); // columns
2851 $rowKey = array(); // unique key to this row
2852 foreach ( $index as $column ) {
2853 $rowKey[$column] = $row[$column];
2855 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2858 $where = array( $this->makeList( $clauses, LIST_OR ) );
2859 } else {
2860 $where = false;
2863 $useTrx = !$this->mTrxLevel;
2864 if ( $useTrx ) {
2865 $this->begin( $fname );
2867 try {
2868 # Update any existing conflicting row(s)
2869 if ( $where !== false ) {
2870 $ok = $this->update( $table, $set, $where, $fname );
2871 } else {
2872 $ok = true;
2874 # Now insert any non-conflicting row(s)
2875 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2876 } catch ( Exception $e ) {
2877 if ( $useTrx ) {
2878 $this->rollback( $fname );
2880 throw $e;
2882 if ( $useTrx ) {
2883 $this->commit( $fname );
2886 return $ok;
2890 * DELETE where the condition is a join.
2892 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2893 * we use sub-selects
2895 * For safety, an empty $conds will not delete everything. If you want to
2896 * delete all rows where the join condition matches, set $conds='*'.
2898 * DO NOT put the join condition in $conds.
2900 * @param string $delTable The table to delete from.
2901 * @param string $joinTable The other table.
2902 * @param string $delVar The variable to join on, in the first table.
2903 * @param string $joinVar The variable to join on, in the second table.
2904 * @param array $conds Condition array of field names mapped to variables,
2905 * ANDed together in the WHERE clause
2906 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2907 * @throws DBUnexpectedError
2909 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2910 $fname = __METHOD__
2912 if ( !$conds ) {
2913 throw new DBUnexpectedError( $this,
2914 'DatabaseBase::deleteJoin() called with empty $conds' );
2917 $delTable = $this->tableName( $delTable );
2918 $joinTable = $this->tableName( $joinTable );
2919 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2920 if ( $conds != '*' ) {
2921 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2923 $sql .= ')';
2925 $this->query( $sql, $fname );
2929 * Returns the size of a text field, or -1 for "unlimited"
2931 * @param string $table
2932 * @param string $field
2933 * @return int
2935 public function textFieldSize( $table, $field ) {
2936 $table = $this->tableName( $table );
2937 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2938 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2939 $row = $this->fetchObject( $res );
2941 $m = array();
2943 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2944 $size = $m[1];
2945 } else {
2946 $size = -1;
2949 return $size;
2953 * A string to insert into queries to show that they're low-priority, like
2954 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2955 * string and nothing bad should happen.
2957 * @return string Returns the text of the low priority option if it is
2958 * supported, or a blank string otherwise
2960 public function lowPriorityOption() {
2961 return '';
2965 * DELETE query wrapper.
2967 * @param array $table Table name
2968 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2969 * for the format. Use $conds == "*" to delete all rows
2970 * @param string $fname Name of the calling function
2971 * @throws DBUnexpectedError
2972 * @return bool|ResultWrapper
2974 public function delete( $table, $conds, $fname = __METHOD__ ) {
2975 if ( !$conds ) {
2976 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2979 $table = $this->tableName( $table );
2980 $sql = "DELETE FROM $table";
2982 if ( $conds != '*' ) {
2983 if ( is_array( $conds ) ) {
2984 $conds = $this->makeList( $conds, LIST_AND );
2986 $sql .= ' WHERE ' . $conds;
2989 return $this->query( $sql, $fname );
2993 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2994 * into another table.
2996 * @param string $destTable The table name to insert into
2997 * @param string|array $srcTable May be either a table name, or an array of table names
2998 * to include in a join.
3000 * @param array $varMap Must be an associative array of the form
3001 * array( 'dest1' => 'source1', ...). Source items may be literals
3002 * rather than field names, but strings should be quoted with
3003 * DatabaseBase::addQuotes()
3005 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3006 * the details of the format of condition arrays. May be "*" to copy the
3007 * whole table.
3009 * @param string $fname The function name of the caller, from __METHOD__
3011 * @param array $insertOptions Options for the INSERT part of the query, see
3012 * DatabaseBase::insert() for details.
3013 * @param array $selectOptions Options for the SELECT part of the query, see
3014 * DatabaseBase::select() for details.
3016 * @return ResultWrapper
3018 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3019 $fname = __METHOD__,
3020 $insertOptions = array(), $selectOptions = array()
3022 $destTable = $this->tableName( $destTable );
3024 if ( !is_array( $insertOptions ) ) {
3025 $insertOptions = array( $insertOptions );
3028 $insertOptions = $this->makeInsertOptions( $insertOptions );
3030 if ( !is_array( $selectOptions ) ) {
3031 $selectOptions = array( $selectOptions );
3034 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3036 if ( is_array( $srcTable ) ) {
3037 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3038 } else {
3039 $srcTable = $this->tableName( $srcTable );
3042 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3043 " SELECT $startOpts " . implode( ',', $varMap ) .
3044 " FROM $srcTable $useIndex ";
3046 if ( $conds != '*' ) {
3047 if ( is_array( $conds ) ) {
3048 $conds = $this->makeList( $conds, LIST_AND );
3050 $sql .= " WHERE $conds";
3053 $sql .= " $tailOpts";
3055 return $this->query( $sql, $fname );
3059 * Construct a LIMIT query with optional offset. This is used for query
3060 * pages. The SQL should be adjusted so that only the first $limit rows
3061 * are returned. If $offset is provided as well, then the first $offset
3062 * rows should be discarded, and the next $limit rows should be returned.
3063 * If the result of the query is not ordered, then the rows to be returned
3064 * are theoretically arbitrary.
3066 * $sql is expected to be a SELECT, if that makes a difference.
3068 * The version provided by default works in MySQL and SQLite. It will very
3069 * likely need to be overridden for most other DBMSes.
3071 * @param string $sql SQL query we will append the limit too
3072 * @param int $limit The SQL limit
3073 * @param int|bool $offset The SQL offset (default false)
3074 * @throws DBUnexpectedError
3075 * @return string
3077 public function limitResult( $sql, $limit, $offset = false ) {
3078 if ( !is_numeric( $limit ) ) {
3079 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3082 return "$sql LIMIT "
3083 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3084 . "{$limit} ";
3088 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3089 * within the UNION construct.
3090 * @return bool
3092 public function unionSupportsOrderAndLimit() {
3093 return true; // True for almost every DB supported
3097 * Construct a UNION query
3098 * This is used for providing overload point for other DB abstractions
3099 * not compatible with the MySQL syntax.
3100 * @param array $sqls SQL statements to combine
3101 * @param bool $all Use UNION ALL
3102 * @return string SQL fragment
3104 public function unionQueries( $sqls, $all ) {
3105 $glue = $all ? ') UNION ALL (' : ') UNION (';
3107 return '(' . implode( $glue, $sqls ) . ')';
3111 * Returns an SQL expression for a simple conditional. This doesn't need
3112 * to be overridden unless CASE isn't supported in your DBMS.
3114 * @param string|array $cond SQL expression which will result in a boolean value
3115 * @param string $trueVal SQL expression to return if true
3116 * @param string $falseVal SQL expression to return if false
3117 * @return string SQL fragment
3119 public function conditional( $cond, $trueVal, $falseVal ) {
3120 if ( is_array( $cond ) ) {
3121 $cond = $this->makeList( $cond, LIST_AND );
3124 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3128 * Returns a comand for str_replace function in SQL query.
3129 * Uses REPLACE() in MySQL
3131 * @param string $orig Column to modify
3132 * @param string $old Column to seek
3133 * @param string $new Column to replace with
3135 * @return string
3137 public function strreplace( $orig, $old, $new ) {
3138 return "REPLACE({$orig}, {$old}, {$new})";
3142 * Determines how long the server has been up
3143 * STUB
3145 * @return int
3147 public function getServerUptime() {
3148 return 0;
3152 * Determines if the last failure was due to a deadlock
3153 * STUB
3155 * @return bool
3157 public function wasDeadlock() {
3158 return false;
3162 * Determines if the last failure was due to a lock timeout
3163 * STUB
3165 * @return bool
3167 public function wasLockTimeout() {
3168 return false;
3172 * Determines if the last query error was something that should be dealt
3173 * with by pinging the connection and reissuing the query.
3174 * STUB
3176 * @return bool
3178 public function wasErrorReissuable() {
3179 return false;
3183 * Determines if the last failure was due to the database being read-only.
3184 * STUB
3186 * @return bool
3188 public function wasReadOnlyError() {
3189 return false;
3193 * Perform a deadlock-prone transaction.
3195 * This function invokes a callback function to perform a set of write
3196 * queries. If a deadlock occurs during the processing, the transaction
3197 * will be rolled back and the callback function will be called again.
3199 * Usage:
3200 * $dbw->deadlockLoop( callback, ... );
3202 * Extra arguments are passed through to the specified callback function.
3204 * Returns whatever the callback function returned on its successful,
3205 * iteration, or false on error, for example if the retry limit was
3206 * reached.
3208 * @return bool
3210 public function deadlockLoop() {
3211 $args = func_get_args();
3212 $function = array_shift( $args );
3213 $tries = self::DEADLOCK_TRIES;
3214 if ( is_array( $function ) ) {
3215 $fname = $function[0];
3216 } else {
3217 $fname = $function;
3220 $this->begin( __METHOD__ );
3222 $e = null;
3223 do {
3224 try {
3225 $retVal = call_user_func_array( $function, $args );
3226 break;
3227 } catch ( DBQueryError $e ) {
3228 $error = $this->lastError();
3229 $errno = $this->lastErrno();
3230 $sql = $this->lastQuery();
3231 if ( $this->wasDeadlock() ) {
3232 // Retry after a randomized delay
3233 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3234 } else {
3235 // Throw the error back up
3236 throw $e;
3239 } while ( --$tries > 0 );
3241 if ( $tries <= 0 ) {
3242 // Too many deadlocks; give up
3243 $this->rollback( __METHOD__ );
3244 throw $e;
3245 } else {
3246 $this->commit( __METHOD__ );
3248 return $retVal;
3253 * Wait for the slave to catch up to a given master position.
3255 * @param DBMasterPos $pos
3256 * @param int $timeout The maximum number of seconds to wait for
3257 * synchronisation
3258 * @return int Zero if the slave was past that position already,
3259 * greater than zero if we waited for some period of time, less than
3260 * zero if we timed out.
3262 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3263 # Real waits are implemented in the subclass.
3264 return 0;
3268 * Get the replication position of this slave
3270 * @return DBMasterPos|bool False if this is not a slave.
3272 public function getSlavePos() {
3273 # Stub
3274 return false;
3278 * Get the position of this master
3280 * @return DBMasterPos|bool False if this is not a master
3282 public function getMasterPos() {
3283 # Stub
3284 return false;
3288 * Run an anonymous function as soon as there is no transaction pending.
3289 * If there is a transaction and it is rolled back, then the callback is cancelled.
3290 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3291 * Callbacks must commit any transactions that they begin.
3293 * This is useful for updates to different systems or when separate transactions are needed.
3294 * For example, one might want to enqueue jobs into a system outside the database, but only
3295 * after the database is updated so that the jobs will see the data when they actually run.
3296 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3298 * @param callable $callback
3299 * @since 1.20
3301 final public function onTransactionIdle( $callback ) {
3302 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3303 if ( !$this->mTrxLevel ) {
3304 $this->runOnTransactionIdleCallbacks();
3309 * Run an anonymous function before the current transaction commits or now if there is none.
3310 * If there is a transaction and it is rolled back, then the callback is cancelled.
3311 * Callbacks must not start nor commit any transactions.
3313 * This is useful for updates that easily cause deadlocks if locks are held too long
3314 * but where atomicity is strongly desired for these updates and some related updates.
3316 * @param callable $callback
3317 * @since 1.22
3319 final public function onTransactionPreCommitOrIdle( $callback ) {
3320 if ( $this->mTrxLevel ) {
3321 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3322 } else {
3323 $this->onTransactionIdle( $callback ); // this will trigger immediately
3328 * Actually any "on transaction idle" callbacks.
3330 * @since 1.20
3332 protected function runOnTransactionIdleCallbacks() {
3333 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3335 $e = $ePrior = null; // last exception
3336 do { // callbacks may add callbacks :)
3337 $callbacks = $this->mTrxIdleCallbacks;
3338 $this->mTrxIdleCallbacks = array(); // recursion guard
3339 foreach ( $callbacks as $callback ) {
3340 try {
3341 list( $phpCallback ) = $callback;
3342 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3343 call_user_func( $phpCallback );
3344 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3345 } catch ( Exception $e ) {
3346 if ( $ePrior ) {
3347 MWExceptionHandler::logException( $ePrior );
3349 $ePrior = $e;
3352 } while ( count( $this->mTrxIdleCallbacks ) );
3354 if ( $e instanceof Exception ) {
3355 throw $e; // re-throw any last exception
3360 * Actually any "on transaction pre-commit" callbacks.
3362 * @since 1.22
3364 protected function runOnTransactionPreCommitCallbacks() {
3365 $e = $ePrior = null; // last exception
3366 do { // callbacks may add callbacks :)
3367 $callbacks = $this->mTrxPreCommitCallbacks;
3368 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3369 foreach ( $callbacks as $callback ) {
3370 try {
3371 list( $phpCallback ) = $callback;
3372 call_user_func( $phpCallback );
3373 } catch ( Exception $e ) {
3374 if ( $ePrior ) {
3375 MWExceptionHandler::logException( $ePrior );
3377 $ePrior = $e;
3380 } while ( count( $this->mTrxPreCommitCallbacks ) );
3382 if ( $e instanceof Exception ) {
3383 throw $e; // re-throw any last exception
3388 * Begin an atomic section of statements
3390 * If a transaction has been started already, just keep track of the given
3391 * section name to make sure the transaction is not committed pre-maturely.
3392 * This function can be used in layers (with sub-sections), so use a stack
3393 * to keep track of the different atomic sections. If there is no transaction,
3394 * start one implicitly.
3396 * The goal of this function is to create an atomic section of SQL queries
3397 * without having to start a new transaction if it already exists.
3399 * Atomic sections are more strict than transactions. With transactions,
3400 * attempting to begin a new transaction when one is already running results
3401 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3402 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3403 * and any database transactions cannot be began or committed until all atomic
3404 * levels are closed. There is no such thing as implicitly opening or closing
3405 * an atomic section.
3407 * @since 1.23
3408 * @param string $fname
3409 * @throws DBError
3411 final public function startAtomic( $fname = __METHOD__ ) {
3412 if ( !$this->mTrxLevel ) {
3413 $this->begin( $fname );
3414 $this->mTrxAutomatic = true;
3415 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3416 // in all changes being in one transaction to keep requests transactional.
3417 if ( !$this->getFlag( DBO_TRX ) ) {
3418 $this->mTrxAutomaticAtomic = true;
3422 $this->mTrxAtomicLevels->push( $fname );
3426 * Ends an atomic section of SQL statements
3428 * Ends the next section of atomic SQL statements and commits the transaction
3429 * if necessary.
3431 * @since 1.23
3432 * @see DatabaseBase::startAtomic
3433 * @param string $fname
3434 * @throws DBError
3436 final public function endAtomic( $fname = __METHOD__ ) {
3437 if ( !$this->mTrxLevel ) {
3438 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3440 if ( $this->mTrxAtomicLevels->isEmpty() ||
3441 $this->mTrxAtomicLevels->pop() !== $fname
3443 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3446 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3447 $this->commit( $fname, 'flush' );
3452 * Begin a transaction. If a transaction is already in progress,
3453 * that transaction will be committed before the new transaction is started.
3455 * Note that when the DBO_TRX flag is set (which is usually the case for web
3456 * requests, but not for maintenance scripts), any previous database query
3457 * will have started a transaction automatically.
3459 * Nesting of transactions is not supported. Attempts to nest transactions
3460 * will cause a warning, unless the current transaction was started
3461 * automatically because of the DBO_TRX flag.
3463 * @param string $fname
3464 * @throws DBError
3466 final public function begin( $fname = __METHOD__ ) {
3467 global $wgDebugDBTransactions;
3469 if ( $this->mTrxLevel ) { // implicit commit
3470 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3471 // If the current transaction was an automatic atomic one, then we definitely have
3472 // a problem. Same if there is any unclosed atomic level.
3473 throw new DBUnexpectedError( $this,
3474 "Attempted to start explicit transaction when atomic levels are still open."
3476 } elseif ( !$this->mTrxAutomatic ) {
3477 // We want to warn about inadvertently nested begin/commit pairs, but not about
3478 // auto-committing implicit transactions that were started by query() via DBO_TRX
3479 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3480 " performing implicit commit!";
3481 wfWarn( $msg );
3482 wfLogDBError( $msg,
3483 $this->getLogContext( array(
3484 'method' => __METHOD__,
3485 'fname' => $fname,
3488 } else {
3489 // if the transaction was automatic and has done write operations,
3490 // log it if $wgDebugDBTransactions is enabled.
3491 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3492 wfDebug( "$fname: Automatic transaction with writes in progress" .
3493 " (from {$this->mTrxFname}), performing implicit commit!\n"
3498 $this->runOnTransactionPreCommitCallbacks();
3499 $writeTime = $this->pendingWriteQueryDuration();
3500 $this->doCommit( $fname );
3501 if ( $this->mTrxDoneWrites ) {
3502 $this->mDoneWrites = microtime( true );
3503 $this->getTransactionProfiler()->transactionWritingOut(
3504 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3506 $this->runOnTransactionIdleCallbacks();
3509 # Avoid fatals if close() was called
3510 $this->assertOpen();
3512 $this->doBegin( $fname );
3513 $this->mTrxTimestamp = microtime( true );
3514 $this->mTrxFname = $fname;
3515 $this->mTrxDoneWrites = false;
3516 $this->mTrxAutomatic = false;
3517 $this->mTrxAutomaticAtomic = false;
3518 $this->mTrxAtomicLevels = new SplStack;
3519 $this->mTrxIdleCallbacks = array();
3520 $this->mTrxPreCommitCallbacks = array();
3521 $this->mTrxShortId = wfRandomString( 12 );
3522 $this->mTrxWriteDuration = 0.0;
3526 * Issues the BEGIN command to the database server.
3528 * @see DatabaseBase::begin()
3529 * @param string $fname
3531 protected function doBegin( $fname ) {
3532 $this->query( 'BEGIN', $fname );
3533 $this->mTrxLevel = 1;
3537 * Commits a transaction previously started using begin().
3538 * If no transaction is in progress, a warning is issued.
3540 * Nesting of transactions is not supported.
3542 * @param string $fname
3543 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3544 * explicitly committing implicit transactions, or calling commit when no
3545 * transaction is in progress. This will silently break any ongoing
3546 * explicit transaction. Only set the flush flag if you are sure that it
3547 * is safe to ignore these warnings in your context.
3548 * @throws DBUnexpectedError
3550 final public function commit( $fname = __METHOD__, $flush = '' ) {
3551 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3552 // There are still atomic sections open. This cannot be ignored
3553 throw new DBUnexpectedError(
3554 $this,
3555 "Attempted to commit transaction while atomic sections are still open"
3559 if ( $flush === 'flush' ) {
3560 if ( !$this->mTrxLevel ) {
3561 return; // nothing to do
3562 } elseif ( !$this->mTrxAutomatic ) {
3563 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3565 } else {
3566 if ( !$this->mTrxLevel ) {
3567 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3568 return; // nothing to do
3569 } elseif ( $this->mTrxAutomatic ) {
3570 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3574 # Avoid fatals if close() was called
3575 $this->assertOpen();
3577 $this->runOnTransactionPreCommitCallbacks();
3578 $writeTime = $this->pendingWriteQueryDuration();
3579 $this->doCommit( $fname );
3580 if ( $this->mTrxDoneWrites ) {
3581 $this->mDoneWrites = microtime( true );
3582 $this->getTransactionProfiler()->transactionWritingOut(
3583 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3585 $this->runOnTransactionIdleCallbacks();
3589 * Issues the COMMIT command to the database server.
3591 * @see DatabaseBase::commit()
3592 * @param string $fname
3594 protected function doCommit( $fname ) {
3595 if ( $this->mTrxLevel ) {
3596 $this->query( 'COMMIT', $fname );
3597 $this->mTrxLevel = 0;
3602 * Rollback a transaction previously started using begin().
3603 * If no transaction is in progress, a warning is issued.
3605 * No-op on non-transactional databases.
3607 * @param string $fname
3608 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3609 * calling rollback when no transaction is in progress. This will silently
3610 * break any ongoing explicit transaction. Only set the flush flag if you
3611 * are sure that it is safe to ignore these warnings in your context.
3612 * @throws DBUnexpectedError
3613 * @since 1.23 Added $flush parameter
3615 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3616 if ( $flush !== 'flush' ) {
3617 if ( !$this->mTrxLevel ) {
3618 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3619 return; // nothing to do
3620 } elseif ( $this->mTrxAutomatic ) {
3621 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3623 } else {
3624 if ( !$this->mTrxLevel ) {
3625 return; // nothing to do
3626 } elseif ( !$this->mTrxAutomatic ) {
3627 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3631 # Avoid fatals if close() was called
3632 $this->assertOpen();
3634 $this->doRollback( $fname );
3635 $this->mTrxIdleCallbacks = array(); // cancel
3636 $this->mTrxPreCommitCallbacks = array(); // cancel
3637 $this->mTrxAtomicLevels = new SplStack;
3638 if ( $this->mTrxDoneWrites ) {
3639 $this->getTransactionProfiler()->transactionWritingOut(
3640 $this->mServer, $this->mDBname, $this->mTrxShortId );
3645 * Issues the ROLLBACK command to the database server.
3647 * @see DatabaseBase::rollback()
3648 * @param string $fname
3650 protected function doRollback( $fname ) {
3651 if ( $this->mTrxLevel ) {
3652 $this->query( 'ROLLBACK', $fname, true );
3653 $this->mTrxLevel = 0;
3658 * Creates a new table with structure copied from existing table
3659 * Note that unlike most database abstraction functions, this function does not
3660 * automatically append database prefix, because it works at a lower
3661 * abstraction level.
3662 * The table names passed to this function shall not be quoted (this
3663 * function calls addIdentifierQuotes when needed).
3665 * @param string $oldName Name of table whose structure should be copied
3666 * @param string $newName Name of table to be created
3667 * @param bool $temporary Whether the new table should be temporary
3668 * @param string $fname Calling function name
3669 * @throws MWException
3670 * @return bool True if operation was successful
3672 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3673 $fname = __METHOD__
3675 throw new MWException(
3676 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3680 * List all tables on the database
3682 * @param string $prefix Only show tables with this prefix, e.g. mw_
3683 * @param string $fname Calling function name
3684 * @throws MWException
3685 * @return array
3687 function listTables( $prefix = null, $fname = __METHOD__ ) {
3688 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3692 * Reset the views process cache set by listViews()
3693 * @since 1.22
3695 final public function clearViewsCache() {
3696 $this->allViews = null;
3700 * Lists all the VIEWs in the database
3702 * For caching purposes the list of all views should be stored in
3703 * $this->allViews. The process cache can be cleared with clearViewsCache()
3705 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3706 * @param string $fname Name of calling function
3707 * @throws MWException
3708 * @return array
3709 * @since 1.22
3711 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3712 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3716 * Differentiates between a TABLE and a VIEW
3718 * @param string $name Name of the database-structure to test.
3719 * @throws MWException
3720 * @return bool
3721 * @since 1.22
3723 public function isView( $name ) {
3724 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3728 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3729 * to the format used for inserting into timestamp fields in this DBMS.
3731 * The result is unquoted, and needs to be passed through addQuotes()
3732 * before it can be included in raw SQL.
3734 * @param string|int $ts
3736 * @return string
3738 public function timestamp( $ts = 0 ) {
3739 return wfTimestamp( TS_MW, $ts );
3743 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3744 * to the format used for inserting into timestamp fields in this DBMS. If
3745 * NULL is input, it is passed through, allowing NULL values to be inserted
3746 * into timestamp fields.
3748 * The result is unquoted, and needs to be passed through addQuotes()
3749 * before it can be included in raw SQL.
3751 * @param string|int $ts
3753 * @return string
3755 public function timestampOrNull( $ts = null ) {
3756 if ( is_null( $ts ) ) {
3757 return null;
3758 } else {
3759 return $this->timestamp( $ts );
3764 * Take the result from a query, and wrap it in a ResultWrapper if
3765 * necessary. Boolean values are passed through as is, to indicate success
3766 * of write queries or failure.
3768 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3769 * resource, and it was necessary to call this function to convert it to
3770 * a wrapper. Nowadays, raw database objects are never exposed to external
3771 * callers, so this is unnecessary in external code. For compatibility with
3772 * old code, ResultWrapper objects are passed through unaltered.
3774 * @param bool|ResultWrapper|resource $result
3775 * @return bool|ResultWrapper
3777 public function resultObject( $result ) {
3778 if ( empty( $result ) ) {
3779 return false;
3780 } elseif ( $result instanceof ResultWrapper ) {
3781 return $result;
3782 } elseif ( $result === true ) {
3783 // Successful write query
3784 return $result;
3785 } else {
3786 return new ResultWrapper( $this, $result );
3791 * Ping the server and try to reconnect if it there is no connection
3793 * @return bool Success or failure
3795 public function ping() {
3796 # Stub. Not essential to override.
3797 return true;
3801 * Get slave lag. Currently supported only by MySQL.
3803 * Note that this function will generate a fatal error on many
3804 * installations. Most callers should use LoadBalancer::safeGetLag()
3805 * instead.
3807 * @return int Database replication lag in seconds
3809 public function getLag() {
3810 return 0;
3814 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3816 * @return int
3818 function maxListLen() {
3819 return 0;
3823 * Some DBMSs have a special format for inserting into blob fields, they
3824 * don't allow simple quoted strings to be inserted. To insert into such
3825 * a field, pass the data through this function before passing it to
3826 * DatabaseBase::insert().
3828 * @param string $b
3829 * @return string
3831 public function encodeBlob( $b ) {
3832 return $b;
3836 * Some DBMSs return a special placeholder object representing blob fields
3837 * in result objects. Pass the object through this function to return the
3838 * original string.
3840 * @param string|Blob $b
3841 * @return string
3843 public function decodeBlob( $b ) {
3844 if ( $b instanceof Blob ) {
3845 $b = $b->fetch();
3847 return $b;
3851 * Override database's default behavior. $options include:
3852 * 'connTimeout' : Set the connection timeout value in seconds.
3853 * May be useful for very long batch queries such as
3854 * full-wiki dumps, where a single query reads out over
3855 * hours or days.
3857 * @param array $options
3858 * @return void
3860 public function setSessionOptions( array $options ) {
3864 * Read and execute SQL commands from a file.
3866 * Returns true on success, error string or exception on failure (depending
3867 * on object's error ignore settings).
3869 * @param string $filename File name to open
3870 * @param bool|callable $lineCallback Optional function called before reading each line
3871 * @param bool|callable $resultCallback Optional function called for each MySQL result
3872 * @param bool|string $fname Calling function name or false if name should be
3873 * generated dynamically using $filename
3874 * @param bool|callable $inputCallback Optional function called for each
3875 * complete line sent
3876 * @throws Exception|MWException
3877 * @return bool|string
3879 public function sourceFile(
3880 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3882 MediaWiki\suppressWarnings();
3883 $fp = fopen( $filename, 'r' );
3884 MediaWiki\restoreWarnings();
3886 if ( false === $fp ) {
3887 throw new MWException( "Could not open \"{$filename}\".\n" );
3890 if ( !$fname ) {
3891 $fname = __METHOD__ . "( $filename )";
3894 try {
3895 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3896 } catch ( Exception $e ) {
3897 fclose( $fp );
3898 throw $e;
3901 fclose( $fp );
3903 return $error;
3907 * Get the full path of a patch file. Originally based on archive()
3908 * from updaters.inc. Keep in mind this always returns a patch, as
3909 * it fails back to MySQL if no DB-specific patch can be found
3911 * @param string $patch The name of the patch, like patch-something.sql
3912 * @return string Full path to patch file
3914 public function patchPath( $patch ) {
3915 global $IP;
3917 $dbType = $this->getType();
3918 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3919 return "$IP/maintenance/$dbType/archives/$patch";
3920 } else {
3921 return "$IP/maintenance/archives/$patch";
3926 * Set variables to be used in sourceFile/sourceStream, in preference to the
3927 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3928 * all. If it's set to false, $GLOBALS will be used.
3930 * @param bool|array $vars Mapping variable name to value.
3932 public function setSchemaVars( $vars ) {
3933 $this->mSchemaVars = $vars;
3937 * Read and execute commands from an open file handle.
3939 * Returns true on success, error string or exception on failure (depending
3940 * on object's error ignore settings).
3942 * @param resource $fp File handle
3943 * @param bool|callable $lineCallback Optional function called before reading each query
3944 * @param bool|callable $resultCallback Optional function called for each MySQL result
3945 * @param string $fname Calling function name
3946 * @param bool|callable $inputCallback Optional function called for each complete query sent
3947 * @return bool|string
3949 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3950 $fname = __METHOD__, $inputCallback = false
3952 $cmd = '';
3954 while ( !feof( $fp ) ) {
3955 if ( $lineCallback ) {
3956 call_user_func( $lineCallback );
3959 $line = trim( fgets( $fp ) );
3961 if ( $line == '' ) {
3962 continue;
3965 if ( '-' == $line[0] && '-' == $line[1] ) {
3966 continue;
3969 if ( $cmd != '' ) {
3970 $cmd .= ' ';
3973 $done = $this->streamStatementEnd( $cmd, $line );
3975 $cmd .= "$line\n";
3977 if ( $done || feof( $fp ) ) {
3978 $cmd = $this->replaceVars( $cmd );
3980 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3981 $res = $this->query( $cmd, $fname );
3983 if ( $resultCallback ) {
3984 call_user_func( $resultCallback, $res, $this );
3987 if ( false === $res ) {
3988 $err = $this->lastError();
3990 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3993 $cmd = '';
3997 return true;
4001 * Called by sourceStream() to check if we've reached a statement end
4003 * @param string $sql SQL assembled so far
4004 * @param string $newLine New line about to be added to $sql
4005 * @return bool Whether $newLine contains end of the statement
4007 public function streamStatementEnd( &$sql, &$newLine ) {
4008 if ( $this->delimiter ) {
4009 $prev = $newLine;
4010 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4011 if ( $newLine != $prev ) {
4012 return true;
4016 return false;
4020 * Database independent variable replacement. Replaces a set of variables
4021 * in an SQL statement with their contents as given by $this->getSchemaVars().
4023 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4025 * - '{$var}' should be used for text and is passed through the database's
4026 * addQuotes method.
4027 * - `{$var}` should be used for identifiers (e.g. table and database names).
4028 * It is passed through the database's addIdentifierQuotes method which
4029 * can be overridden if the database uses something other than backticks.
4030 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4031 * database's tableName method.
4032 * - / *i* / passes the name that follows through the database's indexName method.
4033 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4034 * its use should be avoided. In 1.24 and older, string encoding was applied.
4036 * @param string $ins SQL statement to replace variables in
4037 * @return string The new SQL statement with variables replaced
4039 protected function replaceVars( $ins ) {
4040 $that = $this;
4041 $vars = $this->getSchemaVars();
4042 return preg_replace_callback(
4044 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4045 \'\{\$ (\w+) }\' | # 3. addQuotes
4046 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4047 /\*\$ (\w+) \*/ # 5. leave unencoded
4048 !x',
4049 function ( $m ) use ( $that, $vars ) {
4050 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4051 // check for both nonexistent keys *and* the empty string.
4052 if ( isset( $m[1] ) && $m[1] !== '' ) {
4053 if ( $m[1] === 'i' ) {
4054 return $that->indexName( $m[2] );
4055 } else {
4056 return $that->tableName( $m[2] );
4058 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4059 return $that->addQuotes( $vars[$m[3]] );
4060 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4061 return $that->addIdentifierQuotes( $vars[$m[4]] );
4062 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4063 return $vars[$m[5]];
4064 } else {
4065 return $m[0];
4068 $ins
4073 * Get schema variables. If none have been set via setSchemaVars(), then
4074 * use some defaults from the current object.
4076 * @return array
4078 protected function getSchemaVars() {
4079 if ( $this->mSchemaVars ) {
4080 return $this->mSchemaVars;
4081 } else {
4082 return $this->getDefaultSchemaVars();
4087 * Get schema variables to use if none have been set via setSchemaVars().
4089 * Override this in derived classes to provide variables for tables.sql
4090 * and SQL patch files.
4092 * @return array
4094 protected function getDefaultSchemaVars() {
4095 return array();
4099 * Check to see if a named lock is available (non-blocking)
4101 * @param string $lockName Name of lock to poll
4102 * @param string $method Name of method calling us
4103 * @return bool
4104 * @since 1.20
4106 public function lockIsFree( $lockName, $method ) {
4107 return true;
4111 * Acquire a named lock
4113 * Named locks are not related to transactions
4115 * @param string $lockName Name of lock to aquire
4116 * @param string $method Name of method calling us
4117 * @param int $timeout
4118 * @return bool
4120 public function lock( $lockName, $method, $timeout = 5 ) {
4121 return true;
4125 * Release a lock
4127 * Named locks are not related to transactions
4129 * @param string $lockName Name of lock to release
4130 * @param string $method Name of method calling us
4132 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4133 * by this thread (in which case the lock is not released), and NULL if the named
4134 * lock did not exist
4136 public function unlock( $lockName, $method ) {
4137 return true;
4141 * Check to see if a named lock used by lock() use blocking queues
4143 * @return bool
4144 * @since 1.26
4146 public function namedLocksEnqueue() {
4147 return false;
4151 * Lock specific tables
4153 * @param array $read Array of tables to lock for read access
4154 * @param array $write Array of tables to lock for write access
4155 * @param string $method Name of caller
4156 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4157 * @return bool
4159 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4160 return true;
4164 * Unlock specific tables
4166 * @param string $method The caller
4167 * @return bool
4169 public function unlockTables( $method ) {
4170 return true;
4174 * Delete a table
4175 * @param string $tableName
4176 * @param string $fName
4177 * @return bool|ResultWrapper
4178 * @since 1.18
4180 public function dropTable( $tableName, $fName = __METHOD__ ) {
4181 if ( !$this->tableExists( $tableName, $fName ) ) {
4182 return false;
4184 $sql = "DROP TABLE " . $this->tableName( $tableName );
4185 if ( $this->cascadingDeletes() ) {
4186 $sql .= " CASCADE";
4189 return $this->query( $sql, $fName );
4193 * Get search engine class. All subclasses of this need to implement this
4194 * if they wish to use searching.
4196 * @return string
4198 public function getSearchEngine() {
4199 return 'SearchEngineDummy';
4203 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4204 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4205 * because "i" sorts after all numbers.
4207 * @return string
4209 public function getInfinity() {
4210 return 'infinity';
4214 * Encode an expiry time into the DBMS dependent format
4216 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4217 * @return string
4219 public function encodeExpiry( $expiry ) {
4220 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4221 ? $this->getInfinity()
4222 : $this->timestamp( $expiry );
4226 * Decode an expiry time into a DBMS independent format
4228 * @param string $expiry DB timestamp field value for expiry
4229 * @param int $format TS_* constant, defaults to TS_MW
4230 * @return string
4232 public function decodeExpiry( $expiry, $format = TS_MW ) {
4233 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4234 ? 'infinity'
4235 : wfTimestamp( $format, $expiry );
4239 * Allow or deny "big selects" for this session only. This is done by setting
4240 * the sql_big_selects session variable.
4242 * This is a MySQL-specific feature.
4244 * @param bool|string $value True for allow, false for deny, or "default" to
4245 * restore the initial value
4247 public function setBigSelects( $value = true ) {
4248 // no-op
4252 * @since 1.19
4253 * @return string
4255 public function __toString() {
4256 return (string)$this->mConn;
4260 * Run a few simple sanity checks
4262 public function __destruct() {
4263 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4264 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4266 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4267 $callers = array();
4268 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4269 $callers[] = $callbackInfo[1];
4271 $callers = implode( ', ', $callers );
4272 trigger_error( "DB transaction callbacks still pending (from $callers)." );