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;
231 protected $mConn = null;
232 protected $mOpened = false;
234 protected $mTablePrefix;
236 protected $mTrxLevel = 0;
237 protected $mErrorCount = 0;
238 protected $mLBInfo = array();
239 protected $mFakeSlaveLag = null, $mFakeMaster = false;
240 protected $mDefaultBigSelects = null;
241 protected $mSchemaVars = false;
243 protected $preparedArgs;
245 protected $htmlErrors;
247 protected $delimiter = ';';
249 # ------------------------------------------------------------------------------
251 # ------------------------------------------------------------------------------
252 # These optionally set a variable and return the previous state
255 * A string describing the current software version, and possibly
256 * other details in a user-friendly way. Will be listed on Special:Version, etc.
257 * Use getServerVersion() to get machine-friendly information.
259 * @return string: Version information from the database server
261 public function getServerInfo() {
262 return $this->getServerVersion();
266 * Boolean, controls output of large amounts of debug information.
267 * @param $debug bool|null
268 * - true to enable debugging
269 * - false to disable debugging
270 * - omitted or null to do nothing
272 * @return bool|null previous value of the flag
274 function debug( $debug = null ) {
275 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
279 * Turns buffering of SQL result sets on (true) or off (false). Default is
282 * Unbuffered queries are very troublesome in MySQL:
284 * - If another query is executed while the first query is being read
285 * out, the first query is killed. This means you can't call normal
286 * MediaWiki functions while you are reading an unbuffered query result
287 * from a normal wfGetDB() connection.
289 * - Unbuffered queries cause the MySQL server to use large amounts of
290 * memory and to hold broad locks which block other queries.
292 * If you want to limit client-side memory, it's almost always better to
293 * split up queries into batches using a LIMIT clause than to switch off
296 * @param $buffer null|bool
298 * @return null|bool The previous value of the flag
300 function bufferResults( $buffer = null ) {
301 if ( is_null( $buffer ) ) {
302 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
304 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
309 * Turns on (false) or off (true) the automatic generation and sending
310 * of a "we're sorry, but there has been a database error" page on
311 * database errors. Default is on (false). When turned off, the
312 * code should use lastErrno() and lastError() to handle the
313 * situation as appropriate.
315 * @param $ignoreErrors bool|null
317 * @return bool The previous value of the flag.
319 function ignoreErrors( $ignoreErrors = null ) {
320 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
324 * Gets or sets the current transaction level.
326 * Historically, transactions were allowed to be "nested". This is no
327 * longer supported, so this function really only returns a boolean.
329 * @param $level int An integer (0 or 1), or omitted to leave it unchanged.
330 * @return int The previous value
332 function trxLevel( $level = null ) {
333 return wfSetVar( $this->mTrxLevel
, $level );
337 * Get/set the number of errors logged. Only useful when errors are ignored
338 * @param $count int The count to set, or omitted to leave it unchanged.
339 * @return int The error count
341 function errorCount( $count = null ) {
342 return wfSetVar( $this->mErrorCount
, $count );
346 * Get/set the table prefix.
347 * @param $prefix string The table prefix to set, or omitted to leave it unchanged.
348 * @return string The previous table prefix.
350 function tablePrefix( $prefix = null ) {
351 return wfSetVar( $this->mTablePrefix
, $prefix );
355 * Get properties passed down from the server info array of the load
358 * @param $name string The entry of the info array to get, or null to get the
361 * @return LoadBalancer|null
363 function getLBInfo( $name = null ) {
364 if ( is_null( $name ) ) {
365 return $this->mLBInfo
;
367 if ( array_key_exists( $name, $this->mLBInfo
) ) {
368 return $this->mLBInfo
[$name];
376 * Set the LB info array, or a member of it. If called with one parameter,
377 * the LB info array is set to that parameter. If it is called with two
378 * parameters, the member with the given name is set to the given value.
383 function setLBInfo( $name, $value = null ) {
384 if ( is_null( $value ) ) {
385 $this->mLBInfo
= $name;
387 $this->mLBInfo
[$name] = $value;
392 * Set lag time in seconds for a fake slave
396 function setFakeSlaveLag( $lag ) {
397 $this->mFakeSlaveLag
= $lag;
401 * Make this connection a fake master
403 * @param $enabled bool
405 function setFakeMaster( $enabled = true ) {
406 $this->mFakeMaster
= $enabled;
410 * Returns true if this database supports (and uses) cascading deletes
414 function cascadingDeletes() {
419 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
423 function cleanupTriggers() {
428 * Returns true if this database is strict about what can be put into an IP field.
429 * Specifically, it uses a NULL value instead of an empty string.
433 function strictIPs() {
438 * Returns true if this database uses timestamps rather than integers
442 function realTimestamps() {
447 * Returns true if this database does an implicit sort when doing GROUP BY
451 function implicitGroupby() {
456 * Returns true if this database does an implicit order by when the column has an index
457 * For example: SELECT page_title FROM page LIMIT 1
461 function implicitOrderby() {
466 * Returns true if this database requires that SELECT DISTINCT queries require that all
467 ORDER BY expressions occur in the SELECT list per the SQL92 standard
471 function standardSelectDistinct() {
476 * Returns true if this database can do a native search on IP columns
477 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
481 function searchableIPs() {
486 * Returns true if this database can use functional indexes
490 function functionalIndexes() {
495 * Return the last query that went through DatabaseBase::query()
498 function lastQuery() {
499 return $this->mLastQuery
;
503 * Returns true if the connection may have been used for write queries.
504 * Should return true if unsure.
508 function doneWrites() {
509 return $this->mDoneWrites
;
513 * Is a connection to the database open?
517 return $this->mOpened
;
521 * Set a flag for this connection
523 * @param $flag Integer: DBO_* constants from Defines.php:
524 * - DBO_DEBUG: output some debug info (same as debug())
525 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
526 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
527 * - DBO_TRX: automatically start transactions
528 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
529 * and removes it in command line mode
530 * - DBO_PERSISTENT: use persistant database connection
532 function setFlag( $flag ) {
533 $this->mFlags |
= $flag;
537 * Clear a flag for this connection
539 * @param $flag: same as setFlag()'s $flag param
541 function clearFlag( $flag ) {
542 $this->mFlags
&= ~
$flag;
546 * Returns a boolean whether the flag $flag is set for this connection
548 * @param $flag: same as setFlag()'s $flag param
551 function getFlag( $flag ) {
552 return !!( $this->mFlags
& $flag );
556 * General read-only accessor
558 * @param $name string
562 function getProperty( $name ) {
569 function getWikiID() {
570 if ( $this->mTablePrefix
) {
571 return "{$this->mDBname}-{$this->mTablePrefix}";
573 return $this->mDBname
;
578 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
582 public function getSchemaPath() {
584 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
585 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
587 return "$IP/maintenance/tables.sql";
591 # ------------------------------------------------------------------------------
593 # ------------------------------------------------------------------------------
597 * @param $server String: database server host
598 * @param $user String: database user name
599 * @param $password String: database user password
600 * @param $dbName String: database name
602 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
604 function __construct( $server = false, $user = false, $password = false, $dbName = false,
605 $flags = 0, $tablePrefix = 'get from global'
607 global $wgDBprefix, $wgCommandLineMode;
609 $this->mFlags
= $flags;
611 if ( $this->mFlags
& DBO_DEFAULT
) {
612 if ( $wgCommandLineMode ) {
613 $this->mFlags
&= ~DBO_TRX
;
615 $this->mFlags |
= DBO_TRX
;
619 /** Get the default table prefix*/
620 if ( $tablePrefix == 'get from global' ) {
621 $this->mTablePrefix
= $wgDBprefix;
623 $this->mTablePrefix
= $tablePrefix;
627 $this->open( $server, $user, $password, $dbName );
632 * Called by serialize. Throw an exception when DB connection is serialized.
633 * This causes problems on some database engines because the connection is
634 * not restored on unserialize.
636 public function __sleep() {
637 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
641 * Same as new DatabaseMysql( ... ), kept for backward compatibility
642 * @deprecated since 1.17
649 * @return DatabaseMysql
651 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
652 wfDeprecated( __METHOD__
, '1.17' );
653 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
657 * Same as new factory( ... ), kept for backward compatibility
658 * @deprecated since 1.18
659 * @see Database::factory()
660 * @return DatabaseBase
662 public final static function newFromType( $dbType, $p = array() ) {
663 wfDeprecated( __METHOD__
, '1.18' );
664 if ( isset( $p['tableprefix'] ) ) {
665 $p['tablePrefix'] = $p['tableprefix'];
667 return self
::factory( $dbType, $p );
671 * Given a DB type, construct the name of the appropriate child class of
672 * DatabaseBase. This is designed to replace all of the manual stuff like:
673 * $class = 'Database' . ucfirst( strtolower( $type ) );
674 * as well as validate against the canonical list of DB types we have
676 * This factory function is mostly useful for when you need to connect to a
677 * database other than the MediaWiki default (such as for external auth,
678 * an extension, et cetera). Do not use this to connect to the MediaWiki
679 * database. Example uses in core:
680 * @see LoadBalancer::reallyOpenConnection()
681 * @see ExternalUser_MediaWiki::initFromCond()
682 * @see ForeignDBRepo::getMasterDB()
683 * @see WebInstaller_DBConnect::execute()
687 * @param $dbType String A possible DB type
688 * @param $p Array An array of options to pass to the constructor.
689 * Valid options are: host, user, password, dbname, flags, tablePrefix
690 * @return DatabaseBase subclass or null
692 public final static function factory( $dbType, $p = array() ) {
693 $canonicalDBTypes = array(
694 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
696 $dbType = strtolower( $dbType );
697 $class = 'Database' . ucfirst( $dbType );
699 if( in_array( $dbType, $canonicalDBTypes ) ||
( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) ) {
701 isset( $p['host'] ) ?
$p['host'] : false,
702 isset( $p['user'] ) ?
$p['user'] : false,
703 isset( $p['password'] ) ?
$p['password'] : false,
704 isset( $p['dbname'] ) ?
$p['dbname'] : false,
705 isset( $p['flags'] ) ?
$p['flags'] : 0,
706 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
713 protected function installErrorHandler() {
714 $this->mPHPError
= false;
715 $this->htmlErrors
= ini_set( 'html_errors', '0' );
716 set_error_handler( array( $this, 'connectionErrorHandler' ) );
720 * @return bool|string
722 protected function restoreErrorHandler() {
723 restore_error_handler();
724 if ( $this->htmlErrors
!== false ) {
725 ini_set( 'html_errors', $this->htmlErrors
);
727 if ( $this->mPHPError
) {
728 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
729 $error = preg_replace( '!^.*?:\s?(.*)$!', '$1', $error );
740 protected function connectionErrorHandler( $errno, $errstr ) {
741 $this->mPHPError
= $errstr;
745 * Closes a database connection.
746 * if it is open : commits any open transactions
748 * @return Bool operation success. true if already closed.
750 public function close() {
751 $this->mOpened
= false;
752 if ( $this->mConn
) {
753 if ( $this->trxLevel() ) {
754 $this->commit( __METHOD__
);
756 $ret = $this->closeConnection();
757 $this->mConn
= false;
765 * Closes underlying database connection
767 * @return bool: Whether connection was closed successfully
769 protected abstract function closeConnection();
772 * @param $error String: fallback error message, used if none is given by DB
774 function reportConnectionError( $error = 'Unknown error' ) {
775 $myError = $this->lastError();
781 throw new DBConnectionError( $this, $error );
785 * The DBMS-dependent part of query()
787 * @param $sql String: SQL query.
788 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
790 protected abstract function doQuery( $sql );
793 * Determine whether a query writes to the DB.
794 * Should return true if unsure.
800 function isWriteQuery( $sql ) {
801 return !preg_match( '/^(?:SELECT|BEGIN|ROLLBACK|COMMIT|SET|SHOW|EXPLAIN|\(SELECT)\b/i', $sql );
805 * Run an SQL query and return the result. Normally throws a DBQueryError
806 * on failure. If errors are ignored, returns false instead.
808 * In new code, the query wrappers select(), insert(), update(), delete(),
809 * etc. should be used where possible, since they give much better DBMS
810 * independence and automatically quote or validate user input in a variety
811 * of contexts. This function is generally only useful for queries which are
812 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
815 * However, the query wrappers themselves should call this function.
817 * @param $sql String: SQL query
818 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
819 * comment (you can use __METHOD__ or add some extra info)
820 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
821 * maybe best to catch the exception instead?
822 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
823 * for a successful read query, or false on failure if $tempIgnore set
824 * @throws DBQueryError Thrown when the database returns an error of any kind
826 public function query( $sql, $fname = '', $tempIgnore = false ) {
827 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
828 if ( !Profiler
::instance()->isStub() ) {
829 # generalizeSQL will probably cut down the query to reasonable
830 # logging size most of the time. The substr is really just a sanity check.
833 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
834 $totalProf = 'DatabaseBase::query-master';
836 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
837 $totalProf = 'DatabaseBase::query';
840 wfProfileIn( $totalProf );
841 wfProfileIn( $queryProf );
844 $this->mLastQuery
= $sql;
845 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
846 # Set a flag indicating that writes have been done
847 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
848 $this->mDoneWrites
= true;
851 # Add a comment for easy SHOW PROCESSLIST interpretation
853 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
854 $userName = $wgUser->getName();
855 if ( mb_strlen( $userName ) > 15 ) {
856 $userName = mb_substr( $userName, 0, 15 ) . '...';
858 $userName = str_replace( '/', '', $userName );
862 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
864 # If DBO_TRX is set, start a transaction
865 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
866 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
867 # avoid establishing transactions for SHOW and SET statements too -
868 # that would delay transaction initializations to once connection
869 # is really used by application
870 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
871 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
872 $this->begin( __METHOD__
. " ($fname)" );
875 if ( $this->debug() ) {
879 $sqlx = substr( $commentedSql, 0, 500 );
880 $sqlx = strtr( $sqlx, "\t\n", ' ' );
882 $master = $isMaster ?
'master' : 'slave';
883 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
886 if ( istainted( $sql ) & TC_MYSQL
) {
887 throw new MWException( 'Tainted query found' );
890 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
892 # Do the query and handle errors
893 $ret = $this->doQuery( $commentedSql );
895 MWDebug
::queryTime( $queryId );
897 # Try reconnecting if the connection was lost
898 if ( false === $ret && $this->wasErrorReissuable() ) {
899 # Transaction is gone, like it or not
900 $this->mTrxLevel
= 0;
901 wfDebug( "Connection lost, reconnecting...\n" );
903 if ( $this->ping() ) {
904 wfDebug( "Reconnected\n" );
905 $sqlx = substr( $commentedSql, 0, 500 );
906 $sqlx = strtr( $sqlx, "\t\n", ' ' );
907 global $wgRequestTime;
908 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
909 if ( $elapsed < 300 ) {
910 # Not a database error to lose a transaction after a minute or two
911 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
913 $ret = $this->doQuery( $commentedSql );
915 wfDebug( "Failed\n" );
919 if ( false === $ret ) {
920 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
923 if ( !Profiler
::instance()->isStub() ) {
924 wfProfileOut( $queryProf );
925 wfProfileOut( $totalProf );
928 return $this->resultObject( $ret );
932 * Report a query error. Log the error, and if neither the object ignore
933 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
935 * @param $error String
936 * @param $errno Integer
938 * @param $fname String
939 * @param $tempIgnore Boolean
941 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
942 # Ignore errors during error handling to avoid infinite recursion
943 $ignore = $this->ignoreErrors( true );
944 ++
$this->mErrorCount
;
946 if ( $ignore ||
$tempIgnore ) {
947 wfDebug( "SQL ERROR (ignored): $error\n" );
948 $this->ignoreErrors( $ignore );
950 $sql1line = str_replace( "\n", "\\n", $sql );
951 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
952 wfDebug( "SQL ERROR: " . $error . "\n" );
953 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
958 * Intended to be compatible with the PEAR::DB wrapper functions.
959 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
961 * ? = scalar value, quoted as necessary
962 * ! = raw SQL bit (a function for instance)
963 * & = filename; reads the file and inserts as a blob
964 * (we don't use this though...)
966 * This function should not be used directly by new code outside of the
967 * database classes. The query wrapper functions (select() etc.) should be
971 * @param $func string
975 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
976 /* MySQL doesn't support prepared statements (yet), so just
977 pack up the query for reference. We'll manually replace
979 return array( 'query' => $sql, 'func' => $func );
983 * Free a prepared query, generated by prepare().
986 function freePrepared( $prepared ) {
987 /* No-op by default */
991 * Execute a prepared query with the various arguments
992 * @param $prepared String: the prepared sql
993 * @param $args Mixed: Either an array here, or put scalars as varargs
995 * @return ResultWrapper
997 function execute( $prepared, $args = null ) {
998 if ( !is_array( $args ) ) {
1000 $args = func_get_args();
1001 array_shift( $args );
1004 $sql = $this->fillPrepared( $prepared['query'], $args );
1006 return $this->query( $sql, $prepared['func'] );
1010 * Prepare & execute an SQL statement, quoting and inserting arguments
1011 * in the appropriate places.
1013 * This function should not be used directly by new code outside of the
1014 * database classes. The query wrapper functions (select() etc.) should be
1017 * @param $query String
1020 * @return ResultWrapper
1022 function safeQuery( $query, $args = null ) {
1023 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
1025 if ( !is_array( $args ) ) {
1027 $args = func_get_args();
1028 array_shift( $args );
1031 $retval = $this->execute( $prepared, $args );
1032 $this->freePrepared( $prepared );
1038 * For faking prepared SQL statements on DBs that don't support
1040 * @param $preparedQuery String: a 'preparable' SQL statement
1041 * @param $args Array of arguments to fill it with
1042 * @return string executable SQL
1044 function fillPrepared( $preparedQuery, $args ) {
1046 $this->preparedArgs
=& $args;
1048 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1049 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1053 * preg_callback func for fillPrepared()
1054 * The arguments should be in $this->preparedArgs and must not be touched
1055 * while we're doing this.
1057 * @param $matches Array
1060 function fillPreparedArg( $matches ) {
1061 switch( $matches[1] ) {
1062 case '\\?': return '?';
1063 case '\\!': return '!';
1064 case '\\&': return '&';
1067 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1069 switch( $matches[1] ) {
1070 case '?': return $this->addQuotes( $arg );
1071 case '!': return $arg;
1073 # return $this->addQuotes( file_get_contents( $arg ) );
1074 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1076 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1081 * Free a result object returned by query() or select(). It's usually not
1082 * necessary to call this, just use unset() or let the variable holding
1083 * the result object go out of scope.
1085 * @param $res Mixed: A SQL result
1087 function freeResult( $res ) {
1091 * Simple UPDATE wrapper.
1092 * Usually throws a DBQueryError on failure.
1093 * If errors are explicitly ignored, returns success
1095 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1096 * calling convention and feature set
1098 * @param $table string
1102 * @param $fname string
1106 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1107 $table = $this->tableName( $table );
1108 $sql = "UPDATE $table SET $var = '" .
1109 $this->strencode( $value ) . "' WHERE ($cond)";
1111 return (bool)$this->query( $sql, $fname );
1115 * A SELECT wrapper which returns a single field from a single result row.
1117 * Usually throws a DBQueryError on failure. If errors are explicitly
1118 * ignored, returns false on failure.
1120 * If no result rows are returned from the query, false is returned.
1122 * @param $table string|array Table name. See DatabaseBase::select() for details.
1123 * @param $var string The field name to select. This must be a valid SQL
1124 * fragment: do not use unvalidated user input.
1125 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1126 * @param $fname string The function name of the caller.
1127 * @param $options string|array The query options. See DatabaseBase::select() for details.
1129 * @return bool|mixed The value from the field, or false on failure.
1131 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1132 $options = array() )
1134 if ( !is_array( $options ) ) {
1135 $options = array( $options );
1138 $options['LIMIT'] = 1;
1140 $res = $this->select( $table, $var, $cond, $fname, $options );
1142 if ( $res === false ||
!$this->numRows( $res ) ) {
1146 $row = $this->fetchRow( $res );
1148 if ( $row !== false ) {
1149 return reset( $row );
1156 * Returns an optional USE INDEX clause to go after the table, and a
1157 * string to go at the end of the query.
1159 * @param $options Array: associative array of options to be turned into
1160 * an SQL query, valid keys are listed in the function.
1162 * @see DatabaseBase::select()
1164 function makeSelectOptions( $options ) {
1165 $preLimitTail = $postLimitTail = '';
1168 $noKeyOptions = array();
1170 foreach ( $options as $key => $option ) {
1171 if ( is_numeric( $key ) ) {
1172 $noKeyOptions[$option] = true;
1176 if ( isset( $options['GROUP BY'] ) ) {
1177 $gb = is_array( $options['GROUP BY'] )
1178 ?
implode( ',', $options['GROUP BY'] )
1179 : $options['GROUP BY'];
1180 $preLimitTail .= " GROUP BY {$gb}";
1183 if ( isset( $options['HAVING'] ) ) {
1184 $preLimitTail .= " HAVING {$options['HAVING']}";
1187 if ( isset( $options['ORDER BY'] ) ) {
1188 $ob = is_array( $options['ORDER BY'] )
1189 ?
implode( ',', $options['ORDER BY'] )
1190 : $options['ORDER BY'];
1191 $preLimitTail .= " ORDER BY {$ob}";
1194 // if (isset($options['LIMIT'])) {
1195 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1196 // isset($options['OFFSET']) ? $options['OFFSET']
1200 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1201 $postLimitTail .= ' FOR UPDATE';
1204 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1205 $postLimitTail .= ' LOCK IN SHARE MODE';
1208 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1209 $startOpts .= 'DISTINCT';
1212 # Various MySQL extensions
1213 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1214 $startOpts .= ' /*! STRAIGHT_JOIN */';
1217 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1218 $startOpts .= ' HIGH_PRIORITY';
1221 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1222 $startOpts .= ' SQL_BIG_RESULT';
1225 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1226 $startOpts .= ' SQL_BUFFER_RESULT';
1229 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1230 $startOpts .= ' SQL_SMALL_RESULT';
1233 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1234 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1237 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1238 $startOpts .= ' SQL_CACHE';
1241 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1242 $startOpts .= ' SQL_NO_CACHE';
1245 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1246 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1251 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1255 * Execute a SELECT query constructed using the various parameters provided.
1256 * See below for full details of the parameters.
1258 * @param $table String|Array Table name
1259 * @param $vars String|Array Field names
1260 * @param $conds String|Array Conditions
1261 * @param $fname String Caller function name
1262 * @param $options Array Query options
1263 * @param $join_conds Array Join conditions
1265 * @param $table string|array
1267 * May be either an array of table names, or a single string holding a table
1268 * name. If an array is given, table aliases can be specified, for example:
1270 * array( 'a' => 'user' )
1272 * This includes the user table in the query, with the alias "a" available
1273 * for use in field names (e.g. a.user_name).
1275 * All of the table names given here are automatically run through
1276 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1277 * added, and various other table name mappings to be performed.
1280 * @param $vars string|array
1282 * May be either a field name or an array of field names. The field names
1283 * here are complete fragments of SQL, for direct inclusion into the SELECT
1284 * query. Expressions and aliases may be specified as in SQL, for example:
1286 * array( 'MAX(rev_id) AS maxrev' )
1288 * If an expression is given, care must be taken to ensure that it is
1292 * @param $conds string|array
1294 * May be either a string containing a single condition, or an array of
1295 * conditions. If an array is given, the conditions constructed from each
1296 * element are combined with AND.
1298 * Array elements may take one of two forms:
1300 * - Elements with a numeric key are interpreted as raw SQL fragments.
1301 * - Elements with a string key are interpreted as equality conditions,
1302 * where the key is the field name.
1303 * - If the value of such an array element is a scalar (such as a
1304 * string), it will be treated as data and thus quoted appropriately.
1305 * If it is null, an IS NULL clause will be added.
1306 * - If the value is an array, an IN(...) clause will be constructed,
1307 * such that the field name may match any of the elements in the
1308 * array. The elements of the array will be quoted.
1310 * Note that expressions are often DBMS-dependent in their syntax.
1311 * DBMS-independent wrappers are provided for constructing several types of
1312 * expression commonly used in condition queries. See:
1313 * - DatabaseBase::buildLike()
1314 * - DatabaseBase::conditional()
1317 * @param $options string|array
1319 * Optional: Array of query options. Boolean options are specified by
1320 * including them in the array as a string value with a numeric key, for
1323 * array( 'FOR UPDATE' )
1325 * The supported options are:
1327 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1328 * with LIMIT can theoretically be used for paging through a result set,
1329 * but this is discouraged in MediaWiki for performance reasons.
1331 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1332 * and then the first rows are taken until the limit is reached. LIMIT
1333 * is applied to a result set after OFFSET.
1335 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1336 * changed until the next COMMIT.
1338 * - DISTINCT: Boolean: return only unique result rows.
1340 * - GROUP BY: May be either an SQL fragment string naming a field or
1341 * expression to group by, or an array of such SQL fragments.
1343 * - HAVING: A string containing a HAVING clause.
1345 * - ORDER BY: May be either an SQL fragment giving a field name or
1346 * expression to order by, or an array of such SQL fragments.
1348 * - USE INDEX: This may be either a string giving the index name to use
1349 * for the query, or an array. If it is an associative array, each key
1350 * gives the table name (or alias), each value gives the index name to
1351 * use for that table. All strings are SQL fragments and so should be
1352 * validated by the caller.
1354 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1355 * instead of SELECT.
1357 * And also the following boolean MySQL extensions, see the MySQL manual
1358 * for documentation:
1360 * - LOCK IN SHARE MODE
1364 * - SQL_BUFFER_RESULT
1365 * - SQL_SMALL_RESULT
1366 * - SQL_CALC_FOUND_ROWS
1371 * @param $join_conds string|array
1373 * Optional associative array of table-specific join conditions. In the
1374 * most common case, this is unnecessary, since the join condition can be
1375 * in $conds. However, it is useful for doing a LEFT JOIN.
1377 * The key of the array contains the table name or alias. The value is an
1378 * array with two elements, numbered 0 and 1. The first gives the type of
1379 * join, the second is an SQL fragment giving the join condition for that
1380 * table. For example:
1382 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1384 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1385 * with no rows in it will be returned. If there was a query error, a
1386 * DBQueryError exception will be thrown, except if the "ignore errors"
1387 * option was set, in which case false will be returned.
1389 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1390 $options = array(), $join_conds = array() ) {
1391 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1393 return $this->query( $sql, $fname );
1397 * The equivalent of DatabaseBase::select() except that the constructed SQL
1398 * is returned, instead of being immediately executed.
1400 * @param $table string|array Table name
1401 * @param $vars string|array Field names
1402 * @param $conds string|array Conditions
1403 * @param $fname string Caller function name
1404 * @param $options string|array Query options
1405 * @param $join_conds string|array Join conditions
1407 * @return string SQL query string.
1408 * @see DatabaseBase::select()
1410 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1411 if ( is_array( $vars ) ) {
1412 $vars = implode( ',', $vars );
1415 $options = (array)$options;
1417 if ( is_array( $table ) ) {
1418 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1419 ?
$options['USE INDEX']
1421 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1423 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1425 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1427 } elseif ( $table != '' ) {
1428 if ( $table[0] == ' ' ) {
1429 $from = ' FROM ' . $table;
1431 $from = ' FROM ' . $this->tableName( $table );
1437 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1439 if ( !empty( $conds ) ) {
1440 if ( is_array( $conds ) ) {
1441 $conds = $this->makeList( $conds, LIST_AND
);
1443 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1445 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1448 if ( isset( $options['LIMIT'] ) ) {
1449 $sql = $this->limitResult( $sql, $options['LIMIT'],
1450 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1452 $sql = "$sql $postLimitTail";
1454 if ( isset( $options['EXPLAIN'] ) ) {
1455 $sql = 'EXPLAIN ' . $sql;
1462 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1463 * that a single row object is returned. If the query returns no rows,
1464 * false is returned.
1466 * @param $table string|array Table name
1467 * @param $vars string|array Field names
1468 * @param $conds array Conditions
1469 * @param $fname string Caller function name
1470 * @param $options string|array Query options
1471 * @param $join_conds array|string Join conditions
1473 * @return object|bool
1475 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1476 $options = array(), $join_conds = array() )
1478 $options = (array)$options;
1479 $options['LIMIT'] = 1;
1480 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1482 if ( $res === false ) {
1486 if ( !$this->numRows( $res ) ) {
1490 $obj = $this->fetchObject( $res );
1496 * Estimate rows in dataset.
1498 * MySQL allows you to estimate the number of rows that would be returned
1499 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1500 * index cardinality statistics, and is notoriously inaccurate, especially
1501 * when large numbers of rows have recently been added or deleted.
1503 * For DBMSs that don't support fast result size estimation, this function
1504 * will actually perform the SELECT COUNT(*).
1506 * Takes the same arguments as DatabaseBase::select().
1508 * @param $table String: table name
1509 * @param Array|string $vars : unused
1510 * @param Array|string $conds : filters on the table
1511 * @param $fname String: function name for profiling
1512 * @param $options Array: options for select
1513 * @return Integer: row count
1515 public function estimateRowCount( $table, $vars = '*', $conds = '',
1516 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1519 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1522 $row = $this->fetchRow( $res );
1523 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1530 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1531 * It's only slightly flawed. Don't use for anything important.
1533 * @param $sql String A SQL Query
1537 static function generalizeSQL( $sql ) {
1538 # This does the same as the regexp below would do, but in such a way
1539 # as to avoid crashing php on some large strings.
1540 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1542 $sql = str_replace ( "\\\\", '', $sql );
1543 $sql = str_replace ( "\\'", '', $sql );
1544 $sql = str_replace ( "\\\"", '', $sql );
1545 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1546 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1548 # All newlines, tabs, etc replaced by single space
1549 $sql = preg_replace ( '/\s+/', ' ', $sql );
1552 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1558 * Determines whether a field exists in a table
1560 * @param $table String: table name
1561 * @param $field String: filed to check on that table
1562 * @param $fname String: calling function name (optional)
1563 * @return Boolean: whether $table has filed $field
1565 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1566 $info = $this->fieldInfo( $table, $field );
1572 * Determines whether an index exists
1573 * Usually throws a DBQueryError on failure
1574 * If errors are explicitly ignored, returns NULL on failure
1578 * @param $fname string
1582 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1583 $info = $this->indexInfo( $table, $index, $fname );
1584 if ( is_null( $info ) ) {
1587 return $info !== false;
1592 * Query whether a given table exists
1594 * @param $table string
1595 * @param $fname string
1599 function tableExists( $table, $fname = __METHOD__
) {
1600 $table = $this->tableName( $table );
1601 $old = $this->ignoreErrors( true );
1602 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1603 $this->ignoreErrors( $old );
1609 * mysql_field_type() wrapper
1614 function fieldType( $res, $index ) {
1615 if ( $res instanceof ResultWrapper
) {
1616 $res = $res->result
;
1619 return mysql_field_type( $res, $index );
1623 * Determines if a given index is unique
1625 * @param $table string
1626 * @param $index string
1630 function indexUnique( $table, $index ) {
1631 $indexInfo = $this->indexInfo( $table, $index );
1633 if ( !$indexInfo ) {
1637 return !$indexInfo[0]->Non_unique
;
1641 * Helper for DatabaseBase::insert().
1643 * @param $options array
1646 function makeInsertOptions( $options ) {
1647 return implode( ' ', $options );
1651 * INSERT wrapper, inserts an array into a table.
1655 * - A single associative array. The array keys are the field names, and
1656 * the values are the values to insert. The values are treated as data
1657 * and will be quoted appropriately. If NULL is inserted, this will be
1658 * converted to a database NULL.
1659 * - An array with numeric keys, holding a list of associative arrays.
1660 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1661 * each subarray must be identical to each other, and in the same order.
1663 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1666 * $options is an array of options, with boolean options encoded as values
1667 * with numeric keys, in the same style as $options in
1668 * DatabaseBase::select(). Supported options are:
1670 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1671 * any rows which cause duplicate key errors are not inserted. It's
1672 * possible to determine how many rows were successfully inserted using
1673 * DatabaseBase::affectedRows().
1675 * @param $table String Table name. This will be passed through
1676 * DatabaseBase::tableName().
1677 * @param $a Array of rows to insert
1678 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1679 * @param $options Array of options
1683 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1684 # No rows to insert, easy just return now
1685 if ( !count( $a ) ) {
1689 $table = $this->tableName( $table );
1691 if ( !is_array( $options ) ) {
1692 $options = array( $options );
1695 $options = $this->makeInsertOptions( $options );
1697 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1699 $keys = array_keys( $a[0] );
1702 $keys = array_keys( $a );
1705 $sql = 'INSERT ' . $options .
1706 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1710 foreach ( $a as $row ) {
1716 $sql .= '(' . $this->makeList( $row ) . ')';
1719 $sql .= '(' . $this->makeList( $a ) . ')';
1722 return (bool)$this->query( $sql, $fname );
1726 * Make UPDATE options for the DatabaseBase::update function
1728 * @param $options Array: The options passed to DatabaseBase::update
1731 function makeUpdateOptions( $options ) {
1732 if ( !is_array( $options ) ) {
1733 $options = array( $options );
1738 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1739 $opts[] = $this->lowPriorityOption();
1742 if ( in_array( 'IGNORE', $options ) ) {
1746 return implode( ' ', $opts );
1750 * UPDATE wrapper. Takes a condition array and a SET array.
1752 * @param $table String name of the table to UPDATE. This will be passed through
1753 * DatabaseBase::tableName().
1755 * @param $values Array: An array of values to SET. For each array element,
1756 * the key gives the field name, and the value gives the data
1757 * to set that field to. The data will be quoted by
1758 * DatabaseBase::addQuotes().
1760 * @param $conds Array: An array of conditions (WHERE). See
1761 * DatabaseBase::select() for the details of the format of
1762 * condition arrays. Use '*' to update all rows.
1764 * @param $fname String: The function name of the caller (from __METHOD__),
1765 * for logging and profiling.
1767 * @param $options Array: An array of UPDATE options, can be:
1768 * - IGNORE: Ignore unique key conflicts
1769 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1772 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1773 $table = $this->tableName( $table );
1774 $opts = $this->makeUpdateOptions( $options );
1775 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1777 if ( $conds !== array() && $conds !== '*' ) {
1778 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1781 return $this->query( $sql, $fname );
1785 * Makes an encoded list of strings from an array
1786 * @param $a Array containing the data
1787 * @param $mode int Constant
1788 * - LIST_COMMA: comma separated, no field names
1789 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1790 * the documentation for $conds in DatabaseBase::select().
1791 * - LIST_OR: ORed WHERE clause (without the WHERE)
1792 * - LIST_SET: comma separated with field names, like a SET clause
1793 * - LIST_NAMES: comma separated field names
1797 function makeList( $a, $mode = LIST_COMMA
) {
1798 if ( !is_array( $a ) ) {
1799 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1805 foreach ( $a as $field => $value ) {
1807 if ( $mode == LIST_AND
) {
1809 } elseif ( $mode == LIST_OR
) {
1818 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1819 $list .= "($value)";
1820 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1822 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1823 if ( count( $value ) == 0 ) {
1824 throw new MWException( __METHOD__
. ': empty input' );
1825 } elseif ( count( $value ) == 1 ) {
1826 // Special-case single values, as IN isn't terribly efficient
1827 // Don't necessarily assume the single key is 0; we don't
1828 // enforce linear numeric ordering on other arrays here.
1829 $value = array_values( $value );
1830 $list .= $field . " = " . $this->addQuotes( $value[0] );
1832 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1834 } elseif ( $value === null ) {
1835 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1836 $list .= "$field IS ";
1837 } elseif ( $mode == LIST_SET
) {
1838 $list .= "$field = ";
1842 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1843 $list .= "$field = ";
1845 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1853 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1854 * The keys on each level may be either integers or strings.
1856 * @param $data Array: organized as 2-d
1857 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1858 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1859 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1860 * @return Mixed: string SQL fragment, or false if no items in array.
1862 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1865 foreach ( $data as $base => $sub ) {
1866 if ( count( $sub ) ) {
1867 $conds[] = $this->makeList(
1868 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1874 return $this->makeList( $conds, LIST_OR
);
1876 // Nothing to search for...
1882 * Bitwise operations
1889 function bitNot( $field ) {
1895 * @param $fieldRight
1898 function bitAnd( $fieldLeft, $fieldRight ) {
1899 return "($fieldLeft & $fieldRight)";
1904 * @param $fieldRight
1907 function bitOr( $fieldLeft, $fieldRight ) {
1908 return "($fieldLeft | $fieldRight)";
1912 * Change the current database
1914 * @todo Explain what exactly will fail if this is not overridden.
1918 * @return bool Success or failure
1920 function selectDB( $db ) {
1921 # Stub. Shouldn't cause serious problems if it's not overridden, but
1922 # if your database engine supports a concept similar to MySQL's
1923 # databases you may as well.
1924 $this->mDBname
= $db;
1929 * Get the current DB name
1931 function getDBname() {
1932 return $this->mDBname
;
1936 * Get the server hostname or IP address
1938 function getServer() {
1939 return $this->mServer
;
1943 * Format a table name ready for use in constructing an SQL query
1945 * This does two important things: it quotes the table names to clean them up,
1946 * and it adds a table prefix if only given a table name with no quotes.
1948 * All functions of this object which require a table name call this function
1949 * themselves. Pass the canonical name to such functions. This is only needed
1950 * when calling query() directly.
1952 * @param $name String: database table name
1953 * @param $format String One of:
1954 * quoted - Automatically pass the table name through addIdentifierQuotes()
1955 * so that it can be used in a query.
1956 * raw - Do not add identifier quotes to the table name
1957 * @return String: full database name
1959 function tableName( $name, $format = 'quoted' ) {
1960 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1961 # Skip the entire process when we have a string quoted on both ends.
1962 # Note that we check the end so that we will still quote any use of
1963 # use of `database`.table. But won't break things if someone wants
1964 # to query a database table with a dot in the name.
1965 if ( $this->isQuotedIdentifier( $name ) ) {
1969 # Lets test for any bits of text that should never show up in a table
1970 # name. Basically anything like JOIN or ON which are actually part of
1971 # SQL queries, but may end up inside of the table value to combine
1972 # sql. Such as how the API is doing.
1973 # Note that we use a whitespace test rather than a \b test to avoid
1974 # any remote case where a word like on may be inside of a table name
1975 # surrounded by symbols which may be considered word breaks.
1976 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1980 # Split database and table into proper variables.
1981 # We reverse the explode so that database.table and table both output
1982 # the correct table.
1983 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1984 if ( isset( $dbDetails[1] ) ) {
1985 list( $table, $database ) = $dbDetails;
1987 list( $table ) = $dbDetails;
1989 $prefix = $this->mTablePrefix
; # Default prefix
1991 # A database name has been specified in input. We don't want any
1993 if ( isset( $database ) ) {
1997 # Note that we use the long format because php will complain in in_array if
1998 # the input is not an array, and will complain in is_array if it is not set.
1999 if ( !isset( $database ) # Don't use shared database if pre selected.
2000 && isset( $wgSharedDB ) # We have a shared database
2001 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
2002 && isset( $wgSharedTables )
2003 && is_array( $wgSharedTables )
2004 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
2005 $database = $wgSharedDB;
2006 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
2009 # Quote the $database and $table and apply the prefix if not quoted.
2010 if ( isset( $database ) ) {
2011 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
2014 $table = "{$prefix}{$table}";
2015 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
2016 $table = $this->addIdentifierQuotes( "{$table}" );
2019 # Merge our database and table into our final table name.
2020 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
2026 * Fetch a number of table names into an array
2027 * This is handy when you need to construct SQL for joins
2030 * extract($dbr->tableNames('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 tableNames() {
2037 $inArray = func_get_args();
2040 foreach ( $inArray as $name ) {
2041 $retVal[$name] = $this->tableName( $name );
2048 * Fetch a number of table names into an zero-indexed numerical array
2049 * This is handy when you need to construct SQL for joins
2052 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2053 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2054 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2058 public function tableNamesN() {
2059 $inArray = func_get_args();
2062 foreach ( $inArray as $name ) {
2063 $retVal[] = $this->tableName( $name );
2070 * Get an aliased table name
2071 * e.g. tableName AS newTableName
2073 * @param $name string Table name, see tableName()
2074 * @param $alias string|bool Alias (optional)
2075 * @return string SQL name for aliased table. Will not alias a table to its own name
2077 public function tableNameWithAlias( $name, $alias = false ) {
2078 if ( !$alias ||
$alias == $name ) {
2079 return $this->tableName( $name );
2081 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2086 * Gets an array of aliased table names
2088 * @param $tables array( [alias] => table )
2089 * @return array of strings, see tableNameWithAlias()
2091 public function tableNamesWithAlias( $tables ) {
2093 foreach ( $tables as $alias => $table ) {
2094 if ( is_numeric( $alias ) ) {
2097 $retval[] = $this->tableNameWithAlias( $table, $alias );
2103 * Get the aliased table name clause for a FROM clause
2104 * which might have a JOIN and/or USE INDEX clause
2106 * @param $tables array ( [alias] => table )
2107 * @param $use_index array Same as for select()
2108 * @param $join_conds array Same as for select()
2111 protected function tableNamesWithUseIndexOrJOIN(
2112 $tables, $use_index = array(), $join_conds = array()
2116 $use_index = (array)$use_index;
2117 $join_conds = (array)$join_conds;
2119 foreach ( $tables as $alias => $table ) {
2120 if ( !is_string( $alias ) ) {
2121 // No alias? Set it equal to the table name
2124 // Is there a JOIN clause for this table?
2125 if ( isset( $join_conds[$alias] ) ) {
2126 list( $joinType, $conds ) = $join_conds[$alias];
2127 $tableClause = $joinType;
2128 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2129 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2130 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2132 $tableClause .= ' ' . $use;
2135 $on = $this->makeList( (array)$conds, LIST_AND
);
2137 $tableClause .= ' ON (' . $on . ')';
2140 $retJOIN[] = $tableClause;
2141 // Is there an INDEX clause for this table?
2142 } elseif ( isset( $use_index[$alias] ) ) {
2143 $tableClause = $this->tableNameWithAlias( $table, $alias );
2144 $tableClause .= ' ' . $this->useIndexClause(
2145 implode( ',', (array)$use_index[$alias] ) );
2147 $ret[] = $tableClause;
2149 $tableClause = $this->tableNameWithAlias( $table, $alias );
2151 $ret[] = $tableClause;
2155 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2156 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2157 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2159 // Compile our final table clause
2160 return implode( ' ', array( $straightJoins, $otherJoins ) );
2164 * Get the name of an index in a given table
2170 function indexName( $index ) {
2171 // Backwards-compatibility hack
2173 'ar_usertext_timestamp' => 'usertext_timestamp',
2174 'un_user_id' => 'user_id',
2175 'un_user_ip' => 'user_ip',
2178 if ( isset( $renamed[$index] ) ) {
2179 return $renamed[$index];
2186 * If it's a string, adds quotes and backslashes
2187 * Otherwise returns as-is
2193 function addQuotes( $s ) {
2194 if ( $s === null ) {
2197 # This will also quote numeric values. This should be harmless,
2198 # and protects against weird problems that occur when they really
2199 # _are_ strings such as article titles and string->number->string
2200 # conversion is not 1:1.
2201 return "'" . $this->strencode( $s ) . "'";
2206 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2207 * MySQL uses `backticks` while basically everything else uses double quotes.
2208 * Since MySQL is the odd one out here the double quotes are our generic
2209 * and we implement backticks in DatabaseMysql.
2215 public function addIdentifierQuotes( $s ) {
2216 return '"' . str_replace( '"', '""', $s ) . '"';
2220 * Returns if the given identifier looks quoted or not according to
2221 * the database convention for quoting identifiers .
2223 * @param $name string
2227 public function isQuotedIdentifier( $name ) {
2228 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2232 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2233 * which used quote_ident which does not follow our naming conventions
2234 * was renamed to addIdentifierQuotes.
2235 * @deprecated since 1.18 use addIdentifierQuotes
2241 function quote_ident( $s ) {
2242 wfDeprecated( __METHOD__
, '1.18' );
2243 return $this->addIdentifierQuotes( $s );
2247 * Escape string for safe LIKE usage.
2248 * WARNING: you should almost never use this function directly,
2249 * instead use buildLike() that escapes everything automatically
2250 * @deprecated since 1.17, warnings in 1.17, removed in ???
2256 public function escapeLike( $s ) {
2257 wfDeprecated( __METHOD__
, '1.17' );
2258 return $this->escapeLikeInternal( $s );
2265 protected function escapeLikeInternal( $s ) {
2266 $s = str_replace( '\\', '\\\\', $s );
2267 $s = $this->strencode( $s );
2268 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2274 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2275 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2276 * Alternatively, the function could be provided with an array of aforementioned parameters.
2278 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2279 * for subpages of 'My page title'.
2280 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2283 * @return String: fully built LIKE statement
2285 function buildLike() {
2286 $params = func_get_args();
2288 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2289 $params = $params[0];
2294 foreach ( $params as $value ) {
2295 if ( $value instanceof LikeMatch
) {
2296 $s .= $value->toString();
2298 $s .= $this->escapeLikeInternal( $value );
2302 return " LIKE '" . $s . "' ";
2306 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2310 function anyChar() {
2311 return new LikeMatch( '_' );
2315 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2319 function anyString() {
2320 return new LikeMatch( '%' );
2324 * Returns an appropriately quoted sequence value for inserting a new row.
2325 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2326 * subclass will return an integer, and save the value for insertId()
2328 * Any implementation of this function should *not* involve reusing
2329 * sequence numbers created for rolled-back transactions.
2330 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2331 * @param $seqName string
2334 function nextSequenceValue( $seqName ) {
2339 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2340 * is only needed because a) MySQL must be as efficient as possible due to
2341 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2342 * which index to pick. Anyway, other databases might have different
2343 * indexes on a given table. So don't bother overriding this unless you're
2348 function useIndexClause( $index ) {
2353 * REPLACE query wrapper.
2355 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2356 * except that when there is a duplicate key error, the old row is deleted
2357 * and the new row is inserted in its place.
2359 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2360 * perform the delete, we need to know what the unique indexes are so that
2361 * we know how to find the conflicting rows.
2363 * It may be more efficient to leave off unique indexes which are unlikely
2364 * to collide. However if you do this, you run the risk of encountering
2365 * errors which wouldn't have occurred in MySQL.
2367 * @param $table String: The table to replace the row(s) in.
2368 * @param $rows array Can be either a single row to insert, or multiple rows,
2369 * in the same format as for DatabaseBase::insert()
2370 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2371 * a field name or an array of field names
2372 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2374 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2375 $quotedTable = $this->tableName( $table );
2377 if ( count( $rows ) == 0 ) {
2382 if ( !is_array( reset( $rows ) ) ) {
2383 $rows = array( $rows );
2386 foreach( $rows as $row ) {
2387 # Delete rows which collide
2388 if ( $uniqueIndexes ) {
2389 $sql = "DELETE FROM $quotedTable WHERE ";
2391 foreach ( $uniqueIndexes as $index ) {
2398 if ( is_array( $index ) ) {
2400 foreach ( $index as $col ) {
2406 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2409 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2413 $this->query( $sql, $fname );
2416 # Now insert the row
2417 $this->insert( $table, $row );
2422 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2425 * @param $table string Table name
2426 * @param $rows array Rows to insert
2427 * @param $fname string Caller function name
2429 * @return ResultWrapper
2431 protected function nativeReplace( $table, $rows, $fname ) {
2432 $table = $this->tableName( $table );
2435 if ( !is_array( reset( $rows ) ) ) {
2436 $rows = array( $rows );
2439 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2442 foreach ( $rows as $row ) {
2449 $sql .= '(' . $this->makeList( $row ) . ')';
2452 return $this->query( $sql, $fname );
2456 * DELETE where the condition is a join.
2458 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2459 * we use sub-selects
2461 * For safety, an empty $conds will not delete everything. If you want to
2462 * delete all rows where the join condition matches, set $conds='*'.
2464 * DO NOT put the join condition in $conds.
2466 * @param $delTable String: The table to delete from.
2467 * @param $joinTable String: The other table.
2468 * @param $delVar String: The variable to join on, in the first table.
2469 * @param $joinVar String: The variable to join on, in the second table.
2470 * @param $conds Array: Condition array of field names mapped to variables,
2471 * ANDed together in the WHERE clause
2472 * @param $fname String: Calling function name (use __METHOD__) for
2475 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2476 $fname = 'DatabaseBase::deleteJoin' )
2479 throw new DBUnexpectedError( $this,
2480 'DatabaseBase::deleteJoin() called with empty $conds' );
2483 $delTable = $this->tableName( $delTable );
2484 $joinTable = $this->tableName( $joinTable );
2485 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2486 if ( $conds != '*' ) {
2487 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2491 $this->query( $sql, $fname );
2495 * Returns the size of a text field, or -1 for "unlimited"
2497 * @param $table string
2498 * @param $field string
2502 function textFieldSize( $table, $field ) {
2503 $table = $this->tableName( $table );
2504 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2505 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2506 $row = $this->fetchObject( $res );
2510 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2520 * A string to insert into queries to show that they're low-priority, like
2521 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2522 * string and nothing bad should happen.
2524 * @return string Returns the text of the low priority option if it is
2525 * supported, or a blank string otherwise
2527 function lowPriorityOption() {
2532 * DELETE query wrapper.
2534 * @param $table Array Table name
2535 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2536 * the format. Use $conds == "*" to delete all rows
2537 * @param $fname String name of the calling function
2541 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2543 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2546 $table = $this->tableName( $table );
2547 $sql = "DELETE FROM $table";
2549 if ( $conds != '*' ) {
2550 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2553 return $this->query( $sql, $fname );
2557 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2558 * into another table.
2560 * @param $destTable string The table name to insert into
2561 * @param $srcTable string|array May be either a table name, or an array of table names
2562 * to include in a join.
2564 * @param $varMap array must be an associative array of the form
2565 * array( 'dest1' => 'source1', ...). Source items may be literals
2566 * rather than field names, but strings should be quoted with
2567 * DatabaseBase::addQuotes()
2569 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2570 * the details of the format of condition arrays. May be "*" to copy the
2573 * @param $fname string The function name of the caller, from __METHOD__
2575 * @param $insertOptions array Options for the INSERT part of the query, see
2576 * DatabaseBase::insert() for details.
2577 * @param $selectOptions array Options for the SELECT part of the query, see
2578 * DatabaseBase::select() for details.
2580 * @return ResultWrapper
2582 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2583 $fname = 'DatabaseBase::insertSelect',
2584 $insertOptions = array(), $selectOptions = array() )
2586 $destTable = $this->tableName( $destTable );
2588 if ( is_array( $insertOptions ) ) {
2589 $insertOptions = implode( ' ', $insertOptions );
2592 if ( !is_array( $selectOptions ) ) {
2593 $selectOptions = array( $selectOptions );
2596 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2598 if ( is_array( $srcTable ) ) {
2599 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2601 $srcTable = $this->tableName( $srcTable );
2604 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2605 " SELECT $startOpts " . implode( ',', $varMap ) .
2606 " FROM $srcTable $useIndex ";
2608 if ( $conds != '*' ) {
2609 if ( is_array( $conds ) ) {
2610 $conds = $this->makeList( $conds, LIST_AND
);
2612 $sql .= " WHERE $conds";
2615 $sql .= " $tailOpts";
2617 return $this->query( $sql, $fname );
2621 * Construct a LIMIT query with optional offset. This is used for query
2622 * pages. The SQL should be adjusted so that only the first $limit rows
2623 * are returned. If $offset is provided as well, then the first $offset
2624 * rows should be discarded, and the next $limit rows should be returned.
2625 * If the result of the query is not ordered, then the rows to be returned
2626 * are theoretically arbitrary.
2628 * $sql is expected to be a SELECT, if that makes a difference. For
2629 * UPDATE, limitResultForUpdate should be used.
2631 * The version provided by default works in MySQL and SQLite. It will very
2632 * likely need to be overridden for most other DBMSes.
2634 * @param $sql String SQL query we will append the limit too
2635 * @param $limit Integer the SQL limit
2636 * @param $offset Integer|bool the SQL offset (default false)
2640 function limitResult( $sql, $limit, $offset = false ) {
2641 if ( !is_numeric( $limit ) ) {
2642 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2645 return "$sql LIMIT "
2646 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2655 function limitResultForUpdate( $sql, $num ) {
2656 return $this->limitResult( $sql, $num, 0 );
2660 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2661 * within the UNION construct.
2664 function unionSupportsOrderAndLimit() {
2665 return true; // True for almost every DB supported
2669 * Construct a UNION query
2670 * This is used for providing overload point for other DB abstractions
2671 * not compatible with the MySQL syntax.
2672 * @param $sqls Array: SQL statements to combine
2673 * @param $all Boolean: use UNION ALL
2674 * @return String: SQL fragment
2676 function unionQueries( $sqls, $all ) {
2677 $glue = $all ?
') UNION ALL (' : ') UNION (';
2678 return '(' . implode( $glue, $sqls ) . ')';
2682 * Returns an SQL expression for a simple conditional. This doesn't need
2683 * to be overridden unless CASE isn't supported in your DBMS.
2685 * @param $cond String: SQL expression which will result in a boolean value
2686 * @param $trueVal String: SQL expression to return if true
2687 * @param $falseVal String: SQL expression to return if false
2688 * @return String: SQL fragment
2690 function conditional( $cond, $trueVal, $falseVal ) {
2691 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2695 * Returns a comand for str_replace function in SQL query.
2696 * Uses REPLACE() in MySQL
2698 * @param $orig String: column to modify
2699 * @param $old String: column to seek
2700 * @param $new String: column to replace with
2704 function strreplace( $orig, $old, $new ) {
2705 return "REPLACE({$orig}, {$old}, {$new})";
2709 * Determines how long the server has been up
2714 function getServerUptime() {
2719 * Determines if the last failure was due to a deadlock
2724 function wasDeadlock() {
2729 * Determines if the last failure was due to a lock timeout
2734 function wasLockTimeout() {
2739 * Determines if the last query error was something that should be dealt
2740 * with by pinging the connection and reissuing the query.
2745 function wasErrorReissuable() {
2750 * Determines if the last failure was due to the database being read-only.
2755 function wasReadOnlyError() {
2760 * Perform a deadlock-prone transaction.
2762 * This function invokes a callback function to perform a set of write
2763 * queries. If a deadlock occurs during the processing, the transaction
2764 * will be rolled back and the callback function will be called again.
2767 * $dbw->deadlockLoop( callback, ... );
2769 * Extra arguments are passed through to the specified callback function.
2771 * Returns whatever the callback function returned on its successful,
2772 * iteration, or false on error, for example if the retry limit was
2777 function deadlockLoop() {
2779 $this->begin( __METHOD__
);
2780 $args = func_get_args();
2781 $function = array_shift( $args );
2782 $oldIgnore = $this->ignoreErrors( true );
2783 $tries = DEADLOCK_TRIES
;
2785 if ( is_array( $function ) ) {
2786 $fname = $function[0];
2792 $retVal = call_user_func_array( $function, $args );
2793 $error = $this->lastError();
2794 $errno = $this->lastErrno();
2795 $sql = $this->lastQuery();
2798 if ( $this->wasDeadlock() ) {
2800 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2802 $this->reportQueryError( $error, $errno, $sql, $fname );
2805 } while ( $this->wasDeadlock() && --$tries > 0 );
2807 $this->ignoreErrors( $oldIgnore );
2809 if ( $tries <= 0 ) {
2810 $this->rollback( __METHOD__
);
2811 $this->reportQueryError( $error, $errno, $sql, $fname );
2814 $this->commit( __METHOD__
);
2820 * Wait for the slave to catch up to a given master position.
2822 * @param $pos DBMasterPos object
2823 * @param $timeout Integer: the maximum number of seconds to wait for
2826 * @return integer: zero if the slave was past that position already,
2827 * greater than zero if we waited for some period of time, less than
2828 * zero if we timed out.
2830 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2831 wfProfileIn( __METHOD__
);
2833 if ( !is_null( $this->mFakeSlaveLag
) ) {
2834 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2836 if ( $wait > $timeout * 1e6
) {
2837 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2838 wfProfileOut( __METHOD__
);
2840 } elseif ( $wait > 0 ) {
2841 wfDebug( "Fake slave waiting $wait us\n" );
2843 wfProfileOut( __METHOD__
);
2846 wfDebug( "Fake slave up to date ($wait us)\n" );
2847 wfProfileOut( __METHOD__
);
2852 wfProfileOut( __METHOD__
);
2854 # Real waits are implemented in the subclass.
2859 * Get the replication position of this slave
2861 * @return DBMasterPos, or false if this is not a slave.
2863 function getSlavePos() {
2864 if ( !is_null( $this->mFakeSlaveLag
) ) {
2865 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2866 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2875 * Get the position of this master
2877 * @return DBMasterPos, or false if this is not a master
2879 function getMasterPos() {
2880 if ( $this->mFakeMaster
) {
2881 return new MySQLMasterPos( 'fake', microtime( true ) );
2888 * Begin a transaction, committing any previously open transaction
2890 * @param $fname string
2892 function begin( $fname = 'DatabaseBase::begin' ) {
2893 $this->query( 'BEGIN', $fname );
2894 $this->mTrxLevel
= 1;
2900 * @param $fname string
2902 function commit( $fname = 'DatabaseBase::commit' ) {
2903 if ( $this->mTrxLevel
) {
2904 $this->query( 'COMMIT', $fname );
2905 $this->mTrxLevel
= 0;
2910 * Rollback a transaction.
2911 * No-op on non-transactional databases.
2913 * @param $fname string
2915 function rollback( $fname = 'DatabaseBase::rollback' ) {
2916 if ( $this->mTrxLevel
) {
2917 $this->query( 'ROLLBACK', $fname, true );
2918 $this->mTrxLevel
= 0;
2923 * Creates a new table with structure copied from existing table
2924 * Note that unlike most database abstraction functions, this function does not
2925 * automatically append database prefix, because it works at a lower
2926 * abstraction level.
2927 * The table names passed to this function shall not be quoted (this
2928 * function calls addIdentifierQuotes when needed).
2930 * @param $oldName String: name of table whose structure should be copied
2931 * @param $newName String: name of table to be created
2932 * @param $temporary Boolean: whether the new table should be temporary
2933 * @param $fname String: calling function name
2934 * @return Boolean: true if operation was successful
2936 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2937 $fname = 'DatabaseBase::duplicateTableStructure' )
2939 throw new MWException(
2940 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2944 * List all tables on the database
2946 * @param $prefix string Only show tables with this prefix, e.g. mw_
2947 * @param $fname String: calling function name
2949 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2950 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2954 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2955 * to the format used for inserting into timestamp fields in this DBMS.
2957 * The result is unquoted, and needs to be passed through addQuotes()
2958 * before it can be included in raw SQL.
2960 * @param $ts string|int
2964 function timestamp( $ts = 0 ) {
2965 return wfTimestamp( TS_MW
, $ts );
2969 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2970 * to the format used for inserting into timestamp fields in this DBMS. If
2971 * NULL is input, it is passed through, allowing NULL values to be inserted
2972 * into timestamp fields.
2974 * The result is unquoted, and needs to be passed through addQuotes()
2975 * before it can be included in raw SQL.
2977 * @param $ts string|int
2981 function timestampOrNull( $ts = null ) {
2982 if ( is_null( $ts ) ) {
2985 return $this->timestamp( $ts );
2990 * Take the result from a query, and wrap it in a ResultWrapper if
2991 * necessary. Boolean values are passed through as is, to indicate success
2992 * of write queries or failure.
2994 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2995 * resource, and it was necessary to call this function to convert it to
2996 * a wrapper. Nowadays, raw database objects are never exposed to external
2997 * callers, so this is unnecessary in external code. For compatibility with
2998 * old code, ResultWrapper objects are passed through unaltered.
3000 * @param $result bool|ResultWrapper
3002 * @return bool|ResultWrapper
3004 function resultObject( $result ) {
3005 if ( empty( $result ) ) {
3007 } elseif ( $result instanceof ResultWrapper
) {
3009 } elseif ( $result === true ) {
3010 // Successful write query
3013 return new ResultWrapper( $this, $result );
3018 * Return aggregated value alias
3021 * @param $valuename string
3025 function aggregateValue ( $valuedata, $valuename = 'value' ) {
3030 * Ping the server and try to reconnect if it there is no connection
3032 * @return bool Success or failure
3035 # Stub. Not essential to override.
3040 * Get slave lag. Currently supported only by MySQL.
3042 * Note that this function will generate a fatal error on many
3043 * installations. Most callers should use LoadBalancer::safeGetLag()
3046 * @return int Database replication lag in seconds
3049 return intval( $this->mFakeSlaveLag
);
3053 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3057 function maxListLen() {
3062 * Some DBMSs have a special format for inserting into blob fields, they
3063 * don't allow simple quoted strings to be inserted. To insert into such
3064 * a field, pass the data through this function before passing it to
3065 * DatabaseBase::insert().
3069 function encodeBlob( $b ) {
3074 * Some DBMSs return a special placeholder object representing blob fields
3075 * in result objects. Pass the object through this function to return the
3080 function decodeBlob( $b ) {
3085 * Override database's default connection timeout
3087 * @param $timeout Integer in seconds
3089 * @deprecated since 1.19; use setSessionOptions()
3091 public function setTimeout( $timeout ) {
3092 wfDeprecated( __METHOD__
, '1.19' );
3093 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3097 * Override database's default behavior. $options include:
3098 * 'connTimeout' : Set the connection timeout value in seconds.
3099 * May be useful for very long batch queries such as
3100 * full-wiki dumps, where a single query reads out over
3103 * @param $options Array
3106 public function setSessionOptions( array $options ) {}
3109 * Read and execute SQL commands from a file.
3111 * Returns true on success, error string or exception on failure (depending
3112 * on object's error ignore settings).
3114 * @param $filename String: File name to open
3115 * @param $lineCallback Callback: Optional function called before reading each line
3116 * @param $resultCallback Callback: Optional function called for each MySQL result
3117 * @param $fname String: Calling function name or false if name should be
3118 * generated dynamically using $filename
3119 * @return bool|string
3121 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3122 wfSuppressWarnings();
3123 $fp = fopen( $filename, 'r' );
3124 wfRestoreWarnings();
3126 if ( false === $fp ) {
3127 throw new MWException( "Could not open \"{$filename}\".\n" );
3131 $fname = __METHOD__
. "( $filename )";
3135 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3137 catch ( MWException
$e ) {
3148 * Get the full path of a patch file. Originally based on archive()
3149 * from updaters.inc. Keep in mind this always returns a patch, as
3150 * it fails back to MySQL if no DB-specific patch can be found
3152 * @param $patch String The name of the patch, like patch-something.sql
3153 * @return String Full path to patch file
3155 public function patchPath( $patch ) {
3158 $dbType = $this->getType();
3159 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3160 return "$IP/maintenance/$dbType/archives/$patch";
3162 return "$IP/maintenance/archives/$patch";
3167 * Set variables to be used in sourceFile/sourceStream, in preference to the
3168 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3169 * all. If it's set to false, $GLOBALS will be used.
3171 * @param $vars bool|array mapping variable name to value.
3173 function setSchemaVars( $vars ) {
3174 $this->mSchemaVars
= $vars;
3178 * Read and execute commands from an open file handle.
3180 * Returns true on success, error string or exception on failure (depending
3181 * on object's error ignore settings).
3183 * @param $fp Resource: File handle
3184 * @param $lineCallback Callback: Optional function called before reading each line
3185 * @param $resultCallback Callback: Optional function called for each MySQL result
3186 * @param $fname String: Calling function name
3187 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3188 * @return bool|string
3190 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3191 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3195 while ( !feof( $fp ) ) {
3196 if ( $lineCallback ) {
3197 call_user_func( $lineCallback );
3200 $line = trim( fgets( $fp ) );
3202 if ( $line == '' ) {
3206 if ( '-' == $line[0] && '-' == $line[1] ) {
3214 $done = $this->streamStatementEnd( $cmd, $line );
3218 if ( $done ||
feof( $fp ) ) {
3219 $cmd = $this->replaceVars( $cmd );
3220 if ( $inputCallback ) {
3221 call_user_func( $inputCallback, $cmd );
3223 $res = $this->query( $cmd, $fname );
3225 if ( $resultCallback ) {
3226 call_user_func( $resultCallback, $res, $this );
3229 if ( false === $res ) {
3230 $err = $this->lastError();
3231 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3242 * Called by sourceStream() to check if we've reached a statement end
3244 * @param $sql String SQL assembled so far
3245 * @param $newLine String New line about to be added to $sql
3246 * @return Bool Whether $newLine contains end of the statement
3248 public function streamStatementEnd( &$sql, &$newLine ) {
3249 if ( $this->delimiter
) {
3251 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3252 if ( $newLine != $prev ) {
3260 * Database independent variable replacement. Replaces a set of variables
3261 * in an SQL statement with their contents as given by $this->getSchemaVars().
3263 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3265 * - '{$var}' should be used for text and is passed through the database's
3267 * - `{$var}` should be used for identifiers (eg: table and database names),
3268 * it is passed through the database's addIdentifierQuotes method which
3269 * can be overridden if the database uses something other than backticks.
3270 * - / *$var* / is just encoded, besides traditional table prefix and
3271 * table options its use should be avoided.
3273 * @param $ins String: SQL statement to replace variables in
3274 * @return String The new SQL statement with variables replaced
3276 protected function replaceSchemaVars( $ins ) {
3277 $vars = $this->getSchemaVars();
3278 foreach ( $vars as $var => $value ) {
3280 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3282 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3284 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3290 * Replace variables in sourced SQL
3292 * @param $ins string
3296 protected function replaceVars( $ins ) {
3297 $ins = $this->replaceSchemaVars( $ins );
3300 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3301 array( $this, 'tableNameCallback' ), $ins );
3304 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3305 array( $this, 'indexNameCallback' ), $ins );
3311 * Get schema variables. If none have been set via setSchemaVars(), then
3312 * use some defaults from the current object.
3316 protected function getSchemaVars() {
3317 if ( $this->mSchemaVars
) {
3318 return $this->mSchemaVars
;
3320 return $this->getDefaultSchemaVars();
3325 * Get schema variables to use if none have been set via setSchemaVars().
3327 * Override this in derived classes to provide variables for tables.sql
3328 * and SQL patch files.
3332 protected function getDefaultSchemaVars() {
3337 * Table name callback
3339 * @param $matches array
3343 protected function tableNameCallback( $matches ) {
3344 return $this->tableName( $matches[1] );
3348 * Index name callback
3350 * @param $matches array
3354 protected function indexNameCallback( $matches ) {
3355 return $this->indexName( $matches[1] );
3359 * Build a concatenation list to feed into a SQL query
3360 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3363 function buildConcat( $stringList ) {
3364 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3368 * Check to see if a named lock is available. This is non-blocking.
3370 * @param $lockName String: name of lock to poll
3371 * @param $method String: name of method calling us
3375 public function lockIsFree( $lockName, $method ) {
3380 * Acquire a named lock
3382 * Abstracted from Filestore::lock() so child classes can implement for
3385 * @param $lockName String: name of lock to aquire
3386 * @param $method String: name of method calling us
3387 * @param $timeout Integer: timeout
3390 public function lock( $lockName, $method, $timeout = 5 ) {
3397 * @param $lockName String: Name of lock to release
3398 * @param $method String: Name of method calling us
3400 * @return int Returns 1 if the lock was released, 0 if the lock was not established
3401 * by this thread (in which case the lock is not released), and NULL if the named
3402 * lock did not exist
3404 public function unlock( $lockName, $method ) {
3409 * Lock specific tables
3411 * @param $read Array of tables to lock for read access
3412 * @param $write Array of tables to lock for write access
3413 * @param $method String name of caller
3414 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3418 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3423 * Unlock specific tables
3425 * @param $method String the caller
3429 public function unlockTables( $method ) {
3435 * @param $tableName string
3436 * @param $fName string
3437 * @return bool|ResultWrapper
3440 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3441 if( !$this->tableExists( $tableName, $fName ) ) {
3444 $sql = "DROP TABLE " . $this->tableName( $tableName );
3445 if( $this->cascadingDeletes() ) {
3448 return $this->query( $sql, $fName );
3452 * Get search engine class. All subclasses of this need to implement this
3453 * if they wish to use searching.
3457 public function getSearchEngine() {
3458 return 'SearchEngineDummy';
3462 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3463 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3464 * because "i" sorts after all numbers.
3468 public function getInfinity() {
3473 * Encode an expiry time into the DBMS dependent format
3475 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3478 public function encodeExpiry( $expiry ) {
3479 return ( $expiry == '' ||
$expiry == 'infinity' ||
$expiry == $this->getInfinity() )
3480 ?
$this->getInfinity()
3481 : $this->timestamp( $expiry );
3485 * Decode an expiry time into a DBMS independent format
3487 * @param $expiry String: DB timestamp field value for expiry
3488 * @param $format integer: TS_* constant, defaults to TS_MW
3491 public function decodeExpiry( $expiry, $format = TS_MW
) {
3492 return ( $expiry == '' ||
$expiry == $this->getInfinity() )
3494 : wfTimestamp( $format, $expiry );
3498 * Allow or deny "big selects" for this session only. This is done by setting
3499 * the sql_big_selects session variable.
3501 * This is a MySQL-specific feature.
3503 * @param $value Mixed: true for allow, false for deny, or "default" to
3504 * restore the initial value
3506 public function setBigSelects( $value = true ) {