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__
, '1.17' );
635 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
639 * Same as new factory( ... ), kept for backward compatibility
640 * @deprecated since 1.18
641 * @see Database::factory()
643 public final static function newFromType( $dbType, $p = array() ) {
644 wfDeprecated( __METHOD__
, '1.18' );
645 if ( isset( $p['tableprefix'] ) ) {
646 $p['tablePrefix'] = $p['tableprefix'];
648 return self
::factory( $dbType, $p );
652 * Given a DB type, construct the name of the appropriate child class of
653 * DatabaseBase. This is designed to replace all of the manual stuff like:
654 * $class = 'Database' . ucfirst( strtolower( $type ) );
655 * as well as validate against the canonical list of DB types we have
657 * This factory function is mostly useful for when you need to connect to a
658 * database other than the MediaWiki default (such as for external auth,
659 * an extension, et cetera). Do not use this to connect to the MediaWiki
660 * database. Example uses in core:
661 * @see LoadBalancer::reallyOpenConnection()
662 * @see ExternalUser_MediaWiki::initFromCond()
663 * @see ForeignDBRepo::getMasterDB()
664 * @see WebInstaller_DBConnect::execute()
666 * @param $dbType String A possible DB type
667 * @param $p Array An array of options to pass to the constructor.
668 * Valid options are: host, user, password, dbname, flags, tablePrefix
669 * @return DatabaseBase subclass or null
671 public final static function factory( $dbType, $p = array() ) {
672 $canonicalDBTypes = array(
673 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
675 $dbType = strtolower( $dbType );
677 if( in_array( $dbType, $canonicalDBTypes ) ) {
678 $class = 'Database' . ucfirst( $dbType );
680 isset( $p['host'] ) ?
$p['host'] : false,
681 isset( $p['user'] ) ?
$p['user'] : false,
682 isset( $p['password'] ) ?
$p['password'] : false,
683 isset( $p['dbname'] ) ?
$p['dbname'] : false,
684 isset( $p['flags'] ) ?
$p['flags'] : 0,
685 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
692 protected function installErrorHandler() {
693 $this->mPHPError
= false;
694 $this->htmlErrors
= ini_set( 'html_errors', '0' );
695 set_error_handler( array( $this, 'connectionErrorHandler' ) );
699 * @return bool|string
701 protected function restoreErrorHandler() {
702 restore_error_handler();
703 if ( $this->htmlErrors
!== false ) {
704 ini_set( 'html_errors', $this->htmlErrors
);
706 if ( $this->mPHPError
) {
707 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
708 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
719 protected function connectionErrorHandler( $errno, $errstr ) {
720 $this->mPHPError
= $errstr;
724 * Closes a database connection.
725 * if it is open : commits any open transactions
727 * @return Bool operation success. true if already closed.
730 # Stub, should probably be overridden
735 * @param $error String: fallback error message, used if none is given by DB
737 function reportConnectionError( $error = 'Unknown error' ) {
738 $myError = $this->lastError();
744 throw new DBConnectionError( $this, $error );
748 * The DBMS-dependent part of query()
750 * @param $sql String: SQL query.
751 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
753 protected abstract function doQuery( $sql );
756 * Determine whether a query writes to the DB.
757 * Should return true if unsure.
763 function isWriteQuery( $sql ) {
764 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
768 * Run an SQL query and return the result. Normally throws a DBQueryError
769 * on failure. If errors are ignored, returns false instead.
771 * In new code, the query wrappers select(), insert(), update(), delete(),
772 * etc. should be used where possible, since they give much better DBMS
773 * independence and automatically quote or validate user input in a variety
774 * of contexts. This function is generally only useful for queries which are
775 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
778 * However, the query wrappers themselves should call this function.
780 * @param $sql String: SQL query
781 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
782 * comment (you can use __METHOD__ or add some extra info)
783 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
784 * maybe best to catch the exception instead?
785 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
786 * for a successful read query, or false on failure if $tempIgnore set
787 * @throws DBQueryError Thrown when the database returns an error of any kind
789 public function query( $sql, $fname = '', $tempIgnore = false ) {
790 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
791 if ( !Profiler
::instance()->isStub() ) {
792 # generalizeSQL will probably cut down the query to reasonable
793 # logging size most of the time. The substr is really just a sanity check.
796 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
797 $totalProf = 'DatabaseBase::query-master';
799 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
800 $totalProf = 'DatabaseBase::query';
803 wfProfileIn( $totalProf );
804 wfProfileIn( $queryProf );
807 $this->mLastQuery
= $sql;
808 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
809 # Set a flag indicating that writes have been done
810 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
811 $this->mDoneWrites
= true;
814 # Add a comment for easy SHOW PROCESSLIST interpretation
816 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
817 $userName = $wgUser->getName();
818 if ( mb_strlen( $userName ) > 15 ) {
819 $userName = mb_substr( $userName, 0, 15 ) . '...';
821 $userName = str_replace( '/', '', $userName );
825 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
827 # If DBO_TRX is set, start a transaction
828 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
829 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
830 # avoid establishing transactions for SHOW and SET statements too -
831 # that would delay transaction initializations to once connection
832 # is really used by application
833 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
834 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
838 if ( $this->debug() ) {
842 $sqlx = substr( $commentedSql, 0, 500 );
843 $sqlx = strtr( $sqlx, "\t\n", ' ' );
846 wfDebug( "Query $cnt (master): $sqlx\n" );
848 wfDebug( "Query $cnt (slave): $sqlx\n" );
852 if ( istainted( $sql ) & TC_MYSQL
) {
853 throw new MWException( 'Tainted query found' );
856 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
858 # Do the query and handle errors
859 $ret = $this->doQuery( $commentedSql );
861 MWDebug
::queryTime( $queryId );
863 # Try reconnecting if the connection was lost
864 if ( false === $ret && $this->wasErrorReissuable() ) {
865 # Transaction is gone, like it or not
866 $this->mTrxLevel
= 0;
867 wfDebug( "Connection lost, reconnecting...\n" );
869 if ( $this->ping() ) {
870 wfDebug( "Reconnected\n" );
871 $sqlx = substr( $commentedSql, 0, 500 );
872 $sqlx = strtr( $sqlx, "\t\n", ' ' );
873 global $wgRequestTime;
874 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
875 if ( $elapsed < 300 ) {
876 # Not a database error to lose a transaction after a minute or two
877 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
879 $ret = $this->doQuery( $commentedSql );
881 wfDebug( "Failed\n" );
885 if ( false === $ret ) {
886 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
889 if ( !Profiler
::instance()->isStub() ) {
890 wfProfileOut( $queryProf );
891 wfProfileOut( $totalProf );
894 return $this->resultObject( $ret );
898 * Report a query error. Log the error, and if neither the object ignore
899 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
901 * @param $error String
902 * @param $errno Integer
904 * @param $fname String
905 * @param $tempIgnore Boolean
907 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
908 # Ignore errors during error handling to avoid infinite recursion
909 $ignore = $this->ignoreErrors( true );
910 ++
$this->mErrorCount
;
912 if ( $ignore ||
$tempIgnore ) {
913 wfDebug( "SQL ERROR (ignored): $error\n" );
914 $this->ignoreErrors( $ignore );
916 $sql1line = str_replace( "\n", "\\n", $sql );
917 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
918 wfDebug( "SQL ERROR: " . $error . "\n" );
919 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
924 * Intended to be compatible with the PEAR::DB wrapper functions.
925 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
927 * ? = scalar value, quoted as necessary
928 * ! = raw SQL bit (a function for instance)
929 * & = filename; reads the file and inserts as a blob
930 * (we don't use this though...)
932 * This function should not be used directly by new code outside of the
933 * database classes. The query wrapper functions (select() etc.) should be
937 * @param $func string
941 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
942 /* MySQL doesn't support prepared statements (yet), so just
943 pack up the query for reference. We'll manually replace
945 return array( 'query' => $sql, 'func' => $func );
949 * Free a prepared query, generated by prepare().
952 function freePrepared( $prepared ) {
953 /* No-op by default */
957 * Execute a prepared query with the various arguments
958 * @param $prepared String: the prepared sql
959 * @param $args Mixed: Either an array here, or put scalars as varargs
961 * @return ResultWrapper
963 function execute( $prepared, $args = null ) {
964 if ( !is_array( $args ) ) {
966 $args = func_get_args();
967 array_shift( $args );
970 $sql = $this->fillPrepared( $prepared['query'], $args );
972 return $this->query( $sql, $prepared['func'] );
976 * Prepare & execute an SQL statement, quoting and inserting arguments
977 * in the appropriate places.
979 * This function should not be used directly by new code outside of the
980 * database classes. The query wrapper functions (select() etc.) should be
983 * @param $query String
986 * @return ResultWrapper
988 function safeQuery( $query, $args = null ) {
989 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
991 if ( !is_array( $args ) ) {
993 $args = func_get_args();
994 array_shift( $args );
997 $retval = $this->execute( $prepared, $args );
998 $this->freePrepared( $prepared );
1004 * For faking prepared SQL statements on DBs that don't support
1006 * @param $preparedQuery String: a 'preparable' SQL statement
1007 * @param $args Array of arguments to fill it with
1008 * @return string executable SQL
1010 function fillPrepared( $preparedQuery, $args ) {
1012 $this->preparedArgs
=& $args;
1014 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1015 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1019 * preg_callback func for fillPrepared()
1020 * The arguments should be in $this->preparedArgs and must not be touched
1021 * while we're doing this.
1023 * @param $matches Array
1026 function fillPreparedArg( $matches ) {
1027 switch( $matches[1] ) {
1028 case '\\?': return '?';
1029 case '\\!': return '!';
1030 case '\\&': return '&';
1033 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1035 switch( $matches[1] ) {
1036 case '?': return $this->addQuotes( $arg );
1037 case '!': return $arg;
1039 # return $this->addQuotes( file_get_contents( $arg ) );
1040 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1042 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1047 * Free a result object returned by query() or select(). It's usually not
1048 * necessary to call this, just use unset() or let the variable holding
1049 * the result object go out of scope.
1051 * @param $res Mixed: A SQL result
1053 function freeResult( $res ) {
1057 * Simple UPDATE wrapper.
1058 * Usually throws a DBQueryError on failure.
1059 * If errors are explicitly ignored, returns success
1061 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1062 * calling convention and feature set
1064 * @param $table string
1068 * @param $fname string
1072 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1073 $table = $this->tableName( $table );
1074 $sql = "UPDATE $table SET $var = '" .
1075 $this->strencode( $value ) . "' WHERE ($cond)";
1077 return (bool)$this->query( $sql, $fname );
1081 * A SELECT wrapper which returns a single field from a single result row.
1083 * Usually throws a DBQueryError on failure. If errors are explicitly
1084 * ignored, returns false on failure.
1086 * If no result rows are returned from the query, false is returned.
1088 * @param $table string|array Table name. See DatabaseBase::select() for details.
1089 * @param $var string The field name to select. This must be a valid SQL
1090 * fragment: do not use unvalidated user input.
1091 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1092 * @param $fname string The function name of the caller.
1093 * @param $options string|array The query options. See DatabaseBase::select() for details.
1095 * @return false|mixed The value from the field, or false on failure.
1097 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1098 $options = array() )
1100 if ( !is_array( $options ) ) {
1101 $options = array( $options );
1104 $options['LIMIT'] = 1;
1106 $res = $this->select( $table, $var, $cond, $fname, $options );
1108 if ( $res === false ||
!$this->numRows( $res ) ) {
1112 $row = $this->fetchRow( $res );
1114 if ( $row !== false ) {
1115 return reset( $row );
1122 * Returns an optional USE INDEX clause to go after the table, and a
1123 * string to go at the end of the query.
1125 * @param $options Array: associative array of options to be turned into
1126 * an SQL query, valid keys are listed in the function.
1128 * @see DatabaseBase::select()
1130 function makeSelectOptions( $options ) {
1131 $preLimitTail = $postLimitTail = '';
1134 $noKeyOptions = array();
1136 foreach ( $options as $key => $option ) {
1137 if ( is_numeric( $key ) ) {
1138 $noKeyOptions[$option] = true;
1142 if ( isset( $options['GROUP BY'] ) ) {
1143 $gb = is_array( $options['GROUP BY'] )
1144 ?
implode( ',', $options['GROUP BY'] )
1145 : $options['GROUP BY'];
1146 $preLimitTail .= " GROUP BY {$gb}";
1149 if ( isset( $options['HAVING'] ) ) {
1150 $preLimitTail .= " HAVING {$options['HAVING']}";
1153 if ( isset( $options['ORDER BY'] ) ) {
1154 $ob = is_array( $options['ORDER BY'] )
1155 ?
implode( ',', $options['ORDER BY'] )
1156 : $options['ORDER BY'];
1157 $preLimitTail .= " ORDER BY {$ob}";
1160 // if (isset($options['LIMIT'])) {
1161 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1162 // isset($options['OFFSET']) ? $options['OFFSET']
1166 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1167 $postLimitTail .= ' FOR UPDATE';
1170 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1171 $postLimitTail .= ' LOCK IN SHARE MODE';
1174 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1175 $startOpts .= 'DISTINCT';
1178 # Various MySQL extensions
1179 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1180 $startOpts .= ' /*! STRAIGHT_JOIN */';
1183 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1184 $startOpts .= ' HIGH_PRIORITY';
1187 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1188 $startOpts .= ' SQL_BIG_RESULT';
1191 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1192 $startOpts .= ' SQL_BUFFER_RESULT';
1195 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1196 $startOpts .= ' SQL_SMALL_RESULT';
1199 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1200 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1203 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1204 $startOpts .= ' SQL_CACHE';
1207 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1208 $startOpts .= ' SQL_NO_CACHE';
1211 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1212 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1217 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1221 * Execute a SELECT query constructed using the various parameters provided.
1222 * See below for full details of the parameters.
1224 * @param $table String|Array Table name
1225 * @param $vars String|Array Field names
1226 * @param $conds String|Array Conditions
1227 * @param $fname String Caller function name
1228 * @param $options Array Query options
1229 * @param $join_conds Array Join conditions
1231 * @param $table string|array
1233 * May be either an array of table names, or a single string holding a table
1234 * name. If an array is given, table aliases can be specified, for example:
1236 * array( 'a' => 'user' )
1238 * This includes the user table in the query, with the alias "a" available
1239 * for use in field names (e.g. a.user_name).
1241 * All of the table names given here are automatically run through
1242 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1243 * added, and various other table name mappings to be performed.
1246 * @param $vars string|array
1248 * May be either a field name or an array of field names. The field names
1249 * here are complete fragments of SQL, for direct inclusion into the SELECT
1250 * query. Expressions and aliases may be specified as in SQL, for example:
1252 * array( 'MAX(rev_id) AS maxrev' )
1254 * If an expression is given, care must be taken to ensure that it is
1258 * @param $conds string|array
1260 * May be either a string containing a single condition, or an array of
1261 * conditions. If an array is given, the conditions constructed from each
1262 * element are combined with AND.
1264 * Array elements may take one of two forms:
1266 * - Elements with a numeric key are interpreted as raw SQL fragments.
1267 * - Elements with a string key are interpreted as equality conditions,
1268 * where the key is the field name.
1269 * - If the value of such an array element is a scalar (such as a
1270 * string), it will be treated as data and thus quoted appropriately.
1271 * If it is null, an IS NULL clause will be added.
1272 * - If the value is an array, an IN(...) clause will be constructed,
1273 * such that the field name may match any of the elements in the
1274 * array. The elements of the array will be quoted.
1276 * Note that expressions are often DBMS-dependent in their syntax.
1277 * DBMS-independent wrappers are provided for constructing several types of
1278 * expression commonly used in condition queries. See:
1279 * - DatabaseBase::buildLike()
1280 * - DatabaseBase::conditional()
1283 * @param $options string|array
1285 * Optional: Array of query options. Boolean options are specified by
1286 * including them in the array as a string value with a numeric key, for
1289 * array( 'FOR UPDATE' )
1291 * The supported options are:
1293 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1294 * with LIMIT can theoretically be used for paging through a result set,
1295 * but this is discouraged in MediaWiki for performance reasons.
1297 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1298 * and then the first rows are taken until the limit is reached. LIMIT
1299 * is applied to a result set after OFFSET.
1301 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1302 * changed until the next COMMIT.
1304 * - DISTINCT: Boolean: return only unique result rows.
1306 * - GROUP BY: May be either an SQL fragment string naming a field or
1307 * expression to group by, or an array of such SQL fragments.
1309 * - HAVING: A string containing a HAVING clause.
1311 * - ORDER BY: May be either an SQL fragment giving a field name or
1312 * expression to order by, or an array of such SQL fragments.
1314 * - USE INDEX: This may be either a string giving the index name to use
1315 * for the query, or an array. If it is an associative array, each key
1316 * gives the table name (or alias), each value gives the index name to
1317 * use for that table. All strings are SQL fragments and so should be
1318 * validated by the caller.
1320 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1321 * instead of SELECT.
1323 * And also the following boolean MySQL extensions, see the MySQL manual
1324 * for documentation:
1326 * - LOCK IN SHARE MODE
1330 * - SQL_BUFFER_RESULT
1331 * - SQL_SMALL_RESULT
1332 * - SQL_CALC_FOUND_ROWS
1337 * @param $join_conds string|array
1339 * Optional associative array of table-specific join conditions. In the
1340 * most common case, this is unnecessary, since the join condition can be
1341 * in $conds. However, it is useful for doing a LEFT JOIN.
1343 * The key of the array contains the table name or alias. The value is an
1344 * array with two elements, numbered 0 and 1. The first gives the type of
1345 * join, the second is an SQL fragment giving the join condition for that
1346 * table. For example:
1348 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1350 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1351 * with no rows in it will be returned. If there was a query error, a
1352 * DBQueryError exception will be thrown, except if the "ignore errors"
1353 * option was set, in which case false will be returned.
1355 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1356 $options = array(), $join_conds = array() ) {
1357 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1359 return $this->query( $sql, $fname );
1363 * The equivalent of DatabaseBase::select() except that the constructed SQL
1364 * is returned, instead of being immediately executed.
1366 * @param $table string|array Table name
1367 * @param $vars string|array Field names
1368 * @param $conds string|array Conditions
1369 * @param $fname string Caller function name
1370 * @param $options string|array Query options
1371 * @param $join_conds string|array Join conditions
1373 * @return SQL query string.
1374 * @see DatabaseBase::select()
1376 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1377 if ( is_array( $vars ) ) {
1378 $vars = implode( ',', $vars );
1381 $options = (array)$options;
1383 if ( is_array( $table ) ) {
1384 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1385 ?
$options['USE INDEX']
1387 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1389 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1391 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1393 } elseif ( $table != '' ) {
1394 if ( $table[0] == ' ' ) {
1395 $from = ' FROM ' . $table;
1397 $from = ' FROM ' . $this->tableName( $table );
1403 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1405 if ( !empty( $conds ) ) {
1406 if ( is_array( $conds ) ) {
1407 $conds = $this->makeList( $conds, LIST_AND
);
1409 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1411 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1414 if ( isset( $options['LIMIT'] ) ) {
1415 $sql = $this->limitResult( $sql, $options['LIMIT'],
1416 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1418 $sql = "$sql $postLimitTail";
1420 if ( isset( $options['EXPLAIN'] ) ) {
1421 $sql = 'EXPLAIN ' . $sql;
1428 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1429 * that a single row object is returned. If the query returns no rows,
1430 * false is returned.
1432 * @param $table string|array Table name
1433 * @param $vars string|array Field names
1434 * @param $conds|array Conditions
1435 * @param $fname string Caller function name
1436 * @param $options string|array Query options
1437 * @param $join_conds array|string Join conditions
1439 * @return ResultWrapper|bool
1441 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1442 $options = array(), $join_conds = array() )
1444 $options['LIMIT'] = 1;
1445 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1447 if ( $res === false ) {
1451 if ( !$this->numRows( $res ) ) {
1455 $obj = $this->fetchObject( $res );
1461 * Estimate rows in dataset.
1463 * MySQL allows you to estimate the number of rows that would be returned
1464 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1465 * index cardinality statistics, and is notoriously inaccurate, especially
1466 * when large numbers of rows have recently been added or deleted.
1468 * For DBMSs that don't support fast result size estimation, this function
1469 * will actually perform the SELECT COUNT(*).
1471 * Takes the same arguments as DatabaseBase::select().
1473 * @param $table String: table name
1474 * @param Array|string $vars : unused
1475 * @param Array|string $conds : filters on the table
1476 * @param $fname String: function name for profiling
1477 * @param $options Array: options for select
1478 * @return Integer: row count
1480 public function estimateRowCount( $table, $vars = '*', $conds = '',
1481 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1484 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1487 $row = $this->fetchRow( $res );
1488 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1495 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1496 * It's only slightly flawed. Don't use for anything important.
1498 * @param $sql String A SQL Query
1502 static function generalizeSQL( $sql ) {
1503 # This does the same as the regexp below would do, but in such a way
1504 # as to avoid crashing php on some large strings.
1505 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1507 $sql = str_replace ( "\\\\", '', $sql );
1508 $sql = str_replace ( "\\'", '', $sql );
1509 $sql = str_replace ( "\\\"", '', $sql );
1510 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1511 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1513 # All newlines, tabs, etc replaced by single space
1514 $sql = preg_replace ( '/\s+/', ' ', $sql );
1517 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1523 * Determines whether a field exists in a table
1525 * @param $table String: table name
1526 * @param $field String: filed to check on that table
1527 * @param $fname String: calling function name (optional)
1528 * @return Boolean: whether $table has filed $field
1530 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1531 $info = $this->fieldInfo( $table, $field );
1537 * Determines whether an index exists
1538 * Usually throws a DBQueryError on failure
1539 * If errors are explicitly ignored, returns NULL on failure
1543 * @param $fname string
1547 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1548 $info = $this->indexInfo( $table, $index, $fname );
1549 if ( is_null( $info ) ) {
1552 return $info !== false;
1557 * Query whether a given table exists
1559 * @param $table string
1560 * @param $fname string
1564 function tableExists( $table, $fname = __METHOD__
) {
1565 $table = $this->tableName( $table );
1566 $old = $this->ignoreErrors( true );
1567 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1568 $this->ignoreErrors( $old );
1574 * mysql_field_type() wrapper
1579 function fieldType( $res, $index ) {
1580 if ( $res instanceof ResultWrapper
) {
1581 $res = $res->result
;
1584 return mysql_field_type( $res, $index );
1588 * Determines if a given index is unique
1590 * @param $table string
1591 * @param $index string
1595 function indexUnique( $table, $index ) {
1596 $indexInfo = $this->indexInfo( $table, $index );
1598 if ( !$indexInfo ) {
1602 return !$indexInfo[0]->Non_unique
;
1606 * Helper for DatabaseBase::insert().
1608 * @param $options array
1611 function makeInsertOptions( $options ) {
1612 return implode( ' ', $options );
1616 * INSERT wrapper, inserts an array into a table.
1620 * - A single associative array. The array keys are the field names, and
1621 * the values are the values to insert. The values are treated as data
1622 * and will be quoted appropriately. If NULL is inserted, this will be
1623 * converted to a database NULL.
1624 * - An array with numeric keys, holding a list of associative arrays.
1625 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1626 * each subarray must be identical to each other, and in the same order.
1628 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1631 * $options is an array of options, with boolean options encoded as values
1632 * with numeric keys, in the same style as $options in
1633 * DatabaseBase::select(). Supported options are:
1635 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1636 * any rows which cause duplicate key errors are not inserted. It's
1637 * possible to determine how many rows were successfully inserted using
1638 * DatabaseBase::affectedRows().
1640 * @param $table String Table name. This will be passed through
1641 * DatabaseBase::tableName().
1642 * @param $a Array of rows to insert
1643 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1644 * @param $options Array of options
1648 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1649 # No rows to insert, easy just return now
1650 if ( !count( $a ) ) {
1654 $table = $this->tableName( $table );
1656 if ( !is_array( $options ) ) {
1657 $options = array( $options );
1660 $options = $this->makeInsertOptions( $options );
1662 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1664 $keys = array_keys( $a[0] );
1667 $keys = array_keys( $a );
1670 $sql = 'INSERT ' . $options .
1671 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1675 foreach ( $a as $row ) {
1681 $sql .= '(' . $this->makeList( $row ) . ')';
1684 $sql .= '(' . $this->makeList( $a ) . ')';
1687 return (bool)$this->query( $sql, $fname );
1691 * Make UPDATE options for the DatabaseBase::update function
1693 * @param $options Array: The options passed to DatabaseBase::update
1696 function makeUpdateOptions( $options ) {
1697 if ( !is_array( $options ) ) {
1698 $options = array( $options );
1703 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1704 $opts[] = $this->lowPriorityOption();
1707 if ( in_array( 'IGNORE', $options ) ) {
1711 return implode( ' ', $opts );
1715 * UPDATE wrapper. Takes a condition array and a SET array.
1717 * @param $table String name of the table to UPDATE. This will be passed through
1718 * DatabaseBase::tableName().
1720 * @param $values Array: An array of values to SET. For each array element,
1721 * the key gives the field name, and the value gives the data
1722 * to set that field to. The data will be quoted by
1723 * DatabaseBase::addQuotes().
1725 * @param $conds Array: An array of conditions (WHERE). See
1726 * DatabaseBase::select() for the details of the format of
1727 * condition arrays. Use '*' to update all rows.
1729 * @param $fname String: The function name of the caller (from __METHOD__),
1730 * for logging and profiling.
1732 * @param $options Array: An array of UPDATE options, can be:
1733 * - IGNORE: Ignore unique key conflicts
1734 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1737 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1738 $table = $this->tableName( $table );
1739 $opts = $this->makeUpdateOptions( $options );
1740 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1742 if ( $conds !== array() && $conds !== '*' ) {
1743 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1746 return $this->query( $sql, $fname );
1750 * Makes an encoded list of strings from an array
1751 * @param $a Array containing the data
1752 * @param $mode int Constant
1753 * - LIST_COMMA: comma separated, no field names
1754 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1755 * the documentation for $conds in DatabaseBase::select().
1756 * - LIST_OR: ORed WHERE clause (without the WHERE)
1757 * - LIST_SET: comma separated with field names, like a SET clause
1758 * - LIST_NAMES: comma separated field names
1762 function makeList( $a, $mode = LIST_COMMA
) {
1763 if ( !is_array( $a ) ) {
1764 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1770 foreach ( $a as $field => $value ) {
1772 if ( $mode == LIST_AND
) {
1774 } elseif ( $mode == LIST_OR
) {
1783 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1784 $list .= "($value)";
1785 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1787 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1788 if ( count( $value ) == 0 ) {
1789 throw new MWException( __METHOD__
. ': empty input' );
1790 } elseif ( count( $value ) == 1 ) {
1791 // Special-case single values, as IN isn't terribly efficient
1792 // Don't necessarily assume the single key is 0; we don't
1793 // enforce linear numeric ordering on other arrays here.
1794 $value = array_values( $value );
1795 $list .= $field . " = " . $this->addQuotes( $value[0] );
1797 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1799 } elseif ( $value === null ) {
1800 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1801 $list .= "$field IS ";
1802 } elseif ( $mode == LIST_SET
) {
1803 $list .= "$field = ";
1807 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1808 $list .= "$field = ";
1810 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1818 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1819 * The keys on each level may be either integers or strings.
1821 * @param $data Array: organized as 2-d
1822 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1823 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1824 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1825 * @return Mixed: string SQL fragment, or false if no items in array.
1827 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1830 foreach ( $data as $base => $sub ) {
1831 if ( count( $sub ) ) {
1832 $conds[] = $this->makeList(
1833 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1839 return $this->makeList( $conds, LIST_OR
);
1841 // Nothing to search for...
1847 * Bitwise operations
1854 function bitNot( $field ) {
1860 * @param $fieldRight
1863 function bitAnd( $fieldLeft, $fieldRight ) {
1864 return "($fieldLeft & $fieldRight)";
1869 * @param $fieldRight
1872 function bitOr( $fieldLeft, $fieldRight ) {
1873 return "($fieldLeft | $fieldRight)";
1877 * Change the current database
1879 * @todo Explain what exactly will fail if this is not overridden.
1883 * @return bool Success or failure
1885 function selectDB( $db ) {
1886 # Stub. Shouldn't cause serious problems if it's not overridden, but
1887 # if your database engine supports a concept similar to MySQL's
1888 # databases you may as well.
1889 $this->mDBname
= $db;
1894 * Get the current DB name
1896 function getDBname() {
1897 return $this->mDBname
;
1901 * Get the server hostname or IP address
1903 function getServer() {
1904 return $this->mServer
;
1908 * Format a table name ready for use in constructing an SQL query
1910 * This does two important things: it quotes the table names to clean them up,
1911 * and it adds a table prefix if only given a table name with no quotes.
1913 * All functions of this object which require a table name call this function
1914 * themselves. Pass the canonical name to such functions. This is only needed
1915 * when calling query() directly.
1917 * @param $name String: database table name
1918 * @param $format String One of:
1919 * quoted - Automatically pass the table name through addIdentifierQuotes()
1920 * so that it can be used in a query.
1921 * raw - Do not add identifier quotes to the table name
1922 * @return String: full database name
1924 function tableName( $name, $format = 'quoted' ) {
1925 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1926 # Skip the entire process when we have a string quoted on both ends.
1927 # Note that we check the end so that we will still quote any use of
1928 # use of `database`.table. But won't break things if someone wants
1929 # to query a database table with a dot in the name.
1930 if ( $this->isQuotedIdentifier( $name ) ) {
1934 # Lets test for any bits of text that should never show up in a table
1935 # name. Basically anything like JOIN or ON which are actually part of
1936 # SQL queries, but may end up inside of the table value to combine
1937 # sql. Such as how the API is doing.
1938 # Note that we use a whitespace test rather than a \b test to avoid
1939 # any remote case where a word like on may be inside of a table name
1940 # surrounded by symbols which may be considered word breaks.
1941 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1945 # Split database and table into proper variables.
1946 # We reverse the explode so that database.table and table both output
1947 # the correct table.
1948 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1949 if ( isset( $dbDetails[1] ) ) {
1950 list( $table, $database ) = $dbDetails;
1952 list( $table ) = $dbDetails;
1954 $prefix = $this->mTablePrefix
; # Default prefix
1956 # A database name has been specified in input. We don't want any
1958 if ( isset( $database ) ) {
1962 # Note that we use the long format because php will complain in in_array if
1963 # the input is not an array, and will complain in is_array if it is not set.
1964 if ( !isset( $database ) # Don't use shared database if pre selected.
1965 && isset( $wgSharedDB ) # We have a shared database
1966 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1967 && isset( $wgSharedTables )
1968 && is_array( $wgSharedTables )
1969 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1970 $database = $wgSharedDB;
1971 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1974 # Quote the $database and $table and apply the prefix if not quoted.
1975 if ( isset( $database ) ) {
1976 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1979 $table = "{$prefix}{$table}";
1980 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1981 $table = $this->addIdentifierQuotes( "{$table}" );
1984 # Merge our database and table into our final table name.
1985 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1991 * Fetch a number of table names into an array
1992 * This is handy when you need to construct SQL for joins
1995 * extract($dbr->tableNames('user','watchlist'));
1996 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1997 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2001 public function tableNames() {
2002 $inArray = func_get_args();
2005 foreach ( $inArray as $name ) {
2006 $retVal[$name] = $this->tableName( $name );
2013 * Fetch a number of table names into an zero-indexed numerical array
2014 * This is handy when you need to construct SQL for joins
2017 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2018 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2019 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2023 public function tableNamesN() {
2024 $inArray = func_get_args();
2027 foreach ( $inArray as $name ) {
2028 $retVal[] = $this->tableName( $name );
2035 * Get an aliased table name
2036 * e.g. tableName AS newTableName
2038 * @param $name string Table name, see tableName()
2039 * @param $alias string|bool Alias (optional)
2040 * @return string SQL name for aliased table. Will not alias a table to its own name
2042 public function tableNameWithAlias( $name, $alias = false ) {
2043 if ( !$alias ||
$alias == $name ) {
2044 return $this->tableName( $name );
2046 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2051 * Gets an array of aliased table names
2053 * @param $tables array( [alias] => table )
2054 * @return array of strings, see tableNameWithAlias()
2056 public function tableNamesWithAlias( $tables ) {
2058 foreach ( $tables as $alias => $table ) {
2059 if ( is_numeric( $alias ) ) {
2062 $retval[] = $this->tableNameWithAlias( $table, $alias );
2068 * Get the aliased table name clause for a FROM clause
2069 * which might have a JOIN and/or USE INDEX clause
2071 * @param $tables array ( [alias] => table )
2072 * @param $use_index array Same as for select()
2073 * @param $join_conds array Same as for select()
2076 protected function tableNamesWithUseIndexOrJOIN(
2077 $tables, $use_index = array(), $join_conds = array()
2081 $use_index = (array)$use_index;
2082 $join_conds = (array)$join_conds;
2084 foreach ( $tables as $alias => $table ) {
2085 if ( !is_string( $alias ) ) {
2086 // No alias? Set it equal to the table name
2089 // Is there a JOIN clause for this table?
2090 if ( isset( $join_conds[$alias] ) ) {
2091 list( $joinType, $conds ) = $join_conds[$alias];
2092 $tableClause = $joinType;
2093 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2094 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2095 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2097 $tableClause .= ' ' . $use;
2100 $on = $this->makeList( (array)$conds, LIST_AND
);
2102 $tableClause .= ' ON (' . $on . ')';
2105 $retJOIN[] = $tableClause;
2106 // Is there an INDEX clause for this table?
2107 } elseif ( isset( $use_index[$alias] ) ) {
2108 $tableClause = $this->tableNameWithAlias( $table, $alias );
2109 $tableClause .= ' ' . $this->useIndexClause(
2110 implode( ',', (array)$use_index[$alias] ) );
2112 $ret[] = $tableClause;
2114 $tableClause = $this->tableNameWithAlias( $table, $alias );
2116 $ret[] = $tableClause;
2120 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2121 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2122 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2124 // Compile our final table clause
2125 return implode( ' ', array( $straightJoins, $otherJoins ) );
2129 * Get the name of an index in a given table
2135 function indexName( $index ) {
2136 // Backwards-compatibility hack
2138 'ar_usertext_timestamp' => 'usertext_timestamp',
2139 'un_user_id' => 'user_id',
2140 'un_user_ip' => 'user_ip',
2143 if ( isset( $renamed[$index] ) ) {
2144 return $renamed[$index];
2151 * If it's a string, adds quotes and backslashes
2152 * Otherwise returns as-is
2158 function addQuotes( $s ) {
2159 if ( $s === null ) {
2162 # This will also quote numeric values. This should be harmless,
2163 # and protects against weird problems that occur when they really
2164 # _are_ strings such as article titles and string->number->string
2165 # conversion is not 1:1.
2166 return "'" . $this->strencode( $s ) . "'";
2171 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2172 * MySQL uses `backticks` while basically everything else uses double quotes.
2173 * Since MySQL is the odd one out here the double quotes are our generic
2174 * and we implement backticks in DatabaseMysql.
2180 public function addIdentifierQuotes( $s ) {
2181 return '"' . str_replace( '"', '""', $s ) . '"';
2185 * Returns if the given identifier looks quoted or not according to
2186 * the database convention for quoting identifiers .
2188 * @param $name string
2192 public function isQuotedIdentifier( $name ) {
2193 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2197 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2198 * which used quote_ident which does not follow our naming conventions
2199 * was renamed to addIdentifierQuotes.
2200 * @deprecated since 1.18 use addIdentifierQuotes
2206 function quote_ident( $s ) {
2207 wfDeprecated( __METHOD__
, '1.18' );
2208 return $this->addIdentifierQuotes( $s );
2212 * Escape string for safe LIKE usage.
2213 * WARNING: you should almost never use this function directly,
2214 * instead use buildLike() that escapes everything automatically
2215 * @deprecated since 1.17, warnings in 1.17, removed in ???
2221 public function escapeLike( $s ) {
2222 wfDeprecated( __METHOD__
, '1.17' );
2223 return $this->escapeLikeInternal( $s );
2230 protected function escapeLikeInternal( $s ) {
2231 $s = str_replace( '\\', '\\\\', $s );
2232 $s = $this->strencode( $s );
2233 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2239 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2240 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2241 * Alternatively, the function could be provided with an array of aforementioned parameters.
2243 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2244 * for subpages of 'My page title'.
2245 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2248 * @return String: fully built LIKE statement
2250 function buildLike() {
2251 $params = func_get_args();
2253 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2254 $params = $params[0];
2259 foreach ( $params as $value ) {
2260 if ( $value instanceof LikeMatch
) {
2261 $s .= $value->toString();
2263 $s .= $this->escapeLikeInternal( $value );
2267 return " LIKE '" . $s . "' ";
2271 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2275 function anyChar() {
2276 return new LikeMatch( '_' );
2280 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2284 function anyString() {
2285 return new LikeMatch( '%' );
2289 * Returns an appropriately quoted sequence value for inserting a new row.
2290 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2291 * subclass will return an integer, and save the value for insertId()
2293 * Any implementation of this function should *not* involve reusing
2294 * sequence numbers created for rolled-back transactions.
2295 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2296 * @param $seqName string
2299 function nextSequenceValue( $seqName ) {
2304 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2305 * is only needed because a) MySQL must be as efficient as possible due to
2306 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2307 * which index to pick. Anyway, other databases might have different
2308 * indexes on a given table. So don't bother overriding this unless you're
2313 function useIndexClause( $index ) {
2318 * REPLACE query wrapper.
2320 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2321 * except that when there is a duplicate key error, the old row is deleted
2322 * and the new row is inserted in its place.
2324 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2325 * perform the delete, we need to know what the unique indexes are so that
2326 * we know how to find the conflicting rows.
2328 * It may be more efficient to leave off unique indexes which are unlikely
2329 * to collide. However if you do this, you run the risk of encountering
2330 * errors which wouldn't have occurred in MySQL.
2332 * @param $table String: The table to replace the row(s) in.
2333 * @param $rows array Can be either a single row to insert, or multiple rows,
2334 * in the same format as for DatabaseBase::insert()
2335 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2336 * a field name or an array of field names
2337 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2339 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2340 $quotedTable = $this->tableName( $table );
2342 if ( count( $rows ) == 0 ) {
2347 if ( !is_array( reset( $rows ) ) ) {
2348 $rows = array( $rows );
2351 foreach( $rows as $row ) {
2352 # Delete rows which collide
2353 if ( $uniqueIndexes ) {
2354 $sql = "DELETE FROM $quotedTable WHERE ";
2356 foreach ( $uniqueIndexes as $index ) {
2363 if ( is_array( $index ) ) {
2365 foreach ( $index as $col ) {
2371 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2374 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2378 $this->query( $sql, $fname );
2381 # Now insert the row
2382 $this->insert( $table, $row );
2387 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2390 * @param $table string Table name
2391 * @param $rows array Rows to insert
2392 * @param $fname string Caller function name
2394 * @return ResultWrapper
2396 protected function nativeReplace( $table, $rows, $fname ) {
2397 $table = $this->tableName( $table );
2400 if ( !is_array( reset( $rows ) ) ) {
2401 $rows = array( $rows );
2404 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2407 foreach ( $rows as $row ) {
2414 $sql .= '(' . $this->makeList( $row ) . ')';
2417 return $this->query( $sql, $fname );
2421 * DELETE where the condition is a join.
2423 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2424 * we use sub-selects
2426 * For safety, an empty $conds will not delete everything. If you want to
2427 * delete all rows where the join condition matches, set $conds='*'.
2429 * DO NOT put the join condition in $conds.
2431 * @param $delTable String: The table to delete from.
2432 * @param $joinTable String: The other table.
2433 * @param $delVar String: The variable to join on, in the first table.
2434 * @param $joinVar String: The variable to join on, in the second table.
2435 * @param $conds Array: Condition array of field names mapped to variables,
2436 * ANDed together in the WHERE clause
2437 * @param $fname String: Calling function name (use __METHOD__) for
2440 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2441 $fname = 'DatabaseBase::deleteJoin' )
2444 throw new DBUnexpectedError( $this,
2445 'DatabaseBase::deleteJoin() called with empty $conds' );
2448 $delTable = $this->tableName( $delTable );
2449 $joinTable = $this->tableName( $joinTable );
2450 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2451 if ( $conds != '*' ) {
2452 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2456 $this->query( $sql, $fname );
2460 * Returns the size of a text field, or -1 for "unlimited"
2462 * @param $table string
2463 * @param $field string
2467 function textFieldSize( $table, $field ) {
2468 $table = $this->tableName( $table );
2469 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2470 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2471 $row = $this->fetchObject( $res );
2475 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2485 * A string to insert into queries to show that they're low-priority, like
2486 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2487 * string and nothing bad should happen.
2489 * @return string Returns the text of the low priority option if it is
2490 * supported, or a blank string otherwise
2492 function lowPriorityOption() {
2497 * DELETE query wrapper.
2499 * @param $table Array Table name
2500 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2501 * the format. Use $conds == "*" to delete all rows
2502 * @param $fname String name of the calling function
2506 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2508 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2511 $table = $this->tableName( $table );
2512 $sql = "DELETE FROM $table";
2514 if ( $conds != '*' ) {
2515 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2518 return $this->query( $sql, $fname );
2522 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2523 * into another table.
2525 * @param $destTable string The table name to insert into
2526 * @param $srcTable string|array May be either a table name, or an array of table names
2527 * to include in a join.
2529 * @param $varMap array must be an associative array of the form
2530 * array( 'dest1' => 'source1', ...). Source items may be literals
2531 * rather than field names, but strings should be quoted with
2532 * DatabaseBase::addQuotes()
2534 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2535 * the details of the format of condition arrays. May be "*" to copy the
2538 * @param $fname string The function name of the caller, from __METHOD__
2540 * @param $insertOptions array Options for the INSERT part of the query, see
2541 * DatabaseBase::insert() for details.
2542 * @param $selectOptions array Options for the SELECT part of the query, see
2543 * DatabaseBase::select() for details.
2545 * @return ResultWrapper
2547 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2548 $fname = 'DatabaseBase::insertSelect',
2549 $insertOptions = array(), $selectOptions = array() )
2551 $destTable = $this->tableName( $destTable );
2553 if ( is_array( $insertOptions ) ) {
2554 $insertOptions = implode( ' ', $insertOptions );
2557 if ( !is_array( $selectOptions ) ) {
2558 $selectOptions = array( $selectOptions );
2561 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2563 if ( is_array( $srcTable ) ) {
2564 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2566 $srcTable = $this->tableName( $srcTable );
2569 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2570 " SELECT $startOpts " . implode( ',', $varMap ) .
2571 " FROM $srcTable $useIndex ";
2573 if ( $conds != '*' ) {
2574 if ( is_array( $conds ) ) {
2575 $conds = $this->makeList( $conds, LIST_AND
);
2577 $sql .= " WHERE $conds";
2580 $sql .= " $tailOpts";
2582 return $this->query( $sql, $fname );
2586 * Construct a LIMIT query with optional offset. This is used for query
2587 * pages. The SQL should be adjusted so that only the first $limit rows
2588 * are returned. If $offset is provided as well, then the first $offset
2589 * rows should be discarded, and the next $limit rows should be returned.
2590 * If the result of the query is not ordered, then the rows to be returned
2591 * are theoretically arbitrary.
2593 * $sql is expected to be a SELECT, if that makes a difference. For
2594 * UPDATE, limitResultForUpdate should be used.
2596 * The version provided by default works in MySQL and SQLite. It will very
2597 * likely need to be overridden for most other DBMSes.
2599 * @param $sql String SQL query we will append the limit too
2600 * @param $limit Integer the SQL limit
2601 * @param $offset Integer|false the SQL offset (default false)
2605 function limitResult( $sql, $limit, $offset = false ) {
2606 if ( !is_numeric( $limit ) ) {
2607 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2610 return "$sql LIMIT "
2611 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2620 function limitResultForUpdate( $sql, $num ) {
2621 return $this->limitResult( $sql, $num, 0 );
2625 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2626 * within the UNION construct.
2629 function unionSupportsOrderAndLimit() {
2630 return true; // True for almost every DB supported
2634 * Construct a UNION query
2635 * This is used for providing overload point for other DB abstractions
2636 * not compatible with the MySQL syntax.
2637 * @param $sqls Array: SQL statements to combine
2638 * @param $all Boolean: use UNION ALL
2639 * @return String: SQL fragment
2641 function unionQueries( $sqls, $all ) {
2642 $glue = $all ?
') UNION ALL (' : ') UNION (';
2643 return '(' . implode( $glue, $sqls ) . ')';
2647 * Returns an SQL expression for a simple conditional. This doesn't need
2648 * to be overridden unless CASE isn't supported in your DBMS.
2650 * @param $cond String: SQL expression which will result in a boolean value
2651 * @param $trueVal String: SQL expression to return if true
2652 * @param $falseVal String: SQL expression to return if false
2653 * @return String: SQL fragment
2655 function conditional( $cond, $trueVal, $falseVal ) {
2656 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2660 * Returns a comand for str_replace function in SQL query.
2661 * Uses REPLACE() in MySQL
2663 * @param $orig String: column to modify
2664 * @param $old String: column to seek
2665 * @param $new String: column to replace with
2669 function strreplace( $orig, $old, $new ) {
2670 return "REPLACE({$orig}, {$old}, {$new})";
2674 * Determines how long the server has been up
2679 function getServerUptime() {
2684 * Determines if the last failure was due to a deadlock
2689 function wasDeadlock() {
2694 * Determines if the last failure was due to a lock timeout
2699 function wasLockTimeout() {
2704 * Determines if the last query error was something that should be dealt
2705 * with by pinging the connection and reissuing the query.
2710 function wasErrorReissuable() {
2715 * Determines if the last failure was due to the database being read-only.
2720 function wasReadOnlyError() {
2725 * Perform a deadlock-prone transaction.
2727 * This function invokes a callback function to perform a set of write
2728 * queries. If a deadlock occurs during the processing, the transaction
2729 * will be rolled back and the callback function will be called again.
2732 * $dbw->deadlockLoop( callback, ... );
2734 * Extra arguments are passed through to the specified callback function.
2736 * Returns whatever the callback function returned on its successful,
2737 * iteration, or false on error, for example if the retry limit was
2742 function deadlockLoop() {
2743 $myFname = 'DatabaseBase::deadlockLoop';
2746 $args = func_get_args();
2747 $function = array_shift( $args );
2748 $oldIgnore = $this->ignoreErrors( true );
2749 $tries = DEADLOCK_TRIES
;
2751 if ( is_array( $function ) ) {
2752 $fname = $function[0];
2758 $retVal = call_user_func_array( $function, $args );
2759 $error = $this->lastError();
2760 $errno = $this->lastErrno();
2761 $sql = $this->lastQuery();
2764 if ( $this->wasDeadlock() ) {
2766 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2768 $this->reportQueryError( $error, $errno, $sql, $fname );
2771 } while ( $this->wasDeadlock() && --$tries > 0 );
2773 $this->ignoreErrors( $oldIgnore );
2775 if ( $tries <= 0 ) {
2776 $this->rollback( $myFname );
2777 $this->reportQueryError( $error, $errno, $sql, $fname );
2780 $this->commit( $myFname );
2786 * Wait for the slave to catch up to a given master position.
2788 * @param $pos DBMasterPos object
2789 * @param $timeout Integer: the maximum number of seconds to wait for
2792 * @return An integer: zero if the slave was past that position already,
2793 * greater than zero if we waited for some period of time, less than
2794 * zero if we timed out.
2796 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2797 $fname = 'DatabaseBase::masterPosWait';
2798 wfProfileIn( $fname );
2800 if ( !is_null( $this->mFakeSlaveLag
) ) {
2801 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2803 if ( $wait > $timeout * 1e6
) {
2804 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2805 wfProfileOut( $fname );
2807 } elseif ( $wait > 0 ) {
2808 wfDebug( "Fake slave waiting $wait us\n" );
2810 wfProfileOut( $fname );
2813 wfDebug( "Fake slave up to date ($wait us)\n" );
2814 wfProfileOut( $fname );
2819 wfProfileOut( $fname );
2821 # Real waits are implemented in the subclass.
2826 * Get the replication position of this slave
2828 * @return DBMasterPos, or false if this is not a slave.
2830 function getSlavePos() {
2831 if ( !is_null( $this->mFakeSlaveLag
) ) {
2832 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2833 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2842 * Get the position of this master
2844 * @return DBMasterPos, or false if this is not a master
2846 function getMasterPos() {
2847 if ( $this->mFakeMaster
) {
2848 return new MySQLMasterPos( 'fake', microtime( true ) );
2855 * Begin a transaction, committing any previously open transaction
2857 * @param $fname string
2859 function begin( $fname = 'DatabaseBase::begin' ) {
2860 $this->query( 'BEGIN', $fname );
2861 $this->mTrxLevel
= 1;
2867 * @param $fname string
2869 function commit( $fname = 'DatabaseBase::commit' ) {
2870 if ( $this->mTrxLevel
) {
2871 $this->query( 'COMMIT', $fname );
2872 $this->mTrxLevel
= 0;
2877 * Rollback a transaction.
2878 * No-op on non-transactional databases.
2880 * @param $fname string
2882 function rollback( $fname = 'DatabaseBase::rollback' ) {
2883 if ( $this->mTrxLevel
) {
2884 $this->query( 'ROLLBACK', $fname, true );
2885 $this->mTrxLevel
= 0;
2890 * Creates a new table with structure copied from existing table
2891 * Note that unlike most database abstraction functions, this function does not
2892 * automatically append database prefix, because it works at a lower
2893 * abstraction level.
2894 * The table names passed to this function shall not be quoted (this
2895 * function calls addIdentifierQuotes when needed).
2897 * @param $oldName String: name of table whose structure should be copied
2898 * @param $newName String: name of table to be created
2899 * @param $temporary Boolean: whether the new table should be temporary
2900 * @param $fname String: calling function name
2901 * @return Boolean: true if operation was successful
2903 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2904 $fname = 'DatabaseBase::duplicateTableStructure' )
2906 throw new MWException(
2907 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2911 * List all tables on the database
2913 * @param $prefix Only show tables with this prefix, e.g. mw_
2914 * @param $fname String: calling function name
2916 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2917 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2921 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2922 * to the format used for inserting into timestamp fields in this DBMS.
2924 * The result is unquoted, and needs to be passed through addQuotes()
2925 * before it can be included in raw SQL.
2927 * @param $ts string|int
2931 function timestamp( $ts = 0 ) {
2932 return wfTimestamp( TS_MW
, $ts );
2936 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2937 * to the format used for inserting into timestamp fields in this DBMS. If
2938 * NULL is input, it is passed through, allowing NULL values to be inserted
2939 * into timestamp fields.
2941 * The result is unquoted, and needs to be passed through addQuotes()
2942 * before it can be included in raw SQL.
2944 * @param $ts string|int
2948 function timestampOrNull( $ts = null ) {
2949 if ( is_null( $ts ) ) {
2952 return $this->timestamp( $ts );
2957 * Take the result from a query, and wrap it in a ResultWrapper if
2958 * necessary. Boolean values are passed through as is, to indicate success
2959 * of write queries or failure.
2961 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2962 * resource, and it was necessary to call this function to convert it to
2963 * a wrapper. Nowadays, raw database objects are never exposed to external
2964 * callers, so this is unnecessary in external code. For compatibility with
2965 * old code, ResultWrapper objects are passed through unaltered.
2967 * @param $result bool|ResultWrapper
2969 * @return bool|ResultWrapper
2971 function resultObject( $result ) {
2972 if ( empty( $result ) ) {
2974 } elseif ( $result instanceof ResultWrapper
) {
2976 } elseif ( $result === true ) {
2977 // Successful write query
2980 return new ResultWrapper( $this, $result );
2985 * Return aggregated value alias
2988 * @param $valuename string
2992 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2997 * Ping the server and try to reconnect if it there is no connection
2999 * @return bool Success or failure
3002 # Stub. Not essential to override.
3007 * Get slave lag. Currently supported only by MySQL.
3009 * Note that this function will generate a fatal error on many
3010 * installations. Most callers should use LoadBalancer::safeGetLag()
3013 * @return Database replication lag in seconds
3016 return intval( $this->mFakeSlaveLag
);
3020 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3024 function maxListLen() {
3029 * Some DBMSs have a special format for inserting into blob fields, they
3030 * don't allow simple quoted strings to be inserted. To insert into such
3031 * a field, pass the data through this function before passing it to
3032 * DatabaseBase::insert().
3036 function encodeBlob( $b ) {
3041 * Some DBMSs return a special placeholder object representing blob fields
3042 * in result objects. Pass the object through this function to return the
3047 function decodeBlob( $b ) {
3052 * Override database's default connection timeout
3054 * @param $timeout Integer in seconds
3056 * @deprecated since 1.19; use setSessionOptions()
3058 public function setTimeout( $timeout ) {
3059 wfDeprecated( __METHOD__
, '1.19' );
3060 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3064 * Override database's default behavior. $options include:
3065 * 'connTimeout' : Set the connection timeout value in seconds.
3066 * May be useful for very long batch queries such as
3067 * full-wiki dumps, where a single query reads out over
3070 * @param $options Array
3073 public function setSessionOptions( array $options ) {}
3076 * Read and execute SQL commands from a file.
3078 * Returns true on success, error string or exception on failure (depending
3079 * on object's error ignore settings).
3081 * @param $filename String: File name to open
3082 * @param $lineCallback Callback: Optional function called before reading each line
3083 * @param $resultCallback Callback: Optional function called for each MySQL result
3084 * @param $fname String: Calling function name or false if name should be
3085 * generated dynamically using $filename
3086 * @return bool|string
3088 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3089 wfSuppressWarnings();
3090 $fp = fopen( $filename, 'r' );
3091 wfRestoreWarnings();
3093 if ( false === $fp ) {
3094 throw new MWException( "Could not open \"{$filename}\".\n" );
3098 $fname = __METHOD__
. "( $filename )";
3102 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3104 catch ( MWException
$e ) {
3115 * Get the full path of a patch file. Originally based on archive()
3116 * from updaters.inc. Keep in mind this always returns a patch, as
3117 * it fails back to MySQL if no DB-specific patch can be found
3119 * @param $patch String The name of the patch, like patch-something.sql
3120 * @return String Full path to patch file
3122 public function patchPath( $patch ) {
3125 $dbType = $this->getType();
3126 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3127 return "$IP/maintenance/$dbType/archives/$patch";
3129 return "$IP/maintenance/archives/$patch";
3134 * Set variables to be used in sourceFile/sourceStream, in preference to the
3135 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3136 * all. If it's set to false, $GLOBALS will be used.
3138 * @param $vars False, or array mapping variable name to value.
3140 function setSchemaVars( $vars ) {
3141 $this->mSchemaVars
= $vars;
3145 * Read and execute commands from an open file handle.
3147 * Returns true on success, error string or exception on failure (depending
3148 * on object's error ignore settings).
3150 * @param $fp Resource: File handle
3151 * @param $lineCallback Callback: Optional function called before reading each line
3152 * @param $resultCallback Callback: Optional function called for each MySQL result
3153 * @param $fname String: Calling function name
3154 * @return bool|string
3156 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3157 $fname = 'DatabaseBase::sourceStream' )
3161 $dollarquote = false;
3163 while ( ! feof( $fp ) ) {
3164 if ( $lineCallback ) {
3165 call_user_func( $lineCallback );
3168 $line = trim( fgets( $fp ) );
3169 $sl = strlen( $line ) - 1;
3175 if ( '-' == $line[0] && '-' == $line[1] ) {
3179 # # Allow dollar quoting for function declarations
3180 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3181 if ( $dollarquote ) {
3182 $dollarquote = false;
3186 $dollarquote = true;
3189 elseif ( !$dollarquote ) {
3190 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
3192 $line = substr( $line, 0, $sl );
3203 $cmd = str_replace( ';;', ";", $cmd );
3204 $cmd = $this->replaceVars( $cmd );
3205 $res = $this->query( $cmd, $fname );
3207 if ( $resultCallback ) {
3208 call_user_func( $resultCallback, $res, $this );
3211 if ( false === $res ) {
3212 $err = $this->lastError();
3213 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3225 * Database independent variable replacement. Replaces a set of variables
3226 * in an SQL statement with their contents as given by $this->getSchemaVars().
3228 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3230 * - '{$var}' should be used for text and is passed through the database's
3232 * - `{$var}` should be used for identifiers (eg: table and database names),
3233 * it is passed through the database's addIdentifierQuotes method which
3234 * can be overridden if the database uses something other than backticks.
3235 * - / *$var* / is just encoded, besides traditional table prefix and
3236 * table options its use should be avoided.
3238 * @param $ins String: SQL statement to replace variables in
3239 * @return String The new SQL statement with variables replaced
3241 protected function replaceSchemaVars( $ins ) {
3242 $vars = $this->getSchemaVars();
3243 foreach ( $vars as $var => $value ) {
3245 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3247 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3249 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3255 * Replace variables in sourced SQL
3257 * @param $ins string
3261 protected function replaceVars( $ins ) {
3262 $ins = $this->replaceSchemaVars( $ins );
3265 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3266 array( $this, 'tableNameCallback' ), $ins );
3269 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3270 array( $this, 'indexNameCallback' ), $ins );
3276 * Get schema variables. If none have been set via setSchemaVars(), then
3277 * use some defaults from the current object.
3281 protected function getSchemaVars() {
3282 if ( $this->mSchemaVars
) {
3283 return $this->mSchemaVars
;
3285 return $this->getDefaultSchemaVars();
3290 * Get schema variables to use if none have been set via setSchemaVars().
3292 * Override this in derived classes to provide variables for tables.sql
3293 * and SQL patch files.
3297 protected function getDefaultSchemaVars() {
3302 * Table name callback
3304 * @param $matches array
3308 protected function tableNameCallback( $matches ) {
3309 return $this->tableName( $matches[1] );
3313 * Index name callback
3315 * @param $matches array
3319 protected function indexNameCallback( $matches ) {
3320 return $this->indexName( $matches[1] );
3324 * Build a concatenation list to feed into a SQL query
3325 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3328 function buildConcat( $stringList ) {
3329 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3333 * Acquire a named lock
3335 * Abstracted from Filestore::lock() so child classes can implement for
3338 * @param $lockName String: name of lock to aquire
3339 * @param $method String: name of method calling us
3340 * @param $timeout Integer: timeout
3343 public function lock( $lockName, $method, $timeout = 5 ) {
3350 * @param $lockName String: Name of lock to release
3351 * @param $method String: Name of method calling us
3353 * @return Returns 1 if the lock was released, 0 if the lock was not established
3354 * by this thread (in which case the lock is not released), and NULL if the named
3355 * lock did not exist
3357 public function unlock( $lockName, $method ) {
3362 * Lock specific tables
3364 * @param $read Array of tables to lock for read access
3365 * @param $write Array of tables to lock for write access
3366 * @param $method String name of caller
3367 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3371 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3376 * Unlock specific tables
3378 * @param $method String the caller
3382 public function unlockTables( $method ) {
3388 * @param $tableName string
3389 * @param $fName string
3390 * @return bool|ResultWrapper
3393 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3394 if( !$this->tableExists( $tableName, $fName ) ) {
3397 $sql = "DROP TABLE " . $this->tableName( $tableName );
3398 if( $this->cascadingDeletes() ) {
3401 return $this->query( $sql, $fName );
3405 * Get search engine class. All subclasses of this need to implement this
3406 * if they wish to use searching.
3410 public function getSearchEngine() {
3411 return 'SearchEngineDummy';
3415 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3416 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3417 * because "i" sorts after all numbers.
3421 public function getInfinity() {
3426 * Encode an expiry time
3428 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3431 public function encodeExpiry( $expiry ) {
3432 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3433 return $this->getInfinity();
3435 return $this->timestamp( $expiry );
3440 * Allow or deny "big selects" for this session only. This is done by setting
3441 * the sql_big_selects session variable.
3443 * This is a MySQL-specific feature.
3445 * @param $value Mixed: true for allow, false for deny, or "default" to
3446 * restore the initial value
3448 public function setBigSelects( $value = true ) {