3 * @defgroup Database Database
5 * This file deals with database interface functions
6 * and query specifics/optimisations.
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
27 /** Number of times to re-try an operation in case of deadlock */
28 define( 'DEADLOCK_TRIES', 4 );
29 /** Minimum time to wait before retry, in microseconds */
30 define( 'DEADLOCK_DELAY_MIN', 500000 );
31 /** Maximum time to wait before retry */
32 define( 'DEADLOCK_DELAY_MAX', 1500000 );
35 * Base interface for all DBMS-specific code. At a bare minimum, all of the
36 * following must be implemented to support MediaWiki
41 interface DatabaseType
{
43 * Get the type of the DBMS, as it appears in $wgDBtype.
50 * Open a connection to the database. Usually aborts on failure
52 * @param $server String: database server host
53 * @param $user String: database user name
54 * @param $password String: database user password
55 * @param $dbName String: database name
57 * @throws DBConnectionError
59 function open( $server, $user, $password, $dbName );
62 * Fetch the next row from the given result object, in object form.
63 * Fields can be retrieved with $row->fieldname, with fields acting like
66 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
68 * @throws DBUnexpectedError Thrown if the database returns an error
70 function fetchObject( $res );
73 * Fetch the next row from the given result object, in associative array
74 * form. Fields are retrieved with $row['fieldname'].
76 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
78 * @throws DBUnexpectedError Thrown if the database returns an error
80 function fetchRow( $res );
83 * Get the number of rows in a result object
85 * @param $res Mixed: A SQL result
88 function numRows( $res );
91 * Get the number of fields in a result object
92 * @see http://www.php.net/mysql_num_fields
94 * @param $res Mixed: A SQL result
97 function numFields( $res );
100 * Get a field name in a result object
101 * @see http://www.php.net/mysql_field_name
103 * @param $res Mixed: A SQL result
107 function fieldName( $res, $n );
110 * Get the inserted value of an auto-increment row
112 * The value inserted should be fetched from nextSequenceValue()
115 * $id = $dbw->nextSequenceValue('page_page_id_seq');
116 * $dbw->insert('page',array('page_id' => $id));
117 * $id = $dbw->insertId();
124 * Change the position of the cursor in a result object
125 * @see http://www.php.net/mysql_data_seek
127 * @param $res Mixed: A SQL result
128 * @param $row Mixed: Either MySQL row or ResultWrapper
130 function dataSeek( $res, $row );
133 * Get the last error number
134 * @see http://www.php.net/mysql_errno
138 function lastErrno();
141 * Get a description of the last error
142 * @see http://www.php.net/mysql_error
146 function lastError();
149 * mysql_fetch_field() wrapper
150 * Returns false if the field doesn't exist
152 * @param $table string: table name
153 * @param $field string: field name
157 function fieldInfo( $table, $field );
160 * Get information about an index into an object
161 * @param $table string: Table name
162 * @param $index string: Index name
163 * @param $fname string: Calling function name
164 * @return Mixed: Database-specific index description class or false if the index does not exist
166 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
169 * Get the number of rows affected by the last write query
170 * @see http://www.php.net/mysql_affected_rows
174 function affectedRows();
177 * Wrapper for addslashes()
179 * @param $s string: to be slashed.
180 * @return string: slashed string.
182 function strencode( $s );
185 * Returns a wikitext link to the DB's website, e.g.,
186 * return "[http://www.mysql.com/ MySQL]";
187 * Should at least contain plain text, if for some reason
188 * your database has no website.
190 * @return string: wikitext of a link to the server software's web site
192 static function getSoftwareLink();
195 * A string describing the current software version, like from
196 * mysql_get_server_info().
198 * @return string: Version information from the database server.
200 function getServerVersion();
203 * A string describing the current software version, and possibly
204 * other details in a user-friendly way. Will be listed on Special:Version, etc.
205 * Use getServerVersion() to get machine-friendly information.
207 * @return string: Version information from the database server
209 function getServerInfo();
213 * Database abstraction object
216 abstract class DatabaseBase
implements DatabaseType
{
218 # ------------------------------------------------------------------------------
220 # ------------------------------------------------------------------------------
222 protected $mLastQuery = '';
223 protected $mDoneWrites = false;
224 protected $mPHPError = false;
226 protected $mServer, $mUser, $mPassword, $mDBname;
228 protected $mConn = null;
229 protected $mOpened = false;
233 * @var array of callable
235 protected $trxIdleCallbacks = array();
237 protected $mTablePrefix;
239 protected $mTrxLevel = 0;
240 protected $mErrorCount = 0;
241 protected $mLBInfo = array();
242 protected $mFakeSlaveLag = null, $mFakeMaster = false;
243 protected $mDefaultBigSelects = null;
244 protected $mSchemaVars = false;
246 protected $preparedArgs;
248 protected $htmlErrors;
250 protected $delimiter = ';';
253 * Remembers the function name given for starting the most recent transaction via begin().
254 * Used to provide additional context for error reporting.
257 * @see DatabaseBase::mTrxLevel
259 private $mTrxFname = null;
262 * Record if possible write queries were done in the last transaction started
265 * @see DatabaseBase::mTrxLevel
267 private $mTrxDoneWrites = false;
269 # ------------------------------------------------------------------------------
271 # ------------------------------------------------------------------------------
272 # These optionally set a variable and return the previous state
275 * A string describing the current software version, and possibly
276 * other details in a user-friendly way. Will be listed on Special:Version, etc.
277 * Use getServerVersion() to get machine-friendly information.
279 * @return string: Version information from the database server
281 public function getServerInfo() {
282 return $this->getServerVersion();
286 * Boolean, controls output of large amounts of debug information.
287 * @param $debug bool|null
288 * - true to enable debugging
289 * - false to disable debugging
290 * - omitted or null to do nothing
292 * @return bool|null previous value of the flag
294 public function debug( $debug = null ) {
295 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
299 * Turns buffering of SQL result sets on (true) or off (false). Default is
302 * Unbuffered queries are very troublesome in MySQL:
304 * - If another query is executed while the first query is being read
305 * out, the first query is killed. This means you can't call normal
306 * MediaWiki functions while you are reading an unbuffered query result
307 * from a normal wfGetDB() connection.
309 * - Unbuffered queries cause the MySQL server to use large amounts of
310 * memory and to hold broad locks which block other queries.
312 * If you want to limit client-side memory, it's almost always better to
313 * split up queries into batches using a LIMIT clause than to switch off
316 * @param $buffer null|bool
318 * @return null|bool The previous value of the flag
320 public function bufferResults( $buffer = null ) {
321 if ( is_null( $buffer ) ) {
322 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
324 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
329 * Turns on (false) or off (true) the automatic generation and sending
330 * of a "we're sorry, but there has been a database error" page on
331 * database errors. Default is on (false). When turned off, the
332 * code should use lastErrno() and lastError() to handle the
333 * situation as appropriate.
335 * @param $ignoreErrors bool|null
337 * @return bool The previous value of the flag.
339 public function ignoreErrors( $ignoreErrors = null ) {
340 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
344 * Gets or sets the current transaction level.
346 * Historically, transactions were allowed to be "nested". This is no
347 * longer supported, so this function really only returns a boolean.
349 * @param $level int An integer (0 or 1), or omitted to leave it unchanged.
350 * @return int The previous value
352 public function trxLevel( $level = null ) {
353 return wfSetVar( $this->mTrxLevel
, $level );
357 * Get/set the number of errors logged. Only useful when errors are ignored
358 * @param $count int The count to set, or omitted to leave it unchanged.
359 * @return int The error count
361 public function errorCount( $count = null ) {
362 return wfSetVar( $this->mErrorCount
, $count );
366 * Get/set the table prefix.
367 * @param $prefix string The table prefix to set, or omitted to leave it unchanged.
368 * @return string The previous table prefix.
370 public function tablePrefix( $prefix = null ) {
371 return wfSetVar( $this->mTablePrefix
, $prefix );
375 * Get properties passed down from the server info array of the load
378 * @param $name string The entry of the info array to get, or null to get the
381 * @return LoadBalancer|null
383 public function getLBInfo( $name = null ) {
384 if ( is_null( $name ) ) {
385 return $this->mLBInfo
;
387 if ( array_key_exists( $name, $this->mLBInfo
) ) {
388 return $this->mLBInfo
[$name];
396 * Set the LB info array, or a member of it. If called with one parameter,
397 * the LB info array is set to that parameter. If it is called with two
398 * parameters, the member with the given name is set to the given value.
403 public function setLBInfo( $name, $value = null ) {
404 if ( is_null( $value ) ) {
405 $this->mLBInfo
= $name;
407 $this->mLBInfo
[$name] = $value;
412 * Set lag time in seconds for a fake slave
416 public function setFakeSlaveLag( $lag ) {
417 $this->mFakeSlaveLag
= $lag;
421 * Make this connection a fake master
423 * @param $enabled bool
425 public function setFakeMaster( $enabled = true ) {
426 $this->mFakeMaster
= $enabled;
430 * Returns true if this database supports (and uses) cascading deletes
434 public function cascadingDeletes() {
439 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
443 public function cleanupTriggers() {
448 * Returns true if this database is strict about what can be put into an IP field.
449 * Specifically, it uses a NULL value instead of an empty string.
453 public function strictIPs() {
458 * Returns true if this database uses timestamps rather than integers
462 public function realTimestamps() {
467 * Returns true if this database does an implicit sort when doing GROUP BY
471 public function implicitGroupby() {
476 * Returns true if this database does an implicit order by when the column has an index
477 * For example: SELECT page_title FROM page LIMIT 1
481 public function implicitOrderby() {
486 * Returns true if this database can do a native search on IP columns
487 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
491 public function searchableIPs() {
496 * Returns true if this database can use functional indexes
500 public function functionalIndexes() {
505 * Return the last query that went through DatabaseBase::query()
508 public function lastQuery() {
509 return $this->mLastQuery
;
513 * Returns true if the connection may have been used for write queries.
514 * Should return true if unsure.
518 public function doneWrites() {
519 return $this->mDoneWrites
;
523 * Is a connection to the database open?
526 public function isOpen() {
527 return $this->mOpened
;
531 * Set a flag for this connection
533 * @param $flag Integer: DBO_* constants from Defines.php:
534 * - DBO_DEBUG: output some debug info (same as debug())
535 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
536 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
537 * - DBO_TRX: automatically start transactions
538 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
539 * and removes it in command line mode
540 * - DBO_PERSISTENT: use persistant database connection
542 public function setFlag( $flag ) {
543 global $wgDebugDBTransactions;
544 $this->mFlags |
= $flag;
545 if ( ( $flag & DBO_TRX
) & $wgDebugDBTransactions ) {
546 wfDebug("Implicit transactions are now disabled.\n");
551 * Clear a flag for this connection
553 * @param $flag: same as setFlag()'s $flag param
555 public function clearFlag( $flag ) {
556 global $wgDebugDBTransactions;
557 $this->mFlags
&= ~
$flag;
558 if ( ( $flag & DBO_TRX
) && $wgDebugDBTransactions ) {
559 wfDebug("Implicit transactions are now disabled.\n");
564 * Returns a boolean whether the flag $flag is set for this connection
566 * @param $flag: same as setFlag()'s $flag param
569 public function getFlag( $flag ) {
570 return !!( $this->mFlags
& $flag );
574 * General read-only accessor
576 * @param $name string
580 public function getProperty( $name ) {
587 public function getWikiID() {
588 if ( $this->mTablePrefix
) {
589 return "{$this->mDBname}-{$this->mTablePrefix}";
591 return $this->mDBname
;
596 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
600 public function getSchemaPath() {
602 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
603 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
605 return "$IP/maintenance/tables.sql";
609 # ------------------------------------------------------------------------------
611 # ------------------------------------------------------------------------------
615 * @param $server String: database server host
616 * @param $user String: database user name
617 * @param $password String: database user password
618 * @param $dbName String: database name
620 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
622 function __construct( $server = false, $user = false, $password = false, $dbName = false,
623 $flags = 0, $tablePrefix = 'get from global'
625 global $wgDBprefix, $wgCommandLineMode, $wgDebugDBTransactions;
627 $this->mFlags
= $flags;
629 if ( $this->mFlags
& DBO_DEFAULT
) {
630 if ( $wgCommandLineMode ) {
631 $this->mFlags
&= ~DBO_TRX
;
632 if ( $wgDebugDBTransactions ) {
633 wfDebug("Implicit transaction open disabled.\n");
636 $this->mFlags |
= DBO_TRX
;
637 if ( $wgDebugDBTransactions ) {
638 wfDebug("Implicit transaction open enabled.\n");
643 /** Get the default table prefix*/
644 if ( $tablePrefix == 'get from global' ) {
645 $this->mTablePrefix
= $wgDBprefix;
647 $this->mTablePrefix
= $tablePrefix;
651 $this->open( $server, $user, $password, $dbName );
656 * Called by serialize. Throw an exception when DB connection is serialized.
657 * This causes problems on some database engines because the connection is
658 * not restored on unserialize.
660 public function __sleep() {
661 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
665 * Given a DB type, construct the name of the appropriate child class of
666 * DatabaseBase. This is designed to replace all of the manual stuff like:
667 * $class = 'Database' . ucfirst( strtolower( $type ) );
668 * as well as validate against the canonical list of DB types we have
670 * This factory function is mostly useful for when you need to connect to a
671 * database other than the MediaWiki default (such as for external auth,
672 * an extension, et cetera). Do not use this to connect to the MediaWiki
673 * database. Example uses in core:
674 * @see LoadBalancer::reallyOpenConnection()
675 * @see ExternalUser_MediaWiki::initFromCond()
676 * @see ForeignDBRepo::getMasterDB()
677 * @see WebInstaller_DBConnect::execute()
681 * @param $dbType String A possible DB type
682 * @param $p Array An array of options to pass to the constructor.
683 * Valid options are: host, user, password, dbname, flags, tablePrefix
684 * @return DatabaseBase subclass or null
686 public final static function factory( $dbType, $p = array() ) {
687 $canonicalDBTypes = array(
688 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
690 $dbType = strtolower( $dbType );
691 $class = 'Database' . ucfirst( $dbType );
693 if( in_array( $dbType, $canonicalDBTypes ) ||
( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) ) {
695 isset( $p['host'] ) ?
$p['host'] : false,
696 isset( $p['user'] ) ?
$p['user'] : false,
697 isset( $p['password'] ) ?
$p['password'] : false,
698 isset( $p['dbname'] ) ?
$p['dbname'] : false,
699 isset( $p['flags'] ) ?
$p['flags'] : 0,
700 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
707 protected function installErrorHandler() {
708 $this->mPHPError
= false;
709 $this->htmlErrors
= ini_set( 'html_errors', '0' );
710 set_error_handler( array( $this, 'connectionErrorHandler' ) );
714 * @return bool|string
716 protected function restoreErrorHandler() {
717 restore_error_handler();
718 if ( $this->htmlErrors
!== false ) {
719 ini_set( 'html_errors', $this->htmlErrors
);
721 if ( $this->mPHPError
) {
722 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
723 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
734 protected function connectionErrorHandler( $errno, $errstr ) {
735 $this->mPHPError
= $errstr;
739 * Closes a database connection.
740 * if it is open : commits any open transactions
742 * @return Bool operation success. true if already closed.
744 public function close() {
745 $this->mOpened
= false;
746 if ( $this->mConn
) {
747 if ( $this->trxLevel() ) {
748 $this->commit( __METHOD__
);
750 $ret = $this->closeConnection();
751 $this->mConn
= false;
759 * Closes underlying database connection
761 * @return bool: Whether connection was closed successfully
763 protected abstract function closeConnection();
766 * @param $error String: fallback error message, used if none is given by DB
768 function reportConnectionError( $error = 'Unknown error' ) {
769 $myError = $this->lastError();
775 throw new DBConnectionError( $this, $error );
779 * The DBMS-dependent part of query()
781 * @param $sql String: SQL query.
782 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
784 protected abstract function doQuery( $sql );
787 * Determine whether a query writes to the DB.
788 * Should return true if unsure.
794 public function isWriteQuery( $sql ) {
795 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
799 * Run an SQL query and return the result. Normally throws a DBQueryError
800 * on failure. If errors are ignored, returns false instead.
802 * In new code, the query wrappers select(), insert(), update(), delete(),
803 * etc. should be used where possible, since they give much better DBMS
804 * independence and automatically quote or validate user input in a variety
805 * of contexts. This function is generally only useful for queries which are
806 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
809 * However, the query wrappers themselves should call this function.
811 * @param $sql String: SQL query
812 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
813 * comment (you can use __METHOD__ or add some extra info)
814 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
815 * maybe best to catch the exception instead?
816 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
817 * for a successful read query, or false on failure if $tempIgnore set
818 * @throws DBQueryError Thrown when the database returns an error of any kind
820 public function query( $sql, $fname = '', $tempIgnore = false ) {
821 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
822 if ( !Profiler
::instance()->isStub() ) {
823 # generalizeSQL will probably cut down the query to reasonable
824 # logging size most of the time. The substr is really just a sanity check.
827 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
828 $totalProf = 'DatabaseBase::query-master';
830 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
831 $totalProf = 'DatabaseBase::query';
834 wfProfileIn( $totalProf );
835 wfProfileIn( $queryProf );
838 $this->mLastQuery
= $sql;
839 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
840 # Set a flag indicating that writes have been done
841 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
842 $this->mDoneWrites
= true;
845 # Add a comment for easy SHOW PROCESSLIST interpretation
847 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
848 $userName = $wgUser->getName();
849 if ( mb_strlen( $userName ) > 15 ) {
850 $userName = mb_substr( $userName, 0, 15 ) . '...';
852 $userName = str_replace( '/', '', $userName );
856 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
858 # If DBO_TRX is set, start a transaction
859 if ( ( $this->mFlags
& DBO_TRX
) && !$this->mTrxLevel
&&
860 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' )
862 # Avoid establishing transactions for SHOW and SET statements too -
863 # that would delay transaction initializations to once connection
864 # is really used by application
865 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
866 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 ) {
867 global $wgDebugDBTransactions;
868 if ( $wgDebugDBTransactions ) {
869 wfDebug("Implicit transaction start.\n");
871 $this->begin( __METHOD__
. " ($fname)" );
875 # Keep track of whether the transaction has write queries pending
876 if ( $this->mTrxLevel
&& !$this->mTrxDoneWrites
&& $this->isWriteQuery( $sql ) ) {
877 $this->mTrxDoneWrites
= true;
880 if ( $this->debug() ) {
884 $sqlx = substr( $commentedSql, 0, 500 );
885 $sqlx = strtr( $sqlx, "\t\n", ' ' );
887 $master = $isMaster ?
'master' : 'slave';
888 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
891 if ( istainted( $sql ) & TC_MYSQL
) {
892 throw new MWException( 'Tainted query found' );
895 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
897 # Do the query and handle errors
898 $ret = $this->doQuery( $commentedSql );
900 MWDebug
::queryTime( $queryId );
902 # Try reconnecting if the connection was lost
903 if ( false === $ret && $this->wasErrorReissuable() ) {
904 # Transaction is gone, like it or not
905 $this->mTrxLevel
= 0;
906 wfDebug( "Connection lost, reconnecting...\n" );
908 if ( $this->ping() ) {
909 wfDebug( "Reconnected\n" );
910 $sqlx = substr( $commentedSql, 0, 500 );
911 $sqlx = strtr( $sqlx, "\t\n", ' ' );
912 global $wgRequestTime;
913 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
914 if ( $elapsed < 300 ) {
915 # Not a database error to lose a transaction after a minute or two
916 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
918 $ret = $this->doQuery( $commentedSql );
920 wfDebug( "Failed\n" );
924 if ( false === $ret ) {
925 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
928 if ( !Profiler
::instance()->isStub() ) {
929 wfProfileOut( $queryProf );
930 wfProfileOut( $totalProf );
933 return $this->resultObject( $ret );
937 * Report a query error. Log the error, and if neither the object ignore
938 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
940 * @param $error String
941 * @param $errno Integer
943 * @param $fname String
944 * @param $tempIgnore Boolean
946 public function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
947 # Ignore errors during error handling to avoid infinite recursion
948 $ignore = $this->ignoreErrors( true );
949 ++
$this->mErrorCount
;
951 if ( $ignore ||
$tempIgnore ) {
952 wfDebug( "SQL ERROR (ignored): $error\n" );
953 $this->ignoreErrors( $ignore );
955 $sql1line = str_replace( "\n", "\\n", $sql );
956 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
957 wfDebug( "SQL ERROR: " . $error . "\n" );
958 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
963 * Intended to be compatible with the PEAR::DB wrapper functions.
964 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
966 * ? = scalar value, quoted as necessary
967 * ! = raw SQL bit (a function for instance)
968 * & = filename; reads the file and inserts as a blob
969 * (we don't use this though...)
972 * @param $func string
976 protected function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
977 /* MySQL doesn't support prepared statements (yet), so just
978 pack up the query for reference. We'll manually replace
980 return array( 'query' => $sql, 'func' => $func );
984 * Free a prepared query, generated by prepare().
987 protected function freePrepared( $prepared ) {
988 /* No-op by default */
992 * Execute a prepared query with the various arguments
993 * @param $prepared String: the prepared sql
994 * @param $args Mixed: Either an array here, or put scalars as varargs
996 * @return ResultWrapper
998 public function execute( $prepared, $args = null ) {
999 if ( !is_array( $args ) ) {
1001 $args = func_get_args();
1002 array_shift( $args );
1005 $sql = $this->fillPrepared( $prepared['query'], $args );
1007 return $this->query( $sql, $prepared['func'] );
1011 * For faking prepared SQL statements on DBs that don't support it directly.
1013 * @param $preparedQuery String: a 'preparable' SQL statement
1014 * @param $args Array of arguments to fill it with
1015 * @return string executable SQL
1017 public function fillPrepared( $preparedQuery, $args ) {
1019 $this->preparedArgs
=& $args;
1021 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1022 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1026 * preg_callback func for fillPrepared()
1027 * The arguments should be in $this->preparedArgs and must not be touched
1028 * while we're doing this.
1030 * @param $matches Array
1033 protected function fillPreparedArg( $matches ) {
1034 switch( $matches[1] ) {
1035 case '\\?': return '?';
1036 case '\\!': return '!';
1037 case '\\&': return '&';
1040 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1042 switch( $matches[1] ) {
1043 case '?': return $this->addQuotes( $arg );
1044 case '!': return $arg;
1046 # return $this->addQuotes( file_get_contents( $arg ) );
1047 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1049 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1054 * Free a result object returned by query() or select(). It's usually not
1055 * necessary to call this, just use unset() or let the variable holding
1056 * the result object go out of scope.
1058 * @param $res Mixed: A SQL result
1060 public function freeResult( $res ) {}
1063 * A SELECT wrapper which returns a single field from a single result row.
1065 * Usually throws a DBQueryError on failure. If errors are explicitly
1066 * ignored, returns false on failure.
1068 * If no result rows are returned from the query, false is returned.
1070 * @param $table string|array Table name. See DatabaseBase::select() for details.
1071 * @param $var string The field name to select. This must be a valid SQL
1072 * fragment: do not use unvalidated user input.
1073 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1074 * @param $fname string The function name of the caller.
1075 * @param $options string|array The query options. See DatabaseBase::select() for details.
1077 * @return bool|mixed The value from the field, or false on failure.
1079 public function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1080 $options = array() )
1082 if ( !is_array( $options ) ) {
1083 $options = array( $options );
1086 $options['LIMIT'] = 1;
1088 $res = $this->select( $table, $var, $cond, $fname, $options );
1090 if ( $res === false ||
!$this->numRows( $res ) ) {
1094 $row = $this->fetchRow( $res );
1096 if ( $row !== false ) {
1097 return reset( $row );
1104 * Returns an optional USE INDEX clause to go after the table, and a
1105 * string to go at the end of the query.
1107 * @param $options Array: associative array of options to be turned into
1108 * an SQL query, valid keys are listed in the function.
1110 * @see DatabaseBase::select()
1112 public function makeSelectOptions( $options ) {
1113 $preLimitTail = $postLimitTail = '';
1116 $noKeyOptions = array();
1118 foreach ( $options as $key => $option ) {
1119 if ( is_numeric( $key ) ) {
1120 $noKeyOptions[$option] = true;
1124 if ( isset( $options['GROUP BY'] ) ) {
1125 $gb = is_array( $options['GROUP BY'] )
1126 ?
implode( ',', $options['GROUP BY'] )
1127 : $options['GROUP BY'];
1128 $preLimitTail .= " GROUP BY {$gb}";
1131 if ( isset( $options['HAVING'] ) ) {
1132 $having = is_array( $options['HAVING'] )
1133 ?
$this->makeList( $options['HAVING'], LIST_AND
)
1134 : $options['HAVING'];
1135 $preLimitTail .= " HAVING {$having}";
1138 if ( isset( $options['ORDER BY'] ) ) {
1139 $ob = is_array( $options['ORDER BY'] )
1140 ?
implode( ',', $options['ORDER BY'] )
1141 : $options['ORDER BY'];
1142 $preLimitTail .= " ORDER BY {$ob}";
1145 // if (isset($options['LIMIT'])) {
1146 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1147 // isset($options['OFFSET']) ? $options['OFFSET']
1151 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1152 $postLimitTail .= ' FOR UPDATE';
1155 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1156 $postLimitTail .= ' LOCK IN SHARE MODE';
1159 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1160 $startOpts .= 'DISTINCT';
1163 # Various MySQL extensions
1164 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1165 $startOpts .= ' /*! STRAIGHT_JOIN */';
1168 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1169 $startOpts .= ' HIGH_PRIORITY';
1172 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1173 $startOpts .= ' SQL_BIG_RESULT';
1176 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1177 $startOpts .= ' SQL_BUFFER_RESULT';
1180 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1181 $startOpts .= ' SQL_SMALL_RESULT';
1184 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1185 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1188 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1189 $startOpts .= ' SQL_CACHE';
1192 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1193 $startOpts .= ' SQL_NO_CACHE';
1196 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1197 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1202 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1206 * Execute a SELECT query constructed using the various parameters provided.
1207 * See below for full details of the parameters.
1209 * @param $table String|Array Table name
1210 * @param $vars String|Array Field names
1211 * @param $conds String|Array Conditions
1212 * @param $fname String Caller function name
1213 * @param $options Array Query options
1214 * @param $join_conds Array Join conditions
1216 * @param $table string|array
1218 * May be either an array of table names, or a single string holding a table
1219 * name. If an array is given, table aliases can be specified, for example:
1221 * array( 'a' => 'user' )
1223 * This includes the user table in the query, with the alias "a" available
1224 * for use in field names (e.g. a.user_name).
1226 * All of the table names given here are automatically run through
1227 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1228 * added, and various other table name mappings to be performed.
1231 * @param $vars string|array
1233 * May be either a field name or an array of field names. The field names
1234 * can be complete fragments of SQL, for direct inclusion into the SELECT
1235 * query. If an array is given, field aliases can be specified, for example:
1237 * array( 'maxrev' => 'MAX(rev_id)' )
1239 * This includes an expression with the alias "maxrev" in the query.
1241 * If an expression is given, care must be taken to ensure that it is
1245 * @param $conds string|array
1247 * May be either a string containing a single condition, or an array of
1248 * conditions. If an array is given, the conditions constructed from each
1249 * element are combined with AND.
1251 * Array elements may take one of two forms:
1253 * - Elements with a numeric key are interpreted as raw SQL fragments.
1254 * - Elements with a string key are interpreted as equality conditions,
1255 * where the key is the field name.
1256 * - If the value of such an array element is a scalar (such as a
1257 * string), it will be treated as data and thus quoted appropriately.
1258 * If it is null, an IS NULL clause will be added.
1259 * - If the value is an array, an IN(...) clause will be constructed,
1260 * such that the field name may match any of the elements in the
1261 * array. The elements of the array will be quoted.
1263 * Note that expressions are often DBMS-dependent in their syntax.
1264 * DBMS-independent wrappers are provided for constructing several types of
1265 * expression commonly used in condition queries. See:
1266 * - DatabaseBase::buildLike()
1267 * - DatabaseBase::conditional()
1270 * @param $options string|array
1272 * Optional: Array of query options. Boolean options are specified by
1273 * including them in the array as a string value with a numeric key, for
1276 * array( 'FOR UPDATE' )
1278 * The supported options are:
1280 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1281 * with LIMIT can theoretically be used for paging through a result set,
1282 * but this is discouraged in MediaWiki for performance reasons.
1284 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1285 * and then the first rows are taken until the limit is reached. LIMIT
1286 * is applied to a result set after OFFSET.
1288 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1289 * changed until the next COMMIT.
1291 * - DISTINCT: Boolean: return only unique result rows.
1293 * - GROUP BY: May be either an SQL fragment string naming a field or
1294 * expression to group by, or an array of such SQL fragments.
1296 * - HAVING: May be either an string containing a HAVING clause or an array of
1297 * conditions building the HAVING clause. If an array is given, the conditions
1298 * constructed from each element are combined with AND.
1300 * - ORDER BY: May be either an SQL fragment giving a field name or
1301 * expression to order by, or an array of such SQL fragments.
1303 * - USE INDEX: This may be either a string giving the index name to use
1304 * for the query, or an array. If it is an associative array, each key
1305 * gives the table name (or alias), each value gives the index name to
1306 * use for that table. All strings are SQL fragments and so should be
1307 * validated by the caller.
1309 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1310 * instead of SELECT.
1312 * And also the following boolean MySQL extensions, see the MySQL manual
1313 * for documentation:
1315 * - LOCK IN SHARE MODE
1319 * - SQL_BUFFER_RESULT
1320 * - SQL_SMALL_RESULT
1321 * - SQL_CALC_FOUND_ROWS
1326 * @param $join_conds string|array
1328 * Optional associative array of table-specific join conditions. In the
1329 * most common case, this is unnecessary, since the join condition can be
1330 * in $conds. However, it is useful for doing a LEFT JOIN.
1332 * The key of the array contains the table name or alias. The value is an
1333 * array with two elements, numbered 0 and 1. The first gives the type of
1334 * join, the second is an SQL fragment giving the join condition for that
1335 * table. For example:
1337 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1339 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1340 * with no rows in it will be returned. If there was a query error, a
1341 * DBQueryError exception will be thrown, except if the "ignore errors"
1342 * option was set, in which case false will be returned.
1344 public function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1345 $options = array(), $join_conds = array() ) {
1346 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1348 return $this->query( $sql, $fname );
1352 * The equivalent of DatabaseBase::select() except that the constructed SQL
1353 * is returned, instead of being immediately executed. This can be useful for
1354 * doing UNION queries, where the SQL text of each query is needed. In general,
1355 * however, callers outside of Database classes should just use select().
1357 * @param $table string|array Table name
1358 * @param $vars string|array Field names
1359 * @param $conds string|array Conditions
1360 * @param $fname string Caller function name
1361 * @param $options string|array Query options
1362 * @param $join_conds string|array Join conditions
1364 * @return string SQL query string.
1365 * @see DatabaseBase::select()
1367 public function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1368 $options = array(), $join_conds = array() )
1370 if ( is_array( $vars ) ) {
1371 $vars = implode( ',', $this->fieldNamesWithAlias( $vars ) );
1374 $options = (array)$options;
1376 if ( is_array( $table ) ) {
1377 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1378 ?
$options['USE INDEX']
1380 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1382 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1384 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1386 } elseif ( $table != '' ) {
1387 if ( $table[0] == ' ' ) {
1388 $from = ' FROM ' . $table;
1390 $from = ' FROM ' . $this->tableName( $table );
1396 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1398 if ( !empty( $conds ) ) {
1399 if ( is_array( $conds ) ) {
1400 $conds = $this->makeList( $conds, LIST_AND
);
1402 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1404 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1407 if ( isset( $options['LIMIT'] ) ) {
1408 $sql = $this->limitResult( $sql, $options['LIMIT'],
1409 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1411 $sql = "$sql $postLimitTail";
1413 if ( isset( $options['EXPLAIN'] ) ) {
1414 $sql = 'EXPLAIN ' . $sql;
1421 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1422 * that a single row object is returned. If the query returns no rows,
1423 * false is returned.
1425 * @param $table string|array Table name
1426 * @param $vars string|array Field names
1427 * @param $conds array Conditions
1428 * @param $fname string Caller function name
1429 * @param $options string|array Query options
1430 * @param $join_conds array|string Join conditions
1432 * @return object|bool
1434 public function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1435 $options = array(), $join_conds = array() )
1437 $options = (array)$options;
1438 $options['LIMIT'] = 1;
1439 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1441 if ( $res === false ) {
1445 if ( !$this->numRows( $res ) ) {
1449 $obj = $this->fetchObject( $res );
1455 * Estimate rows in dataset.
1457 * MySQL allows you to estimate the number of rows that would be returned
1458 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1459 * index cardinality statistics, and is notoriously inaccurate, especially
1460 * when large numbers of rows have recently been added or deleted.
1462 * For DBMSs that don't support fast result size estimation, this function
1463 * will actually perform the SELECT COUNT(*).
1465 * Takes the same arguments as DatabaseBase::select().
1467 * @param $table String: table name
1468 * @param Array|string $vars : unused
1469 * @param Array|string $conds : filters on the table
1470 * @param $fname String: function name for profiling
1471 * @param $options Array: options for select
1472 * @return Integer: row count
1474 public function estimateRowCount( $table, $vars = '*', $conds = '',
1475 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1478 $res = $this->select( $table, array( 'rowcount' => 'COUNT(*)' ), $conds, $fname, $options );
1481 $row = $this->fetchRow( $res );
1482 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1489 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1490 * It's only slightly flawed. Don't use for anything important.
1492 * @param $sql String A SQL Query
1496 static function generalizeSQL( $sql ) {
1497 # This does the same as the regexp below would do, but in such a way
1498 # as to avoid crashing php on some large strings.
1499 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1501 $sql = str_replace ( "\\\\", '', $sql );
1502 $sql = str_replace ( "\\'", '', $sql );
1503 $sql = str_replace ( "\\\"", '', $sql );
1504 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1505 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1507 # All newlines, tabs, etc replaced by single space
1508 $sql = preg_replace ( '/\s+/', ' ', $sql );
1511 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1517 * Determines whether a field exists in a table
1519 * @param $table String: table name
1520 * @param $field String: filed to check on that table
1521 * @param $fname String: calling function name (optional)
1522 * @return Boolean: whether $table has filed $field
1524 public function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1525 $info = $this->fieldInfo( $table, $field );
1531 * Determines whether an index exists
1532 * Usually throws a DBQueryError on failure
1533 * If errors are explicitly ignored, returns NULL on failure
1537 * @param $fname string
1541 public function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1542 $info = $this->indexInfo( $table, $index, $fname );
1543 if ( is_null( $info ) ) {
1546 return $info !== false;
1551 * Query whether a given table exists
1553 * @param $table string
1554 * @param $fname string
1558 public function tableExists( $table, $fname = __METHOD__
) {
1559 $table = $this->tableName( $table );
1560 $old = $this->ignoreErrors( true );
1561 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1562 $this->ignoreErrors( $old );
1568 * mysql_field_type() wrapper
1573 public function fieldType( $res, $index ) {
1574 if ( $res instanceof ResultWrapper
) {
1575 $res = $res->result
;
1578 return mysql_field_type( $res, $index );
1582 * Determines if a given index is unique
1584 * @param $table string
1585 * @param $index string
1589 public function indexUnique( $table, $index ) {
1590 $indexInfo = $this->indexInfo( $table, $index );
1592 if ( !$indexInfo ) {
1596 return !$indexInfo[0]->Non_unique
;
1600 * Helper for DatabaseBase::insert().
1602 * @param $options array
1605 protected function makeInsertOptions( $options ) {
1606 return implode( ' ', $options );
1610 * INSERT wrapper, inserts an array into a table.
1614 * - A single associative array. The array keys are the field names, and
1615 * the values are the values to insert. The values are treated as data
1616 * and will be quoted appropriately. If NULL is inserted, this will be
1617 * converted to a database NULL.
1618 * - An array with numeric keys, holding a list of associative arrays.
1619 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1620 * each subarray must be identical to each other, and in the same order.
1622 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1625 * $options is an array of options, with boolean options encoded as values
1626 * with numeric keys, in the same style as $options in
1627 * DatabaseBase::select(). Supported options are:
1629 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1630 * any rows which cause duplicate key errors are not inserted. It's
1631 * possible to determine how many rows were successfully inserted using
1632 * DatabaseBase::affectedRows().
1634 * @param $table String Table name. This will be passed through
1635 * DatabaseBase::tableName().
1636 * @param $a Array of rows to insert
1637 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1638 * @param $options Array of options
1642 public function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1643 # No rows to insert, easy just return now
1644 if ( !count( $a ) ) {
1648 $table = $this->tableName( $table );
1650 if ( !is_array( $options ) ) {
1651 $options = array( $options );
1654 $options = $this->makeInsertOptions( $options );
1656 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1658 $keys = array_keys( $a[0] );
1661 $keys = array_keys( $a );
1664 $sql = 'INSERT ' . $options .
1665 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1669 foreach ( $a as $row ) {
1675 $sql .= '(' . $this->makeList( $row ) . ')';
1678 $sql .= '(' . $this->makeList( $a ) . ')';
1681 return (bool)$this->query( $sql, $fname );
1685 * Make UPDATE options for the DatabaseBase::update function
1687 * @param $options Array: The options passed to DatabaseBase::update
1690 protected function makeUpdateOptions( $options ) {
1691 if ( !is_array( $options ) ) {
1692 $options = array( $options );
1697 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1698 $opts[] = $this->lowPriorityOption();
1701 if ( in_array( 'IGNORE', $options ) ) {
1705 return implode( ' ', $opts );
1709 * UPDATE wrapper. Takes a condition array and a SET array.
1711 * @param $table String name of the table to UPDATE. This will be passed through
1712 * DatabaseBase::tableName().
1714 * @param $values Array: An array of values to SET. For each array element,
1715 * the key gives the field name, and the value gives the data
1716 * to set that field to. The data will be quoted by
1717 * DatabaseBase::addQuotes().
1719 * @param $conds Array: An array of conditions (WHERE). See
1720 * DatabaseBase::select() for the details of the format of
1721 * condition arrays. Use '*' to update all rows.
1723 * @param $fname String: The function name of the caller (from __METHOD__),
1724 * for logging and profiling.
1726 * @param $options Array: An array of UPDATE options, can be:
1727 * - IGNORE: Ignore unique key conflicts
1728 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1731 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1732 $table = $this->tableName( $table );
1733 $opts = $this->makeUpdateOptions( $options );
1734 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1736 if ( $conds !== array() && $conds !== '*' ) {
1737 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1740 return $this->query( $sql, $fname );
1744 * Makes an encoded list of strings from an array
1745 * @param $a Array containing the data
1746 * @param $mode int Constant
1747 * - LIST_COMMA: comma separated, no field names
1748 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1749 * the documentation for $conds in DatabaseBase::select().
1750 * - LIST_OR: ORed WHERE clause (without the WHERE)
1751 * - LIST_SET: comma separated with field names, like a SET clause
1752 * - LIST_NAMES: comma separated field names
1756 public function makeList( $a, $mode = LIST_COMMA
) {
1757 if ( !is_array( $a ) ) {
1758 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1764 foreach ( $a as $field => $value ) {
1766 if ( $mode == LIST_AND
) {
1768 } elseif ( $mode == LIST_OR
) {
1777 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1778 $list .= "($value)";
1779 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1781 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1782 if ( count( $value ) == 0 ) {
1783 throw new MWException( __METHOD__
. ': empty input' );
1784 } elseif ( count( $value ) == 1 ) {
1785 // Special-case single values, as IN isn't terribly efficient
1786 // Don't necessarily assume the single key is 0; we don't
1787 // enforce linear numeric ordering on other arrays here.
1788 $value = array_values( $value );
1789 $list .= $field . " = " . $this->addQuotes( $value[0] );
1791 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1793 } elseif ( $value === null ) {
1794 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1795 $list .= "$field IS ";
1796 } elseif ( $mode == LIST_SET
) {
1797 $list .= "$field = ";
1801 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1802 $list .= "$field = ";
1804 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1812 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1813 * The keys on each level may be either integers or strings.
1815 * @param $data Array: organized as 2-d
1816 * array(baseKeyVal => array(subKeyVal => [ignored], ...), ...)
1817 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1818 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1819 * @return Mixed: string SQL fragment, or false if no items in array.
1821 public function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1824 foreach ( $data as $base => $sub ) {
1825 if ( count( $sub ) ) {
1826 $conds[] = $this->makeList(
1827 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1833 return $this->makeList( $conds, LIST_OR
);
1835 // Nothing to search for...
1841 * Return aggregated value alias
1844 * @param $valuename string
1848 public function aggregateValue( $valuedata, $valuename = 'value' ) {
1856 public function bitNot( $field ) {
1862 * @param $fieldRight
1865 public function bitAnd( $fieldLeft, $fieldRight ) {
1866 return "($fieldLeft & $fieldRight)";
1871 * @param $fieldRight
1874 public function bitOr( $fieldLeft, $fieldRight ) {
1875 return "($fieldLeft | $fieldRight)";
1879 * Build a concatenation list to feed into a SQL query
1880 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
1883 public function buildConcat( $stringList ) {
1884 return 'CONCAT(' . implode( ',', $stringList ) . ')';
1888 * Change the current database
1890 * @todo Explain what exactly will fail if this is not overridden.
1894 * @return bool Success or failure
1896 public function selectDB( $db ) {
1897 # Stub. Shouldn't cause serious problems if it's not overridden, but
1898 # if your database engine supports a concept similar to MySQL's
1899 # databases you may as well.
1900 $this->mDBname
= $db;
1905 * Get the current DB name
1907 public function getDBname() {
1908 return $this->mDBname
;
1912 * Get the server hostname or IP address
1914 public function getServer() {
1915 return $this->mServer
;
1919 * Format a table name ready for use in constructing an SQL query
1921 * This does two important things: it quotes the table names to clean them up,
1922 * and it adds a table prefix if only given a table name with no quotes.
1924 * All functions of this object which require a table name call this function
1925 * themselves. Pass the canonical name to such functions. This is only needed
1926 * when calling query() directly.
1928 * @param $name String: database table name
1929 * @param $format String One of:
1930 * quoted - Automatically pass the table name through addIdentifierQuotes()
1931 * so that it can be used in a query.
1932 * raw - Do not add identifier quotes to the table name
1933 * @return String: full database name
1935 public function tableName( $name, $format = 'quoted' ) {
1936 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1937 # Skip the entire process when we have a string quoted on both ends.
1938 # Note that we check the end so that we will still quote any use of
1939 # use of `database`.table. But won't break things if someone wants
1940 # to query a database table with a dot in the name.
1941 if ( $this->isQuotedIdentifier( $name ) ) {
1945 # Lets test for any bits of text that should never show up in a table
1946 # name. Basically anything like JOIN or ON which are actually part of
1947 # SQL queries, but may end up inside of the table value to combine
1948 # sql. Such as how the API is doing.
1949 # Note that we use a whitespace test rather than a \b test to avoid
1950 # any remote case where a word like on may be inside of a table name
1951 # surrounded by symbols which may be considered word breaks.
1952 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1956 # Split database and table into proper variables.
1957 # We reverse the explode so that database.table and table both output
1958 # the correct table.
1959 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1960 if ( isset( $dbDetails[1] ) ) {
1961 list( $table, $database ) = $dbDetails;
1963 list( $table ) = $dbDetails;
1965 $prefix = $this->mTablePrefix
; # Default prefix
1967 # A database name has been specified in input. We don't want any
1969 if ( isset( $database ) ) {
1973 # Note that we use the long format because php will complain in in_array if
1974 # the input is not an array, and will complain in is_array if it is not set.
1975 if ( !isset( $database ) # Don't use shared database if pre selected.
1976 && isset( $wgSharedDB ) # We have a shared database
1977 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1978 && isset( $wgSharedTables )
1979 && is_array( $wgSharedTables )
1980 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1981 $database = $wgSharedDB;
1982 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1985 # Quote the $database and $table and apply the prefix if not quoted.
1986 if ( isset( $database ) ) {
1987 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $database ) ) {
1988 $database = $this->addIdentifierQuotes( $database );
1992 $table = "{$prefix}{$table}";
1993 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1994 $table = $this->addIdentifierQuotes( "{$table}" );
1997 # Merge our database and table into our final table name.
1998 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
2004 * Fetch a number of table names into an array
2005 * This is handy when you need to construct SQL for joins
2008 * extract($dbr->tableNames('user','watchlist'));
2009 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2010 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2014 public function tableNames() {
2015 $inArray = func_get_args();
2018 foreach ( $inArray as $name ) {
2019 $retVal[$name] = $this->tableName( $name );
2026 * Fetch a number of table names into an zero-indexed numerical array
2027 * This is handy when you need to construct SQL for joins
2030 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2031 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2032 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2036 public function tableNamesN() {
2037 $inArray = func_get_args();
2040 foreach ( $inArray as $name ) {
2041 $retVal[] = $this->tableName( $name );
2048 * Get an aliased table name
2049 * e.g. tableName AS newTableName
2051 * @param $name string Table name, see tableName()
2052 * @param $alias string|bool Alias (optional)
2053 * @return string SQL name for aliased table. Will not alias a table to its own name
2055 public function tableNameWithAlias( $name, $alias = false ) {
2056 if ( !$alias ||
$alias == $name ) {
2057 return $this->tableName( $name );
2059 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2064 * Gets an array of aliased table names
2066 * @param $tables array( [alias] => table )
2067 * @return array of strings, see tableNameWithAlias()
2069 public function tableNamesWithAlias( $tables ) {
2071 foreach ( $tables as $alias => $table ) {
2072 if ( is_numeric( $alias ) ) {
2075 $retval[] = $this->tableNameWithAlias( $table, $alias );
2081 * Get an aliased field name
2082 * e.g. fieldName AS newFieldName
2084 * @param $name string Field name
2085 * @param $alias string|bool Alias (optional)
2086 * @return string SQL name for aliased field. Will not alias a field to its own name
2088 public function fieldNameWithAlias( $name, $alias = false ) {
2089 if ( !$alias ||
(string)$alias === (string)$name ) {
2092 return $name . ' AS ' . $alias; //PostgreSQL needs AS
2097 * Gets an array of aliased field names
2099 * @param $fields array( [alias] => field )
2100 * @return array of strings, see fieldNameWithAlias()
2102 public function fieldNamesWithAlias( $fields ) {
2104 foreach ( $fields as $alias => $field ) {
2105 if ( is_numeric( $alias ) ) {
2108 $retval[] = $this->fieldNameWithAlias( $field, $alias );
2114 * Get the aliased table name clause for a FROM clause
2115 * which might have a JOIN and/or USE INDEX clause
2117 * @param $tables array ( [alias] => table )
2118 * @param $use_index array Same as for select()
2119 * @param $join_conds array Same as for select()
2122 protected function tableNamesWithUseIndexOrJOIN(
2123 $tables, $use_index = array(), $join_conds = array()
2127 $use_index = (array)$use_index;
2128 $join_conds = (array)$join_conds;
2130 foreach ( $tables as $alias => $table ) {
2131 if ( !is_string( $alias ) ) {
2132 // No alias? Set it equal to the table name
2135 // Is there a JOIN clause for this table?
2136 if ( isset( $join_conds[$alias] ) ) {
2137 list( $joinType, $conds ) = $join_conds[$alias];
2138 $tableClause = $joinType;
2139 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2140 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2141 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2143 $tableClause .= ' ' . $use;
2146 $on = $this->makeList( (array)$conds, LIST_AND
);
2148 $tableClause .= ' ON (' . $on . ')';
2151 $retJOIN[] = $tableClause;
2152 // Is there an INDEX clause for this table?
2153 } elseif ( isset( $use_index[$alias] ) ) {
2154 $tableClause = $this->tableNameWithAlias( $table, $alias );
2155 $tableClause .= ' ' . $this->useIndexClause(
2156 implode( ',', (array)$use_index[$alias] ) );
2158 $ret[] = $tableClause;
2160 $tableClause = $this->tableNameWithAlias( $table, $alias );
2162 $ret[] = $tableClause;
2166 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2167 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2168 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2170 // Compile our final table clause
2171 return implode( ' ', array( $straightJoins, $otherJoins ) );
2175 * Get the name of an index in a given table
2181 protected function indexName( $index ) {
2182 // Backwards-compatibility hack
2184 'ar_usertext_timestamp' => 'usertext_timestamp',
2185 'un_user_id' => 'user_id',
2186 'un_user_ip' => 'user_ip',
2189 if ( isset( $renamed[$index] ) ) {
2190 return $renamed[$index];
2197 * If it's a string, adds quotes and backslashes
2198 * Otherwise returns as-is
2204 public function addQuotes( $s ) {
2205 if ( $s === null ) {
2208 # This will also quote numeric values. This should be harmless,
2209 # and protects against weird problems that occur when they really
2210 # _are_ strings such as article titles and string->number->string
2211 # conversion is not 1:1.
2212 return "'" . $this->strencode( $s ) . "'";
2217 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2218 * MySQL uses `backticks` while basically everything else uses double quotes.
2219 * Since MySQL is the odd one out here the double quotes are our generic
2220 * and we implement backticks in DatabaseMysql.
2226 public function addIdentifierQuotes( $s ) {
2227 return '"' . str_replace( '"', '""', $s ) . '"';
2231 * Returns if the given identifier looks quoted or not according to
2232 * the database convention for quoting identifiers .
2234 * @param $name string
2238 public function isQuotedIdentifier( $name ) {
2239 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2246 protected function escapeLikeInternal( $s ) {
2247 $s = str_replace( '\\', '\\\\', $s );
2248 $s = $this->strencode( $s );
2249 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2255 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2256 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2257 * Alternatively, the function could be provided with an array of aforementioned parameters.
2259 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2260 * for subpages of 'My page title'.
2261 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2264 * @return String: fully built LIKE statement
2266 public function buildLike() {
2267 $params = func_get_args();
2269 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2270 $params = $params[0];
2275 foreach ( $params as $value ) {
2276 if ( $value instanceof LikeMatch
) {
2277 $s .= $value->toString();
2279 $s .= $this->escapeLikeInternal( $value );
2283 return " LIKE '" . $s . "' ";
2287 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2291 public function anyChar() {
2292 return new LikeMatch( '_' );
2296 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2300 public function anyString() {
2301 return new LikeMatch( '%' );
2305 * Returns an appropriately quoted sequence value for inserting a new row.
2306 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2307 * subclass will return an integer, and save the value for insertId()
2309 * Any implementation of this function should *not* involve reusing
2310 * sequence numbers created for rolled-back transactions.
2311 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2312 * @param $seqName string
2315 public function nextSequenceValue( $seqName ) {
2320 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2321 * is only needed because a) MySQL must be as efficient as possible due to
2322 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2323 * which index to pick. Anyway, other databases might have different
2324 * indexes on a given table. So don't bother overriding this unless you're
2329 public function useIndexClause( $index ) {
2334 * REPLACE query wrapper.
2336 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2337 * except that when there is a duplicate key error, the old row is deleted
2338 * and the new row is inserted in its place.
2340 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2341 * perform the delete, we need to know what the unique indexes are so that
2342 * we know how to find the conflicting rows.
2344 * It may be more efficient to leave off unique indexes which are unlikely
2345 * to collide. However if you do this, you run the risk of encountering
2346 * errors which wouldn't have occurred in MySQL.
2348 * @param $table String: The table to replace the row(s) in.
2349 * @param $rows array Can be either a single row to insert, or multiple rows,
2350 * in the same format as for DatabaseBase::insert()
2351 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2352 * a field name or an array of field names
2353 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2355 public function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2356 $quotedTable = $this->tableName( $table );
2358 if ( count( $rows ) == 0 ) {
2363 if ( !is_array( reset( $rows ) ) ) {
2364 $rows = array( $rows );
2367 foreach( $rows as $row ) {
2368 # Delete rows which collide
2369 if ( $uniqueIndexes ) {
2370 $sql = "DELETE FROM $quotedTable WHERE ";
2372 foreach ( $uniqueIndexes as $index ) {
2379 if ( is_array( $index ) ) {
2381 foreach ( $index as $col ) {
2387 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2390 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2394 $this->query( $sql, $fname );
2397 # Now insert the row
2398 $this->insert( $table, $row );
2403 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2406 * @param $table string Table name
2407 * @param $rows array Rows to insert
2408 * @param $fname string Caller function name
2410 * @return ResultWrapper
2412 protected function nativeReplace( $table, $rows, $fname ) {
2413 $table = $this->tableName( $table );
2416 if ( !is_array( reset( $rows ) ) ) {
2417 $rows = array( $rows );
2420 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2423 foreach ( $rows as $row ) {
2430 $sql .= '(' . $this->makeList( $row ) . ')';
2433 return $this->query( $sql, $fname );
2437 * DELETE where the condition is a join.
2439 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2440 * we use sub-selects
2442 * For safety, an empty $conds will not delete everything. If you want to
2443 * delete all rows where the join condition matches, set $conds='*'.
2445 * DO NOT put the join condition in $conds.
2447 * @param $delTable String: The table to delete from.
2448 * @param $joinTable String: The other table.
2449 * @param $delVar String: The variable to join on, in the first table.
2450 * @param $joinVar String: The variable to join on, in the second table.
2451 * @param $conds Array: Condition array of field names mapped to variables,
2452 * ANDed together in the WHERE clause
2453 * @param $fname String: Calling function name (use __METHOD__) for
2456 public function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2457 $fname = 'DatabaseBase::deleteJoin' )
2460 throw new DBUnexpectedError( $this,
2461 'DatabaseBase::deleteJoin() called with empty $conds' );
2464 $delTable = $this->tableName( $delTable );
2465 $joinTable = $this->tableName( $joinTable );
2466 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2467 if ( $conds != '*' ) {
2468 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2472 $this->query( $sql, $fname );
2476 * Returns the size of a text field, or -1 for "unlimited"
2478 * @param $table string
2479 * @param $field string
2483 public function textFieldSize( $table, $field ) {
2484 $table = $this->tableName( $table );
2485 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2486 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2487 $row = $this->fetchObject( $res );
2491 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2501 * A string to insert into queries to show that they're low-priority, like
2502 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2503 * string and nothing bad should happen.
2505 * @return string Returns the text of the low priority option if it is
2506 * supported, or a blank string otherwise
2508 public function lowPriorityOption() {
2513 * DELETE query wrapper.
2515 * @param $table Array Table name
2516 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2517 * the format. Use $conds == "*" to delete all rows
2518 * @param $fname String name of the calling function
2522 public function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2524 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2527 $table = $this->tableName( $table );
2528 $sql = "DELETE FROM $table";
2530 if ( $conds != '*' ) {
2531 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2534 return $this->query( $sql, $fname );
2538 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2539 * into another table.
2541 * @param $destTable string The table name to insert into
2542 * @param $srcTable string|array May be either a table name, or an array of table names
2543 * to include in a join.
2545 * @param $varMap array must be an associative array of the form
2546 * array( 'dest1' => 'source1', ...). Source items may be literals
2547 * rather than field names, but strings should be quoted with
2548 * DatabaseBase::addQuotes()
2550 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2551 * the details of the format of condition arrays. May be "*" to copy the
2554 * @param $fname string The function name of the caller, from __METHOD__
2556 * @param $insertOptions array Options for the INSERT part of the query, see
2557 * DatabaseBase::insert() for details.
2558 * @param $selectOptions array Options for the SELECT part of the query, see
2559 * DatabaseBase::select() for details.
2561 * @return ResultWrapper
2563 public function insertSelect( $destTable, $srcTable, $varMap, $conds,
2564 $fname = 'DatabaseBase::insertSelect',
2565 $insertOptions = array(), $selectOptions = array() )
2567 $destTable = $this->tableName( $destTable );
2569 if ( is_array( $insertOptions ) ) {
2570 $insertOptions = implode( ' ', $insertOptions );
2573 if ( !is_array( $selectOptions ) ) {
2574 $selectOptions = array( $selectOptions );
2577 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2579 if ( is_array( $srcTable ) ) {
2580 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2582 $srcTable = $this->tableName( $srcTable );
2585 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2586 " SELECT $startOpts " . implode( ',', $varMap ) .
2587 " FROM $srcTable $useIndex ";
2589 if ( $conds != '*' ) {
2590 if ( is_array( $conds ) ) {
2591 $conds = $this->makeList( $conds, LIST_AND
);
2593 $sql .= " WHERE $conds";
2596 $sql .= " $tailOpts";
2598 return $this->query( $sql, $fname );
2602 * Construct a LIMIT query with optional offset. This is used for query
2603 * pages. The SQL should be adjusted so that only the first $limit rows
2604 * are returned. If $offset is provided as well, then the first $offset
2605 * rows should be discarded, and the next $limit rows should be returned.
2606 * If the result of the query is not ordered, then the rows to be returned
2607 * are theoretically arbitrary.
2609 * $sql is expected to be a SELECT, if that makes a difference.
2611 * The version provided by default works in MySQL and SQLite. It will very
2612 * likely need to be overridden for most other DBMSes.
2614 * @param $sql String SQL query we will append the limit too
2615 * @param $limit Integer the SQL limit
2616 * @param $offset Integer|bool the SQL offset (default false)
2620 public function limitResult( $sql, $limit, $offset = false ) {
2621 if ( !is_numeric( $limit ) ) {
2622 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2624 return "$sql LIMIT "
2625 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2630 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2631 * within the UNION construct.
2634 public function unionSupportsOrderAndLimit() {
2635 return true; // True for almost every DB supported
2639 * Construct a UNION query
2640 * This is used for providing overload point for other DB abstractions
2641 * not compatible with the MySQL syntax.
2642 * @param $sqls Array: SQL statements to combine
2643 * @param $all Boolean: use UNION ALL
2644 * @return String: SQL fragment
2646 public function unionQueries( $sqls, $all ) {
2647 $glue = $all ?
') UNION ALL (' : ') UNION (';
2648 return '(' . implode( $glue, $sqls ) . ')';
2652 * Returns an SQL expression for a simple conditional. This doesn't need
2653 * to be overridden unless CASE isn't supported in your DBMS.
2655 * @param $cond string|array SQL expression which will result in a boolean value
2656 * @param $trueVal String: SQL expression to return if true
2657 * @param $falseVal String: SQL expression to return if false
2658 * @return String: SQL fragment
2660 public function conditional( $cond, $trueVal, $falseVal ) {
2661 if ( is_array( $cond ) ) {
2662 $cond = $this->makeList( $cond, LIST_AND
);
2664 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2668 * Returns a comand for str_replace function in SQL query.
2669 * Uses REPLACE() in MySQL
2671 * @param $orig String: column to modify
2672 * @param $old String: column to seek
2673 * @param $new String: column to replace with
2677 public function strreplace( $orig, $old, $new ) {
2678 return "REPLACE({$orig}, {$old}, {$new})";
2682 * Determines how long the server has been up
2687 public function getServerUptime() {
2692 * Determines if the last failure was due to a deadlock
2697 public function wasDeadlock() {
2702 * Determines if the last failure was due to a lock timeout
2707 public function wasLockTimeout() {
2712 * Determines if the last query error was something that should be dealt
2713 * with by pinging the connection and reissuing the query.
2718 public function wasErrorReissuable() {
2723 * Determines if the last failure was due to the database being read-only.
2728 public function wasReadOnlyError() {
2733 * Perform a deadlock-prone transaction.
2735 * This function invokes a callback function to perform a set of write
2736 * queries. If a deadlock occurs during the processing, the transaction
2737 * will be rolled back and the callback function will be called again.
2740 * $dbw->deadlockLoop( callback, ... );
2742 * Extra arguments are passed through to the specified callback function.
2744 * Returns whatever the callback function returned on its successful,
2745 * iteration, or false on error, for example if the retry limit was
2750 public function deadlockLoop() {
2751 $this->begin( __METHOD__
);
2752 $args = func_get_args();
2753 $function = array_shift( $args );
2754 $oldIgnore = $this->ignoreErrors( true );
2755 $tries = DEADLOCK_TRIES
;
2757 if ( is_array( $function ) ) {
2758 $fname = $function[0];
2764 $retVal = call_user_func_array( $function, $args );
2765 $error = $this->lastError();
2766 $errno = $this->lastErrno();
2767 $sql = $this->lastQuery();
2770 if ( $this->wasDeadlock() ) {
2772 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2774 $this->reportQueryError( $error, $errno, $sql, $fname );
2777 } while ( $this->wasDeadlock() && --$tries > 0 );
2779 $this->ignoreErrors( $oldIgnore );
2781 if ( $tries <= 0 ) {
2782 $this->rollback( __METHOD__
);
2783 $this->reportQueryError( $error, $errno, $sql, $fname );
2786 $this->commit( __METHOD__
);
2792 * Wait for the slave to catch up to a given master position.
2794 * @param $pos DBMasterPos object
2795 * @param $timeout Integer: the maximum number of seconds to wait for
2798 * @return integer: zero if the slave was past that position already,
2799 * greater than zero if we waited for some period of time, less than
2800 * zero if we timed out.
2802 public function masterPosWait( DBMasterPos
$pos, $timeout ) {
2803 wfProfileIn( __METHOD__
);
2805 if ( !is_null( $this->mFakeSlaveLag
) ) {
2806 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2808 if ( $wait > $timeout * 1e6
) {
2809 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2810 wfProfileOut( __METHOD__
);
2812 } elseif ( $wait > 0 ) {
2813 wfDebug( "Fake slave waiting $wait us\n" );
2815 wfProfileOut( __METHOD__
);
2818 wfDebug( "Fake slave up to date ($wait us)\n" );
2819 wfProfileOut( __METHOD__
);
2824 wfProfileOut( __METHOD__
);
2826 # Real waits are implemented in the subclass.
2831 * Get the replication position of this slave
2833 * @return DBMasterPos, or false if this is not a slave.
2835 public function getSlavePos() {
2836 if ( !is_null( $this->mFakeSlaveLag
) ) {
2837 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2838 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2847 * Get the position of this master
2849 * @return DBMasterPos, or false if this is not a master
2851 public function getMasterPos() {
2852 if ( $this->mFakeMaster
) {
2853 return new MySQLMasterPos( 'fake', microtime( true ) );
2860 * Run an anonymous function as soon as there is no transaction pending.
2861 * If there is a transaction and it is rolled back, then the callback is cancelled.
2862 * Callbacks must commit any transactions that they begin.
2864 * This is useful for updates to different systems or separate transactions are needed.
2868 * @param Closure $callback
2870 final public function onTransactionIdle( Closure
$callback ) {
2871 if ( $this->mTrxLevel
) {
2872 $this->trxIdleCallbacks
[] = $callback;
2879 * Actually run the "on transaction idle" callbacks.
2883 protected function runOnTransactionIdleCallbacks() {
2884 $e = null; // last exception
2885 do { // callbacks may add callbacks :)
2886 $callbacks = $this->trxIdleCallbacks
;
2887 $this->trxIdleCallbacks
= array(); // recursion guard
2888 foreach ( $callbacks as $callback ) {
2891 } catch ( Exception
$e ) {}
2893 } while ( count( $this->trxIdleCallbacks
) );
2895 if ( $e instanceof Exception
) {
2896 throw $e; // re-throw any last exception
2901 * Begin a transaction. If a transaction is already in progress, that transaction will be committed before the
2902 * new transaction is started.
2904 * Note that when the DBO_TRX flag is set (which is usually the case for web requests, but not for maintenance scripts),
2905 * any previous database query will have started a transaction automatically.
2907 * Nesting of transactions is not supported. Attempts to nest transactions will cause warnings if DBO_TRX is not set
2908 * or the extsting transaction contained write operations.
2910 * @param $fname string
2912 final public function begin( $fname = 'DatabaseBase::begin' ) {
2913 global $wgDebugDBTransactions;
2915 if ( $this->mTrxLevel
) { // implicit commit
2916 if ( $this->mTrxDoneWrites ||
( $this->mFlags
& DBO_TRX
) === 0 ) {
2917 // In theory, we should always warn about nesting BEGIN statements.
2918 // However, it is sometimes hard to avoid so we only warn if:
2920 // a) the transaction has done writes. This gives warnings about bad transactions
2921 // that could cause partial writes but not about read queries seeing more
2922 // than one DB snapshot (when in REPEATABLE-READ) due to nested BEGINs.
2924 // b) the DBO_TRX flag is not set. Explicit transactions should always be properly
2925 // started and comitted.
2926 /*wfWarn( "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2927 " performing implicit commit!" );*/
2928 } elseif ( $wgDebugDBTransactions ) {
2929 wfDebug( "$fname: Transaction already in progress (from {$this->mTrxFname}), " .
2930 " performing implicit commit!\n" );
2933 $this->doCommit( $fname );
2934 $this->runOnTransactionIdleCallbacks();
2937 $this->doBegin( $fname );
2938 $this->mTrxFname
= $fname;
2939 $this->mTrxDoneWrites
= false;
2943 * Issues the BEGIN command to the database server.
2945 * @see DatabaseBase::begin()
2946 * @param type $fname
2948 protected function doBegin( $fname ) {
2949 $this->query( 'BEGIN', $fname );
2950 $this->mTrxLevel
= 1;
2954 * Commits a transaction previously started using begin().
2955 * If no transaction is in progress, a warning is issued.
2957 * Nesting of transactions is not supported.
2959 * @param $fname string
2961 final public function commit( $fname = 'DatabaseBase::commit' ) {
2962 if ( !$this->mTrxLevel
) {
2963 wfWarn( "$fname: No transaction to commit, something got out of sync!" );
2965 $this->doCommit( $fname );
2966 $this->runOnTransactionIdleCallbacks();
2970 * Issues the COMMIT command to the database server.
2972 * @see DatabaseBase::commit()
2973 * @param type $fname
2975 protected function doCommit( $fname ) {
2976 if ( $this->mTrxLevel
) {
2977 $this->query( 'COMMIT', $fname );
2978 $this->mTrxLevel
= 0;
2983 * Rollback a transaction previously started using begin().
2984 * If no transaction is in progress, a warning is issued.
2986 * No-op on non-transactional databases.
2988 * @param $fname string
2990 final public function rollback( $fname = 'DatabaseBase::rollback' ) {
2991 if ( !$this->mTrxLevel
) {
2992 wfWarn( "$fname: No transaction to rollback, something got out of sync!" );
2994 $this->doRollback( $fname );
2995 $this->trxIdleCallbacks
= array(); // cancel
2999 * Issues the ROLLBACK command to the database server.
3001 * @see DatabaseBase::rollback()
3002 * @param type $fname
3004 protected function doRollback( $fname ) {
3005 if ( $this->mTrxLevel
) {
3006 $this->query( 'ROLLBACK', $fname, true );
3007 $this->mTrxLevel
= 0;
3012 * Creates a new table with structure copied from existing table
3013 * Note that unlike most database abstraction functions, this function does not
3014 * automatically append database prefix, because it works at a lower
3015 * abstraction level.
3016 * The table names passed to this function shall not be quoted (this
3017 * function calls addIdentifierQuotes when needed).
3019 * @param $oldName String: name of table whose structure should be copied
3020 * @param $newName String: name of table to be created
3021 * @param $temporary Boolean: whether the new table should be temporary
3022 * @param $fname String: calling function name
3023 * @return Boolean: true if operation was successful
3025 public function duplicateTableStructure( $oldName, $newName, $temporary = false,
3026 $fname = 'DatabaseBase::duplicateTableStructure' )
3028 throw new MWException(
3029 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
3033 * List all tables on the database
3035 * @param $prefix string Only show tables with this prefix, e.g. mw_
3036 * @param $fname String: calling function name
3038 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
3039 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
3043 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3044 * to the format used for inserting into timestamp fields in this DBMS.
3046 * The result is unquoted, and needs to be passed through addQuotes()
3047 * before it can be included in raw SQL.
3049 * @param $ts string|int
3053 public function timestamp( $ts = 0 ) {
3054 return wfTimestamp( TS_MW
, $ts );
3058 * Convert a timestamp in one of the formats accepted by wfTimestamp()
3059 * to the format used for inserting into timestamp fields in this DBMS. If
3060 * NULL is input, it is passed through, allowing NULL values to be inserted
3061 * into timestamp fields.
3063 * The result is unquoted, and needs to be passed through addQuotes()
3064 * before it can be included in raw SQL.
3066 * @param $ts string|int
3070 public function timestampOrNull( $ts = null ) {
3071 if ( is_null( $ts ) ) {
3074 return $this->timestamp( $ts );
3079 * Take the result from a query, and wrap it in a ResultWrapper if
3080 * necessary. Boolean values are passed through as is, to indicate success
3081 * of write queries or failure.
3083 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
3084 * resource, and it was necessary to call this function to convert it to
3085 * a wrapper. Nowadays, raw database objects are never exposed to external
3086 * callers, so this is unnecessary in external code. For compatibility with
3087 * old code, ResultWrapper objects are passed through unaltered.
3089 * @param $result bool|ResultWrapper
3091 * @return bool|ResultWrapper
3093 public function resultObject( $result ) {
3094 if ( empty( $result ) ) {
3096 } elseif ( $result instanceof ResultWrapper
) {
3098 } elseif ( $result === true ) {
3099 // Successful write query
3102 return new ResultWrapper( $this, $result );
3107 * Ping the server and try to reconnect if it there is no connection
3109 * @return bool Success or failure
3111 public function ping() {
3112 # Stub. Not essential to override.
3117 * Get slave lag. Currently supported only by MySQL.
3119 * Note that this function will generate a fatal error on many
3120 * installations. Most callers should use LoadBalancer::safeGetLag()
3123 * @return int Database replication lag in seconds
3125 public function getLag() {
3126 return intval( $this->mFakeSlaveLag
);
3130 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3134 function maxListLen() {
3139 * Some DBMSs have a special format for inserting into blob fields, they
3140 * don't allow simple quoted strings to be inserted. To insert into such
3141 * a field, pass the data through this function before passing it to
3142 * DatabaseBase::insert().
3146 public function encodeBlob( $b ) {
3151 * Some DBMSs return a special placeholder object representing blob fields
3152 * in result objects. Pass the object through this function to return the
3157 public function decodeBlob( $b ) {
3162 * Override database's default behavior. $options include:
3163 * 'connTimeout' : Set the connection timeout value in seconds.
3164 * May be useful for very long batch queries such as
3165 * full-wiki dumps, where a single query reads out over
3168 * @param $options Array
3171 public function setSessionOptions( array $options ) {}
3174 * Read and execute SQL commands from a file.
3176 * Returns true on success, error string or exception on failure (depending
3177 * on object's error ignore settings).
3179 * @param $filename String: File name to open
3180 * @param $lineCallback Callback: Optional function called before reading each line
3181 * @param $resultCallback Callback: Optional function called for each MySQL result
3182 * @param $fname String: Calling function name or false if name should be
3183 * generated dynamically using $filename
3184 * @return bool|string
3186 public function sourceFile(
3187 $filename, $lineCallback = false, $resultCallback = false, $fname = false
3189 wfSuppressWarnings();
3190 $fp = fopen( $filename, 'r' );
3191 wfRestoreWarnings();
3193 if ( false === $fp ) {
3194 throw new MWException( "Could not open \"{$filename}\".\n" );
3198 $fname = __METHOD__
. "( $filename )";
3202 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3204 catch ( MWException
$e ) {
3215 * Get the full path of a patch file. Originally based on archive()
3216 * from updaters.inc. Keep in mind this always returns a patch, as
3217 * it fails back to MySQL if no DB-specific patch can be found
3219 * @param $patch String The name of the patch, like patch-something.sql
3220 * @return String Full path to patch file
3222 public function patchPath( $patch ) {
3225 $dbType = $this->getType();
3226 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3227 return "$IP/maintenance/$dbType/archives/$patch";
3229 return "$IP/maintenance/archives/$patch";
3234 * Set variables to be used in sourceFile/sourceStream, in preference to the
3235 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3236 * all. If it's set to false, $GLOBALS will be used.
3238 * @param $vars bool|array mapping variable name to value.
3240 public function setSchemaVars( $vars ) {
3241 $this->mSchemaVars
= $vars;
3245 * Read and execute commands from an open file handle.
3247 * Returns true on success, error string or exception on failure (depending
3248 * on object's error ignore settings).
3250 * @param $fp Resource: File handle
3251 * @param $lineCallback Callback: Optional function called before reading each line
3252 * @param $resultCallback Callback: Optional function called for each MySQL result
3253 * @param $fname String: Calling function name
3254 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3255 * @return bool|string
3257 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3258 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3262 while ( !feof( $fp ) ) {
3263 if ( $lineCallback ) {
3264 call_user_func( $lineCallback );
3267 $line = trim( fgets( $fp ) );
3269 if ( $line == '' ) {
3273 if ( '-' == $line[0] && '-' == $line[1] ) {
3281 $done = $this->streamStatementEnd( $cmd, $line );
3285 if ( $done ||
feof( $fp ) ) {
3286 $cmd = $this->replaceVars( $cmd );
3287 if ( $inputCallback ) {
3288 call_user_func( $inputCallback, $cmd );
3290 $res = $this->query( $cmd, $fname );
3292 if ( $resultCallback ) {
3293 call_user_func( $resultCallback, $res, $this );
3296 if ( false === $res ) {
3297 $err = $this->lastError();
3298 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3309 * Called by sourceStream() to check if we've reached a statement end
3311 * @param $sql String SQL assembled so far
3312 * @param $newLine String New line about to be added to $sql
3313 * @return Bool Whether $newLine contains end of the statement
3315 public function streamStatementEnd( &$sql, &$newLine ) {
3316 if ( $this->delimiter
) {
3318 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3319 if ( $newLine != $prev ) {
3327 * Database independent variable replacement. Replaces a set of variables
3328 * in an SQL statement with their contents as given by $this->getSchemaVars().
3330 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3332 * - '{$var}' should be used for text and is passed through the database's
3334 * - `{$var}` should be used for identifiers (eg: table and database names),
3335 * it is passed through the database's addIdentifierQuotes method which
3336 * can be overridden if the database uses something other than backticks.
3337 * - / *$var* / is just encoded, besides traditional table prefix and
3338 * table options its use should be avoided.
3340 * @param $ins String: SQL statement to replace variables in
3341 * @return String The new SQL statement with variables replaced
3343 protected function replaceSchemaVars( $ins ) {
3344 $vars = $this->getSchemaVars();
3345 foreach ( $vars as $var => $value ) {
3347 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3349 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3351 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3357 * Replace variables in sourced SQL
3359 * @param $ins string
3363 protected function replaceVars( $ins ) {
3364 $ins = $this->replaceSchemaVars( $ins );
3367 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3368 array( $this, 'tableNameCallback' ), $ins );
3371 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3372 array( $this, 'indexNameCallback' ), $ins );
3378 * Get schema variables. If none have been set via setSchemaVars(), then
3379 * use some defaults from the current object.
3383 protected function getSchemaVars() {
3384 if ( $this->mSchemaVars
) {
3385 return $this->mSchemaVars
;
3387 return $this->getDefaultSchemaVars();
3392 * Get schema variables to use if none have been set via setSchemaVars().
3394 * Override this in derived classes to provide variables for tables.sql
3395 * and SQL patch files.
3399 protected function getDefaultSchemaVars() {
3404 * Table name callback
3406 * @param $matches array
3410 protected function tableNameCallback( $matches ) {
3411 return $this->tableName( $matches[1] );
3415 * Index name callback
3417 * @param $matches array
3421 protected function indexNameCallback( $matches ) {
3422 return $this->indexName( $matches[1] );
3426 * Check to see if a named lock is available. This is non-blocking.
3428 * @param $lockName String: name of lock to poll
3429 * @param $method String: name of method calling us
3433 public function lockIsFree( $lockName, $method ) {
3438 * Acquire a named lock
3440 * Abstracted from Filestore::lock() so child classes can implement for
3443 * @param $lockName String: name of lock to aquire
3444 * @param $method String: name of method calling us
3445 * @param $timeout Integer: timeout
3448 public function lock( $lockName, $method, $timeout = 5 ) {
3455 * @param $lockName String: Name of lock to release
3456 * @param $method String: Name of method calling us
3458 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3459 * by this thread (in which case the lock is not released), and NULL if the named
3460 * lock did not exist
3462 public function unlock( $lockName, $method ) {
3467 * Lock specific tables
3469 * @param $read Array of tables to lock for read access
3470 * @param $write Array of tables to lock for write access
3471 * @param $method String name of caller
3472 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3476 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3481 * Unlock specific tables
3483 * @param $method String the caller
3487 public function unlockTables( $method ) {
3493 * @param $tableName string
3494 * @param $fName string
3495 * @return bool|ResultWrapper
3498 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3499 if( !$this->tableExists( $tableName, $fName ) ) {
3502 $sql = "DROP TABLE " . $this->tableName( $tableName );
3503 if( $this->cascadingDeletes() ) {
3506 return $this->query( $sql, $fName );
3510 * Get search engine class. All subclasses of this need to implement this
3511 * if they wish to use searching.
3515 public function getSearchEngine() {
3516 return 'SearchEngineDummy';
3520 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3521 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3522 * because "i" sorts after all numbers.
3526 public function getInfinity() {
3531 * Encode an expiry time into the DBMS dependent format
3533 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3536 public function encodeExpiry( $expiry ) {
3537 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3538 ?
$this->getInfinity()
3539 : $this->timestamp( $expiry );
3543 * Decode an expiry time into a DBMS independent format
3545 * @param $expiry String: DB timestamp field value for expiry
3546 * @param $format integer: TS_* constant, defaults to TS_MW
3549 public function decodeExpiry( $expiry, $format = TS_MW
) {
3550 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
3552 : wfTimestamp( $format, $expiry );
3556 * Allow or deny "big selects" for this session only. This is done by setting
3557 * the sql_big_selects session variable.
3559 * This is a MySQL-specific feature.
3561 * @param $value Mixed: true for allow, false for deny, or "default" to
3562 * restore the initial value
3564 public function setBigSelects( $value = true ) {
3571 public function __toString() {
3572 return (string)$this->mConn
;