Merge "DatabaseMssql: Don't duplicate body of makeList()"
[mediawiki.git] / includes / db / Database.php
blob8fa10a633d23106aa04b6f19eb25a1e927a6443f
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 * Interface for classes that implement or wrap DatabaseBase
30 * @ingroup Database
32 interface IDatabase {
35 /**
36 * Database abstraction object
37 * @ingroup Database
39 abstract class DatabaseBase implements IDatabase {
40 /** Number of times to re-try an operation in case of deadlock */
41 const DEADLOCK_TRIES = 4;
43 /** Minimum time to wait before retry, in microseconds */
44 const DEADLOCK_DELAY_MIN = 500000;
46 /** Maximum time to wait before retry */
47 const DEADLOCK_DELAY_MAX = 1500000;
49 protected $mLastQuery = '';
50 protected $mDoneWrites = false;
51 protected $mPHPError = false;
53 protected $mServer, $mUser, $mPassword, $mDBname;
55 /** @var resource Database connection */
56 protected $mConn = null;
57 protected $mOpened = false;
59 /** @var callable[] */
60 protected $mTrxIdleCallbacks = array();
61 /** @var callable[] */
62 protected $mTrxPreCommitCallbacks = array();
64 protected $mTablePrefix;
65 protected $mSchema;
66 protected $mFlags;
67 protected $mForeign;
68 protected $mErrorCount = 0;
69 protected $mLBInfo = array();
70 protected $mDefaultBigSelects = null;
71 protected $mSchemaVars = false;
73 protected $preparedArgs;
75 protected $htmlErrors;
77 protected $delimiter = ';';
79 /**
80 * Either 1 if a transaction is active or 0 otherwise.
81 * The other Trx fields may not be meaningfull if this is 0.
83 * @var int
85 protected $mTrxLevel = 0;
87 /**
88 * Either a short hexidecimal string if a transaction is active or ""
90 * @var string
91 * @see DatabaseBase::mTrxLevel
93 protected $mTrxShortId = '';
95 /**
96 * The UNIX time that the transaction started. Callers can assume that if
97 * snapshot isolation is used, then the data is *at least* up to date to that
98 * point (possibly more up-to-date since the first SELECT defines the snapshot).
100 * @var float|null
101 * @see DatabaseBase::mTrxLevel
103 private $mTrxTimestamp = null;
106 * Remembers the function name given for starting the most recent transaction via begin().
107 * Used to provide additional context for error reporting.
109 * @var string
110 * @see DatabaseBase::mTrxLevel
112 private $mTrxFname = null;
115 * Record if possible write queries were done in the last transaction started
117 * @var bool
118 * @see DatabaseBase::mTrxLevel
120 private $mTrxDoneWrites = false;
123 * Record if the current transaction was started implicitly due to DBO_TRX being set.
125 * @var bool
126 * @see DatabaseBase::mTrxLevel
128 private $mTrxAutomatic = false;
131 * Array of levels of atomicity within transactions
133 * @var SplStack
135 private $mTrxAtomicLevels;
138 * Record if the current transaction was started implicitly by DatabaseBase::startAtomic
140 * @var bool
142 private $mTrxAutomaticAtomic = false;
145 * @since 1.21
146 * @var resource File handle for upgrade
148 protected $fileHandle = null;
151 * @since 1.22
152 * @var string[] Process cache of VIEWs names in the database
154 protected $allViews = null;
157 * A string describing the current software version, and possibly
158 * other details in a user-friendly way. Will be listed on Special:Version, etc.
159 * Use getServerVersion() to get machine-friendly information.
161 * @return string Version information from the database server
163 public function getServerInfo() {
164 return $this->getServerVersion();
168 * @return string Command delimiter used by this database engine
170 public function getDelimiter() {
171 return $this->delimiter;
175 * Boolean, controls output of large amounts of debug information.
176 * @param bool|null $debug
177 * - true to enable debugging
178 * - false to disable debugging
179 * - omitted or null to do nothing
181 * @return bool|null Previous value of the flag
183 public function debug( $debug = null ) {
184 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
188 * Turns buffering of SQL result sets on (true) or off (false). Default is
189 * "on".
191 * Unbuffered queries are very troublesome in MySQL:
193 * - If another query is executed while the first query is being read
194 * out, the first query is killed. This means you can't call normal
195 * MediaWiki functions while you are reading an unbuffered query result
196 * from a normal wfGetDB() connection.
198 * - Unbuffered queries cause the MySQL server to use large amounts of
199 * memory and to hold broad locks which block other queries.
201 * If you want to limit client-side memory, it's almost always better to
202 * split up queries into batches using a LIMIT clause than to switch off
203 * buffering.
205 * @param null|bool $buffer
206 * @return null|bool The previous value of the flag
208 public function bufferResults( $buffer = null ) {
209 if ( is_null( $buffer ) ) {
210 return !(bool)( $this->mFlags & DBO_NOBUFFER );
211 } else {
212 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
217 * Turns on (false) or off (true) the automatic generation and sending
218 * of a "we're sorry, but there has been a database error" page on
219 * database errors. Default is on (false). When turned off, the
220 * code should use lastErrno() and lastError() to handle the
221 * situation as appropriate.
223 * Do not use this function outside of the Database classes.
225 * @param null|bool $ignoreErrors
226 * @return bool The previous value of the flag.
228 public function ignoreErrors( $ignoreErrors = null ) {
229 return wfSetBit( $this->mFlags, DBO_IGNORE, $ignoreErrors );
233 * Gets the current transaction level.
235 * Historically, transactions were allowed to be "nested". This is no
236 * longer supported, so this function really only returns a boolean.
238 * @return int The previous value
240 public function trxLevel() {
241 return $this->mTrxLevel;
245 * Get the UNIX timestamp of the time that the transaction was established
247 * This can be used to reason about the staleness of SELECT data
248 * in REPEATABLE-READ transaction isolation level.
250 * @return float|null Returns null if there is not active transaction
251 * @since 1.25
253 public function trxTimestamp() {
254 return $this->mTrxLevel ? $this->mTrxTimestamp : null;
258 * Get/set the number of errors logged. Only useful when errors are ignored
259 * @param int $count The count to set, or omitted to leave it unchanged.
260 * @return int The error count
262 public function errorCount( $count = null ) {
263 return wfSetVar( $this->mErrorCount, $count );
267 * Get/set the table prefix.
268 * @param string $prefix The table prefix to set, or omitted to leave it unchanged.
269 * @return string The previous table prefix.
271 public function tablePrefix( $prefix = null ) {
272 return wfSetVar( $this->mTablePrefix, $prefix );
276 * Get/set the db schema.
277 * @param string $schema The database schema to set, or omitted to leave it unchanged.
278 * @return string The previous db schema.
280 public function dbSchema( $schema = null ) {
281 return wfSetVar( $this->mSchema, $schema );
285 * Set the filehandle to copy write statements to.
287 * @param resource $fh File handle
289 public function setFileHandle( $fh ) {
290 $this->fileHandle = $fh;
294 * Get properties passed down from the server info array of the load
295 * balancer.
297 * @param string $name The entry of the info array to get, or null to get the
298 * whole array
300 * @return array|mixed|null
302 public function getLBInfo( $name = null ) {
303 if ( is_null( $name ) ) {
304 return $this->mLBInfo;
305 } else {
306 if ( array_key_exists( $name, $this->mLBInfo ) ) {
307 return $this->mLBInfo[$name];
308 } else {
309 return null;
315 * Set the LB info array, or a member of it. If called with one parameter,
316 * the LB info array is set to that parameter. If it is called with two
317 * parameters, the member with the given name is set to the given value.
319 * @param string $name
320 * @param array $value
322 public function setLBInfo( $name, $value = null ) {
323 if ( is_null( $value ) ) {
324 $this->mLBInfo = $name;
325 } else {
326 $this->mLBInfo[$name] = $value;
331 * Set lag time in seconds for a fake slave
333 * @param mixed $lag Valid values for this parameter are determined by the
334 * subclass, but should be a PHP scalar or array that would be sensible
335 * as part of $wgLBFactoryConf.
337 public function setFakeSlaveLag( $lag ) {
341 * Make this connection a fake master
343 * @param bool $enabled
345 public function setFakeMaster( $enabled = true ) {
349 * Returns true if this database supports (and uses) cascading deletes
351 * @return bool
353 public function cascadingDeletes() {
354 return false;
358 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
360 * @return bool
362 public function cleanupTriggers() {
363 return false;
367 * Returns true if this database is strict about what can be put into an IP field.
368 * Specifically, it uses a NULL value instead of an empty string.
370 * @return bool
372 public function strictIPs() {
373 return false;
377 * Returns true if this database uses timestamps rather than integers
379 * @return bool
381 public function realTimestamps() {
382 return false;
386 * Returns true if this database does an implicit sort when doing GROUP BY
388 * @return bool
390 public function implicitGroupby() {
391 return true;
395 * Returns true if this database does an implicit order by when the column has an index
396 * For example: SELECT page_title FROM page LIMIT 1
398 * @return bool
400 public function implicitOrderby() {
401 return true;
405 * Returns true if this database can do a native search on IP columns
406 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
408 * @return bool
410 public function searchableIPs() {
411 return false;
415 * Returns true if this database can use functional indexes
417 * @return bool
419 public function functionalIndexes() {
420 return false;
424 * Return the last query that went through DatabaseBase::query()
425 * @return string
427 public function lastQuery() {
428 return $this->mLastQuery;
432 * Returns true if the connection may have been used for write queries.
433 * Should return true if unsure.
435 * @return bool
437 public function doneWrites() {
438 return (bool)$this->mDoneWrites;
442 * Returns the last time the connection may have been used for write queries.
443 * Should return a timestamp if unsure.
445 * @return int|float UNIX timestamp or false
446 * @since 1.24
448 public function lastDoneWrites() {
449 return $this->mDoneWrites ?: false;
453 * Returns true if there is a transaction open with possible write
454 * queries or transaction pre-commit/idle callbacks waiting on it to finish.
456 * @return bool
458 public function writesOrCallbacksPending() {
459 return $this->mTrxLevel && (
460 $this->mTrxDoneWrites || $this->mTrxIdleCallbacks || $this->mTrxPreCommitCallbacks
465 * Is a connection to the database open?
466 * @return bool
468 public function isOpen() {
469 return $this->mOpened;
473 * Set a flag for this connection
475 * @param int $flag DBO_* constants from Defines.php:
476 * - DBO_DEBUG: output some debug info (same as debug())
477 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
478 * - DBO_TRX: automatically start transactions
479 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
480 * and removes it in command line mode
481 * - DBO_PERSISTENT: use persistant database connection
483 public function setFlag( $flag ) {
484 global $wgDebugDBTransactions;
485 $this->mFlags |= $flag;
486 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
487 wfDebug( "Implicit transactions are now enabled.\n" );
492 * Clear a flag for this connection
494 * @param int $flag DBO_* constants from Defines.php:
495 * - DBO_DEBUG: output some debug info (same as debug())
496 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
497 * - DBO_TRX: automatically start transactions
498 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
499 * and removes it in command line mode
500 * - DBO_PERSISTENT: use persistant database connection
502 public function clearFlag( $flag ) {
503 global $wgDebugDBTransactions;
504 $this->mFlags &= ~$flag;
505 if ( ( $flag & DBO_TRX ) && $wgDebugDBTransactions ) {
506 wfDebug( "Implicit transactions are now disabled.\n" );
511 * Returns a boolean whether the flag $flag is set for this connection
513 * @param int $flag DBO_* constants from Defines.php:
514 * - DBO_DEBUG: output some debug info (same as debug())
515 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
516 * - DBO_TRX: automatically start transactions
517 * - DBO_PERSISTENT: use persistant database connection
518 * @return bool
520 public function getFlag( $flag ) {
521 return !!( $this->mFlags & $flag );
525 * General read-only accessor
527 * @param string $name
528 * @return string
530 public function getProperty( $name ) {
531 return $this->$name;
535 * @return string
537 public function getWikiID() {
538 if ( $this->mTablePrefix ) {
539 return "{$this->mDBname}-{$this->mTablePrefix}";
540 } else {
541 return $this->mDBname;
546 * Return a path to the DBMS-specific SQL file if it exists,
547 * otherwise default SQL file
549 * @param string $filename
550 * @return string
552 private function getSqlFilePath( $filename ) {
553 global $IP;
554 $dbmsSpecificFilePath = "$IP/maintenance/" . $this->getType() . "/$filename";
555 if ( file_exists( $dbmsSpecificFilePath ) ) {
556 return $dbmsSpecificFilePath;
557 } else {
558 return "$IP/maintenance/$filename";
563 * Return a path to the DBMS-specific schema file,
564 * otherwise default to tables.sql
566 * @return string
568 public function getSchemaPath() {
569 return $this->getSqlFilePath( 'tables.sql' );
573 * Return a path to the DBMS-specific update key file,
574 * otherwise default to update-keys.sql
576 * @return string
578 public function getUpdateKeysPath() {
579 return $this->getSqlFilePath( 'update-keys.sql' );
583 * Get the type of the DBMS, as it appears in $wgDBtype.
585 * @return string
587 abstract function getType();
590 * Open a connection to the database. Usually aborts on failure
592 * @param string $server Database server host
593 * @param string $user Database user name
594 * @param string $password Database user password
595 * @param string $dbName Database name
596 * @return bool
597 * @throws DBConnectionError
599 abstract function open( $server, $user, $password, $dbName );
602 * Fetch the next row from the given result object, in object form.
603 * Fields can be retrieved with $row->fieldname, with fields acting like
604 * member variables.
605 * If no more rows are available, false is returned.
607 * @param ResultWrapper|stdClass $res Object as returned from DatabaseBase::query(), etc.
608 * @return stdClass|bool
609 * @throws DBUnexpectedError Thrown if the database returns an error
611 abstract function fetchObject( $res );
614 * Fetch the next row from the given result object, in associative array
615 * form. Fields are retrieved with $row['fieldname'].
616 * If no more rows are available, false is returned.
618 * @param ResultWrapper $res Result object as returned from DatabaseBase::query(), etc.
619 * @return array|bool
620 * @throws DBUnexpectedError Thrown if the database returns an error
622 abstract function fetchRow( $res );
625 * Get the number of rows in a result object
627 * @param mixed $res A SQL result
628 * @return int
630 abstract function numRows( $res );
633 * Get the number of fields in a result object
634 * @see http://www.php.net/mysql_num_fields
636 * @param mixed $res A SQL result
637 * @return int
639 abstract function numFields( $res );
642 * Get a field name in a result object
643 * @see http://www.php.net/mysql_field_name
645 * @param mixed $res A SQL result
646 * @param int $n
647 * @return string
649 abstract function fieldName( $res, $n );
652 * Get the inserted value of an auto-increment row
654 * The value inserted should be fetched from nextSequenceValue()
656 * Example:
657 * $id = $dbw->nextSequenceValue( 'page_page_id_seq' );
658 * $dbw->insert( 'page', array( 'page_id' => $id ) );
659 * $id = $dbw->insertId();
661 * @return int
663 abstract function insertId();
666 * Change the position of the cursor in a result object
667 * @see http://www.php.net/mysql_data_seek
669 * @param mixed $res A SQL result
670 * @param int $row
672 abstract function dataSeek( $res, $row );
675 * Get the last error number
676 * @see http://www.php.net/mysql_errno
678 * @return int
680 abstract function lastErrno();
683 * Get a description of the last error
684 * @see http://www.php.net/mysql_error
686 * @return string
688 abstract function lastError();
691 * mysql_fetch_field() wrapper
692 * Returns false if the field doesn't exist
694 * @param string $table Table name
695 * @param string $field Field name
697 * @return Field
699 abstract function fieldInfo( $table, $field );
702 * Get information about an index into an object
703 * @param string $table Table name
704 * @param string $index Index name
705 * @param string $fname Calling function name
706 * @return mixed Database-specific index description class or false if the index does not exist
708 abstract function indexInfo( $table, $index, $fname = __METHOD__ );
711 * Get the number of rows affected by the last write query
712 * @see http://www.php.net/mysql_affected_rows
714 * @return int
716 abstract function affectedRows();
719 * Wrapper for addslashes()
721 * @param string $s String to be slashed.
722 * @return string Slashed string.
724 abstract function strencode( $s );
727 * Returns a wikitext link to the DB's website, e.g.,
728 * return "[http://www.mysql.com/ MySQL]";
729 * Should at least contain plain text, if for some reason
730 * your database has no website.
732 * @return string Wikitext of a link to the server software's web site
734 abstract function getSoftwareLink();
737 * A string describing the current software version, like from
738 * mysql_get_server_info().
740 * @return string Version information from the database server.
742 abstract function getServerVersion();
745 * Constructor.
747 * FIXME: It is possible to construct a Database object with no associated
748 * connection object, by specifying no parameters to __construct(). This
749 * feature is deprecated and should be removed.
751 * DatabaseBase subclasses should not be constructed directly in external
752 * code. DatabaseBase::factory() should be used instead.
754 * @param array $params Parameters passed from DatabaseBase::factory()
756 function __construct( $params = null ) {
757 global $wgDBprefix, $wgDBmwschema, $wgCommandLineMode, $wgDebugDBTransactions;
759 $this->mTrxAtomicLevels = new SplStack;
761 if ( is_array( $params ) ) { // MW 1.22
762 $server = $params['host'];
763 $user = $params['user'];
764 $password = $params['password'];
765 $dbName = $params['dbname'];
766 $flags = $params['flags'];
767 $tablePrefix = $params['tablePrefix'];
768 $schema = $params['schema'];
769 $foreign = $params['foreign'];
770 } else { // legacy calling pattern
771 wfDeprecated( __METHOD__ . " method called without parameter array.", "1.23" );
772 $args = func_get_args();
773 $server = isset( $args[0] ) ? $args[0] : false;
774 $user = isset( $args[1] ) ? $args[1] : false;
775 $password = isset( $args[2] ) ? $args[2] : false;
776 $dbName = isset( $args[3] ) ? $args[3] : false;
777 $flags = isset( $args[4] ) ? $args[4] : 0;
778 $tablePrefix = isset( $args[5] ) ? $args[5] : 'get from global';
779 $schema = 'get from global';
780 $foreign = isset( $args[6] ) ? $args[6] : false;
783 $this->mFlags = $flags;
784 if ( $this->mFlags & DBO_DEFAULT ) {
785 if ( $wgCommandLineMode ) {
786 $this->mFlags &= ~DBO_TRX;
787 if ( $wgDebugDBTransactions ) {
788 wfDebug( "Implicit transaction open disabled.\n" );
790 } else {
791 $this->mFlags |= DBO_TRX;
792 if ( $wgDebugDBTransactions ) {
793 wfDebug( "Implicit transaction open enabled.\n" );
798 /** Get the default table prefix*/
799 if ( $tablePrefix == 'get from global' ) {
800 $this->mTablePrefix = $wgDBprefix;
801 } else {
802 $this->mTablePrefix = $tablePrefix;
805 /** Get the database schema*/
806 if ( $schema == 'get from global' ) {
807 $this->mSchema = $wgDBmwschema;
808 } else {
809 $this->mSchema = $schema;
812 $this->mForeign = $foreign;
814 if ( $user ) {
815 $this->open( $server, $user, $password, $dbName );
818 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
819 $trxProf = Profiler::instance()->getTransactionProfiler();
820 $trxProf->recordConnection( $this->mServer, $this->mDBname, $isMaster );
824 * Called by serialize. Throw an exception when DB connection is serialized.
825 * This causes problems on some database engines because the connection is
826 * not restored on unserialize.
828 public function __sleep() {
829 throw new MWException( 'Database serialization may cause problems, since ' .
830 'the connection is not restored on wakeup.' );
834 * Given a DB type, construct the name of the appropriate child class of
835 * DatabaseBase. This is designed to replace all of the manual stuff like:
836 * $class = 'Database' . ucfirst( strtolower( $dbType ) );
837 * as well as validate against the canonical list of DB types we have
839 * This factory function is mostly useful for when you need to connect to a
840 * database other than the MediaWiki default (such as for external auth,
841 * an extension, et cetera). Do not use this to connect to the MediaWiki
842 * database. Example uses in core:
843 * @see LoadBalancer::reallyOpenConnection()
844 * @see ForeignDBRepo::getMasterDB()
845 * @see WebInstallerDBConnect::execute()
847 * @since 1.18
849 * @param string $dbType A possible DB type
850 * @param array $p An array of options to pass to the constructor.
851 * Valid options are: host, user, password, dbname, flags, tablePrefix, schema, driver
852 * @throws MWException If the database driver or extension cannot be found
853 * @return DatabaseBase|null DatabaseBase subclass or null
855 final public static function factory( $dbType, $p = array() ) {
856 $canonicalDBTypes = array(
857 'mysql' => array( 'mysqli', 'mysql' ),
858 'postgres' => array(),
859 'sqlite' => array(),
860 'oracle' => array(),
861 'mssql' => array(),
864 $driver = false;
865 $dbType = strtolower( $dbType );
866 if ( isset( $canonicalDBTypes[$dbType] ) && $canonicalDBTypes[$dbType] ) {
867 $possibleDrivers = $canonicalDBTypes[$dbType];
868 if ( !empty( $p['driver'] ) ) {
869 if ( in_array( $p['driver'], $possibleDrivers ) ) {
870 $driver = $p['driver'];
871 } else {
872 throw new MWException( __METHOD__ .
873 " cannot construct Database with type '$dbType' and driver '{$p['driver']}'" );
875 } else {
876 foreach ( $possibleDrivers as $posDriver ) {
877 if ( extension_loaded( $posDriver ) ) {
878 $driver = $posDriver;
879 break;
883 } else {
884 $driver = $dbType;
886 if ( $driver === false ) {
887 throw new MWException( __METHOD__ .
888 " no viable database extension found for type '$dbType'" );
891 // Determine schema defaults. Currently Microsoft SQL Server uses $wgDBmwschema,
892 // and everything else doesn't use a schema (e.g. null)
893 // Although postgres and oracle support schemas, we don't use them (yet)
894 // to maintain backwards compatibility
895 $defaultSchemas = array(
896 'mysql' => null,
897 'postgres' => null,
898 'sqlite' => null,
899 'oracle' => null,
900 'mssql' => 'get from global',
903 $class = 'Database' . ucfirst( $driver );
904 if ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
905 $params = array(
906 'host' => isset( $p['host'] ) ? $p['host'] : false,
907 'user' => isset( $p['user'] ) ? $p['user'] : false,
908 'password' => isset( $p['password'] ) ? $p['password'] : false,
909 'dbname' => isset( $p['dbname'] ) ? $p['dbname'] : false,
910 'flags' => isset( $p['flags'] ) ? $p['flags'] : 0,
911 'tablePrefix' => isset( $p['tablePrefix'] ) ? $p['tablePrefix'] : 'get from global',
912 'schema' => isset( $p['schema'] ) ? $p['schema'] : $defaultSchemas[$dbType],
913 'foreign' => isset( $p['foreign'] ) ? $p['foreign'] : false
916 return new $class( $params );
917 } else {
918 return null;
922 protected function installErrorHandler() {
923 $this->mPHPError = false;
924 $this->htmlErrors = ini_set( 'html_errors', '0' );
925 set_error_handler( array( $this, 'connectionErrorHandler' ) );
929 * @return bool|string
931 protected function restoreErrorHandler() {
932 restore_error_handler();
933 if ( $this->htmlErrors !== false ) {
934 ini_set( 'html_errors', $this->htmlErrors );
936 if ( $this->mPHPError ) {
937 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
938 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
940 return $error;
941 } else {
942 return false;
947 * @param int $errno
948 * @param string $errstr
950 public function connectionErrorHandler( $errno, $errstr ) {
951 $this->mPHPError = $errstr;
955 * Create a log context to pass to wfLogDBError or other logging functions.
957 * @param array $extras Additional data to add to context
958 * @return array
960 protected function getLogContext( array $extras = array() ) {
961 return array_merge(
962 array(
963 'db_server' => $this->mServer,
964 'db_name' => $this->mDBname,
965 'db_user' => $this->mUser,
967 $extras
972 * Closes a database connection.
973 * if it is open : commits any open transactions
975 * @throws MWException
976 * @return bool Operation success. true if already closed.
978 public function close() {
979 if ( count( $this->mTrxIdleCallbacks ) ) { // sanity
980 throw new MWException( "Transaction idle callbacks still pending." );
982 if ( $this->mConn ) {
983 if ( $this->trxLevel() ) {
984 if ( !$this->mTrxAutomatic ) {
985 wfWarn( "Transaction still in progress (from {$this->mTrxFname}), " .
986 " performing implicit commit before closing connection!" );
989 $this->commit( __METHOD__, 'flush' );
992 $closed = $this->closeConnection();
993 $this->mConn = false;
994 } else {
995 $closed = true;
997 $this->mOpened = false;
999 return $closed;
1003 * Closes underlying database connection
1004 * @since 1.20
1005 * @return bool Whether connection was closed successfully
1007 abstract protected function closeConnection();
1010 * @param string $error Fallback error message, used if none is given by DB
1011 * @throws DBConnectionError
1013 function reportConnectionError( $error = 'Unknown error' ) {
1014 $myError = $this->lastError();
1015 if ( $myError ) {
1016 $error = $myError;
1019 # New method
1020 throw new DBConnectionError( $this, $error );
1024 * The DBMS-dependent part of query()
1026 * @param string $sql SQL query.
1027 * @return ResultWrapper|bool Result object to feed to fetchObject,
1028 * fetchRow, ...; or false on failure
1030 abstract protected function doQuery( $sql );
1033 * Determine whether a query writes to the DB.
1034 * Should return true if unsure.
1036 * @param string $sql
1037 * @return bool
1039 public function isWriteQuery( $sql ) {
1040 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
1044 * Determine whether a SQL statement is sensitive to isolation level.
1045 * A SQL statement is considered transactable if its result could vary
1046 * depending on the transaction isolation level. Operational commands
1047 * such as 'SET' and 'SHOW' are not considered to be transactable.
1049 * @param string $sql
1050 * @return bool
1052 public function isTransactableQuery( $sql ) {
1053 $verb = substr( $sql, 0, strcspn( $sql, " \t\r\n" ) );
1054 return !in_array( $verb, array( 'BEGIN', 'COMMIT', 'ROLLBACK', 'SHOW', 'SET' ) );
1058 * Run an SQL query and return the result. Normally throws a DBQueryError
1059 * on failure. If errors are ignored, returns false instead.
1061 * In new code, the query wrappers select(), insert(), update(), delete(),
1062 * etc. should be used where possible, since they give much better DBMS
1063 * independence and automatically quote or validate user input in a variety
1064 * of contexts. This function is generally only useful for queries which are
1065 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
1066 * as CREATE TABLE.
1068 * However, the query wrappers themselves should call this function.
1070 * @param string $sql SQL query
1071 * @param string $fname Name of the calling function, for profiling/SHOW PROCESSLIST
1072 * comment (you can use __METHOD__ or add some extra info)
1073 * @param bool $tempIgnore Whether to avoid throwing an exception on errors...
1074 * maybe best to catch the exception instead?
1075 * @throws MWException
1076 * @return bool|ResultWrapper True for a successful write query, ResultWrapper object
1077 * for a successful read query, or false on failure if $tempIgnore set
1079 public function query( $sql, $fname = __METHOD__, $tempIgnore = false ) {
1080 global $wgUser, $wgDebugDBTransactions, $wgDebugDumpSqlLength;
1082 $this->mLastQuery = $sql;
1084 $isWriteQuery = $this->isWriteQuery( $sql );
1085 if ( $isWriteQuery ) {
1086 if ( !$this->mDoneWrites ) {
1087 wfDebug( __METHOD__ . ': Writes done: ' .
1088 DatabaseBase::generalizeSQL( $sql ) . "\n" );
1090 # Set a flag indicating that writes have been done
1091 $this->mDoneWrites = microtime( true );
1094 # Add a comment for easy SHOW PROCESSLIST interpretation
1095 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
1096 $userName = $wgUser->getName();
1097 if ( mb_strlen( $userName ) > 15 ) {
1098 $userName = mb_substr( $userName, 0, 15 ) . '...';
1100 $userName = str_replace( '/', '', $userName );
1101 } else {
1102 $userName = '';
1105 // Add trace comment to the begin of the sql string, right after the operator.
1106 // Or, for one-word queries (like "BEGIN" or COMMIT") add it to the end (bug 42598)
1107 $commentedSql = preg_replace( '/\s|$/', " /* $fname $userName */ ", $sql, 1 );
1109 if ( !$this->mTrxLevel && $this->getFlag( DBO_TRX ) && $this->isTransactableQuery( $sql ) ) {
1110 if ( $wgDebugDBTransactions ) {
1111 wfDebug( "Implicit transaction start.\n" );
1113 $this->begin( __METHOD__ . " ($fname)" );
1114 $this->mTrxAutomatic = true;
1117 # Keep track of whether the transaction has write queries pending
1118 if ( $this->mTrxLevel && !$this->mTrxDoneWrites && $isWriteQuery ) {
1119 $this->mTrxDoneWrites = true;
1120 Profiler::instance()->getTransactionProfiler()->transactionWritingIn(
1121 $this->mServer, $this->mDBname, $this->mTrxShortId );
1124 $queryProf = '';
1125 $totalProf = '';
1126 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
1128 $profiler = Profiler::instance();
1129 if ( !$profiler instanceof ProfilerStub ) {
1130 # generalizeSQL will probably cut down the query to reasonable
1131 # logging size most of the time. The substr is really just a sanity check.
1132 if ( $isMaster ) {
1133 $queryProf = 'query-m: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1134 $totalProf = 'DatabaseBase::query-master';
1135 } else {
1136 $queryProf = 'query: ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
1137 $totalProf = 'DatabaseBase::query';
1139 # Include query transaction state
1140 $queryProf .= $this->mTrxShortId ? " [TRX#{$this->mTrxShortId}]" : "";
1142 $totalProfSection = $profiler->scopedProfileIn( $totalProf );
1143 $queryProfSection = $profiler->scopedProfileIn( $queryProf );
1146 if ( $this->debug() ) {
1147 static $cnt = 0;
1149 $cnt++;
1150 $sqlx = $wgDebugDumpSqlLength ? substr( $commentedSql, 0, $wgDebugDumpSqlLength )
1151 : $commentedSql;
1152 $sqlx = strtr( $sqlx, "\t\n", ' ' );
1154 $master = $isMaster ? 'master' : 'slave';
1155 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
1158 $queryId = MWDebug::query( $sql, $fname, $isMaster );
1160 # Avoid fatals if close() was called
1161 if ( !$this->isOpen() ) {
1162 throw new DBUnexpectedError( $this, "DB connection was already closed." );
1165 # Log the query time and feed it into the DB trx profiler
1166 if ( $queryProf != '' ) {
1167 $that = $this;
1168 $queryStartTime = microtime( true );
1169 $queryProfile = new ScopedCallback(
1170 function () use ( $that, $queryStartTime, $queryProf, $isWriteQuery ) {
1171 $n = $that->affectedRows();
1172 $trxProf = Profiler::instance()->getTransactionProfiler();
1173 $trxProf->recordQueryCompletion(
1174 $queryProf, $queryStartTime, $isWriteQuery, $n );
1179 # Do the query and handle errors
1180 $ret = $this->doQuery( $commentedSql );
1182 MWDebug::queryTime( $queryId );
1184 # Try reconnecting if the connection was lost
1185 if ( false === $ret && $this->wasErrorReissuable() ) {
1186 # Transaction is gone, like it or not
1187 $hadTrx = $this->mTrxLevel; // possible lost transaction
1188 $this->mTrxLevel = 0;
1189 $this->mTrxIdleCallbacks = array(); // bug 65263
1190 $this->mTrxPreCommitCallbacks = array(); // bug 65263
1191 wfDebug( "Connection lost, reconnecting...\n" );
1192 # Stash the last error values since ping() might clear them
1193 $lastError = $this->lastError();
1194 $lastErrno = $this->lastErrno();
1195 if ( $this->ping() ) {
1196 wfDebug( "Reconnected\n" );
1197 $server = $this->getServer();
1198 $msg = __METHOD__ . ": lost connection to $server; reconnected";
1199 wfDebugLog( 'DBPerformance', "$msg:\n" . wfBacktrace( true ) );
1201 if ( $hadTrx ) {
1202 # Leave $ret as false and let an error be reported.
1203 # Callers may catch the exception and continue to use the DB.
1204 $this->reportQueryError( $lastError, $lastErrno, $sql, $fname, $tempIgnore );
1205 } else {
1206 # Should be safe to silently retry (no trx and thus no callbacks)
1207 $ret = $this->doQuery( $commentedSql );
1209 } else {
1210 wfDebug( "Failed\n" );
1214 if ( false === $ret ) {
1215 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
1218 $res = $this->resultObject( $ret );
1220 // Destroy profile sections in the opposite order to their creation
1221 $queryProfSection = false;
1222 $totalProfSection = false;
1224 return $res;
1228 * Report a query error. Log the error, and if neither the object ignore
1229 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
1231 * @param string $error
1232 * @param int $errno
1233 * @param string $sql
1234 * @param string $fname
1235 * @param bool $tempIgnore
1236 * @throws DBQueryError
1238 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
1239 # Ignore errors during error handling to avoid infinite recursion
1240 $ignore = $this->ignoreErrors( true );
1241 ++$this->mErrorCount;
1243 if ( $ignore || $tempIgnore ) {
1244 wfDebug( "SQL ERROR (ignored): $error\n" );
1245 $this->ignoreErrors( $ignore );
1246 } else {
1247 $sql1line = mb_substr( str_replace( "\n", "\\n", $sql ), 0, 5 * 1024 );
1248 wfLogDBError(
1249 "{fname}\t{db_server}\t{errno}\t{error}\t{sql1line}",
1250 $this->getLogContext( array(
1251 'method' => __METHOD__,
1252 'errno' => $errno,
1253 'error' => $error,
1254 'sql1line' => $sql1line,
1255 'fname' => $fname,
1258 wfDebug( "SQL ERROR: " . $error . "\n" );
1259 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
1264 * Intended to be compatible with the PEAR::DB wrapper functions.
1265 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
1267 * ? = scalar value, quoted as necessary
1268 * ! = raw SQL bit (a function for instance)
1269 * & = filename; reads the file and inserts as a blob
1270 * (we don't use this though...)
1272 * @param string $sql
1273 * @param string $func
1275 * @return array
1277 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
1278 /* MySQL doesn't support prepared statements (yet), so just
1279 * pack up the query for reference. We'll manually replace
1280 * the bits later.
1282 return array( 'query' => $sql, 'func' => $func );
1286 * Free a prepared query, generated by prepare().
1287 * @param string $prepared
1289 protected function freePrepared( $prepared ) {
1290 /* No-op by default */
1294 * Execute a prepared query with the various arguments
1295 * @param string $prepared The prepared sql
1296 * @param mixed $args Either an array here, or put scalars as varargs
1298 * @return ResultWrapper
1300 public function execute( $prepared, $args = null ) {
1301 if ( !is_array( $args ) ) {
1302 # Pull the var args
1303 $args = func_get_args();
1304 array_shift( $args );
1307 $sql = $this->fillPrepared( $prepared['query'], $args );
1309 return $this->query( $sql, $prepared['func'] );
1313 * For faking prepared SQL statements on DBs that don't support it directly.
1315 * @param string $preparedQuery A 'preparable' SQL statement
1316 * @param array $args Array of Arguments to fill it with
1317 * @return string Executable SQL
1319 public function fillPrepared( $preparedQuery, $args ) {
1320 reset( $args );
1321 $this->preparedArgs =& $args;
1323 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1324 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1328 * preg_callback func for fillPrepared()
1329 * The arguments should be in $this->preparedArgs and must not be touched
1330 * while we're doing this.
1332 * @param array $matches
1333 * @throws DBUnexpectedError
1334 * @return string
1336 protected function fillPreparedArg( $matches ) {
1337 switch ( $matches[1] ) {
1338 case '\\?':
1339 return '?';
1340 case '\\!':
1341 return '!';
1342 case '\\&':
1343 return '&';
1346 list( /* $n */, $arg ) = each( $this->preparedArgs );
1348 switch ( $matches[1] ) {
1349 case '?':
1350 return $this->addQuotes( $arg );
1351 case '!':
1352 return $arg;
1353 case '&':
1354 # return $this->addQuotes( file_get_contents( $arg ) );
1355 throw new DBUnexpectedError(
1356 $this,
1357 '& mode is not implemented. If it\'s really needed, uncomment the line above.'
1359 default:
1360 throw new DBUnexpectedError(
1361 $this,
1362 'Received invalid match. This should never happen!'
1368 * Free a result object returned by query() or select(). It's usually not
1369 * necessary to call this, just use unset() or let the variable holding
1370 * the result object go out of scope.
1372 * @param mixed $res A SQL result
1374 public function freeResult( $res ) {
1378 * A SELECT wrapper which returns a single field from a single result row.
1380 * Usually throws a DBQueryError on failure. If errors are explicitly
1381 * ignored, returns false on failure.
1383 * If no result rows are returned from the query, false is returned.
1385 * @param string|array $table Table name. See DatabaseBase::select() for details.
1386 * @param string $var The field name to select. This must be a valid SQL
1387 * fragment: do not use unvalidated user input.
1388 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1389 * @param string $fname The function name of the caller.
1390 * @param string|array $options The query options. See DatabaseBase::select() for details.
1392 * @return bool|mixed The value from the field, or false on failure.
1394 public function selectField(
1395 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1397 if ( $var === '*' ) { // sanity
1398 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1401 if ( !is_array( $options ) ) {
1402 $options = array( $options );
1405 $options['LIMIT'] = 1;
1407 $res = $this->select( $table, $var, $cond, $fname, $options );
1408 if ( $res === false || !$this->numRows( $res ) ) {
1409 return false;
1412 $row = $this->fetchRow( $res );
1414 if ( $row !== false ) {
1415 return reset( $row );
1416 } else {
1417 return false;
1422 * A SELECT wrapper which returns a list of single field values from result rows.
1424 * Usually throws a DBQueryError on failure. If errors are explicitly
1425 * ignored, returns false on failure.
1427 * If no result rows are returned from the query, false is returned.
1429 * @param string|array $table Table name. See DatabaseBase::select() for details.
1430 * @param string $var The field name to select. This must be a valid SQL
1431 * fragment: do not use unvalidated user input.
1432 * @param string|array $cond The condition array. See DatabaseBase::select() for details.
1433 * @param string $fname The function name of the caller.
1434 * @param string|array $options The query options. See DatabaseBase::select() for details.
1436 * @return bool|array The values from the field, or false on failure
1437 * @since 1.25
1439 public function selectFieldValues(
1440 $table, $var, $cond = '', $fname = __METHOD__, $options = array()
1442 if ( $var === '*' ) { // sanity
1443 throw new DBUnexpectedError( $this, "Cannot use a * field: got '$var'" );
1446 if ( !is_array( $options ) ) {
1447 $options = array( $options );
1450 $res = $this->select( $table, $var, $cond, $fname, $options );
1451 if ( $res === false ) {
1452 return false;
1455 $values = array();
1456 foreach ( $res as $row ) {
1457 $values[] = $row->$var;
1460 return $values;
1464 * Returns an optional USE INDEX clause to go after the table, and a
1465 * string to go at the end of the query.
1467 * @param array $options Associative array of options to be turned into
1468 * an SQL query, valid keys are listed in the function.
1469 * @return array
1470 * @see DatabaseBase::select()
1472 public function makeSelectOptions( $options ) {
1473 $preLimitTail = $postLimitTail = '';
1474 $startOpts = '';
1476 $noKeyOptions = array();
1478 foreach ( $options as $key => $option ) {
1479 if ( is_numeric( $key ) ) {
1480 $noKeyOptions[$option] = true;
1484 $preLimitTail .= $this->makeGroupByWithHaving( $options );
1486 $preLimitTail .= $this->makeOrderBy( $options );
1488 // if (isset($options['LIMIT'])) {
1489 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1490 // isset($options['OFFSET']) ? $options['OFFSET']
1491 // : false);
1492 // }
1494 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1495 $postLimitTail .= ' FOR UPDATE';
1498 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1499 $postLimitTail .= ' LOCK IN SHARE MODE';
1502 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) {
1503 $startOpts .= 'DISTINCT';
1506 # Various MySQL extensions
1507 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1508 $startOpts .= ' /*! STRAIGHT_JOIN */';
1511 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1512 $startOpts .= ' HIGH_PRIORITY';
1515 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1516 $startOpts .= ' SQL_BIG_RESULT';
1519 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1520 $startOpts .= ' SQL_BUFFER_RESULT';
1523 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1524 $startOpts .= ' SQL_SMALL_RESULT';
1527 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1528 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1531 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1532 $startOpts .= ' SQL_CACHE';
1535 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1536 $startOpts .= ' SQL_NO_CACHE';
1539 if ( isset( $options['USE INDEX'] ) && is_string( $options['USE INDEX'] ) ) {
1540 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1541 } else {
1542 $useIndex = '';
1545 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1549 * Returns an optional GROUP BY with an optional HAVING
1551 * @param array $options Associative array of options
1552 * @return string
1553 * @see DatabaseBase::select()
1554 * @since 1.21
1556 public function makeGroupByWithHaving( $options ) {
1557 $sql = '';
1558 if ( isset( $options['GROUP BY'] ) ) {
1559 $gb = is_array( $options['GROUP BY'] )
1560 ? implode( ',', $options['GROUP BY'] )
1561 : $options['GROUP BY'];
1562 $sql .= ' GROUP BY ' . $gb;
1564 if ( isset( $options['HAVING'] ) ) {
1565 $having = is_array( $options['HAVING'] )
1566 ? $this->makeList( $options['HAVING'], LIST_AND )
1567 : $options['HAVING'];
1568 $sql .= ' HAVING ' . $having;
1571 return $sql;
1575 * Returns an optional ORDER BY
1577 * @param array $options Associative array of options
1578 * @return string
1579 * @see DatabaseBase::select()
1580 * @since 1.21
1582 public function makeOrderBy( $options ) {
1583 if ( isset( $options['ORDER BY'] ) ) {
1584 $ob = is_array( $options['ORDER BY'] )
1585 ? implode( ',', $options['ORDER BY'] )
1586 : $options['ORDER BY'];
1588 return ' ORDER BY ' . $ob;
1591 return '';
1595 * Execute a SELECT query constructed using the various parameters provided.
1596 * See below for full details of the parameters.
1598 * @param string|array $table Table name
1599 * @param string|array $vars Field names
1600 * @param string|array $conds Conditions
1601 * @param string $fname Caller function name
1602 * @param array $options Query options
1603 * @param array $join_conds Join conditions
1606 * @param string|array $table
1608 * May be either an array of table names, or a single string holding a table
1609 * name. If an array is given, table aliases can be specified, for example:
1611 * array( 'a' => 'user' )
1613 * This includes the user table in the query, with the alias "a" available
1614 * for use in field names (e.g. a.user_name).
1616 * All of the table names given here are automatically run through
1617 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1618 * added, and various other table name mappings to be performed.
1621 * @param string|array $vars
1623 * May be either a field name or an array of field names. The field names
1624 * can be complete fragments of SQL, for direct inclusion into the SELECT
1625 * query. If an array is given, field aliases can be specified, for example:
1627 * array( 'maxrev' => 'MAX(rev_id)' )
1629 * This includes an expression with the alias "maxrev" in the query.
1631 * If an expression is given, care must be taken to ensure that it is
1632 * DBMS-independent.
1635 * @param string|array $conds
1637 * May be either a string containing a single condition, or an array of
1638 * conditions. If an array is given, the conditions constructed from each
1639 * element are combined with AND.
1641 * Array elements may take one of two forms:
1643 * - Elements with a numeric key are interpreted as raw SQL fragments.
1644 * - Elements with a string key are interpreted as equality conditions,
1645 * where the key is the field name.
1646 * - If the value of such an array element is a scalar (such as a
1647 * string), it will be treated as data and thus quoted appropriately.
1648 * If it is null, an IS NULL clause will be added.
1649 * - If the value is an array, an IN(...) clause will be constructed,
1650 * such that the field name may match any of the elements in the
1651 * array. The elements of the array will be quoted.
1653 * Note that expressions are often DBMS-dependent in their syntax.
1654 * DBMS-independent wrappers are provided for constructing several types of
1655 * expression commonly used in condition queries. See:
1656 * - DatabaseBase::buildLike()
1657 * - DatabaseBase::conditional()
1660 * @param string|array $options
1662 * Optional: Array of query options. Boolean options are specified by
1663 * including them in the array as a string value with a numeric key, for
1664 * example:
1666 * array( 'FOR UPDATE' )
1668 * The supported options are:
1670 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1671 * with LIMIT can theoretically be used for paging through a result set,
1672 * but this is discouraged in MediaWiki for performance reasons.
1674 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1675 * and then the first rows are taken until the limit is reached. LIMIT
1676 * is applied to a result set after OFFSET.
1678 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1679 * changed until the next COMMIT.
1681 * - DISTINCT: Boolean: return only unique result rows.
1683 * - GROUP BY: May be either an SQL fragment string naming a field or
1684 * expression to group by, or an array of such SQL fragments.
1686 * - HAVING: May be either an string containing a HAVING clause or an array of
1687 * conditions building the HAVING clause. If an array is given, the conditions
1688 * constructed from each element are combined with AND.
1690 * - ORDER BY: May be either an SQL fragment giving a field name or
1691 * expression to order by, or an array of such SQL fragments.
1693 * - USE INDEX: This may be either a string giving the index name to use
1694 * for the query, or an array. If it is an associative array, each key
1695 * gives the table name (or alias), each value gives the index name to
1696 * use for that table. All strings are SQL fragments and so should be
1697 * validated by the caller.
1699 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1700 * instead of SELECT.
1702 * And also the following boolean MySQL extensions, see the MySQL manual
1703 * for documentation:
1705 * - LOCK IN SHARE MODE
1706 * - STRAIGHT_JOIN
1707 * - HIGH_PRIORITY
1708 * - SQL_BIG_RESULT
1709 * - SQL_BUFFER_RESULT
1710 * - SQL_SMALL_RESULT
1711 * - SQL_CALC_FOUND_ROWS
1712 * - SQL_CACHE
1713 * - SQL_NO_CACHE
1716 * @param string|array $join_conds
1718 * Optional associative array of table-specific join conditions. In the
1719 * most common case, this is unnecessary, since the join condition can be
1720 * in $conds. However, it is useful for doing a LEFT JOIN.
1722 * The key of the array contains the table name or alias. The value is an
1723 * array with two elements, numbered 0 and 1. The first gives the type of
1724 * join, the second is an SQL fragment giving the join condition for that
1725 * table. For example:
1727 * array( 'page' => array( 'LEFT JOIN', 'page_latest=rev_id' ) )
1729 * @return ResultWrapper|bool If the query returned no rows, a ResultWrapper
1730 * with no rows in it will be returned. If there was a query error, a
1731 * DBQueryError exception will be thrown, except if the "ignore errors"
1732 * option was set, in which case false will be returned.
1734 public function select( $table, $vars, $conds = '', $fname = __METHOD__,
1735 $options = array(), $join_conds = array() ) {
1736 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1738 return $this->query( $sql, $fname );
1742 * The equivalent of DatabaseBase::select() except that the constructed SQL
1743 * is returned, instead of being immediately executed. This can be useful for
1744 * doing UNION queries, where the SQL text of each query is needed. In general,
1745 * however, callers outside of Database classes should just use select().
1747 * @param string|array $table Table name
1748 * @param string|array $vars Field names
1749 * @param string|array $conds Conditions
1750 * @param string $fname Caller function name
1751 * @param string|array $options Query options
1752 * @param string|array $join_conds Join conditions
1754 * @return string SQL query string.
1755 * @see DatabaseBase::select()
1757 public function selectSQLText( $table, $vars, $conds = '', $fname = __METHOD__,
1758 $options = array(), $join_conds = array()
1760 if ( is_array( $vars ) ) {
1761 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1764 $options = (array)$options;
1765 $useIndexes = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1766 ? $options['USE INDEX']
1767 : array();
1769 if ( is_array( $table ) ) {
1770 $from = ' FROM ' .
1771 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndexes, $join_conds );
1772 } elseif ( $table != '' ) {
1773 if ( $table[0] == ' ' ) {
1774 $from = ' FROM ' . $table;
1775 } else {
1776 $from = ' FROM ' .
1777 $this->tableNamesWithUseIndexOrJOIN( array( $table ), $useIndexes, array() );
1779 } else {
1780 $from = '';
1783 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) =
1784 $this->makeSelectOptions( $options );
1786 if ( !empty( $conds ) ) {
1787 if ( is_array( $conds ) ) {
1788 $conds = $this->makeList( $conds, LIST_AND );
1790 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1791 } else {
1792 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1795 if ( isset( $options['LIMIT'] ) ) {
1796 $sql = $this->limitResult( $sql, $options['LIMIT'],
1797 isset( $options['OFFSET'] ) ? $options['OFFSET'] : false );
1799 $sql = "$sql $postLimitTail";
1801 if ( isset( $options['EXPLAIN'] ) ) {
1802 $sql = 'EXPLAIN ' . $sql;
1805 return $sql;
1809 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1810 * that a single row object is returned. If the query returns no rows,
1811 * false is returned.
1813 * @param string|array $table Table name
1814 * @param string|array $vars Field names
1815 * @param array $conds Conditions
1816 * @param string $fname Caller function name
1817 * @param string|array $options Query options
1818 * @param array|string $join_conds Join conditions
1820 * @return stdClass|bool
1822 public function selectRow( $table, $vars, $conds, $fname = __METHOD__,
1823 $options = array(), $join_conds = array()
1825 $options = (array)$options;
1826 $options['LIMIT'] = 1;
1827 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1829 if ( $res === false ) {
1830 return false;
1833 if ( !$this->numRows( $res ) ) {
1834 return false;
1837 $obj = $this->fetchObject( $res );
1839 return $obj;
1843 * Estimate the number of rows in dataset
1845 * MySQL allows you to estimate the number of rows that would be returned
1846 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1847 * index cardinality statistics, and is notoriously inaccurate, especially
1848 * when large numbers of rows have recently been added or deleted.
1850 * For DBMSs that don't support fast result size estimation, this function
1851 * will actually perform the SELECT COUNT(*).
1853 * Takes the same arguments as DatabaseBase::select().
1855 * @param string $table Table name
1856 * @param string $vars Unused
1857 * @param array|string $conds Filters on the table
1858 * @param string $fname Function name for profiling
1859 * @param array $options Options for select
1860 * @return int Row count
1862 public function estimateRowCount(
1863 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1865 $rows = 0;
1866 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1868 if ( $res ) {
1869 $row = $this->fetchRow( $res );
1870 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1873 return $rows;
1877 * Get the number of rows in dataset
1879 * This is useful when trying to do COUNT(*) but with a LIMIT for performance.
1881 * Takes the same arguments as DatabaseBase::select().
1883 * @param string $table Table name
1884 * @param string $vars Unused
1885 * @param array|string $conds Filters on the table
1886 * @param string $fname Function name for profiling
1887 * @param array $options Options for select
1888 * @return int Row count
1889 * @since 1.24
1891 public function selectRowCount(
1892 $table, $vars = '*', $conds = '', $fname = __METHOD__, $options = array()
1894 $rows = 0;
1895 $sql = $this->selectSQLText( $table, '1', $conds, $fname, $options );
1896 $res = $this->query( "SELECT COUNT(*) AS rowcount FROM ($sql) tmp_count" );
1898 if ( $res ) {
1899 $row = $this->fetchRow( $res );
1900 $rows = ( isset( $row['rowcount'] ) ) ? (int)$row['rowcount'] : 0;
1903 return $rows;
1907 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1908 * It's only slightly flawed. Don't use for anything important.
1910 * @param string $sql A SQL Query
1912 * @return string
1914 static function generalizeSQL( $sql ) {
1915 # This does the same as the regexp below would do, but in such a way
1916 # as to avoid crashing php on some large strings.
1917 # $sql = preg_replace( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql );
1919 $sql = str_replace( "\\\\", '', $sql );
1920 $sql = str_replace( "\\'", '', $sql );
1921 $sql = str_replace( "\\\"", '', $sql );
1922 $sql = preg_replace( "/'.*'/s", "'X'", $sql );
1923 $sql = preg_replace( '/".*"/s', "'X'", $sql );
1925 # All newlines, tabs, etc replaced by single space
1926 $sql = preg_replace( '/\s+/', ' ', $sql );
1928 # All numbers => N,
1929 # except the ones surrounded by characters, e.g. l10n
1930 $sql = preg_replace( '/-?\d+(,-?\d+)+/s', 'N,...,N', $sql );
1931 $sql = preg_replace( '/(?<![a-zA-Z])-?\d+(?![a-zA-Z])/s', 'N', $sql );
1933 return $sql;
1937 * Determines whether a field exists in a table
1939 * @param string $table Table name
1940 * @param string $field Filed to check on that table
1941 * @param string $fname Calling function name (optional)
1942 * @return bool Whether $table has filed $field
1944 public function fieldExists( $table, $field, $fname = __METHOD__ ) {
1945 $info = $this->fieldInfo( $table, $field );
1947 return (bool)$info;
1951 * Determines whether an index exists
1952 * Usually throws a DBQueryError on failure
1953 * If errors are explicitly ignored, returns NULL on failure
1955 * @param string $table
1956 * @param string $index
1957 * @param string $fname
1958 * @return bool|null
1960 public function indexExists( $table, $index, $fname = __METHOD__ ) {
1961 if ( !$this->tableExists( $table ) ) {
1962 return null;
1965 $info = $this->indexInfo( $table, $index, $fname );
1966 if ( is_null( $info ) ) {
1967 return null;
1968 } else {
1969 return $info !== false;
1974 * Query whether a given table exists
1976 * @param string $table
1977 * @param string $fname
1978 * @return bool
1980 public function tableExists( $table, $fname = __METHOD__ ) {
1981 $table = $this->tableName( $table );
1982 $old = $this->ignoreErrors( true );
1983 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1984 $this->ignoreErrors( $old );
1986 return (bool)$res;
1990 * Determines if a given index is unique
1992 * @param string $table
1993 * @param string $index
1995 * @return bool
1997 public function indexUnique( $table, $index ) {
1998 $indexInfo = $this->indexInfo( $table, $index );
2000 if ( !$indexInfo ) {
2001 return null;
2004 return !$indexInfo[0]->Non_unique;
2008 * Helper for DatabaseBase::insert().
2010 * @param array $options
2011 * @return string
2013 protected function makeInsertOptions( $options ) {
2014 return implode( ' ', $options );
2018 * INSERT wrapper, inserts an array into a table.
2020 * $a may be either:
2022 * - A single associative array. The array keys are the field names, and
2023 * the values are the values to insert. The values are treated as data
2024 * and will be quoted appropriately. If NULL is inserted, this will be
2025 * converted to a database NULL.
2026 * - An array with numeric keys, holding a list of associative arrays.
2027 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2028 * each subarray must be identical to each other, and in the same order.
2030 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2031 * returns success.
2033 * $options is an array of options, with boolean options encoded as values
2034 * with numeric keys, in the same style as $options in
2035 * DatabaseBase::select(). Supported options are:
2037 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
2038 * any rows which cause duplicate key errors are not inserted. It's
2039 * possible to determine how many rows were successfully inserted using
2040 * DatabaseBase::affectedRows().
2042 * @param string $table Table name. This will be passed through
2043 * DatabaseBase::tableName().
2044 * @param array $a Array of rows to insert
2045 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2046 * @param array $options Array of options
2048 * @return bool
2050 public function insert( $table, $a, $fname = __METHOD__, $options = array() ) {
2051 # No rows to insert, easy just return now
2052 if ( !count( $a ) ) {
2053 return true;
2056 $table = $this->tableName( $table );
2058 if ( !is_array( $options ) ) {
2059 $options = array( $options );
2062 $fh = null;
2063 if ( isset( $options['fileHandle'] ) ) {
2064 $fh = $options['fileHandle'];
2066 $options = $this->makeInsertOptions( $options );
2068 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
2069 $multi = true;
2070 $keys = array_keys( $a[0] );
2071 } else {
2072 $multi = false;
2073 $keys = array_keys( $a );
2076 $sql = 'INSERT ' . $options .
2077 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
2079 if ( $multi ) {
2080 $first = true;
2081 foreach ( $a as $row ) {
2082 if ( $first ) {
2083 $first = false;
2084 } else {
2085 $sql .= ',';
2087 $sql .= '(' . $this->makeList( $row ) . ')';
2089 } else {
2090 $sql .= '(' . $this->makeList( $a ) . ')';
2093 if ( $fh !== null && false === fwrite( $fh, $sql ) ) {
2094 return false;
2095 } elseif ( $fh !== null ) {
2096 return true;
2099 return (bool)$this->query( $sql, $fname );
2103 * Make UPDATE options array for DatabaseBase::makeUpdateOptions
2105 * @param array $options
2106 * @return array
2108 protected function makeUpdateOptionsArray( $options ) {
2109 if ( !is_array( $options ) ) {
2110 $options = array( $options );
2113 $opts = array();
2115 if ( in_array( 'LOW_PRIORITY', $options ) ) {
2116 $opts[] = $this->lowPriorityOption();
2119 if ( in_array( 'IGNORE', $options ) ) {
2120 $opts[] = 'IGNORE';
2123 return $opts;
2127 * Make UPDATE options for the DatabaseBase::update function
2129 * @param array $options The options passed to DatabaseBase::update
2130 * @return string
2132 protected function makeUpdateOptions( $options ) {
2133 $opts = $this->makeUpdateOptionsArray( $options );
2135 return implode( ' ', $opts );
2139 * UPDATE wrapper. Takes a condition array and a SET array.
2141 * @param string $table Name of the table to UPDATE. This will be passed through
2142 * DatabaseBase::tableName().
2143 * @param array $values An array of values to SET. For each array element,
2144 * the key gives the field name, and the value gives the data to set
2145 * that field to. The data will be quoted by DatabaseBase::addQuotes().
2146 * @param array $conds An array of conditions (WHERE). See
2147 * DatabaseBase::select() for the details of the format of condition
2148 * arrays. Use '*' to update all rows.
2149 * @param string $fname The function name of the caller (from __METHOD__),
2150 * for logging and profiling.
2151 * @param array $options An array of UPDATE options, can be:
2152 * - IGNORE: Ignore unique key conflicts
2153 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
2154 * @return bool
2156 function update( $table, $values, $conds, $fname = __METHOD__, $options = array() ) {
2157 $table = $this->tableName( $table );
2158 $opts = $this->makeUpdateOptions( $options );
2159 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
2161 if ( $conds !== array() && $conds !== '*' ) {
2162 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
2165 return $this->query( $sql, $fname );
2169 * Makes an encoded list of strings from an array
2171 * @param array $a Containing the data
2172 * @param int $mode Constant
2173 * - LIST_COMMA: Comma separated, no field names
2174 * - LIST_AND: ANDed WHERE clause (without the WHERE). See the
2175 * documentation for $conds in DatabaseBase::select().
2176 * - LIST_OR: ORed WHERE clause (without the WHERE)
2177 * - LIST_SET: Comma separated with field names, like a SET clause
2178 * - LIST_NAMES: Comma separated field names
2179 * @throws MWException|DBUnexpectedError
2180 * @return string
2182 public function makeList( $a, $mode = LIST_COMMA ) {
2183 if ( !is_array( $a ) ) {
2184 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
2187 $first = true;
2188 $list = '';
2190 foreach ( $a as $field => $value ) {
2191 if ( !$first ) {
2192 if ( $mode == LIST_AND ) {
2193 $list .= ' AND ';
2194 } elseif ( $mode == LIST_OR ) {
2195 $list .= ' OR ';
2196 } else {
2197 $list .= ',';
2199 } else {
2200 $first = false;
2203 if ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_numeric( $field ) ) {
2204 $list .= "($value)";
2205 } elseif ( ( $mode == LIST_SET ) && is_numeric( $field ) ) {
2206 $list .= "$value";
2207 } elseif ( ( $mode == LIST_AND || $mode == LIST_OR ) && is_array( $value ) ) {
2208 // Remove null from array to be handled separately if found
2209 $includeNull = false;
2210 foreach ( array_keys( $value, null, true ) as $nullKey ) {
2211 $includeNull = true;
2212 unset( $value[$nullKey] );
2214 if ( count( $value ) == 0 && !$includeNull ) {
2215 throw new MWException( __METHOD__ . ": empty input for field $field" );
2216 } elseif ( count( $value ) == 0 ) {
2217 // only check if $field is null
2218 $list .= "$field IS NULL";
2219 } else {
2220 // IN clause contains at least one valid element
2221 if ( $includeNull ) {
2222 // Group subconditions to ensure correct precedence
2223 $list .= '(';
2225 if ( count( $value ) == 1 ) {
2226 // Special-case single values, as IN isn't terribly efficient
2227 // Don't necessarily assume the single key is 0; we don't
2228 // enforce linear numeric ordering on other arrays here.
2229 $value = array_values( $value );
2230 $list .= $field . " = " . $this->addQuotes( $value[0] );
2231 } else {
2232 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
2234 // if null present in array, append IS NULL
2235 if ( $includeNull ) {
2236 $list .= " OR $field IS NULL)";
2239 } elseif ( $value === null ) {
2240 if ( $mode == LIST_AND || $mode == LIST_OR ) {
2241 $list .= "$field IS ";
2242 } elseif ( $mode == LIST_SET ) {
2243 $list .= "$field = ";
2245 $list .= 'NULL';
2246 } else {
2247 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
2248 $list .= "$field = ";
2250 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
2254 return $list;
2258 * Build a partial where clause from a 2-d array such as used for LinkBatch.
2259 * The keys on each level may be either integers or strings.
2261 * @param array $data Organized as 2-d
2262 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
2263 * @param string $baseKey Field name to match the base-level keys to (eg 'pl_namespace')
2264 * @param string $subKey Field name to match the sub-level keys to (eg 'pl_title')
2265 * @return string|bool SQL fragment, or false if no items in array
2267 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
2268 $conds = array();
2270 foreach ( $data as $base => $sub ) {
2271 if ( count( $sub ) ) {
2272 $conds[] = $this->makeList(
2273 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
2274 LIST_AND );
2278 if ( $conds ) {
2279 return $this->makeList( $conds, LIST_OR );
2280 } else {
2281 // Nothing to search for...
2282 return false;
2287 * Return aggregated value alias
2289 * @param array $valuedata
2290 * @param string $valuename
2292 * @return string
2294 public function aggregateValue( $valuedata, $valuename = 'value' ) {
2295 return $valuename;
2299 * @param string $field
2300 * @return string
2302 public function bitNot( $field ) {
2303 return "(~$field)";
2307 * @param string $fieldLeft
2308 * @param string $fieldRight
2309 * @return string
2311 public function bitAnd( $fieldLeft, $fieldRight ) {
2312 return "($fieldLeft & $fieldRight)";
2316 * @param string $fieldLeft
2317 * @param string $fieldRight
2318 * @return string
2320 public function bitOr( $fieldLeft, $fieldRight ) {
2321 return "($fieldLeft | $fieldRight)";
2325 * Build a concatenation list to feed into a SQL query
2326 * @param array $stringList List of raw SQL expressions; caller is
2327 * responsible for any quoting
2328 * @return string
2330 public function buildConcat( $stringList ) {
2331 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2335 * Build a GROUP_CONCAT or equivalent statement for a query.
2337 * This is useful for combining a field for several rows into a single string.
2338 * NULL values will not appear in the output, duplicated values will appear,
2339 * and the resulting delimiter-separated values have no defined sort order.
2340 * Code using the results may need to use the PHP unique() or sort() methods.
2342 * @param string $delim Glue to bind the results together
2343 * @param string|array $table Table name
2344 * @param string $field Field name
2345 * @param string|array $conds Conditions
2346 * @param string|array $join_conds Join conditions
2347 * @return string SQL text
2348 * @since 1.23
2350 public function buildGroupConcatField(
2351 $delim, $table, $field, $conds = '', $join_conds = array()
2353 $fld = "GROUP_CONCAT($field SEPARATOR " . $this->addQuotes( $delim ) . ')';
2355 return '(' . $this->selectSQLText( $table, $fld, $conds, null, array(), $join_conds ) . ')';
2359 * Change the current database
2361 * @todo Explain what exactly will fail if this is not overridden.
2363 * @param string $db
2365 * @return bool Success or failure
2367 public function selectDB( $db ) {
2368 # Stub. Shouldn't cause serious problems if it's not overridden, but
2369 # if your database engine supports a concept similar to MySQL's
2370 # databases you may as well.
2371 $this->mDBname = $db;
2373 return true;
2377 * Get the current DB name
2378 * @return string
2380 public function getDBname() {
2381 return $this->mDBname;
2385 * Get the server hostname or IP address
2386 * @return string
2388 public function getServer() {
2389 return $this->mServer;
2393 * Format a table name ready for use in constructing an SQL query
2395 * This does two important things: it quotes the table names to clean them up,
2396 * and it adds a table prefix if only given a table name with no quotes.
2398 * All functions of this object which require a table name call this function
2399 * themselves. Pass the canonical name to such functions. This is only needed
2400 * when calling query() directly.
2402 * @param string $name Database table name
2403 * @param string $format One of:
2404 * quoted - Automatically pass the table name through addIdentifierQuotes()
2405 * so that it can be used in a query.
2406 * raw - Do not add identifier quotes to the table name
2407 * @return string Full database name
2409 public function tableName( $name, $format = 'quoted' ) {
2410 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables, $wgSharedSchema;
2411 # Skip the entire process when we have a string quoted on both ends.
2412 # Note that we check the end so that we will still quote any use of
2413 # use of `database`.table. But won't break things if someone wants
2414 # to query a database table with a dot in the name.
2415 if ( $this->isQuotedIdentifier( $name ) ) {
2416 return $name;
2419 # Lets test for any bits of text that should never show up in a table
2420 # name. Basically anything like JOIN or ON which are actually part of
2421 # SQL queries, but may end up inside of the table value to combine
2422 # sql. Such as how the API is doing.
2423 # Note that we use a whitespace test rather than a \b test to avoid
2424 # any remote case where a word like on may be inside of a table name
2425 # surrounded by symbols which may be considered word breaks.
2426 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
2427 return $name;
2430 # Split database and table into proper variables.
2431 # We reverse the explode so that database.table and table both output
2432 # the correct table.
2433 $dbDetails = explode( '.', $name, 3 );
2434 if ( count( $dbDetails ) == 3 ) {
2435 list( $database, $schema, $table ) = $dbDetails;
2436 # We don't want any prefix added in this case
2437 $prefix = '';
2438 } elseif ( count( $dbDetails ) == 2 ) {
2439 list( $database, $table ) = $dbDetails;
2440 # We don't want any prefix added in this case
2441 # In dbs that support it, $database may actually be the schema
2442 # but that doesn't affect any of the functionality here
2443 $prefix = '';
2444 $schema = null;
2445 } else {
2446 list( $table ) = $dbDetails;
2447 if ( $wgSharedDB !== null # We have a shared database
2448 && $this->mForeign == false # We're not working on a foreign database
2449 && !$this->isQuotedIdentifier( $table ) # Prevent shared tables listing '`table`'
2450 && in_array( $table, $wgSharedTables ) # A shared table is selected
2452 $database = $wgSharedDB;
2453 $schema = $wgSharedSchema === null ? $this->mSchema : $wgSharedSchema;
2454 $prefix = $wgSharedPrefix === null ? $this->mTablePrefix : $wgSharedPrefix;
2455 } else {
2456 $database = null;
2457 $schema = $this->mSchema; # Default schema
2458 $prefix = $this->mTablePrefix; # Default prefix
2462 # Quote $table and apply the prefix if not quoted.
2463 # $tableName might be empty if this is called from Database::replaceVars()
2464 $tableName = "{$prefix}{$table}";
2465 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $tableName ) && $tableName !== '' ) {
2466 $tableName = $this->addIdentifierQuotes( $tableName );
2469 # Quote $schema and merge it with the table name if needed
2470 if ( $schema !== null ) {
2471 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $schema ) ) {
2472 $schema = $this->addIdentifierQuotes( $schema );
2474 $tableName = $schema . '.' . $tableName;
2477 # Quote $database and merge it with the table name if needed
2478 if ( $database !== null ) {
2479 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
2480 $database = $this->addIdentifierQuotes( $database );
2482 $tableName = $database . '.' . $tableName;
2485 return $tableName;
2489 * Fetch a number of table names into an array
2490 * This is handy when you need to construct SQL for joins
2492 * Example:
2493 * extract( $dbr->tableNames( 'user', 'watchlist' ) );
2494 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2495 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2497 * @return array
2499 public function tableNames() {
2500 $inArray = func_get_args();
2501 $retVal = array();
2503 foreach ( $inArray as $name ) {
2504 $retVal[$name] = $this->tableName( $name );
2507 return $retVal;
2511 * Fetch a number of table names into an zero-indexed numerical array
2512 * This is handy when you need to construct SQL for joins
2514 * Example:
2515 * list( $user, $watchlist ) = $dbr->tableNamesN( 'user', 'watchlist' );
2516 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2517 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2519 * @return array
2521 public function tableNamesN() {
2522 $inArray = func_get_args();
2523 $retVal = array();
2525 foreach ( $inArray as $name ) {
2526 $retVal[] = $this->tableName( $name );
2529 return $retVal;
2533 * Get an aliased table name
2534 * e.g. tableName AS newTableName
2536 * @param string $name Table name, see tableName()
2537 * @param string|bool $alias Alias (optional)
2538 * @return string SQL name for aliased table. Will not alias a table to its own name
2540 public function tableNameWithAlias( $name, $alias = false ) {
2541 if ( !$alias || $alias == $name ) {
2542 return $this->tableName( $name );
2543 } else {
2544 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2549 * Gets an array of aliased table names
2551 * @param array $tables Array( [alias] => table )
2552 * @return string[] See tableNameWithAlias()
2554 public function tableNamesWithAlias( $tables ) {
2555 $retval = array();
2556 foreach ( $tables as $alias => $table ) {
2557 if ( is_numeric( $alias ) ) {
2558 $alias = $table;
2560 $retval[] = $this->tableNameWithAlias( $table, $alias );
2563 return $retval;
2567 * Get an aliased field name
2568 * e.g. fieldName AS newFieldName
2570 * @param string $name Field name
2571 * @param string|bool $alias Alias (optional)
2572 * @return string SQL name for aliased field. Will not alias a field to its own name
2574 public function fieldNameWithAlias( $name, $alias = false ) {
2575 if ( !$alias || (string)$alias === (string)$name ) {
2576 return $name;
2577 } else {
2578 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2583 * Gets an array of aliased field names
2585 * @param array $fields Array( [alias] => field )
2586 * @return string[] See fieldNameWithAlias()
2588 public function fieldNamesWithAlias( $fields ) {
2589 $retval = array();
2590 foreach ( $fields as $alias => $field ) {
2591 if ( is_numeric( $alias ) ) {
2592 $alias = $field;
2594 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2597 return $retval;
2601 * Get the aliased table name clause for a FROM clause
2602 * which might have a JOIN and/or USE INDEX clause
2604 * @param array $tables ( [alias] => table )
2605 * @param array $use_index Same as for select()
2606 * @param array $join_conds Same as for select()
2607 * @return string
2609 protected function tableNamesWithUseIndexOrJOIN(
2610 $tables, $use_index = array(), $join_conds = array()
2612 $ret = array();
2613 $retJOIN = array();
2614 $use_index = (array)$use_index;
2615 $join_conds = (array)$join_conds;
2617 foreach ( $tables as $alias => $table ) {
2618 if ( !is_string( $alias ) ) {
2619 // No alias? Set it equal to the table name
2620 $alias = $table;
2622 // Is there a JOIN clause for this table?
2623 if ( isset( $join_conds[$alias] ) ) {
2624 list( $joinType, $conds ) = $join_conds[$alias];
2625 $tableClause = $joinType;
2626 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2627 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2628 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2629 if ( $use != '' ) {
2630 $tableClause .= ' ' . $use;
2633 $on = $this->makeList( (array)$conds, LIST_AND );
2634 if ( $on != '' ) {
2635 $tableClause .= ' ON (' . $on . ')';
2638 $retJOIN[] = $tableClause;
2639 } elseif ( isset( $use_index[$alias] ) ) {
2640 // Is there an INDEX clause for this table?
2641 $tableClause = $this->tableNameWithAlias( $table, $alias );
2642 $tableClause .= ' ' . $this->useIndexClause(
2643 implode( ',', (array)$use_index[$alias] )
2646 $ret[] = $tableClause;
2647 } else {
2648 $tableClause = $this->tableNameWithAlias( $table, $alias );
2650 $ret[] = $tableClause;
2654 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2655 $implicitJoins = !empty( $ret ) ? implode( ',', $ret ) : "";
2656 $explicitJoins = !empty( $retJOIN ) ? implode( ' ', $retJOIN ) : "";
2658 // Compile our final table clause
2659 return implode( ' ', array( $implicitJoins, $explicitJoins ) );
2663 * Get the name of an index in a given table.
2665 * @protected Don't use outside of DatabaseBase and childs
2666 * @param string $index
2667 * @return string
2669 public function indexName( $index ) {
2670 // @FIXME: Make this protected once we move away from PHP 5.3
2671 // Needs to be public because of usage in closure (in DatabaseBase::replaceVars)
2673 // Backwards-compatibility hack
2674 $renamed = array(
2675 'ar_usertext_timestamp' => 'usertext_timestamp',
2676 'un_user_id' => 'user_id',
2677 'un_user_ip' => 'user_ip',
2680 if ( isset( $renamed[$index] ) ) {
2681 return $renamed[$index];
2682 } else {
2683 return $index;
2688 * Adds quotes and backslashes.
2690 * @param string $s
2691 * @return string
2693 public function addQuotes( $s ) {
2694 if ( $s === null ) {
2695 return 'NULL';
2696 } else {
2697 # This will also quote numeric values. This should be harmless,
2698 # and protects against weird problems that occur when they really
2699 # _are_ strings such as article titles and string->number->string
2700 # conversion is not 1:1.
2701 return "'" . $this->strencode( $s ) . "'";
2706 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2707 * MySQL uses `backticks` while basically everything else uses double quotes.
2708 * Since MySQL is the odd one out here the double quotes are our generic
2709 * and we implement backticks in DatabaseMysql.
2711 * @param string $s
2712 * @return string
2714 public function addIdentifierQuotes( $s ) {
2715 return '"' . str_replace( '"', '""', $s ) . '"';
2719 * Returns if the given identifier looks quoted or not according to
2720 * the database convention for quoting identifiers .
2722 * @param string $name
2723 * @return bool
2725 public function isQuotedIdentifier( $name ) {
2726 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2730 * @param string $s
2731 * @return string
2733 protected function escapeLikeInternal( $s ) {
2734 return addcslashes( $s, '\%_' );
2738 * LIKE statement wrapper, receives a variable-length argument list with
2739 * parts of pattern to match containing either string literals that will be
2740 * escaped or tokens returned by anyChar() or anyString(). Alternatively,
2741 * the function could be provided with an array of aforementioned
2742 * parameters.
2744 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns
2745 * a LIKE clause that searches for subpages of 'My page title'.
2746 * Alternatively:
2747 * $pattern = array( 'My_page_title/', $dbr->anyString() );
2748 * $query .= $dbr->buildLike( $pattern );
2750 * @since 1.16
2751 * @return string Fully built LIKE statement
2753 public function buildLike() {
2754 $params = func_get_args();
2756 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2757 $params = $params[0];
2760 $s = '';
2762 foreach ( $params as $value ) {
2763 if ( $value instanceof LikeMatch ) {
2764 $s .= $value->toString();
2765 } else {
2766 $s .= $this->escapeLikeInternal( $value );
2770 return " LIKE {$this->addQuotes( $s )} ";
2774 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2776 * @return LikeMatch
2778 public function anyChar() {
2779 return new LikeMatch( '_' );
2783 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2785 * @return LikeMatch
2787 public function anyString() {
2788 return new LikeMatch( '%' );
2792 * Returns an appropriately quoted sequence value for inserting a new row.
2793 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2794 * subclass will return an integer, and save the value for insertId()
2796 * Any implementation of this function should *not* involve reusing
2797 * sequence numbers created for rolled-back transactions.
2798 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2799 * @param string $seqName
2800 * @return null|int
2802 public function nextSequenceValue( $seqName ) {
2803 return null;
2807 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2808 * is only needed because a) MySQL must be as efficient as possible due to
2809 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2810 * which index to pick. Anyway, other databases might have different
2811 * indexes on a given table. So don't bother overriding this unless you're
2812 * MySQL.
2813 * @param string $index
2814 * @return string
2816 public function useIndexClause( $index ) {
2817 return '';
2821 * REPLACE query wrapper.
2823 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2824 * except that when there is a duplicate key error, the old row is deleted
2825 * and the new row is inserted in its place.
2827 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2828 * perform the delete, we need to know what the unique indexes are so that
2829 * we know how to find the conflicting rows.
2831 * It may be more efficient to leave off unique indexes which are unlikely
2832 * to collide. However if you do this, you run the risk of encountering
2833 * errors which wouldn't have occurred in MySQL.
2835 * @param string $table The table to replace the row(s) in.
2836 * @param array $uniqueIndexes Is an array of indexes. Each element may be either
2837 * a field name or an array of field names
2838 * @param array $rows Can be either a single row to insert, or multiple rows,
2839 * in the same format as for DatabaseBase::insert()
2840 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2842 public function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__ ) {
2843 $quotedTable = $this->tableName( $table );
2845 if ( count( $rows ) == 0 ) {
2846 return;
2849 # Single row case
2850 if ( !is_array( reset( $rows ) ) ) {
2851 $rows = array( $rows );
2854 foreach ( $rows as $row ) {
2855 # Delete rows which collide
2856 if ( $uniqueIndexes ) {
2857 $sql = "DELETE FROM $quotedTable WHERE ";
2858 $first = true;
2859 foreach ( $uniqueIndexes as $index ) {
2860 if ( $first ) {
2861 $first = false;
2862 $sql .= '( ';
2863 } else {
2864 $sql .= ' ) OR ( ';
2866 if ( is_array( $index ) ) {
2867 $first2 = true;
2868 foreach ( $index as $col ) {
2869 if ( $first2 ) {
2870 $first2 = false;
2871 } else {
2872 $sql .= ' AND ';
2874 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2876 } else {
2877 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2880 $sql .= ' )';
2881 $this->query( $sql, $fname );
2884 # Now insert the row
2885 $this->insert( $table, $row, $fname );
2890 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2891 * statement.
2893 * @param string $table Table name
2894 * @param array|string $rows Row(s) to insert
2895 * @param string $fname Caller function name
2897 * @return ResultWrapper
2899 protected function nativeReplace( $table, $rows, $fname ) {
2900 $table = $this->tableName( $table );
2902 # Single row case
2903 if ( !is_array( reset( $rows ) ) ) {
2904 $rows = array( $rows );
2907 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2908 $first = true;
2910 foreach ( $rows as $row ) {
2911 if ( $first ) {
2912 $first = false;
2913 } else {
2914 $sql .= ',';
2917 $sql .= '(' . $this->makeList( $row ) . ')';
2920 return $this->query( $sql, $fname );
2924 * INSERT ON DUPLICATE KEY UPDATE wrapper, upserts an array into a table.
2926 * This updates any conflicting rows (according to the unique indexes) using
2927 * the provided SET clause and inserts any remaining (non-conflicted) rows.
2929 * $rows may be either:
2930 * - A single associative array. The array keys are the field names, and
2931 * the values are the values to insert. The values are treated as data
2932 * and will be quoted appropriately. If NULL is inserted, this will be
2933 * converted to a database NULL.
2934 * - An array with numeric keys, holding a list of associative arrays.
2935 * This causes a multi-row INSERT on DBMSs that support it. The keys in
2936 * each subarray must be identical to each other, and in the same order.
2938 * It may be more efficient to leave off unique indexes which are unlikely
2939 * to collide. However if you do this, you run the risk of encountering
2940 * errors which wouldn't have occurred in MySQL.
2942 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
2943 * returns success.
2945 * @since 1.22
2947 * @param string $table Table name. This will be passed through DatabaseBase::tableName().
2948 * @param array $rows A single row or list of rows to insert
2949 * @param array $uniqueIndexes List of single field names or field name tuples
2950 * @param array $set An array of values to SET. For each array element, the
2951 * key gives the field name, and the value gives the data to set that
2952 * field to. The data will be quoted by DatabaseBase::addQuotes().
2953 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
2954 * @throws Exception
2955 * @return bool
2957 public function upsert( $table, array $rows, array $uniqueIndexes, array $set,
2958 $fname = __METHOD__
2960 if ( !count( $rows ) ) {
2961 return true; // nothing to do
2964 if ( !is_array( reset( $rows ) ) ) {
2965 $rows = array( $rows );
2968 if ( count( $uniqueIndexes ) ) {
2969 $clauses = array(); // list WHERE clauses that each identify a single row
2970 foreach ( $rows as $row ) {
2971 foreach ( $uniqueIndexes as $index ) {
2972 $index = is_array( $index ) ? $index : array( $index ); // columns
2973 $rowKey = array(); // unique key to this row
2974 foreach ( $index as $column ) {
2975 $rowKey[$column] = $row[$column];
2977 $clauses[] = $this->makeList( $rowKey, LIST_AND );
2980 $where = array( $this->makeList( $clauses, LIST_OR ) );
2981 } else {
2982 $where = false;
2985 $useTrx = !$this->mTrxLevel;
2986 if ( $useTrx ) {
2987 $this->begin( $fname );
2989 try {
2990 # Update any existing conflicting row(s)
2991 if ( $where !== false ) {
2992 $ok = $this->update( $table, $set, $where, $fname );
2993 } else {
2994 $ok = true;
2996 # Now insert any non-conflicting row(s)
2997 $ok = $this->insert( $table, $rows, $fname, array( 'IGNORE' ) ) && $ok;
2998 } catch ( Exception $e ) {
2999 if ( $useTrx ) {
3000 $this->rollback( $fname );
3002 throw $e;
3004 if ( $useTrx ) {
3005 $this->commit( $fname );
3008 return $ok;
3012 * DELETE where the condition is a join.
3014 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
3015 * we use sub-selects
3017 * For safety, an empty $conds will not delete everything. If you want to
3018 * delete all rows where the join condition matches, set $conds='*'.
3020 * DO NOT put the join condition in $conds.
3022 * @param string $delTable The table to delete from.
3023 * @param string $joinTable The other table.
3024 * @param string $delVar The variable to join on, in the first table.
3025 * @param string $joinVar The variable to join on, in the second table.
3026 * @param array $conds Condition array of field names mapped to variables,
3027 * ANDed together in the WHERE clause
3028 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
3029 * @throws DBUnexpectedError
3031 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
3032 $fname = __METHOD__
3034 if ( !$conds ) {
3035 throw new DBUnexpectedError( $this,
3036 'DatabaseBase::deleteJoin() called with empty $conds' );
3039 $delTable = $this->tableName( $delTable );
3040 $joinTable = $this->tableName( $joinTable );
3041 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
3042 if ( $conds != '*' ) {
3043 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND );
3045 $sql .= ')';
3047 $this->query( $sql, $fname );
3051 * Returns the size of a text field, or -1 for "unlimited"
3053 * @param string $table
3054 * @param string $field
3055 * @return int
3057 public function textFieldSize( $table, $field ) {
3058 $table = $this->tableName( $table );
3059 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
3060 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
3061 $row = $this->fetchObject( $res );
3063 $m = array();
3065 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
3066 $size = $m[1];
3067 } else {
3068 $size = -1;
3071 return $size;
3075 * A string to insert into queries to show that they're low-priority, like
3076 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
3077 * string and nothing bad should happen.
3079 * @return string Returns the text of the low priority option if it is
3080 * supported, or a blank string otherwise
3082 public function lowPriorityOption() {
3083 return '';
3087 * DELETE query wrapper.
3089 * @param array $table Table name
3090 * @param string|array $conds Array of conditions. See $conds in DatabaseBase::select()
3091 * for the format. Use $conds == "*" to delete all rows
3092 * @param string $fname Name of the calling function
3093 * @throws DBUnexpectedError
3094 * @return bool|ResultWrapper
3096 public function delete( $table, $conds, $fname = __METHOD__ ) {
3097 if ( !$conds ) {
3098 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
3101 $table = $this->tableName( $table );
3102 $sql = "DELETE FROM $table";
3104 if ( $conds != '*' ) {
3105 if ( is_array( $conds ) ) {
3106 $conds = $this->makeList( $conds, LIST_AND );
3108 $sql .= ' WHERE ' . $conds;
3111 return $this->query( $sql, $fname );
3115 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
3116 * into another table.
3118 * @param string $destTable The table name to insert into
3119 * @param string|array $srcTable May be either a table name, or an array of table names
3120 * to include in a join.
3122 * @param array $varMap Must be an associative array of the form
3123 * array( 'dest1' => 'source1', ...). Source items may be literals
3124 * rather than field names, but strings should be quoted with
3125 * DatabaseBase::addQuotes()
3127 * @param array $conds Condition array. See $conds in DatabaseBase::select() for
3128 * the details of the format of condition arrays. May be "*" to copy the
3129 * whole table.
3131 * @param string $fname The function name of the caller, from __METHOD__
3133 * @param array $insertOptions Options for the INSERT part of the query, see
3134 * DatabaseBase::insert() for details.
3135 * @param array $selectOptions Options for the SELECT part of the query, see
3136 * DatabaseBase::select() for details.
3138 * @return ResultWrapper
3140 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
3141 $fname = __METHOD__,
3142 $insertOptions = array(), $selectOptions = array()
3144 $destTable = $this->tableName( $destTable );
3146 if ( !is_array( $insertOptions ) ) {
3147 $insertOptions = array( $insertOptions );
3150 $insertOptions = $this->makeInsertOptions( $insertOptions );
3152 if ( !is_array( $selectOptions ) ) {
3153 $selectOptions = array( $selectOptions );
3156 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
3158 if ( is_array( $srcTable ) ) {
3159 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
3160 } else {
3161 $srcTable = $this->tableName( $srcTable );
3164 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
3165 " SELECT $startOpts " . implode( ',', $varMap ) .
3166 " FROM $srcTable $useIndex ";
3168 if ( $conds != '*' ) {
3169 if ( is_array( $conds ) ) {
3170 $conds = $this->makeList( $conds, LIST_AND );
3172 $sql .= " WHERE $conds";
3175 $sql .= " $tailOpts";
3177 return $this->query( $sql, $fname );
3181 * Construct a LIMIT query with optional offset. This is used for query
3182 * pages. The SQL should be adjusted so that only the first $limit rows
3183 * are returned. If $offset is provided as well, then the first $offset
3184 * rows should be discarded, and the next $limit rows should be returned.
3185 * If the result of the query is not ordered, then the rows to be returned
3186 * are theoretically arbitrary.
3188 * $sql is expected to be a SELECT, if that makes a difference.
3190 * The version provided by default works in MySQL and SQLite. It will very
3191 * likely need to be overridden for most other DBMSes.
3193 * @param string $sql SQL query we will append the limit too
3194 * @param int $limit The SQL limit
3195 * @param int|bool $offset The SQL offset (default false)
3196 * @throws DBUnexpectedError
3197 * @return string
3199 public function limitResult( $sql, $limit, $offset = false ) {
3200 if ( !is_numeric( $limit ) ) {
3201 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
3204 return "$sql LIMIT "
3205 . ( ( is_numeric( $offset ) && $offset != 0 ) ? "{$offset}," : "" )
3206 . "{$limit} ";
3210 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
3211 * within the UNION construct.
3212 * @return bool
3214 public function unionSupportsOrderAndLimit() {
3215 return true; // True for almost every DB supported
3219 * Construct a UNION query
3220 * This is used for providing overload point for other DB abstractions
3221 * not compatible with the MySQL syntax.
3222 * @param array $sqls SQL statements to combine
3223 * @param bool $all Use UNION ALL
3224 * @return string SQL fragment
3226 public function unionQueries( $sqls, $all ) {
3227 $glue = $all ? ') UNION ALL (' : ') UNION (';
3229 return '(' . implode( $glue, $sqls ) . ')';
3233 * Returns an SQL expression for a simple conditional. This doesn't need
3234 * to be overridden unless CASE isn't supported in your DBMS.
3236 * @param string|array $cond SQL expression which will result in a boolean value
3237 * @param string $trueVal SQL expression to return if true
3238 * @param string $falseVal SQL expression to return if false
3239 * @return string SQL fragment
3241 public function conditional( $cond, $trueVal, $falseVal ) {
3242 if ( is_array( $cond ) ) {
3243 $cond = $this->makeList( $cond, LIST_AND );
3246 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
3250 * Returns a comand for str_replace function in SQL query.
3251 * Uses REPLACE() in MySQL
3253 * @param string $orig Column to modify
3254 * @param string $old Column to seek
3255 * @param string $new Column to replace with
3257 * @return string
3259 public function strreplace( $orig, $old, $new ) {
3260 return "REPLACE({$orig}, {$old}, {$new})";
3264 * Determines how long the server has been up
3265 * STUB
3267 * @return int
3269 public function getServerUptime() {
3270 return 0;
3274 * Determines if the last failure was due to a deadlock
3275 * STUB
3277 * @return bool
3279 public function wasDeadlock() {
3280 return false;
3284 * Determines if the last failure was due to a lock timeout
3285 * STUB
3287 * @return bool
3289 public function wasLockTimeout() {
3290 return false;
3294 * Determines if the last query error was something that should be dealt
3295 * with by pinging the connection and reissuing the query.
3296 * STUB
3298 * @return bool
3300 public function wasErrorReissuable() {
3301 return false;
3305 * Determines if the last failure was due to the database being read-only.
3306 * STUB
3308 * @return bool
3310 public function wasReadOnlyError() {
3311 return false;
3315 * Perform a deadlock-prone transaction.
3317 * This function invokes a callback function to perform a set of write
3318 * queries. If a deadlock occurs during the processing, the transaction
3319 * will be rolled back and the callback function will be called again.
3321 * Usage:
3322 * $dbw->deadlockLoop( callback, ... );
3324 * Extra arguments are passed through to the specified callback function.
3326 * Returns whatever the callback function returned on its successful,
3327 * iteration, or false on error, for example if the retry limit was
3328 * reached.
3330 * @return bool
3332 public function deadlockLoop() {
3333 $this->begin( __METHOD__ );
3334 $args = func_get_args();
3335 $function = array_shift( $args );
3336 $oldIgnore = $this->ignoreErrors( true );
3337 $tries = self::DEADLOCK_TRIES;
3339 if ( is_array( $function ) ) {
3340 $fname = $function[0];
3341 } else {
3342 $fname = $function;
3345 do {
3346 $retVal = call_user_func_array( $function, $args );
3347 $error = $this->lastError();
3348 $errno = $this->lastErrno();
3349 $sql = $this->lastQuery();
3351 if ( $errno ) {
3352 if ( $this->wasDeadlock() ) {
3353 # Retry
3354 usleep( mt_rand( self::DEADLOCK_DELAY_MIN, self::DEADLOCK_DELAY_MAX ) );
3355 } else {
3356 $this->reportQueryError( $error, $errno, $sql, $fname );
3359 } while ( $this->wasDeadlock() && --$tries > 0 );
3361 $this->ignoreErrors( $oldIgnore );
3363 if ( $tries <= 0 ) {
3364 $this->rollback( __METHOD__ );
3365 $this->reportQueryError( $error, $errno, $sql, $fname );
3367 return false;
3368 } else {
3369 $this->commit( __METHOD__ );
3371 return $retVal;
3376 * Wait for the slave to catch up to a given master position.
3378 * @param DBMasterPos $pos
3379 * @param int $timeout The maximum number of seconds to wait for
3380 * synchronisation
3381 * @return int Zero if the slave was past that position already,
3382 * greater than zero if we waited for some period of time, less than
3383 * zero if we timed out.
3385 public function masterPosWait( DBMasterPos $pos, $timeout ) {
3386 # Real waits are implemented in the subclass.
3387 return 0;
3391 * Get the replication position of this slave
3393 * @return DBMasterPos|bool False if this is not a slave.
3395 public function getSlavePos() {
3396 # Stub
3397 return false;
3401 * Get the position of this master
3403 * @return DBMasterPos|bool False if this is not a master
3405 public function getMasterPos() {
3406 # Stub
3407 return false;
3411 * Run an anonymous function as soon as there is no transaction pending.
3412 * If there is a transaction and it is rolled back, then the callback is cancelled.
3413 * Queries in the function will run in AUTO-COMMIT mode unless there are begin() calls.
3414 * Callbacks must commit any transactions that they begin.
3416 * This is useful for updates to different systems or when separate transactions are needed.
3417 * For example, one might want to enqueue jobs into a system outside the database, but only
3418 * after the database is updated so that the jobs will see the data when they actually run.
3419 * It can also be used for updates that easily cause deadlocks if locks are held too long.
3421 * @param callable $callback
3422 * @since 1.20
3424 final public function onTransactionIdle( $callback ) {
3425 $this->mTrxIdleCallbacks[] = array( $callback, wfGetCaller() );
3426 if ( !$this->mTrxLevel ) {
3427 $this->runOnTransactionIdleCallbacks();
3432 * Run an anonymous function before the current transaction commits or now if there is none.
3433 * If there is a transaction and it is rolled back, then the callback is cancelled.
3434 * Callbacks must not start nor commit any transactions.
3436 * This is useful for updates that easily cause deadlocks if locks are held too long
3437 * but where atomicity is strongly desired for these updates and some related updates.
3439 * @param callable $callback
3440 * @since 1.22
3442 final public function onTransactionPreCommitOrIdle( $callback ) {
3443 if ( $this->mTrxLevel ) {
3444 $this->mTrxPreCommitCallbacks[] = array( $callback, wfGetCaller() );
3445 } else {
3446 $this->onTransactionIdle( $callback ); // this will trigger immediately
3451 * Actually any "on transaction idle" callbacks.
3453 * @since 1.20
3455 protected function runOnTransactionIdleCallbacks() {
3456 $autoTrx = $this->getFlag( DBO_TRX ); // automatic begin() enabled?
3458 $e = $ePrior = null; // last exception
3459 do { // callbacks may add callbacks :)
3460 $callbacks = $this->mTrxIdleCallbacks;
3461 $this->mTrxIdleCallbacks = array(); // recursion guard
3462 foreach ( $callbacks as $callback ) {
3463 try {
3464 list( $phpCallback ) = $callback;
3465 $this->clearFlag( DBO_TRX ); // make each query its own transaction
3466 call_user_func( $phpCallback );
3467 $this->setFlag( $autoTrx ? DBO_TRX : 0 ); // restore automatic begin()
3468 } catch ( Exception $e ) {
3469 if ( $ePrior ) {
3470 MWExceptionHandler::logException( $ePrior );
3472 $ePrior = $e;
3475 } while ( count( $this->mTrxIdleCallbacks ) );
3477 if ( $e instanceof Exception ) {
3478 throw $e; // re-throw any last exception
3483 * Actually any "on transaction pre-commit" callbacks.
3485 * @since 1.22
3487 protected function runOnTransactionPreCommitCallbacks() {
3488 $e = $ePrior = null; // last exception
3489 do { // callbacks may add callbacks :)
3490 $callbacks = $this->mTrxPreCommitCallbacks;
3491 $this->mTrxPreCommitCallbacks = array(); // recursion guard
3492 foreach ( $callbacks as $callback ) {
3493 try {
3494 list( $phpCallback ) = $callback;
3495 call_user_func( $phpCallback );
3496 } catch ( Exception $e ) {
3497 if ( $ePrior ) {
3498 MWExceptionHandler::logException( $ePrior );
3500 $ePrior = $e;
3503 } while ( count( $this->mTrxPreCommitCallbacks ) );
3505 if ( $e instanceof Exception ) {
3506 throw $e; // re-throw any last exception
3511 * Begin an atomic section of statements
3513 * If a transaction has been started already, just keep track of the given
3514 * section name to make sure the transaction is not committed pre-maturely.
3515 * This function can be used in layers (with sub-sections), so use a stack
3516 * to keep track of the different atomic sections. If there is no transaction,
3517 * start one implicitly.
3519 * The goal of this function is to create an atomic section of SQL queries
3520 * without having to start a new transaction if it already exists.
3522 * Atomic sections are more strict than transactions. With transactions,
3523 * attempting to begin a new transaction when one is already running results
3524 * in MediaWiki issuing a brief warning and doing an implicit commit. All
3525 * atomic levels *must* be explicitly closed using DatabaseBase::endAtomic(),
3526 * and any database transactions cannot be began or committed until all atomic
3527 * levels are closed. There is no such thing as implicitly opening or closing
3528 * an atomic section.
3530 * @since 1.23
3531 * @param string $fname
3532 * @throws DBError
3534 final public function startAtomic( $fname = __METHOD__ ) {
3535 if ( !$this->mTrxLevel ) {
3536 $this->begin( $fname );
3537 $this->mTrxAutomatic = true;
3538 $this->mTrxAutomaticAtomic = true;
3541 $this->mTrxAtomicLevels->push( $fname );
3545 * Ends an atomic section of SQL statements
3547 * Ends the next section of atomic SQL statements and commits the transaction
3548 * if necessary.
3550 * @since 1.23
3551 * @see DatabaseBase::startAtomic
3552 * @param string $fname
3553 * @throws DBError
3555 final public function endAtomic( $fname = __METHOD__ ) {
3556 if ( !$this->mTrxLevel ) {
3557 throw new DBUnexpectedError( $this, 'No atomic transaction is open.' );
3559 if ( $this->mTrxAtomicLevels->isEmpty() ||
3560 $this->mTrxAtomicLevels->pop() !== $fname
3562 throw new DBUnexpectedError( $this, 'Invalid atomic section ended.' );
3565 if ( $this->mTrxAtomicLevels->isEmpty() && $this->mTrxAutomaticAtomic ) {
3566 $this->commit( $fname, 'flush' );
3571 * Begin a transaction. If a transaction is already in progress,
3572 * that transaction will be committed before the new transaction is started.
3574 * Note that when the DBO_TRX flag is set (which is usually the case for web
3575 * requests, but not for maintenance scripts), any previous database query
3576 * will have started a transaction automatically.
3578 * Nesting of transactions is not supported. Attempts to nest transactions
3579 * will cause a warning, unless the current transaction was started
3580 * automatically because of the DBO_TRX flag.
3582 * @param string $fname
3583 * @throws DBError
3585 final public function begin( $fname = __METHOD__ ) {
3586 global $wgDebugDBTransactions;
3588 if ( $this->mTrxLevel ) { // implicit commit
3589 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3590 // If the current transaction was an automatic atomic one, then we definitely have
3591 // a problem. Same if there is any unclosed atomic level.
3592 throw new DBUnexpectedError( $this,
3593 "Attempted to start explicit transaction when atomic levels are still open."
3595 } elseif ( !$this->mTrxAutomatic ) {
3596 // We want to warn about inadvertently nested begin/commit pairs, but not about
3597 // auto-committing implicit transactions that were started by query() via DBO_TRX
3598 $msg = "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
3599 " performing implicit commit!";
3600 wfWarn( $msg );
3601 wfLogDBError( $msg,
3602 $this->getLogContext( array(
3603 'method' => __METHOD__,
3604 'fname' => $fname,
3607 } else {
3608 // if the transaction was automatic and has done write operations,
3609 // log it if $wgDebugDBTransactions is enabled.
3610 if ( $this->mTrxDoneWrites && $wgDebugDBTransactions ) {
3611 wfDebug( "$fname: Automatic transaction with writes in progress" .
3612 " (from {$this->mTrxFname}), performing implicit commit!\n"
3617 $this->runOnTransactionPreCommitCallbacks();
3618 $this->doCommit( $fname );
3619 if ( $this->mTrxDoneWrites ) {
3620 Profiler::instance()->getTransactionProfiler()->transactionWritingOut(
3621 $this->mServer, $this->mDBname, $this->mTrxShortId );
3623 $this->runOnTransactionIdleCallbacks();
3626 # Avoid fatals if close() was called
3627 if ( !$this->isOpen() ) {
3628 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3631 $this->doBegin( $fname );
3632 $this->mTrxTimestamp = microtime( true );
3633 $this->mTrxFname = $fname;
3634 $this->mTrxDoneWrites = false;
3635 $this->mTrxAutomatic = false;
3636 $this->mTrxAutomaticAtomic = false;
3637 $this->mTrxAtomicLevels = new SplStack;
3638 $this->mTrxIdleCallbacks = array();
3639 $this->mTrxPreCommitCallbacks = array();
3640 $this->mTrxShortId = wfRandomString( 12 );
3644 * Issues the BEGIN command to the database server.
3646 * @see DatabaseBase::begin()
3647 * @param string $fname
3649 protected function doBegin( $fname ) {
3650 $this->query( 'BEGIN', $fname );
3651 $this->mTrxLevel = 1;
3655 * Commits a transaction previously started using begin().
3656 * If no transaction is in progress, a warning is issued.
3658 * Nesting of transactions is not supported.
3660 * @param string $fname
3661 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3662 * explicitly committing implicit transactions, or calling commit when no
3663 * transaction is in progress. This will silently break any ongoing
3664 * explicit transaction. Only set the flush flag if you are sure that it
3665 * is safe to ignore these warnings in your context.
3666 * @throws DBUnexpectedError
3668 final public function commit( $fname = __METHOD__, $flush = '' ) {
3669 if ( !$this->mTrxAtomicLevels->isEmpty() ) {
3670 // There are still atomic sections open. This cannot be ignored
3671 throw new DBUnexpectedError(
3672 $this,
3673 "Attempted to commit transaction while atomic sections are still open"
3677 if ( $flush === 'flush' ) {
3678 if ( !$this->mTrxLevel ) {
3679 return; // nothing to do
3680 } elseif ( !$this->mTrxAutomatic ) {
3681 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3683 } else {
3684 if ( !$this->mTrxLevel ) {
3685 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
3686 return; // nothing to do
3687 } elseif ( $this->mTrxAutomatic ) {
3688 wfWarn( "$fname: Explicit commit of implicit transaction. Something may be out of sync!" );
3692 # Avoid fatals if close() was called
3693 if ( !$this->isOpen() ) {
3694 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3697 $this->runOnTransactionPreCommitCallbacks();
3698 $this->doCommit( $fname );
3699 if ( $this->mTrxDoneWrites ) {
3700 Profiler::instance()->getTransactionProfiler()->transactionWritingOut(
3701 $this->mServer, $this->mDBname, $this->mTrxShortId );
3703 $this->runOnTransactionIdleCallbacks();
3707 * Issues the COMMIT command to the database server.
3709 * @see DatabaseBase::commit()
3710 * @param string $fname
3712 protected function doCommit( $fname ) {
3713 if ( $this->mTrxLevel ) {
3714 $this->query( 'COMMIT', $fname );
3715 $this->mTrxLevel = 0;
3720 * Rollback a transaction previously started using begin().
3721 * If no transaction is in progress, a warning is issued.
3723 * No-op on non-transactional databases.
3725 * @param string $fname
3726 * @param string $flush Flush flag, set to 'flush' to disable warnings about
3727 * calling rollback when no transaction is in progress. This will silently
3728 * break any ongoing explicit transaction. Only set the flush flag if you
3729 * are sure that it is safe to ignore these warnings in your context.
3730 * @throws DBUnexpectedError
3731 * @since 1.23 Added $flush parameter
3733 final public function rollback( $fname = __METHOD__, $flush = '' ) {
3734 if ( $flush !== 'flush' ) {
3735 if ( !$this->mTrxLevel ) {
3736 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
3737 return; // nothing to do
3738 } elseif ( $this->mTrxAutomatic ) {
3739 wfWarn( "$fname: Explicit rollback of implicit transaction. Something may be out of sync!" );
3741 } else {
3742 if ( !$this->mTrxLevel ) {
3743 return; // nothing to do
3744 } elseif ( !$this->mTrxAutomatic ) {
3745 wfWarn( "$fname: Flushing an explicit transaction, getting out of sync!" );
3749 # Avoid fatals if close() was called
3750 if ( !$this->isOpen() ) {
3751 throw new DBUnexpectedError( $this, "DB connection was already closed." );
3754 $this->doRollback( $fname );
3755 $this->mTrxIdleCallbacks = array(); // cancel
3756 $this->mTrxPreCommitCallbacks = array(); // cancel
3757 $this->mTrxAtomicLevels = new SplStack;
3758 if ( $this->mTrxDoneWrites ) {
3759 Profiler::instance()->getTransactionProfiler()->transactionWritingOut(
3760 $this->mServer, $this->mDBname, $this->mTrxShortId );
3765 * Issues the ROLLBACK command to the database server.
3767 * @see DatabaseBase::rollback()
3768 * @param string $fname
3770 protected function doRollback( $fname ) {
3771 if ( $this->mTrxLevel ) {
3772 $this->query( 'ROLLBACK', $fname, true );
3773 $this->mTrxLevel = 0;
3778 * Creates a new table with structure copied from existing table
3779 * Note that unlike most database abstraction functions, this function does not
3780 * automatically append database prefix, because it works at a lower
3781 * abstraction level.
3782 * The table names passed to this function shall not be quoted (this
3783 * function calls addIdentifierQuotes when needed).
3785 * @param string $oldName Name of table whose structure should be copied
3786 * @param string $newName Name of table to be created
3787 * @param bool $temporary Whether the new table should be temporary
3788 * @param string $fname Calling function name
3789 * @throws MWException
3790 * @return bool True if operation was successful
3792 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3793 $fname = __METHOD__
3795 throw new MWException(
3796 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3800 * List all tables on the database
3802 * @param string $prefix Only show tables with this prefix, e.g. mw_
3803 * @param string $fname Calling function name
3804 * @throws MWException
3806 function listTables( $prefix = null, $fname = __METHOD__ ) {
3807 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3811 * Reset the views process cache set by listViews()
3812 * @since 1.22
3814 final public function clearViewsCache() {
3815 $this->allViews = null;
3819 * Lists all the VIEWs in the database
3821 * For caching purposes the list of all views should be stored in
3822 * $this->allViews. The process cache can be cleared with clearViewsCache()
3824 * @param string $prefix Only show VIEWs with this prefix, eg. unit_test_
3825 * @param string $fname Name of calling function
3826 * @throws MWException
3827 * @since 1.22
3829 public function listViews( $prefix = null, $fname = __METHOD__ ) {
3830 throw new MWException( 'DatabaseBase::listViews is not implemented in descendant class' );
3834 * Differentiates between a TABLE and a VIEW
3836 * @param string $name Name of the database-structure to test.
3837 * @throws MWException
3838 * @since 1.22
3840 public function isView( $name ) {
3841 throw new MWException( 'DatabaseBase::isView is not implemented in descendant class' );
3845 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3846 * to the format used for inserting into timestamp fields in this DBMS.
3848 * The result is unquoted, and needs to be passed through addQuotes()
3849 * before it can be included in raw SQL.
3851 * @param string|int $ts
3853 * @return string
3855 public function timestamp( $ts = 0 ) {
3856 return wfTimestamp( TS_MW, $ts );
3860 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3861 * to the format used for inserting into timestamp fields in this DBMS. If
3862 * NULL is input, it is passed through, allowing NULL values to be inserted
3863 * into timestamp fields.
3865 * The result is unquoted, and needs to be passed through addQuotes()
3866 * before it can be included in raw SQL.
3868 * @param string|int $ts
3870 * @return string
3872 public function timestampOrNull( $ts = null ) {
3873 if ( is_null( $ts ) ) {
3874 return null;
3875 } else {
3876 return $this->timestamp( $ts );
3881 * Take the result from a query, and wrap it in a ResultWrapper if
3882 * necessary. Boolean values are passed through as is, to indicate success
3883 * of write queries or failure.
3885 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3886 * resource, and it was necessary to call this function to convert it to
3887 * a wrapper. Nowadays, raw database objects are never exposed to external
3888 * callers, so this is unnecessary in external code. For compatibility with
3889 * old code, ResultWrapper objects are passed through unaltered.
3891 * @param bool|ResultWrapper|resource $result
3892 * @return bool|ResultWrapper
3894 public function resultObject( $result ) {
3895 if ( empty( $result ) ) {
3896 return false;
3897 } elseif ( $result instanceof ResultWrapper ) {
3898 return $result;
3899 } elseif ( $result === true ) {
3900 // Successful write query
3901 return $result;
3902 } else {
3903 return new ResultWrapper( $this, $result );
3908 * Ping the server and try to reconnect if it there is no connection
3910 * @return bool Success or failure
3912 public function ping() {
3913 # Stub. Not essential to override.
3914 return true;
3918 * Get slave lag. Currently supported only by MySQL.
3920 * Note that this function will generate a fatal error on many
3921 * installations. Most callers should use LoadBalancer::safeGetLag()
3922 * instead.
3924 * @return int Database replication lag in seconds
3926 public function getLag() {
3927 return 0;
3931 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3933 * @return int
3935 function maxListLen() {
3936 return 0;
3940 * Some DBMSs have a special format for inserting into blob fields, they
3941 * don't allow simple quoted strings to be inserted. To insert into such
3942 * a field, pass the data through this function before passing it to
3943 * DatabaseBase::insert().
3945 * @param string $b
3946 * @return string
3948 public function encodeBlob( $b ) {
3949 return $b;
3953 * Some DBMSs return a special placeholder object representing blob fields
3954 * in result objects. Pass the object through this function to return the
3955 * original string.
3957 * @param string $b
3958 * @return string
3960 public function decodeBlob( $b ) {
3961 return $b;
3965 * Override database's default behavior. $options include:
3966 * 'connTimeout' : Set the connection timeout value in seconds.
3967 * May be useful for very long batch queries such as
3968 * full-wiki dumps, where a single query reads out over
3969 * hours or days.
3971 * @param array $options
3972 * @return void
3974 public function setSessionOptions( array $options ) {
3978 * Read and execute SQL commands from a file.
3980 * Returns true on success, error string or exception on failure (depending
3981 * on object's error ignore settings).
3983 * @param string $filename File name to open
3984 * @param bool|callable $lineCallback Optional function called before reading each line
3985 * @param bool|callable $resultCallback Optional function called for each MySQL result
3986 * @param bool|string $fname Calling function name or false if name should be
3987 * generated dynamically using $filename
3988 * @param bool|callable $inputCallback Optional function called for each
3989 * complete line sent
3990 * @throws Exception|MWException
3991 * @return bool|string
3993 public function sourceFile(
3994 $filename, $lineCallback = false, $resultCallback = false, $fname = false, $inputCallback = false
3996 wfSuppressWarnings();
3997 $fp = fopen( $filename, 'r' );
3998 wfRestoreWarnings();
4000 if ( false === $fp ) {
4001 throw new MWException( "Could not open \"{$filename}\".\n" );
4004 if ( !$fname ) {
4005 $fname = __METHOD__ . "( $filename )";
4008 try {
4009 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname, $inputCallback );
4010 } catch ( Exception $e ) {
4011 fclose( $fp );
4012 throw $e;
4015 fclose( $fp );
4017 return $error;
4021 * Get the full path of a patch file. Originally based on archive()
4022 * from updaters.inc. Keep in mind this always returns a patch, as
4023 * it fails back to MySQL if no DB-specific patch can be found
4025 * @param string $patch The name of the patch, like patch-something.sql
4026 * @return string Full path to patch file
4028 public function patchPath( $patch ) {
4029 global $IP;
4031 $dbType = $this->getType();
4032 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
4033 return "$IP/maintenance/$dbType/archives/$patch";
4034 } else {
4035 return "$IP/maintenance/archives/$patch";
4040 * Set variables to be used in sourceFile/sourceStream, in preference to the
4041 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
4042 * all. If it's set to false, $GLOBALS will be used.
4044 * @param bool|array $vars Mapping variable name to value.
4046 public function setSchemaVars( $vars ) {
4047 $this->mSchemaVars = $vars;
4051 * Read and execute commands from an open file handle.
4053 * Returns true on success, error string or exception on failure (depending
4054 * on object's error ignore settings).
4056 * @param resource $fp File handle
4057 * @param bool|callable $lineCallback Optional function called before reading each query
4058 * @param bool|callable $resultCallback Optional function called for each MySQL result
4059 * @param string $fname Calling function name
4060 * @param bool|callable $inputCallback Optional function called for each complete query sent
4061 * @return bool|string
4063 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
4064 $fname = __METHOD__, $inputCallback = false
4066 $cmd = '';
4068 while ( !feof( $fp ) ) {
4069 if ( $lineCallback ) {
4070 call_user_func( $lineCallback );
4073 $line = trim( fgets( $fp ) );
4075 if ( $line == '' ) {
4076 continue;
4079 if ( '-' == $line[0] && '-' == $line[1] ) {
4080 continue;
4083 if ( $cmd != '' ) {
4084 $cmd .= ' ';
4087 $done = $this->streamStatementEnd( $cmd, $line );
4089 $cmd .= "$line\n";
4091 if ( $done || feof( $fp ) ) {
4092 $cmd = $this->replaceVars( $cmd );
4094 if ( ( $inputCallback && call_user_func( $inputCallback, $cmd ) ) || !$inputCallback ) {
4095 $res = $this->query( $cmd, $fname );
4097 if ( $resultCallback ) {
4098 call_user_func( $resultCallback, $res, $this );
4101 if ( false === $res ) {
4102 $err = $this->lastError();
4104 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
4107 $cmd = '';
4111 return true;
4115 * Called by sourceStream() to check if we've reached a statement end
4117 * @param string $sql SQL assembled so far
4118 * @param string $newLine New line about to be added to $sql
4119 * @return bool Whether $newLine contains end of the statement
4121 public function streamStatementEnd( &$sql, &$newLine ) {
4122 if ( $this->delimiter ) {
4123 $prev = $newLine;
4124 $newLine = preg_replace( '/' . preg_quote( $this->delimiter, '/' ) . '$/', '', $newLine );
4125 if ( $newLine != $prev ) {
4126 return true;
4130 return false;
4134 * Database independent variable replacement. Replaces a set of variables
4135 * in an SQL statement with their contents as given by $this->getSchemaVars().
4137 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
4139 * - '{$var}' should be used for text and is passed through the database's
4140 * addQuotes method.
4141 * - `{$var}` should be used for identifiers (e.g. table and database names).
4142 * It is passed through the database's addIdentifierQuotes method which
4143 * can be overridden if the database uses something other than backticks.
4144 * - / *_* / or / *$wgDBprefix* / passes the name that follows through the
4145 * database's tableName method.
4146 * - / *i* / passes the name that follows through the database's indexName method.
4147 * - In all other cases, / *$var* / is left unencoded. Except for table options,
4148 * its use should be avoided. In 1.24 and older, string encoding was applied.
4150 * @param string $ins SQL statement to replace variables in
4151 * @return string The new SQL statement with variables replaced
4153 protected function replaceVars( $ins ) {
4154 $that = $this;
4155 $vars = $this->getSchemaVars();
4156 return preg_replace_callback(
4158 /\* (\$wgDBprefix|[_i]) \*/ (\w*) | # 1-2. tableName, indexName
4159 \'\{\$ (\w+) }\' | # 3. addQuotes
4160 `\{\$ (\w+) }` | # 4. addIdentifierQuotes
4161 /\*\$ (\w+) \*/ # 5. leave unencoded
4162 !x',
4163 function ( $m ) use ( $that, $vars ) {
4164 // Note: Because of <https://bugs.php.net/bug.php?id=51881>,
4165 // check for both nonexistent keys *and* the empty string.
4166 if ( isset( $m[1] ) && $m[1] !== '' ) {
4167 if ( $m[1] === 'i' ) {
4168 return $that->indexName( $m[2] );
4169 } else {
4170 return $that->tableName( $m[2] );
4172 } elseif ( isset( $m[3] ) && $m[3] !== '' && array_key_exists( $m[3], $vars ) ) {
4173 return $that->addQuotes( $vars[$m[3]] );
4174 } elseif ( isset( $m[4] ) && $m[4] !== '' && array_key_exists( $m[4], $vars ) ) {
4175 return $that->addIdentifierQuotes( $vars[$m[4]] );
4176 } elseif ( isset( $m[5] ) && $m[5] !== '' && array_key_exists( $m[5], $vars ) ) {
4177 return $vars[$m[5]];
4178 } else {
4179 return $m[0];
4182 $ins
4187 * Get schema variables. If none have been set via setSchemaVars(), then
4188 * use some defaults from the current object.
4190 * @return array
4192 protected function getSchemaVars() {
4193 if ( $this->mSchemaVars ) {
4194 return $this->mSchemaVars;
4195 } else {
4196 return $this->getDefaultSchemaVars();
4201 * Get schema variables to use if none have been set via setSchemaVars().
4203 * Override this in derived classes to provide variables for tables.sql
4204 * and SQL patch files.
4206 * @return array
4208 protected function getDefaultSchemaVars() {
4209 return array();
4213 * Check to see if a named lock is available. This is non-blocking.
4215 * @param string $lockName Name of lock to poll
4216 * @param string $method Name of method calling us
4217 * @return bool
4218 * @since 1.20
4220 public function lockIsFree( $lockName, $method ) {
4221 return true;
4225 * Acquire a named lock
4227 * Abstracted from Filestore::lock() so child classes can implement for
4228 * their own needs.
4230 * @param string $lockName Name of lock to aquire
4231 * @param string $method Name of method calling us
4232 * @param int $timeout
4233 * @return bool
4235 public function lock( $lockName, $method, $timeout = 5 ) {
4236 return true;
4240 * Release a lock.
4242 * @param string $lockName Name of lock to release
4243 * @param string $method Name of method calling us
4245 * @return int Returns 1 if the lock was released, 0 if the lock was not established
4246 * by this thread (in which case the lock is not released), and NULL if the named
4247 * lock did not exist
4249 public function unlock( $lockName, $method ) {
4250 return true;
4254 * Lock specific tables
4256 * @param array $read Array of tables to lock for read access
4257 * @param array $write Array of tables to lock for write access
4258 * @param string $method Name of caller
4259 * @param bool $lowPriority Whether to indicate writes to be LOW PRIORITY
4260 * @return bool
4262 public function lockTables( $read, $write, $method, $lowPriority = true ) {
4263 return true;
4267 * Unlock specific tables
4269 * @param string $method The caller
4270 * @return bool
4272 public function unlockTables( $method ) {
4273 return true;
4277 * Delete a table
4278 * @param string $tableName
4279 * @param string $fName
4280 * @return bool|ResultWrapper
4281 * @since 1.18
4283 public function dropTable( $tableName, $fName = __METHOD__ ) {
4284 if ( !$this->tableExists( $tableName, $fName ) ) {
4285 return false;
4287 $sql = "DROP TABLE " . $this->tableName( $tableName );
4288 if ( $this->cascadingDeletes() ) {
4289 $sql .= " CASCADE";
4292 return $this->query( $sql, $fName );
4296 * Get search engine class. All subclasses of this need to implement this
4297 * if they wish to use searching.
4299 * @return string
4301 public function getSearchEngine() {
4302 return 'SearchEngineDummy';
4306 * Find out when 'infinity' is. Most DBMSes support this. This is a special
4307 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
4308 * because "i" sorts after all numbers.
4310 * @return string
4312 public function getInfinity() {
4313 return 'infinity';
4317 * Encode an expiry time into the DBMS dependent format
4319 * @param string $expiry Timestamp for expiry, or the 'infinity' string
4320 * @return string
4322 public function encodeExpiry( $expiry ) {
4323 return ( $expiry == '' || $expiry == 'infinity' || $expiry == $this->getInfinity() )
4324 ? $this->getInfinity()
4325 : $this->timestamp( $expiry );
4329 * Decode an expiry time into a DBMS independent format
4331 * @param string $expiry DB timestamp field value for expiry
4332 * @param int $format TS_* constant, defaults to TS_MW
4333 * @return string
4335 public function decodeExpiry( $expiry, $format = TS_MW ) {
4336 return ( $expiry == '' || $expiry == $this->getInfinity() )
4337 ? 'infinity'
4338 : wfTimestamp( $format, $expiry );
4342 * Allow or deny "big selects" for this session only. This is done by setting
4343 * the sql_big_selects session variable.
4345 * This is a MySQL-specific feature.
4347 * @param bool|string $value True for allow, false for deny, or "default" to
4348 * restore the initial value
4350 public function setBigSelects( $value = true ) {
4351 // no-op
4355 * @since 1.19
4356 * @return string
4358 public function __toString() {
4359 return (string)$this->mConn;
4363 * Run a few simple sanity checks
4365 public function __destruct() {
4366 if ( $this->mTrxLevel && $this->mTrxDoneWrites ) {
4367 trigger_error( "Uncommitted DB writes (transaction from {$this->mTrxFname})." );
4369 if ( count( $this->mTrxIdleCallbacks ) || count( $this->mTrxPreCommitCallbacks ) ) {
4370 $callers = array();
4371 foreach ( $this->mTrxIdleCallbacks as $callbackInfo ) {
4372 $callers[] = $callbackInfo[1];
4374 $callers = implode( ', ', $callers );
4375 trigger_error( "DB transaction callbacks still pending (from $callers)." );