3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * Fetch the next row from the given result object, in object form.
47 * Fields can be retrieved with $row->fieldname, with fields acting like
50 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
52 * @throws DBUnexpectedError Thrown if the database returns an error
54 function fetchObject( $res );
57 * Fetch the next row from the given result object, in associative array
58 * form. Fields are retrieved with $row['fieldname'].
60 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchRow( $res );
67 * Get the number of rows in a result object
69 * @param $res Mixed: A SQL result
72 function numRows( $res );
75 * Get the number of fields in a result object
76 * @see http://www.php.net/mysql_num_fields
78 * @param $res Mixed: A SQL result
81 function numFields( $res );
84 * Get a field name in a result object
85 * @see http://www.php.net/mysql_field_name
87 * @param $res Mixed: A SQL result
91 function fieldName( $res, $n );
94 * Get the inserted value of an auto-increment row
96 * The value inserted should be fetched from nextSequenceValue()
99 * $id = $dbw->nextSequenceValue('page_page_id_seq');
100 * $dbw->insert('page',array('page_id' => $id));
101 * $id = $dbw->insertId();
108 * Change the position of the cursor in a result object
109 * @see http://www.php.net/mysql_data_seek
111 * @param $res Mixed: A SQL result
112 * @param $row Mixed: Either MySQL row or ResultWrapper
114 function dataSeek( $res, $row );
117 * Get the last error number
118 * @see http://www.php.net/mysql_errno
122 function lastErrno();
125 * Get a description of the last error
126 * @see http://www.php.net/mysql_error
130 function lastError();
133 * mysql_fetch_field() wrapper
134 * Returns false if the field doesn't exist
136 * @param $table string: table name
137 * @param $field string: field name
141 function fieldInfo( $table, $field );
144 * Get information about an index into an object
145 * @param $table string: Table name
146 * @param $index string: Index name
147 * @param $fname string: Calling function name
148 * @return Mixed: Database-specific index description class or false if the index does not exist
150 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info().
182 * @return string: Version information from the database server.
184 function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 function getServerInfo();
197 * Database abstraction object
200 abstract class DatabaseBase
implements DatabaseType
{
202 # ------------------------------------------------------------------------------
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mDBname;
215 protected $mConn = null;
216 protected $mOpened = false;
218 protected $mTablePrefix;
220 protected $mTrxLevel = 0;
221 protected $mErrorCount = 0;
222 protected $mLBInfo = array();
223 protected $mFakeSlaveLag = null, $mFakeMaster = false;
224 protected $mDefaultBigSelects = null;
225 protected $mSchemaVars = false;
227 # ------------------------------------------------------------------------------
229 # ------------------------------------------------------------------------------
230 # These optionally set a variable and return the previous state
233 * A string describing the current software version, and possibly
234 * other details in a user-friendly way. Will be listed on Special:Version, etc.
235 * Use getServerVersion() to get machine-friendly information.
237 * @return string: Version information from the database server
239 public function getServerInfo() {
240 return $this->getServerVersion();
244 * Boolean, controls output of large amounts of debug information.
246 * - true to enable debugging
247 * - false to disable debugging
248 * - omitted or null to do nothing
250 * @return The previous value of the flag
252 function debug( $debug = null ) {
253 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
257 * Turns buffering of SQL result sets on (true) or off (false). Default is
260 * Unbuffered queries are very troublesome in MySQL:
262 * - If another query is executed while the first query is being read
263 * out, the first query is killed. This means you can't call normal
264 * MediaWiki functions while you are reading an unbuffered query result
265 * from a normal wfGetDB() connection.
267 * - Unbuffered queries cause the MySQL server to use large amounts of
268 * memory and to hold broad locks which block other queries.
270 * If you want to limit client-side memory, it's almost always better to
271 * split up queries into batches using a LIMIT clause than to switch off
274 * @return The previous value of the flag
276 function bufferResults( $buffer = null ) {
277 if ( is_null( $buffer ) ) {
278 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
280 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
285 * Turns on (false) or off (true) the automatic generation and sending
286 * of a "we're sorry, but there has been a database error" page on
287 * database errors. Default is on (false). When turned off, the
288 * code should use lastErrno() and lastError() to handle the
289 * situation as appropriate.
291 * @return The previous value of the flag.
293 function ignoreErrors( $ignoreErrors = null ) {
294 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
298 * Gets or sets the current transaction level.
300 * Historically, transactions were allowed to be "nested". This is no
301 * longer supported, so this function really only returns a boolean.
303 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
304 * @return The previous value
306 function trxLevel( $level = null ) {
307 return wfSetVar( $this->mTrxLevel
, $level );
311 * Get/set the number of errors logged. Only useful when errors are ignored
312 * @param $count The count to set, or omitted to leave it unchanged.
313 * @return The error count
315 function errorCount( $count = null ) {
316 return wfSetVar( $this->mErrorCount
, $count );
320 * Get/set the table prefix.
321 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
322 * @return The previous table prefix.
324 function tablePrefix( $prefix = null ) {
325 return wfSetVar( $this->mTablePrefix
, $prefix, true );
329 * Get properties passed down from the server info array of the load
332 * @param $name The entry of the info array to get, or null to get the
335 function getLBInfo( $name = null ) {
336 if ( is_null( $name ) ) {
337 return $this->mLBInfo
;
339 if ( array_key_exists( $name, $this->mLBInfo
) ) {
340 return $this->mLBInfo
[$name];
348 * Set the LB info array, or a member of it. If called with one parameter,
349 * the LB info array is set to that parameter. If it is called with two
350 * parameters, the member with the given name is set to the given value.
356 function setLBInfo( $name, $value = null ) {
357 if ( is_null( $value ) ) {
358 $this->mLBInfo
= $name;
360 $this->mLBInfo
[$name] = $value;
365 * Set lag time in seconds for a fake slave
367 function setFakeSlaveLag( $lag ) {
368 $this->mFakeSlaveLag
= $lag;
372 * Make this connection a fake master
374 function setFakeMaster( $enabled = true ) {
375 $this->mFakeMaster
= $enabled;
379 * Returns true if this database supports (and uses) cascading deletes
381 function cascadingDeletes() {
386 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
388 function cleanupTriggers() {
393 * Returns true if this database is strict about what can be put into an IP field.
394 * Specifically, it uses a NULL value instead of an empty string.
396 function strictIPs() {
401 * Returns true if this database uses timestamps rather than integers
403 function realTimestamps() {
408 * Returns true if this database does an implicit sort when doing GROUP BY
410 function implicitGroupby() {
415 * Returns true if this database does an implicit order by when the column has an index
416 * For example: SELECT page_title FROM page LIMIT 1
418 function implicitOrderby() {
423 * Returns true if this database requires that SELECT DISTINCT queries require that all
424 ORDER BY expressions occur in the SELECT list per the SQL92 standard
426 function standardSelectDistinct() {
431 * Returns true if this database can do a native search on IP columns
432 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
434 function searchableIPs() {
439 * Returns true if this database can use functional indexes
441 function functionalIndexes() {
446 * Return the last query that went through DatabaseBase::query()
449 function lastQuery() {
450 return $this->mLastQuery
;
455 * Returns true if the connection may have been used for write queries.
456 * Should return true if unsure.
460 function doneWrites() {
461 return $this->mDoneWrites
;
465 * Is a connection to the database open?
469 return $this->mOpened
;
473 * Set a flag for this connection
475 * @param $flag Integer: DBO_* constants from Defines.php:
476 * - DBO_DEBUG: output some debug info (same as debug())
477 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
478 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
479 * - DBO_TRX: automatically start transactions
480 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
481 * and removes it in command line mode
482 * - DBO_PERSISTENT: use persistant database connection
484 function setFlag( $flag ) {
485 $this->mFlags |
= $flag;
489 * Clear a flag for this connection
491 * @param $flag: same as setFlag()'s $flag param
493 function clearFlag( $flag ) {
494 $this->mFlags
&= ~
$flag;
498 * Returns a boolean whether the flag $flag is set for this connection
500 * @param $flag: same as setFlag()'s $flag param
503 function getFlag( $flag ) {
504 return !!( $this->mFlags
& $flag );
508 * General read-only accessor
510 function getProperty( $name ) {
517 function getWikiID() {
518 if ( $this->mTablePrefix
) {
519 return "{$this->mDBname}-{$this->mTablePrefix}";
521 return $this->mDBname
;
526 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
530 public function getSchemaPath() {
532 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
533 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
535 return "$IP/maintenance/tables.sql";
539 # ------------------------------------------------------------------------------
541 # ------------------------------------------------------------------------------
545 * @param $server String: database server host
546 * @param $user String: database user name
547 * @param $password String: database user password
548 * @param $dbName String: database name
550 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
552 function __construct( $server = false, $user = false, $password = false, $dbName = false,
553 $flags = 0, $tablePrefix = 'get from global'
555 global $wgDBprefix, $wgCommandLineMode;
557 $this->mFlags
= $flags;
559 if ( $this->mFlags
& DBO_DEFAULT
) {
560 if ( $wgCommandLineMode ) {
561 $this->mFlags
&= ~DBO_TRX
;
563 $this->mFlags |
= DBO_TRX
;
567 /** Get the default table prefix*/
568 if ( $tablePrefix == 'get from global' ) {
569 $this->mTablePrefix
= $wgDBprefix;
571 $this->mTablePrefix
= $tablePrefix;
575 $this->open( $server, $user, $password, $dbName );
580 * Same as new DatabaseMysql( ... ), kept for backward compatibility
581 * @deprecated since 1.17
583 * @return DatabaseMysql
585 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
586 wfDeprecated( __METHOD__
);
587 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
591 * Given a DB type, construct the name of the appropriate child class of
592 * DatabaseBase. This is designed to replace all of the manual stuff like:
593 * $class = 'Database' . ucfirst( strtolower( $type ) );
594 * as well as validate against the canonical list of DB types we have
596 * This factory function is mostly useful for when you need to connect to a
597 * database other than the MediaWiki default (such as for external auth,
598 * an extension, et cetera). Do not use this to connect to the MediaWiki
599 * database. Example uses in core:
600 * @see LoadBalancer::reallyOpenConnection()
601 * @see ExternalUser_MediaWiki::initFromCond()
602 * @see ForeignDBRepo::getMasterDB()
603 * @see WebInstaller_DBConnect::execute()
605 * @param $dbType String A possible DB type
606 * @param $p Array An array of options to pass to the constructor.
607 * Valid options are: host, user, password, dbname, flags, tablePrefix
608 * @return DatabaseBase subclass or null
610 public final static function factory( $dbType, $p = array() ) {
611 $canonicalDBTypes = array(
612 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
614 $dbType = strtolower( $dbType );
616 if( in_array( $dbType, $canonicalDBTypes ) ) {
617 $class = 'Database' . ucfirst( $dbType );
619 isset( $p['host'] ) ?
$p['host'] : false,
620 isset( $p['user'] ) ?
$p['user'] : false,
621 isset( $p['password'] ) ?
$p['password'] : false,
622 isset( $p['dbname'] ) ?
$p['dbname'] : false,
623 isset( $p['flags'] ) ?
$p['flags'] : 0,
624 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
631 protected function installErrorHandler() {
632 $this->mPHPError
= false;
633 $this->htmlErrors
= ini_set( 'html_errors', '0' );
634 set_error_handler( array( $this, 'connectionErrorHandler' ) );
637 protected function restoreErrorHandler() {
638 restore_error_handler();
639 if ( $this->htmlErrors
!== false ) {
640 ini_set( 'html_errors', $this->htmlErrors
);
642 if ( $this->mPHPError
) {
643 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
644 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
651 protected function connectionErrorHandler( $errno, $errstr ) {
652 $this->mPHPError
= $errstr;
656 * Closes a database connection.
657 * if it is open : commits any open transactions
659 * @return Bool operation success. true if already closed.
662 # Stub, should probably be overridden
667 * @param $error String: fallback error message, used if none is given by DB
669 function reportConnectionError( $error = 'Unknown error' ) {
670 $myError = $this->lastError();
676 throw new DBConnectionError( $this, $error );
680 * The DBMS-dependent part of query()
682 * @param $sql String: SQL query.
683 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
685 protected abstract function doQuery( $sql );
688 * Determine whether a query writes to the DB.
689 * Should return true if unsure.
693 function isWriteQuery( $sql ) {
694 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
698 * Run an SQL query and return the result. Normally throws a DBQueryError
699 * on failure. If errors are ignored, returns false instead.
701 * In new code, the query wrappers select(), insert(), update(), delete(),
702 * etc. should be used where possible, since they give much better DBMS
703 * independence and automatically quote or validate user input in a variety
704 * of contexts. This function is generally only useful for queries which are
705 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
708 * However, the query wrappers themselves should call this function.
710 * @param $sql String: SQL query
711 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
712 * comment (you can use __METHOD__ or add some extra info)
713 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
714 * maybe best to catch the exception instead?
715 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
716 * for a successful read query, or false on failure if $tempIgnore set
717 * @throws DBQueryError Thrown when the database returns an error of any kind
719 public function query( $sql, $fname = '', $tempIgnore = false ) {
720 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
721 if ( !Profiler
::instance()->isStub() ) {
722 # generalizeSQL will probably cut down the query to reasonable
723 # logging size most of the time. The substr is really just a sanity check.
726 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
727 $totalProf = 'DatabaseBase::query-master';
729 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
730 $totalProf = 'DatabaseBase::query';
733 wfProfileIn( $totalProf );
734 wfProfileIn( $queryProf );
737 $this->mLastQuery
= $sql;
738 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
739 # Set a flag indicating that writes have been done
740 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
741 $this->mDoneWrites
= true;
744 # Add a comment for easy SHOW PROCESSLIST interpretation
746 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
747 $userName = $wgUser->getName();
748 if ( mb_strlen( $userName ) > 15 ) {
749 $userName = mb_substr( $userName, 0, 15 ) . '...';
751 $userName = str_replace( '/', '', $userName );
755 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
757 # If DBO_TRX is set, start a transaction
758 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
759 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
760 # avoid establishing transactions for SHOW and SET statements too -
761 # that would delay transaction initializations to once connection
762 # is really used by application
763 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
764 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
768 if ( $this->debug() ) {
772 $sqlx = substr( $commentedSql, 0, 500 );
773 $sqlx = strtr( $sqlx, "\t\n", ' ' );
776 wfDebug( "Query $cnt (master): $sqlx\n" );
778 wfDebug( "Query $cnt (slave): $sqlx\n" );
782 if ( istainted( $sql ) & TC_MYSQL
) {
783 throw new MWException( 'Tainted query found' );
786 # Do the query and handle errors
787 $ret = $this->doQuery( $commentedSql );
789 # Try reconnecting if the connection was lost
790 if ( false === $ret && $this->wasErrorReissuable() ) {
791 # Transaction is gone, like it or not
792 $this->mTrxLevel
= 0;
793 wfDebug( "Connection lost, reconnecting...\n" );
795 if ( $this->ping() ) {
796 wfDebug( "Reconnected\n" );
797 $sqlx = substr( $commentedSql, 0, 500 );
798 $sqlx = strtr( $sqlx, "\t\n", ' ' );
799 global $wgRequestTime;
800 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
801 if ( $elapsed < 300 ) {
802 # Not a database error to lose a transaction after a minute or two
803 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
805 $ret = $this->doQuery( $commentedSql );
807 wfDebug( "Failed\n" );
811 if ( false === $ret ) {
812 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
815 if ( !Profiler
::instance()->isStub() ) {
816 wfProfileOut( $queryProf );
817 wfProfileOut( $totalProf );
820 return $this->resultObject( $ret );
824 * Report a query error. Log the error, and if neither the object ignore
825 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
827 * @param $error String
828 * @param $errno Integer
830 * @param $fname String
831 * @param $tempIgnore Boolean
833 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
834 # Ignore errors during error handling to avoid infinite recursion
835 $ignore = $this->ignoreErrors( true );
836 ++
$this->mErrorCount
;
838 if ( $ignore ||
$tempIgnore ) {
839 wfDebug( "SQL ERROR (ignored): $error\n" );
840 $this->ignoreErrors( $ignore );
842 $sql1line = str_replace( "\n", "\\n", $sql );
843 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
844 wfDebug( "SQL ERROR: " . $error . "\n" );
845 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
850 * Intended to be compatible with the PEAR::DB wrapper functions.
851 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
853 * ? = scalar value, quoted as necessary
854 * ! = raw SQL bit (a function for instance)
855 * & = filename; reads the file and inserts as a blob
856 * (we don't use this though...)
858 * This function should not be used directly by new code outside of the
859 * database classes. The query wrapper functions (select() etc.) should be
864 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
865 /* MySQL doesn't support prepared statements (yet), so just
866 pack up the query for reference. We'll manually replace
868 return array( 'query' => $sql, 'func' => $func );
872 * Free a prepared query, generated by prepare().
874 function freePrepared( $prepared ) {
875 /* No-op by default */
879 * Execute a prepared query with the various arguments
880 * @param $prepared String: the prepared sql
881 * @param $args Mixed: Either an array here, or put scalars as varargs
883 * @return ResultWrapper
885 function execute( $prepared, $args = null ) {
886 if ( !is_array( $args ) ) {
888 $args = func_get_args();
889 array_shift( $args );
892 $sql = $this->fillPrepared( $prepared['query'], $args );
894 return $this->query( $sql, $prepared['func'] );
898 * Prepare & execute an SQL statement, quoting and inserting arguments
899 * in the appropriate places.
901 * This function should not be used directly by new code outside of the
902 * database classes. The query wrapper functions (select() etc.) should be
905 * @param $query String
908 * @return ResultWrapper
910 function safeQuery( $query, $args = null ) {
911 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
913 if ( !is_array( $args ) ) {
915 $args = func_get_args();
916 array_shift( $args );
919 $retval = $this->execute( $prepared, $args );
920 $this->freePrepared( $prepared );
926 * For faking prepared SQL statements on DBs that don't support
928 * @param $preparedQuery String: a 'preparable' SQL statement
929 * @param $args Array of arguments to fill it with
930 * @return string executable SQL
932 function fillPrepared( $preparedQuery, $args ) {
934 $this->preparedArgs
=& $args;
936 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
937 array( &$this, 'fillPreparedArg' ), $preparedQuery );
941 * preg_callback func for fillPrepared()
942 * The arguments should be in $this->preparedArgs and must not be touched
943 * while we're doing this.
945 * @param $matches Array
949 function fillPreparedArg( $matches ) {
950 switch( $matches[1] ) {
951 case '\\?': return '?';
952 case '\\!': return '!';
953 case '\\&': return '&';
956 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
958 switch( $matches[1] ) {
959 case '?': return $this->addQuotes( $arg );
960 case '!': return $arg;
962 # return $this->addQuotes( file_get_contents( $arg ) );
963 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
965 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
970 * Free a result object returned by query() or select(). It's usually not
971 * necessary to call this, just use unset() or let the variable holding
972 * the result object go out of scope.
974 * @param $res Mixed: A SQL result
976 function freeResult( $res ) {
980 * Simple UPDATE wrapper.
981 * Usually throws a DBQueryError on failure.
982 * If errors are explicitly ignored, returns success
984 * This function exists for historical reasons, DatabaseBase::update() has a more standard
985 * calling convention and feature set
989 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
990 $table = $this->tableName( $table );
991 $sql = "UPDATE $table SET $var = '" .
992 $this->strencode( $value ) . "' WHERE ($cond)";
994 return (bool)$this->query( $sql, $fname );
998 * A SELECT wrapper which returns a single field from a single result row.
1000 * Usually throws a DBQueryError on failure. If errors are explicitly
1001 * ignored, returns false on failure.
1003 * If no result rows are returned from the query, false is returned.
1005 * @param $table Table name. See DatabaseBase::select() for details.
1006 * @param $var The field name to select. This must be a valid SQL
1007 * fragment: do not use unvalidated user input.
1008 * @param $cond The condition array. See DatabaseBase::select() for details.
1009 * @param $fname The function name of the caller.
1010 * @param $options The query options. See DatabaseBase::select() for details.
1012 * @return The value from the field, or false on failure.
1014 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1015 $options = array() )
1017 if ( !is_array( $options ) ) {
1018 $options = array( $options );
1021 $options['LIMIT'] = 1;
1023 $res = $this->select( $table, $var, $cond, $fname, $options );
1025 if ( $res === false ||
!$this->numRows( $res ) ) {
1029 $row = $this->fetchRow( $res );
1031 if ( $row !== false ) {
1032 return reset( $row );
1039 * Returns an optional USE INDEX clause to go after the table, and a
1040 * string to go at the end of the query.
1042 * @param $options Array: associative array of options to be turned into
1043 * an SQL query, valid keys are listed in the function.
1045 * @see DatabaseBase::select()
1047 function makeSelectOptions( $options ) {
1048 $preLimitTail = $postLimitTail = '';
1051 $noKeyOptions = array();
1053 foreach ( $options as $key => $option ) {
1054 if ( is_numeric( $key ) ) {
1055 $noKeyOptions[$option] = true;
1059 if ( isset( $options['GROUP BY'] ) ) {
1060 $gb = is_array( $options['GROUP BY'] )
1061 ?
implode( ',', $options['GROUP BY'] )
1062 : $options['GROUP BY'];
1063 $preLimitTail .= " GROUP BY {$gb}";
1066 if ( isset( $options['HAVING'] ) ) {
1067 $preLimitTail .= " HAVING {$options['HAVING']}";
1070 if ( isset( $options['ORDER BY'] ) ) {
1071 $ob = is_array( $options['ORDER BY'] )
1072 ?
implode( ',', $options['ORDER BY'] )
1073 : $options['ORDER BY'];
1074 $preLimitTail .= " ORDER BY {$ob}";
1077 // if (isset($options['LIMIT'])) {
1078 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1079 // isset($options['OFFSET']) ? $options['OFFSET']
1083 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1084 $postLimitTail .= ' FOR UPDATE';
1087 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1088 $postLimitTail .= ' LOCK IN SHARE MODE';
1091 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1092 $startOpts .= 'DISTINCT';
1095 # Various MySQL extensions
1096 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1097 $startOpts .= ' /*! STRAIGHT_JOIN */';
1100 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1101 $startOpts .= ' HIGH_PRIORITY';
1104 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1105 $startOpts .= ' SQL_BIG_RESULT';
1108 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1109 $startOpts .= ' SQL_BUFFER_RESULT';
1112 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1113 $startOpts .= ' SQL_SMALL_RESULT';
1116 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1117 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1120 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1121 $startOpts .= ' SQL_CACHE';
1124 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1125 $startOpts .= ' SQL_NO_CACHE';
1128 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1129 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1134 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1138 * Execute a SELECT query constructed using the various parameters provided.
1139 * See below for full details of the parameters.
1141 * @param $table Table name
1142 * @param $vars Field names
1143 * @param $conds Conditions
1144 * @param $fname Caller function name
1145 * @param $options Query options
1146 * @param $join_conds Join conditions
1151 * May be either an array of table names, or a single string holding a table
1152 * name. If an array is given, table aliases can be specified, for example:
1154 * array( 'a' => 'user' )
1156 * This includes the user table in the query, with the alias "a" available
1157 * for use in field names (e.g. a.user_name).
1159 * All of the table names given here are automatically run through
1160 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1161 * added, and various other table name mappings to be performed.
1166 * May be either a field name or an array of field names. The field names
1167 * here are complete fragments of SQL, for direct inclusion into the SELECT
1168 * query. Expressions and aliases may be specified as in SQL, for example:
1170 * array( 'MAX(rev_id) AS maxrev' )
1172 * If an expression is given, care must be taken to ensure that it is
1178 * May be either a string containing a single condition, or an array of
1179 * conditions. If an array is given, the conditions constructed from each
1180 * element are combined with AND.
1182 * Array elements may take one of two forms:
1184 * - Elements with a numeric key are interpreted as raw SQL fragments.
1185 * - Elements with a string key are interpreted as equality conditions,
1186 * where the key is the field name.
1187 * - If the value of such an array element is a scalar (such as a
1188 * string), it will be treated as data and thus quoted appropriately.
1189 * If it is null, an IS NULL clause will be added.
1190 * - If the value is an array, an IN(...) clause will be constructed,
1191 * such that the field name may match any of the elements in the
1192 * array. The elements of the array will be quoted.
1193 * - If the field name ends with "!", this is taken as a flag which
1194 * inverts the comparison, allowing NOT IN clauses to be constructed,
1195 * for example: array( 'user_id!' => array( 1, 2, 3 ) )
1197 * Note that expressions are often DBMS-dependent in their syntax.
1198 * DBMS-independent wrappers are provided for constructing several types of
1199 * expression commonly used in condition queries. See:
1200 * - DatabaseBase::buildLike()
1201 * - DatabaseBase::conditional()
1206 * Optional: Array of query options. Boolean options are specified by
1207 * including them in the array as a string value with a numeric key, for
1210 * array( 'FOR UPDATE' )
1212 * The supported options are:
1214 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1215 * with LIMIT can theoretically be used for paging through a result set,
1216 * but this is discouraged in MediaWiki for performance reasons.
1218 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1219 * and then the first rows are taken until the limit is reached. LIMIT
1220 * is applied to a result set after OFFSET.
1222 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1223 * changed until the next COMMIT.
1225 * - DISTINCT: Boolean: return only unique result rows.
1227 * - GROUP BY: May be either an SQL fragment string naming a field or
1228 * expression to group by, or an array of such SQL fragments.
1230 * - HAVING: A string containing a HAVING clause.
1232 * - ORDER BY: May be either an SQL fragment giving a field name or
1233 * expression to order by, or an array of such SQL fragments.
1235 * - USE INDEX: This may be either a string giving the index name to use
1236 * for the query, or an array. If it is an associative array, each key
1237 * gives the table name (or alias), each value gives the index name to
1238 * use for that table. All strings are SQL fragments and so should be
1239 * validated by the caller.
1241 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1242 * instead of SELECT.
1244 * And also the following boolean MySQL extensions, see the MySQL manual
1245 * for documentation:
1247 * - LOCK IN SHARE MODE
1251 * - SQL_BUFFER_RESULT
1252 * - SQL_SMALL_RESULT
1253 * - SQL_CALC_FOUND_ROWS
1260 * Optional associative array of table-specific join conditions. In the
1261 * most common case, this is unnecessary, since the join condition can be
1262 * in $conds. However, it is useful for doing a LEFT JOIN.
1264 * The key of the array contains the table name or alias. The value is an
1265 * array with two elements, numbered 0 and 1. The first gives the type of
1266 * join, the second is an SQL fragment giving the join condition for that
1267 * table. For example:
1269 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1271 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1272 * with no rows in it will be returned. If there was a query error, a
1273 * DBQueryError exception will be thrown, except if the "ignore errors"
1274 * option was set, in which case false will be returned.
1276 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1277 $options = array(), $join_conds = array() )
1279 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1281 return $this->query( $sql, $fname );
1285 * The equivalent of DatabaseBase::select() except that the constructed SQL
1286 * is returned, instead of being immediately executed.
1288 * @param $table Table name
1289 * @param $vars Field names
1290 * @param $conds Conditions
1291 * @param $fname Caller function name
1292 * @param $options Query options
1293 * @param $join_conds Join conditions
1295 * @return SQL query string.
1296 * @see DatabaseBase::select()
1298 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1299 if ( is_array( $vars ) ) {
1300 $vars = implode( ',', $vars );
1303 $options = (array)$options;
1305 if ( is_array( $table ) ) {
1306 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1307 ?
$options['USE INDEX']
1309 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1311 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1313 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1315 } elseif ( $table != '' ) {
1316 if ( $table { 0 } == ' ' ) {
1317 $from = ' FROM ' . $table;
1319 $from = ' FROM ' . $this->tableName( $table );
1325 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1327 if ( !empty( $conds ) ) {
1328 if ( is_array( $conds ) ) {
1329 $conds = $this->makeList( $conds, LIST_AND
);
1331 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1333 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1336 if ( isset( $options['LIMIT'] ) ) {
1337 $sql = $this->limitResult( $sql, $options['LIMIT'],
1338 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1340 $sql = "$sql $postLimitTail";
1342 if ( isset( $options['EXPLAIN'] ) ) {
1343 $sql = 'EXPLAIN ' . $sql;
1350 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1351 * that a single row object is returned. If the query returns no rows,
1352 * false is returned.
1354 * @param $table Table name
1355 * @param $vars Field names
1356 * @param $conds Conditions
1357 * @param $fname Caller function name
1358 * @param $options Query options
1359 * @param $join_conds Join conditions
1361 * @return ResultWrapper or bool
1363 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1364 $options = array(), $join_conds = array() )
1366 $options['LIMIT'] = 1;
1367 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1369 if ( $res === false ) {
1373 if ( !$this->numRows( $res ) ) {
1377 $obj = $this->fetchObject( $res );
1383 * Estimate rows in dataset.
1385 * MySQL allows you to estimate the number of rows that would be returned
1386 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1387 * index cardinality statistics, and is notoriously inaccurate, especially
1388 * when large numbers of rows have recently been added or deleted.
1390 * For DBMSs that don't support fast result size estimation, this function
1391 * will actually perform the SELECT COUNT(*).
1393 * Takes the same arguments as DatabaseBase::select().
1395 * @param $table String: table name
1396 * @param $vars Array: unused
1397 * @param $conds Array: filters on the table
1398 * @param $fname String: function name for profiling
1399 * @param $options Array: options for select
1400 * @return Integer: row count
1402 public function estimateRowCount( $table, $vars = '*', $conds = '',
1403 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1406 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1409 $row = $this->fetchRow( $res );
1410 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1417 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1418 * It's only slightly flawed. Don't use for anything important.
1420 * @param $sql String: A SQL Query
1422 static function generalizeSQL( $sql ) {
1423 # This does the same as the regexp below would do, but in such a way
1424 # as to avoid crashing php on some large strings.
1425 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1427 $sql = str_replace ( "\\\\", '', $sql );
1428 $sql = str_replace ( "\\'", '', $sql );
1429 $sql = str_replace ( "\\\"", '', $sql );
1430 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1431 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1433 # All newlines, tabs, etc replaced by single space
1434 $sql = preg_replace ( '/\s+/', ' ', $sql );
1437 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1443 * Determines whether a field exists in a table
1445 * @param $table String: table name
1446 * @param $field String: filed to check on that table
1447 * @param $fname String: calling function name (optional)
1448 * @return Boolean: whether $table has filed $field
1450 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1451 $info = $this->fieldInfo( $table, $field );
1457 * Determines whether an index exists
1458 * Usually throws a DBQueryError on failure
1459 * If errors are explicitly ignored, returns NULL on failure
1463 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1464 $info = $this->indexInfo( $table, $index, $fname );
1465 if ( is_null( $info ) ) {
1468 return $info !== false;
1473 * Query whether a given table exists
1479 function tableExists( $table ) {
1480 $table = $this->tableName( $table );
1481 $old = $this->ignoreErrors( true );
1482 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1483 $this->ignoreErrors( $old );
1489 * mysql_field_type() wrapper
1491 function fieldType( $res, $index ) {
1492 if ( $res instanceof ResultWrapper
) {
1493 $res = $res->result
;
1496 return mysql_field_type( $res, $index );
1500 * Determines if a given index is unique
1502 * @param $table string
1503 * @param $index string
1507 function indexUnique( $table, $index ) {
1508 $indexInfo = $this->indexInfo( $table, $index );
1510 if ( !$indexInfo ) {
1514 return !$indexInfo[0]->Non_unique
;
1518 * Helper for DatabaseBase::insert().
1520 * @param $options array
1523 function makeInsertOptions( $options ) {
1524 return implode( ' ', $options );
1528 * INSERT wrapper, inserts an array into a table.
1532 * - A single associative array. The array keys are the field names, and
1533 * the values are the values to insert. The values are treated as data
1534 * and will be quoted appropriately. If NULL is inserted, this will be
1535 * converted to a database NULL.
1536 * - An array with numeric keys, holding a list of associative arrays.
1537 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1538 * each subarray must be identical to each other, and in the same order.
1540 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1543 * $options is an array of options, with boolean options encoded as values
1544 * with numeric keys, in the same style as $options in
1545 * DatabaseBase::select(). Supported options are:
1547 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1548 * any rows which cause duplicate key errors are not inserted. It's
1549 * possible to determine how many rows were successfully inserted using
1550 * DatabaseBase::affectedRows().
1552 * @param $table Table name. This will be passed through
1553 * DatabaseBase::tableName().
1554 * @param $a Array of rows to insert
1555 * @param $fname Calling function name (use __METHOD__) for logs/profiling
1556 * @param $options Array of options
1560 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1561 # No rows to insert, easy just return now
1562 if ( !count( $a ) ) {
1566 $table = $this->tableName( $table );
1568 if ( !is_array( $options ) ) {
1569 $options = array( $options );
1572 $options = $this->makeInsertOptions( $options );
1574 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1576 $keys = array_keys( $a[0] );
1579 $keys = array_keys( $a );
1582 $sql = 'INSERT ' . $options .
1583 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1587 foreach ( $a as $row ) {
1593 $sql .= '(' . $this->makeList( $row ) . ')';
1596 $sql .= '(' . $this->makeList( $a ) . ')';
1599 return (bool)$this->query( $sql, $fname );
1603 * Make UPDATE options for the DatabaseBase::update function
1605 * @param $options Array: The options passed to DatabaseBase::update
1608 function makeUpdateOptions( $options ) {
1609 if ( !is_array( $options ) ) {
1610 $options = array( $options );
1615 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1616 $opts[] = $this->lowPriorityOption();
1619 if ( in_array( 'IGNORE', $options ) ) {
1623 return implode( ' ', $opts );
1627 * UPDATE wrapper. Takes a condition array and a SET array.
1629 * @param $table The name of the table to UPDATE. This will be passed through
1630 * DatabaseBase::tableName().
1632 * @param $values Array: An array of values to SET. For each array element,
1633 * the key gives the field name, and the value gives the data
1634 * to set that field to. The data will be quoted by
1635 * DatabaseBase::addQuotes().
1637 * @param $conds Array: An array of conditions (WHERE). See
1638 * DatabaseBase::select() for the details of the format of
1639 * condition arrays. Use '*' to update all rows.
1641 * @param $fname String: The function name of the caller (from __METHOD__),
1642 * for logging and profiling.
1644 * @param $options Array: An array of UPDATE options, can be:
1645 * - IGNORE: Ignore unique key conflicts
1646 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1649 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1650 $table = $this->tableName( $table );
1651 $opts = $this->makeUpdateOptions( $options );
1652 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1654 if ( $conds != '*' ) {
1655 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1658 return $this->query( $sql, $fname );
1662 * Makes an encoded list of strings from an array
1663 * @param $a Array containing the data
1665 * - LIST_COMMA: comma separated, no field names
1666 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1667 * the documentation for $conds in DatabaseBase::select().
1668 * - LIST_OR: ORed WHERE clause (without the WHERE)
1669 * - LIST_SET: comma separated with field names, like a SET clause
1670 * - LIST_NAMES: comma separated field names
1672 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1673 * mark to generate a 'NOT IN' structure.
1676 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1679 * 'field' NOT IN ('1', '2', '3' );
1683 function makeList( $a, $mode = LIST_COMMA
) {
1684 if ( !is_array( $a ) ) {
1685 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1691 foreach ( $a as $field => $value ) {
1693 if ( $mode == LIST_AND
) {
1695 } elseif ( $mode == LIST_OR
) {
1704 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1706 if( substr($field,-1) == '!' ) {
1708 $field = substr($field, 0, -1 );
1711 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1712 $list .= "($value)";
1713 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1715 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1716 if ( count( $value ) == 0 ) {
1717 throw new MWException( __METHOD__
. ': empty input' );
1718 } elseif ( count( $value ) == 1 ) {
1719 // Special-case single values, as IN isn't terribly efficient
1720 // Don't necessarily assume the single key is 0; we don't
1721 // enforce linear numeric ordering on other arrays here.
1722 $value = array_values( $value );
1724 $operator = $not ?
' != ' : ' = ';
1725 $list .= $field . $operator . $this->addQuotes( $value[0] );
1727 $operator = $not ?
' NOT IN ' : ' IN ';
1728 $list .= $field . $operator . "(" . $this->makeList( $value ) . ")";
1730 } elseif ( $value === null ) {
1731 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1732 $list .= "$field IS ";
1736 } elseif ( $mode == LIST_SET
) {
1737 $list .= "$field = ";
1741 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1742 $list .= "$field = ";
1744 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1752 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1753 * The keys on each level may be either integers or strings.
1755 * @param $data Array: organized as 2-d
1756 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1757 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1758 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1759 * @return Mixed: string SQL fragment, or false if no items in array.
1761 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1764 foreach ( $data as $base => $sub ) {
1765 if ( count( $sub ) ) {
1766 $conds[] = $this->makeList(
1767 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1773 return $this->makeList( $conds, LIST_OR
);
1775 // Nothing to search for...
1781 * Bitwise operations
1788 function bitNot( $field ) {
1794 * @param $fieldRight
1797 function bitAnd( $fieldLeft, $fieldRight ) {
1798 return "($fieldLeft & $fieldRight)";
1803 * @param $fieldRight
1806 function bitOr( $fieldLeft, $fieldRight ) {
1807 return "($fieldLeft | $fieldRight)";
1811 * Change the current database
1813 * @todo Explain what exactly will fail if this is not overridden.
1814 * @return bool Success or failure
1816 function selectDB( $db ) {
1817 # Stub. Shouldn't cause serious problems if it's not overridden, but
1818 # if your database engine supports a concept similar to MySQL's
1819 # databases you may as well.
1820 $this->mDBname
= $db;
1825 * Get the current DB name
1827 function getDBname() {
1828 return $this->mDBname
;
1832 * Get the server hostname or IP address
1834 function getServer() {
1835 return $this->mServer
;
1839 * Format a table name ready for use in constructing an SQL query
1841 * This does two important things: it quotes the table names to clean them up,
1842 * and it adds a table prefix if only given a table name with no quotes.
1844 * All functions of this object which require a table name call this function
1845 * themselves. Pass the canonical name to such functions. This is only needed
1846 * when calling query() directly.
1848 * @param $name String: database table name
1849 * @param $quoted Boolean: Automatically pass the table name through
1850 * addIdentifierQuotes() so that it can be used in a query.
1851 * @return String: full database name
1853 function tableName( $name, $quoted = true ) {
1854 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1855 # Skip the entire process when we have a string quoted on both ends.
1856 # Note that we check the end so that we will still quote any use of
1857 # use of `database`.table. But won't break things if someone wants
1858 # to query a database table with a dot in the name.
1859 if ( $this->isQuotedIdentifier( $name ) ) {
1863 # Lets test for any bits of text that should never show up in a table
1864 # name. Basically anything like JOIN or ON which are actually part of
1865 # SQL queries, but may end up inside of the table value to combine
1866 # sql. Such as how the API is doing.
1867 # Note that we use a whitespace test rather than a \b test to avoid
1868 # any remote case where a word like on may be inside of a table name
1869 # surrounded by symbols which may be considered word breaks.
1870 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1874 # Split database and table into proper variables.
1875 # We reverse the explode so that database.table and table both output
1876 # the correct table.
1877 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1878 if ( isset( $dbDetails[1] ) ) {
1879 @list
( $table, $database ) = $dbDetails;
1881 @list
( $table ) = $dbDetails;
1883 $prefix = $this->mTablePrefix
; # Default prefix
1885 # Note that we use the long format because php will complain in in_array if
1886 # the input is not an array, and will complain in is_array if it is not set.
1887 if ( !isset( $database ) # Don't use shared database if pre selected.
1888 && isset( $wgSharedDB ) # We have a shared database
1889 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1890 && isset( $wgSharedTables )
1891 && is_array( $wgSharedTables )
1892 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1893 $database = $wgSharedDB;
1894 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1897 # Quote the $database and $table and apply the prefix if not quoted.
1898 if ( isset( $database ) ) {
1899 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1903 $table = "{$prefix}{$table}";
1904 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1905 $table = $this->addIdentifierQuotes( "{$table}" );
1908 # Merge our database and table into our final table name.
1909 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1915 * Fetch a number of table names into an array
1916 * This is handy when you need to construct SQL for joins
1919 * extract($dbr->tableNames('user','watchlist'));
1920 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1921 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1923 public function tableNames() {
1924 $inArray = func_get_args();
1927 foreach ( $inArray as $name ) {
1928 $retVal[$name] = $this->tableName( $name );
1935 * Fetch a number of table names into an zero-indexed numerical array
1936 * This is handy when you need to construct SQL for joins
1939 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1940 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1941 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1943 public function tableNamesN() {
1944 $inArray = func_get_args();
1947 foreach ( $inArray as $name ) {
1948 $retVal[] = $this->tableName( $name );
1955 * Get an aliased table name
1956 * e.g. tableName AS newTableName
1958 * @param $name string Table name, see tableName()
1959 * @param $alias string Alias (optional)
1960 * @return string SQL name for aliased table. Will not alias a table to its own name
1962 public function tableNameWithAlias( $name, $alias = false ) {
1963 if ( !$alias ||
$alias == $name ) {
1964 return $this->tableName( $name );
1966 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1971 * Gets an array of aliased table names
1973 * @param $tables array( [alias] => table )
1974 * @return array of strings, see tableNameWithAlias()
1976 public function tableNamesWithAlias( $tables ) {
1978 foreach ( $tables as $alias => $table ) {
1979 if ( is_numeric( $alias ) ) {
1982 $retval[] = $this->tableNameWithAlias( $table, $alias );
1988 * Get the aliased table name clause for a FROM clause
1989 * which might have a JOIN and/or USE INDEX clause
1991 * @param $tables array( [alias] => table )
1992 * @param $use_index array() Same as for select()
1993 * @param $join_conds array() Same as for select()
1996 protected function tableNamesWithUseIndexOrJOIN(
1997 $tables, $use_index = array(), $join_conds = array()
2001 $use_index = (array)$use_index;
2002 $join_conds = (array)$join_conds;
2004 foreach ( $tables as $alias => $table ) {
2005 if ( !is_string( $alias ) ) {
2006 // No alias? Set it equal to the table name
2009 // Is there a JOIN clause for this table?
2010 if ( isset( $join_conds[$alias] ) ) {
2011 list( $joinType, $conds ) = $join_conds[$alias];
2012 $tableClause = $joinType;
2013 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2014 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2015 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2017 $tableClause .= ' ' . $use;
2020 $on = $this->makeList( (array)$conds, LIST_AND
);
2022 $tableClause .= ' ON (' . $on . ')';
2025 $retJOIN[] = $tableClause;
2026 // Is there an INDEX clause for this table?
2027 } elseif ( isset( $use_index[$alias] ) ) {
2028 $tableClause = $this->tableNameWithAlias( $table, $alias );
2029 $tableClause .= ' ' . $this->useIndexClause(
2030 implode( ',', (array)$use_index[$alias] ) );
2032 $ret[] = $tableClause;
2034 $tableClause = $this->tableNameWithAlias( $table, $alias );
2036 $ret[] = $tableClause;
2040 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2041 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2042 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2044 // Compile our final table clause
2045 return implode( ' ', array( $straightJoins, $otherJoins ) );
2049 * Get the name of an index in a given table
2055 function indexName( $index ) {
2056 // Backwards-compatibility hack
2058 'ar_usertext_timestamp' => 'usertext_timestamp',
2059 'un_user_id' => 'user_id',
2060 'un_user_ip' => 'user_ip',
2063 if ( isset( $renamed[$index] ) ) {
2064 return $renamed[$index];
2071 * If it's a string, adds quotes and backslashes
2072 * Otherwise returns as-is
2078 function addQuotes( $s ) {
2079 if ( $s === null ) {
2082 # This will also quote numeric values. This should be harmless,
2083 # and protects against weird problems that occur when they really
2084 # _are_ strings such as article titles and string->number->string
2085 # conversion is not 1:1.
2086 return "'" . $this->strencode( $s ) . "'";
2091 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2092 * MySQL uses `backticks` while basically everything else uses double quotes.
2093 * Since MySQL is the odd one out here the double quotes are our generic
2094 * and we implement backticks in DatabaseMysql.
2098 public function addIdentifierQuotes( $s ) {
2099 return '"' . str_replace( '"', '""', $s ) . '"';
2103 * Returns if the given identifier looks quoted or not according to
2104 * the database convention for quoting identifiers .
2106 * @param $name string
2110 public function isQuotedIdentifier( $name ) {
2111 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2115 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2116 * which used quote_ident which does not follow our naming conventions
2117 * was renamed to addIdentifierQuotes.
2118 * @deprecated since 1.18 use addIdentifierQuotes
2122 function quote_ident( $s ) {
2123 wfDeprecated( __METHOD__
);
2124 return $this->addIdentifierQuotes( $s );
2128 * Escape string for safe LIKE usage.
2129 * WARNING: you should almost never use this function directly,
2130 * instead use buildLike() that escapes everything automatically
2131 * @deprecated since 1.17, warnings in 1.17, removed in ???
2133 public function escapeLike( $s ) {
2134 wfDeprecated( __METHOD__
);
2135 return $this->escapeLikeInternal( $s );
2138 protected function escapeLikeInternal( $s ) {
2139 $s = str_replace( '\\', '\\\\', $s );
2140 $s = $this->strencode( $s );
2141 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2147 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2148 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2149 * Alternatively, the function could be provided with an array of aforementioned parameters.
2151 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2152 * for subpages of 'My page title'.
2153 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2156 * @return String: fully built LIKE statement
2158 function buildLike() {
2159 $params = func_get_args();
2161 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2162 $params = $params[0];
2167 foreach ( $params as $value ) {
2168 if ( $value instanceof LikeMatch
) {
2169 $s .= $value->toString();
2171 $s .= $this->escapeLikeInternal( $value );
2175 return " LIKE '" . $s . "' ";
2179 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2183 function anyChar() {
2184 return new LikeMatch( '_' );
2188 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2190 * @rerturn LikeMatch
2192 function anyString() {
2193 return new LikeMatch( '%' );
2197 * Returns an appropriately quoted sequence value for inserting a new row.
2198 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2199 * subclass will return an integer, and save the value for insertId()
2201 function nextSequenceValue( $seqName ) {
2206 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2207 * is only needed because a) MySQL must be as efficient as possible due to
2208 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2209 * which index to pick. Anyway, other databases might have different
2210 * indexes on a given table. So don't bother overriding this unless you're
2213 function useIndexClause( $index ) {
2218 * REPLACE query wrapper
2219 * PostgreSQL simulates this with a DELETE followed by INSERT
2220 * $row is the row to insert, an associative array
2221 * $uniqueIndexes is an array of indexes. Each element may be either a
2222 * field name or an array of field names
2224 * It may be more efficient to leave off unique indexes which are unlikely to collide.
2225 * However if you do this, you run the risk of encountering errors which wouldn't have
2228 * @param $table String: The table to replace the row(s) in.
2229 * @param $uniqueIndexes Array: An associative array of indexes
2230 * @param $rows Array: Array of rows to replace
2231 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2233 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2234 $table = $this->tableName( $table );
2237 if ( !is_array( reset( $rows ) ) ) {
2238 $rows = array( $rows );
2241 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2244 foreach ( $rows as $row ) {
2251 $sql .= '(' . $this->makeList( $row ) . ')';
2254 return $this->query( $sql, $fname );
2258 * DELETE where the condition is a join.
2260 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2261 * we use sub-selects
2263 * For safety, an empty $conds will not delete everything. If you want to
2264 * delete all rows where the join condition matches, set $conds='*'.
2266 * DO NOT put the join condition in $conds.
2268 * @param $delTable String: The table to delete from.
2269 * @param $joinTable String: The other table.
2270 * @param $delVar String: The variable to join on, in the first table.
2271 * @param $joinVar String: The variable to join on, in the second table.
2272 * @param $conds Array: Condition array of field names mapped to variables,
2273 * ANDed together in the WHERE clause
2274 * @param $fname String: Calling function name (use __METHOD__) for
2277 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2278 $fname = 'DatabaseBase::deleteJoin' )
2281 throw new DBUnexpectedError( $this,
2282 'DatabaseBase::deleteJoin() called with empty $conds' );
2285 $delTable = $this->tableName( $delTable );
2286 $joinTable = $this->tableName( $joinTable );
2287 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2288 if ( $conds != '*' ) {
2289 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2293 $this->query( $sql, $fname );
2297 * Returns the size of a text field, or -1 for "unlimited"
2299 function textFieldSize( $table, $field ) {
2300 $table = $this->tableName( $table );
2301 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2302 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2303 $row = $this->fetchObject( $res );
2307 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2317 * A string to insert into queries to show that they're low-priority, like
2318 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2319 * string and nothing bad should happen.
2321 * @return string Returns the text of the low priority option if it is
2322 * supported, or a blank string otherwise
2324 function lowPriorityOption() {
2329 * DELETE query wrapper.
2331 * @param $table Table name
2332 * @param $conds Condition array. See $conds in DatabaseBase::select() for
2333 * the format. Use $conds == "*" to delete all rows
2337 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2339 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2342 $table = $this->tableName( $table );
2343 $sql = "DELETE FROM $table";
2345 if ( $conds != '*' ) {
2346 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2349 return $this->query( $sql, $fname );
2353 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2354 * into another table.
2356 * @param $destTable The table name to insert into
2357 * @param $srcTable May be either a table name, or an array of table names
2358 * to include in a join.
2360 * @param $varMap must be an associative array of the form
2361 * array( 'dest1' => 'source1', ...). Source items may be literals
2362 * rather than field names, but strings should be quoted with
2363 * DatabaseBase::addQuotes()
2365 * @param $conds Condition array. See $conds in DatabaseBase::select() for
2366 * the details of the format of condition arrays. May be "*" to copy the
2369 * @param $fname The function name of the caller, from __METHOD__
2371 * @param $insertOptions Options for the INSERT part of the query, see
2372 * DatabaseBase::insert() for details.
2373 * @param $selectOptions Options for the SELECT part of the query, see
2374 * DatabaseBase::select() for details.
2376 * @return ResultWrapper
2378 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2379 $fname = 'DatabaseBase::insertSelect',
2380 $insertOptions = array(), $selectOptions = array() )
2382 $destTable = $this->tableName( $destTable );
2384 if ( is_array( $insertOptions ) ) {
2385 $insertOptions = implode( ' ', $insertOptions );
2388 if ( !is_array( $selectOptions ) ) {
2389 $selectOptions = array( $selectOptions );
2392 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2394 if ( is_array( $srcTable ) ) {
2395 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2397 $srcTable = $this->tableName( $srcTable );
2400 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2401 " SELECT $startOpts " . implode( ',', $varMap ) .
2402 " FROM $srcTable $useIndex ";
2404 if ( $conds != '*' ) {
2405 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2408 $sql .= " $tailOpts";
2410 return $this->query( $sql, $fname );
2414 * Construct a LIMIT query with optional offset. This is used for query
2415 * pages. The SQL should be adjusted so that only the first $limit rows
2416 * are returned. If $offset is provided as well, then the first $offset
2417 * rows should be discarded, and the next $limit rows should be returned.
2418 * If the result of the query is not ordered, then the rows to be returned
2419 * are theoretically arbitrary.
2421 * $sql is expected to be a SELECT, if that makes a difference. For
2422 * UPDATE, limitResultForUpdate should be used.
2424 * The version provided by default works in MySQL and SQLite. It will very
2425 * likely need to be overridden for most other DBMSes.
2427 * @param $sql String: SQL query we will append the limit too
2428 * @param $limit Integer: the SQL limit
2429 * @param $offset Integer the SQL offset (default false)
2433 function limitResult( $sql, $limit, $offset = false ) {
2434 if ( !is_numeric( $limit ) ) {
2435 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2438 return "$sql LIMIT "
2439 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2443 function limitResultForUpdate( $sql, $num ) {
2444 return $this->limitResult( $sql, $num, 0 );
2448 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2449 * within the UNION construct.
2452 function unionSupportsOrderAndLimit() {
2453 return true; // True for almost every DB supported
2457 * Construct a UNION query
2458 * This is used for providing overload point for other DB abstractions
2459 * not compatible with the MySQL syntax.
2460 * @param $sqls Array: SQL statements to combine
2461 * @param $all Boolean: use UNION ALL
2462 * @return String: SQL fragment
2464 function unionQueries( $sqls, $all ) {
2465 $glue = $all ?
') UNION ALL (' : ') UNION (';
2466 return '(' . implode( $glue, $sqls ) . ')';
2470 * Returns an SQL expression for a simple conditional. This doesn't need
2471 * to be overridden unless CASE isn't supported in your DBMS.
2473 * @param $cond String: SQL expression which will result in a boolean value
2474 * @param $trueVal String: SQL expression to return if true
2475 * @param $falseVal String: SQL expression to return if false
2476 * @return String: SQL fragment
2478 function conditional( $cond, $trueVal, $falseVal ) {
2479 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2483 * Returns a comand for str_replace function in SQL query.
2484 * Uses REPLACE() in MySQL
2486 * @param $orig String: column to modify
2487 * @param $old String: column to seek
2488 * @param $new String: column to replace with
2492 function strreplace( $orig, $old, $new ) {
2493 return "REPLACE({$orig}, {$old}, {$new})";
2497 * Determines if the last failure was due to a deadlock
2502 function wasDeadlock() {
2507 * Determines if the last query error was something that should be dealt
2508 * with by pinging the connection and reissuing the query.
2513 function wasErrorReissuable() {
2518 * Determines if the last failure was due to the database being read-only.
2523 function wasReadOnlyError() {
2528 * Perform a deadlock-prone transaction.
2530 * This function invokes a callback function to perform a set of write
2531 * queries. If a deadlock occurs during the processing, the transaction
2532 * will be rolled back and the callback function will be called again.
2535 * $dbw->deadlockLoop( callback, ... );
2537 * Extra arguments are passed through to the specified callback function.
2539 * Returns whatever the callback function returned on its successful,
2540 * iteration, or false on error, for example if the retry limit was
2543 function deadlockLoop() {
2544 $myFname = 'DatabaseBase::deadlockLoop';
2547 $args = func_get_args();
2548 $function = array_shift( $args );
2549 $oldIgnore = $this->ignoreErrors( true );
2550 $tries = DEADLOCK_TRIES
;
2552 if ( is_array( $function ) ) {
2553 $fname = $function[0];
2559 $retVal = call_user_func_array( $function, $args );
2560 $error = $this->lastError();
2561 $errno = $this->lastErrno();
2562 $sql = $this->lastQuery();
2565 if ( $this->wasDeadlock() ) {
2567 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2569 $this->reportQueryError( $error, $errno, $sql, $fname );
2572 } while ( $this->wasDeadlock() && --$tries > 0 );
2574 $this->ignoreErrors( $oldIgnore );
2576 if ( $tries <= 0 ) {
2577 $this->rollback( $myFname );
2578 $this->reportQueryError( $error, $errno, $sql, $fname );
2581 $this->commit( $myFname );
2587 * Do a SELECT MASTER_POS_WAIT()
2589 * @param $pos MySQLMasterPos object
2590 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2592 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2593 $fname = 'DatabaseBase::masterPosWait';
2594 wfProfileIn( $fname );
2596 # Commit any open transactions
2597 if ( $this->mTrxLevel
) {
2601 if ( !is_null( $this->mFakeSlaveLag
) ) {
2602 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2604 if ( $wait > $timeout * 1e6
) {
2605 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2606 wfProfileOut( $fname );
2608 } elseif ( $wait > 0 ) {
2609 wfDebug( "Fake slave waiting $wait us\n" );
2611 wfProfileOut( $fname );
2614 wfDebug( "Fake slave up to date ($wait us)\n" );
2615 wfProfileOut( $fname );
2620 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2621 $encFile = $this->addQuotes( $pos->file
);
2622 $encPos = intval( $pos->pos
);
2623 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2624 $res = $this->doQuery( $sql );
2626 if ( $res && $row = $this->fetchRow( $res ) ) {
2627 wfProfileOut( $fname );
2630 wfProfileOut( $fname );
2636 * Get the position of the master from SHOW SLAVE STATUS
2638 * @return MySQLMasterPos|false
2640 function getSlavePos() {
2641 if ( !is_null( $this->mFakeSlaveLag
) ) {
2642 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2643 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2647 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2648 $row = $this->fetchObject( $res );
2651 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2652 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2659 * Get the position of the master from SHOW MASTER STATUS
2661 * @return MySQLMasterPos|false
2663 function getMasterPos() {
2664 if ( $this->mFakeMaster
) {
2665 return new MySQLMasterPos( 'fake', microtime( true ) );
2668 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2669 $row = $this->fetchObject( $res );
2672 return new MySQLMasterPos( $row->File
, $row->Position
);
2679 * Begin a transaction, committing any previously open transaction
2681 function begin( $fname = 'DatabaseBase::begin' ) {
2682 $this->query( 'BEGIN', $fname );
2683 $this->mTrxLevel
= 1;
2689 function commit( $fname = 'DatabaseBase::commit' ) {
2690 if ( $this->mTrxLevel
) {
2691 $this->query( 'COMMIT', $fname );
2692 $this->mTrxLevel
= 0;
2697 * Rollback a transaction.
2698 * No-op on non-transactional databases.
2700 function rollback( $fname = 'DatabaseBase::rollback' ) {
2701 if ( $this->mTrxLevel
) {
2702 $this->query( 'ROLLBACK', $fname, true );
2703 $this->mTrxLevel
= 0;
2708 * Creates a new table with structure copied from existing table
2709 * Note that unlike most database abstraction functions, this function does not
2710 * automatically append database prefix, because it works at a lower
2711 * abstraction level.
2712 * The table names passed to this function shall not be quoted (this
2713 * function calls addIdentifierQuotes when needed).
2715 * @param $oldName String: name of table whose structure should be copied
2716 * @param $newName String: name of table to be created
2717 * @param $temporary Boolean: whether the new table should be temporary
2718 * @param $fname String: calling function name
2719 * @return Boolean: true if operation was successful
2721 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2722 $fname = 'DatabaseBase::duplicateTableStructure' )
2724 throw new MWException(
2725 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2729 * List all tables on the database
2731 * @param $prefix Only show tables with this prefix, e.g. mw_
2732 * @param $fname String: calling function name
2734 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2735 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2739 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2740 * to the format used for inserting into timestamp fields in this DBMS.
2742 * The result is unquoted, and needs to be passed through addQuotes()
2743 * before it can be included in raw SQL.
2747 function timestamp( $ts = 0 ) {
2748 return wfTimestamp( TS_MW
, $ts );
2752 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2753 * to the format used for inserting into timestamp fields in this DBMS. If
2754 * NULL is input, it is passed through, allowing NULL values to be inserted
2755 * into timestamp fields.
2757 * The result is unquoted, and needs to be passed through addQuotes()
2758 * before it can be included in raw SQL.
2762 function timestampOrNull( $ts = null ) {
2763 if ( is_null( $ts ) ) {
2766 return $this->timestamp( $ts );
2771 * Take the result from a query, and wrap it in a ResultWrapper if
2772 * necessary. Boolean values are passed through as is, to indicate success
2773 * of write queries or failure.
2775 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2776 * resource, and it was necessary to call this function to convert it to
2777 * a wrapper. Nowadays, raw database objects are never exposed to external
2778 * callers, so this is unnecessary in external code. For compatibility with
2779 * old code, ResultWrapper objects are passed through unaltered.
2781 function resultObject( $result ) {
2782 if ( empty( $result ) ) {
2784 } elseif ( $result instanceof ResultWrapper
) {
2786 } elseif ( $result === true ) {
2787 // Successful write query
2790 return new ResultWrapper( $this, $result );
2795 * Return aggregated value alias
2797 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2802 * Ping the server and try to reconnect if it there is no connection
2804 * @return bool Success or failure
2807 # Stub. Not essential to override.
2813 * Currently supported only by MySQL
2814 * @return Database replication lag in seconds
2817 return intval( $this->mFakeSlaveLag
);
2821 * Get status information from SHOW STATUS in an associative array
2825 function getStatus( $which = "%" ) {
2826 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2829 foreach ( $res as $row ) {
2830 $status[$row->Variable_name
] = $row->Value
;
2837 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2841 function maxListLen() {
2846 * Some DBMSs have a special format for inserting into blob fields, they
2847 * don't allow simple quoted strings to be inserted. To insert into such
2848 * a field, pass the data through this function before passing it to
2849 * DatabaseBase::insert().
2851 function encodeBlob( $b ) {
2856 * Some DBMSs return a special placeholder object representing blob fields
2857 * in result objects. Pass the object through this function to return the
2860 function decodeBlob( $b ) {
2865 * Override database's default connection timeout. May be useful for very
2866 * long batch queries such as full-wiki dumps, where a single query reads
2867 * out over hours or days. May or may not be necessary for non-MySQL
2868 * databases. For most purposes, leaving it as a no-op should be fine.
2870 * @param $timeout Integer in seconds
2872 public function setTimeout( $timeout ) {}
2875 * Read and execute SQL commands from a file.
2877 * Returns true on success, error string or exception on failure (depending
2878 * on object's error ignore settings).
2880 * @param $filename String: File name to open
2881 * @param $lineCallback Callback: Optional function called before reading each line
2882 * @param $resultCallback Callback: Optional function called for each MySQL result
2883 * @param $fname String: Calling function name or false if name should be
2884 * generated dynamically using $filename
2886 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2887 wfSuppressWarnings();
2888 $fp = fopen( $filename, 'r' );
2889 wfRestoreWarnings();
2891 if ( false === $fp ) {
2892 throw new MWException( "Could not open \"{$filename}\".\n" );
2896 $fname = __METHOD__
. "( $filename )";
2900 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2902 catch ( MWException
$e ) {
2913 * Get the full path of a patch file. Originally based on archive()
2914 * from updaters.inc. Keep in mind this always returns a patch, as
2915 * it fails back to MySQL if no DB-specific patch can be found
2917 * @param $patch String The name of the patch, like patch-something.sql
2918 * @return String Full path to patch file
2920 public function patchPath( $patch ) {
2923 $dbType = $this->getType();
2924 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2925 return "$IP/maintenance/$dbType/archives/$patch";
2927 return "$IP/maintenance/archives/$patch";
2932 * Set variables to be used in sourceFile/sourceStream, in preference to the
2933 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2934 * all. If it's set to false, $GLOBALS will be used.
2936 * @param $vars False, or array mapping variable name to value.
2938 function setSchemaVars( $vars ) {
2939 $this->mSchemaVars
= $vars;
2943 * Read and execute commands from an open file handle.
2945 * Returns true on success, error string or exception on failure (depending
2946 * on object's error ignore settings).
2948 * @param $fp Resource: File handle
2949 * @param $lineCallback Callback: Optional function called before reading each line
2950 * @param $resultCallback Callback: Optional function called for each MySQL result
2951 * @param $fname String: Calling function name
2953 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
2954 $fname = 'DatabaseBase::sourceStream' )
2958 $dollarquote = false;
2960 while ( ! feof( $fp ) ) {
2961 if ( $lineCallback ) {
2962 call_user_func( $lineCallback );
2965 $line = trim( fgets( $fp ) );
2966 $sl = strlen( $line ) - 1;
2972 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2976 # # Allow dollar quoting for function declarations
2977 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2978 if ( $dollarquote ) {
2979 $dollarquote = false;
2983 $dollarquote = true;
2986 elseif ( !$dollarquote ) {
2987 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2989 $line = substr( $line, 0, $sl );
3000 $cmd = str_replace( ';;', ";", $cmd );
3001 $cmd = $this->replaceVars( $cmd );
3002 $res = $this->query( $cmd, $fname );
3004 if ( $resultCallback ) {
3005 call_user_func( $resultCallback, $res, $this );
3008 if ( false === $res ) {
3009 $err = $this->lastError();
3010 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3022 * Database independent variable replacement. Replaces a set of variables
3023 * in an SQL statement with their contents as given by $this->getSchemaVars().
3025 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3027 * - '{$var}' should be used for text and is passed through the database's
3029 * - `{$var}` should be used for identifiers (eg: table and database names),
3030 * it is passed through the database's addIdentifierQuotes method which
3031 * can be overridden if the database uses something other than backticks.
3032 * - / *$var* / is just encoded, besides traditional table prefix and
3033 * table options its use should be avoided.
3035 * @param $ins String: SQL statement to replace variables in
3036 * @return String The new SQL statement with variables replaced
3038 protected function replaceSchemaVars( $ins ) {
3039 $vars = $this->getSchemaVars();
3040 foreach ( $vars as $var => $value ) {
3042 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3044 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3046 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3052 * Replace variables in sourced SQL
3054 protected function replaceVars( $ins ) {
3055 $ins = $this->replaceSchemaVars( $ins );
3058 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3059 array( $this, 'tableNameCallback' ), $ins );
3062 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3063 array( $this, 'indexNameCallback' ), $ins );
3069 * Get schema variables. If none have been set via setSchemaVars(), then
3070 * use some defaults from the current object.
3072 protected function getSchemaVars() {
3073 if ( $this->mSchemaVars
) {
3074 return $this->mSchemaVars
;
3076 return $this->getDefaultSchemaVars();
3081 * Get schema variables to use if none have been set via setSchemaVars().
3083 * Override this in derived classes to provide variables for tables.sql
3084 * and SQL patch files.
3086 protected function getDefaultSchemaVars() {
3091 * Table name callback
3094 protected function tableNameCallback( $matches ) {
3095 return $this->tableName( $matches[1] );
3099 * Index name callback
3101 protected function indexNameCallback( $matches ) {
3102 return $this->indexName( $matches[1] );
3106 * Build a concatenation list to feed into a SQL query
3107 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3110 function buildConcat( $stringList ) {
3111 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3115 * Acquire a named lock
3117 * Abstracted from Filestore::lock() so child classes can implement for
3120 * @param $lockName String: name of lock to aquire
3121 * @param $method String: name of method calling us
3122 * @param $timeout Integer: timeout
3125 public function lock( $lockName, $method, $timeout = 5 ) {
3132 * @param $lockName String: Name of lock to release
3133 * @param $method String: Name of method calling us
3135 * @return Returns 1 if the lock was released, 0 if the lock was not established
3136 * by this thread (in which case the lock is not released), and NULL if the named
3137 * lock did not exist
3139 public function unlock( $lockName, $method ) {
3144 * Lock specific tables
3146 * @param $read Array of tables to lock for read access
3147 * @param $write Array of tables to lock for write access
3148 * @param $method String name of caller
3149 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3151 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3156 * Unlock specific tables
3158 * @param $method String the caller
3160 public function unlockTables( $method ) {
3167 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3168 if( !$this->tableExists( $tableName ) ) {
3171 $sql = "DROP TABLE " . $this->tableName( $tableName );
3172 if( $this->cascadingDeletes() ) {
3175 return $this->query( $sql, $fName );
3179 * Get search engine class. All subclasses of this need to implement this
3180 * if they wish to use searching.
3184 public function getSearchEngine() {
3185 return 'SearchEngineDummy';
3189 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3190 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3191 * because "i" sorts after all numbers.
3195 public function getInfinity() {
3200 * Encode an expiry time
3202 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3205 public function encodeExpiry( $expiry ) {
3206 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3207 return $this->getInfinity();
3209 return $this->timestamp( $expiry );
3214 * Allow or deny "big selects" for this session only. This is done by setting
3215 * the sql_big_selects session variable.
3217 * This is a MySQL-specific feature.
3219 * @param $value Mixed: true for allow, false for deny, or "default" to
3220 * restore the initial value
3222 public function setBigSelects( $value = true ) {