3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * Fetch the next row from the given result object, in object form.
47 * Fields can be retrieved with $row->fieldname, with fields acting like
50 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
52 * @throws DBUnexpectedError Thrown if the database returns an error
54 function fetchObject( $res );
57 * Fetch the next row from the given result object, in associative array
58 * form. Fields are retrieved with $row['fieldname'].
60 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchRow( $res );
67 * Get the number of rows in a result object
69 * @param $res Mixed: A SQL result
72 function numRows( $res );
75 * Get the number of fields in a result object
76 * @see http://www.php.net/mysql_num_fields
78 * @param $res Mixed: A SQL result
81 function numFields( $res );
84 * Get a field name in a result object
85 * @see http://www.php.net/mysql_field_name
87 * @param $res Mixed: A SQL result
91 function fieldName( $res, $n );
94 * Get the inserted value of an auto-increment row
96 * The value inserted should be fetched from nextSequenceValue()
99 * $id = $dbw->nextSequenceValue('page_page_id_seq');
100 * $dbw->insert('page',array('page_id' => $id));
101 * $id = $dbw->insertId();
108 * Change the position of the cursor in a result object
109 * @see http://www.php.net/mysql_data_seek
111 * @param $res Mixed: A SQL result
112 * @param $row Mixed: Either MySQL row or ResultWrapper
114 function dataSeek( $res, $row );
117 * Get the last error number
118 * @see http://www.php.net/mysql_errno
122 function lastErrno();
125 * Get a description of the last error
126 * @see http://www.php.net/mysql_error
130 function lastError();
133 * mysql_fetch_field() wrapper
134 * Returns false if the field doesn't exist
136 * @param $table string: table name
137 * @param $field string: field name
141 function fieldInfo( $table, $field );
144 * Get information about an index into an object
145 * @param $table string: Table name
146 * @param $index string: Index name
147 * @param $fname string: Calling function name
148 * @return Mixed: Database-specific index description class or false if the index does not exist
150 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info().
182 * @return string: Version information from the database server.
184 function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 function getServerInfo();
197 * Database abstraction object
200 abstract class DatabaseBase
implements DatabaseType
{
202 # ------------------------------------------------------------------------------
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mDBname;
215 protected $mConn = null;
216 protected $mOpened = false;
218 protected $mTablePrefix;
220 protected $mTrxLevel = 0;
221 protected $mErrorCount = 0;
222 protected $mLBInfo = array();
223 protected $mFakeSlaveLag = null, $mFakeMaster = false;
224 protected $mDefaultBigSelects = null;
225 protected $mSchemaVars = false;
227 # ------------------------------------------------------------------------------
229 # ------------------------------------------------------------------------------
230 # These optionally set a variable and return the previous state
233 * A string describing the current software version, and possibly
234 * other details in a user-friendly way. Will be listed on Special:Version, etc.
235 * Use getServerVersion() to get machine-friendly information.
237 * @return string: Version information from the database server
239 public function getServerInfo() {
240 return $this->getServerVersion();
244 * Boolean, controls output of large amounts of debug information.
246 * - true to enable debugging
247 * - false to disable debugging
248 * - omitted or null to do nothing
250 * @return The previous value of the flag
252 function debug( $debug = null ) {
253 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
257 * Turns buffering of SQL result sets on (true) or off (false). Default is
260 * Unbuffered queries are very troublesome in MySQL:
262 * - If another query is executed while the first query is being read
263 * out, the first query is killed. This means you can't call normal
264 * MediaWiki functions while you are reading an unbuffered query result
265 * from a normal wfGetDB() connection.
267 * - Unbuffered queries cause the MySQL server to use large amounts of
268 * memory and to hold broad locks which block other queries.
270 * If you want to limit client-side memory, it's almost always better to
271 * split up queries into batches using a LIMIT clause than to switch off
274 * @param $buffer null|bool
276 * @return The previous value of the flag
278 function bufferResults( $buffer = null ) {
279 if ( is_null( $buffer ) ) {
280 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
282 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
287 * Turns on (false) or off (true) the automatic generation and sending
288 * of a "we're sorry, but there has been a database error" page on
289 * database errors. Default is on (false). When turned off, the
290 * code should use lastErrno() and lastError() to handle the
291 * situation as appropriate.
293 * @return The previous value of the flag.
295 function ignoreErrors( $ignoreErrors = null ) {
296 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
300 * Gets or sets the current transaction level.
302 * Historically, transactions were allowed to be "nested". This is no
303 * longer supported, so this function really only returns a boolean.
305 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
306 * @return The previous value
308 function trxLevel( $level = null ) {
309 return wfSetVar( $this->mTrxLevel
, $level );
313 * Get/set the number of errors logged. Only useful when errors are ignored
314 * @param $count The count to set, or omitted to leave it unchanged.
315 * @return The error count
317 function errorCount( $count = null ) {
318 return wfSetVar( $this->mErrorCount
, $count );
322 * Get/set the table prefix.
323 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
324 * @return The previous table prefix.
326 function tablePrefix( $prefix = null ) {
327 return wfSetVar( $this->mTablePrefix
, $prefix );
331 * Get properties passed down from the server info array of the load
334 * @param $name The entry of the info array to get, or null to get the
337 function getLBInfo( $name = null ) {
338 if ( is_null( $name ) ) {
339 return $this->mLBInfo
;
341 if ( array_key_exists( $name, $this->mLBInfo
) ) {
342 return $this->mLBInfo
[$name];
350 * Set the LB info array, or a member of it. If called with one parameter,
351 * the LB info array is set to that parameter. If it is called with two
352 * parameters, the member with the given name is set to the given value.
358 function setLBInfo( $name, $value = null ) {
359 if ( is_null( $value ) ) {
360 $this->mLBInfo
= $name;
362 $this->mLBInfo
[$name] = $value;
367 * Set lag time in seconds for a fake slave
369 function setFakeSlaveLag( $lag ) {
370 $this->mFakeSlaveLag
= $lag;
374 * Make this connection a fake master
376 function setFakeMaster( $enabled = true ) {
377 $this->mFakeMaster
= $enabled;
381 * Returns true if this database supports (and uses) cascading deletes
383 function cascadingDeletes() {
388 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
390 function cleanupTriggers() {
395 * Returns true if this database is strict about what can be put into an IP field.
396 * Specifically, it uses a NULL value instead of an empty string.
398 function strictIPs() {
403 * Returns true if this database uses timestamps rather than integers
405 function realTimestamps() {
410 * Returns true if this database does an implicit sort when doing GROUP BY
412 function implicitGroupby() {
417 * Returns true if this database does an implicit order by when the column has an index
418 * For example: SELECT page_title FROM page LIMIT 1
420 function implicitOrderby() {
425 * Returns true if this database requires that SELECT DISTINCT queries require that all
426 ORDER BY expressions occur in the SELECT list per the SQL92 standard
428 function standardSelectDistinct() {
433 * Returns true if this database can do a native search on IP columns
434 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
436 function searchableIPs() {
441 * Returns true if this database can use functional indexes
443 function functionalIndexes() {
448 * Return the last query that went through DatabaseBase::query()
451 function lastQuery() {
452 return $this->mLastQuery
;
457 * Returns true if the connection may have been used for write queries.
458 * Should return true if unsure.
462 function doneWrites() {
463 return $this->mDoneWrites
;
467 * Is a connection to the database open?
471 return $this->mOpened
;
475 * Set a flag for this connection
477 * @param $flag Integer: DBO_* constants from Defines.php:
478 * - DBO_DEBUG: output some debug info (same as debug())
479 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
480 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
481 * - DBO_TRX: automatically start transactions
482 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
483 * and removes it in command line mode
484 * - DBO_PERSISTENT: use persistant database connection
486 function setFlag( $flag ) {
487 $this->mFlags |
= $flag;
491 * Clear a flag for this connection
493 * @param $flag: same as setFlag()'s $flag param
495 function clearFlag( $flag ) {
496 $this->mFlags
&= ~
$flag;
500 * Returns a boolean whether the flag $flag is set for this connection
502 * @param $flag: same as setFlag()'s $flag param
505 function getFlag( $flag ) {
506 return !!( $this->mFlags
& $flag );
510 * General read-only accessor
512 function getProperty( $name ) {
519 function getWikiID() {
520 if ( $this->mTablePrefix
) {
521 return "{$this->mDBname}-{$this->mTablePrefix}";
523 return $this->mDBname
;
528 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
532 public function getSchemaPath() {
534 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
535 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
537 return "$IP/maintenance/tables.sql";
541 # ------------------------------------------------------------------------------
543 # ------------------------------------------------------------------------------
547 * @param $server String: database server host
548 * @param $user String: database user name
549 * @param $password String: database user password
550 * @param $dbName String: database name
552 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
554 function __construct( $server = false, $user = false, $password = false, $dbName = false,
555 $flags = 0, $tablePrefix = 'get from global'
557 global $wgDBprefix, $wgCommandLineMode;
559 $this->mFlags
= $flags;
561 if ( $this->mFlags
& DBO_DEFAULT
) {
562 if ( $wgCommandLineMode ) {
563 $this->mFlags
&= ~DBO_TRX
;
565 $this->mFlags |
= DBO_TRX
;
569 /** Get the default table prefix*/
570 if ( $tablePrefix == 'get from global' ) {
571 $this->mTablePrefix
= $wgDBprefix;
573 $this->mTablePrefix
= $tablePrefix;
577 $this->open( $server, $user, $password, $dbName );
582 * Same as new DatabaseMysql( ... ), kept for backward compatibility
583 * @deprecated since 1.17
585 * @return DatabaseMysql
587 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
588 wfDeprecated( __METHOD__
);
589 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
593 * Given a DB type, construct the name of the appropriate child class of
594 * DatabaseBase. This is designed to replace all of the manual stuff like:
595 * $class = 'Database' . ucfirst( strtolower( $type ) );
596 * as well as validate against the canonical list of DB types we have
598 * This factory function is mostly useful for when you need to connect to a
599 * database other than the MediaWiki default (such as for external auth,
600 * an extension, et cetera). Do not use this to connect to the MediaWiki
601 * database. Example uses in core:
602 * @see LoadBalancer::reallyOpenConnection()
603 * @see ExternalUser_MediaWiki::initFromCond()
604 * @see ForeignDBRepo::getMasterDB()
605 * @see WebInstaller_DBConnect::execute()
607 * @param $dbType String A possible DB type
608 * @param $p Array An array of options to pass to the constructor.
609 * Valid options are: host, user, password, dbname, flags, tablePrefix
610 * @return DatabaseBase subclass or null
612 public final static function factory( $dbType, $p = array() ) {
613 $canonicalDBTypes = array(
614 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
616 $dbType = strtolower( $dbType );
618 if( in_array( $dbType, $canonicalDBTypes ) ) {
619 $class = 'Database' . ucfirst( $dbType );
621 isset( $p['host'] ) ?
$p['host'] : false,
622 isset( $p['user'] ) ?
$p['user'] : false,
623 isset( $p['password'] ) ?
$p['password'] : false,
624 isset( $p['dbname'] ) ?
$p['dbname'] : false,
625 isset( $p['flags'] ) ?
$p['flags'] : 0,
626 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
633 protected function installErrorHandler() {
634 $this->mPHPError
= false;
635 $this->htmlErrors
= ini_set( 'html_errors', '0' );
636 set_error_handler( array( $this, 'connectionErrorHandler' ) );
639 protected function restoreErrorHandler() {
640 restore_error_handler();
641 if ( $this->htmlErrors
!== false ) {
642 ini_set( 'html_errors', $this->htmlErrors
);
644 if ( $this->mPHPError
) {
645 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
646 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
653 protected function connectionErrorHandler( $errno, $errstr ) {
654 $this->mPHPError
= $errstr;
658 * Closes a database connection.
659 * if it is open : commits any open transactions
661 * @return Bool operation success. true if already closed.
664 # Stub, should probably be overridden
669 * @param $error String: fallback error message, used if none is given by DB
671 function reportConnectionError( $error = 'Unknown error' ) {
672 $myError = $this->lastError();
678 throw new DBConnectionError( $this, $error );
682 * The DBMS-dependent part of query()
684 * @param $sql String: SQL query.
685 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
687 protected abstract function doQuery( $sql );
690 * Determine whether a query writes to the DB.
691 * Should return true if unsure.
695 function isWriteQuery( $sql ) {
696 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
700 * Run an SQL query and return the result. Normally throws a DBQueryError
701 * on failure. If errors are ignored, returns false instead.
703 * In new code, the query wrappers select(), insert(), update(), delete(),
704 * etc. should be used where possible, since they give much better DBMS
705 * independence and automatically quote or validate user input in a variety
706 * of contexts. This function is generally only useful for queries which are
707 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
710 * However, the query wrappers themselves should call this function.
712 * @param $sql String: SQL query
713 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
714 * comment (you can use __METHOD__ or add some extra info)
715 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
716 * maybe best to catch the exception instead?
717 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
718 * for a successful read query, or false on failure if $tempIgnore set
719 * @throws DBQueryError Thrown when the database returns an error of any kind
721 public function query( $sql, $fname = '', $tempIgnore = false ) {
722 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
723 if ( !Profiler
::instance()->isStub() ) {
724 # generalizeSQL will probably cut down the query to reasonable
725 # logging size most of the time. The substr is really just a sanity check.
728 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
729 $totalProf = 'DatabaseBase::query-master';
731 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
732 $totalProf = 'DatabaseBase::query';
735 wfProfileIn( $totalProf );
736 wfProfileIn( $queryProf );
739 $this->mLastQuery
= $sql;
740 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
741 # Set a flag indicating that writes have been done
742 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
743 $this->mDoneWrites
= true;
746 # Add a comment for easy SHOW PROCESSLIST interpretation
748 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
749 $userName = $wgUser->getName();
750 if ( mb_strlen( $userName ) > 15 ) {
751 $userName = mb_substr( $userName, 0, 15 ) . '...';
753 $userName = str_replace( '/', '', $userName );
757 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
759 # If DBO_TRX is set, start a transaction
760 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
761 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
762 # avoid establishing transactions for SHOW and SET statements too -
763 # that would delay transaction initializations to once connection
764 # is really used by application
765 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
766 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
770 if ( $this->debug() ) {
774 $sqlx = substr( $commentedSql, 0, 500 );
775 $sqlx = strtr( $sqlx, "\t\n", ' ' );
778 wfDebug( "Query $cnt (master): $sqlx\n" );
780 wfDebug( "Query $cnt (slave): $sqlx\n" );
784 if ( istainted( $sql ) & TC_MYSQL
) {
785 throw new MWException( 'Tainted query found' );
788 # Do the query and handle errors
789 $ret = $this->doQuery( $commentedSql );
791 # Try reconnecting if the connection was lost
792 if ( false === $ret && $this->wasErrorReissuable() ) {
793 # Transaction is gone, like it or not
794 $this->mTrxLevel
= 0;
795 wfDebug( "Connection lost, reconnecting...\n" );
797 if ( $this->ping() ) {
798 wfDebug( "Reconnected\n" );
799 $sqlx = substr( $commentedSql, 0, 500 );
800 $sqlx = strtr( $sqlx, "\t\n", ' ' );
801 global $wgRequestTime;
802 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
803 if ( $elapsed < 300 ) {
804 # Not a database error to lose a transaction after a minute or two
805 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
807 $ret = $this->doQuery( $commentedSql );
809 wfDebug( "Failed\n" );
813 if ( false === $ret ) {
814 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
817 if ( !Profiler
::instance()->isStub() ) {
818 wfProfileOut( $queryProf );
819 wfProfileOut( $totalProf );
822 return $this->resultObject( $ret );
826 * Report a query error. Log the error, and if neither the object ignore
827 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
829 * @param $error String
830 * @param $errno Integer
832 * @param $fname String
833 * @param $tempIgnore Boolean
835 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
836 # Ignore errors during error handling to avoid infinite recursion
837 $ignore = $this->ignoreErrors( true );
838 ++
$this->mErrorCount
;
840 if ( $ignore ||
$tempIgnore ) {
841 wfDebug( "SQL ERROR (ignored): $error\n" );
842 $this->ignoreErrors( $ignore );
844 $sql1line = str_replace( "\n", "\\n", $sql );
845 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
846 wfDebug( "SQL ERROR: " . $error . "\n" );
847 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
852 * Intended to be compatible with the PEAR::DB wrapper functions.
853 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
855 * ? = scalar value, quoted as necessary
856 * ! = raw SQL bit (a function for instance)
857 * & = filename; reads the file and inserts as a blob
858 * (we don't use this though...)
860 * This function should not be used directly by new code outside of the
861 * database classes. The query wrapper functions (select() etc.) should be
866 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
867 /* MySQL doesn't support prepared statements (yet), so just
868 pack up the query for reference. We'll manually replace
870 return array( 'query' => $sql, 'func' => $func );
874 * Free a prepared query, generated by prepare().
876 function freePrepared( $prepared ) {
877 /* No-op by default */
881 * Execute a prepared query with the various arguments
882 * @param $prepared String: the prepared sql
883 * @param $args Mixed: Either an array here, or put scalars as varargs
885 * @return ResultWrapper
887 function execute( $prepared, $args = null ) {
888 if ( !is_array( $args ) ) {
890 $args = func_get_args();
891 array_shift( $args );
894 $sql = $this->fillPrepared( $prepared['query'], $args );
896 return $this->query( $sql, $prepared['func'] );
900 * Prepare & execute an SQL statement, quoting and inserting arguments
901 * in the appropriate places.
903 * This function should not be used directly by new code outside of the
904 * database classes. The query wrapper functions (select() etc.) should be
907 * @param $query String
910 * @return ResultWrapper
912 function safeQuery( $query, $args = null ) {
913 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
915 if ( !is_array( $args ) ) {
917 $args = func_get_args();
918 array_shift( $args );
921 $retval = $this->execute( $prepared, $args );
922 $this->freePrepared( $prepared );
928 * For faking prepared SQL statements on DBs that don't support
930 * @param $preparedQuery String: a 'preparable' SQL statement
931 * @param $args Array of arguments to fill it with
932 * @return string executable SQL
934 function fillPrepared( $preparedQuery, $args ) {
936 $this->preparedArgs
=& $args;
938 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
939 array( &$this, 'fillPreparedArg' ), $preparedQuery );
943 * preg_callback func for fillPrepared()
944 * The arguments should be in $this->preparedArgs and must not be touched
945 * while we're doing this.
947 * @param $matches Array
951 function fillPreparedArg( $matches ) {
952 switch( $matches[1] ) {
953 case '\\?': return '?';
954 case '\\!': return '!';
955 case '\\&': return '&';
958 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
960 switch( $matches[1] ) {
961 case '?': return $this->addQuotes( $arg );
962 case '!': return $arg;
964 # return $this->addQuotes( file_get_contents( $arg ) );
965 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
967 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
972 * Free a result object returned by query() or select(). It's usually not
973 * necessary to call this, just use unset() or let the variable holding
974 * the result object go out of scope.
976 * @param $res Mixed: A SQL result
978 function freeResult( $res ) {
982 * Simple UPDATE wrapper.
983 * Usually throws a DBQueryError on failure.
984 * If errors are explicitly ignored, returns success
986 * This function exists for historical reasons, DatabaseBase::update() has a more standard
987 * calling convention and feature set
991 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
992 $table = $this->tableName( $table );
993 $sql = "UPDATE $table SET $var = '" .
994 $this->strencode( $value ) . "' WHERE ($cond)";
996 return (bool)$this->query( $sql, $fname );
1000 * A SELECT wrapper which returns a single field from a single result row.
1002 * Usually throws a DBQueryError on failure. If errors are explicitly
1003 * ignored, returns false on failure.
1005 * If no result rows are returned from the query, false is returned.
1007 * @param $table string|array Table name. See DatabaseBase::select() for details.
1008 * @param $var string The field name to select. This must be a valid SQL
1009 * fragment: do not use unvalidated user input.
1010 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1011 * @param $fname string The function name of the caller.
1012 * @param $options string|array The query options. See DatabaseBase::select() for details.
1014 * @return false|mixed The value from the field, or false on failure.
1016 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1017 $options = array() )
1019 if ( !is_array( $options ) ) {
1020 $options = array( $options );
1023 $options['LIMIT'] = 1;
1025 $res = $this->select( $table, $var, $cond, $fname, $options );
1027 if ( $res === false ||
!$this->numRows( $res ) ) {
1031 $row = $this->fetchRow( $res );
1033 if ( $row !== false ) {
1034 return reset( $row );
1041 * Returns an optional USE INDEX clause to go after the table, and a
1042 * string to go at the end of the query.
1044 * @param $options Array: associative array of options to be turned into
1045 * an SQL query, valid keys are listed in the function.
1047 * @see DatabaseBase::select()
1049 function makeSelectOptions( $options ) {
1050 $preLimitTail = $postLimitTail = '';
1053 $noKeyOptions = array();
1055 foreach ( $options as $key => $option ) {
1056 if ( is_numeric( $key ) ) {
1057 $noKeyOptions[$option] = true;
1061 if ( isset( $options['GROUP BY'] ) ) {
1062 $gb = is_array( $options['GROUP BY'] )
1063 ?
implode( ',', $options['GROUP BY'] )
1064 : $options['GROUP BY'];
1065 $preLimitTail .= " GROUP BY {$gb}";
1068 if ( isset( $options['HAVING'] ) ) {
1069 $preLimitTail .= " HAVING {$options['HAVING']}";
1072 if ( isset( $options['ORDER BY'] ) ) {
1073 $ob = is_array( $options['ORDER BY'] )
1074 ?
implode( ',', $options['ORDER BY'] )
1075 : $options['ORDER BY'];
1076 $preLimitTail .= " ORDER BY {$ob}";
1079 // if (isset($options['LIMIT'])) {
1080 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1081 // isset($options['OFFSET']) ? $options['OFFSET']
1085 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1086 $postLimitTail .= ' FOR UPDATE';
1089 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1090 $postLimitTail .= ' LOCK IN SHARE MODE';
1093 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1094 $startOpts .= 'DISTINCT';
1097 # Various MySQL extensions
1098 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1099 $startOpts .= ' /*! STRAIGHT_JOIN */';
1102 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1103 $startOpts .= ' HIGH_PRIORITY';
1106 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1107 $startOpts .= ' SQL_BIG_RESULT';
1110 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1111 $startOpts .= ' SQL_BUFFER_RESULT';
1114 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1115 $startOpts .= ' SQL_SMALL_RESULT';
1118 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1119 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1122 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1123 $startOpts .= ' SQL_CACHE';
1126 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1127 $startOpts .= ' SQL_NO_CACHE';
1130 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1131 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1136 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1140 * Execute a SELECT query constructed using the various parameters provided.
1141 * See below for full details of the parameters.
1143 * @param $table String|Array Table name
1144 * @param $vars String|Array Field names
1145 * @param $conds String|Array Conditions
1146 * @param $fname String Caller function name
1147 * @param $options Array Query options
1148 * @param $join_conds Array Join conditions
1151 * @param $table string|array
1153 * May be either an array of table names, or a single string holding a table
1154 * name. If an array is given, table aliases can be specified, for example:
1156 * array( 'a' => 'user' )
1158 * This includes the user table in the query, with the alias "a" available
1159 * for use in field names (e.g. a.user_name).
1161 * All of the table names given here are automatically run through
1162 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1163 * added, and various other table name mappings to be performed.
1166 * @param $vars string|array
1168 * May be either a field name or an array of field names. The field names
1169 * here are complete fragments of SQL, for direct inclusion into the SELECT
1170 * query. Expressions and aliases may be specified as in SQL, for example:
1172 * array( 'MAX(rev_id) AS maxrev' )
1174 * If an expression is given, care must be taken to ensure that it is
1178 * @param $conds string|array
1180 * May be either a string containing a single condition, or an array of
1181 * conditions. If an array is given, the conditions constructed from each
1182 * element are combined with AND.
1184 * Array elements may take one of two forms:
1186 * - Elements with a numeric key are interpreted as raw SQL fragments.
1187 * - Elements with a string key are interpreted as equality conditions,
1188 * where the key is the field name.
1189 * - If the value of such an array element is a scalar (such as a
1190 * string), it will be treated as data and thus quoted appropriately.
1191 * If it is null, an IS NULL clause will be added.
1192 * - If the value is an array, an IN(...) clause will be constructed,
1193 * such that the field name may match any of the elements in the
1194 * array. The elements of the array will be quoted.
1195 * - If the field name ends with "!", this is taken as a flag which
1196 * inverts the comparison, allowing NOT IN clauses to be constructed,
1197 * for example: array( 'user_id!' => array( 1, 2, 3 ) )
1199 * Note that expressions are often DBMS-dependent in their syntax.
1200 * DBMS-independent wrappers are provided for constructing several types of
1201 * expression commonly used in condition queries. See:
1202 * - DatabaseBase::buildLike()
1203 * - DatabaseBase::conditional()
1206 * @param $options string|array
1208 * Optional: Array of query options. Boolean options are specified by
1209 * including them in the array as a string value with a numeric key, for
1212 * array( 'FOR UPDATE' )
1214 * The supported options are:
1216 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1217 * with LIMIT can theoretically be used for paging through a result set,
1218 * but this is discouraged in MediaWiki for performance reasons.
1220 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1221 * and then the first rows are taken until the limit is reached. LIMIT
1222 * is applied to a result set after OFFSET.
1224 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1225 * changed until the next COMMIT.
1227 * - DISTINCT: Boolean: return only unique result rows.
1229 * - GROUP BY: May be either an SQL fragment string naming a field or
1230 * expression to group by, or an array of such SQL fragments.
1232 * - HAVING: A string containing a HAVING clause.
1234 * - ORDER BY: May be either an SQL fragment giving a field name or
1235 * expression to order by, or an array of such SQL fragments.
1237 * - USE INDEX: This may be either a string giving the index name to use
1238 * for the query, or an array. If it is an associative array, each key
1239 * gives the table name (or alias), each value gives the index name to
1240 * use for that table. All strings are SQL fragments and so should be
1241 * validated by the caller.
1243 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1244 * instead of SELECT.
1246 * And also the following boolean MySQL extensions, see the MySQL manual
1247 * for documentation:
1249 * - LOCK IN SHARE MODE
1253 * - SQL_BUFFER_RESULT
1254 * - SQL_SMALL_RESULT
1255 * - SQL_CALC_FOUND_ROWS
1260 * @param $join_conds string|array
1262 * Optional associative array of table-specific join conditions. In the
1263 * most common case, this is unnecessary, since the join condition can be
1264 * in $conds. However, it is useful for doing a LEFT JOIN.
1266 * The key of the array contains the table name or alias. The value is an
1267 * array with two elements, numbered 0 and 1. The first gives the type of
1268 * join, the second is an SQL fragment giving the join condition for that
1269 * table. For example:
1271 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1273 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1274 * with no rows in it will be returned. If there was a query error, a
1275 * DBQueryError exception will be thrown, except if the "ignore errors"
1276 * option was set, in which case false will be returned.
1278 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1279 $options = array(), $join_conds = array() ) {
1280 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1282 return $this->query( $sql, $fname );
1286 * The equivalent of DatabaseBase::select() except that the constructed SQL
1287 * is returned, instead of being immediately executed.
1289 * @param $table string|array Table name
1290 * @param $vars string|array Field names
1291 * @param $conds string|array Conditions
1292 * @param $fname string Caller function name
1293 * @param $options string|array Query options
1294 * @param $join_conds string|array Join conditions
1296 * @return SQL query string.
1297 * @see DatabaseBase::select()
1299 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1300 if ( is_array( $vars ) ) {
1301 $vars = implode( ',', $vars );
1304 $options = (array)$options;
1306 if ( is_array( $table ) ) {
1307 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1308 ?
$options['USE INDEX']
1310 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1312 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1314 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1316 } elseif ( $table != '' ) {
1317 if ( $table { 0 } == ' ' ) {
1318 $from = ' FROM ' . $table;
1320 $from = ' FROM ' . $this->tableName( $table );
1326 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1328 if ( !empty( $conds ) ) {
1329 if ( is_array( $conds ) ) {
1330 $conds = $this->makeList( $conds, LIST_AND
);
1332 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1334 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1337 if ( isset( $options['LIMIT'] ) ) {
1338 $sql = $this->limitResult( $sql, $options['LIMIT'],
1339 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1341 $sql = "$sql $postLimitTail";
1343 if ( isset( $options['EXPLAIN'] ) ) {
1344 $sql = 'EXPLAIN ' . $sql;
1351 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1352 * that a single row object is returned. If the query returns no rows,
1353 * false is returned.
1355 * @param $table string|array Table name
1356 * @param $vars string|array Field names
1357 * @param $conds|array Conditions
1358 * @param $fname string Caller function name
1359 * @param $options string|array Query options
1360 * @param $join_conds array|string Join conditions
1362 * @return ResultWrapper|bool
1364 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1365 $options = array(), $join_conds = array() )
1367 $options['LIMIT'] = 1;
1368 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1370 if ( $res === false ) {
1374 if ( !$this->numRows( $res ) ) {
1378 $obj = $this->fetchObject( $res );
1384 * Estimate rows in dataset.
1386 * MySQL allows you to estimate the number of rows that would be returned
1387 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1388 * index cardinality statistics, and is notoriously inaccurate, especially
1389 * when large numbers of rows have recently been added or deleted.
1391 * For DBMSs that don't support fast result size estimation, this function
1392 * will actually perform the SELECT COUNT(*).
1394 * Takes the same arguments as DatabaseBase::select().
1396 * @param $table String: table name
1397 * @param $vars Array: unused
1398 * @param $conds Array: filters on the table
1399 * @param $fname String: function name for profiling
1400 * @param $options Array: options for select
1401 * @return Integer: row count
1403 public function estimateRowCount( $table, $vars = '*', $conds = '',
1404 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1407 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1410 $row = $this->fetchRow( $res );
1411 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1418 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1419 * It's only slightly flawed. Don't use for anything important.
1421 * @param $sql String: A SQL Query
1423 static function generalizeSQL( $sql ) {
1424 # This does the same as the regexp below would do, but in such a way
1425 # as to avoid crashing php on some large strings.
1426 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1428 $sql = str_replace ( "\\\\", '', $sql );
1429 $sql = str_replace ( "\\'", '', $sql );
1430 $sql = str_replace ( "\\\"", '', $sql );
1431 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1432 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1434 # All newlines, tabs, etc replaced by single space
1435 $sql = preg_replace ( '/\s+/', ' ', $sql );
1438 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1444 * Determines whether a field exists in a table
1446 * @param $table String: table name
1447 * @param $field String: filed to check on that table
1448 * @param $fname String: calling function name (optional)
1449 * @return Boolean: whether $table has filed $field
1451 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1452 $info = $this->fieldInfo( $table, $field );
1458 * Determines whether an index exists
1459 * Usually throws a DBQueryError on failure
1460 * If errors are explicitly ignored, returns NULL on failure
1464 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1465 $info = $this->indexInfo( $table, $index, $fname );
1466 if ( is_null( $info ) ) {
1469 return $info !== false;
1474 * Query whether a given table exists
1480 function tableExists( $table ) {
1481 $table = $this->tableName( $table );
1482 $old = $this->ignoreErrors( true );
1483 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1484 $this->ignoreErrors( $old );
1490 * mysql_field_type() wrapper
1492 function fieldType( $res, $index ) {
1493 if ( $res instanceof ResultWrapper
) {
1494 $res = $res->result
;
1497 return mysql_field_type( $res, $index );
1501 * Determines if a given index is unique
1503 * @param $table string
1504 * @param $index string
1508 function indexUnique( $table, $index ) {
1509 $indexInfo = $this->indexInfo( $table, $index );
1511 if ( !$indexInfo ) {
1515 return !$indexInfo[0]->Non_unique
;
1519 * Helper for DatabaseBase::insert().
1521 * @param $options array
1524 function makeInsertOptions( $options ) {
1525 return implode( ' ', $options );
1529 * INSERT wrapper, inserts an array into a table.
1533 * - A single associative array. The array keys are the field names, and
1534 * the values are the values to insert. The values are treated as data
1535 * and will be quoted appropriately. If NULL is inserted, this will be
1536 * converted to a database NULL.
1537 * - An array with numeric keys, holding a list of associative arrays.
1538 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1539 * each subarray must be identical to each other, and in the same order.
1541 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1544 * $options is an array of options, with boolean options encoded as values
1545 * with numeric keys, in the same style as $options in
1546 * DatabaseBase::select(). Supported options are:
1548 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1549 * any rows which cause duplicate key errors are not inserted. It's
1550 * possible to determine how many rows were successfully inserted using
1551 * DatabaseBase::affectedRows().
1553 * @param $table String Table name. This will be passed through
1554 * DatabaseBase::tableName().
1555 * @param $a Array of rows to insert
1556 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1557 * @param $options Array of options
1561 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1562 # No rows to insert, easy just return now
1563 if ( !count( $a ) ) {
1567 $table = $this->tableName( $table );
1569 if ( !is_array( $options ) ) {
1570 $options = array( $options );
1573 $options = $this->makeInsertOptions( $options );
1575 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1577 $keys = array_keys( $a[0] );
1580 $keys = array_keys( $a );
1583 $sql = 'INSERT ' . $options .
1584 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1588 foreach ( $a as $row ) {
1594 $sql .= '(' . $this->makeList( $row ) . ')';
1597 $sql .= '(' . $this->makeList( $a ) . ')';
1600 return (bool)$this->query( $sql, $fname );
1604 * Make UPDATE options for the DatabaseBase::update function
1606 * @param $options Array: The options passed to DatabaseBase::update
1609 function makeUpdateOptions( $options ) {
1610 if ( !is_array( $options ) ) {
1611 $options = array( $options );
1616 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1617 $opts[] = $this->lowPriorityOption();
1620 if ( in_array( 'IGNORE', $options ) ) {
1624 return implode( ' ', $opts );
1628 * UPDATE wrapper. Takes a condition array and a SET array.
1630 * @param $table String name of the table to UPDATE. This will be passed through
1631 * DatabaseBase::tableName().
1633 * @param $values Array: An array of values to SET. For each array element,
1634 * the key gives the field name, and the value gives the data
1635 * to set that field to. The data will be quoted by
1636 * DatabaseBase::addQuotes().
1638 * @param $conds Array: An array of conditions (WHERE). See
1639 * DatabaseBase::select() for the details of the format of
1640 * condition arrays. Use '*' to update all rows.
1642 * @param $fname String: The function name of the caller (from __METHOD__),
1643 * for logging and profiling.
1645 * @param $options Array: An array of UPDATE options, can be:
1646 * - IGNORE: Ignore unique key conflicts
1647 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1650 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1651 $table = $this->tableName( $table );
1652 $opts = $this->makeUpdateOptions( $options );
1653 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1655 if ( $conds != '*' ) {
1656 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1659 return $this->query( $sql, $fname );
1663 * Makes an encoded list of strings from an array
1664 * @param $a Array containing the data
1666 * - LIST_COMMA: comma separated, no field names
1667 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1668 * the documentation for $conds in DatabaseBase::select().
1669 * - LIST_OR: ORed WHERE clause (without the WHERE)
1670 * - LIST_SET: comma separated with field names, like a SET clause
1671 * - LIST_NAMES: comma separated field names
1673 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1674 * mark to generate a 'NOT IN' structure.
1677 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1680 * 'field' NOT IN ('1', '2', '3' );
1684 function makeList( $a, $mode = LIST_COMMA
) {
1685 if ( !is_array( $a ) ) {
1686 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1692 foreach ( $a as $field => $value ) {
1694 if ( $mode == LIST_AND
) {
1696 } elseif ( $mode == LIST_OR
) {
1705 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1707 if( substr($field,-1) == '!' ) {
1709 $field = substr($field, 0, -1 );
1712 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1713 $list .= "($value)";
1714 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1716 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1717 if ( count( $value ) == 0 ) {
1718 throw new MWException( __METHOD__
. ': empty input' );
1719 } elseif ( count( $value ) == 1 ) {
1720 // Special-case single values, as IN isn't terribly efficient
1721 // Don't necessarily assume the single key is 0; we don't
1722 // enforce linear numeric ordering on other arrays here.
1723 $value = array_values( $value );
1725 $operator = $not ?
' != ' : ' = ';
1726 $list .= $field . $operator . $this->addQuotes( $value[0] );
1728 $operator = $not ?
' NOT IN ' : ' IN ';
1729 $list .= $field . $operator . "(" . $this->makeList( $value ) . ")";
1731 } elseif ( $value === null ) {
1732 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1733 $list .= "$field IS ";
1737 } elseif ( $mode == LIST_SET
) {
1738 $list .= "$field = ";
1742 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1743 $list .= "$field = ";
1745 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1753 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1754 * The keys on each level may be either integers or strings.
1756 * @param $data Array: organized as 2-d
1757 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1758 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1759 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1760 * @return Mixed: string SQL fragment, or false if no items in array.
1762 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1765 foreach ( $data as $base => $sub ) {
1766 if ( count( $sub ) ) {
1767 $conds[] = $this->makeList(
1768 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1774 return $this->makeList( $conds, LIST_OR
);
1776 // Nothing to search for...
1782 * Build a partial where clause from a 3-d array
1783 * The keys on each level may be either integers or strings.
1785 * @param $data Array: organized as 3-d array(baseKeyVal => array(middleKeyVal => array(subKeyVal => <ignored>, ...), ...), ...)
1786 * @param $baseKey String: field name to match the base-level keys to (eg 'gtl_to_prefix')
1787 * @param $middleKey String: field name to match the middle-level keys to (eg 'gtl_to_namespace')
1788 * @param $subKey String: field name to match the sub-level keys to (eg 'gtl_to_title')
1789 * @return Mixed: string SQL fragment, or false if no items in array.
1791 function makeWhereFrom3d( $data, $baseKey, $middleKey, $subKey ) {
1793 foreach ( $data as $base => $subdata ) {
1794 foreach ( $subdata as $middle => $sub ) {
1795 if ( count( $sub ) ) {
1796 $conds[] = $this->makeList(
1797 array( $baseKey => $base,
1798 $middleKey => $middle,
1799 $subKey => array_keys( $sub ) ),
1807 return $this->makeList( $conds, LIST_OR
);
1809 // Nothing to search for...
1815 * Bitwise operations
1822 function bitNot( $field ) {
1828 * @param $fieldRight
1831 function bitAnd( $fieldLeft, $fieldRight ) {
1832 return "($fieldLeft & $fieldRight)";
1837 * @param $fieldRight
1840 function bitOr( $fieldLeft, $fieldRight ) {
1841 return "($fieldLeft | $fieldRight)";
1845 * Change the current database
1847 * @todo Explain what exactly will fail if this is not overridden.
1848 * @return bool Success or failure
1850 function selectDB( $db ) {
1851 # Stub. Shouldn't cause serious problems if it's not overridden, but
1852 # if your database engine supports a concept similar to MySQL's
1853 # databases you may as well.
1854 $this->mDBname
= $db;
1859 * Get the current DB name
1861 function getDBname() {
1862 return $this->mDBname
;
1866 * Get the server hostname or IP address
1868 function getServer() {
1869 return $this->mServer
;
1873 * Format a table name ready for use in constructing an SQL query
1875 * This does two important things: it quotes the table names to clean them up,
1876 * and it adds a table prefix if only given a table name with no quotes.
1878 * All functions of this object which require a table name call this function
1879 * themselves. Pass the canonical name to such functions. This is only needed
1880 * when calling query() directly.
1882 * @param $name String: database table name
1883 * @param $quoted Boolean: Automatically pass the table name through
1884 * addIdentifierQuotes() so that it can be used in a query.
1885 * @return String: full database name
1887 function tableName( $name, $quoted = true ) {
1888 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1889 # Skip the entire process when we have a string quoted on both ends.
1890 # Note that we check the end so that we will still quote any use of
1891 # use of `database`.table. But won't break things if someone wants
1892 # to query a database table with a dot in the name.
1893 if ( $this->isQuotedIdentifier( $name ) ) {
1897 # Lets test for any bits of text that should never show up in a table
1898 # name. Basically anything like JOIN or ON which are actually part of
1899 # SQL queries, but may end up inside of the table value to combine
1900 # sql. Such as how the API is doing.
1901 # Note that we use a whitespace test rather than a \b test to avoid
1902 # any remote case where a word like on may be inside of a table name
1903 # surrounded by symbols which may be considered word breaks.
1904 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1908 # Split database and table into proper variables.
1909 # We reverse the explode so that database.table and table both output
1910 # the correct table.
1911 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1912 if ( isset( $dbDetails[1] ) ) {
1913 list( $table, $database ) = $dbDetails;
1915 list( $table ) = $dbDetails;
1917 $prefix = $this->mTablePrefix
; # Default prefix
1919 # A database name has been specified in input. We don't want any
1921 if ( isset( $database ) ) {
1925 # Note that we use the long format because php will complain in in_array if
1926 # the input is not an array, and will complain in is_array if it is not set.
1927 if ( !isset( $database ) # Don't use shared database if pre selected.
1928 && isset( $wgSharedDB ) # We have a shared database
1929 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1930 && isset( $wgSharedTables )
1931 && is_array( $wgSharedTables )
1932 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1933 $database = $wgSharedDB;
1934 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1937 # Quote the $database and $table and apply the prefix if not quoted.
1938 if ( isset( $database ) ) {
1939 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1942 $table = "{$prefix}{$table}";
1943 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1944 $table = $this->addIdentifierQuotes( "{$table}" );
1947 # Merge our database and table into our final table name.
1948 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1954 * Fetch a number of table names into an array
1955 * This is handy when you need to construct SQL for joins
1958 * extract($dbr->tableNames('user','watchlist'));
1959 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1960 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1962 public function tableNames() {
1963 $inArray = func_get_args();
1966 foreach ( $inArray as $name ) {
1967 $retVal[$name] = $this->tableName( $name );
1974 * Fetch a number of table names into an zero-indexed numerical array
1975 * This is handy when you need to construct SQL for joins
1978 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1979 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1980 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1982 public function tableNamesN() {
1983 $inArray = func_get_args();
1986 foreach ( $inArray as $name ) {
1987 $retVal[] = $this->tableName( $name );
1994 * Get an aliased table name
1995 * e.g. tableName AS newTableName
1997 * @param $name string Table name, see tableName()
1998 * @param $alias string Alias (optional)
1999 * @return string SQL name for aliased table. Will not alias a table to its own name
2001 public function tableNameWithAlias( $name, $alias = false ) {
2002 if ( !$alias ||
$alias == $name ) {
2003 return $this->tableName( $name );
2005 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2010 * Gets an array of aliased table names
2012 * @param $tables array( [alias] => table )
2013 * @return array of strings, see tableNameWithAlias()
2015 public function tableNamesWithAlias( $tables ) {
2017 foreach ( $tables as $alias => $table ) {
2018 if ( is_numeric( $alias ) ) {
2021 $retval[] = $this->tableNameWithAlias( $table, $alias );
2027 * Get the aliased table name clause for a FROM clause
2028 * which might have a JOIN and/or USE INDEX clause
2030 * @param $tables array( [alias] => table )
2031 * @param $use_index array() Same as for select()
2032 * @param $join_conds array() Same as for select()
2035 protected function tableNamesWithUseIndexOrJOIN(
2036 $tables, $use_index = array(), $join_conds = array()
2040 $use_index = (array)$use_index;
2041 $join_conds = (array)$join_conds;
2043 foreach ( $tables as $alias => $table ) {
2044 if ( !is_string( $alias ) ) {
2045 // No alias? Set it equal to the table name
2048 // Is there a JOIN clause for this table?
2049 if ( isset( $join_conds[$alias] ) ) {
2050 list( $joinType, $conds ) = $join_conds[$alias];
2051 $tableClause = $joinType;
2052 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2053 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2054 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2056 $tableClause .= ' ' . $use;
2059 $on = $this->makeList( (array)$conds, LIST_AND
);
2061 $tableClause .= ' ON (' . $on . ')';
2064 $retJOIN[] = $tableClause;
2065 // Is there an INDEX clause for this table?
2066 } elseif ( isset( $use_index[$alias] ) ) {
2067 $tableClause = $this->tableNameWithAlias( $table, $alias );
2068 $tableClause .= ' ' . $this->useIndexClause(
2069 implode( ',', (array)$use_index[$alias] ) );
2071 $ret[] = $tableClause;
2073 $tableClause = $this->tableNameWithAlias( $table, $alias );
2075 $ret[] = $tableClause;
2079 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2080 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2081 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2083 // Compile our final table clause
2084 return implode( ' ', array( $straightJoins, $otherJoins ) );
2088 * Get the name of an index in a given table
2094 function indexName( $index ) {
2095 // Backwards-compatibility hack
2097 'ar_usertext_timestamp' => 'usertext_timestamp',
2098 'un_user_id' => 'user_id',
2099 'un_user_ip' => 'user_ip',
2102 if ( isset( $renamed[$index] ) ) {
2103 return $renamed[$index];
2110 * If it's a string, adds quotes and backslashes
2111 * Otherwise returns as-is
2117 function addQuotes( $s ) {
2118 if ( $s === null ) {
2121 # This will also quote numeric values. This should be harmless,
2122 # and protects against weird problems that occur when they really
2123 # _are_ strings such as article titles and string->number->string
2124 # conversion is not 1:1.
2125 return "'" . $this->strencode( $s ) . "'";
2130 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2131 * MySQL uses `backticks` while basically everything else uses double quotes.
2132 * Since MySQL is the odd one out here the double quotes are our generic
2133 * and we implement backticks in DatabaseMysql.
2137 public function addIdentifierQuotes( $s ) {
2138 return '"' . str_replace( '"', '""', $s ) . '"';
2142 * Returns if the given identifier looks quoted or not according to
2143 * the database convention for quoting identifiers .
2145 * @param $name string
2149 public function isQuotedIdentifier( $name ) {
2150 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2154 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2155 * which used quote_ident which does not follow our naming conventions
2156 * was renamed to addIdentifierQuotes.
2157 * @deprecated since 1.18 use addIdentifierQuotes
2161 function quote_ident( $s ) {
2162 wfDeprecated( __METHOD__
);
2163 return $this->addIdentifierQuotes( $s );
2167 * Escape string for safe LIKE usage.
2168 * WARNING: you should almost never use this function directly,
2169 * instead use buildLike() that escapes everything automatically
2170 * @deprecated since 1.17, warnings in 1.17, removed in ???
2172 public function escapeLike( $s ) {
2173 wfDeprecated( __METHOD__
);
2174 return $this->escapeLikeInternal( $s );
2177 protected function escapeLikeInternal( $s ) {
2178 $s = str_replace( '\\', '\\\\', $s );
2179 $s = $this->strencode( $s );
2180 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2186 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2187 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2188 * Alternatively, the function could be provided with an array of aforementioned parameters.
2190 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2191 * for subpages of 'My page title'.
2192 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2195 * @return String: fully built LIKE statement
2197 function buildLike() {
2198 $params = func_get_args();
2200 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2201 $params = $params[0];
2206 foreach ( $params as $value ) {
2207 if ( $value instanceof LikeMatch
) {
2208 $s .= $value->toString();
2210 $s .= $this->escapeLikeInternal( $value );
2214 return " LIKE '" . $s . "' ";
2218 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2222 function anyChar() {
2223 return new LikeMatch( '_' );
2227 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2229 * @rerturn LikeMatch
2231 function anyString() {
2232 return new LikeMatch( '%' );
2236 * Returns an appropriately quoted sequence value for inserting a new row.
2237 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2238 * subclass will return an integer, and save the value for insertId()
2240 function nextSequenceValue( $seqName ) {
2245 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2246 * is only needed because a) MySQL must be as efficient as possible due to
2247 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2248 * which index to pick. Anyway, other databases might have different
2249 * indexes on a given table. So don't bother overriding this unless you're
2252 function useIndexClause( $index ) {
2257 * REPLACE query wrapper.
2259 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2260 * except that when there is a duplicate key error, the old row is deleted
2261 * and the new row is inserted in its place.
2263 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2264 * perform the delete, we need to know what the unique indexes are so that
2265 * we know how to find the conflicting rows.
2267 * It may be more efficient to leave off unique indexes which are unlikely
2268 * to collide. However if you do this, you run the risk of encountering
2269 * errors which wouldn't have occurred in MySQL.
2271 * @param $rows Can be either a single row to insert, or multiple rows,
2272 * in the same format as for DatabaseBase::insert()
2273 * @param $uniqueIndexes is an array of indexes. Each element may be either
2274 * a field name or an array of field names
2276 * @param $table String: The table to replace the row(s) in.
2277 * @param $uniqueIndexes Array: An associative array of indexes
2278 * @param $rows Array: Array of rows to replace
2279 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2281 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2282 $quotedTable = $this->tableName( $table );
2284 if ( count( $rows ) == 0 ) {
2289 if ( !is_array( reset( $rows ) ) ) {
2290 $rows = array( $rows );
2293 foreach( $rows as $row ) {
2294 # Delete rows which collide
2295 if ( $uniqueIndexes ) {
2296 $sql = "DELETE FROM $quotedTable WHERE ";
2298 foreach ( $uniqueIndexes as $index ) {
2305 if ( is_array( $index ) ) {
2307 foreach ( $index as $col ) {
2313 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2316 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2320 $this->query( $sql, $fname );
2323 # Now insert the row
2324 $this->insert( $table, $row );
2329 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2332 * @param $table Table name
2333 * @param $rows Rows to insert
2334 * @param $fname Caller function name
2336 protected function nativeReplace( $table, $rows, $fname ) {
2337 $table = $this->tableName( $table );
2340 if ( !is_array( reset( $rows ) ) ) {
2341 $rows = array( $rows );
2344 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2347 foreach ( $rows as $row ) {
2354 $sql .= '(' . $this->makeList( $row ) . ')';
2357 return $this->query( $sql, $fname );
2361 * DELETE where the condition is a join.
2363 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2364 * we use sub-selects
2366 * For safety, an empty $conds will not delete everything. If you want to
2367 * delete all rows where the join condition matches, set $conds='*'.
2369 * DO NOT put the join condition in $conds.
2371 * @param $delTable String: The table to delete from.
2372 * @param $joinTable String: The other table.
2373 * @param $delVar String: The variable to join on, in the first table.
2374 * @param $joinVar String: The variable to join on, in the second table.
2375 * @param $conds Array: Condition array of field names mapped to variables,
2376 * ANDed together in the WHERE clause
2377 * @param $fname String: Calling function name (use __METHOD__) for
2380 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2381 $fname = 'DatabaseBase::deleteJoin' )
2384 throw new DBUnexpectedError( $this,
2385 'DatabaseBase::deleteJoin() called with empty $conds' );
2388 $delTable = $this->tableName( $delTable );
2389 $joinTable = $this->tableName( $joinTable );
2390 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2391 if ( $conds != '*' ) {
2392 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2396 $this->query( $sql, $fname );
2400 * Returns the size of a text field, or -1 for "unlimited"
2402 function textFieldSize( $table, $field ) {
2403 $table = $this->tableName( $table );
2404 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2405 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2406 $row = $this->fetchObject( $res );
2410 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2420 * A string to insert into queries to show that they're low-priority, like
2421 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2422 * string and nothing bad should happen.
2424 * @return string Returns the text of the low priority option if it is
2425 * supported, or a blank string otherwise
2427 function lowPriorityOption() {
2432 * DELETE query wrapper.
2434 * @param $table Array Table name
2435 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2436 * the format. Use $conds == "*" to delete all rows
2437 * @param $fname String name of the calling function
2441 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2443 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2446 $table = $this->tableName( $table );
2447 $sql = "DELETE FROM $table";
2449 if ( $conds != '*' ) {
2450 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2453 return $this->query( $sql, $fname );
2457 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2458 * into another table.
2460 * @param $destTable The table name to insert into
2461 * @param $srcTable May be either a table name, or an array of table names
2462 * to include in a join.
2464 * @param $varMap must be an associative array of the form
2465 * array( 'dest1' => 'source1', ...). Source items may be literals
2466 * rather than field names, but strings should be quoted with
2467 * DatabaseBase::addQuotes()
2469 * @param $conds Condition array. See $conds in DatabaseBase::select() for
2470 * the details of the format of condition arrays. May be "*" to copy the
2473 * @param $fname The function name of the caller, from __METHOD__
2475 * @param $insertOptions Options for the INSERT part of the query, see
2476 * DatabaseBase::insert() for details.
2477 * @param $selectOptions Options for the SELECT part of the query, see
2478 * DatabaseBase::select() for details.
2480 * @return ResultWrapper
2482 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2483 $fname = 'DatabaseBase::insertSelect',
2484 $insertOptions = array(), $selectOptions = array() )
2486 $destTable = $this->tableName( $destTable );
2488 if ( is_array( $insertOptions ) ) {
2489 $insertOptions = implode( ' ', $insertOptions );
2492 if ( !is_array( $selectOptions ) ) {
2493 $selectOptions = array( $selectOptions );
2496 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2498 if ( is_array( $srcTable ) ) {
2499 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2501 $srcTable = $this->tableName( $srcTable );
2504 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2505 " SELECT $startOpts " . implode( ',', $varMap ) .
2506 " FROM $srcTable $useIndex ";
2508 if ( $conds != '*' ) {
2509 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2512 $sql .= " $tailOpts";
2514 return $this->query( $sql, $fname );
2518 * Construct a LIMIT query with optional offset. This is used for query
2519 * pages. The SQL should be adjusted so that only the first $limit rows
2520 * are returned. If $offset is provided as well, then the first $offset
2521 * rows should be discarded, and the next $limit rows should be returned.
2522 * If the result of the query is not ordered, then the rows to be returned
2523 * are theoretically arbitrary.
2525 * $sql is expected to be a SELECT, if that makes a difference. For
2526 * UPDATE, limitResultForUpdate should be used.
2528 * The version provided by default works in MySQL and SQLite. It will very
2529 * likely need to be overridden for most other DBMSes.
2531 * @param $sql String: SQL query we will append the limit too
2532 * @param $limit Integer: the SQL limit
2533 * @param $offset Integer the SQL offset (default false)
2537 function limitResult( $sql, $limit, $offset = false ) {
2538 if ( !is_numeric( $limit ) ) {
2539 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2542 return "$sql LIMIT "
2543 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2547 function limitResultForUpdate( $sql, $num ) {
2548 return $this->limitResult( $sql, $num, 0 );
2552 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2553 * within the UNION construct.
2556 function unionSupportsOrderAndLimit() {
2557 return true; // True for almost every DB supported
2561 * Construct a UNION query
2562 * This is used for providing overload point for other DB abstractions
2563 * not compatible with the MySQL syntax.
2564 * @param $sqls Array: SQL statements to combine
2565 * @param $all Boolean: use UNION ALL
2566 * @return String: SQL fragment
2568 function unionQueries( $sqls, $all ) {
2569 $glue = $all ?
') UNION ALL (' : ') UNION (';
2570 return '(' . implode( $glue, $sqls ) . ')';
2574 * Returns an SQL expression for a simple conditional. This doesn't need
2575 * to be overridden unless CASE isn't supported in your DBMS.
2577 * @param $cond String: SQL expression which will result in a boolean value
2578 * @param $trueVal String: SQL expression to return if true
2579 * @param $falseVal String: SQL expression to return if false
2580 * @return String: SQL fragment
2582 function conditional( $cond, $trueVal, $falseVal ) {
2583 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2587 * Returns a comand for str_replace function in SQL query.
2588 * Uses REPLACE() in MySQL
2590 * @param $orig String: column to modify
2591 * @param $old String: column to seek
2592 * @param $new String: column to replace with
2596 function strreplace( $orig, $old, $new ) {
2597 return "REPLACE({$orig}, {$old}, {$new})";
2601 * Determines if the last failure was due to a deadlock
2606 function wasDeadlock() {
2611 * Determines if the last query error was something that should be dealt
2612 * with by pinging the connection and reissuing the query.
2617 function wasErrorReissuable() {
2622 * Determines if the last failure was due to the database being read-only.
2627 function wasReadOnlyError() {
2632 * Perform a deadlock-prone transaction.
2634 * This function invokes a callback function to perform a set of write
2635 * queries. If a deadlock occurs during the processing, the transaction
2636 * will be rolled back and the callback function will be called again.
2639 * $dbw->deadlockLoop( callback, ... );
2641 * Extra arguments are passed through to the specified callback function.
2643 * Returns whatever the callback function returned on its successful,
2644 * iteration, or false on error, for example if the retry limit was
2647 function deadlockLoop() {
2648 $myFname = 'DatabaseBase::deadlockLoop';
2651 $args = func_get_args();
2652 $function = array_shift( $args );
2653 $oldIgnore = $this->ignoreErrors( true );
2654 $tries = DEADLOCK_TRIES
;
2656 if ( is_array( $function ) ) {
2657 $fname = $function[0];
2663 $retVal = call_user_func_array( $function, $args );
2664 $error = $this->lastError();
2665 $errno = $this->lastErrno();
2666 $sql = $this->lastQuery();
2669 if ( $this->wasDeadlock() ) {
2671 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2673 $this->reportQueryError( $error, $errno, $sql, $fname );
2676 } while ( $this->wasDeadlock() && --$tries > 0 );
2678 $this->ignoreErrors( $oldIgnore );
2680 if ( $tries <= 0 ) {
2681 $this->rollback( $myFname );
2682 $this->reportQueryError( $error, $errno, $sql, $fname );
2685 $this->commit( $myFname );
2691 * Wait for the slave to catch up to a given master position.
2693 * @param $pos DBMasterPos object
2694 * @param $timeout Integer: the maximum number of seconds to wait for
2697 * @return An integer: zero if the slave was past that position already,
2698 * greater than zero if we waited for some period of time, less than
2699 * zero if we timed out.
2701 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2702 $fname = 'DatabaseBase::masterPosWait';
2703 wfProfileIn( $fname );
2705 if ( !is_null( $this->mFakeSlaveLag
) ) {
2706 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2708 if ( $wait > $timeout * 1e6
) {
2709 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2710 wfProfileOut( $fname );
2712 } elseif ( $wait > 0 ) {
2713 wfDebug( "Fake slave waiting $wait us\n" );
2715 wfProfileOut( $fname );
2718 wfDebug( "Fake slave up to date ($wait us)\n" );
2719 wfProfileOut( $fname );
2724 wfProfileOut( $fname );
2726 # Real waits are implemented in the subclass.
2731 * Get the replication position of this slave
2733 * @return DBMasterPos, or false if this is not a slave.
2735 function getSlavePos() {
2736 if ( !is_null( $this->mFakeSlaveLag
) ) {
2737 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2738 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2747 * Get the position of this master
2749 * @return DBMasterPos, or false if this is not a master
2751 function getMasterPos() {
2752 if ( $this->mFakeMaster
) {
2753 return new MySQLMasterPos( 'fake', microtime( true ) );
2760 * Begin a transaction, committing any previously open transaction
2762 function begin( $fname = 'DatabaseBase::begin' ) {
2763 $this->query( 'BEGIN', $fname );
2764 $this->mTrxLevel
= 1;
2770 function commit( $fname = 'DatabaseBase::commit' ) {
2771 if ( $this->mTrxLevel
) {
2772 $this->query( 'COMMIT', $fname );
2773 $this->mTrxLevel
= 0;
2778 * Rollback a transaction.
2779 * No-op on non-transactional databases.
2781 function rollback( $fname = 'DatabaseBase::rollback' ) {
2782 if ( $this->mTrxLevel
) {
2783 $this->query( 'ROLLBACK', $fname, true );
2784 $this->mTrxLevel
= 0;
2789 * Creates a new table with structure copied from existing table
2790 * Note that unlike most database abstraction functions, this function does not
2791 * automatically append database prefix, because it works at a lower
2792 * abstraction level.
2793 * The table names passed to this function shall not be quoted (this
2794 * function calls addIdentifierQuotes when needed).
2796 * @param $oldName String: name of table whose structure should be copied
2797 * @param $newName String: name of table to be created
2798 * @param $temporary Boolean: whether the new table should be temporary
2799 * @param $fname String: calling function name
2800 * @return Boolean: true if operation was successful
2802 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2803 $fname = 'DatabaseBase::duplicateTableStructure' )
2805 throw new MWException(
2806 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2810 * List all tables on the database
2812 * @param $prefix Only show tables with this prefix, e.g. mw_
2813 * @param $fname String: calling function name
2815 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2816 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2820 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2821 * to the format used for inserting into timestamp fields in this DBMS.
2823 * The result is unquoted, and needs to be passed through addQuotes()
2824 * before it can be included in raw SQL.
2828 function timestamp( $ts = 0 ) {
2829 return wfTimestamp( TS_MW
, $ts );
2833 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2834 * to the format used for inserting into timestamp fields in this DBMS. If
2835 * NULL is input, it is passed through, allowing NULL values to be inserted
2836 * into timestamp fields.
2838 * The result is unquoted, and needs to be passed through addQuotes()
2839 * before it can be included in raw SQL.
2843 function timestampOrNull( $ts = null ) {
2844 if ( is_null( $ts ) ) {
2847 return $this->timestamp( $ts );
2852 * Take the result from a query, and wrap it in a ResultWrapper if
2853 * necessary. Boolean values are passed through as is, to indicate success
2854 * of write queries or failure.
2856 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2857 * resource, and it was necessary to call this function to convert it to
2858 * a wrapper. Nowadays, raw database objects are never exposed to external
2859 * callers, so this is unnecessary in external code. For compatibility with
2860 * old code, ResultWrapper objects are passed through unaltered.
2862 function resultObject( $result ) {
2863 if ( empty( $result ) ) {
2865 } elseif ( $result instanceof ResultWrapper
) {
2867 } elseif ( $result === true ) {
2868 // Successful write query
2871 return new ResultWrapper( $this, $result );
2876 * Return aggregated value alias
2878 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2883 * Ping the server and try to reconnect if it there is no connection
2885 * @return bool Success or failure
2888 # Stub. Not essential to override.
2894 * Currently supported only by MySQL
2895 * @return Database replication lag in seconds
2898 return intval( $this->mFakeSlaveLag
);
2902 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2906 function maxListLen() {
2911 * Some DBMSs have a special format for inserting into blob fields, they
2912 * don't allow simple quoted strings to be inserted. To insert into such
2913 * a field, pass the data through this function before passing it to
2914 * DatabaseBase::insert().
2916 function encodeBlob( $b ) {
2921 * Some DBMSs return a special placeholder object representing blob fields
2922 * in result objects. Pass the object through this function to return the
2925 function decodeBlob( $b ) {
2930 * Override database's default connection timeout. May be useful for very
2931 * long batch queries such as full-wiki dumps, where a single query reads
2932 * out over hours or days. May or may not be necessary for non-MySQL
2933 * databases. For most purposes, leaving it as a no-op should be fine.
2935 * @param $timeout Integer in seconds
2937 public function setTimeout( $timeout ) {}
2940 * Read and execute SQL commands from a file.
2942 * Returns true on success, error string or exception on failure (depending
2943 * on object's error ignore settings).
2945 * @param $filename String: File name to open
2946 * @param $lineCallback Callback: Optional function called before reading each line
2947 * @param $resultCallback Callback: Optional function called for each MySQL result
2948 * @param $fname String: Calling function name or false if name should be
2949 * generated dynamically using $filename
2951 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2952 wfSuppressWarnings();
2953 $fp = fopen( $filename, 'r' );
2954 wfRestoreWarnings();
2956 if ( false === $fp ) {
2957 throw new MWException( "Could not open \"{$filename}\".\n" );
2961 $fname = __METHOD__
. "( $filename )";
2965 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2967 catch ( MWException
$e ) {
2978 * Get the full path of a patch file. Originally based on archive()
2979 * from updaters.inc. Keep in mind this always returns a patch, as
2980 * it fails back to MySQL if no DB-specific patch can be found
2982 * @param $patch String The name of the patch, like patch-something.sql
2983 * @return String Full path to patch file
2985 public function patchPath( $patch ) {
2988 $dbType = $this->getType();
2989 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2990 return "$IP/maintenance/$dbType/archives/$patch";
2992 return "$IP/maintenance/archives/$patch";
2997 * Set variables to be used in sourceFile/sourceStream, in preference to the
2998 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2999 * all. If it's set to false, $GLOBALS will be used.
3001 * @param $vars False, or array mapping variable name to value.
3003 function setSchemaVars( $vars ) {
3004 $this->mSchemaVars
= $vars;
3008 * Read and execute commands from an open file handle.
3010 * Returns true on success, error string or exception on failure (depending
3011 * on object's error ignore settings).
3013 * @param $fp Resource: File handle
3014 * @param $lineCallback Callback: Optional function called before reading each line
3015 * @param $resultCallback Callback: Optional function called for each MySQL result
3016 * @param $fname String: Calling function name
3018 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3019 $fname = 'DatabaseBase::sourceStream' )
3023 $dollarquote = false;
3025 while ( ! feof( $fp ) ) {
3026 if ( $lineCallback ) {
3027 call_user_func( $lineCallback );
3030 $line = trim( fgets( $fp ) );
3031 $sl = strlen( $line ) - 1;
3037 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
3041 # # Allow dollar quoting for function declarations
3042 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3043 if ( $dollarquote ) {
3044 $dollarquote = false;
3048 $dollarquote = true;
3051 elseif ( !$dollarquote ) {
3052 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
3054 $line = substr( $line, 0, $sl );
3065 $cmd = str_replace( ';;', ";", $cmd );
3066 $cmd = $this->replaceVars( $cmd );
3067 $res = $this->query( $cmd, $fname );
3069 if ( $resultCallback ) {
3070 call_user_func( $resultCallback, $res, $this );
3073 if ( false === $res ) {
3074 $err = $this->lastError();
3075 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3087 * Database independent variable replacement. Replaces a set of variables
3088 * in an SQL statement with their contents as given by $this->getSchemaVars().
3090 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3092 * - '{$var}' should be used for text and is passed through the database's
3094 * - `{$var}` should be used for identifiers (eg: table and database names),
3095 * it is passed through the database's addIdentifierQuotes method which
3096 * can be overridden if the database uses something other than backticks.
3097 * - / *$var* / is just encoded, besides traditional table prefix and
3098 * table options its use should be avoided.
3100 * @param $ins String: SQL statement to replace variables in
3101 * @return String The new SQL statement with variables replaced
3103 protected function replaceSchemaVars( $ins ) {
3104 $vars = $this->getSchemaVars();
3105 foreach ( $vars as $var => $value ) {
3107 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3109 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3111 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3117 * Replace variables in sourced SQL
3119 * @param $ins string
3123 protected function replaceVars( $ins ) {
3124 $ins = $this->replaceSchemaVars( $ins );
3127 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3128 array( $this, 'tableNameCallback' ), $ins );
3131 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3132 array( $this, 'indexNameCallback' ), $ins );
3138 * Get schema variables. If none have been set via setSchemaVars(), then
3139 * use some defaults from the current object.
3141 protected function getSchemaVars() {
3142 if ( $this->mSchemaVars
) {
3143 return $this->mSchemaVars
;
3145 return $this->getDefaultSchemaVars();
3150 * Get schema variables to use if none have been set via setSchemaVars().
3152 * Override this in derived classes to provide variables for tables.sql
3153 * and SQL patch files.
3157 protected function getDefaultSchemaVars() {
3162 * Table name callback
3164 * @param $matches array
3168 protected function tableNameCallback( $matches ) {
3169 return $this->tableName( $matches[1] );
3173 * Index name callback
3175 * @param $matches array
3179 protected function indexNameCallback( $matches ) {
3180 return $this->indexName( $matches[1] );
3184 * Build a concatenation list to feed into a SQL query
3185 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3188 function buildConcat( $stringList ) {
3189 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3193 * Acquire a named lock
3195 * Abstracted from Filestore::lock() so child classes can implement for
3198 * @param $lockName String: name of lock to aquire
3199 * @param $method String: name of method calling us
3200 * @param $timeout Integer: timeout
3203 public function lock( $lockName, $method, $timeout = 5 ) {
3210 * @param $lockName String: Name of lock to release
3211 * @param $method String: Name of method calling us
3213 * @return Returns 1 if the lock was released, 0 if the lock was not established
3214 * by this thread (in which case the lock is not released), and NULL if the named
3215 * lock did not exist
3217 public function unlock( $lockName, $method ) {
3222 * Lock specific tables
3224 * @param $read Array of tables to lock for read access
3225 * @param $write Array of tables to lock for write access
3226 * @param $method String name of caller
3227 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3231 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3236 * Unlock specific tables
3238 * @param $method String the caller
3242 public function unlockTables( $method ) {
3248 * @param $tableName string
3249 * @param $fName string
3250 * @return bool|ResultWrapper
3252 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3253 if( !$this->tableExists( $tableName ) ) {
3256 $sql = "DROP TABLE " . $this->tableName( $tableName );
3257 if( $this->cascadingDeletes() ) {
3260 return $this->query( $sql, $fName );
3264 * Get search engine class. All subclasses of this need to implement this
3265 * if they wish to use searching.
3269 public function getSearchEngine() {
3270 return 'SearchEngineDummy';
3274 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3275 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3276 * because "i" sorts after all numbers.
3280 public function getInfinity() {
3285 * Encode an expiry time
3287 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3290 public function encodeExpiry( $expiry ) {
3291 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3292 return $this->getInfinity();
3294 return $this->timestamp( $expiry );
3299 * Allow or deny "big selects" for this session only. This is done by setting
3300 * the sql_big_selects session variable.
3302 * This is a MySQL-specific feature.
3304 * @param $value Mixed: true for allow, false for deny, or "default" to
3305 * restore the initial value
3307 public function setBigSelects( $value = true ) {