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 protected $preparedArgs;
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
232 # These optionally set a variable and return the previous state
235 * A string describing the current software version, and possibly
236 * other details in a user-friendly way. Will be listed on Special:Version, etc.
237 * Use getServerVersion() to get machine-friendly information.
239 * @return string: Version information from the database server
241 public function getServerInfo() {
242 return $this->getServerVersion();
246 * Boolean, controls output of large amounts of debug information.
247 * @param $debug bool|null
248 * - true to enable debugging
249 * - false to disable debugging
250 * - omitted or null to do nothing
252 * @return The previous value of the flag
254 function debug( $debug = null ) {
255 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
259 * Turns buffering of SQL result sets on (true) or off (false). Default is
262 * Unbuffered queries are very troublesome in MySQL:
264 * - If another query is executed while the first query is being read
265 * out, the first query is killed. This means you can't call normal
266 * MediaWiki functions while you are reading an unbuffered query result
267 * from a normal wfGetDB() connection.
269 * - Unbuffered queries cause the MySQL server to use large amounts of
270 * memory and to hold broad locks which block other queries.
272 * If you want to limit client-side memory, it's almost always better to
273 * split up queries into batches using a LIMIT clause than to switch off
276 * @param $buffer null|bool
278 * @return The previous value of the flag
280 function bufferResults( $buffer = null ) {
281 if ( is_null( $buffer ) ) {
282 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
284 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
289 * Turns on (false) or off (true) the automatic generation and sending
290 * of a "we're sorry, but there has been a database error" page on
291 * database errors. Default is on (false). When turned off, the
292 * code should use lastErrno() and lastError() to handle the
293 * situation as appropriate.
295 * @param $ignoreErrors bool|null
297 * @return The previous value of the flag.
299 function ignoreErrors( $ignoreErrors = null ) {
300 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
304 * Gets or sets the current transaction level.
306 * Historically, transactions were allowed to be "nested". This is no
307 * longer supported, so this function really only returns a boolean.
309 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
310 * @return The previous value
312 function trxLevel( $level = null ) {
313 return wfSetVar( $this->mTrxLevel
, $level );
317 * Get/set the number of errors logged. Only useful when errors are ignored
318 * @param $count The count to set, or omitted to leave it unchanged.
319 * @return The error count
321 function errorCount( $count = null ) {
322 return wfSetVar( $this->mErrorCount
, $count );
326 * Get/set the table prefix.
327 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
328 * @return The previous table prefix.
330 function tablePrefix( $prefix = null ) {
331 return wfSetVar( $this->mTablePrefix
, $prefix );
335 * Get properties passed down from the server info array of the load
338 * @param $name string The entry of the info array to get, or null to get the
341 * @return LoadBalancer|null
343 function getLBInfo( $name = null ) {
344 if ( is_null( $name ) ) {
345 return $this->mLBInfo
;
347 if ( array_key_exists( $name, $this->mLBInfo
) ) {
348 return $this->mLBInfo
[$name];
356 * Set the LB info array, or a member of it. If called with one parameter,
357 * the LB info array is set to that parameter. If it is called with two
358 * parameters, the member with the given name is set to the given value.
363 function setLBInfo( $name, $value = null ) {
364 if ( is_null( $value ) ) {
365 $this->mLBInfo
= $name;
367 $this->mLBInfo
[$name] = $value;
372 * Set lag time in seconds for a fake slave
376 function setFakeSlaveLag( $lag ) {
377 $this->mFakeSlaveLag
= $lag;
381 * Make this connection a fake master
383 * @param $enabled bool
385 function setFakeMaster( $enabled = true ) {
386 $this->mFakeMaster
= $enabled;
390 * Returns true if this database supports (and uses) cascading deletes
394 function cascadingDeletes() {
399 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
403 function cleanupTriggers() {
408 * Returns true if this database is strict about what can be put into an IP field.
409 * Specifically, it uses a NULL value instead of an empty string.
413 function strictIPs() {
418 * Returns true if this database uses timestamps rather than integers
422 function realTimestamps() {
427 * Returns true if this database does an implicit sort when doing GROUP BY
431 function implicitGroupby() {
436 * Returns true if this database does an implicit order by when the column has an index
437 * For example: SELECT page_title FROM page LIMIT 1
441 function implicitOrderby() {
446 * Returns true if this database requires that SELECT DISTINCT queries require that all
447 ORDER BY expressions occur in the SELECT list per the SQL92 standard
451 function standardSelectDistinct() {
456 * Returns true if this database can do a native search on IP columns
457 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
461 function searchableIPs() {
466 * Returns true if this database can use functional indexes
470 function functionalIndexes() {
475 * Return the last query that went through DatabaseBase::query()
478 function lastQuery() {
479 return $this->mLastQuery
;
483 * Returns true if the connection may have been used for write queries.
484 * Should return true if unsure.
488 function doneWrites() {
489 return $this->mDoneWrites
;
493 * Is a connection to the database open?
497 return $this->mOpened
;
501 * Set a flag for this connection
503 * @param $flag Integer: DBO_* constants from Defines.php:
504 * - DBO_DEBUG: output some debug info (same as debug())
505 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
506 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
507 * - DBO_TRX: automatically start transactions
508 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
509 * and removes it in command line mode
510 * - DBO_PERSISTENT: use persistant database connection
512 function setFlag( $flag ) {
513 $this->mFlags |
= $flag;
517 * Clear a flag for this connection
519 * @param $flag: same as setFlag()'s $flag param
521 function clearFlag( $flag ) {
522 $this->mFlags
&= ~
$flag;
526 * Returns a boolean whether the flag $flag is set for this connection
528 * @param $flag: same as setFlag()'s $flag param
531 function getFlag( $flag ) {
532 return !!( $this->mFlags
& $flag );
536 * General read-only accessor
538 * @param $name string
542 function getProperty( $name ) {
549 function getWikiID() {
550 if ( $this->mTablePrefix
) {
551 return "{$this->mDBname}-{$this->mTablePrefix}";
553 return $this->mDBname
;
558 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
562 public function getSchemaPath() {
564 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
565 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
567 return "$IP/maintenance/tables.sql";
571 # ------------------------------------------------------------------------------
573 # ------------------------------------------------------------------------------
577 * @param $server String: database server host
578 * @param $user String: database user name
579 * @param $password String: database user password
580 * @param $dbName String: database name
582 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
584 function __construct( $server = false, $user = false, $password = false, $dbName = false,
585 $flags = 0, $tablePrefix = 'get from global'
587 global $wgDBprefix, $wgCommandLineMode;
589 $this->mFlags
= $flags;
591 if ( $this->mFlags
& DBO_DEFAULT
) {
592 if ( $wgCommandLineMode ) {
593 $this->mFlags
&= ~DBO_TRX
;
595 $this->mFlags |
= DBO_TRX
;
599 /** Get the default table prefix*/
600 if ( $tablePrefix == 'get from global' ) {
601 $this->mTablePrefix
= $wgDBprefix;
603 $this->mTablePrefix
= $tablePrefix;
607 $this->open( $server, $user, $password, $dbName );
612 * Same as new DatabaseMysql( ... ), kept for backward compatibility
613 * @deprecated since 1.17
615 * @return DatabaseMysql
617 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
618 wfDeprecated( __METHOD__
);
619 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
623 * Given a DB type, construct the name of the appropriate child class of
624 * DatabaseBase. This is designed to replace all of the manual stuff like:
625 * $class = 'Database' . ucfirst( strtolower( $type ) );
626 * as well as validate against the canonical list of DB types we have
628 * This factory function is mostly useful for when you need to connect to a
629 * database other than the MediaWiki default (such as for external auth,
630 * an extension, et cetera). Do not use this to connect to the MediaWiki
631 * database. Example uses in core:
632 * @see LoadBalancer::reallyOpenConnection()
633 * @see ExternalUser_MediaWiki::initFromCond()
634 * @see ForeignDBRepo::getMasterDB()
635 * @see WebInstaller_DBConnect::execute()
637 * @param $dbType String A possible DB type
638 * @param $p Array An array of options to pass to the constructor.
639 * Valid options are: host, user, password, dbname, flags, tablePrefix
640 * @return DatabaseBase subclass or null
642 public final static function factory( $dbType, $p = array() ) {
643 $canonicalDBTypes = array(
644 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
646 $dbType = strtolower( $dbType );
648 if( in_array( $dbType, $canonicalDBTypes ) ) {
649 $class = 'Database' . ucfirst( $dbType );
651 isset( $p['host'] ) ?
$p['host'] : false,
652 isset( $p['user'] ) ?
$p['user'] : false,
653 isset( $p['password'] ) ?
$p['password'] : false,
654 isset( $p['dbname'] ) ?
$p['dbname'] : false,
655 isset( $p['flags'] ) ?
$p['flags'] : 0,
656 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
663 protected function installErrorHandler() {
664 $this->mPHPError
= false;
665 $this->htmlErrors
= ini_set( 'html_errors', '0' );
666 set_error_handler( array( $this, 'connectionErrorHandler' ) );
670 * @return bool|string
672 protected function restoreErrorHandler() {
673 restore_error_handler();
674 if ( $this->htmlErrors
!== false ) {
675 ini_set( 'html_errors', $this->htmlErrors
);
677 if ( $this->mPHPError
) {
678 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
679 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
686 protected function connectionErrorHandler( $errno, $errstr ) {
687 $this->mPHPError
= $errstr;
691 * Closes a database connection.
692 * if it is open : commits any open transactions
694 * @return Bool operation success. true if already closed.
697 # Stub, should probably be overridden
702 * @param $error String: fallback error message, used if none is given by DB
704 function reportConnectionError( $error = 'Unknown error' ) {
705 $myError = $this->lastError();
711 throw new DBConnectionError( $this, $error );
715 * The DBMS-dependent part of query()
717 * @param $sql String: SQL query.
718 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
720 protected abstract function doQuery( $sql );
723 * Determine whether a query writes to the DB.
724 * Should return true if unsure.
730 function isWriteQuery( $sql ) {
731 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
735 * Run an SQL query and return the result. Normally throws a DBQueryError
736 * on failure. If errors are ignored, returns false instead.
738 * In new code, the query wrappers select(), insert(), update(), delete(),
739 * etc. should be used where possible, since they give much better DBMS
740 * independence and automatically quote or validate user input in a variety
741 * of contexts. This function is generally only useful for queries which are
742 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
745 * However, the query wrappers themselves should call this function.
747 * @param $sql String: SQL query
748 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
749 * comment (you can use __METHOD__ or add some extra info)
750 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
751 * maybe best to catch the exception instead?
752 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
753 * for a successful read query, or false on failure if $tempIgnore set
754 * @throws DBQueryError Thrown when the database returns an error of any kind
756 public function query( $sql, $fname = '', $tempIgnore = false ) {
757 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
758 if ( !Profiler
::instance()->isStub() ) {
759 # generalizeSQL will probably cut down the query to reasonable
760 # logging size most of the time. The substr is really just a sanity check.
763 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
764 $totalProf = 'DatabaseBase::query-master';
766 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
767 $totalProf = 'DatabaseBase::query';
770 wfProfileIn( $totalProf );
771 wfProfileIn( $queryProf );
774 $this->mLastQuery
= $sql;
775 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
776 # Set a flag indicating that writes have been done
777 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
778 $this->mDoneWrites
= true;
781 # Add a comment for easy SHOW PROCESSLIST interpretation
783 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
784 $userName = $wgUser->getName();
785 if ( mb_strlen( $userName ) > 15 ) {
786 $userName = mb_substr( $userName, 0, 15 ) . '...';
788 $userName = str_replace( '/', '', $userName );
792 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
794 # If DBO_TRX is set, start a transaction
795 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
796 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
797 # avoid establishing transactions for SHOW and SET statements too -
798 # that would delay transaction initializations to once connection
799 # is really used by application
800 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
801 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
805 if ( $this->debug() ) {
809 $sqlx = substr( $commentedSql, 0, 500 );
810 $sqlx = strtr( $sqlx, "\t\n", ' ' );
813 wfDebug( "Query $cnt (master): $sqlx\n" );
815 wfDebug( "Query $cnt (slave): $sqlx\n" );
819 if ( istainted( $sql ) & TC_MYSQL
) {
820 throw new MWException( 'Tainted query found' );
823 # Do the query and handle errors
824 $ret = $this->doQuery( $commentedSql );
826 # Try reconnecting if the connection was lost
827 if ( false === $ret && $this->wasErrorReissuable() ) {
828 # Transaction is gone, like it or not
829 $this->mTrxLevel
= 0;
830 wfDebug( "Connection lost, reconnecting...\n" );
832 if ( $this->ping() ) {
833 wfDebug( "Reconnected\n" );
834 $sqlx = substr( $commentedSql, 0, 500 );
835 $sqlx = strtr( $sqlx, "\t\n", ' ' );
836 global $wgRequestTime;
837 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
838 if ( $elapsed < 300 ) {
839 # Not a database error to lose a transaction after a minute or two
840 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
842 $ret = $this->doQuery( $commentedSql );
844 wfDebug( "Failed\n" );
848 if ( false === $ret ) {
849 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
852 if ( !Profiler
::instance()->isStub() ) {
853 wfProfileOut( $queryProf );
854 wfProfileOut( $totalProf );
857 return $this->resultObject( $ret );
861 * Report a query error. Log the error, and if neither the object ignore
862 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
864 * @param $error String
865 * @param $errno Integer
867 * @param $fname String
868 * @param $tempIgnore Boolean
870 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
871 # Ignore errors during error handling to avoid infinite recursion
872 $ignore = $this->ignoreErrors( true );
873 ++
$this->mErrorCount
;
875 if ( $ignore ||
$tempIgnore ) {
876 wfDebug( "SQL ERROR (ignored): $error\n" );
877 $this->ignoreErrors( $ignore );
879 $sql1line = str_replace( "\n", "\\n", $sql );
880 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
881 wfDebug( "SQL ERROR: " . $error . "\n" );
882 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
887 * Intended to be compatible with the PEAR::DB wrapper functions.
888 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
890 * ? = scalar value, quoted as necessary
891 * ! = raw SQL bit (a function for instance)
892 * & = filename; reads the file and inserts as a blob
893 * (we don't use this though...)
895 * This function should not be used directly by new code outside of the
896 * database classes. The query wrapper functions (select() etc.) should be
900 * @param $func string
904 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
905 /* MySQL doesn't support prepared statements (yet), so just
906 pack up the query for reference. We'll manually replace
908 return array( 'query' => $sql, 'func' => $func );
912 * Free a prepared query, generated by prepare().
914 function freePrepared( $prepared ) {
915 /* No-op by default */
919 * Execute a prepared query with the various arguments
920 * @param $prepared String: the prepared sql
921 * @param $args Mixed: Either an array here, or put scalars as varargs
923 * @return ResultWrapper
925 function execute( $prepared, $args = null ) {
926 if ( !is_array( $args ) ) {
928 $args = func_get_args();
929 array_shift( $args );
932 $sql = $this->fillPrepared( $prepared['query'], $args );
934 return $this->query( $sql, $prepared['func'] );
938 * Prepare & execute an SQL statement, quoting and inserting arguments
939 * in the appropriate places.
941 * This function should not be used directly by new code outside of the
942 * database classes. The query wrapper functions (select() etc.) should be
945 * @param $query String
948 * @return ResultWrapper
950 function safeQuery( $query, $args = null ) {
951 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
953 if ( !is_array( $args ) ) {
955 $args = func_get_args();
956 array_shift( $args );
959 $retval = $this->execute( $prepared, $args );
960 $this->freePrepared( $prepared );
966 * For faking prepared SQL statements on DBs that don't support
968 * @param $preparedQuery String: a 'preparable' SQL statement
969 * @param $args Array of arguments to fill it with
970 * @return string executable SQL
972 function fillPrepared( $preparedQuery, $args ) {
974 $this->preparedArgs
=& $args;
976 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
977 array( &$this, 'fillPreparedArg' ), $preparedQuery );
981 * preg_callback func for fillPrepared()
982 * The arguments should be in $this->preparedArgs and must not be touched
983 * while we're doing this.
985 * @param $matches Array
988 function fillPreparedArg( $matches ) {
989 switch( $matches[1] ) {
990 case '\\?': return '?';
991 case '\\!': return '!';
992 case '\\&': return '&';
995 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
997 switch( $matches[1] ) {
998 case '?': return $this->addQuotes( $arg );
999 case '!': return $arg;
1001 # return $this->addQuotes( file_get_contents( $arg ) );
1002 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1004 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1009 * Free a result object returned by query() or select(). It's usually not
1010 * necessary to call this, just use unset() or let the variable holding
1011 * the result object go out of scope.
1013 * @param $res Mixed: A SQL result
1015 function freeResult( $res ) {
1019 * Simple UPDATE wrapper.
1020 * Usually throws a DBQueryError on failure.
1021 * If errors are explicitly ignored, returns success
1023 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1024 * calling convention and feature set
1026 * @param $table string
1030 * @param $fname string
1034 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1035 $table = $this->tableName( $table );
1036 $sql = "UPDATE $table SET $var = '" .
1037 $this->strencode( $value ) . "' WHERE ($cond)";
1039 return (bool)$this->query( $sql, $fname );
1043 * A SELECT wrapper which returns a single field from a single result row.
1045 * Usually throws a DBQueryError on failure. If errors are explicitly
1046 * ignored, returns false on failure.
1048 * If no result rows are returned from the query, false is returned.
1050 * @param $table string|array Table name. See DatabaseBase::select() for details.
1051 * @param $var string The field name to select. This must be a valid SQL
1052 * fragment: do not use unvalidated user input.
1053 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1054 * @param $fname string The function name of the caller.
1055 * @param $options string|array The query options. See DatabaseBase::select() for details.
1057 * @return false|mixed The value from the field, or false on failure.
1059 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1060 $options = array() )
1062 if ( !is_array( $options ) ) {
1063 $options = array( $options );
1066 $options['LIMIT'] = 1;
1068 $res = $this->select( $table, $var, $cond, $fname, $options );
1070 if ( $res === false ||
!$this->numRows( $res ) ) {
1074 $row = $this->fetchRow( $res );
1076 if ( $row !== false ) {
1077 return reset( $row );
1084 * Returns an optional USE INDEX clause to go after the table, and a
1085 * string to go at the end of the query.
1087 * @param $options Array: associative array of options to be turned into
1088 * an SQL query, valid keys are listed in the function.
1090 * @see DatabaseBase::select()
1092 function makeSelectOptions( $options ) {
1093 $preLimitTail = $postLimitTail = '';
1096 $noKeyOptions = array();
1098 foreach ( $options as $key => $option ) {
1099 if ( is_numeric( $key ) ) {
1100 $noKeyOptions[$option] = true;
1104 if ( isset( $options['GROUP BY'] ) ) {
1105 $gb = is_array( $options['GROUP BY'] )
1106 ?
implode( ',', $options['GROUP BY'] )
1107 : $options['GROUP BY'];
1108 $preLimitTail .= " GROUP BY {$gb}";
1111 if ( isset( $options['HAVING'] ) ) {
1112 $preLimitTail .= " HAVING {$options['HAVING']}";
1115 if ( isset( $options['ORDER BY'] ) ) {
1116 $ob = is_array( $options['ORDER BY'] )
1117 ?
implode( ',', $options['ORDER BY'] )
1118 : $options['ORDER BY'];
1119 $preLimitTail .= " ORDER BY {$ob}";
1122 // if (isset($options['LIMIT'])) {
1123 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1124 // isset($options['OFFSET']) ? $options['OFFSET']
1128 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1129 $postLimitTail .= ' FOR UPDATE';
1132 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1133 $postLimitTail .= ' LOCK IN SHARE MODE';
1136 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1137 $startOpts .= 'DISTINCT';
1140 # Various MySQL extensions
1141 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1142 $startOpts .= ' /*! STRAIGHT_JOIN */';
1145 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1146 $startOpts .= ' HIGH_PRIORITY';
1149 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1150 $startOpts .= ' SQL_BIG_RESULT';
1153 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1154 $startOpts .= ' SQL_BUFFER_RESULT';
1157 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1158 $startOpts .= ' SQL_SMALL_RESULT';
1161 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1162 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1165 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1166 $startOpts .= ' SQL_CACHE';
1169 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1170 $startOpts .= ' SQL_NO_CACHE';
1173 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1174 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1179 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1183 * Execute a SELECT query constructed using the various parameters provided.
1184 * See below for full details of the parameters.
1186 * @param $table String|Array Table name
1187 * @param $vars String|Array Field names
1188 * @param $conds String|Array Conditions
1189 * @param $fname String Caller function name
1190 * @param $options Array Query options
1191 * @param $join_conds Array Join conditions
1193 * @param $table string|array
1195 * May be either an array of table names, or a single string holding a table
1196 * name. If an array is given, table aliases can be specified, for example:
1198 * array( 'a' => 'user' )
1200 * This includes the user table in the query, with the alias "a" available
1201 * for use in field names (e.g. a.user_name).
1203 * All of the table names given here are automatically run through
1204 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1205 * added, and various other table name mappings to be performed.
1208 * @param $vars string|array
1210 * May be either a field name or an array of field names. The field names
1211 * here are complete fragments of SQL, for direct inclusion into the SELECT
1212 * query. Expressions and aliases may be specified as in SQL, for example:
1214 * array( 'MAX(rev_id) AS maxrev' )
1216 * If an expression is given, care must be taken to ensure that it is
1220 * @param $conds string|array
1222 * May be either a string containing a single condition, or an array of
1223 * conditions. If an array is given, the conditions constructed from each
1224 * element are combined with AND.
1226 * Array elements may take one of two forms:
1228 * - Elements with a numeric key are interpreted as raw SQL fragments.
1229 * - Elements with a string key are interpreted as equality conditions,
1230 * where the key is the field name.
1231 * - If the value of such an array element is a scalar (such as a
1232 * string), it will be treated as data and thus quoted appropriately.
1233 * If it is null, an IS NULL clause will be added.
1234 * - If the value is an array, an IN(...) clause will be constructed,
1235 * such that the field name may match any of the elements in the
1236 * array. The elements of the array will be quoted.
1237 * - If the field name ends with "!", this is taken as a flag which
1238 * inverts the comparison, allowing NOT IN clauses to be constructed,
1239 * for example: array( 'user_id!' => array( 1, 2, 3 ) )
1241 * Note that expressions are often DBMS-dependent in their syntax.
1242 * DBMS-independent wrappers are provided for constructing several types of
1243 * expression commonly used in condition queries. See:
1244 * - DatabaseBase::buildLike()
1245 * - DatabaseBase::conditional()
1248 * @param $options string|array
1250 * Optional: Array of query options. Boolean options are specified by
1251 * including them in the array as a string value with a numeric key, for
1254 * array( 'FOR UPDATE' )
1256 * The supported options are:
1258 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1259 * with LIMIT can theoretically be used for paging through a result set,
1260 * but this is discouraged in MediaWiki for performance reasons.
1262 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1263 * and then the first rows are taken until the limit is reached. LIMIT
1264 * is applied to a result set after OFFSET.
1266 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1267 * changed until the next COMMIT.
1269 * - DISTINCT: Boolean: return only unique result rows.
1271 * - GROUP BY: May be either an SQL fragment string naming a field or
1272 * expression to group by, or an array of such SQL fragments.
1274 * - HAVING: A string containing a HAVING clause.
1276 * - ORDER BY: May be either an SQL fragment giving a field name or
1277 * expression to order by, or an array of such SQL fragments.
1279 * - USE INDEX: This may be either a string giving the index name to use
1280 * for the query, or an array. If it is an associative array, each key
1281 * gives the table name (or alias), each value gives the index name to
1282 * use for that table. All strings are SQL fragments and so should be
1283 * validated by the caller.
1285 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1286 * instead of SELECT.
1288 * And also the following boolean MySQL extensions, see the MySQL manual
1289 * for documentation:
1291 * - LOCK IN SHARE MODE
1295 * - SQL_BUFFER_RESULT
1296 * - SQL_SMALL_RESULT
1297 * - SQL_CALC_FOUND_ROWS
1302 * @param $join_conds string|array
1304 * Optional associative array of table-specific join conditions. In the
1305 * most common case, this is unnecessary, since the join condition can be
1306 * in $conds. However, it is useful for doing a LEFT JOIN.
1308 * The key of the array contains the table name or alias. The value is an
1309 * array with two elements, numbered 0 and 1. The first gives the type of
1310 * join, the second is an SQL fragment giving the join condition for that
1311 * table. For example:
1313 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1315 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1316 * with no rows in it will be returned. If there was a query error, a
1317 * DBQueryError exception will be thrown, except if the "ignore errors"
1318 * option was set, in which case false will be returned.
1320 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1321 $options = array(), $join_conds = array() ) {
1322 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1324 return $this->query( $sql, $fname );
1328 * The equivalent of DatabaseBase::select() except that the constructed SQL
1329 * is returned, instead of being immediately executed.
1331 * @param $table string|array Table name
1332 * @param $vars string|array Field names
1333 * @param $conds string|array Conditions
1334 * @param $fname string Caller function name
1335 * @param $options string|array Query options
1336 * @param $join_conds string|array Join conditions
1338 * @return SQL query string.
1339 * @see DatabaseBase::select()
1341 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1342 if ( is_array( $vars ) ) {
1343 $vars = implode( ',', $vars );
1346 $options = (array)$options;
1348 if ( is_array( $table ) ) {
1349 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1350 ?
$options['USE INDEX']
1352 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1354 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1356 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1358 } elseif ( $table != '' ) {
1359 if ( $table { 0 } == ' ' ) {
1360 $from = ' FROM ' . $table;
1362 $from = ' FROM ' . $this->tableName( $table );
1368 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1370 if ( !empty( $conds ) ) {
1371 if ( is_array( $conds ) ) {
1372 $conds = $this->makeList( $conds, LIST_AND
);
1374 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1376 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1379 if ( isset( $options['LIMIT'] ) ) {
1380 $sql = $this->limitResult( $sql, $options['LIMIT'],
1381 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1383 $sql = "$sql $postLimitTail";
1385 if ( isset( $options['EXPLAIN'] ) ) {
1386 $sql = 'EXPLAIN ' . $sql;
1393 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1394 * that a single row object is returned. If the query returns no rows,
1395 * false is returned.
1397 * @param $table string|array Table name
1398 * @param $vars string|array Field names
1399 * @param $conds|array Conditions
1400 * @param $fname string Caller function name
1401 * @param $options string|array Query options
1402 * @param $join_conds array|string Join conditions
1404 * @return ResultWrapper|bool
1406 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1407 $options = array(), $join_conds = array() )
1409 $options['LIMIT'] = 1;
1410 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1412 if ( $res === false ) {
1416 if ( !$this->numRows( $res ) ) {
1420 $obj = $this->fetchObject( $res );
1426 * Estimate rows in dataset.
1428 * MySQL allows you to estimate the number of rows that would be returned
1429 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1430 * index cardinality statistics, and is notoriously inaccurate, especially
1431 * when large numbers of rows have recently been added or deleted.
1433 * For DBMSs that don't support fast result size estimation, this function
1434 * will actually perform the SELECT COUNT(*).
1436 * Takes the same arguments as DatabaseBase::select().
1438 * @param $table String: table name
1439 * @param Array|string $vars : unused
1440 * @param Array|string $conds : filters on the table
1441 * @param $fname String: function name for profiling
1442 * @param $options Array: options for select
1443 * @return Integer: row count
1445 public function estimateRowCount( $table, $vars = '*', $conds = '',
1446 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1449 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1452 $row = $this->fetchRow( $res );
1453 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1460 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1461 * It's only slightly flawed. Don't use for anything important.
1463 * @param $sql String A SQL Query
1467 static function generalizeSQL( $sql ) {
1468 # This does the same as the regexp below would do, but in such a way
1469 # as to avoid crashing php on some large strings.
1470 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1472 $sql = str_replace ( "\\\\", '', $sql );
1473 $sql = str_replace ( "\\'", '', $sql );
1474 $sql = str_replace ( "\\\"", '', $sql );
1475 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1476 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1478 # All newlines, tabs, etc replaced by single space
1479 $sql = preg_replace ( '/\s+/', ' ', $sql );
1482 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1488 * Determines whether a field exists in a table
1490 * @param $table String: table name
1491 * @param $field String: filed to check on that table
1492 * @param $fname String: calling function name (optional)
1493 * @return Boolean: whether $table has filed $field
1495 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1496 $info = $this->fieldInfo( $table, $field );
1502 * Determines whether an index exists
1503 * Usually throws a DBQueryError on failure
1504 * If errors are explicitly ignored, returns NULL on failure
1508 * @param $fname string
1512 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1513 $info = $this->indexInfo( $table, $index, $fname );
1514 if ( is_null( $info ) ) {
1517 return $info !== false;
1522 * Query whether a given table exists
1524 * @param $table string
1528 function tableExists( $table ) {
1529 $table = $this->tableName( $table );
1530 $old = $this->ignoreErrors( true );
1531 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1532 $this->ignoreErrors( $old );
1539 * mysql_field_type() wrapper
1541 function fieldType( $res, $index ) {
1542 if ( $res instanceof ResultWrapper
) {
1543 $res = $res->result
;
1546 return mysql_field_type( $res, $index );
1550 * Determines if a given index is unique
1552 * @param $table string
1553 * @param $index string
1557 function indexUnique( $table, $index ) {
1558 $indexInfo = $this->indexInfo( $table, $index );
1560 if ( !$indexInfo ) {
1564 return !$indexInfo[0]->Non_unique
;
1568 * Helper for DatabaseBase::insert().
1570 * @param $options array
1573 function makeInsertOptions( $options ) {
1574 return implode( ' ', $options );
1578 * INSERT wrapper, inserts an array into a table.
1582 * - A single associative array. The array keys are the field names, and
1583 * the values are the values to insert. The values are treated as data
1584 * and will be quoted appropriately. If NULL is inserted, this will be
1585 * converted to a database NULL.
1586 * - An array with numeric keys, holding a list of associative arrays.
1587 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1588 * each subarray must be identical to each other, and in the same order.
1590 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1593 * $options is an array of options, with boolean options encoded as values
1594 * with numeric keys, in the same style as $options in
1595 * DatabaseBase::select(). Supported options are:
1597 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1598 * any rows which cause duplicate key errors are not inserted. It's
1599 * possible to determine how many rows were successfully inserted using
1600 * DatabaseBase::affectedRows().
1602 * @param $table String Table name. This will be passed through
1603 * DatabaseBase::tableName().
1604 * @param $a Array of rows to insert
1605 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1606 * @param $options Array of options
1610 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1611 # No rows to insert, easy just return now
1612 if ( !count( $a ) ) {
1616 $table = $this->tableName( $table );
1618 if ( !is_array( $options ) ) {
1619 $options = array( $options );
1622 $options = $this->makeInsertOptions( $options );
1624 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1626 $keys = array_keys( $a[0] );
1629 $keys = array_keys( $a );
1632 $sql = 'INSERT ' . $options .
1633 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1637 foreach ( $a as $row ) {
1643 $sql .= '(' . $this->makeList( $row ) . ')';
1646 $sql .= '(' . $this->makeList( $a ) . ')';
1649 return (bool)$this->query( $sql, $fname );
1653 * Make UPDATE options for the DatabaseBase::update function
1655 * @param $options Array: The options passed to DatabaseBase::update
1658 function makeUpdateOptions( $options ) {
1659 if ( !is_array( $options ) ) {
1660 $options = array( $options );
1665 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1666 $opts[] = $this->lowPriorityOption();
1669 if ( in_array( 'IGNORE', $options ) ) {
1673 return implode( ' ', $opts );
1677 * UPDATE wrapper. Takes a condition array and a SET array.
1679 * @param $table String name of the table to UPDATE. This will be passed through
1680 * DatabaseBase::tableName().
1682 * @param $values Array: An array of values to SET. For each array element,
1683 * the key gives the field name, and the value gives the data
1684 * to set that field to. The data will be quoted by
1685 * DatabaseBase::addQuotes().
1687 * @param $conds Array: An array of conditions (WHERE). See
1688 * DatabaseBase::select() for the details of the format of
1689 * condition arrays. Use '*' to update all rows.
1691 * @param $fname String: The function name of the caller (from __METHOD__),
1692 * for logging and profiling.
1694 * @param $options Array: An array of UPDATE options, can be:
1695 * - IGNORE: Ignore unique key conflicts
1696 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1699 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1700 $table = $this->tableName( $table );
1701 $opts = $this->makeUpdateOptions( $options );
1702 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1704 if ( $conds !== array() && $conds !== '*' ) {
1705 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1708 return $this->query( $sql, $fname );
1712 * Makes an encoded list of strings from an array
1713 * @param $a Array containing the data
1714 * @param $mode int Constant
1715 * - LIST_COMMA: comma separated, no field names
1716 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1717 * the documentation for $conds in DatabaseBase::select().
1718 * - LIST_OR: ORed WHERE clause (without the WHERE)
1719 * - LIST_SET: comma separated with field names, like a SET clause
1720 * - LIST_NAMES: comma separated field names
1724 function makeList( $a, $mode = LIST_COMMA
) {
1725 if ( !is_array( $a ) ) {
1726 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1732 foreach ( $a as $field => $value ) {
1734 if ( $mode == LIST_AND
) {
1736 } elseif ( $mode == LIST_OR
) {
1745 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1746 $list .= "($value)";
1747 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1749 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1750 if ( count( $value ) == 0 ) {
1751 throw new MWException( __METHOD__
. ': empty input' );
1752 } elseif ( count( $value ) == 1 ) {
1753 // Special-case single values, as IN isn't terribly efficient
1754 // Don't necessarily assume the single key is 0; we don't
1755 // enforce linear numeric ordering on other arrays here.
1756 $value = array_values( $value );
1757 $list .= $field . " = " . $this->addQuotes( $value[0] );
1759 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1761 } elseif ( $value === null ) {
1762 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1763 $list .= "$field IS ";
1764 } elseif ( $mode == LIST_SET
) {
1765 $list .= "$field = ";
1769 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1770 $list .= "$field = ";
1772 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1780 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1781 * The keys on each level may be either integers or strings.
1783 * @param $data Array: organized as 2-d
1784 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1785 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1786 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1787 * @return Mixed: string SQL fragment, or false if no items in array.
1789 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1792 foreach ( $data as $base => $sub ) {
1793 if ( count( $sub ) ) {
1794 $conds[] = $this->makeList(
1795 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1801 return $this->makeList( $conds, LIST_OR
);
1803 // Nothing to search for...
1809 * Build a partial where clause from a 3-d array
1810 * The keys on each level may be either integers or strings.
1812 * @param $data Array: organized as 3-d array(baseKeyVal => array(middleKeyVal => array(subKeyVal => <ignored>, ...), ...), ...)
1813 * @param $baseKey String: field name to match the base-level keys to (eg 'gtl_to_prefix')
1814 * @param $middleKey String: field name to match the middle-level keys to (eg 'gtl_to_namespace')
1815 * @param $subKey String: field name to match the sub-level keys to (eg 'gtl_to_title')
1816 * @return Mixed: string SQL fragment, or false if no items in array.
1818 function makeWhereFrom3d( $data, $baseKey, $middleKey, $subKey ) {
1820 foreach ( $data as $base => $subdata ) {
1821 foreach ( $subdata as $middle => $sub ) {
1822 if ( count( $sub ) ) {
1823 $conds[] = $this->makeList(
1824 array( $baseKey => $base,
1825 $middleKey => $middle,
1826 $subKey => array_keys( $sub ) ),
1834 return $this->makeList( $conds, LIST_OR
);
1836 // Nothing to search for...
1842 * Bitwise operations
1849 function bitNot( $field ) {
1855 * @param $fieldRight
1858 function bitAnd( $fieldLeft, $fieldRight ) {
1859 return "($fieldLeft & $fieldRight)";
1864 * @param $fieldRight
1867 function bitOr( $fieldLeft, $fieldRight ) {
1868 return "($fieldLeft | $fieldRight)";
1872 * Change the current database
1874 * @todo Explain what exactly will fail if this is not overridden.
1878 * @return bool Success or failure
1880 function selectDB( $db ) {
1881 # Stub. Shouldn't cause serious problems if it's not overridden, but
1882 # if your database engine supports a concept similar to MySQL's
1883 # databases you may as well.
1884 $this->mDBname
= $db;
1889 * Get the current DB name
1891 function getDBname() {
1892 return $this->mDBname
;
1896 * Get the server hostname or IP address
1898 function getServer() {
1899 return $this->mServer
;
1903 * Format a table name ready for use in constructing an SQL query
1905 * This does two important things: it quotes the table names to clean them up,
1906 * and it adds a table prefix if only given a table name with no quotes.
1908 * All functions of this object which require a table name call this function
1909 * themselves. Pass the canonical name to such functions. This is only needed
1910 * when calling query() directly.
1912 * @param $name String: database table name
1913 * @param $format String One of:
1914 * quoted - Automatically pass the table name through addIdentifierQuotes()
1915 * so that it can be used in a query.
1916 * raw - Do not add identifier quotes to the table name
1917 * @return String: full database name
1919 function tableName( $name, $format = 'quoted' ) {
1920 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1921 # Skip the entire process when we have a string quoted on both ends.
1922 # Note that we check the end so that we will still quote any use of
1923 # use of `database`.table. But won't break things if someone wants
1924 # to query a database table with a dot in the name.
1925 if ( $this->isQuotedIdentifier( $name ) ) {
1929 # Lets test for any bits of text that should never show up in a table
1930 # name. Basically anything like JOIN or ON which are actually part of
1931 # SQL queries, but may end up inside of the table value to combine
1932 # sql. Such as how the API is doing.
1933 # Note that we use a whitespace test rather than a \b test to avoid
1934 # any remote case where a word like on may be inside of a table name
1935 # surrounded by symbols which may be considered word breaks.
1936 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1940 # Split database and table into proper variables.
1941 # We reverse the explode so that database.table and table both output
1942 # the correct table.
1943 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1944 if ( isset( $dbDetails[1] ) ) {
1945 list( $table, $database ) = $dbDetails;
1947 list( $table ) = $dbDetails;
1949 $prefix = $this->mTablePrefix
; # Default prefix
1951 # A database name has been specified in input. We don't want any
1953 if ( isset( $database ) ) {
1957 # Note that we use the long format because php will complain in in_array if
1958 # the input is not an array, and will complain in is_array if it is not set.
1959 if ( !isset( $database ) # Don't use shared database if pre selected.
1960 && isset( $wgSharedDB ) # We have a shared database
1961 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1962 && isset( $wgSharedTables )
1963 && is_array( $wgSharedTables )
1964 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1965 $database = $wgSharedDB;
1966 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1969 # Quote the $database and $table and apply the prefix if not quoted.
1970 if ( isset( $database ) ) {
1971 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1974 $table = "{$prefix}{$table}";
1975 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1976 $table = $this->addIdentifierQuotes( "{$table}" );
1979 # Merge our database and table into our final table name.
1980 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1986 * Fetch a number of table names into an array
1987 * This is handy when you need to construct SQL for joins
1990 * extract($dbr->tableNames('user','watchlist'));
1991 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1992 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1996 public function tableNames() {
1997 $inArray = func_get_args();
2000 foreach ( $inArray as $name ) {
2001 $retVal[$name] = $this->tableName( $name );
2008 * Fetch a number of table names into an zero-indexed numerical array
2009 * This is handy when you need to construct SQL for joins
2012 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2013 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2014 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2018 public function tableNamesN() {
2019 $inArray = func_get_args();
2022 foreach ( $inArray as $name ) {
2023 $retVal[] = $this->tableName( $name );
2030 * Get an aliased table name
2031 * e.g. tableName AS newTableName
2033 * @param $name string Table name, see tableName()
2034 * @param $alias string|bool Alias (optional)
2035 * @return string SQL name for aliased table. Will not alias a table to its own name
2037 public function tableNameWithAlias( $name, $alias = false ) {
2038 if ( !$alias ||
$alias == $name ) {
2039 return $this->tableName( $name );
2041 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2046 * Gets an array of aliased table names
2048 * @param $tables array( [alias] => table )
2049 * @return array of strings, see tableNameWithAlias()
2051 public function tableNamesWithAlias( $tables ) {
2053 foreach ( $tables as $alias => $table ) {
2054 if ( is_numeric( $alias ) ) {
2057 $retval[] = $this->tableNameWithAlias( $table, $alias );
2063 * Get the aliased table name clause for a FROM clause
2064 * which might have a JOIN and/or USE INDEX clause
2066 * @param $tables array ( [alias] => table )
2067 * @param $use_index array Same as for select()
2068 * @param $join_conds array Same as for select()
2071 protected function tableNamesWithUseIndexOrJOIN(
2072 $tables, $use_index = array(), $join_conds = array()
2076 $use_index = (array)$use_index;
2077 $join_conds = (array)$join_conds;
2079 foreach ( $tables as $alias => $table ) {
2080 if ( !is_string( $alias ) ) {
2081 // No alias? Set it equal to the table name
2084 // Is there a JOIN clause for this table?
2085 if ( isset( $join_conds[$alias] ) ) {
2086 list( $joinType, $conds ) = $join_conds[$alias];
2087 $tableClause = $joinType;
2088 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2089 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2090 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2092 $tableClause .= ' ' . $use;
2095 $on = $this->makeList( (array)$conds, LIST_AND
);
2097 $tableClause .= ' ON (' . $on . ')';
2100 $retJOIN[] = $tableClause;
2101 // Is there an INDEX clause for this table?
2102 } elseif ( isset( $use_index[$alias] ) ) {
2103 $tableClause = $this->tableNameWithAlias( $table, $alias );
2104 $tableClause .= ' ' . $this->useIndexClause(
2105 implode( ',', (array)$use_index[$alias] ) );
2107 $ret[] = $tableClause;
2109 $tableClause = $this->tableNameWithAlias( $table, $alias );
2111 $ret[] = $tableClause;
2115 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2116 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2117 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2119 // Compile our final table clause
2120 return implode( ' ', array( $straightJoins, $otherJoins ) );
2124 * Get the name of an index in a given table
2130 function indexName( $index ) {
2131 // Backwards-compatibility hack
2133 'ar_usertext_timestamp' => 'usertext_timestamp',
2134 'un_user_id' => 'user_id',
2135 'un_user_ip' => 'user_ip',
2138 if ( isset( $renamed[$index] ) ) {
2139 return $renamed[$index];
2146 * If it's a string, adds quotes and backslashes
2147 * Otherwise returns as-is
2153 function addQuotes( $s ) {
2154 if ( $s === null ) {
2157 # This will also quote numeric values. This should be harmless,
2158 # and protects against weird problems that occur when they really
2159 # _are_ strings such as article titles and string->number->string
2160 # conversion is not 1:1.
2161 return "'" . $this->strencode( $s ) . "'";
2166 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2167 * MySQL uses `backticks` while basically everything else uses double quotes.
2168 * Since MySQL is the odd one out here the double quotes are our generic
2169 * and we implement backticks in DatabaseMysql.
2175 public function addIdentifierQuotes( $s ) {
2176 return '"' . str_replace( '"', '""', $s ) . '"';
2180 * Returns if the given identifier looks quoted or not according to
2181 * the database convention for quoting identifiers .
2183 * @param $name string
2187 public function isQuotedIdentifier( $name ) {
2188 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2192 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2193 * which used quote_ident which does not follow our naming conventions
2194 * was renamed to addIdentifierQuotes.
2195 * @deprecated since 1.18 use addIdentifierQuotes
2201 function quote_ident( $s ) {
2202 wfDeprecated( __METHOD__
);
2203 return $this->addIdentifierQuotes( $s );
2207 * Escape string for safe LIKE usage.
2208 * WARNING: you should almost never use this function directly,
2209 * instead use buildLike() that escapes everything automatically
2210 * @deprecated since 1.17, warnings in 1.17, removed in ???
2216 public function escapeLike( $s ) {
2217 wfDeprecated( __METHOD__
);
2218 return $this->escapeLikeInternal( $s );
2225 protected function escapeLikeInternal( $s ) {
2226 $s = str_replace( '\\', '\\\\', $s );
2227 $s = $this->strencode( $s );
2228 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2234 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2235 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2236 * Alternatively, the function could be provided with an array of aforementioned parameters.
2238 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2239 * for subpages of 'My page title'.
2240 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2243 * @return String: fully built LIKE statement
2245 function buildLike() {
2246 $params = func_get_args();
2248 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2249 $params = $params[0];
2254 foreach ( $params as $value ) {
2255 if ( $value instanceof LikeMatch
) {
2256 $s .= $value->toString();
2258 $s .= $this->escapeLikeInternal( $value );
2262 return " LIKE '" . $s . "' ";
2266 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2270 function anyChar() {
2271 return new LikeMatch( '_' );
2275 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2279 function anyString() {
2280 return new LikeMatch( '%' );
2284 * Returns an appropriately quoted sequence value for inserting a new row.
2285 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2286 * subclass will return an integer, and save the value for insertId()
2288 function nextSequenceValue( $seqName ) {
2293 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2294 * is only needed because a) MySQL must be as efficient as possible due to
2295 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2296 * which index to pick. Anyway, other databases might have different
2297 * indexes on a given table. So don't bother overriding this unless you're
2300 function useIndexClause( $index ) {
2305 * REPLACE query wrapper.
2307 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2308 * except that when there is a duplicate key error, the old row is deleted
2309 * and the new row is inserted in its place.
2311 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2312 * perform the delete, we need to know what the unique indexes are so that
2313 * we know how to find the conflicting rows.
2315 * It may be more efficient to leave off unique indexes which are unlikely
2316 * to collide. However if you do this, you run the risk of encountering
2317 * errors which wouldn't have occurred in MySQL.
2319 * @param $table String: The table to replace the row(s) in.
2320 * @param $rows array Can be either a single row to insert, or multiple rows,
2321 * in the same format as for DatabaseBase::insert()
2322 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2323 * a field name or an array of field names
2324 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2326 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2327 $quotedTable = $this->tableName( $table );
2329 if ( count( $rows ) == 0 ) {
2334 if ( !is_array( reset( $rows ) ) ) {
2335 $rows = array( $rows );
2338 foreach( $rows as $row ) {
2339 # Delete rows which collide
2340 if ( $uniqueIndexes ) {
2341 $sql = "DELETE FROM $quotedTable WHERE ";
2343 foreach ( $uniqueIndexes as $index ) {
2350 if ( is_array( $index ) ) {
2352 foreach ( $index as $col ) {
2358 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2361 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2365 $this->query( $sql, $fname );
2368 # Now insert the row
2369 $this->insert( $table, $row );
2374 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2377 * @param $table Table name
2378 * @param $rows Rows to insert
2379 * @param $fname Caller function name
2381 * @return ResultWrapper
2383 protected function nativeReplace( $table, $rows, $fname ) {
2384 $table = $this->tableName( $table );
2387 if ( !is_array( reset( $rows ) ) ) {
2388 $rows = array( $rows );
2391 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2394 foreach ( $rows as $row ) {
2401 $sql .= '(' . $this->makeList( $row ) . ')';
2404 return $this->query( $sql, $fname );
2408 * DELETE where the condition is a join.
2410 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2411 * we use sub-selects
2413 * For safety, an empty $conds will not delete everything. If you want to
2414 * delete all rows where the join condition matches, set $conds='*'.
2416 * DO NOT put the join condition in $conds.
2418 * @param $delTable String: The table to delete from.
2419 * @param $joinTable String: The other table.
2420 * @param $delVar String: The variable to join on, in the first table.
2421 * @param $joinVar String: The variable to join on, in the second table.
2422 * @param $conds Array: Condition array of field names mapped to variables,
2423 * ANDed together in the WHERE clause
2424 * @param $fname String: Calling function name (use __METHOD__) for
2427 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2428 $fname = 'DatabaseBase::deleteJoin' )
2431 throw new DBUnexpectedError( $this,
2432 'DatabaseBase::deleteJoin() called with empty $conds' );
2435 $delTable = $this->tableName( $delTable );
2436 $joinTable = $this->tableName( $joinTable );
2437 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2438 if ( $conds != '*' ) {
2439 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2443 $this->query( $sql, $fname );
2447 * Returns the size of a text field, or -1 for "unlimited"
2449 * @param $table string
2450 * @param $field string
2454 function textFieldSize( $table, $field ) {
2455 $table = $this->tableName( $table );
2456 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2457 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2458 $row = $this->fetchObject( $res );
2462 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2472 * A string to insert into queries to show that they're low-priority, like
2473 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2474 * string and nothing bad should happen.
2476 * @return string Returns the text of the low priority option if it is
2477 * supported, or a blank string otherwise
2479 function lowPriorityOption() {
2484 * DELETE query wrapper.
2486 * @param $table Array Table name
2487 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2488 * the format. Use $conds == "*" to delete all rows
2489 * @param $fname String name of the calling function
2493 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2495 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2498 $table = $this->tableName( $table );
2499 $sql = "DELETE FROM $table";
2501 if ( $conds != '*' ) {
2502 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2505 return $this->query( $sql, $fname );
2509 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2510 * into another table.
2512 * @param $destTable string The table name to insert into
2513 * @param $srcTable string|array May be either a table name, or an array of table names
2514 * to include in a join.
2516 * @param $varMap array must be an associative array of the form
2517 * array( 'dest1' => 'source1', ...). Source items may be literals
2518 * rather than field names, but strings should be quoted with
2519 * DatabaseBase::addQuotes()
2521 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2522 * the details of the format of condition arrays. May be "*" to copy the
2525 * @param $fname string The function name of the caller, from __METHOD__
2527 * @param $insertOptions array Options for the INSERT part of the query, see
2528 * DatabaseBase::insert() for details.
2529 * @param $selectOptions array Options for the SELECT part of the query, see
2530 * DatabaseBase::select() for details.
2532 * @return ResultWrapper
2534 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2535 $fname = 'DatabaseBase::insertSelect',
2536 $insertOptions = array(), $selectOptions = array() )
2538 $destTable = $this->tableName( $destTable );
2540 if ( is_array( $insertOptions ) ) {
2541 $insertOptions = implode( ' ', $insertOptions );
2544 if ( !is_array( $selectOptions ) ) {
2545 $selectOptions = array( $selectOptions );
2548 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2550 if ( is_array( $srcTable ) ) {
2551 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2553 $srcTable = $this->tableName( $srcTable );
2556 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2557 " SELECT $startOpts " . implode( ',', $varMap ) .
2558 " FROM $srcTable $useIndex ";
2560 if ( $conds != '*' ) {
2561 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2564 $sql .= " $tailOpts";
2566 return $this->query( $sql, $fname );
2570 * Construct a LIMIT query with optional offset. This is used for query
2571 * pages. The SQL should be adjusted so that only the first $limit rows
2572 * are returned. If $offset is provided as well, then the first $offset
2573 * rows should be discarded, and the next $limit rows should be returned.
2574 * If the result of the query is not ordered, then the rows to be returned
2575 * are theoretically arbitrary.
2577 * $sql is expected to be a SELECT, if that makes a difference. For
2578 * UPDATE, limitResultForUpdate should be used.
2580 * The version provided by default works in MySQL and SQLite. It will very
2581 * likely need to be overridden for most other DBMSes.
2583 * @param $sql String SQL query we will append the limit too
2584 * @param $limit Integer the SQL limit
2585 * @param $offset Integer|false the SQL offset (default false)
2589 function limitResult( $sql, $limit, $offset = false ) {
2590 if ( !is_numeric( $limit ) ) {
2591 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2594 return "$sql LIMIT "
2595 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2604 function limitResultForUpdate( $sql, $num ) {
2605 return $this->limitResult( $sql, $num, 0 );
2609 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2610 * within the UNION construct.
2613 function unionSupportsOrderAndLimit() {
2614 return true; // True for almost every DB supported
2618 * Construct a UNION query
2619 * This is used for providing overload point for other DB abstractions
2620 * not compatible with the MySQL syntax.
2621 * @param $sqls Array: SQL statements to combine
2622 * @param $all Boolean: use UNION ALL
2623 * @return String: SQL fragment
2625 function unionQueries( $sqls, $all ) {
2626 $glue = $all ?
') UNION ALL (' : ') UNION (';
2627 return '(' . implode( $glue, $sqls ) . ')';
2631 * Returns an SQL expression for a simple conditional. This doesn't need
2632 * to be overridden unless CASE isn't supported in your DBMS.
2634 * @param $cond String: SQL expression which will result in a boolean value
2635 * @param $trueVal String: SQL expression to return if true
2636 * @param $falseVal String: SQL expression to return if false
2637 * @return String: SQL fragment
2639 function conditional( $cond, $trueVal, $falseVal ) {
2640 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2644 * Returns a comand for str_replace function in SQL query.
2645 * Uses REPLACE() in MySQL
2647 * @param $orig String: column to modify
2648 * @param $old String: column to seek
2649 * @param $new String: column to replace with
2653 function strreplace( $orig, $old, $new ) {
2654 return "REPLACE({$orig}, {$old}, {$new})";
2658 * Determines if the last failure was due to a deadlock
2663 function wasDeadlock() {
2668 * Determines if the last query error was something that should be dealt
2669 * with by pinging the connection and reissuing the query.
2674 function wasErrorReissuable() {
2679 * Determines if the last failure was due to the database being read-only.
2684 function wasReadOnlyError() {
2689 * Perform a deadlock-prone transaction.
2691 * This function invokes a callback function to perform a set of write
2692 * queries. If a deadlock occurs during the processing, the transaction
2693 * will be rolled back and the callback function will be called again.
2696 * $dbw->deadlockLoop( callback, ... );
2698 * Extra arguments are passed through to the specified callback function.
2700 * Returns whatever the callback function returned on its successful,
2701 * iteration, or false on error, for example if the retry limit was
2706 function deadlockLoop() {
2707 $myFname = 'DatabaseBase::deadlockLoop';
2710 $args = func_get_args();
2711 $function = array_shift( $args );
2712 $oldIgnore = $this->ignoreErrors( true );
2713 $tries = DEADLOCK_TRIES
;
2715 if ( is_array( $function ) ) {
2716 $fname = $function[0];
2722 $retVal = call_user_func_array( $function, $args );
2723 $error = $this->lastError();
2724 $errno = $this->lastErrno();
2725 $sql = $this->lastQuery();
2728 if ( $this->wasDeadlock() ) {
2730 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2732 $this->reportQueryError( $error, $errno, $sql, $fname );
2735 } while ( $this->wasDeadlock() && --$tries > 0 );
2737 $this->ignoreErrors( $oldIgnore );
2739 if ( $tries <= 0 ) {
2740 $this->rollback( $myFname );
2741 $this->reportQueryError( $error, $errno, $sql, $fname );
2744 $this->commit( $myFname );
2750 * Wait for the slave to catch up to a given master position.
2752 * @param $pos DBMasterPos object
2753 * @param $timeout Integer: the maximum number of seconds to wait for
2756 * @return An integer: zero if the slave was past that position already,
2757 * greater than zero if we waited for some period of time, less than
2758 * zero if we timed out.
2760 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2761 $fname = 'DatabaseBase::masterPosWait';
2762 wfProfileIn( $fname );
2764 if ( !is_null( $this->mFakeSlaveLag
) ) {
2765 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2767 if ( $wait > $timeout * 1e6
) {
2768 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2769 wfProfileOut( $fname );
2771 } elseif ( $wait > 0 ) {
2772 wfDebug( "Fake slave waiting $wait us\n" );
2774 wfProfileOut( $fname );
2777 wfDebug( "Fake slave up to date ($wait us)\n" );
2778 wfProfileOut( $fname );
2783 wfProfileOut( $fname );
2785 # Real waits are implemented in the subclass.
2790 * Get the replication position of this slave
2792 * @return DBMasterPos, or false if this is not a slave.
2794 function getSlavePos() {
2795 if ( !is_null( $this->mFakeSlaveLag
) ) {
2796 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2797 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2806 * Get the position of this master
2808 * @return DBMasterPos, or false if this is not a master
2810 function getMasterPos() {
2811 if ( $this->mFakeMaster
) {
2812 return new MySQLMasterPos( 'fake', microtime( true ) );
2819 * Begin a transaction, committing any previously open transaction
2821 * @param $fname string
2823 function begin( $fname = 'DatabaseBase::begin' ) {
2824 $this->query( 'BEGIN', $fname );
2825 $this->mTrxLevel
= 1;
2831 * @param $fname string
2833 function commit( $fname = 'DatabaseBase::commit' ) {
2834 if ( $this->mTrxLevel
) {
2835 $this->query( 'COMMIT', $fname );
2836 $this->mTrxLevel
= 0;
2841 * Rollback a transaction.
2842 * No-op on non-transactional databases.
2844 * @param $fname string
2846 function rollback( $fname = 'DatabaseBase::rollback' ) {
2847 if ( $this->mTrxLevel
) {
2848 $this->query( 'ROLLBACK', $fname, true );
2849 $this->mTrxLevel
= 0;
2854 * Creates a new table with structure copied from existing table
2855 * Note that unlike most database abstraction functions, this function does not
2856 * automatically append database prefix, because it works at a lower
2857 * abstraction level.
2858 * The table names passed to this function shall not be quoted (this
2859 * function calls addIdentifierQuotes when needed).
2861 * @param $oldName String: name of table whose structure should be copied
2862 * @param $newName String: name of table to be created
2863 * @param $temporary Boolean: whether the new table should be temporary
2864 * @param $fname String: calling function name
2865 * @return Boolean: true if operation was successful
2867 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2868 $fname = 'DatabaseBase::duplicateTableStructure' )
2870 throw new MWException(
2871 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2875 * List all tables on the database
2877 * @param $prefix Only show tables with this prefix, e.g. mw_
2878 * @param $fname String: calling function name
2880 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2881 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2885 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2886 * to the format used for inserting into timestamp fields in this DBMS.
2888 * The result is unquoted, and needs to be passed through addQuotes()
2889 * before it can be included in raw SQL.
2891 * @param $ts string|int
2895 function timestamp( $ts = 0 ) {
2896 return wfTimestamp( TS_MW
, $ts );
2900 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2901 * to the format used for inserting into timestamp fields in this DBMS. If
2902 * NULL is input, it is passed through, allowing NULL values to be inserted
2903 * into timestamp fields.
2905 * The result is unquoted, and needs to be passed through addQuotes()
2906 * before it can be included in raw SQL.
2908 * @param $ts string|int
2912 function timestampOrNull( $ts = null ) {
2913 if ( is_null( $ts ) ) {
2916 return $this->timestamp( $ts );
2921 * Take the result from a query, and wrap it in a ResultWrapper if
2922 * necessary. Boolean values are passed through as is, to indicate success
2923 * of write queries or failure.
2925 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2926 * resource, and it was necessary to call this function to convert it to
2927 * a wrapper. Nowadays, raw database objects are never exposed to external
2928 * callers, so this is unnecessary in external code. For compatibility with
2929 * old code, ResultWrapper objects are passed through unaltered.
2931 * @param $result bool|ResultWrapper
2933 * @param bool|ResultWrapper
2935 function resultObject( $result ) {
2936 if ( empty( $result ) ) {
2938 } elseif ( $result instanceof ResultWrapper
) {
2940 } elseif ( $result === true ) {
2941 // Successful write query
2944 return new ResultWrapper( $this, $result );
2949 * Return aggregated value alias
2952 * @param $valuename string
2956 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2961 * Ping the server and try to reconnect if it there is no connection
2963 * @return bool Success or failure
2966 # Stub. Not essential to override.
2971 * Get slave lag. Currently supported only by MySQL.
2973 * Note that this function will generate a fatal error on many
2974 * installations. Most callers should use LoadBalancer::safeGetLag()
2977 * @return Database replication lag in seconds
2980 return intval( $this->mFakeSlaveLag
);
2984 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2988 function maxListLen() {
2993 * Some DBMSs have a special format for inserting into blob fields, they
2994 * don't allow simple quoted strings to be inserted. To insert into such
2995 * a field, pass the data through this function before passing it to
2996 * DatabaseBase::insert().
2998 function encodeBlob( $b ) {
3003 * Some DBMSs return a special placeholder object representing blob fields
3004 * in result objects. Pass the object through this function to return the
3007 function decodeBlob( $b ) {
3012 * Override database's default connection timeout. May be useful for very
3013 * long batch queries such as full-wiki dumps, where a single query reads
3014 * out over hours or days. May or may not be necessary for non-MySQL
3015 * databases. For most purposes, leaving it as a no-op should be fine.
3017 * @param $timeout Integer in seconds
3019 public function setTimeout( $timeout ) {}
3022 * Read and execute SQL commands from a file.
3024 * Returns true on success, error string or exception on failure (depending
3025 * on object's error ignore settings).
3027 * @param $filename String: File name to open
3028 * @param $lineCallback Callback: Optional function called before reading each line
3029 * @param $resultCallback Callback: Optional function called for each MySQL result
3030 * @param $fname String: Calling function name or false if name should be
3031 * generated dynamically using $filename
3033 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3034 wfSuppressWarnings();
3035 $fp = fopen( $filename, 'r' );
3036 wfRestoreWarnings();
3038 if ( false === $fp ) {
3039 throw new MWException( "Could not open \"{$filename}\".\n" );
3043 $fname = __METHOD__
. "( $filename )";
3047 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3049 catch ( MWException
$e ) {
3060 * Get the full path of a patch file. Originally based on archive()
3061 * from updaters.inc. Keep in mind this always returns a patch, as
3062 * it fails back to MySQL if no DB-specific patch can be found
3064 * @param $patch String The name of the patch, like patch-something.sql
3065 * @return String Full path to patch file
3067 public function patchPath( $patch ) {
3070 $dbType = $this->getType();
3071 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3072 return "$IP/maintenance/$dbType/archives/$patch";
3074 return "$IP/maintenance/archives/$patch";
3079 * Set variables to be used in sourceFile/sourceStream, in preference to the
3080 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3081 * all. If it's set to false, $GLOBALS will be used.
3083 * @param $vars False, or array mapping variable name to value.
3085 function setSchemaVars( $vars ) {
3086 $this->mSchemaVars
= $vars;
3090 * Read and execute commands from an open file handle.
3092 * Returns true on success, error string or exception on failure (depending
3093 * on object's error ignore settings).
3095 * @param $fp Resource: File handle
3096 * @param $lineCallback Callback: Optional function called before reading each line
3097 * @param $resultCallback Callback: Optional function called for each MySQL result
3098 * @param $fname String: Calling function name
3100 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3101 $fname = 'DatabaseBase::sourceStream' )
3105 $dollarquote = false;
3107 while ( ! feof( $fp ) ) {
3108 if ( $lineCallback ) {
3109 call_user_func( $lineCallback );
3112 $line = trim( fgets( $fp ) );
3113 $sl = strlen( $line ) - 1;
3119 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
3123 # # Allow dollar quoting for function declarations
3124 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3125 if ( $dollarquote ) {
3126 $dollarquote = false;
3130 $dollarquote = true;
3133 elseif ( !$dollarquote ) {
3134 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
3136 $line = substr( $line, 0, $sl );
3147 $cmd = str_replace( ';;', ";", $cmd );
3148 $cmd = $this->replaceVars( $cmd );
3149 $res = $this->query( $cmd, $fname );
3151 if ( $resultCallback ) {
3152 call_user_func( $resultCallback, $res, $this );
3155 if ( false === $res ) {
3156 $err = $this->lastError();
3157 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3169 * Database independent variable replacement. Replaces a set of variables
3170 * in an SQL statement with their contents as given by $this->getSchemaVars().
3172 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3174 * - '{$var}' should be used for text and is passed through the database's
3176 * - `{$var}` should be used for identifiers (eg: table and database names),
3177 * it is passed through the database's addIdentifierQuotes method which
3178 * can be overridden if the database uses something other than backticks.
3179 * - / *$var* / is just encoded, besides traditional table prefix and
3180 * table options its use should be avoided.
3182 * @param $ins String: SQL statement to replace variables in
3183 * @return String The new SQL statement with variables replaced
3185 protected function replaceSchemaVars( $ins ) {
3186 $vars = $this->getSchemaVars();
3187 foreach ( $vars as $var => $value ) {
3189 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3191 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3193 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3199 * Replace variables in sourced SQL
3201 * @param $ins string
3205 protected function replaceVars( $ins ) {
3206 $ins = $this->replaceSchemaVars( $ins );
3209 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3210 array( $this, 'tableNameCallback' ), $ins );
3213 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3214 array( $this, 'indexNameCallback' ), $ins );
3220 * Get schema variables. If none have been set via setSchemaVars(), then
3221 * use some defaults from the current object.
3223 protected function getSchemaVars() {
3224 if ( $this->mSchemaVars
) {
3225 return $this->mSchemaVars
;
3227 return $this->getDefaultSchemaVars();
3232 * Get schema variables to use if none have been set via setSchemaVars().
3234 * Override this in derived classes to provide variables for tables.sql
3235 * and SQL patch files.
3239 protected function getDefaultSchemaVars() {
3244 * Table name callback
3246 * @param $matches array
3250 protected function tableNameCallback( $matches ) {
3251 return $this->tableName( $matches[1] );
3255 * Index name callback
3257 * @param $matches array
3261 protected function indexNameCallback( $matches ) {
3262 return $this->indexName( $matches[1] );
3266 * Build a concatenation list to feed into a SQL query
3267 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3270 function buildConcat( $stringList ) {
3271 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3275 * Acquire a named lock
3277 * Abstracted from Filestore::lock() so child classes can implement for
3280 * @param $lockName String: name of lock to aquire
3281 * @param $method String: name of method calling us
3282 * @param $timeout Integer: timeout
3285 public function lock( $lockName, $method, $timeout = 5 ) {
3292 * @param $lockName String: Name of lock to release
3293 * @param $method String: Name of method calling us
3295 * @return Returns 1 if the lock was released, 0 if the lock was not established
3296 * by this thread (in which case the lock is not released), and NULL if the named
3297 * lock did not exist
3299 public function unlock( $lockName, $method ) {
3304 * Lock specific tables
3306 * @param $read Array of tables to lock for read access
3307 * @param $write Array of tables to lock for write access
3308 * @param $method String name of caller
3309 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3313 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3318 * Unlock specific tables
3320 * @param $method String the caller
3324 public function unlockTables( $method ) {
3330 * @param $tableName string
3331 * @param $fName string
3332 * @return bool|ResultWrapper
3334 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3335 if( !$this->tableExists( $tableName ) ) {
3338 $sql = "DROP TABLE " . $this->tableName( $tableName );
3339 if( $this->cascadingDeletes() ) {
3342 return $this->query( $sql, $fName );
3346 * Get search engine class. All subclasses of this need to implement this
3347 * if they wish to use searching.
3351 public function getSearchEngine() {
3352 return 'SearchEngineDummy';
3356 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3357 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3358 * because "i" sorts after all numbers.
3362 public function getInfinity() {
3367 * Encode an expiry time
3369 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3372 public function encodeExpiry( $expiry ) {
3373 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3374 return $this->getInfinity();
3376 return $this->timestamp( $expiry );
3381 * Allow or deny "big selects" for this session only. This is done by setting
3382 * the sql_big_selects session variable.
3384 * This is a MySQL-specific feature.
3386 * @param $value Mixed: true for allow, false for deny, or "default" to
3387 * restore the initial value
3389 public function setBigSelects( $value = true ) {