jquery.tablesorter: Improve detection and handling of isoDate
[mediawiki.git] / includes / db / Database.php
blob1e54f55457a0da3cfe08fbbc6c6236261a3b9386
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 $mLBInfo = array();
62 protected $mDefaultBigSelects = null;
63 protected $mSchemaVars = false;
64 /** @var array */
65 protected $mSessionVars = array();
67 protected $preparedArgs;
69 protected $htmlErrors;
71 protected $delimiter = ';';
73 /**
74 * Either 1 if a transaction is active or 0 otherwise.
75 * The other Trx fields may not be meaningfull if this is 0.
77 * @var int
79 protected $mTrxLevel = 0;
81 /**
82 * Either a short hexidecimal string if a transaction is active or ""
84 * @var string
85 * @see DatabaseBase::mTrxLevel
87 protected $mTrxShortId = '';
89 /**
90 * The UNIX time that the transaction started. Callers can assume that if
91 * snapshot isolation is used, then the data is *at least* up to date to that
92 * point (possibly more up-to-date since the first SELECT defines the snapshot).
94 * @var float|null
95 * @see DatabaseBase::mTrxLevel
97 private $mTrxTimestamp = null;
99 /**
100 * Remembers the function name given for starting the most recent transaction via begin().
101 * Used to provide additional context for error reporting.
103 * @var string
104 * @see DatabaseBase::mTrxLevel
106 private $mTrxFname = null;
109 * Record if possible write queries were done in the last transaction started
111 * @var bool
112 * @see DatabaseBase::mTrxLevel
114 private $mTrxDoneWrites = false;
117 * Record if the current transaction was started implicitly due to DBO_TRX being set.
119 * @var bool
120 * @see DatabaseBase::mTrxLevel
122 private $mTrxAutomatic = false;
125 * Array of levels of atomicity within transactions
127 * @var SplStack
129 private $mTrxAtomicLevels;
132 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
134 * @var bool
136 private $mTrxAutomaticAtomic = false;
139 * Track the seconds spent in write queries for the current transaction
141 * @var float
143 private $mTrxWriteDuration = 0.0;
146 * @since 1.21
147 * @var resource File handle for upgrade
149 protected $fileHandle = null;
152 * @since 1.22
153 * @var string[] Process cache of VIEWs names in the database
155 protected $allViews = null;
157 /** @var TransactionProfiler */
158 protected $trxProfiler;
161 * A string describing the current software version, and possibly
162 * other details in a user-friendly way. Will be listed on Special:Version, etc.
163 * Use getServerVersion() to get machine-friendly information.
165 * @return string Version information from the database server
167 public function getServerInfo() {
168 return $this->getServerVersion();
172 * @return string Command delimiter used by this database engine
174 public function getDelimiter() {
175 return $this->delimiter;
179 * Boolean, controls output of large amounts of debug information.
180 * @param bool|null $debug
181 * - true to enable debugging
182 * - false to disable debugging
183 * - omitted or null to do nothing
185 * @return bool|null Previous value of the flag
187 public function debug( $debug = null ) {
188 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
192 * Turns buffering of SQL result sets on (true) or off (false). Default is
193 * "on".
195 * Unbuffered queries are very troublesome in MySQL:
197 * - If another query is executed while the first query is being read
198 * out, the first query is killed. This means you can't call normal
199 * MediaWiki functions while you are reading an unbuffered query result
200 * from a normal wfGetDB() connection.
202 * - Unbuffered queries cause the MySQL server to use large amounts of
203 * memory and to hold broad locks which block other queries.
205 * If you want to limit client-side memory, it's almost always better to
206 * split up queries into batches using a LIMIT clause than to switch off
207 * buffering.
209 * @param null|bool $buffer
210 * @return null|bool The previous value of the flag
212 public function bufferResults( $buffer = null ) {
213 if ( is_null( $buffer ) ) {
214 return !(bool)( $this->mFlags & DBO_NOBUFFER );
215 } else {
216 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
221 * Turns on (false) or off (true) the automatic generation and sending
222 * of a "we're sorry, but there has been a database error" page on
223 * database errors. Default is on (false). When turned off, the
224 * code should use lastErrno() and lastError() to handle the
225 * situation as appropriate.
227 * Do not use this function outside of the Database classes.
229 * @param null|bool $ignoreErrors
230 * @return bool The previous value of the flag.
232 protected function ignoreErrors( $ignoreErrors = null ) {
233 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
237 * Gets the current transaction level.
239 * Historically, transactions were allowed to be "nested". This is no
240 * longer supported, so this function really only returns a boolean.
242 * @return int The previous value
244 public function trxLevel() {
245 return $this->mTrxLevel;
249 * Get the UNIX timestamp of the time that the transaction was established
251 * This can be used to reason about the staleness of SELECT data
252 * in REPEATABLE-READ transaction isolation level.
254 * @return float|null Returns null if there is not active transaction
255 * @since 1.25
257 public function trxTimestamp() {
258 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
262 * Get/set the table prefix.
263 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
264 * @return string The previous table prefix.
266 public function tablePrefix( $prefix = null ) {
267 return wfSetVar( $this->mTablePrefix, $prefix );
271 * Get/set the db schema.
272 * @param string $schema The database schema to set, or omitted to leave it unchanged.
273 * @return string The previous db schema.
275 public function dbSchema( $schema = null ) {
276 return wfSetVar( $this->mSchema, $schema );
280 * Set the filehandle to copy write statements to.
282 * @param resource $fh File handle
284 public function setFileHandle( $fh ) {
285 $this->fileHandle = $fh;
289 * Get properties passed down from the server info array of the load
290 * balancer.
292 * @param string $name The entry of the info array to get, or null to get the
293 * whole array
295 * @return array|mixed|null
297 public function getLBInfo( $name = null ) {
298 if ( is_null( $name ) ) {
299 return $this->mLBInfo;
300 } else {
301 if ( array_key_exists( $name, $this->mLBInfo ) ) {
302 return $this->mLBInfo[$name];
303 } else {
304 return null;
310 * Set the LB info array, or a member of it. If called with one parameter,
311 * the LB info array is set to that parameter. If it is called with two
312 * parameters, the member with the given name is set to the given value.
314 * @param string $name
315 * @param array $value
317 public function setLBInfo( $name, $value = null ) {
318 if ( is_null( $value ) ) {
319 $this->mLBInfo = $name;
320 } else {
321 $this->mLBInfo[$name] = $value;
326 * Set lag time in seconds for a fake slave
328 * @param mixed $lag Valid values for this parameter are determined by the
329 * subclass, but should be a PHP scalar or array that would be sensible
330 * as part of $wgLBFactoryConf.
332 public function setFakeSlaveLag( $lag ) {
336 * Make this connection a fake master
338 * @param bool $enabled
340 public function setFakeMaster( $enabled = true ) {
344 * @return TransactionProfiler
346 protected function getTransactionProfiler() {
347 return $this->trxProfiler
348 ? $this->trxProfiler
349 : Profiler::instance()->getTransactionProfiler();
353 * Returns true if this database supports (and uses) cascading deletes
355 * @return bool
357 public function cascadingDeletes() {
358 return false;
362 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
364 * @return bool
366 public function cleanupTriggers() {
367 return false;
371 * Returns true if this database is strict about what can be put into an IP field.
372 * Specifically, it uses a NULL value instead of an empty string.
374 * @return bool
376 public function strictIPs() {
377 return false;
381 * Returns true if this database uses timestamps rather than integers
383 * @return bool
385 public function realTimestamps() {
386 return false;
390 * Returns true if this database does an implicit sort when doing GROUP BY
392 * @return bool
394 public function implicitGroupby() {
395 return true;
399 * Returns true if this database does an implicit order by when the column has an index
400 * For example: SELECT page_title FROM page LIMIT 1
402 * @return bool
404 public function implicitOrderby() {
405 return true;
409 * Returns true if this database can do a native search on IP columns
410 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
412 * @return bool
414 public function searchableIPs() {
415 return false;
419 * Returns true if this database can use functional indexes
421 * @return bool
423 public function functionalIndexes() {
424 return false;
428 * Return the last query that went through DatabaseBase::query()
429 * @return string
431 public function lastQuery() {
432 return $this->mLastQuery;
436 * Returns true if the connection may have been used for write queries.
437 * Should return true if unsure.
439 * @return bool
441 public function doneWrites() {
442 return (bool)$this->mDoneWrites;
446 * Returns the last time the connection may have been used for write queries.
447 * Should return a timestamp if unsure.
449 * @return int|float UNIX timestamp or false
450 * @since 1.24
452 public function lastDoneWrites() {
453 return $this->mDoneWrites ?: false;
457 * Returns true if there is a transaction open with possible write
458 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
460 * @return bool
462 public function writesOrCallbacksPending() {
463 return $this->mTrxLevel && (
464 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
469 * Get the time spend running write queries for this
471 * High times could be due to scanning, updates, locking, and such
473 * @return float|bool Returns false if not transaction is active
474 * @since 1.26
476 public function pendingWriteQueryDuration() {
477 return $this->mTrxLevel ? $this->mTrxWriteDuration : false;
481 * Is a connection to the database open?
482 * @return bool
484 public function isOpen() {
485 return $this->mOpened;
489 * Set a flag for this connection
491 * @param int $flag DBO_* constants from Defines.php:
492 * - DBO_DEBUG: output some debug info (same as debug())
493 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
494 * - DBO_TRX: automatically start transactions
495 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
496 * and removes it in command line mode
497 * - DBO_PERSISTENT: use persistant database connection
499 public function setFlag( $flag ) {
500 global $wgDebugDBTransactions;
501 $this->mFlags |= $flag;
502 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
503 wfDebug( "Implicit transactions are now enabled.\n" );
508 * Clear a flag for this connection
510 * @param int $flag DBO_* constants from Defines.php:
511 * - DBO_DEBUG: output some debug info (same as debug())
512 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
513 * - DBO_TRX: automatically start transactions
514 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
515 * and removes it in command line mode
516 * - DBO_PERSISTENT: use persistant database connection
518 public function clearFlag( $flag ) {
519 global $wgDebugDBTransactions;
520 $this->mFlags &= ~$flag;
521 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
522 wfDebug( "Implicit transactions are now disabled.\n" );
527 * Returns a boolean whether the flag $flag is set for this connection
529 * @param int $flag DBO_* constants from Defines.php:
530 * - DBO_DEBUG: output some debug info (same as debug())
531 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
532 * - DBO_TRX: automatically start transactions
533 * - DBO_PERSISTENT: use persistant database connection
534 * @return bool
536 public function getFlag( $flag ) {
537 return !!( $this->mFlags & $flag );
541 * General read-only accessor
543 * @param string $name
544 * @return string
546 public function getProperty( $name ) {
547 return $this->$name;
551 * @return string
553 public function getWikiID() {
554 if ( $this->mTablePrefix ) {
555 return "{$this->mDBname}-{$this->mTablePrefix}";
556 } else {
557 return $this->mDBname;
562 * Return a path to the DBMS-specific SQL file if it exists,
563 * otherwise default SQL file
565 * @param string $filename
566 * @return string
568 private function getSqlFilePath( $filename ) {
569 global $IP;
570 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
571 if ( file_exists( $dbmsSpecificFilePath ) ) {
572 return $dbmsSpecificFilePath;
573 } else {
574 return "$IP/maintenance/$filename";
579 * Return a path to the DBMS-specific schema file,
580 * otherwise default to tables.sql
582 * @return string
584 public function getSchemaPath() {
585 return $this->getSqlFilePath( 'tables.sql' );
589 * Return a path to the DBMS-specific update key file,
590 * otherwise default to update-keys.sql
592 * @return string
594 public function getUpdateKeysPath() {
595 return $this->getSqlFilePath( 'update-keys.sql' );
599 * Get information about an index into an object
600 * @param string $table Table name
601 * @param string $index Index name
602 * @param string $fname Calling function name
603 * @return mixed Database-specific index description class or false if the index does not exist
605 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
608 * Wrapper for addslashes()
610 * @param string $s String to be slashed.
611 * @return string Slashed string.
613 abstract function strencode( $s );
616 * Constructor.
618 * FIXME: It is possible to construct a Database object with no associated
619 * connection object, by specifying no parameters to __construct(). This
620 * feature is deprecated and should be removed.
622 * DatabaseBase subclasses should not be constructed directly in external
623 * code. DatabaseBase::factory() should be used instead.
625 * @param array $params Parameters passed from DatabaseBase::factory()
627 function __construct( array $params ) {
628 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
630 $this->mTrxAtomicLevels = new SplStack;
632 $server = $params['host'];
633 $user = $params['user'];
634 $password = $params['password'];
635 $dbName = $params['dbname'];
636 $flags = $params['flags'];
637 $tablePrefix = $params['tablePrefix'];
638 $schema = $params['schema'];
639 $foreign = $params['foreign'];
641 $this->mFlags = $flags;
642 if ( $this->mFlags & DBO_DEFAULT ) {
643 if ( $wgCommandLineMode ) {
644 $this->mFlags &= ~DBO_TRX;
645 if ( $wgDebugDBTransactions ) {
646 wfDebug( "Implicit transaction open disabled.\n" );
648 } else {
649 $this->mFlags |= DBO_TRX;
650 if ( $wgDebugDBTransactions ) {
651 wfDebug( "Implicit transaction open enabled.\n" );
656 $this->mSessionVars = $params['variables'];
658 /** Get the default table prefix*/
659 if ( $tablePrefix === 'get from global' ) {
660 $this->mTablePrefix = $wgDBprefix;
661 } else {
662 $this->mTablePrefix = $tablePrefix;
665 /** Get the database schema*/
666 if ( $schema === 'get from global' ) {
667 $this->mSchema = $wgDBmwschema;
668 } else {
669 $this->mSchema = $schema;
672 $this->mForeign = $foreign;
674 if ( isset( $params['trxProfiler'] ) ) {
675 $this->trxProfiler = $params['trxProfiler']; // override
678 if ( $user ) {
679 $this->open( $server, $user, $password, $dbName );
684 * Called by serialize. Throw an exception when DB connection is serialized.
685 * This causes problems on some database engines because the connection is
686 * not restored on unserialize.
688 public function __sleep() {
689 throw new MWException( 'Database serialization may cause problems, since ' .
690 'the connection is not restored on wakeup.' );
694 * Given a DB type, construct the name of the appropriate child class of
695 * DatabaseBase. This is designed to replace all of the manual stuff like:
696 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
697 * as well as validate against the canonical list of DB types we have
699 * This factory function is mostly useful for when you need to connect to a
700 * database other than the MediaWiki default (such as for external auth,
701 * an extension, et cetera). Do not use this to connect to the MediaWiki
702 * database. Example uses in core:
703 * @see LoadBalancer::reallyOpenConnection()
704 * @see ForeignDBRepo::getMasterDB()
705 * @see WebInstallerDBConnect::execute()
707 * @since 1.18
709 * @param string $dbType A possible DB type
710 * @param array $p An array of options to pass to the constructor.
711 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
712 * @throws MWException If the database driver or extension cannot be found
713 * @return DatabaseBase|null DatabaseBase subclass or null
715 final public static function factory( $dbType, $p = array() ) {
716 $canonicalDBTypes = array(
717 'mysql' => array( 'mysqli', 'mysql' ),
718 'postgres' => array(),
719 'sqlite' => array(),
720 'oracle' => array(),
721 'mssql' => array(),
724 $driver = false;
725 $dbType = strtolower( $dbType );
726 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
727 $possibleDrivers = $canonicalDBTypes[$dbType];
728 if ( !empty( $p['driver'] ) ) {
729 if ( in_array( $p['driver'], $possibleDrivers ) ) {
730 $driver = $p['driver'];
731 } else {
732 throw new MWException( __METHOD__ .
733 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
735 } else {
736 foreach ( $possibleDrivers as $posDriver ) {
737 if ( extension_loaded( $posDriver ) ) {
738 $driver = $posDriver;
739 break;
743 } else {
744 $driver = $dbType;
746 if ( $driver === false ) {
747 throw new MWException( __METHOD__ .
748 " no viable database extension found for type '$dbType'" );
751 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
752 // and everything else doesn't use a schema (e.g. null)
753 // Although postgres and oracle support schemas, we don't use them (yet)
754 // to maintain backwards compatibility
755 $defaultSchemas = array(
756 'mssql' => 'get from global',
759 $class = 'Database' . ucfirst( $driver );
760 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
761 // Resolve some defaults for b/c
762 $p['host'] = isset( $p['host'] ) ? $p['host'] : false;
763 $p['user'] = isset( $p['user'] ) ? $p['user'] : false;
764 $p['password'] = isset( $p['password'] ) ? $p['password'] : false;
765 $p['dbname'] = isset( $p['dbname'] ) ? $p['dbname'] : false;
766 $p['flags'] = isset( $p['flags'] ) ? $p['flags'] : 0;
767 $p['variables'] = isset( $p['variables'] ) ? $p['variables'] : array();
768 $p['tablePrefix'] = isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global';
769 if ( !isset( $p['schema'] ) ) {
770 $p['schema'] = isset( $defaultSchemas[$dbType] ) ? $defaultSchemas[$dbType] : null;
772 $p['foreign'] = isset( $p['foreign'] ) ? $p['foreign'] : false;
774 return new $class( $p );
775 } else {
776 return null;
780 protected function installErrorHandler() {
781 $this->mPHPError = false;
782 $this->htmlErrors = ini_set( 'html_errors', '0' );
783 set_error_handler( array( $this, 'connectionErrorHandler' ) );
787 * @return bool|string
789 protected function restoreErrorHandler() {
790 restore_error_handler();
791 if ( $this->htmlErrors !== false ) {
792 ini_set( 'html_errors', $this->htmlErrors );
794 if ( $this->mPHPError ) {
795 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
796 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
798 return $error;
799 } else {
800 return false;
805 * @param int $errno
806 * @param string $errstr
808 public function connectionErrorHandler( $errno, $errstr ) {
809 $this->mPHPError = $errstr;
813 * Create a log context to pass to wfLogDBError or other logging functions.
815 * @param array $extras Additional data to add to context
816 * @return array
818 protected function getLogContext( array $extras = array() ) {
819 return array_merge(
820 array(
821 'db_server' => $this->mServer,
822 'db_name' => $this->mDBname,
823 'db_user' => $this->mUser,
825 $extras
830 * Closes a database connection.
831 * if it is open : commits any open transactions
833 * @throws MWException
834 * @return bool Operation success. true if already closed.
836 public function close() {
837 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
838 throw new MWException( "Transaction idle callbacks still pending." );
840 if ( $this->mConn ) {
841 if ( $this->trxLevel() ) {
842 if ( !$this->mTrxAutomatic ) {
843 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
844 " performing implicit commit before closing connection!" );
847 $this->commit( __METHOD__, 'flush' );
850 $closed = $this->closeConnection();
851 $this->mConn = false;
852 } else {
853 $closed = true;
855 $this->mOpened = false;
857 return $closed;
861 * Make sure isOpen() returns true as a sanity check
863 * @throws DBUnexpectedError
865 protected function assertOpen() {
866 if ( !$this->isOpen() ) {
867 throw new DBUnexpectedError( $this, "DB connection was already closed." );
872 * Closes underlying database connection
873 * @since 1.20
874 * @return bool Whether connection was closed successfully
876 abstract protected function closeConnection();
879 * @param string $error Fallback error message, used if none is given by DB
880 * @throws DBConnectionError
882 function reportConnectionError( $error = 'Unknown error' ) {
883 $myError = $this->lastError();
884 if ( $myError ) {
885 $error = $myError;
888 # New method
889 throw new DBConnectionError( $this, $error );
893 * The DBMS-dependent part of query()
895 * @param string $sql SQL query.
896 * @return ResultWrapper|bool Result object to feed to fetchObject,
897 * fetchRow, ...; or false on failure
899 abstract protected function doQuery( $sql );
902 * Determine whether a query writes to the DB.
903 * Should return true if unsure.
905 * @param string $sql
906 * @return bool
908 protected function isWriteQuery( $sql ) {
909 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
913 * Determine whether a SQL statement is sensitive to isolation level.
914 * A SQL statement is considered transactable if its result could vary
915 * depending on the transaction isolation level. Operational commands
916 * such as 'SET' and 'SHOW' are not considered to be transactable.
918 * @param string $sql
919 * @return bool
921 protected function isTransactableQuery( $sql ) {
922 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
923 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
927 * Run an SQL query and return the result. Normally throws a DBQueryError
928 * on failure. If errors are ignored, returns false instead.
930 * In new code, the query wrappers select(), insert(), update(), delete(),
931 * etc. should be used where possible, since they give much better DBMS
932 * independence and automatically quote or validate user input in a variety
933 * of contexts. This function is generally only useful for queries which are
934 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
935 * as CREATE TABLE.
937 * However, the query wrappers themselves should call this function.
939 * @param string $sql SQL query
940 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
941 * comment (you can use __METHOD__ or add some extra info)
942 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
943 * maybe best to catch the exception instead?
944 * @throws MWException
945 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
946 * for a successful read query, or false on failure if $tempIgnore set
948 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
949 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
951 $this->mLastQuery = $sql;
953 $isWriteQuery = $this->isWriteQuery( $sql );
954 if ( $isWriteQuery ) {
955 if ( !$this->mDoneWrites ) {
956 wfDebug( __METHOD__ . ': Writes done: ' .
957 DatabaseBase::generalizeSQL( $sql ) . "\n" );
959 # Set a flag indicating that writes have been done
960 $this->mDoneWrites = microtime( true );
963 # Add a comment for easy SHOW PROCESSLIST interpretation
964 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
965 $userName = $wgUser->getName();
966 if ( mb_strlen( $userName ) > 15 ) {
967 $userName = mb_substr( $userName, 0, 15 ) . '...';
969 $userName = str_replace( '/', '', $userName );
970 } else {
971 $userName = '';
974 // Add trace comment to the begin of the sql string, right after the operator.
975 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
976 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
978 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
979 if ( $wgDebugDBTransactions ) {
980 wfDebug( "Implicit transaction start.\n" );
982 $this->begin( __METHOD__ . " ($fname)" );
983 $this->mTrxAutomatic = true;
986 # Keep track of whether the transaction has write queries pending
987 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
988 $this->mTrxDoneWrites = true;
989 $this->getTransactionProfiler()->transactionWritingIn(
990 $this->mServer, $this->mDBname, $this->mTrxShortId );
993 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
994 # generalizeSQL will probably cut down the query to reasonable
995 # logging size most of the time. The substr is really just a sanity check.
996 if ( $isMaster ) {
997 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
998 $totalProf = 'DatabaseBase::query-master';
999 } else {
1000 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1001 $totalProf = 'DatabaseBase::query';
1003 # Include query transaction state
1004 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1006 $profiler = Profiler::instance();
1007 if ( !$profiler instanceof ProfilerStub ) {
1008 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1009 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1012 if ( $this->debug() ) {
1013 static $cnt = 0;
1015 $cnt++;
1016 $sqlx = $wgDebugDumpSqlLength ? substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1017 : $commentedSql;
1018 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1020 $master = $isMaster ? 'master' : 'slave';
1021 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1024 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1026 # Avoid fatals if close() was called
1027 $this->assertOpen();
1029 # Do the query and handle errors
1030 $startTime = microtime( true );
1031 $ret = $this->doQuery( $commentedSql );
1032 $queryRuntime = microtime( true ) - $startTime;
1033 # Log the query time and feed it into the DB trx profiler
1034 $this->getTransactionProfiler()->recordQueryCompletion(
1035 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1037 MWDebug::queryTime( $queryId );
1039 # Try reconnecting if the connection was lost
1040 if ( false === $ret && $this->wasErrorReissuable() ) {
1041 # Transaction is gone, like it or not
1042 $hadTrx = $this->mTrxLevel; // possible lost transaction
1043 $this->mTrxLevel = 0;
1044 $this->mTrxIdleCallbacks = array(); // bug 65263
1045 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1046 wfDebug( "Connection lost, reconnecting...\n" );
1047 # Stash the last error values since ping() might clear them
1048 $lastError = $this->lastError();
1049 $lastErrno = $this->lastErrno();
1050 if ( $this->ping() ) {
1051 wfDebug( "Reconnected\n" );
1052 $server = $this->getServer();
1053 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1054 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1056 if ( $hadTrx ) {
1057 # Leave $ret as false and let an error be reported.
1058 # Callers may catch the exception and continue to use the DB.
1059 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1060 } else {
1061 # Should be safe to silently retry (no trx and thus no callbacks)
1062 $startTime = microtime( true );
1063 $ret = $this->doQuery( $commentedSql );
1064 $queryRuntime = microtime( true ) - $startTime;
1065 # Log the query time and feed it into the DB trx profiler
1066 $this->getTransactionProfiler()->recordQueryCompletion(
1067 $queryProf, $startTime, $isWriteQuery, $this->affectedRows() );
1069 } else {
1070 wfDebug( "Failed\n" );
1074 if ( false === $ret ) {
1075 $this->reportQueryError(
1076 $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1079 $res = $this->resultObject( $ret );
1081 // Destroy profile sections in the opposite order to their creation
1082 $queryProfSection = false;
1083 $totalProfSection = false;
1085 if ( $isWriteQuery && $this->mTrxLevel ) {
1086 $this->mTrxWriteDuration += $queryRuntime;
1089 return $res;
1093 * Report a query error. Log the error, and if neither the object ignore
1094 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1096 * @param string $error
1097 * @param int $errno
1098 * @param string $sql
1099 * @param string $fname
1100 * @param bool $tempIgnore
1101 * @throws DBQueryError
1103 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1104 if ( $this->ignoreErrors() || $tempIgnore ) {
1105 wfDebug( "SQL ERROR (ignored): $error\n" );
1106 } else {
1107 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1108 wfLogDBError(
1109 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1110 $this->getLogContext( array(
1111 'method' => __METHOD__,
1112 'errno' => $errno,
1113 'error' => $error,
1114 'sql1line' => $sql1line,
1115 'fname' => $fname,
1118 wfDebug( "SQL ERROR: " . $error . "\n" );
1119 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1124 * Intended to be compatible with the PEAR::DB wrapper functions.
1125 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1127 * ? = scalar value, quoted as necessary
1128 * ! = raw SQL bit (a function for instance)
1129 * & = filename; reads the file and inserts as a blob
1130 * (we don't use this though...)
1132 * @param string $sql
1133 * @param string $func
1135 * @return array
1137 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1138 /* MySQL doesn't support prepared statements (yet), so just
1139 * pack up the query for reference. We'll manually replace
1140 * the bits later.
1142 return array( 'query' => $sql, 'func' => $func );
1146 * Free a prepared query, generated by prepare().
1147 * @param string $prepared
1149 protected function freePrepared( $prepared ) {
1150 /* No-op by default */
1154 * Execute a prepared query with the various arguments
1155 * @param string $prepared The prepared sql
1156 * @param mixed $args Either an array here, or put scalars as varargs
1158 * @return ResultWrapper
1160 public function execute( $prepared, $args = null ) {
1161 if ( !is_array( $args ) ) {
1162 # Pull the var args
1163 $args = func_get_args();
1164 array_shift( $args );
1167 $sql = $this->fillPrepared( $prepared['query'], $args );
1169 return $this->query( $sql, $prepared['func'] );
1173 * For faking prepared SQL statements on DBs that don't support it directly.
1175 * @param string $preparedQuery A 'preparable' SQL statement
1176 * @param array $args Array of Arguments to fill it with
1177 * @return string Executable SQL
1179 public function fillPrepared( $preparedQuery, $args ) {
1180 reset( $args );
1181 $this->preparedArgs =& $args;
1183 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1184 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1188 * preg_callback func for fillPrepared()
1189 * The arguments should be in $this->preparedArgs and must not be touched
1190 * while we're doing this.
1192 * @param array $matches
1193 * @throws DBUnexpectedError
1194 * @return string
1196 protected function fillPreparedArg( $matches ) {
1197 switch ( $matches[1] ) {
1198 case '\\?':
1199 return '?';
1200 case '\\!':
1201 return '!';
1202 case '\\&':
1203 return '&';
1206 list( /* $n */, $arg ) = each( $this->preparedArgs );
1208 switch ( $matches[1] ) {
1209 case '?':
1210 return $this->addQuotes( $arg );
1211 case '!':
1212 return $arg;
1213 case '&':
1214 # return $this->addQuotes( file_get_contents( $arg ) );
1215 throw new DBUnexpectedError(
1216 $this,
1217 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1219 default:
1220 throw new DBUnexpectedError(
1221 $this,
1222 'Received invalid match. This should never happen!'
1228 * Free a result object returned by query() or select(). It's usually not
1229 * necessary to call this, just use unset() or let the variable holding
1230 * the result object go out of scope.
1232 * @param mixed $res A SQL result
1234 public function freeResult( $res ) {
1238 * A SELECT wrapper which returns a single field from a single result row.
1240 * Usually throws a DBQueryError on failure. If errors are explicitly
1241 * ignored, returns false on failure.
1243 * If no result rows are returned from the query, false is returned.
1245 * @param string|array $table Table name. See DatabaseBase::select() for details.
1246 * @param string $var The field name to select. This must be a valid SQL
1247 * fragment: do not use unvalidated user input.
1248 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1249 * @param string $fname The function name of the caller.
1250 * @param string|array $options The query options. See DatabaseBase::select() for details.
1252 * @return bool|mixed The value from the field, or false on failure.
1254 public function selectField(
1255 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1257 if ( $var === '*' ) { // sanity
1258 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1261 if ( !is_array( $options ) ) {
1262 $options = array( $options );
1265 $options['LIMIT'] = 1;
1267 $res = $this->select( $table, $var, $cond, $fname, $options );
1268 if ( $res === false || !$this->numRows( $res ) ) {
1269 return false;
1272 $row = $this->fetchRow( $res );
1274 if ( $row !== false ) {
1275 return reset( $row );
1276 } else {
1277 return false;
1282 * A SELECT wrapper which returns a list of single field values from result rows.
1284 * Usually throws a DBQueryError on failure. If errors are explicitly
1285 * ignored, returns false on failure.
1287 * If no result rows are returned from the query, false is returned.
1289 * @param string|array $table Table name. See DatabaseBase::select() for details.
1290 * @param string $var The field name to select. This must be a valid SQL
1291 * fragment: do not use unvalidated user input.
1292 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1293 * @param string $fname The function name of the caller.
1294 * @param string|array $options The query options. See DatabaseBase::select() for details.
1296 * @return bool|array The values from the field, or false on failure
1297 * @throws DBUnexpectedError
1298 * @since 1.25
1300 public function selectFieldValues(
1301 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1303 if ( $var === '*' ) { // sanity
1304 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1307 if ( !is_array( $options ) ) {
1308 $options = array( $options );
1311 $res = $this->select( $table, $var, $cond, $fname, $options );
1312 if ( $res === false ) {
1313 return false;
1316 $values = array();
1317 foreach ( $res as $row ) {
1318 $values[] = $row->$var;
1321 return $values;
1325 * Returns an optional USE INDEX clause to go after the table, and a
1326 * string to go at the end of the query.
1328 * @param array $options Associative array of options to be turned into
1329 * an SQL query, valid keys are listed in the function.
1330 * @return array
1331 * @see DatabaseBase::select()
1333 public function makeSelectOptions( $options ) {
1334 $preLimitTail = $postLimitTail = '';
1335 $startOpts = '';
1337 $noKeyOptions = array();
1339 foreach ( $options as $key => $option ) {
1340 if ( is_numeric( $key ) ) {
1341 $noKeyOptions[$option] = true;
1345 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1347 $preLimitTail .= $this->makeOrderBy( $options );
1349 // if (isset($options['LIMIT'])) {
1350 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1351 // isset($options['OFFSET']) ? $options['OFFSET']
1352 // : false);
1353 // }
1355 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1356 $postLimitTail .= ' FOR UPDATE';
1359 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1360 $postLimitTail .= ' LOCK IN SHARE MODE';
1363 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1364 $startOpts .= 'DISTINCT';
1367 # Various MySQL extensions
1368 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1369 $startOpts .= ' /*! STRAIGHT_JOIN */';
1372 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1373 $startOpts .= ' HIGH_PRIORITY';
1376 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1377 $startOpts .= ' SQL_BIG_RESULT';
1380 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1381 $startOpts .= ' SQL_BUFFER_RESULT';
1384 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1385 $startOpts .= ' SQL_SMALL_RESULT';
1388 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1389 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1392 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1393 $startOpts .= ' SQL_CACHE';
1396 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1397 $startOpts .= ' SQL_NO_CACHE';
1400 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1401 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1402 } else {
1403 $useIndex = '';
1406 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1410 * Returns an optional GROUP BY with an optional HAVING
1412 * @param array $options Associative array of options
1413 * @return string
1414 * @see DatabaseBase::select()
1415 * @since 1.21
1417 public function makeGroupByWithHaving( $options ) {
1418 $sql = '';
1419 if ( isset( $options['GROUP BY'] ) ) {
1420 $gb = is_array( $options['GROUP BY'] )
1421 ? implode( ',', $options['GROUP BY'] )
1422 : $options['GROUP BY'];
1423 $sql .= ' GROUP BY ' . $gb;
1425 if ( isset( $options['HAVING'] ) ) {
1426 $having = is_array( $options['HAVING'] )
1427 ? $this->makeList( $options['HAVING'], LIST_AND )
1428 : $options['HAVING'];
1429 $sql .= ' HAVING ' . $having;
1432 return $sql;
1436 * Returns an optional ORDER BY
1438 * @param array $options Associative array of options
1439 * @return string
1440 * @see DatabaseBase::select()
1441 * @since 1.21
1443 public function makeOrderBy( $options ) {
1444 if ( isset( $options['ORDER BY'] ) ) {
1445 $ob = is_array( $options['ORDER BY'] )
1446 ? implode( ',', $options['ORDER BY'] )
1447 : $options['ORDER BY'];
1449 return ' ORDER BY ' . $ob;
1452 return '';
1456 * Execute a SELECT query constructed using the various parameters provided.
1457 * See below for full details of the parameters.
1459 * @param string|array $table Table name
1460 * @param string|array $vars Field names
1461 * @param string|array $conds Conditions
1462 * @param string $fname Caller function name
1463 * @param array $options Query options
1464 * @param array $join_conds Join conditions
1467 * @param string|array $table
1469 * May be either an array of table names, or a single string holding a table
1470 * name. If an array is given, table aliases can be specified, for example:
1472 * array( 'a' => 'user' )
1474 * This includes the user table in the query, with the alias "a" available
1475 * for use in field names (e.g. a.user_name).
1477 * All of the table names given here are automatically run through
1478 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1479 * added, and various other table name mappings to be performed.
1482 * @param string|array $vars
1484 * May be either a field name or an array of field names. The field names
1485 * can be complete fragments of SQL, for direct inclusion into the SELECT
1486 * query. If an array is given, field aliases can be specified, for example:
1488 * array( 'maxrev' => 'MAX(rev_id)' )
1490 * This includes an expression with the alias "maxrev" in the query.
1492 * If an expression is given, care must be taken to ensure that it is
1493 * DBMS-independent.
1496 * @param string|array $conds
1498 * May be either a string containing a single condition, or an array of
1499 * conditions. If an array is given, the conditions constructed from each
1500 * element are combined with AND.
1502 * Array elements may take one of two forms:
1504 * - Elements with a numeric key are interpreted as raw SQL fragments.
1505 * - Elements with a string key are interpreted as equality conditions,
1506 * where the key is the field name.
1507 * - If the value of such an array element is a scalar (such as a
1508 * string), it will be treated as data and thus quoted appropriately.
1509 * If it is null, an IS NULL clause will be added.
1510 * - If the value is an array, an IN (...) clause will be constructed
1511 * from its non-null elements, and an IS NULL clause will be added
1512 * if null is present, such that the field may match any of the
1513 * elements in the array. The non-null elements will be quoted.
1515 * Note that expressions are often DBMS-dependent in their syntax.
1516 * DBMS-independent wrappers are provided for constructing several types of
1517 * expression commonly used in condition queries. See:
1518 * - DatabaseBase::buildLike()
1519 * - DatabaseBase::conditional()
1522 * @param string|array $options
1524 * Optional: Array of query options. Boolean options are specified by
1525 * including them in the array as a string value with a numeric key, for
1526 * example:
1528 * array( 'FOR UPDATE' )
1530 * The supported options are:
1532 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1533 * with LIMIT can theoretically be used for paging through a result set,
1534 * but this is discouraged in MediaWiki for performance reasons.
1536 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1537 * and then the first rows are taken until the limit is reached. LIMIT
1538 * is applied to a result set after OFFSET.
1540 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1541 * changed until the next COMMIT.
1543 * - DISTINCT: Boolean: return only unique result rows.
1545 * - GROUP BY: May be either an SQL fragment string naming a field or
1546 * expression to group by, or an array of such SQL fragments.
1548 * - HAVING: May be either an string containing a HAVING clause or an array of
1549 * conditions building the HAVING clause. If an array is given, the conditions
1550 * constructed from each element are combined with AND.
1552 * - ORDER BY: May be either an SQL fragment giving a field name or
1553 * expression to order by, or an array of such SQL fragments.
1555 * - USE INDEX: This may be either a string giving the index name to use
1556 * for the query, or an array. If it is an associative array, each key
1557 * gives the table name (or alias), each value gives the index name to
1558 * use for that table. All strings are SQL fragments and so should be
1559 * validated by the caller.
1561 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1562 * instead of SELECT.
1564 * And also the following boolean MySQL extensions, see the MySQL manual
1565 * for documentation:
1567 * - LOCK IN SHARE MODE
1568 * - STRAIGHT_JOIN
1569 * - HIGH_PRIORITY
1570 * - SQL_BIG_RESULT
1571 * - SQL_BUFFER_RESULT
1572 * - SQL_SMALL_RESULT
1573 * - SQL_CALC_FOUND_ROWS
1574 * - SQL_CACHE
1575 * - SQL_NO_CACHE
1578 * @param string|array $join_conds
1580 * Optional associative array of table-specific join conditions. In the
1581 * most common case, this is unnecessary, since the join condition can be
1582 * in $conds. However, it is useful for doing a LEFT JOIN.
1584 * The key of the array contains the table name or alias. The value is an
1585 * array with two elements, numbered 0 and 1. The first gives the type of
1586 * join, the second is an SQL fragment giving the join condition for that
1587 * table. For example:
1589 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1591 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1592 * with no rows in it will be returned. If there was a query error, a
1593 * DBQueryError exception will be thrown, except if the "ignore errors"
1594 * option was set, in which case false will be returned.
1596 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1597 $options = array(), $join_conds = array() ) {
1598 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1600 return $this->query( $sql, $fname );
1604 * The equivalent of DatabaseBase::select() except that the constructed SQL
1605 * is returned, instead of being immediately executed. This can be useful for
1606 * doing UNION queries, where the SQL text of each query is needed. In general,
1607 * however, callers outside of Database classes should just use select().
1609 * @param string|array $table Table name
1610 * @param string|array $vars Field names
1611 * @param string|array $conds Conditions
1612 * @param string $fname Caller function name
1613 * @param string|array $options Query options
1614 * @param string|array $join_conds Join conditions
1616 * @return string SQL query string.
1617 * @see DatabaseBase::select()
1619 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1620 $options = array(), $join_conds = array()
1622 if ( is_array( $vars ) ) {
1623 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1626 $options = (array)$options;
1627 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1628 ? $options['USE INDEX']
1629 : array();
1631 if ( is_array( $table ) ) {
1632 $from = ' FROM ' .
1633 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1634 } elseif ( $table != '' ) {
1635 if ( $table[0] == ' ' ) {
1636 $from = ' FROM ' . $table;
1637 } else {
1638 $from = ' FROM ' .
1639 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1641 } else {
1642 $from = '';
1645 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1646 $this->makeSelectOptions( $options );
1648 if ( !empty( $conds ) ) {
1649 if ( is_array( $conds ) ) {
1650 $conds = $this->makeList( $conds, LIST_AND );
1652 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1653 } else {
1654 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1657 if ( isset( $options['LIMIT'] ) ) {
1658 $sql = $this->limitResult( $sql, $options['LIMIT'],
1659 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1661 $sql = "$sql $postLimitTail";
1663 if ( isset( $options['EXPLAIN'] ) ) {
1664 $sql = 'EXPLAIN ' . $sql;
1667 return $sql;
1671 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1672 * that a single row object is returned. If the query returns no rows,
1673 * false is returned.
1675 * @param string|array $table Table name
1676 * @param string|array $vars Field names
1677 * @param array $conds Conditions
1678 * @param string $fname Caller function name
1679 * @param string|array $options Query options
1680 * @param array|string $join_conds Join conditions
1682 * @return stdClass|bool
1684 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1685 $options = array(), $join_conds = array()
1687 $options = (array)$options;
1688 $options['LIMIT'] = 1;
1689 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1691 if ( $res === false ) {
1692 return false;
1695 if ( !$this->numRows( $res ) ) {
1696 return false;
1699 $obj = $this->fetchObject( $res );
1701 return $obj;
1705 * Estimate the number of rows in dataset
1707 * MySQL allows you to estimate the number of rows that would be returned
1708 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1709 * index cardinality statistics, and is notoriously inaccurate, especially
1710 * when large numbers of rows have recently been added or deleted.
1712 * For DBMSs that don't support fast result size estimation, this function
1713 * will actually perform the SELECT COUNT(*).
1715 * Takes the same arguments as DatabaseBase::select().
1717 * @param string $table Table name
1718 * @param string $vars Unused
1719 * @param array|string $conds Filters on the table
1720 * @param string $fname Function name for profiling
1721 * @param array $options Options for select
1722 * @return int Row count
1724 public function estimateRowCount(
1725 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1727 $rows = 0;
1728 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1730 if ( $res ) {
1731 $row = $this->fetchRow( $res );
1732 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1735 return $rows;
1739 * Get the number of rows in dataset
1741 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1743 * Takes the same arguments as DatabaseBase::select().
1745 * @param string $table Table name
1746 * @param string $vars Unused
1747 * @param array|string $conds Filters on the table
1748 * @param string $fname Function name for profiling
1749 * @param array $options Options for select
1750 * @return int Row count
1751 * @since 1.24
1753 public function selectRowCount(
1754 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1756 $rows = 0;
1757 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1758 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count", $fname );
1760 if ( $res ) {
1761 $row = $this->fetchRow( $res );
1762 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1765 return $rows;
1769 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1770 * It's only slightly flawed. Don't use for anything important.
1772 * @param string $sql A SQL Query
1774 * @return string
1776 static function generalizeSQL( $sql ) {
1777 # This does the same as the regexp below would do, but in such a way
1778 # as to avoid crashing php on some large strings.
1779 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1781 $sql = str_replace( "\\\\", '', $sql );
1782 $sql = str_replace( "\\'", '', $sql );
1783 $sql = str_replace( "\\\"", '', $sql );
1784 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1785 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1787 # All newlines, tabs, etc replaced by single space
1788 $sql = preg_replace( '/\s+/', ' ', $sql );
1790 # All numbers => N,
1791 # except the ones surrounded by characters, e.g. l10n
1792 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1793 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1795 return $sql;
1799 * Determines whether a field exists in a table
1801 * @param string $table Table name
1802 * @param string $field Filed to check on that table
1803 * @param string $fname Calling function name (optional)
1804 * @return bool Whether $table has filed $field
1806 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1807 $info = $this->fieldInfo( $table, $field );
1809 return (bool)$info;
1813 * Determines whether an index exists
1814 * Usually throws a DBQueryError on failure
1815 * If errors are explicitly ignored, returns NULL on failure
1817 * @param string $table
1818 * @param string $index
1819 * @param string $fname
1820 * @return bool|null
1822 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1823 if ( !$this->tableExists( $table ) ) {
1824 return null;
1827 $info = $this->indexInfo( $table, $index, $fname );
1828 if ( is_null( $info ) ) {
1829 return null;
1830 } else {
1831 return $info !== false;
1836 * Query whether a given table exists
1838 * @param string $table
1839 * @param string $fname
1840 * @return bool
1842 public function tableExists( $table, $fname = __METHOD__ ) {
1843 $table = $this->tableName( $table );
1844 $old = $this->ignoreErrors( true );
1845 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1846 $this->ignoreErrors( $old );
1848 return (bool)$res;
1852 * Determines if a given index is unique
1854 * @param string $table
1855 * @param string $index
1857 * @return bool
1859 public function indexUnique( $table, $index ) {
1860 $indexInfo = $this->indexInfo( $table, $index );
1862 if ( !$indexInfo ) {
1863 return null;
1866 return !$indexInfo[0]->Non_unique;
1870 * Helper for DatabaseBase::insert().
1872 * @param array $options
1873 * @return string
1875 protected function makeInsertOptions( $options ) {
1876 return implode( ' ', $options );
1880 * INSERT wrapper, inserts an array into a table.
1882 * $a may be either:
1884 * - A single associative array. The array keys are the field names, and
1885 * the values are the values to insert. The values are treated as data
1886 * and will be quoted appropriately. If NULL is inserted, this will be
1887 * converted to a database NULL.
1888 * - An array with numeric keys, holding a list of associative arrays.
1889 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1890 * each subarray must be identical to each other, and in the same order.
1892 * $options is an array of options, with boolean options encoded as values
1893 * with numeric keys, in the same style as $options in
1894 * DatabaseBase::select(). Supported options are:
1896 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1897 * any rows which cause duplicate key errors are not inserted. It's
1898 * possible to determine how many rows were successfully inserted using
1899 * DatabaseBase::affectedRows().
1901 * @param string $table Table name. This will be passed through
1902 * DatabaseBase::tableName().
1903 * @param array $a Array of rows to insert
1904 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1905 * @param array $options Array of options
1907 * @throws DBQueryError Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1908 * returns success.
1910 * @return bool
1912 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
1913 # No rows to insert, easy just return now
1914 if ( !count( $a ) ) {
1915 return true;
1918 $table = $this->tableName( $table );
1920 if ( !is_array( $options ) ) {
1921 $options = array( $options );
1924 $fh = null;
1925 if ( isset( $options['fileHandle'] ) ) {
1926 $fh = $options['fileHandle'];
1928 $options = $this->makeInsertOptions( $options );
1930 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1931 $multi = true;
1932 $keys = array_keys( $a[0] );
1933 } else {
1934 $multi = false;
1935 $keys = array_keys( $a );
1938 $sql = 'INSERT ' . $options .
1939 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1941 if ( $multi ) {
1942 $first = true;
1943 foreach ( $a as $row ) {
1944 if ( $first ) {
1945 $first = false;
1946 } else {
1947 $sql .= ',';
1949 $sql .= '(' . $this->makeList( $row ) . ')';
1951 } else {
1952 $sql .= '(' . $this->makeList( $a ) . ')';
1955 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
1956 return false;
1957 } elseif ( $fh !== null ) {
1958 return true;
1961 return (bool)$this->query( $sql, $fname );
1965 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
1967 * @param array $options
1968 * @return array
1970 protected function makeUpdateOptionsArray( $options ) {
1971 if ( !is_array( $options ) ) {
1972 $options = array( $options );
1975 $opts = array();
1977 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1978 $opts[] = $this->lowPriorityOption();
1981 if ( in_array( 'IGNORE', $options ) ) {
1982 $opts[] = 'IGNORE';
1985 return $opts;
1989 * Make UPDATE options for the DatabaseBase::update function
1991 * @param array $options The options passed to DatabaseBase::update
1992 * @return string
1994 protected function makeUpdateOptions( $options ) {
1995 $opts = $this->makeUpdateOptionsArray( $options );
1997 return implode( ' ', $opts );
2001 * UPDATE wrapper. Takes a condition array and a SET array.
2003 * @param string $table Name of the table to UPDATE. This will be passed through
2004 * DatabaseBase::tableName().
2005 * @param array $values An array of values to SET. For each array element,
2006 * the key gives the field name, and the value gives the data to set
2007 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2008 * @param array $conds An array of conditions (WHERE). See
2009 * DatabaseBase::select() for the details of the format of condition
2010 * arrays. Use '*' to update all rows.
2011 * @param string $fname The function name of the caller (from __METHOD__),
2012 * for logging and profiling.
2013 * @param array $options An array of UPDATE options, can be:
2014 * - IGNORE: Ignore unique key conflicts
2015 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2016 * @return bool
2018 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
2019 $table = $this->tableName( $table );
2020 $opts = $this->makeUpdateOptions( $options );
2021 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
2023 if ( $conds !== array() && $conds !== '*' ) {
2024 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2027 return $this->query( $sql, $fname );
2031 * Makes an encoded list of strings from an array
2033 * @param array $a Containing the data
2034 * @param int $mode Constant
2035 * - LIST_COMMA: Comma separated, no field names
2036 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2037 * documentation for $conds in DatabaseBase::select().
2038 * - LIST_OR: ORed WHERE clause (without the WHERE)
2039 * - LIST_SET: Comma separated with field names, like a SET clause
2040 * - LIST_NAMES: Comma separated field names
2041 * @throws MWException|DBUnexpectedError
2042 * @return string
2044 public function makeList( $a, $mode = LIST_COMMA ) {
2045 if ( !is_array( $a ) ) {
2046 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2049 $first = true;
2050 $list = '';
2052 foreach ( $a as $field => $value ) {
2053 if ( !$first ) {
2054 if ( $mode == LIST_AND ) {
2055 $list .= ' AND ';
2056 } elseif ( $mode == LIST_OR ) {
2057 $list .= ' OR ';
2058 } else {
2059 $list .= ',';
2061 } else {
2062 $first = false;
2065 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2066 $list .= "($value)";
2067 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2068 $list .= "$value";
2069 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2070 // Remove null from array to be handled separately if found
2071 $includeNull = false;
2072 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2073 $includeNull = true;
2074 unset( $value[$nullKey] );
2076 if ( count( $value ) == 0 && !$includeNull ) {
2077 throw new MWException( __METHOD__ . ": empty input for field $field" );
2078 } elseif ( count( $value ) == 0 ) {
2079 // only check if $field is null
2080 $list .= "$field IS NULL";
2081 } else {
2082 // IN clause contains at least one valid element
2083 if ( $includeNull ) {
2084 // Group subconditions to ensure correct precedence
2085 $list .= '(';
2087 if ( count( $value ) == 1 ) {
2088 // Special-case single values, as IN isn't terribly efficient
2089 // Don't necessarily assume the single key is 0; we don't
2090 // enforce linear numeric ordering on other arrays here.
2091 $value = array_values( $value );
2092 $list .= $field . " = " . $this->addQuotes( $value[0] );
2093 } else {
2094 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2096 // if null present in array, append IS NULL
2097 if ( $includeNull ) {
2098 $list .= " OR $field IS NULL)";
2101 } elseif ( $value === null ) {
2102 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2103 $list .= "$field IS ";
2104 } elseif ( $mode == LIST_SET ) {
2105 $list .= "$field = ";
2107 $list .= 'NULL';
2108 } else {
2109 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2110 $list .= "$field = ";
2112 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2116 return $list;
2120 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2121 * The keys on each level may be either integers or strings.
2123 * @param array $data Organized as 2-d
2124 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2125 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2126 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2127 * @return string|bool SQL fragment, or false if no items in array
2129 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2130 $conds = array();
2132 foreach ( $data as $base => $sub ) {
2133 if ( count( $sub ) ) {
2134 $conds[] = $this->makeList(
2135 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2136 LIST_AND );
2140 if ( $conds ) {
2141 return $this->makeList( $conds, LIST_OR );
2142 } else {
2143 // Nothing to search for...
2144 return false;
2149 * Return aggregated value alias
2151 * @param array $valuedata
2152 * @param string $valuename
2154 * @return string
2156 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2157 return $valuename;
2161 * @param string $field
2162 * @return string
2164 public function bitNot( $field ) {
2165 return "(~$field)";
2169 * @param string $fieldLeft
2170 * @param string $fieldRight
2171 * @return string
2173 public function bitAnd( $fieldLeft, $fieldRight ) {
2174 return "($fieldLeft & $fieldRight)";
2178 * @param string $fieldLeft
2179 * @param string $fieldRight
2180 * @return string
2182 public function bitOr( $fieldLeft, $fieldRight ) {
2183 return "($fieldLeft | $fieldRight)";
2187 * Build a concatenation list to feed into a SQL query
2188 * @param array $stringList List of raw SQL expressions; caller is
2189 * responsible for any quoting
2190 * @return string
2192 public function buildConcat( $stringList ) {
2193 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2197 * Build a GROUP_CONCAT or equivalent statement for a query.
2199 * This is useful for combining a field for several rows into a single string.
2200 * NULL values will not appear in the output, duplicated values will appear,
2201 * and the resulting delimiter-separated values have no defined sort order.
2202 * Code using the results may need to use the PHP unique() or sort() methods.
2204 * @param string $delim Glue to bind the results together
2205 * @param string|array $table Table name
2206 * @param string $field Field name
2207 * @param string|array $conds Conditions
2208 * @param string|array $join_conds Join conditions
2209 * @return string SQL text
2210 * @since 1.23
2212 public function buildGroupConcatField(
2213 $delim, $table, $field, $conds = '', $join_conds = array()
2215 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2217 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2221 * Change the current database
2223 * @todo Explain what exactly will fail if this is not overridden.
2225 * @param string $db
2227 * @return bool Success or failure
2229 public function selectDB( $db ) {
2230 # Stub. Shouldn't cause serious problems if it's not overridden, but
2231 # if your database engine supports a concept similar to MySQL's
2232 # databases you may as well.
2233 $this->mDBname = $db;
2235 return true;
2239 * Get the current DB name
2240 * @return string
2242 public function getDBname() {
2243 return $this->mDBname;
2247 * Get the server hostname or IP address
2248 * @return string
2250 public function getServer() {
2251 return $this->mServer;
2255 * Format a table name ready for use in constructing an SQL query
2257 * This does two important things: it quotes the table names to clean them up,
2258 * and it adds a table prefix if only given a table name with no quotes.
2260 * All functions of this object which require a table name call this function
2261 * themselves. Pass the canonical name to such functions. This is only needed
2262 * when calling query() directly.
2264 * @param string $name Database table name
2265 * @param string $format One of:
2266 * quoted - Automatically pass the table name through addIdentifierQuotes()
2267 * so that it can be used in a query.
2268 * raw - Do not add identifier quotes to the table name
2269 * @return string Full database name
2271 public function tableName( $name, $format = 'quoted' ) {
2272 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2273 # Skip the entire process when we have a string quoted on both ends.
2274 # Note that we check the end so that we will still quote any use of
2275 # use of `database`.table. But won't break things if someone wants
2276 # to query a database table with a dot in the name.
2277 if ( $this->isQuotedIdentifier( $name ) ) {
2278 return $name;
2281 # Lets test for any bits of text that should never show up in a table
2282 # name. Basically anything like JOIN or ON which are actually part of
2283 # SQL queries, but may end up inside of the table value to combine
2284 # sql. Such as how the API is doing.
2285 # Note that we use a whitespace test rather than a \b test to avoid
2286 # any remote case where a word like on may be inside of a table name
2287 # surrounded by symbols which may be considered word breaks.
2288 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2289 return $name;
2292 # Split database and table into proper variables.
2293 # We reverse the explode so that database.table and table both output
2294 # the correct table.
2295 $dbDetails = explode( '.', $name, 3 );
2296 if ( count( $dbDetails ) == 3 ) {
2297 list( $database, $schema, $table ) = $dbDetails;
2298 # We don't want any prefix added in this case
2299 $prefix = '';
2300 } elseif ( count( $dbDetails ) == 2 ) {
2301 list( $database, $table ) = $dbDetails;
2302 # We don't want any prefix added in this case
2303 # In dbs that support it, $database may actually be the schema
2304 # but that doesn't affect any of the functionality here
2305 $prefix = '';
2306 $schema = null;
2307 } else {
2308 list( $table ) = $dbDetails;
2309 if ( $wgSharedDB !== null # We have a shared database
2310 && $this->mForeign == false # We're not working on a foreign database
2311 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2312 && in_array( $table, $wgSharedTables ) # A shared table is selected
2314 $database = $wgSharedDB;
2315 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2316 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2317 } else {
2318 $database = null;
2319 $schema = $this->mSchema; # Default schema
2320 $prefix = $this->mTablePrefix; # Default prefix
2324 # Quote $table and apply the prefix if not quoted.
2325 # $tableName might be empty if this is called from Database::replaceVars()
2326 $tableName = "{$prefix}{$table}";
2327 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2328 $tableName = $this->addIdentifierQuotes( $tableName );
2331 # Quote $schema and merge it with the table name if needed
2332 if ( strlen( $schema ) ) {
2333 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2334 $schema = $this->addIdentifierQuotes( $schema );
2336 $tableName = $schema . '.' . $tableName;
2339 # Quote $database and merge it with the table name if needed
2340 if ( $database !== null ) {
2341 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2342 $database = $this->addIdentifierQuotes( $database );
2344 $tableName = $database . '.' . $tableName;
2347 return $tableName;
2351 * Fetch a number of table names into an array
2352 * This is handy when you need to construct SQL for joins
2354 * Example:
2355 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2356 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2357 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2359 * @return array
2361 public function tableNames() {
2362 $inArray = func_get_args();
2363 $retVal = array();
2365 foreach ( $inArray as $name ) {
2366 $retVal[$name] = $this->tableName( $name );
2369 return $retVal;
2373 * Fetch a number of table names into an zero-indexed numerical array
2374 * This is handy when you need to construct SQL for joins
2376 * Example:
2377 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2378 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2379 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2381 * @return array
2383 public function tableNamesN() {
2384 $inArray = func_get_args();
2385 $retVal = array();
2387 foreach ( $inArray as $name ) {
2388 $retVal[] = $this->tableName( $name );
2391 return $retVal;
2395 * Get an aliased table name
2396 * e.g. tableName AS newTableName
2398 * @param string $name Table name, see tableName()
2399 * @param string|bool $alias Alias (optional)
2400 * @return string SQL name for aliased table. Will not alias a table to its own name
2402 public function tableNameWithAlias( $name, $alias = false ) {
2403 if ( !$alias || $alias == $name ) {
2404 return $this->tableName( $name );
2405 } else {
2406 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2411 * Gets an array of aliased table names
2413 * @param array $tables Array( [alias] => table )
2414 * @return string[] See tableNameWithAlias()
2416 public function tableNamesWithAlias( $tables ) {
2417 $retval = array();
2418 foreach ( $tables as $alias => $table ) {
2419 if ( is_numeric( $alias ) ) {
2420 $alias = $table;
2422 $retval[] = $this->tableNameWithAlias( $table, $alias );
2425 return $retval;
2429 * Get an aliased field name
2430 * e.g. fieldName AS newFieldName
2432 * @param string $name Field name
2433 * @param string|bool $alias Alias (optional)
2434 * @return string SQL name for aliased field. Will not alias a field to its own name
2436 public function fieldNameWithAlias( $name, $alias = false ) {
2437 if ( !$alias || (string)$alias === (string)$name ) {
2438 return $name;
2439 } else {
2440 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2445 * Gets an array of aliased field names
2447 * @param array $fields Array( [alias] => field )
2448 * @return string[] See fieldNameWithAlias()
2450 public function fieldNamesWithAlias( $fields ) {
2451 $retval = array();
2452 foreach ( $fields as $alias => $field ) {
2453 if ( is_numeric( $alias ) ) {
2454 $alias = $field;
2456 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2459 return $retval;
2463 * Get the aliased table name clause for a FROM clause
2464 * which might have a JOIN and/or USE INDEX clause
2466 * @param array $tables ( [alias] => table )
2467 * @param array $use_index Same as for select()
2468 * @param array $join_conds Same as for select()
2469 * @return string
2471 protected function tableNamesWithUseIndexOrJOIN(
2472 $tables, $use_index = array(), $join_conds = array()
2474 $ret = array();
2475 $retJOIN = array();
2476 $use_index = (array)$use_index;
2477 $join_conds = (array)$join_conds;
2479 foreach ( $tables as $alias => $table ) {
2480 if ( !is_string( $alias ) ) {
2481 // No alias? Set it equal to the table name
2482 $alias = $table;
2484 // Is there a JOIN clause for this table?
2485 if ( isset( $join_conds[$alias] ) ) {
2486 list( $joinType, $conds ) = $join_conds[$alias];
2487 $tableClause = $joinType;
2488 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2489 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2490 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2491 if ( $use != '' ) {
2492 $tableClause .= ' ' . $use;
2495 $on = $this->makeList( (array)$conds, LIST_AND );
2496 if ( $on != '' ) {
2497 $tableClause .= ' ON (' . $on . ')';
2500 $retJOIN[] = $tableClause;
2501 } elseif ( isset( $use_index[$alias] ) ) {
2502 // Is there an INDEX clause for this table?
2503 $tableClause = $this->tableNameWithAlias( $table, $alias );
2504 $tableClause .= ' ' . $this->useIndexClause(
2505 implode( ',', (array)$use_index[$alias] )
2508 $ret[] = $tableClause;
2509 } else {
2510 $tableClause = $this->tableNameWithAlias( $table, $alias );
2512 $ret[] = $tableClause;
2516 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2517 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2518 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2520 // Compile our final table clause
2521 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2525 * Get the name of an index in a given table.
2527 * @protected Don't use outside of DatabaseBase and childs
2528 * @param string $index
2529 * @return string
2531 public function indexName( $index ) {
2532 // @FIXME: Make this protected once we move away from PHP 5.3
2533 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2535 // Backwards-compatibility hack
2536 $renamed = array(
2537 'ar_usertext_timestamp' => 'usertext_timestamp',
2538 'un_user_id' => 'user_id',
2539 'un_user_ip' => 'user_ip',
2542 if ( isset( $renamed[$index] ) ) {
2543 return $renamed[$index];
2544 } else {
2545 return $index;
2550 * Adds quotes and backslashes.
2552 * @param string|Blob $s
2553 * @return string
2555 public function addQuotes( $s ) {
2556 if ( $s instanceof Blob ) {
2557 $s = $s->fetch();
2559 if ( $s === null ) {
2560 return 'NULL';
2561 } else {
2562 # This will also quote numeric values. This should be harmless,
2563 # and protects against weird problems that occur when they really
2564 # _are_ strings such as article titles and string->number->string
2565 # conversion is not 1:1.
2566 return "'" . $this->strencode( $s ) . "'";
2571 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2572 * MySQL uses `backticks` while basically everything else uses double quotes.
2573 * Since MySQL is the odd one out here the double quotes are our generic
2574 * and we implement backticks in DatabaseMysql.
2576 * @param string $s
2577 * @return string
2579 public function addIdentifierQuotes( $s ) {
2580 return '"' . str_replace( '"', '""', $s ) . '"';
2584 * Returns if the given identifier looks quoted or not according to
2585 * the database convention for quoting identifiers .
2587 * @param string $name
2588 * @return bool
2590 public function isQuotedIdentifier( $name ) {
2591 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2595 * @param string $s
2596 * @return string
2598 protected function escapeLikeInternal( $s ) {
2599 return addcslashes( $s, '\%_' );
2603 * LIKE statement wrapper, receives a variable-length argument list with
2604 * parts of pattern to match containing either string literals that will be
2605 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2606 * the function could be provided with an array of aforementioned
2607 * parameters.
2609 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2610 * a LIKE clause that searches for subpages of 'My page title'.
2611 * Alternatively:
2612 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2613 * $query .= $dbr->buildLike( $pattern );
2615 * @since 1.16
2616 * @return string Fully built LIKE statement
2618 public function buildLike() {
2619 $params = func_get_args();
2621 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2622 $params = $params[0];
2625 $s = '';
2627 foreach ( $params as $value ) {
2628 if ( $value instanceof LikeMatch ) {
2629 $s .= $value->toString();
2630 } else {
2631 $s .= $this->escapeLikeInternal( $value );
2635 return " LIKE {$this->addQuotes( $s )} ";
2639 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2641 * @return LikeMatch
2643 public function anyChar() {
2644 return new LikeMatch( '_' );
2648 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2650 * @return LikeMatch
2652 public function anyString() {
2653 return new LikeMatch( '%' );
2657 * Returns an appropriately quoted sequence value for inserting a new row.
2658 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2659 * subclass will return an integer, and save the value for insertId()
2661 * Any implementation of this function should *not* involve reusing
2662 * sequence numbers created for rolled-back transactions.
2663 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2664 * @param string $seqName
2665 * @return null|int
2667 public function nextSequenceValue( $seqName ) {
2668 return null;
2672 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2673 * is only needed because a) MySQL must be as efficient as possible due to
2674 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2675 * which index to pick. Anyway, other databases might have different
2676 * indexes on a given table. So don't bother overriding this unless you're
2677 * MySQL.
2678 * @param string $index
2679 * @return string
2681 public function useIndexClause( $index ) {
2682 return '';
2686 * REPLACE query wrapper.
2688 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2689 * except that when there is a duplicate key error, the old row is deleted
2690 * and the new row is inserted in its place.
2692 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2693 * perform the delete, we need to know what the unique indexes are so that
2694 * we know how to find the conflicting rows.
2696 * It may be more efficient to leave off unique indexes which are unlikely
2697 * to collide. However if you do this, you run the risk of encountering
2698 * errors which wouldn't have occurred in MySQL.
2700 * @param string $table The table to replace the row(s) in.
2701 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2702 * a field name or an array of field names
2703 * @param array $rows Can be either a single row to insert, or multiple rows,
2704 * in the same format as for DatabaseBase::insert()
2705 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2707 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2708 $quotedTable = $this->tableName( $table );
2710 if ( count( $rows ) == 0 ) {
2711 return;
2714 # Single row case
2715 if ( !is_array( reset( $rows ) ) ) {
2716 $rows = array( $rows );
2719 // @FXIME: this is not atomic, but a trx would break affectedRows()
2720 foreach ( $rows as $row ) {
2721 # Delete rows which collide
2722 if ( $uniqueIndexes ) {
2723 $sql = "DELETE FROM $quotedTable WHERE ";
2724 $first = true;
2725 foreach ( $uniqueIndexes as $index ) {
2726 if ( $first ) {
2727 $first = false;
2728 $sql .= '( ';
2729 } else {
2730 $sql .= ' ) OR ( ';
2732 if ( is_array( $index ) ) {
2733 $first2 = true;
2734 foreach ( $index as $col ) {
2735 if ( $first2 ) {
2736 $first2 = false;
2737 } else {
2738 $sql .= ' AND ';
2740 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2742 } else {
2743 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2746 $sql .= ' )';
2747 $this->query( $sql, $fname );
2750 # Now insert the row
2751 $this->insert( $table, $row, $fname );
2756 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2757 * statement.
2759 * @param string $table Table name
2760 * @param array|string $rows Row(s) to insert
2761 * @param string $fname Caller function name
2763 * @return ResultWrapper
2765 protected function nativeReplace( $table, $rows, $fname ) {
2766 $table = $this->tableName( $table );
2768 # Single row case
2769 if ( !is_array( reset( $rows ) ) ) {
2770 $rows = array( $rows );
2773 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2774 $first = true;
2776 foreach ( $rows as $row ) {
2777 if ( $first ) {
2778 $first = false;
2779 } else {
2780 $sql .= ',';
2783 $sql .= '(' . $this->makeList( $row ) . ')';
2786 return $this->query( $sql, $fname );
2790 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2792 * This updates any conflicting rows (according to the unique indexes) using
2793 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2795 * $rows may be either:
2796 * - A single associative array. The array keys are the field names, and
2797 * the values are the values to insert. The values are treated as data
2798 * and will be quoted appropriately. If NULL is inserted, this will be
2799 * converted to a database NULL.
2800 * - An array with numeric keys, holding a list of associative arrays.
2801 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2802 * each subarray must be identical to each other, and in the same order.
2804 * It may be more efficient to leave off unique indexes which are unlikely
2805 * to collide. However if you do this, you run the risk of encountering
2806 * errors which wouldn't have occurred in MySQL.
2808 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2809 * returns success.
2811 * @since 1.22
2813 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2814 * @param array $rows A single row or list of rows to insert
2815 * @param array $uniqueIndexes List of single field names or field name tuples
2816 * @param array $set An array of values to SET. For each array element, the
2817 * key gives the field name, and the value gives the data to set that
2818 * field to. The data will be quoted by DatabaseBase::addQuotes().
2819 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2820 * @throws Exception
2821 * @return bool
2823 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2824 $fname = __METHOD__
2826 if ( !count( $rows ) ) {
2827 return true; // nothing to do
2830 if ( !is_array( reset( $rows ) ) ) {
2831 $rows = array( $rows );
2834 if ( count( $uniqueIndexes ) ) {
2835 $clauses = array(); // list WHERE clauses that each identify a single row
2836 foreach ( $rows as $row ) {
2837 foreach ( $uniqueIndexes as $index ) {
2838 $index = is_array( $index ) ? $index : array( $index ); // columns
2839 $rowKey = array(); // unique key to this row
2840 foreach ( $index as $column ) {
2841 $rowKey[$column] = $row[$column];
2843 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2846 $where = array( $this->makeList( $clauses, LIST_OR ) );
2847 } else {
2848 $where = false;
2851 $useTrx = !$this->mTrxLevel;
2852 if ( $useTrx ) {
2853 $this->begin( $fname );
2855 try {
2856 # Update any existing conflicting row(s)
2857 if ( $where !== false ) {
2858 $ok = $this->update( $table, $set, $where, $fname );
2859 } else {
2860 $ok = true;
2862 # Now insert any non-conflicting row(s)
2863 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2864 } catch ( Exception $e ) {
2865 if ( $useTrx ) {
2866 $this->rollback( $fname );
2868 throw $e;
2870 if ( $useTrx ) {
2871 $this->commit( $fname );
2874 return $ok;
2878 * DELETE where the condition is a join.
2880 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2881 * we use sub-selects
2883 * For safety, an empty $conds will not delete everything. If you want to
2884 * delete all rows where the join condition matches, set $conds='*'.
2886 * DO NOT put the join condition in $conds.
2888 * @param string $delTable The table to delete from.
2889 * @param string $joinTable The other table.
2890 * @param string $delVar The variable to join on, in the first table.
2891 * @param string $joinVar The variable to join on, in the second table.
2892 * @param array $conds Condition array of field names mapped to variables,
2893 * ANDed together in the WHERE clause
2894 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2895 * @throws DBUnexpectedError
2897 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2898 $fname = __METHOD__
2900 if ( !$conds ) {
2901 throw new DBUnexpectedError( $this,
2902 'DatabaseBase::deleteJoin() called with empty $conds' );
2905 $delTable = $this->tableName( $delTable );
2906 $joinTable = $this->tableName( $joinTable );
2907 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2908 if ( $conds != '*' ) {
2909 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
2911 $sql .= ')';
2913 $this->query( $sql, $fname );
2917 * Returns the size of a text field, or -1 for "unlimited"
2919 * @param string $table
2920 * @param string $field
2921 * @return int
2923 public function textFieldSize( $table, $field ) {
2924 $table = $this->tableName( $table );
2925 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2926 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2927 $row = $this->fetchObject( $res );
2929 $m = array();
2931 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
2932 $size = $m[1];
2933 } else {
2934 $size = -1;
2937 return $size;
2941 * A string to insert into queries to show that they're low-priority, like
2942 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2943 * string and nothing bad should happen.
2945 * @return string Returns the text of the low priority option if it is
2946 * supported, or a blank string otherwise
2948 public function lowPriorityOption() {
2949 return '';
2953 * DELETE query wrapper.
2955 * @param array $table Table name
2956 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
2957 * for the format. Use $conds == "*" to delete all rows
2958 * @param string $fname Name of the calling function
2959 * @throws DBUnexpectedError
2960 * @return bool|ResultWrapper
2962 public function delete( $table, $conds, $fname = __METHOD__ ) {
2963 if ( !$conds ) {
2964 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2967 $table = $this->tableName( $table );
2968 $sql = "DELETE FROM $table";
2970 if ( $conds != '*' ) {
2971 if ( is_array( $conds ) ) {
2972 $conds = $this->makeList( $conds, LIST_AND );
2974 $sql .= ' WHERE ' . $conds;
2977 return $this->query( $sql, $fname );
2981 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2982 * into another table.
2984 * @param string $destTable The table name to insert into
2985 * @param string|array $srcTable May be either a table name, or an array of table names
2986 * to include in a join.
2988 * @param array $varMap Must be an associative array of the form
2989 * array( 'dest1' => 'source1', ...). Source items may be literals
2990 * rather than field names, but strings should be quoted with
2991 * DatabaseBase::addQuotes()
2993 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
2994 * the details of the format of condition arrays. May be "*" to copy the
2995 * whole table.
2997 * @param string $fname The function name of the caller, from __METHOD__
2999 * @param array $insertOptions Options for the INSERT part of the query, see
3000 * DatabaseBase::insert() for details.
3001 * @param array $selectOptions Options for the SELECT part of the query, see
3002 * DatabaseBase::select() for details.
3004 * @return ResultWrapper
3006 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3007 $fname = __METHOD__,
3008 $insertOptions = array(), $selectOptions = array()
3010 $destTable = $this->tableName( $destTable );
3012 if ( !is_array( $insertOptions ) ) {
3013 $insertOptions = array( $insertOptions );
3016 $insertOptions = $this->makeInsertOptions( $insertOptions );
3018 if ( !is_array( $selectOptions ) ) {
3019 $selectOptions = array( $selectOptions );
3022 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3024 if ( is_array( $srcTable ) ) {
3025 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3026 } else {
3027 $srcTable = $this->tableName( $srcTable );
3030 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3031 " SELECT $startOpts " . implode( ',', $varMap ) .
3032 " FROM $srcTable $useIndex ";
3034 if ( $conds != '*' ) {
3035 if ( is_array( $conds ) ) {
3036 $conds = $this->makeList( $conds, LIST_AND );
3038 $sql .= " WHERE $conds";
3041 $sql .= " $tailOpts";
3043 return $this->query( $sql, $fname );
3047 * Construct a LIMIT query with optional offset. This is used for query
3048 * pages. The SQL should be adjusted so that only the first $limit rows
3049 * are returned. If $offset is provided as well, then the first $offset
3050 * rows should be discarded, and the next $limit rows should be returned.
3051 * If the result of the query is not ordered, then the rows to be returned
3052 * are theoretically arbitrary.
3054 * $sql is expected to be a SELECT, if that makes a difference.
3056 * The version provided by default works in MySQL and SQLite. It will very
3057 * likely need to be overridden for most other DBMSes.
3059 * @param string $sql SQL query we will append the limit too
3060 * @param int $limit The SQL limit
3061 * @param int|bool $offset The SQL offset (default false)
3062 * @throws DBUnexpectedError
3063 * @return string
3065 public function limitResult( $sql, $limit, $offset = false ) {
3066 if ( !is_numeric( $limit ) ) {
3067 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3070 return "$sql LIMIT "
3071 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3072 . "{$limit} ";
3076 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3077 * within the UNION construct.
3078 * @return bool
3080 public function unionSupportsOrderAndLimit() {
3081 return true; // True for almost every DB supported
3085 * Construct a UNION query
3086 * This is used for providing overload point for other DB abstractions
3087 * not compatible with the MySQL syntax.
3088 * @param array $sqls SQL statements to combine
3089 * @param bool $all Use UNION ALL
3090 * @return string SQL fragment
3092 public function unionQueries( $sqls, $all ) {
3093 $glue = $all ? ') UNION ALL (' : ') UNION (';
3095 return '(' . implode( $glue, $sqls ) . ')';
3099 * Returns an SQL expression for a simple conditional. This doesn't need
3100 * to be overridden unless CASE isn't supported in your DBMS.
3102 * @param string|array $cond SQL expression which will result in a boolean value
3103 * @param string $trueVal SQL expression to return if true
3104 * @param string $falseVal SQL expression to return if false
3105 * @return string SQL fragment
3107 public function conditional( $cond, $trueVal, $falseVal ) {
3108 if ( is_array( $cond ) ) {
3109 $cond = $this->makeList( $cond, LIST_AND );
3112 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3116 * Returns a comand for str_replace function in SQL query.
3117 * Uses REPLACE() in MySQL
3119 * @param string $orig Column to modify
3120 * @param string $old Column to seek
3121 * @param string $new Column to replace with
3123 * @return string
3125 public function strreplace( $orig, $old, $new ) {
3126 return "REPLACE({$orig}, {$old}, {$new})";
3130 * Determines how long the server has been up
3131 * STUB
3133 * @return int
3135 public function getServerUptime() {
3136 return 0;
3140 * Determines if the last failure was due to a deadlock
3141 * STUB
3143 * @return bool
3145 public function wasDeadlock() {
3146 return false;
3150 * Determines if the last failure was due to a lock timeout
3151 * STUB
3153 * @return bool
3155 public function wasLockTimeout() {
3156 return false;
3160 * Determines if the last query error was something that should be dealt
3161 * with by pinging the connection and reissuing the query.
3162 * STUB
3164 * @return bool
3166 public function wasErrorReissuable() {
3167 return false;
3171 * Determines if the last failure was due to the database being read-only.
3172 * STUB
3174 * @return bool
3176 public function wasReadOnlyError() {
3177 return false;
3181 * Determines if the given query error was a connection drop
3182 * STUB
3184 * @param integer|string $errno
3185 * @return bool
3187 public function wasConnectionError( $errno ) {
3188 return false;
3192 * Perform a deadlock-prone transaction.
3194 * This function invokes a callback function to perform a set of write
3195 * queries. If a deadlock occurs during the processing, the transaction
3196 * will be rolled back and the callback function will be called again.
3198 * Usage:
3199 * $dbw->deadlockLoop( callback, ... );
3201 * Extra arguments are passed through to the specified callback function.
3203 * Returns whatever the callback function returned on its successful,
3204 * iteration, or false on error, for example if the retry limit was
3205 * reached.
3207 * @return mixed
3208 * @throws DBQueryError
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 $retVal = null;
3223 $e = null;
3224 do {
3225 try {
3226 $retVal = call_user_func_array( $function, $args );
3227 break;
3228 } catch ( DBQueryError $e ) {
3229 if ( $this->wasDeadlock() ) {
3230 // Retry after a randomized delay
3231 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3232 } else {
3233 // Throw the error back up
3234 throw $e;
3237 } while ( --$tries > 0 );
3239 if ( $tries <= 0 ) {
3240 // Too many deadlocks; give up
3241 $this->rollback( __METHOD__ );
3242 throw $e;
3243 } else {
3244 $this->commit( __METHOD__ );
3246 return $retVal;
3251 * Wait for the slave to catch up to a given master position.
3253 * @param DBMasterPos $pos
3254 * @param int $timeout The maximum number of seconds to wait for
3255 * synchronisation
3256 * @return int Zero if the slave was past that position already,
3257 * greater than zero if we waited for some period of time, less than
3258 * zero if we timed out.
3260 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3261 # Real waits are implemented in the subclass.
3262 return 0;
3266 * Get the replication position of this slave
3268 * @return DBMasterPos|bool False if this is not a slave.
3270 public function getSlavePos() {
3271 # Stub
3272 return false;
3276 * Get the position of this master
3278 * @return DBMasterPos|bool False if this is not a master
3280 public function getMasterPos() {
3281 # Stub
3282 return false;
3286 * Run an anonymous function as soon as there is no transaction pending.
3287 * If there is a transaction and it is rolled back, then the callback is cancelled.
3288 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3289 * Callbacks must commit any transactions that they begin.
3291 * This is useful for updates to different systems or when separate transactions are needed.
3292 * For example, one might want to enqueue jobs into a system outside the database, but only
3293 * after the database is updated so that the jobs will see the data when they actually run.
3294 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3296 * @param callable $callback
3297 * @since 1.20
3299 final public function onTransactionIdle( $callback ) {
3300 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3301 if ( !$this->mTrxLevel ) {
3302 $this->runOnTransactionIdleCallbacks();
3307 * Run an anonymous function before the current transaction commits or now if there is none.
3308 * If there is a transaction and it is rolled back, then the callback is cancelled.
3309 * Callbacks must not start nor commit any transactions.
3311 * This is useful for updates that easily cause deadlocks if locks are held too long
3312 * but where atomicity is strongly desired for these updates and some related updates.
3314 * @param callable $callback
3315 * @since 1.22
3317 final public function onTransactionPreCommitOrIdle( $callback ) {
3318 if ( $this->mTrxLevel ) {
3319 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3320 } else {
3321 $this->onTransactionIdle( $callback ); // this will trigger immediately
3326 * Actually any "on transaction idle" callbacks.
3328 * @since 1.20
3330 protected function runOnTransactionIdleCallbacks() {
3331 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3333 $e = $ePrior = null; // last exception
3334 do { // callbacks may add callbacks :)
3335 $callbacks = $this->mTrxIdleCallbacks;
3336 $this->mTrxIdleCallbacks = array(); // recursion guard
3337 foreach ( $callbacks as $callback ) {
3338 try {
3339 list( $phpCallback ) = $callback;
3340 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3341 call_user_func( $phpCallback );
3342 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3343 } catch ( Exception $e ) {
3344 if ( $ePrior ) {
3345 MWExceptionHandler::logException( $ePrior );
3347 $ePrior = $e;
3350 } while ( count( $this->mTrxIdleCallbacks ) );
3352 if ( $e instanceof Exception ) {
3353 throw $e; // re-throw any last exception
3358 * Actually any "on transaction pre-commit" callbacks.
3360 * @since 1.22
3362 protected function runOnTransactionPreCommitCallbacks() {
3363 $e = $ePrior = null; // last exception
3364 do { // callbacks may add callbacks :)
3365 $callbacks = $this->mTrxPreCommitCallbacks;
3366 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3367 foreach ( $callbacks as $callback ) {
3368 try {
3369 list( $phpCallback ) = $callback;
3370 call_user_func( $phpCallback );
3371 } catch ( Exception $e ) {
3372 if ( $ePrior ) {
3373 MWExceptionHandler::logException( $ePrior );
3375 $ePrior = $e;
3378 } while ( count( $this->mTrxPreCommitCallbacks ) );
3380 if ( $e instanceof Exception ) {
3381 throw $e; // re-throw any last exception
3386 * Begin an atomic section of statements
3388 * If a transaction has been started already, just keep track of the given
3389 * section name to make sure the transaction is not committed pre-maturely.
3390 * This function can be used in layers (with sub-sections), so use a stack
3391 * to keep track of the different atomic sections. If there is no transaction,
3392 * start one implicitly.
3394 * The goal of this function is to create an atomic section of SQL queries
3395 * without having to start a new transaction if it already exists.
3397 * Atomic sections are more strict than transactions. With transactions,
3398 * attempting to begin a new transaction when one is already running results
3399 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3400 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3401 * and any database transactions cannot be began or committed until all atomic
3402 * levels are closed. There is no such thing as implicitly opening or closing
3403 * an atomic section.
3405 * @since 1.23
3406 * @param string $fname
3407 * @throws DBError
3409 final public function startAtomic( $fname = __METHOD__ ) {
3410 if ( !$this->mTrxLevel ) {
3411 $this->begin( $fname );
3412 $this->mTrxAutomatic = true;
3413 // If DBO_TRX is set, a series of startAtomic/endAtomic pairs will result
3414 // in all changes being in one transaction to keep requests transactional.
3415 if ( !$this->getFlag( DBO_TRX ) ) {
3416 $this->mTrxAutomaticAtomic = true;
3420 $this->mTrxAtomicLevels->push( $fname );
3424 * Ends an atomic section of SQL statements
3426 * Ends the next section of atomic SQL statements and commits the transaction
3427 * if necessary.
3429 * @since 1.23
3430 * @see DatabaseBase::startAtomic
3431 * @param string $fname
3432 * @throws DBError
3434 final public function endAtomic( $fname = __METHOD__ ) {
3435 if ( !$this->mTrxLevel ) {
3436 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3438 if ( $this->mTrxAtomicLevels->isEmpty() ||
3439 $this->mTrxAtomicLevels->pop() !== $fname
3441 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3444 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3445 $this->commit( $fname, 'flush' );
3450 * Begin a transaction. If a transaction is already in progress,
3451 * that transaction will be committed before the new transaction is started.
3453 * Note that when the DBO_TRX flag is set (which is usually the case for web
3454 * requests, but not for maintenance scripts), any previous database query
3455 * will have started a transaction automatically.
3457 * Nesting of transactions is not supported. Attempts to nest transactions
3458 * will cause a warning, unless the current transaction was started
3459 * automatically because of the DBO_TRX flag.
3461 * @param string $fname
3462 * @throws DBError
3464 final public function begin( $fname = __METHOD__ ) {
3465 global $wgDebugDBTransactions;
3467 if ( $this->mTrxLevel ) { // implicit commit
3468 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3469 // If the current transaction was an automatic atomic one, then we definitely have
3470 // a problem. Same if there is any unclosed atomic level.
3471 throw new DBUnexpectedError( $this,
3472 "Attempted to start explicit transaction when atomic levels are still open."
3474 } elseif ( !$this->mTrxAutomatic ) {
3475 // We want to warn about inadvertently nested begin/commit pairs, but not about
3476 // auto-committing implicit transactions that were started by query() via DBO_TRX
3477 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3478 " performing implicit commit!";
3479 wfWarn( $msg );
3480 wfLogDBError( $msg,
3481 $this->getLogContext( array(
3482 'method' => __METHOD__,
3483 'fname' => $fname,
3486 } else {
3487 // if the transaction was automatic and has done write operations,
3488 // log it if $wgDebugDBTransactions is enabled.
3489 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3490 wfDebug( "$fname: Automatic transaction with writes in progress" .
3491 " (from {$this->mTrxFname}), performing implicit commit!\n"
3496 $this->runOnTransactionPreCommitCallbacks();
3497 $writeTime = $this->pendingWriteQueryDuration();
3498 $this->doCommit( $fname );
3499 if ( $this->mTrxDoneWrites ) {
3500 $this->mDoneWrites = microtime( true );
3501 $this->getTransactionProfiler()->transactionWritingOut(
3502 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3504 $this->runOnTransactionIdleCallbacks();
3507 # Avoid fatals if close() was called
3508 $this->assertOpen();
3510 $this->doBegin( $fname );
3511 $this->mTrxTimestamp = microtime( true );
3512 $this->mTrxFname = $fname;
3513 $this->mTrxDoneWrites = false;
3514 $this->mTrxAutomatic = false;
3515 $this->mTrxAutomaticAtomic = false;
3516 $this->mTrxAtomicLevels = new SplStack;
3517 $this->mTrxIdleCallbacks = array();
3518 $this->mTrxPreCommitCallbacks = array();
3519 $this->mTrxShortId = wfRandomString( 12 );
3520 $this->mTrxWriteDuration = 0.0;
3524 * Issues the BEGIN command to the database server.
3526 * @see DatabaseBase::begin()
3527 * @param string $fname
3529 protected function doBegin( $fname ) {
3530 $this->query( 'BEGIN', $fname );
3531 $this->mTrxLevel = 1;
3535 * Commits a transaction previously started using begin().
3536 * If no transaction is in progress, a warning is issued.
3538 * Nesting of transactions is not supported.
3540 * @param string $fname
3541 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3542 * explicitly committing implicit transactions, or calling commit when no
3543 * transaction is in progress. This will silently break any ongoing
3544 * explicit transaction. Only set the flush flag if you are sure that it
3545 * is safe to ignore these warnings in your context.
3546 * @throws DBUnexpectedError
3548 final public function commit( $fname = __METHOD__, $flush = '' ) {
3549 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3550 // There are still atomic sections open. This cannot be ignored
3551 throw new DBUnexpectedError(
3552 $this,
3553 "Attempted to commit transaction while atomic sections are still open"
3557 if ( $flush === 'flush' ) {
3558 if ( !$this->mTrxLevel ) {
3559 return; // nothing to do
3560 } elseif ( !$this->mTrxAutomatic ) {
3561 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3563 } else {
3564 if ( !$this->mTrxLevel ) {
3565 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3566 return; // nothing to do
3567 } elseif ( $this->mTrxAutomatic ) {
3568 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3572 # Avoid fatals if close() was called
3573 $this->assertOpen();
3575 $this->runOnTransactionPreCommitCallbacks();
3576 $writeTime = $this->pendingWriteQueryDuration();
3577 $this->doCommit( $fname );
3578 if ( $this->mTrxDoneWrites ) {
3579 $this->mDoneWrites = microtime( true );
3580 $this->getTransactionProfiler()->transactionWritingOut(
3581 $this->mServer, $this->mDBname, $this->mTrxShortId, $writeTime );
3583 $this->runOnTransactionIdleCallbacks();
3587 * Issues the COMMIT command to the database server.
3589 * @see DatabaseBase::commit()
3590 * @param string $fname
3592 protected function doCommit( $fname ) {
3593 if ( $this->mTrxLevel ) {
3594 $this->query( 'COMMIT', $fname );
3595 $this->mTrxLevel = 0;
3600 * Rollback a transaction previously started using begin().
3601 * If no transaction is in progress, a warning is issued.
3603 * No-op on non-transactional databases.
3605 * @param string $fname
3606 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3607 * calling rollback when no transaction is in progress. This will silently
3608 * break any ongoing explicit transaction. Only set the flush flag if you
3609 * are sure that it is safe to ignore these warnings in your context.
3610 * @throws DBUnexpectedError
3611 * @since 1.23 Added $flush parameter
3613 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3614 if ( $flush !== 'flush' ) {
3615 if ( !$this->mTrxLevel ) {
3616 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3617 return; // nothing to do
3618 } elseif ( $this->mTrxAutomatic ) {
3619 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3621 } else {
3622 if ( !$this->mTrxLevel ) {
3623 return; // nothing to do
3624 } elseif ( !$this->mTrxAutomatic ) {
3625 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3629 # Avoid fatals if close() was called
3630 $this->assertOpen();
3632 $this->doRollback( $fname );
3633 $this->mTrxIdleCallbacks = array(); // cancel
3634 $this->mTrxPreCommitCallbacks = array(); // cancel
3635 $this->mTrxAtomicLevels = new SplStack;
3636 if ( $this->mTrxDoneWrites ) {
3637 $this->getTransactionProfiler()->transactionWritingOut(
3638 $this->mServer, $this->mDBname, $this->mTrxShortId );
3643 * Issues the ROLLBACK command to the database server.
3645 * @see DatabaseBase::rollback()
3646 * @param string $fname
3648 protected function doRollback( $fname ) {
3649 if ( $this->mTrxLevel ) {
3650 $this->query( 'ROLLBACK', $fname, true );
3651 $this->mTrxLevel = 0;
3656 * Creates a new table with structure copied from existing table
3657 * Note that unlike most database abstraction functions, this function does not
3658 * automatically append database prefix, because it works at a lower
3659 * abstraction level.
3660 * The table names passed to this function shall not be quoted (this
3661 * function calls addIdentifierQuotes when needed).
3663 * @param string $oldName Name of table whose structure should be copied
3664 * @param string $newName Name of table to be created
3665 * @param bool $temporary Whether the new table should be temporary
3666 * @param string $fname Calling function name
3667 * @throws MWException
3668 * @return bool True if operation was successful
3670 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3671 $fname = __METHOD__
3673 throw new MWException(
3674 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3678 * List all tables on the database
3680 * @param string $prefix Only show tables with this prefix, e.g. mw_
3681 * @param string $fname Calling function name
3682 * @throws MWException
3683 * @return array
3685 function listTables( $prefix = null, $fname = __METHOD__ ) {
3686 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3690 * Reset the views process cache set by listViews()
3691 * @since 1.22
3693 final public function clearViewsCache() {
3694 $this->allViews = null;
3698 * Lists all the VIEWs in the database
3700 * For caching purposes the list of all views should be stored in
3701 * $this->allViews. The process cache can be cleared with clearViewsCache()
3703 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3704 * @param string $fname Name of calling function
3705 * @throws MWException
3706 * @return array
3707 * @since 1.22
3709 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3710 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3714 * Differentiates between a TABLE and a VIEW
3716 * @param string $name Name of the database-structure to test.
3717 * @throws MWException
3718 * @return bool
3719 * @since 1.22
3721 public function isView( $name ) {
3722 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3726 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3727 * to the format used for inserting into timestamp fields in this DBMS.
3729 * The result is unquoted, and needs to be passed through addQuotes()
3730 * before it can be included in raw SQL.
3732 * @param string|int $ts
3734 * @return string
3736 public function timestamp( $ts = 0 ) {
3737 return wfTimestamp( TS_MW, $ts );
3741 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3742 * to the format used for inserting into timestamp fields in this DBMS. If
3743 * NULL is input, it is passed through, allowing NULL values to be inserted
3744 * into timestamp fields.
3746 * The result is unquoted, and needs to be passed through addQuotes()
3747 * before it can be included in raw SQL.
3749 * @param string|int $ts
3751 * @return string
3753 public function timestampOrNull( $ts = null ) {
3754 if ( is_null( $ts ) ) {
3755 return null;
3756 } else {
3757 return $this->timestamp( $ts );
3762 * Take the result from a query, and wrap it in a ResultWrapper if
3763 * necessary. Boolean values are passed through as is, to indicate success
3764 * of write queries or failure.
3766 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3767 * resource, and it was necessary to call this function to convert it to
3768 * a wrapper. Nowadays, raw database objects are never exposed to external
3769 * callers, so this is unnecessary in external code. For compatibility with
3770 * old code, ResultWrapper objects are passed through unaltered.
3772 * @param bool|ResultWrapper|resource $result
3773 * @return bool|ResultWrapper
3775 public function resultObject( $result ) {
3776 if ( empty( $result ) ) {
3777 return false;
3778 } elseif ( $result instanceof ResultWrapper ) {
3779 return $result;
3780 } elseif ( $result === true ) {
3781 // Successful write query
3782 return $result;
3783 } else {
3784 return new ResultWrapper( $this, $result );
3789 * Ping the server and try to reconnect if it there is no connection
3791 * @return bool Success or failure
3793 public function ping() {
3794 # Stub. Not essential to override.
3795 return true;
3799 * Get slave lag. Currently supported only by MySQL.
3801 * Note that this function will generate a fatal error on many
3802 * installations. Most callers should use LoadBalancer::safeGetLag()
3803 * instead.
3805 * @return int Database replication lag in seconds
3807 public function getLag() {
3808 return 0;
3812 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3814 * @return int
3816 function maxListLen() {
3817 return 0;
3821 * Some DBMSs have a special format for inserting into blob fields, they
3822 * don't allow simple quoted strings to be inserted. To insert into such
3823 * a field, pass the data through this function before passing it to
3824 * DatabaseBase::insert().
3826 * @param string $b
3827 * @return string
3829 public function encodeBlob( $b ) {
3830 return $b;
3834 * Some DBMSs return a special placeholder object representing blob fields
3835 * in result objects. Pass the object through this function to return the
3836 * original string.
3838 * @param string|Blob $b
3839 * @return string
3841 public function decodeBlob( $b ) {
3842 if ( $b instanceof Blob ) {
3843 $b = $b->fetch();
3845 return $b;
3849 * Override database's default behavior. $options include:
3850 * 'connTimeout' : Set the connection timeout value in seconds.
3851 * May be useful for very long batch queries such as
3852 * full-wiki dumps, where a single query reads out over
3853 * hours or days.
3855 * @param array $options
3856 * @return void
3858 public function setSessionOptions( array $options ) {
3862 * Read and execute SQL commands from a file.
3864 * Returns true on success, error string or exception on failure (depending
3865 * on object's error ignore settings).
3867 * @param string $filename File name to open
3868 * @param bool|callable $lineCallback Optional function called before reading each line
3869 * @param bool|callable $resultCallback Optional function called for each MySQL result
3870 * @param bool|string $fname Calling function name or false if name should be
3871 * generated dynamically using $filename
3872 * @param bool|callable $inputCallback Optional function called for each
3873 * complete line sent
3874 * @throws Exception|MWException
3875 * @return bool|string
3877 public function sourceFile(
3878 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3880 MediaWiki\suppressWarnings();
3881 $fp = fopen( $filename, 'r' );
3882 MediaWiki\restoreWarnings();
3884 if ( false === $fp ) {
3885 throw new MWException( "Could not open \"{$filename}\".\n" );
3888 if ( !$fname ) {
3889 $fname = __METHOD__ . "( $filename )";
3892 try {
3893 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
3894 } catch ( Exception $e ) {
3895 fclose( $fp );
3896 throw $e;
3899 fclose( $fp );
3901 return $error;
3905 * Get the full path of a patch file. Originally based on archive()
3906 * from updaters.inc. Keep in mind this always returns a patch, as
3907 * it fails back to MySQL if no DB-specific patch can be found
3909 * @param string $patch The name of the patch, like patch-something.sql
3910 * @return string Full path to patch file
3912 public function patchPath( $patch ) {
3913 global $IP;
3915 $dbType = $this->getType();
3916 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3917 return "$IP/maintenance/$dbType/archives/$patch";
3918 } else {
3919 return "$IP/maintenance/archives/$patch";
3924 * Set variables to be used in sourceFile/sourceStream, in preference to the
3925 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3926 * all. If it's set to false, $GLOBALS will be used.
3928 * @param bool|array $vars Mapping variable name to value.
3930 public function setSchemaVars( $vars ) {
3931 $this->mSchemaVars = $vars;
3935 * Read and execute commands from an open file handle.
3937 * Returns true on success, error string or exception on failure (depending
3938 * on object's error ignore settings).
3940 * @param resource $fp File handle
3941 * @param bool|callable $lineCallback Optional function called before reading each query
3942 * @param bool|callable $resultCallback Optional function called for each MySQL result
3943 * @param string $fname Calling function name
3944 * @param bool|callable $inputCallback Optional function called for each complete query sent
3945 * @return bool|string
3947 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3948 $fname = __METHOD__, $inputCallback = false
3950 $cmd = '';
3952 while ( !feof( $fp ) ) {
3953 if ( $lineCallback ) {
3954 call_user_func( $lineCallback );
3957 $line = trim( fgets( $fp ) );
3959 if ( $line == '' ) {
3960 continue;
3963 if ( '-' == $line[0] && '-' == $line[1] ) {
3964 continue;
3967 if ( $cmd != '' ) {
3968 $cmd .= ' ';
3971 $done = $this->streamStatementEnd( $cmd, $line );
3973 $cmd .= "$line\n";
3975 if ( $done || feof( $fp ) ) {
3976 $cmd = $this->replaceVars( $cmd );
3978 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
3979 $res = $this->query( $cmd, $fname );
3981 if ( $resultCallback ) {
3982 call_user_func( $resultCallback, $res, $this );
3985 if ( false === $res ) {
3986 $err = $this->lastError();
3988 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3991 $cmd = '';
3995 return true;
3999 * Called by sourceStream() to check if we've reached a statement end
4001 * @param string $sql SQL assembled so far
4002 * @param string $newLine New line about to be added to $sql
4003 * @return bool Whether $newLine contains end of the statement
4005 public function streamStatementEnd( &$sql, &$newLine ) {
4006 if ( $this->delimiter ) {
4007 $prev = $newLine;
4008 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4009 if ( $newLine != $prev ) {
4010 return true;
4014 return false;
4018 * Database independent variable replacement. Replaces a set of variables
4019 * in an SQL statement with their contents as given by $this->getSchemaVars().
4021 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4023 * - '{$var}' should be used for text and is passed through the database's
4024 * addQuotes method.
4025 * - `{$var}` should be used for identifiers (e.g. table and database names).
4026 * It is passed through the database's addIdentifierQuotes method which
4027 * can be overridden if the database uses something other than backticks.
4028 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4029 * database's tableName method.
4030 * - / *i* / passes the name that follows through the database's indexName method.
4031 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4032 * its use should be avoided. In 1.24 and older, string encoding was applied.
4034 * @param string $ins SQL statement to replace variables in
4035 * @return string The new SQL statement with variables replaced
4037 protected function replaceVars( $ins ) {
4038 $that = $this;
4039 $vars = $this->getSchemaVars();
4040 return preg_replace_callback(
4042 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4043 \'\{\$ (\w+) }\' | # 3. addQuotes
4044 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4045 /\*\$ (\w+) \*/ # 5. leave unencoded
4046 !x',
4047 function ( $m ) use ( $that, $vars ) {
4048 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4049 // check for both nonexistent keys *and* the empty string.
4050 if ( isset( $m[1] ) && $m[1] !== '' ) {
4051 if ( $m[1] === 'i' ) {
4052 return $that->indexName( $m[2] );
4053 } else {
4054 return $that->tableName( $m[2] );
4056 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4057 return $that->addQuotes( $vars[$m[3]] );
4058 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4059 return $that->addIdentifierQuotes( $vars[$m[4]] );
4060 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4061 return $vars[$m[5]];
4062 } else {
4063 return $m[0];
4066 $ins
4071 * Get schema variables. If none have been set via setSchemaVars(), then
4072 * use some defaults from the current object.
4074 * @return array
4076 protected function getSchemaVars() {
4077 if ( $this->mSchemaVars ) {
4078 return $this->mSchemaVars;
4079 } else {
4080 return $this->getDefaultSchemaVars();
4085 * Get schema variables to use if none have been set via setSchemaVars().
4087 * Override this in derived classes to provide variables for tables.sql
4088 * and SQL patch files.
4090 * @return array
4092 protected function getDefaultSchemaVars() {
4093 return array();
4097 * Check to see if a named lock is available (non-blocking)
4099 * @param string $lockName Name of lock to poll
4100 * @param string $method Name of method calling us
4101 * @return bool
4102 * @since 1.20
4104 public function lockIsFree( $lockName, $method ) {
4105 return true;
4109 * Acquire a named lock
4111 * Named locks are not related to transactions
4113 * @param string $lockName Name of lock to aquire
4114 * @param string $method Name of method calling us
4115 * @param int $timeout
4116 * @return bool
4118 public function lock( $lockName, $method, $timeout = 5 ) {
4119 return true;
4123 * Release a lock
4125 * Named locks are not related to transactions
4127 * @param string $lockName Name of lock to release
4128 * @param string $method Name of method calling us
4130 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4131 * by this thread (in which case the lock is not released), and NULL if the named
4132 * lock did not exist
4134 public function unlock( $lockName, $method ) {
4135 return true;
4139 * Check to see if a named lock used by lock() use blocking queues
4141 * @return bool
4142 * @since 1.26
4144 public function namedLocksEnqueue() {
4145 return false;
4149 * Lock specific tables
4151 * @param array $read Array of tables to lock for read access
4152 * @param array $write Array of tables to lock for write access
4153 * @param string $method Name of caller
4154 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4155 * @return bool
4157 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4158 return true;
4162 * Unlock specific tables
4164 * @param string $method The caller
4165 * @return bool
4167 public function unlockTables( $method ) {
4168 return true;
4172 * Delete a table
4173 * @param string $tableName
4174 * @param string $fName
4175 * @return bool|ResultWrapper
4176 * @since 1.18
4178 public function dropTable( $tableName, $fName = __METHOD__ ) {
4179 if ( !$this->tableExists( $tableName, $fName ) ) {
4180 return false;
4182 $sql = "DROP TABLE " . $this->tableName( $tableName );
4183 if ( $this->cascadingDeletes() ) {
4184 $sql .= " CASCADE";
4187 return $this->query( $sql, $fName );
4191 * Get search engine class. All subclasses of this need to implement this
4192 * if they wish to use searching.
4194 * @return string
4196 public function getSearchEngine() {
4197 return 'SearchEngineDummy';
4201 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4202 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4203 * because "i" sorts after all numbers.
4205 * @return string
4207 public function getInfinity() {
4208 return 'infinity';
4212 * Encode an expiry time into the DBMS dependent format
4214 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4215 * @return string
4217 public function encodeExpiry( $expiry ) {
4218 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4219 ? $this->getInfinity()
4220 : $this->timestamp( $expiry );
4224 * Decode an expiry time into a DBMS independent format
4226 * @param string $expiry DB timestamp field value for expiry
4227 * @param int $format TS_* constant, defaults to TS_MW
4228 * @return string
4230 public function decodeExpiry( $expiry, $format = TS_MW ) {
4231 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4232 ? 'infinity'
4233 : wfTimestamp( $format, $expiry );
4237 * Allow or deny "big selects" for this session only. This is done by setting
4238 * the sql_big_selects session variable.
4240 * This is a MySQL-specific feature.
4242 * @param bool|string $value True for allow, false for deny, or "default" to
4243 * restore the initial value
4245 public function setBigSelects( $value = true ) {
4246 // no-op
4250 * @since 1.19
4251 * @return string
4253 public function __toString() {
4254 return (string)$this->mConn;
4258 * Run a few simple sanity checks
4260 public function __destruct() {
4261 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4262 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4264 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4265 $callers = array();
4266 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4267 $callers[] = $callbackInfo[1];
4269 $callers = implode( ', ', $callers );
4270 trigger_error( "DB transaction callbacks still pending (from $callers)." );