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 ResultWrapper|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 protected $preparedArgs;
229 protected $htmlErrors;
231 # ------------------------------------------------------------------------------
233 # ------------------------------------------------------------------------------
234 # These optionally set a variable and return the previous state
237 * A string describing the current software version, and possibly
238 * other details in a user-friendly way. Will be listed on Special:Version, etc.
239 * Use getServerVersion() to get machine-friendly information.
241 * @return string: Version information from the database server
243 public function getServerInfo() {
244 return $this->getServerVersion();
248 * Boolean, controls output of large amounts of debug information.
249 * @param $debug bool|null
250 * - true to enable debugging
251 * - false to disable debugging
252 * - omitted or null to do nothing
254 * @return The previous value of the flag
256 function debug( $debug = null ) {
257 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
261 * Turns buffering of SQL result sets on (true) or off (false). Default is
264 * Unbuffered queries are very troublesome in MySQL:
266 * - If another query is executed while the first query is being read
267 * out, the first query is killed. This means you can't call normal
268 * MediaWiki functions while you are reading an unbuffered query result
269 * from a normal wfGetDB() connection.
271 * - Unbuffered queries cause the MySQL server to use large amounts of
272 * memory and to hold broad locks which block other queries.
274 * If you want to limit client-side memory, it's almost always better to
275 * split up queries into batches using a LIMIT clause than to switch off
278 * @param $buffer null|bool
280 * @return The previous value of the flag
282 function bufferResults( $buffer = null ) {
283 if ( is_null( $buffer ) ) {
284 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
286 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
291 * Turns on (false) or off (true) the automatic generation and sending
292 * of a "we're sorry, but there has been a database error" page on
293 * database errors. Default is on (false). When turned off, the
294 * code should use lastErrno() and lastError() to handle the
295 * situation as appropriate.
297 * @param $ignoreErrors bool|null
299 * @return bool The previous value of the flag.
301 function ignoreErrors( $ignoreErrors = null ) {
302 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
306 * Gets or sets the current transaction level.
308 * Historically, transactions were allowed to be "nested". This is no
309 * longer supported, so this function really only returns a boolean.
311 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
312 * @return The previous value
314 function trxLevel( $level = null ) {
315 return wfSetVar( $this->mTrxLevel
, $level );
319 * Get/set the number of errors logged. Only useful when errors are ignored
320 * @param $count The count to set, or omitted to leave it unchanged.
321 * @return The error count
323 function errorCount( $count = null ) {
324 return wfSetVar( $this->mErrorCount
, $count );
328 * Get/set the table prefix.
329 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
330 * @return The previous table prefix.
332 function tablePrefix( $prefix = null ) {
333 return wfSetVar( $this->mTablePrefix
, $prefix );
337 * Get properties passed down from the server info array of the load
340 * @param $name string The entry of the info array to get, or null to get the
343 * @return LoadBalancer|null
345 function getLBInfo( $name = null ) {
346 if ( is_null( $name ) ) {
347 return $this->mLBInfo
;
349 if ( array_key_exists( $name, $this->mLBInfo
) ) {
350 return $this->mLBInfo
[$name];
358 * Set the LB info array, or a member of it. If called with one parameter,
359 * the LB info array is set to that parameter. If it is called with two
360 * parameters, the member with the given name is set to the given value.
365 function setLBInfo( $name, $value = null ) {
366 if ( is_null( $value ) ) {
367 $this->mLBInfo
= $name;
369 $this->mLBInfo
[$name] = $value;
374 * Set lag time in seconds for a fake slave
378 function setFakeSlaveLag( $lag ) {
379 $this->mFakeSlaveLag
= $lag;
383 * Make this connection a fake master
385 * @param $enabled bool
387 function setFakeMaster( $enabled = true ) {
388 $this->mFakeMaster
= $enabled;
392 * Returns true if this database supports (and uses) cascading deletes
396 function cascadingDeletes() {
401 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
405 function cleanupTriggers() {
410 * Returns true if this database is strict about what can be put into an IP field.
411 * Specifically, it uses a NULL value instead of an empty string.
415 function strictIPs() {
420 * Returns true if this database uses timestamps rather than integers
424 function realTimestamps() {
429 * Returns true if this database does an implicit sort when doing GROUP BY
433 function implicitGroupby() {
438 * Returns true if this database does an implicit order by when the column has an index
439 * For example: SELECT page_title FROM page LIMIT 1
443 function implicitOrderby() {
448 * Returns true if this database requires that SELECT DISTINCT queries require that all
449 ORDER BY expressions occur in the SELECT list per the SQL92 standard
453 function standardSelectDistinct() {
458 * Returns true if this database can do a native search on IP columns
459 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
463 function searchableIPs() {
468 * Returns true if this database can use functional indexes
472 function functionalIndexes() {
477 * Return the last query that went through DatabaseBase::query()
480 function lastQuery() {
481 return $this->mLastQuery
;
485 * Returns true if the connection may have been used for write queries.
486 * Should return true if unsure.
490 function doneWrites() {
491 return $this->mDoneWrites
;
495 * Is a connection to the database open?
499 return $this->mOpened
;
503 * Set a flag for this connection
505 * @param $flag Integer: DBO_* constants from Defines.php:
506 * - DBO_DEBUG: output some debug info (same as debug())
507 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
508 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
509 * - DBO_TRX: automatically start transactions
510 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
511 * and removes it in command line mode
512 * - DBO_PERSISTENT: use persistant database connection
514 function setFlag( $flag ) {
515 $this->mFlags |
= $flag;
519 * Clear a flag for this connection
521 * @param $flag: same as setFlag()'s $flag param
523 function clearFlag( $flag ) {
524 $this->mFlags
&= ~
$flag;
528 * Returns a boolean whether the flag $flag is set for this connection
530 * @param $flag: same as setFlag()'s $flag param
533 function getFlag( $flag ) {
534 return !!( $this->mFlags
& $flag );
538 * General read-only accessor
540 * @param $name string
544 function getProperty( $name ) {
551 function getWikiID() {
552 if ( $this->mTablePrefix
) {
553 return "{$this->mDBname}-{$this->mTablePrefix}";
555 return $this->mDBname
;
560 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
564 public function getSchemaPath() {
566 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
567 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
569 return "$IP/maintenance/tables.sql";
573 # ------------------------------------------------------------------------------
575 # ------------------------------------------------------------------------------
579 * @param $server String: database server host
580 * @param $user String: database user name
581 * @param $password String: database user password
582 * @param $dbName String: database name
584 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
586 function __construct( $server = false, $user = false, $password = false, $dbName = false,
587 $flags = 0, $tablePrefix = 'get from global'
589 global $wgDBprefix, $wgCommandLineMode;
591 $this->mFlags
= $flags;
593 if ( $this->mFlags
& DBO_DEFAULT
) {
594 if ( $wgCommandLineMode ) {
595 $this->mFlags
&= ~DBO_TRX
;
597 $this->mFlags |
= DBO_TRX
;
601 /** Get the default table prefix*/
602 if ( $tablePrefix == 'get from global' ) {
603 $this->mTablePrefix
= $wgDBprefix;
605 $this->mTablePrefix
= $tablePrefix;
609 $this->open( $server, $user, $password, $dbName );
614 * Called by serialize. Throw an exception when DB connection is serialized.
615 * This causes problems on some database engines because the connection is
616 * not restored on unserialize.
618 public function __sleep() {
619 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
623 * Same as new DatabaseMysql( ... ), kept for backward compatibility
624 * @deprecated since 1.17
631 * @return DatabaseMysql
633 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
634 wfDeprecated( __METHOD__
);
635 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
639 * Given a DB type, construct the name of the appropriate child class of
640 * DatabaseBase. This is designed to replace all of the manual stuff like:
641 * $class = 'Database' . ucfirst( strtolower( $type ) );
642 * as well as validate against the canonical list of DB types we have
644 * This factory function is mostly useful for when you need to connect to a
645 * database other than the MediaWiki default (such as for external auth,
646 * an extension, et cetera). Do not use this to connect to the MediaWiki
647 * database. Example uses in core:
648 * @see LoadBalancer::reallyOpenConnection()
649 * @see ExternalUser_MediaWiki::initFromCond()
650 * @see ForeignDBRepo::getMasterDB()
651 * @see WebInstaller_DBConnect::execute()
653 * @param $dbType String A possible DB type
654 * @param $p Array An array of options to pass to the constructor.
655 * Valid options are: host, user, password, dbname, flags, tablePrefix
656 * @return DatabaseBase subclass or null
658 public final static function factory( $dbType, $p = array() ) {
659 $canonicalDBTypes = array(
660 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
662 $dbType = strtolower( $dbType );
664 if( in_array( $dbType, $canonicalDBTypes ) ) {
665 $class = 'Database' . ucfirst( $dbType );
667 isset( $p['host'] ) ?
$p['host'] : false,
668 isset( $p['user'] ) ?
$p['user'] : false,
669 isset( $p['password'] ) ?
$p['password'] : false,
670 isset( $p['dbname'] ) ?
$p['dbname'] : false,
671 isset( $p['flags'] ) ?
$p['flags'] : 0,
672 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
679 protected function installErrorHandler() {
680 $this->mPHPError
= false;
681 $this->htmlErrors
= ini_set( 'html_errors', '0' );
682 set_error_handler( array( $this, 'connectionErrorHandler' ) );
686 * @return bool|string
688 protected function restoreErrorHandler() {
689 restore_error_handler();
690 if ( $this->htmlErrors
!== false ) {
691 ini_set( 'html_errors', $this->htmlErrors
);
693 if ( $this->mPHPError
) {
694 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
695 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
706 protected function connectionErrorHandler( $errno, $errstr ) {
707 $this->mPHPError
= $errstr;
711 * Closes a database connection.
712 * if it is open : commits any open transactions
714 * @return Bool operation success. true if already closed.
717 # Stub, should probably be overridden
722 * @param $error String: fallback error message, used if none is given by DB
724 function reportConnectionError( $error = 'Unknown error' ) {
725 $myError = $this->lastError();
731 throw new DBConnectionError( $this, $error );
735 * The DBMS-dependent part of query()
737 * @param $sql String: SQL query.
738 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
740 protected abstract function doQuery( $sql );
743 * Determine whether a query writes to the DB.
744 * Should return true if unsure.
750 function isWriteQuery( $sql ) {
751 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
755 * Run an SQL query and return the result. Normally throws a DBQueryError
756 * on failure. If errors are ignored, returns false instead.
758 * In new code, the query wrappers select(), insert(), update(), delete(),
759 * etc. should be used where possible, since they give much better DBMS
760 * independence and automatically quote or validate user input in a variety
761 * of contexts. This function is generally only useful for queries which are
762 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
765 * However, the query wrappers themselves should call this function.
767 * @param $sql String: SQL query
768 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
769 * comment (you can use __METHOD__ or add some extra info)
770 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
771 * maybe best to catch the exception instead?
772 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
773 * for a successful read query, or false on failure if $tempIgnore set
774 * @throws DBQueryError Thrown when the database returns an error of any kind
776 public function query( $sql, $fname = '', $tempIgnore = false ) {
777 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
778 if ( !Profiler
::instance()->isStub() ) {
779 # generalizeSQL will probably cut down the query to reasonable
780 # logging size most of the time. The substr is really just a sanity check.
783 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
784 $totalProf = 'DatabaseBase::query-master';
786 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
787 $totalProf = 'DatabaseBase::query';
790 wfProfileIn( $totalProf );
791 wfProfileIn( $queryProf );
794 $this->mLastQuery
= $sql;
795 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
796 # Set a flag indicating that writes have been done
797 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
798 $this->mDoneWrites
= true;
801 # Add a comment for easy SHOW PROCESSLIST interpretation
803 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
804 $userName = $wgUser->getName();
805 if ( mb_strlen( $userName ) > 15 ) {
806 $userName = mb_substr( $userName, 0, 15 ) . '...';
808 $userName = str_replace( '/', '', $userName );
812 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
814 # If DBO_TRX is set, start a transaction
815 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
816 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
817 # avoid establishing transactions for SHOW and SET statements too -
818 # that would delay transaction initializations to once connection
819 # is really used by application
820 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
821 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
825 if ( $this->debug() ) {
829 $sqlx = substr( $commentedSql, 0, 500 );
830 $sqlx = strtr( $sqlx, "\t\n", ' ' );
833 wfDebug( "Query $cnt (master): $sqlx\n" );
835 wfDebug( "Query $cnt (slave): $sqlx\n" );
839 if ( istainted( $sql ) & TC_MYSQL
) {
840 throw new MWException( 'Tainted query found' );
843 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
845 # Do the query and handle errors
846 $ret = $this->doQuery( $commentedSql );
848 MWDebug
::queryTime( $queryId );
850 # Try reconnecting if the connection was lost
851 if ( false === $ret && $this->wasErrorReissuable() ) {
852 # Transaction is gone, like it or not
853 $this->mTrxLevel
= 0;
854 wfDebug( "Connection lost, reconnecting...\n" );
856 if ( $this->ping() ) {
857 wfDebug( "Reconnected\n" );
858 $sqlx = substr( $commentedSql, 0, 500 );
859 $sqlx = strtr( $sqlx, "\t\n", ' ' );
860 global $wgRequestTime;
861 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
862 if ( $elapsed < 300 ) {
863 # Not a database error to lose a transaction after a minute or two
864 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
866 $ret = $this->doQuery( $commentedSql );
868 wfDebug( "Failed\n" );
872 if ( false === $ret ) {
873 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
876 if ( !Profiler
::instance()->isStub() ) {
877 wfProfileOut( $queryProf );
878 wfProfileOut( $totalProf );
881 return $this->resultObject( $ret );
885 * Report a query error. Log the error, and if neither the object ignore
886 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
888 * @param $error String
889 * @param $errno Integer
891 * @param $fname String
892 * @param $tempIgnore Boolean
894 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
895 # Ignore errors during error handling to avoid infinite recursion
896 $ignore = $this->ignoreErrors( true );
897 ++
$this->mErrorCount
;
899 if ( $ignore ||
$tempIgnore ) {
900 wfDebug( "SQL ERROR (ignored): $error\n" );
901 $this->ignoreErrors( $ignore );
903 $sql1line = str_replace( "\n", "\\n", $sql );
904 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
905 wfDebug( "SQL ERROR: " . $error . "\n" );
906 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
911 * Intended to be compatible with the PEAR::DB wrapper functions.
912 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
914 * ? = scalar value, quoted as necessary
915 * ! = raw SQL bit (a function for instance)
916 * & = filename; reads the file and inserts as a blob
917 * (we don't use this though...)
919 * This function should not be used directly by new code outside of the
920 * database classes. The query wrapper functions (select() etc.) should be
924 * @param $func string
928 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
929 /* MySQL doesn't support prepared statements (yet), so just
930 pack up the query for reference. We'll manually replace
932 return array( 'query' => $sql, 'func' => $func );
936 * Free a prepared query, generated by prepare().
939 function freePrepared( $prepared ) {
940 /* No-op by default */
944 * Execute a prepared query with the various arguments
945 * @param $prepared String: the prepared sql
946 * @param $args Mixed: Either an array here, or put scalars as varargs
948 * @return ResultWrapper
950 function execute( $prepared, $args = null ) {
951 if ( !is_array( $args ) ) {
953 $args = func_get_args();
954 array_shift( $args );
957 $sql = $this->fillPrepared( $prepared['query'], $args );
959 return $this->query( $sql, $prepared['func'] );
963 * Prepare & execute an SQL statement, quoting and inserting arguments
964 * in the appropriate places.
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
970 * @param $query String
973 * @return ResultWrapper
975 function safeQuery( $query, $args = null ) {
976 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
978 if ( !is_array( $args ) ) {
980 $args = func_get_args();
981 array_shift( $args );
984 $retval = $this->execute( $prepared, $args );
985 $this->freePrepared( $prepared );
991 * For faking prepared SQL statements on DBs that don't support
993 * @param $preparedQuery String: a 'preparable' SQL statement
994 * @param $args Array of arguments to fill it with
995 * @return string executable SQL
997 function fillPrepared( $preparedQuery, $args ) {
999 $this->preparedArgs
=& $args;
1001 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1002 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1006 * preg_callback func for fillPrepared()
1007 * The arguments should be in $this->preparedArgs and must not be touched
1008 * while we're doing this.
1010 * @param $matches Array
1013 function fillPreparedArg( $matches ) {
1014 switch( $matches[1] ) {
1015 case '\\?': return '?';
1016 case '\\!': return '!';
1017 case '\\&': return '&';
1020 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1022 switch( $matches[1] ) {
1023 case '?': return $this->addQuotes( $arg );
1024 case '!': return $arg;
1026 # return $this->addQuotes( file_get_contents( $arg ) );
1027 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1029 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1034 * Free a result object returned by query() or select(). It's usually not
1035 * necessary to call this, just use unset() or let the variable holding
1036 * the result object go out of scope.
1038 * @param $res Mixed: A SQL result
1040 function freeResult( $res ) {
1044 * Simple UPDATE wrapper.
1045 * Usually throws a DBQueryError on failure.
1046 * If errors are explicitly ignored, returns success
1048 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1049 * calling convention and feature set
1051 * @param $table string
1055 * @param $fname string
1059 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1060 $table = $this->tableName( $table );
1061 $sql = "UPDATE $table SET $var = '" .
1062 $this->strencode( $value ) . "' WHERE ($cond)";
1064 return (bool)$this->query( $sql, $fname );
1068 * A SELECT wrapper which returns a single field from a single result row.
1070 * Usually throws a DBQueryError on failure. If errors are explicitly
1071 * ignored, returns false on failure.
1073 * If no result rows are returned from the query, false is returned.
1075 * @param $table string|array Table name. See DatabaseBase::select() for details.
1076 * @param $var string The field name to select. This must be a valid SQL
1077 * fragment: do not use unvalidated user input.
1078 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1079 * @param $fname string The function name of the caller.
1080 * @param $options string|array The query options. See DatabaseBase::select() for details.
1082 * @return false|mixed The value from the field, or false on failure.
1084 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1085 $options = array() )
1087 if ( !is_array( $options ) ) {
1088 $options = array( $options );
1091 $options['LIMIT'] = 1;
1093 $res = $this->select( $table, $var, $cond, $fname, $options );
1095 if ( $res === false ||
!$this->numRows( $res ) ) {
1099 $row = $this->fetchRow( $res );
1101 if ( $row !== false ) {
1102 return reset( $row );
1109 * Returns an optional USE INDEX clause to go after the table, and a
1110 * string to go at the end of the query.
1112 * @param $options Array: associative array of options to be turned into
1113 * an SQL query, valid keys are listed in the function.
1115 * @see DatabaseBase::select()
1117 function makeSelectOptions( $options ) {
1118 $preLimitTail = $postLimitTail = '';
1121 $noKeyOptions = array();
1123 foreach ( $options as $key => $option ) {
1124 if ( is_numeric( $key ) ) {
1125 $noKeyOptions[$option] = true;
1129 if ( isset( $options['GROUP BY'] ) ) {
1130 $gb = is_array( $options['GROUP BY'] )
1131 ?
implode( ',', $options['GROUP BY'] )
1132 : $options['GROUP BY'];
1133 $preLimitTail .= " GROUP BY {$gb}";
1136 if ( isset( $options['HAVING'] ) ) {
1137 $preLimitTail .= " HAVING {$options['HAVING']}";
1140 if ( isset( $options['ORDER BY'] ) ) {
1141 $ob = is_array( $options['ORDER BY'] )
1142 ?
implode( ',', $options['ORDER BY'] )
1143 : $options['ORDER BY'];
1144 $preLimitTail .= " ORDER BY {$ob}";
1147 // if (isset($options['LIMIT'])) {
1148 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1149 // isset($options['OFFSET']) ? $options['OFFSET']
1153 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1154 $postLimitTail .= ' FOR UPDATE';
1157 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1158 $postLimitTail .= ' LOCK IN SHARE MODE';
1161 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1162 $startOpts .= 'DISTINCT';
1165 # Various MySQL extensions
1166 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1167 $startOpts .= ' /*! STRAIGHT_JOIN */';
1170 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1171 $startOpts .= ' HIGH_PRIORITY';
1174 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1175 $startOpts .= ' SQL_BIG_RESULT';
1178 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1179 $startOpts .= ' SQL_BUFFER_RESULT';
1182 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1183 $startOpts .= ' SQL_SMALL_RESULT';
1186 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1187 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1190 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1191 $startOpts .= ' SQL_CACHE';
1194 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1195 $startOpts .= ' SQL_NO_CACHE';
1198 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1199 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1204 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1208 * Execute a SELECT query constructed using the various parameters provided.
1209 * See below for full details of the parameters.
1211 * @param $table String|Array Table name
1212 * @param $vars String|Array Field names
1213 * @param $conds String|Array Conditions
1214 * @param $fname String Caller function name
1215 * @param $options Array Query options
1216 * @param $join_conds Array Join conditions
1218 * @param $table string|array
1220 * May be either an array of table names, or a single string holding a table
1221 * name. If an array is given, table aliases can be specified, for example:
1223 * array( 'a' => 'user' )
1225 * This includes the user table in the query, with the alias "a" available
1226 * for use in field names (e.g. a.user_name).
1228 * All of the table names given here are automatically run through
1229 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1230 * added, and various other table name mappings to be performed.
1233 * @param $vars string|array
1235 * May be either a field name or an array of field names. The field names
1236 * here are complete fragments of SQL, for direct inclusion into the SELECT
1237 * query. Expressions and aliases may be specified as in SQL, for example:
1239 * array( 'MAX(rev_id) AS maxrev' )
1241 * If an expression is given, care must be taken to ensure that it is
1245 * @param $conds string|array
1247 * May be either a string containing a single condition, or an array of
1248 * conditions. If an array is given, the conditions constructed from each
1249 * element are combined with AND.
1251 * Array elements may take one of two forms:
1253 * - Elements with a numeric key are interpreted as raw SQL fragments.
1254 * - Elements with a string key are interpreted as equality conditions,
1255 * where the key is the field name.
1256 * - If the value of such an array element is a scalar (such as a
1257 * string), it will be treated as data and thus quoted appropriately.
1258 * If it is null, an IS NULL clause will be added.
1259 * - If the value is an array, an IN(...) clause will be constructed,
1260 * such that the field name may match any of the elements in the
1261 * array. The elements of the array will be quoted.
1263 * Note that expressions are often DBMS-dependent in their syntax.
1264 * DBMS-independent wrappers are provided for constructing several types of
1265 * expression commonly used in condition queries. See:
1266 * - DatabaseBase::buildLike()
1267 * - DatabaseBase::conditional()
1270 * @param $options string|array
1272 * Optional: Array of query options. Boolean options are specified by
1273 * including them in the array as a string value with a numeric key, for
1276 * array( 'FOR UPDATE' )
1278 * The supported options are:
1280 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1281 * with LIMIT can theoretically be used for paging through a result set,
1282 * but this is discouraged in MediaWiki for performance reasons.
1284 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1285 * and then the first rows are taken until the limit is reached. LIMIT
1286 * is applied to a result set after OFFSET.
1288 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1289 * changed until the next COMMIT.
1291 * - DISTINCT: Boolean: return only unique result rows.
1293 * - GROUP BY: May be either an SQL fragment string naming a field or
1294 * expression to group by, or an array of such SQL fragments.
1296 * - HAVING: A string containing a HAVING clause.
1298 * - ORDER BY: May be either an SQL fragment giving a field name or
1299 * expression to order by, or an array of such SQL fragments.
1301 * - USE INDEX: This may be either a string giving the index name to use
1302 * for the query, or an array. If it is an associative array, each key
1303 * gives the table name (or alias), each value gives the index name to
1304 * use for that table. All strings are SQL fragments and so should be
1305 * validated by the caller.
1307 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1308 * instead of SELECT.
1310 * And also the following boolean MySQL extensions, see the MySQL manual
1311 * for documentation:
1313 * - LOCK IN SHARE MODE
1317 * - SQL_BUFFER_RESULT
1318 * - SQL_SMALL_RESULT
1319 * - SQL_CALC_FOUND_ROWS
1324 * @param $join_conds string|array
1326 * Optional associative array of table-specific join conditions. In the
1327 * most common case, this is unnecessary, since the join condition can be
1328 * in $conds. However, it is useful for doing a LEFT JOIN.
1330 * The key of the array contains the table name or alias. The value is an
1331 * array with two elements, numbered 0 and 1. The first gives the type of
1332 * join, the second is an SQL fragment giving the join condition for that
1333 * table. For example:
1335 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1337 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1338 * with no rows in it will be returned. If there was a query error, a
1339 * DBQueryError exception will be thrown, except if the "ignore errors"
1340 * option was set, in which case false will be returned.
1342 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1343 $options = array(), $join_conds = array() ) {
1344 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1346 return $this->query( $sql, $fname );
1350 * The equivalent of DatabaseBase::select() except that the constructed SQL
1351 * is returned, instead of being immediately executed.
1353 * @param $table string|array Table name
1354 * @param $vars string|array Field names
1355 * @param $conds string|array Conditions
1356 * @param $fname string Caller function name
1357 * @param $options string|array Query options
1358 * @param $join_conds string|array Join conditions
1360 * @return SQL query string.
1361 * @see DatabaseBase::select()
1363 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1364 if ( is_array( $vars ) ) {
1365 $vars = implode( ',', $vars );
1368 $options = (array)$options;
1370 if ( is_array( $table ) ) {
1371 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1372 ?
$options['USE INDEX']
1374 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1376 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1378 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1380 } elseif ( $table != '' ) {
1381 if ( $table[0] == ' ' ) {
1382 $from = ' FROM ' . $table;
1384 $from = ' FROM ' . $this->tableName( $table );
1390 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1392 if ( !empty( $conds ) ) {
1393 if ( is_array( $conds ) ) {
1394 $conds = $this->makeList( $conds, LIST_AND
);
1396 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1398 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1401 if ( isset( $options['LIMIT'] ) ) {
1402 $sql = $this->limitResult( $sql, $options['LIMIT'],
1403 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1405 $sql = "$sql $postLimitTail";
1407 if ( isset( $options['EXPLAIN'] ) ) {
1408 $sql = 'EXPLAIN ' . $sql;
1415 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1416 * that a single row object is returned. If the query returns no rows,
1417 * false is returned.
1419 * @param $table string|array Table name
1420 * @param $vars string|array Field names
1421 * @param $conds|array Conditions
1422 * @param $fname string Caller function name
1423 * @param $options string|array Query options
1424 * @param $join_conds array|string Join conditions
1426 * @return ResultWrapper|bool
1428 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1429 $options = array(), $join_conds = array() )
1431 $options['LIMIT'] = 1;
1432 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1434 if ( $res === false ) {
1438 if ( !$this->numRows( $res ) ) {
1442 $obj = $this->fetchObject( $res );
1448 * Estimate rows in dataset.
1450 * MySQL allows you to estimate the number of rows that would be returned
1451 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1452 * index cardinality statistics, and is notoriously inaccurate, especially
1453 * when large numbers of rows have recently been added or deleted.
1455 * For DBMSs that don't support fast result size estimation, this function
1456 * will actually perform the SELECT COUNT(*).
1458 * Takes the same arguments as DatabaseBase::select().
1460 * @param $table String: table name
1461 * @param Array|string $vars : unused
1462 * @param Array|string $conds : filters on the table
1463 * @param $fname String: function name for profiling
1464 * @param $options Array: options for select
1465 * @return Integer: row count
1467 public function estimateRowCount( $table, $vars = '*', $conds = '',
1468 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1471 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1474 $row = $this->fetchRow( $res );
1475 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1482 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1483 * It's only slightly flawed. Don't use for anything important.
1485 * @param $sql String A SQL Query
1489 static function generalizeSQL( $sql ) {
1490 # This does the same as the regexp below would do, but in such a way
1491 # as to avoid crashing php on some large strings.
1492 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1494 $sql = str_replace ( "\\\\", '', $sql );
1495 $sql = str_replace ( "\\'", '', $sql );
1496 $sql = str_replace ( "\\\"", '', $sql );
1497 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1498 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1500 # All newlines, tabs, etc replaced by single space
1501 $sql = preg_replace ( '/\s+/', ' ', $sql );
1504 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1510 * Determines whether a field exists in a table
1512 * @param $table String: table name
1513 * @param $field String: filed to check on that table
1514 * @param $fname String: calling function name (optional)
1515 * @return Boolean: whether $table has filed $field
1517 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1518 $info = $this->fieldInfo( $table, $field );
1524 * Determines whether an index exists
1525 * Usually throws a DBQueryError on failure
1526 * If errors are explicitly ignored, returns NULL on failure
1530 * @param $fname string
1534 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1535 $info = $this->indexInfo( $table, $index, $fname );
1536 if ( is_null( $info ) ) {
1539 return $info !== false;
1544 * Query whether a given table exists
1546 * @param $table string
1547 * @param $fname string
1551 function tableExists( $table, $fname = __METHOD__
) {
1552 $table = $this->tableName( $table );
1553 $old = $this->ignoreErrors( true );
1554 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1555 $this->ignoreErrors( $old );
1561 * mysql_field_type() wrapper
1566 function fieldType( $res, $index ) {
1567 if ( $res instanceof ResultWrapper
) {
1568 $res = $res->result
;
1571 return mysql_field_type( $res, $index );
1575 * Determines if a given index is unique
1577 * @param $table string
1578 * @param $index string
1582 function indexUnique( $table, $index ) {
1583 $indexInfo = $this->indexInfo( $table, $index );
1585 if ( !$indexInfo ) {
1589 return !$indexInfo[0]->Non_unique
;
1593 * Helper for DatabaseBase::insert().
1595 * @param $options array
1598 function makeInsertOptions( $options ) {
1599 return implode( ' ', $options );
1603 * INSERT wrapper, inserts an array into a table.
1607 * - A single associative array. The array keys are the field names, and
1608 * the values are the values to insert. The values are treated as data
1609 * and will be quoted appropriately. If NULL is inserted, this will be
1610 * converted to a database NULL.
1611 * - An array with numeric keys, holding a list of associative arrays.
1612 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1613 * each subarray must be identical to each other, and in the same order.
1615 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1618 * $options is an array of options, with boolean options encoded as values
1619 * with numeric keys, in the same style as $options in
1620 * DatabaseBase::select(). Supported options are:
1622 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1623 * any rows which cause duplicate key errors are not inserted. It's
1624 * possible to determine how many rows were successfully inserted using
1625 * DatabaseBase::affectedRows().
1627 * @param $table String Table name. This will be passed through
1628 * DatabaseBase::tableName().
1629 * @param $a Array of rows to insert
1630 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1631 * @param $options Array of options
1635 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1636 # No rows to insert, easy just return now
1637 if ( !count( $a ) ) {
1641 $table = $this->tableName( $table );
1643 if ( !is_array( $options ) ) {
1644 $options = array( $options );
1647 $options = $this->makeInsertOptions( $options );
1649 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1651 $keys = array_keys( $a[0] );
1654 $keys = array_keys( $a );
1657 $sql = 'INSERT ' . $options .
1658 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1662 foreach ( $a as $row ) {
1668 $sql .= '(' . $this->makeList( $row ) . ')';
1671 $sql .= '(' . $this->makeList( $a ) . ')';
1674 return (bool)$this->query( $sql, $fname );
1678 * Make UPDATE options for the DatabaseBase::update function
1680 * @param $options Array: The options passed to DatabaseBase::update
1683 function makeUpdateOptions( $options ) {
1684 if ( !is_array( $options ) ) {
1685 $options = array( $options );
1690 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1691 $opts[] = $this->lowPriorityOption();
1694 if ( in_array( 'IGNORE', $options ) ) {
1698 return implode( ' ', $opts );
1702 * UPDATE wrapper. Takes a condition array and a SET array.
1704 * @param $table String name of the table to UPDATE. This will be passed through
1705 * DatabaseBase::tableName().
1707 * @param $values Array: An array of values to SET. For each array element,
1708 * the key gives the field name, and the value gives the data
1709 * to set that field to. The data will be quoted by
1710 * DatabaseBase::addQuotes().
1712 * @param $conds Array: An array of conditions (WHERE). See
1713 * DatabaseBase::select() for the details of the format of
1714 * condition arrays. Use '*' to update all rows.
1716 * @param $fname String: The function name of the caller (from __METHOD__),
1717 * for logging and profiling.
1719 * @param $options Array: An array of UPDATE options, can be:
1720 * - IGNORE: Ignore unique key conflicts
1721 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1724 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1725 $table = $this->tableName( $table );
1726 $opts = $this->makeUpdateOptions( $options );
1727 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1729 if ( $conds !== array() && $conds !== '*' ) {
1730 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1733 return $this->query( $sql, $fname );
1737 * Makes an encoded list of strings from an array
1738 * @param $a Array containing the data
1739 * @param $mode int Constant
1740 * - LIST_COMMA: comma separated, no field names
1741 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1742 * the documentation for $conds in DatabaseBase::select().
1743 * - LIST_OR: ORed WHERE clause (without the WHERE)
1744 * - LIST_SET: comma separated with field names, like a SET clause
1745 * - LIST_NAMES: comma separated field names
1749 function makeList( $a, $mode = LIST_COMMA
) {
1750 if ( !is_array( $a ) ) {
1751 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1757 foreach ( $a as $field => $value ) {
1759 if ( $mode == LIST_AND
) {
1761 } elseif ( $mode == LIST_OR
) {
1770 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1771 $list .= "($value)";
1772 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1774 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1775 if ( count( $value ) == 0 ) {
1776 throw new MWException( __METHOD__
. ': empty input' );
1777 } elseif ( count( $value ) == 1 ) {
1778 // Special-case single values, as IN isn't terribly efficient
1779 // Don't necessarily assume the single key is 0; we don't
1780 // enforce linear numeric ordering on other arrays here.
1781 $value = array_values( $value );
1782 $list .= $field . " = " . $this->addQuotes( $value[0] );
1784 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1786 } elseif ( $value === null ) {
1787 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1788 $list .= "$field IS ";
1789 } elseif ( $mode == LIST_SET
) {
1790 $list .= "$field = ";
1794 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1795 $list .= "$field = ";
1797 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1805 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1806 * The keys on each level may be either integers or strings.
1808 * @param $data Array: organized as 2-d
1809 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1810 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1811 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1812 * @return Mixed: string SQL fragment, or false if no items in array.
1814 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1817 foreach ( $data as $base => $sub ) {
1818 if ( count( $sub ) ) {
1819 $conds[] = $this->makeList(
1820 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1826 return $this->makeList( $conds, LIST_OR
);
1828 // Nothing to search for...
1834 * Bitwise operations
1841 function bitNot( $field ) {
1847 * @param $fieldRight
1850 function bitAnd( $fieldLeft, $fieldRight ) {
1851 return "($fieldLeft & $fieldRight)";
1856 * @param $fieldRight
1859 function bitOr( $fieldLeft, $fieldRight ) {
1860 return "($fieldLeft | $fieldRight)";
1864 * Change the current database
1866 * @todo Explain what exactly will fail if this is not overridden.
1870 * @return bool Success or failure
1872 function selectDB( $db ) {
1873 # Stub. Shouldn't cause serious problems if it's not overridden, but
1874 # if your database engine supports a concept similar to MySQL's
1875 # databases you may as well.
1876 $this->mDBname
= $db;
1881 * Get the current DB name
1883 function getDBname() {
1884 return $this->mDBname
;
1888 * Get the server hostname or IP address
1890 function getServer() {
1891 return $this->mServer
;
1895 * Format a table name ready for use in constructing an SQL query
1897 * This does two important things: it quotes the table names to clean them up,
1898 * and it adds a table prefix if only given a table name with no quotes.
1900 * All functions of this object which require a table name call this function
1901 * themselves. Pass the canonical name to such functions. This is only needed
1902 * when calling query() directly.
1904 * @param $name String: database table name
1905 * @param $format String One of:
1906 * quoted - Automatically pass the table name through addIdentifierQuotes()
1907 * so that it can be used in a query.
1908 * raw - Do not add identifier quotes to the table name
1909 * @return String: full database name
1911 function tableName( $name, $format = 'quoted' ) {
1912 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1913 # Skip the entire process when we have a string quoted on both ends.
1914 # Note that we check the end so that we will still quote any use of
1915 # use of `database`.table. But won't break things if someone wants
1916 # to query a database table with a dot in the name.
1917 if ( $this->isQuotedIdentifier( $name ) ) {
1921 # Lets test for any bits of text that should never show up in a table
1922 # name. Basically anything like JOIN or ON which are actually part of
1923 # SQL queries, but may end up inside of the table value to combine
1924 # sql. Such as how the API is doing.
1925 # Note that we use a whitespace test rather than a \b test to avoid
1926 # any remote case where a word like on may be inside of a table name
1927 # surrounded by symbols which may be considered word breaks.
1928 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1932 # Split database and table into proper variables.
1933 # We reverse the explode so that database.table and table both output
1934 # the correct table.
1935 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1936 if ( isset( $dbDetails[1] ) ) {
1937 list( $table, $database ) = $dbDetails;
1939 list( $table ) = $dbDetails;
1941 $prefix = $this->mTablePrefix
; # Default prefix
1943 # A database name has been specified in input. We don't want any
1945 if ( isset( $database ) ) {
1949 # Note that we use the long format because php will complain in in_array if
1950 # the input is not an array, and will complain in is_array if it is not set.
1951 if ( !isset( $database ) # Don't use shared database if pre selected.
1952 && isset( $wgSharedDB ) # We have a shared database
1953 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1954 && isset( $wgSharedTables )
1955 && is_array( $wgSharedTables )
1956 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1957 $database = $wgSharedDB;
1958 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1961 # Quote the $database and $table and apply the prefix if not quoted.
1962 if ( isset( $database ) ) {
1963 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1966 $table = "{$prefix}{$table}";
1967 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1968 $table = $this->addIdentifierQuotes( "{$table}" );
1971 # Merge our database and table into our final table name.
1972 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1978 * Fetch a number of table names into an array
1979 * This is handy when you need to construct SQL for joins
1982 * extract($dbr->tableNames('user','watchlist'));
1983 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1984 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1988 public function tableNames() {
1989 $inArray = func_get_args();
1992 foreach ( $inArray as $name ) {
1993 $retVal[$name] = $this->tableName( $name );
2000 * Fetch a number of table names into an zero-indexed numerical array
2001 * This is handy when you need to construct SQL for joins
2004 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2005 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2006 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2010 public function tableNamesN() {
2011 $inArray = func_get_args();
2014 foreach ( $inArray as $name ) {
2015 $retVal[] = $this->tableName( $name );
2022 * Get an aliased table name
2023 * e.g. tableName AS newTableName
2025 * @param $name string Table name, see tableName()
2026 * @param $alias string|bool Alias (optional)
2027 * @return string SQL name for aliased table. Will not alias a table to its own name
2029 public function tableNameWithAlias( $name, $alias = false ) {
2030 if ( !$alias ||
$alias == $name ) {
2031 return $this->tableName( $name );
2033 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2038 * Gets an array of aliased table names
2040 * @param $tables array( [alias] => table )
2041 * @return array of strings, see tableNameWithAlias()
2043 public function tableNamesWithAlias( $tables ) {
2045 foreach ( $tables as $alias => $table ) {
2046 if ( is_numeric( $alias ) ) {
2049 $retval[] = $this->tableNameWithAlias( $table, $alias );
2055 * Get the aliased table name clause for a FROM clause
2056 * which might have a JOIN and/or USE INDEX clause
2058 * @param $tables array ( [alias] => table )
2059 * @param $use_index array Same as for select()
2060 * @param $join_conds array Same as for select()
2063 protected function tableNamesWithUseIndexOrJOIN(
2064 $tables, $use_index = array(), $join_conds = array()
2068 $use_index = (array)$use_index;
2069 $join_conds = (array)$join_conds;
2071 foreach ( $tables as $alias => $table ) {
2072 if ( !is_string( $alias ) ) {
2073 // No alias? Set it equal to the table name
2076 // Is there a JOIN clause for this table?
2077 if ( isset( $join_conds[$alias] ) ) {
2078 list( $joinType, $conds ) = $join_conds[$alias];
2079 $tableClause = $joinType;
2080 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2081 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2082 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2084 $tableClause .= ' ' . $use;
2087 $on = $this->makeList( (array)$conds, LIST_AND
);
2089 $tableClause .= ' ON (' . $on . ')';
2092 $retJOIN[] = $tableClause;
2093 // Is there an INDEX clause for this table?
2094 } elseif ( isset( $use_index[$alias] ) ) {
2095 $tableClause = $this->tableNameWithAlias( $table, $alias );
2096 $tableClause .= ' ' . $this->useIndexClause(
2097 implode( ',', (array)$use_index[$alias] ) );
2099 $ret[] = $tableClause;
2101 $tableClause = $this->tableNameWithAlias( $table, $alias );
2103 $ret[] = $tableClause;
2107 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2108 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2109 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2111 // Compile our final table clause
2112 return implode( ' ', array( $straightJoins, $otherJoins ) );
2116 * Get the name of an index in a given table
2122 function indexName( $index ) {
2123 // Backwards-compatibility hack
2125 'ar_usertext_timestamp' => 'usertext_timestamp',
2126 'un_user_id' => 'user_id',
2127 'un_user_ip' => 'user_ip',
2130 if ( isset( $renamed[$index] ) ) {
2131 return $renamed[$index];
2138 * If it's a string, adds quotes and backslashes
2139 * Otherwise returns as-is
2145 function addQuotes( $s ) {
2146 if ( $s === null ) {
2149 # This will also quote numeric values. This should be harmless,
2150 # and protects against weird problems that occur when they really
2151 # _are_ strings such as article titles and string->number->string
2152 # conversion is not 1:1.
2153 return "'" . $this->strencode( $s ) . "'";
2158 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2159 * MySQL uses `backticks` while basically everything else uses double quotes.
2160 * Since MySQL is the odd one out here the double quotes are our generic
2161 * and we implement backticks in DatabaseMysql.
2167 public function addIdentifierQuotes( $s ) {
2168 return '"' . str_replace( '"', '""', $s ) . '"';
2172 * Returns if the given identifier looks quoted or not according to
2173 * the database convention for quoting identifiers .
2175 * @param $name string
2179 public function isQuotedIdentifier( $name ) {
2180 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2184 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2185 * which used quote_ident which does not follow our naming conventions
2186 * was renamed to addIdentifierQuotes.
2187 * @deprecated since 1.18 use addIdentifierQuotes
2193 function quote_ident( $s ) {
2194 wfDeprecated( __METHOD__
);
2195 return $this->addIdentifierQuotes( $s );
2199 * Escape string for safe LIKE usage.
2200 * WARNING: you should almost never use this function directly,
2201 * instead use buildLike() that escapes everything automatically
2202 * @deprecated since 1.17, warnings in 1.17, removed in ???
2208 public function escapeLike( $s ) {
2209 wfDeprecated( __METHOD__
);
2210 return $this->escapeLikeInternal( $s );
2217 protected function escapeLikeInternal( $s ) {
2218 $s = str_replace( '\\', '\\\\', $s );
2219 $s = $this->strencode( $s );
2220 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2226 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2227 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2228 * Alternatively, the function could be provided with an array of aforementioned parameters.
2230 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2231 * for subpages of 'My page title'.
2232 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2235 * @return String: fully built LIKE statement
2237 function buildLike() {
2238 $params = func_get_args();
2240 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2241 $params = $params[0];
2246 foreach ( $params as $value ) {
2247 if ( $value instanceof LikeMatch
) {
2248 $s .= $value->toString();
2250 $s .= $this->escapeLikeInternal( $value );
2254 return " LIKE '" . $s . "' ";
2258 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2262 function anyChar() {
2263 return new LikeMatch( '_' );
2267 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2271 function anyString() {
2272 return new LikeMatch( '%' );
2276 * Returns an appropriately quoted sequence value for inserting a new row.
2277 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2278 * subclass will return an integer, and save the value for insertId()
2280 * Any implementation of this function should *not* involve reusing
2281 * sequence numbers created for rolled-back transactions.
2282 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2286 function nextSequenceValue( $seqName ) {
2291 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2292 * is only needed because a) MySQL must be as efficient as possible due to
2293 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2294 * which index to pick. Anyway, other databases might have different
2295 * indexes on a given table. So don't bother overriding this unless you're
2300 function useIndexClause( $index ) {
2305 * REPLACE query wrapper.
2307 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2308 * except that when there is a duplicate key error, the old row is deleted
2309 * and the new row is inserted in its place.
2311 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2312 * perform the delete, we need to know what the unique indexes are so that
2313 * we know how to find the conflicting rows.
2315 * It may be more efficient to leave off unique indexes which are unlikely
2316 * to collide. However if you do this, you run the risk of encountering
2317 * errors which wouldn't have occurred in MySQL.
2319 * @param $table String: The table to replace the row(s) in.
2320 * @param $rows array Can be either a single row to insert, or multiple rows,
2321 * in the same format as for DatabaseBase::insert()
2322 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2323 * a field name or an array of field names
2324 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2326 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2327 $quotedTable = $this->tableName( $table );
2329 if ( count( $rows ) == 0 ) {
2334 if ( !is_array( reset( $rows ) ) ) {
2335 $rows = array( $rows );
2338 foreach( $rows as $row ) {
2339 # Delete rows which collide
2340 if ( $uniqueIndexes ) {
2341 $sql = "DELETE FROM $quotedTable WHERE ";
2343 foreach ( $uniqueIndexes as $index ) {
2350 if ( is_array( $index ) ) {
2352 foreach ( $index as $col ) {
2358 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2361 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2365 $this->query( $sql, $fname );
2368 # Now insert the row
2369 $this->insert( $table, $row );
2374 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2377 * @param $table Table name
2378 * @param $rows Rows to insert
2379 * @param $fname Caller function name
2381 * @return ResultWrapper
2383 protected function nativeReplace( $table, $rows, $fname ) {
2384 $table = $this->tableName( $table );
2387 if ( !is_array( reset( $rows ) ) ) {
2388 $rows = array( $rows );
2391 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2394 foreach ( $rows as $row ) {
2401 $sql .= '(' . $this->makeList( $row ) . ')';
2404 return $this->query( $sql, $fname );
2408 * DELETE where the condition is a join.
2410 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2411 * we use sub-selects
2413 * For safety, an empty $conds will not delete everything. If you want to
2414 * delete all rows where the join condition matches, set $conds='*'.
2416 * DO NOT put the join condition in $conds.
2418 * @param $delTable String: The table to delete from.
2419 * @param $joinTable String: The other table.
2420 * @param $delVar String: The variable to join on, in the first table.
2421 * @param $joinVar String: The variable to join on, in the second table.
2422 * @param $conds Array: Condition array of field names mapped to variables,
2423 * ANDed together in the WHERE clause
2424 * @param $fname String: Calling function name (use __METHOD__) for
2427 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2428 $fname = 'DatabaseBase::deleteJoin' )
2431 throw new DBUnexpectedError( $this,
2432 'DatabaseBase::deleteJoin() called with empty $conds' );
2435 $delTable = $this->tableName( $delTable );
2436 $joinTable = $this->tableName( $joinTable );
2437 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2438 if ( $conds != '*' ) {
2439 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2443 $this->query( $sql, $fname );
2447 * Returns the size of a text field, or -1 for "unlimited"
2449 * @param $table string
2450 * @param $field string
2454 function textFieldSize( $table, $field ) {
2455 $table = $this->tableName( $table );
2456 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2457 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2458 $row = $this->fetchObject( $res );
2462 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2472 * A string to insert into queries to show that they're low-priority, like
2473 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2474 * string and nothing bad should happen.
2476 * @return string Returns the text of the low priority option if it is
2477 * supported, or a blank string otherwise
2479 function lowPriorityOption() {
2484 * DELETE query wrapper.
2486 * @param $table Array Table name
2487 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2488 * the format. Use $conds == "*" to delete all rows
2489 * @param $fname String name of the calling function
2493 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2495 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2498 $table = $this->tableName( $table );
2499 $sql = "DELETE FROM $table";
2501 if ( $conds != '*' ) {
2502 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2505 return $this->query( $sql, $fname );
2509 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2510 * into another table.
2512 * @param $destTable string The table name to insert into
2513 * @param $srcTable string|array May be either a table name, or an array of table names
2514 * to include in a join.
2516 * @param $varMap array must be an associative array of the form
2517 * array( 'dest1' => 'source1', ...). Source items may be literals
2518 * rather than field names, but strings should be quoted with
2519 * DatabaseBase::addQuotes()
2521 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2522 * the details of the format of condition arrays. May be "*" to copy the
2525 * @param $fname string The function name of the caller, from __METHOD__
2527 * @param $insertOptions array Options for the INSERT part of the query, see
2528 * DatabaseBase::insert() for details.
2529 * @param $selectOptions array Options for the SELECT part of the query, see
2530 * DatabaseBase::select() for details.
2532 * @return ResultWrapper
2534 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2535 $fname = 'DatabaseBase::insertSelect',
2536 $insertOptions = array(), $selectOptions = array() )
2538 $destTable = $this->tableName( $destTable );
2540 if ( is_array( $insertOptions ) ) {
2541 $insertOptions = implode( ' ', $insertOptions );
2544 if ( !is_array( $selectOptions ) ) {
2545 $selectOptions = array( $selectOptions );
2548 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2550 if ( is_array( $srcTable ) ) {
2551 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2553 $srcTable = $this->tableName( $srcTable );
2556 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2557 " SELECT $startOpts " . implode( ',', $varMap ) .
2558 " FROM $srcTable $useIndex ";
2560 if ( $conds != '*' ) {
2561 if ( is_array( $conds ) ) {
2562 $conds = $this->makeList( $conds, LIST_AND
);
2564 $sql .= " WHERE $conds";
2567 $sql .= " $tailOpts";
2569 return $this->query( $sql, $fname );
2573 * Construct a LIMIT query with optional offset. This is used for query
2574 * pages. The SQL should be adjusted so that only the first $limit rows
2575 * are returned. If $offset is provided as well, then the first $offset
2576 * rows should be discarded, and the next $limit rows should be returned.
2577 * If the result of the query is not ordered, then the rows to be returned
2578 * are theoretically arbitrary.
2580 * $sql is expected to be a SELECT, if that makes a difference. For
2581 * UPDATE, limitResultForUpdate should be used.
2583 * The version provided by default works in MySQL and SQLite. It will very
2584 * likely need to be overridden for most other DBMSes.
2586 * @param $sql String SQL query we will append the limit too
2587 * @param $limit Integer the SQL limit
2588 * @param $offset Integer|false the SQL offset (default false)
2592 function limitResult( $sql, $limit, $offset = false ) {
2593 if ( !is_numeric( $limit ) ) {
2594 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2597 return "$sql LIMIT "
2598 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2607 function limitResultForUpdate( $sql, $num ) {
2608 return $this->limitResult( $sql, $num, 0 );
2612 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2613 * within the UNION construct.
2616 function unionSupportsOrderAndLimit() {
2617 return true; // True for almost every DB supported
2621 * Construct a UNION query
2622 * This is used for providing overload point for other DB abstractions
2623 * not compatible with the MySQL syntax.
2624 * @param $sqls Array: SQL statements to combine
2625 * @param $all Boolean: use UNION ALL
2626 * @return String: SQL fragment
2628 function unionQueries( $sqls, $all ) {
2629 $glue = $all ?
') UNION ALL (' : ') UNION (';
2630 return '(' . implode( $glue, $sqls ) . ')';
2634 * Returns an SQL expression for a simple conditional. This doesn't need
2635 * to be overridden unless CASE isn't supported in your DBMS.
2637 * @param $cond String: SQL expression which will result in a boolean value
2638 * @param $trueVal String: SQL expression to return if true
2639 * @param $falseVal String: SQL expression to return if false
2640 * @return String: SQL fragment
2642 function conditional( $cond, $trueVal, $falseVal ) {
2643 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2647 * Returns a comand for str_replace function in SQL query.
2648 * Uses REPLACE() in MySQL
2650 * @param $orig String: column to modify
2651 * @param $old String: column to seek
2652 * @param $new String: column to replace with
2656 function strreplace( $orig, $old, $new ) {
2657 return "REPLACE({$orig}, {$old}, {$new})";
2661 * Determines how long the server has been up
2666 function getServerUptime() {
2671 * Determines if the last failure was due to a deadlock
2676 function wasDeadlock() {
2681 * Determines if the last failure was due to a lock timeout
2686 function wasLockTimeout() {
2691 * Determines if the last query error was something that should be dealt
2692 * with by pinging the connection and reissuing the query.
2697 function wasErrorReissuable() {
2702 * Determines if the last failure was due to the database being read-only.
2707 function wasReadOnlyError() {
2712 * Perform a deadlock-prone transaction.
2714 * This function invokes a callback function to perform a set of write
2715 * queries. If a deadlock occurs during the processing, the transaction
2716 * will be rolled back and the callback function will be called again.
2719 * $dbw->deadlockLoop( callback, ... );
2721 * Extra arguments are passed through to the specified callback function.
2723 * Returns whatever the callback function returned on its successful,
2724 * iteration, or false on error, for example if the retry limit was
2729 function deadlockLoop() {
2730 $myFname = 'DatabaseBase::deadlockLoop';
2733 $args = func_get_args();
2734 $function = array_shift( $args );
2735 $oldIgnore = $this->ignoreErrors( true );
2736 $tries = DEADLOCK_TRIES
;
2738 if ( is_array( $function ) ) {
2739 $fname = $function[0];
2745 $retVal = call_user_func_array( $function, $args );
2746 $error = $this->lastError();
2747 $errno = $this->lastErrno();
2748 $sql = $this->lastQuery();
2751 if ( $this->wasDeadlock() ) {
2753 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2755 $this->reportQueryError( $error, $errno, $sql, $fname );
2758 } while ( $this->wasDeadlock() && --$tries > 0 );
2760 $this->ignoreErrors( $oldIgnore );
2762 if ( $tries <= 0 ) {
2763 $this->rollback( $myFname );
2764 $this->reportQueryError( $error, $errno, $sql, $fname );
2767 $this->commit( $myFname );
2773 * Wait for the slave to catch up to a given master position.
2775 * @param $pos DBMasterPos object
2776 * @param $timeout Integer: the maximum number of seconds to wait for
2779 * @return An integer: zero if the slave was past that position already,
2780 * greater than zero if we waited for some period of time, less than
2781 * zero if we timed out.
2783 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2784 $fname = 'DatabaseBase::masterPosWait';
2785 wfProfileIn( $fname );
2787 if ( !is_null( $this->mFakeSlaveLag
) ) {
2788 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2790 if ( $wait > $timeout * 1e6
) {
2791 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2792 wfProfileOut( $fname );
2794 } elseif ( $wait > 0 ) {
2795 wfDebug( "Fake slave waiting $wait us\n" );
2797 wfProfileOut( $fname );
2800 wfDebug( "Fake slave up to date ($wait us)\n" );
2801 wfProfileOut( $fname );
2806 wfProfileOut( $fname );
2808 # Real waits are implemented in the subclass.
2813 * Get the replication position of this slave
2815 * @return DBMasterPos, or false if this is not a slave.
2817 function getSlavePos() {
2818 if ( !is_null( $this->mFakeSlaveLag
) ) {
2819 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2820 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2829 * Get the position of this master
2831 * @return DBMasterPos, or false if this is not a master
2833 function getMasterPos() {
2834 if ( $this->mFakeMaster
) {
2835 return new MySQLMasterPos( 'fake', microtime( true ) );
2842 * Begin a transaction, committing any previously open transaction
2844 * @param $fname string
2846 function begin( $fname = 'DatabaseBase::begin' ) {
2847 $this->query( 'BEGIN', $fname );
2848 $this->mTrxLevel
= 1;
2854 * @param $fname string
2856 function commit( $fname = 'DatabaseBase::commit' ) {
2857 if ( $this->mTrxLevel
) {
2858 $this->query( 'COMMIT', $fname );
2859 $this->mTrxLevel
= 0;
2864 * Rollback a transaction.
2865 * No-op on non-transactional databases.
2867 * @param $fname string
2869 function rollback( $fname = 'DatabaseBase::rollback' ) {
2870 if ( $this->mTrxLevel
) {
2871 $this->query( 'ROLLBACK', $fname, true );
2872 $this->mTrxLevel
= 0;
2877 * Creates a new table with structure copied from existing table
2878 * Note that unlike most database abstraction functions, this function does not
2879 * automatically append database prefix, because it works at a lower
2880 * abstraction level.
2881 * The table names passed to this function shall not be quoted (this
2882 * function calls addIdentifierQuotes when needed).
2884 * @param $oldName String: name of table whose structure should be copied
2885 * @param $newName String: name of table to be created
2886 * @param $temporary Boolean: whether the new table should be temporary
2887 * @param $fname String: calling function name
2888 * @return Boolean: true if operation was successful
2890 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2891 $fname = 'DatabaseBase::duplicateTableStructure' )
2893 throw new MWException(
2894 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2898 * List all tables on the database
2900 * @param $prefix Only show tables with this prefix, e.g. mw_
2901 * @param $fname String: calling function name
2903 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2904 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2908 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2909 * to the format used for inserting into timestamp fields in this DBMS.
2911 * The result is unquoted, and needs to be passed through addQuotes()
2912 * before it can be included in raw SQL.
2914 * @param $ts string|int
2918 function timestamp( $ts = 0 ) {
2919 return wfTimestamp( TS_MW
, $ts );
2923 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2924 * to the format used for inserting into timestamp fields in this DBMS. If
2925 * NULL is input, it is passed through, allowing NULL values to be inserted
2926 * into timestamp fields.
2928 * The result is unquoted, and needs to be passed through addQuotes()
2929 * before it can be included in raw SQL.
2931 * @param $ts string|int
2935 function timestampOrNull( $ts = null ) {
2936 if ( is_null( $ts ) ) {
2939 return $this->timestamp( $ts );
2944 * Take the result from a query, and wrap it in a ResultWrapper if
2945 * necessary. Boolean values are passed through as is, to indicate success
2946 * of write queries or failure.
2948 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2949 * resource, and it was necessary to call this function to convert it to
2950 * a wrapper. Nowadays, raw database objects are never exposed to external
2951 * callers, so this is unnecessary in external code. For compatibility with
2952 * old code, ResultWrapper objects are passed through unaltered.
2954 * @param $result bool|ResultWrapper
2956 * @return bool|ResultWrapper
2958 function resultObject( $result ) {
2959 if ( empty( $result ) ) {
2961 } elseif ( $result instanceof ResultWrapper
) {
2963 } elseif ( $result === true ) {
2964 // Successful write query
2967 return new ResultWrapper( $this, $result );
2972 * Return aggregated value alias
2975 * @param $valuename string
2979 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2984 * Ping the server and try to reconnect if it there is no connection
2986 * @return bool Success or failure
2989 # Stub. Not essential to override.
2994 * Get slave lag. Currently supported only by MySQL.
2996 * Note that this function will generate a fatal error on many
2997 * installations. Most callers should use LoadBalancer::safeGetLag()
3000 * @return Database replication lag in seconds
3003 return intval( $this->mFakeSlaveLag
);
3007 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3011 function maxListLen() {
3016 * Some DBMSs have a special format for inserting into blob fields, they
3017 * don't allow simple quoted strings to be inserted. To insert into such
3018 * a field, pass the data through this function before passing it to
3019 * DatabaseBase::insert().
3023 function encodeBlob( $b ) {
3028 * Some DBMSs return a special placeholder object representing blob fields
3029 * in result objects. Pass the object through this function to return the
3034 function decodeBlob( $b ) {
3039 * Override database's default connection timeout
3041 * @param $timeout Integer in seconds
3043 * @deprecated since 1.19; use setSessionOptions()
3045 public function setTimeout( $timeout ) {
3046 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3050 * Override database's default behavior. $options include:
3051 * 'connTimeout' : Set the connection timeout value in seconds.
3052 * May be useful for very long batch queries such as
3053 * full-wiki dumps, where a single query reads out over
3056 * @param $options Array
3059 public function setSessionOptions( array $options ) {}
3062 * Read and execute SQL commands from a file.
3064 * Returns true on success, error string or exception on failure (depending
3065 * on object's error ignore settings).
3067 * @param $filename String: File name to open
3068 * @param $lineCallback Callback: Optional function called before reading each line
3069 * @param $resultCallback Callback: Optional function called for each MySQL result
3070 * @param $fname String: Calling function name or false if name should be
3071 * generated dynamically using $filename
3072 * @return bool|string
3074 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3075 wfSuppressWarnings();
3076 $fp = fopen( $filename, 'r' );
3077 wfRestoreWarnings();
3079 if ( false === $fp ) {
3080 throw new MWException( "Could not open \"{$filename}\".\n" );
3084 $fname = __METHOD__
. "( $filename )";
3088 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3090 catch ( MWException
$e ) {
3101 * Get the full path of a patch file. Originally based on archive()
3102 * from updaters.inc. Keep in mind this always returns a patch, as
3103 * it fails back to MySQL if no DB-specific patch can be found
3105 * @param $patch String The name of the patch, like patch-something.sql
3106 * @return String Full path to patch file
3108 public function patchPath( $patch ) {
3111 $dbType = $this->getType();
3112 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3113 return "$IP/maintenance/$dbType/archives/$patch";
3115 return "$IP/maintenance/archives/$patch";
3120 * Set variables to be used in sourceFile/sourceStream, in preference to the
3121 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3122 * all. If it's set to false, $GLOBALS will be used.
3124 * @param $vars False, or array mapping variable name to value.
3126 function setSchemaVars( $vars ) {
3127 $this->mSchemaVars
= $vars;
3131 * Read and execute commands from an open file handle.
3133 * Returns true on success, error string or exception on failure (depending
3134 * on object's error ignore settings).
3136 * @param $fp Resource: File handle
3137 * @param $lineCallback Callback: Optional function called before reading each line
3138 * @param $resultCallback Callback: Optional function called for each MySQL result
3139 * @param $fname String: Calling function name
3140 * @return bool|string
3142 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3143 $fname = 'DatabaseBase::sourceStream' )
3147 $dollarquote = false;
3149 while ( ! feof( $fp ) ) {
3150 if ( $lineCallback ) {
3151 call_user_func( $lineCallback );
3154 $line = trim( fgets( $fp ) );
3155 $sl = strlen( $line ) - 1;
3161 if ( '-' == $line[0] && '-' == $line[1] ) {
3165 # # Allow dollar quoting for function declarations
3166 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3167 if ( $dollarquote ) {
3168 $dollarquote = false;
3172 $dollarquote = true;
3175 elseif ( !$dollarquote ) {
3176 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
3178 $line = substr( $line, 0, $sl );
3189 $cmd = str_replace( ';;', ";", $cmd );
3190 $cmd = $this->replaceVars( $cmd );
3191 $res = $this->query( $cmd, $fname );
3193 if ( $resultCallback ) {
3194 call_user_func( $resultCallback, $res, $this );
3197 if ( false === $res ) {
3198 $err = $this->lastError();
3199 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3211 * Database independent variable replacement. Replaces a set of variables
3212 * in an SQL statement with their contents as given by $this->getSchemaVars().
3214 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3216 * - '{$var}' should be used for text and is passed through the database's
3218 * - `{$var}` should be used for identifiers (eg: table and database names),
3219 * it is passed through the database's addIdentifierQuotes method which
3220 * can be overridden if the database uses something other than backticks.
3221 * - / *$var* / is just encoded, besides traditional table prefix and
3222 * table options its use should be avoided.
3224 * @param $ins String: SQL statement to replace variables in
3225 * @return String The new SQL statement with variables replaced
3227 protected function replaceSchemaVars( $ins ) {
3228 $vars = $this->getSchemaVars();
3229 foreach ( $vars as $var => $value ) {
3231 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3233 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3235 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3241 * Replace variables in sourced SQL
3243 * @param $ins string
3247 protected function replaceVars( $ins ) {
3248 $ins = $this->replaceSchemaVars( $ins );
3251 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3252 array( $this, 'tableNameCallback' ), $ins );
3255 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3256 array( $this, 'indexNameCallback' ), $ins );
3262 * Get schema variables. If none have been set via setSchemaVars(), then
3263 * use some defaults from the current object.
3267 protected function getSchemaVars() {
3268 if ( $this->mSchemaVars
) {
3269 return $this->mSchemaVars
;
3271 return $this->getDefaultSchemaVars();
3276 * Get schema variables to use if none have been set via setSchemaVars().
3278 * Override this in derived classes to provide variables for tables.sql
3279 * and SQL patch files.
3283 protected function getDefaultSchemaVars() {
3288 * Table name callback
3290 * @param $matches array
3294 protected function tableNameCallback( $matches ) {
3295 return $this->tableName( $matches[1] );
3299 * Index name callback
3301 * @param $matches array
3305 protected function indexNameCallback( $matches ) {
3306 return $this->indexName( $matches[1] );
3310 * Build a concatenation list to feed into a SQL query
3311 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3314 function buildConcat( $stringList ) {
3315 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3319 * Acquire a named lock
3321 * Abstracted from Filestore::lock() so child classes can implement for
3324 * @param $lockName String: name of lock to aquire
3325 * @param $method String: name of method calling us
3326 * @param $timeout Integer: timeout
3329 public function lock( $lockName, $method, $timeout = 5 ) {
3336 * @param $lockName String: Name of lock to release
3337 * @param $method String: Name of method calling us
3339 * @return Returns 1 if the lock was released, 0 if the lock was not established
3340 * by this thread (in which case the lock is not released), and NULL if the named
3341 * lock did not exist
3343 public function unlock( $lockName, $method ) {
3348 * Lock specific tables
3350 * @param $read Array of tables to lock for read access
3351 * @param $write Array of tables to lock for write access
3352 * @param $method String name of caller
3353 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3357 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3362 * Unlock specific tables
3364 * @param $method String the caller
3368 public function unlockTables( $method ) {
3374 * @param $tableName string
3375 * @param $fName string
3376 * @return bool|ResultWrapper
3379 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3380 if( !$this->tableExists( $tableName, $fName ) ) {
3383 $sql = "DROP TABLE " . $this->tableName( $tableName );
3384 if( $this->cascadingDeletes() ) {
3387 return $this->query( $sql, $fName );
3391 * Get search engine class. All subclasses of this need to implement this
3392 * if they wish to use searching.
3396 public function getSearchEngine() {
3397 return 'SearchEngineDummy';
3401 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3402 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3403 * because "i" sorts after all numbers.
3407 public function getInfinity() {
3412 * Encode an expiry time
3414 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3417 public function encodeExpiry( $expiry ) {
3418 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3419 return $this->getInfinity();
3421 return $this->timestamp( $expiry );
3426 * Allow or deny "big selects" for this session only. This is done by setting
3427 * the sql_big_selects session variable.
3429 * This is a MySQL-specific feature.
3431 * @param $value Mixed: true for allow, false for deny, or "default" to
3432 * restore the initial value
3434 public function setBigSelects( $value = true ) {