3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * Fetch the next row from the given result object, in object form.
47 * Fields can be retrieved with $row->fieldname, with fields acting like
50 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
52 * @throws DBUnexpectedError Thrown if the database returns an error
54 function fetchObject( $res );
57 * Fetch the next row from the given result object, in associative array
58 * form. Fields are retrieved with $row['fieldname'].
60 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchRow( $res );
67 * Get the number of rows in a result object
69 * @param $res Mixed: A SQL result
72 function numRows( $res );
75 * Get the number of fields in a result object
76 * @see http://www.php.net/mysql_num_fields
78 * @param $res Mixed: A SQL result
81 function numFields( $res );
84 * Get a field name in a result object
85 * @see http://www.php.net/mysql_field_name
87 * @param $res Mixed: A SQL result
91 function fieldName( $res, $n );
94 * Get the inserted value of an auto-increment row
96 * The value inserted should be fetched from nextSequenceValue()
99 * $id = $dbw->nextSequenceValue('page_page_id_seq');
100 * $dbw->insert('page',array('page_id' => $id));
101 * $id = $dbw->insertId();
108 * Change the position of the cursor in a result object
109 * @see http://www.php.net/mysql_data_seek
111 * @param $res Mixed: A SQL result
112 * @param $row Mixed: Either MySQL row or ResultWrapper
114 function dataSeek( $res, $row );
117 * Get the last error number
118 * @see http://www.php.net/mysql_errno
122 function lastErrno();
125 * Get a description of the last error
126 * @see http://www.php.net/mysql_error
130 function lastError();
133 * mysql_fetch_field() wrapper
134 * Returns false if the field doesn't exist
136 * @param $table string: table name
137 * @param $field string: field name
141 function fieldInfo( $table, $field );
144 * Get information about an index into an object
145 * @param $table string: Table name
146 * @param $index string: Index name
147 * @param $fname string: Calling function name
148 * @return Mixed: Database-specific index description class or false if the index does not exist
150 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info().
182 * @return string: Version information from the database server.
184 function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 function getServerInfo();
197 * Database abstraction object
200 abstract class DatabaseBase
implements DatabaseType
{
202 # ------------------------------------------------------------------------------
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mDBname;
215 protected $mConn = null;
216 protected $mOpened = false;
218 protected $mTablePrefix;
220 protected $mTrxLevel = 0;
221 protected $mErrorCount = 0;
222 protected $mLBInfo = array();
223 protected $mFakeSlaveLag = null, $mFakeMaster = false;
224 protected $mDefaultBigSelects = null;
225 protected $mSchemaVars = false;
227 protected $preparedArgs;
229 # ------------------------------------------------------------------------------
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 * Called by serialize. Throw an exception when DB connection is serialized.
613 * This causes problems on some database engines because the connection is
614 * not restored on unserialize.
616 public function __sleep() {
617 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
621 * Same as new DatabaseMysql( ... ), kept for backward compatibility
622 * @deprecated since 1.17
624 * @return DatabaseMysql
626 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
627 wfDeprecated( __METHOD__
);
628 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
632 * Given a DB type, construct the name of the appropriate child class of
633 * DatabaseBase. This is designed to replace all of the manual stuff like:
634 * $class = 'Database' . ucfirst( strtolower( $type ) );
635 * as well as validate against the canonical list of DB types we have
637 * This factory function is mostly useful for when you need to connect to a
638 * database other than the MediaWiki default (such as for external auth,
639 * an extension, et cetera). Do not use this to connect to the MediaWiki
640 * database. Example uses in core:
641 * @see LoadBalancer::reallyOpenConnection()
642 * @see ExternalUser_MediaWiki::initFromCond()
643 * @see ForeignDBRepo::getMasterDB()
644 * @see WebInstaller_DBConnect::execute()
646 * @param $dbType String A possible DB type
647 * @param $p Array An array of options to pass to the constructor.
648 * Valid options are: host, user, password, dbname, flags, tablePrefix
649 * @return DatabaseBase subclass or null
651 public final static function factory( $dbType, $p = array() ) {
652 $canonicalDBTypes = array(
653 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
655 $dbType = strtolower( $dbType );
657 if( in_array( $dbType, $canonicalDBTypes ) ) {
658 $class = 'Database' . ucfirst( $dbType );
660 isset( $p['host'] ) ?
$p['host'] : false,
661 isset( $p['user'] ) ?
$p['user'] : false,
662 isset( $p['password'] ) ?
$p['password'] : false,
663 isset( $p['dbname'] ) ?
$p['dbname'] : false,
664 isset( $p['flags'] ) ?
$p['flags'] : 0,
665 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
672 protected function installErrorHandler() {
673 $this->mPHPError
= false;
674 $this->htmlErrors
= ini_set( 'html_errors', '0' );
675 set_error_handler( array( $this, 'connectionErrorHandler' ) );
679 * @return bool|string
681 protected function restoreErrorHandler() {
682 restore_error_handler();
683 if ( $this->htmlErrors
!== false ) {
684 ini_set( 'html_errors', $this->htmlErrors
);
686 if ( $this->mPHPError
) {
687 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
688 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
695 protected function connectionErrorHandler( $errno, $errstr ) {
696 $this->mPHPError
= $errstr;
700 * Closes a database connection.
701 * if it is open : commits any open transactions
703 * @return Bool operation success. true if already closed.
706 # Stub, should probably be overridden
711 * @param $error String: fallback error message, used if none is given by DB
713 function reportConnectionError( $error = 'Unknown error' ) {
714 $myError = $this->lastError();
720 throw new DBConnectionError( $this, $error );
724 * The DBMS-dependent part of query()
726 * @param $sql String: SQL query.
727 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
729 protected abstract function doQuery( $sql );
732 * Determine whether a query writes to the DB.
733 * Should return true if unsure.
739 function isWriteQuery( $sql ) {
740 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
744 * Run an SQL query and return the result. Normally throws a DBQueryError
745 * on failure. If errors are ignored, returns false instead.
747 * In new code, the query wrappers select(), insert(), update(), delete(),
748 * etc. should be used where possible, since they give much better DBMS
749 * independence and automatically quote or validate user input in a variety
750 * of contexts. This function is generally only useful for queries which are
751 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
754 * However, the query wrappers themselves should call this function.
756 * @param $sql String: SQL query
757 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
758 * comment (you can use __METHOD__ or add some extra info)
759 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
760 * maybe best to catch the exception instead?
761 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
762 * for a successful read query, or false on failure if $tempIgnore set
763 * @throws DBQueryError Thrown when the database returns an error of any kind
765 public function query( $sql, $fname = '', $tempIgnore = false ) {
766 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
767 if ( !Profiler
::instance()->isStub() ) {
768 # generalizeSQL will probably cut down the query to reasonable
769 # logging size most of the time. The substr is really just a sanity check.
772 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
773 $totalProf = 'DatabaseBase::query-master';
775 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
776 $totalProf = 'DatabaseBase::query';
779 wfProfileIn( $totalProf );
780 wfProfileIn( $queryProf );
783 $this->mLastQuery
= $sql;
784 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
785 # Set a flag indicating that writes have been done
786 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
787 $this->mDoneWrites
= true;
790 # Add a comment for easy SHOW PROCESSLIST interpretation
792 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
793 $userName = $wgUser->getName();
794 if ( mb_strlen( $userName ) > 15 ) {
795 $userName = mb_substr( $userName, 0, 15 ) . '...';
797 $userName = str_replace( '/', '', $userName );
801 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
803 # If DBO_TRX is set, start a transaction
804 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
805 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
806 # avoid establishing transactions for SHOW and SET statements too -
807 # that would delay transaction initializations to once connection
808 # is really used by application
809 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
810 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
814 if ( $this->debug() ) {
818 $sqlx = substr( $commentedSql, 0, 500 );
819 $sqlx = strtr( $sqlx, "\t\n", ' ' );
822 wfDebug( "Query $cnt (master): $sqlx\n" );
824 wfDebug( "Query $cnt (slave): $sqlx\n" );
828 if ( istainted( $sql ) & TC_MYSQL
) {
829 throw new MWException( 'Tainted query found' );
832 # Do the query and handle errors
833 $ret = $this->doQuery( $commentedSql );
835 # Try reconnecting if the connection was lost
836 if ( false === $ret && $this->wasErrorReissuable() ) {
837 # Transaction is gone, like it or not
838 $this->mTrxLevel
= 0;
839 wfDebug( "Connection lost, reconnecting...\n" );
841 if ( $this->ping() ) {
842 wfDebug( "Reconnected\n" );
843 $sqlx = substr( $commentedSql, 0, 500 );
844 $sqlx = strtr( $sqlx, "\t\n", ' ' );
845 global $wgRequestTime;
846 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
847 if ( $elapsed < 300 ) {
848 # Not a database error to lose a transaction after a minute or two
849 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
851 $ret = $this->doQuery( $commentedSql );
853 wfDebug( "Failed\n" );
857 if ( false === $ret ) {
858 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
861 if ( !Profiler
::instance()->isStub() ) {
862 wfProfileOut( $queryProf );
863 wfProfileOut( $totalProf );
866 return $this->resultObject( $ret );
870 * Report a query error. Log the error, and if neither the object ignore
871 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
873 * @param $error String
874 * @param $errno Integer
876 * @param $fname String
877 * @param $tempIgnore Boolean
879 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
880 # Ignore errors during error handling to avoid infinite recursion
881 $ignore = $this->ignoreErrors( true );
882 ++
$this->mErrorCount
;
884 if ( $ignore ||
$tempIgnore ) {
885 wfDebug( "SQL ERROR (ignored): $error\n" );
886 $this->ignoreErrors( $ignore );
888 $sql1line = str_replace( "\n", "\\n", $sql );
889 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
890 wfDebug( "SQL ERROR: " . $error . "\n" );
891 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
896 * Intended to be compatible with the PEAR::DB wrapper functions.
897 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
899 * ? = scalar value, quoted as necessary
900 * ! = raw SQL bit (a function for instance)
901 * & = filename; reads the file and inserts as a blob
902 * (we don't use this though...)
904 * This function should not be used directly by new code outside of the
905 * database classes. The query wrapper functions (select() etc.) should be
909 * @param $func string
913 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
914 /* MySQL doesn't support prepared statements (yet), so just
915 pack up the query for reference. We'll manually replace
917 return array( 'query' => $sql, 'func' => $func );
921 * Free a prepared query, generated by prepare().
923 function freePrepared( $prepared ) {
924 /* No-op by default */
928 * Execute a prepared query with the various arguments
929 * @param $prepared String: the prepared sql
930 * @param $args Mixed: Either an array here, or put scalars as varargs
932 * @return ResultWrapper
934 function execute( $prepared, $args = null ) {
935 if ( !is_array( $args ) ) {
937 $args = func_get_args();
938 array_shift( $args );
941 $sql = $this->fillPrepared( $prepared['query'], $args );
943 return $this->query( $sql, $prepared['func'] );
947 * Prepare & execute an SQL statement, quoting and inserting arguments
948 * in the appropriate places.
950 * This function should not be used directly by new code outside of the
951 * database classes. The query wrapper functions (select() etc.) should be
954 * @param $query String
957 * @return ResultWrapper
959 function safeQuery( $query, $args = null ) {
960 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
962 if ( !is_array( $args ) ) {
964 $args = func_get_args();
965 array_shift( $args );
968 $retval = $this->execute( $prepared, $args );
969 $this->freePrepared( $prepared );
975 * For faking prepared SQL statements on DBs that don't support
977 * @param $preparedQuery String: a 'preparable' SQL statement
978 * @param $args Array of arguments to fill it with
979 * @return string executable SQL
981 function fillPrepared( $preparedQuery, $args ) {
983 $this->preparedArgs
=& $args;
985 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
986 array( &$this, 'fillPreparedArg' ), $preparedQuery );
990 * preg_callback func for fillPrepared()
991 * The arguments should be in $this->preparedArgs and must not be touched
992 * while we're doing this.
994 * @param $matches Array
997 function fillPreparedArg( $matches ) {
998 switch( $matches[1] ) {
999 case '\\?': return '?';
1000 case '\\!': return '!';
1001 case '\\&': return '&';
1004 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1006 switch( $matches[1] ) {
1007 case '?': return $this->addQuotes( $arg );
1008 case '!': return $arg;
1010 # return $this->addQuotes( file_get_contents( $arg ) );
1011 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1013 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1018 * Free a result object returned by query() or select(). It's usually not
1019 * necessary to call this, just use unset() or let the variable holding
1020 * the result object go out of scope.
1022 * @param $res Mixed: A SQL result
1024 function freeResult( $res ) {
1028 * Simple UPDATE wrapper.
1029 * Usually throws a DBQueryError on failure.
1030 * If errors are explicitly ignored, returns success
1032 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1033 * calling convention and feature set
1035 * @param $table string
1039 * @param $fname string
1043 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1044 $table = $this->tableName( $table );
1045 $sql = "UPDATE $table SET $var = '" .
1046 $this->strencode( $value ) . "' WHERE ($cond)";
1048 return (bool)$this->query( $sql, $fname );
1052 * A SELECT wrapper which returns a single field from a single result row.
1054 * Usually throws a DBQueryError on failure. If errors are explicitly
1055 * ignored, returns false on failure.
1057 * If no result rows are returned from the query, false is returned.
1059 * @param $table string|array Table name. See DatabaseBase::select() for details.
1060 * @param $var string The field name to select. This must be a valid SQL
1061 * fragment: do not use unvalidated user input.
1062 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1063 * @param $fname string The function name of the caller.
1064 * @param $options string|array The query options. See DatabaseBase::select() for details.
1066 * @return false|mixed The value from the field, or false on failure.
1068 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1069 $options = array() )
1071 if ( !is_array( $options ) ) {
1072 $options = array( $options );
1075 $options['LIMIT'] = 1;
1077 $res = $this->select( $table, $var, $cond, $fname, $options );
1079 if ( $res === false ||
!$this->numRows( $res ) ) {
1083 $row = $this->fetchRow( $res );
1085 if ( $row !== false ) {
1086 return reset( $row );
1093 * Returns an optional USE INDEX clause to go after the table, and a
1094 * string to go at the end of the query.
1096 * @param $options Array: associative array of options to be turned into
1097 * an SQL query, valid keys are listed in the function.
1099 * @see DatabaseBase::select()
1101 function makeSelectOptions( $options ) {
1102 $preLimitTail = $postLimitTail = '';
1105 $noKeyOptions = array();
1107 foreach ( $options as $key => $option ) {
1108 if ( is_numeric( $key ) ) {
1109 $noKeyOptions[$option] = true;
1113 if ( isset( $options['GROUP BY'] ) ) {
1114 $gb = is_array( $options['GROUP BY'] )
1115 ?
implode( ',', $options['GROUP BY'] )
1116 : $options['GROUP BY'];
1117 $preLimitTail .= " GROUP BY {$gb}";
1120 if ( isset( $options['HAVING'] ) ) {
1121 $preLimitTail .= " HAVING {$options['HAVING']}";
1124 if ( isset( $options['ORDER BY'] ) ) {
1125 $ob = is_array( $options['ORDER BY'] )
1126 ?
implode( ',', $options['ORDER BY'] )
1127 : $options['ORDER BY'];
1128 $preLimitTail .= " ORDER BY {$ob}";
1131 // if (isset($options['LIMIT'])) {
1132 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1133 // isset($options['OFFSET']) ? $options['OFFSET']
1137 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1138 $postLimitTail .= ' FOR UPDATE';
1141 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1142 $postLimitTail .= ' LOCK IN SHARE MODE';
1145 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1146 $startOpts .= 'DISTINCT';
1149 # Various MySQL extensions
1150 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1151 $startOpts .= ' /*! STRAIGHT_JOIN */';
1154 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1155 $startOpts .= ' HIGH_PRIORITY';
1158 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1159 $startOpts .= ' SQL_BIG_RESULT';
1162 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1163 $startOpts .= ' SQL_BUFFER_RESULT';
1166 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1167 $startOpts .= ' SQL_SMALL_RESULT';
1170 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1171 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1174 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1175 $startOpts .= ' SQL_CACHE';
1178 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1179 $startOpts .= ' SQL_NO_CACHE';
1182 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1183 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1188 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1192 * Execute a SELECT query constructed using the various parameters provided.
1193 * See below for full details of the parameters.
1195 * @param $table String|Array Table name
1196 * @param $vars String|Array Field names
1197 * @param $conds String|Array Conditions
1198 * @param $fname String Caller function name
1199 * @param $options Array Query options
1200 * @param $join_conds Array Join conditions
1202 * @param $table string|array
1204 * May be either an array of table names, or a single string holding a table
1205 * name. If an array is given, table aliases can be specified, for example:
1207 * array( 'a' => 'user' )
1209 * This includes the user table in the query, with the alias "a" available
1210 * for use in field names (e.g. a.user_name).
1212 * All of the table names given here are automatically run through
1213 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1214 * added, and various other table name mappings to be performed.
1217 * @param $vars string|array
1219 * May be either a field name or an array of field names. The field names
1220 * here are complete fragments of SQL, for direct inclusion into the SELECT
1221 * query. Expressions and aliases may be specified as in SQL, for example:
1223 * array( 'MAX(rev_id) AS maxrev' )
1225 * If an expression is given, care must be taken to ensure that it is
1229 * @param $conds string|array
1231 * May be either a string containing a single condition, or an array of
1232 * conditions. If an array is given, the conditions constructed from each
1233 * element are combined with AND.
1235 * Array elements may take one of two forms:
1237 * - Elements with a numeric key are interpreted as raw SQL fragments.
1238 * - Elements with a string key are interpreted as equality conditions,
1239 * where the key is the field name.
1240 * - If the value of such an array element is a scalar (such as a
1241 * string), it will be treated as data and thus quoted appropriately.
1242 * If it is null, an IS NULL clause will be added.
1243 * - If the value is an array, an IN(...) clause will be constructed,
1244 * such that the field name may match any of the elements in the
1245 * array. The elements of the array will be quoted.
1247 * Note that expressions are often DBMS-dependent in their syntax.
1248 * DBMS-independent wrappers are provided for constructing several types of
1249 * expression commonly used in condition queries. See:
1250 * - DatabaseBase::buildLike()
1251 * - DatabaseBase::conditional()
1254 * @param $options string|array
1256 * Optional: Array of query options. Boolean options are specified by
1257 * including them in the array as a string value with a numeric key, for
1260 * array( 'FOR UPDATE' )
1262 * The supported options are:
1264 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1265 * with LIMIT can theoretically be used for paging through a result set,
1266 * but this is discouraged in MediaWiki for performance reasons.
1268 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1269 * and then the first rows are taken until the limit is reached. LIMIT
1270 * is applied to a result set after OFFSET.
1272 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1273 * changed until the next COMMIT.
1275 * - DISTINCT: Boolean: return only unique result rows.
1277 * - GROUP BY: May be either an SQL fragment string naming a field or
1278 * expression to group by, or an array of such SQL fragments.
1280 * - HAVING: A string containing a HAVING clause.
1282 * - ORDER BY: May be either an SQL fragment giving a field name or
1283 * expression to order by, or an array of such SQL fragments.
1285 * - USE INDEX: This may be either a string giving the index name to use
1286 * for the query, or an array. If it is an associative array, each key
1287 * gives the table name (or alias), each value gives the index name to
1288 * use for that table. All strings are SQL fragments and so should be
1289 * validated by the caller.
1291 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1292 * instead of SELECT.
1294 * And also the following boolean MySQL extensions, see the MySQL manual
1295 * for documentation:
1297 * - LOCK IN SHARE MODE
1301 * - SQL_BUFFER_RESULT
1302 * - SQL_SMALL_RESULT
1303 * - SQL_CALC_FOUND_ROWS
1308 * @param $join_conds string|array
1310 * Optional associative array of table-specific join conditions. In the
1311 * most common case, this is unnecessary, since the join condition can be
1312 * in $conds. However, it is useful for doing a LEFT JOIN.
1314 * The key of the array contains the table name or alias. The value is an
1315 * array with two elements, numbered 0 and 1. The first gives the type of
1316 * join, the second is an SQL fragment giving the join condition for that
1317 * table. For example:
1319 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1321 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1322 * with no rows in it will be returned. If there was a query error, a
1323 * DBQueryError exception will be thrown, except if the "ignore errors"
1324 * option was set, in which case false will be returned.
1326 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1327 $options = array(), $join_conds = array() ) {
1328 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1330 return $this->query( $sql, $fname );
1334 * The equivalent of DatabaseBase::select() except that the constructed SQL
1335 * is returned, instead of being immediately executed.
1337 * @param $table string|array Table name
1338 * @param $vars string|array Field names
1339 * @param $conds string|array Conditions
1340 * @param $fname string Caller function name
1341 * @param $options string|array Query options
1342 * @param $join_conds string|array Join conditions
1344 * @return SQL query string.
1345 * @see DatabaseBase::select()
1347 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1348 if ( is_array( $vars ) ) {
1349 $vars = implode( ',', $vars );
1352 $options = (array)$options;
1354 if ( is_array( $table ) ) {
1355 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1356 ?
$options['USE INDEX']
1358 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1360 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1362 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1364 } elseif ( $table != '' ) {
1365 if ( $table[0] == ' ' ) {
1366 $from = ' FROM ' . $table;
1368 $from = ' FROM ' . $this->tableName( $table );
1374 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1376 if ( !empty( $conds ) ) {
1377 if ( is_array( $conds ) ) {
1378 $conds = $this->makeList( $conds, LIST_AND
);
1380 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1382 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1385 if ( isset( $options['LIMIT'] ) ) {
1386 $sql = $this->limitResult( $sql, $options['LIMIT'],
1387 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1389 $sql = "$sql $postLimitTail";
1391 if ( isset( $options['EXPLAIN'] ) ) {
1392 $sql = 'EXPLAIN ' . $sql;
1399 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1400 * that a single row object is returned. If the query returns no rows,
1401 * false is returned.
1403 * @param $table string|array Table name
1404 * @param $vars string|array Field names
1405 * @param $conds|array Conditions
1406 * @param $fname string Caller function name
1407 * @param $options string|array Query options
1408 * @param $join_conds array|string Join conditions
1410 * @return ResultWrapper|bool
1412 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1413 $options = array(), $join_conds = array() )
1415 $options['LIMIT'] = 1;
1416 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1418 if ( $res === false ) {
1422 if ( !$this->numRows( $res ) ) {
1426 $obj = $this->fetchObject( $res );
1432 * Estimate rows in dataset.
1434 * MySQL allows you to estimate the number of rows that would be returned
1435 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1436 * index cardinality statistics, and is notoriously inaccurate, especially
1437 * when large numbers of rows have recently been added or deleted.
1439 * For DBMSs that don't support fast result size estimation, this function
1440 * will actually perform the SELECT COUNT(*).
1442 * Takes the same arguments as DatabaseBase::select().
1444 * @param $table String: table name
1445 * @param Array|string $vars : unused
1446 * @param Array|string $conds : filters on the table
1447 * @param $fname String: function name for profiling
1448 * @param $options Array: options for select
1449 * @return Integer: row count
1451 public function estimateRowCount( $table, $vars = '*', $conds = '',
1452 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1455 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1458 $row = $this->fetchRow( $res );
1459 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1466 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1467 * It's only slightly flawed. Don't use for anything important.
1469 * @param $sql String A SQL Query
1473 static function generalizeSQL( $sql ) {
1474 # This does the same as the regexp below would do, but in such a way
1475 # as to avoid crashing php on some large strings.
1476 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1478 $sql = str_replace ( "\\\\", '', $sql );
1479 $sql = str_replace ( "\\'", '', $sql );
1480 $sql = str_replace ( "\\\"", '', $sql );
1481 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1482 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1484 # All newlines, tabs, etc replaced by single space
1485 $sql = preg_replace ( '/\s+/', ' ', $sql );
1488 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1494 * Determines whether a field exists in a table
1496 * @param $table String: table name
1497 * @param $field String: filed to check on that table
1498 * @param $fname String: calling function name (optional)
1499 * @return Boolean: whether $table has filed $field
1501 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1502 $info = $this->fieldInfo( $table, $field );
1508 * Determines whether an index exists
1509 * Usually throws a DBQueryError on failure
1510 * If errors are explicitly ignored, returns NULL on failure
1514 * @param $fname string
1518 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1519 $info = $this->indexInfo( $table, $index, $fname );
1520 if ( is_null( $info ) ) {
1523 return $info !== false;
1528 * Query whether a given table exists
1530 * @param $table string
1531 * @param $fname string
1535 function tableExists( $table, $fname = __METHOD__
) {
1536 $table = $this->tableName( $table );
1537 $old = $this->ignoreErrors( true );
1538 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1539 $this->ignoreErrors( $old );
1546 * mysql_field_type() wrapper
1548 function fieldType( $res, $index ) {
1549 if ( $res instanceof ResultWrapper
) {
1550 $res = $res->result
;
1553 return mysql_field_type( $res, $index );
1557 * Determines if a given index is unique
1559 * @param $table string
1560 * @param $index string
1564 function indexUnique( $table, $index ) {
1565 $indexInfo = $this->indexInfo( $table, $index );
1567 if ( !$indexInfo ) {
1571 return !$indexInfo[0]->Non_unique
;
1575 * Helper for DatabaseBase::insert().
1577 * @param $options array
1580 function makeInsertOptions( $options ) {
1581 return implode( ' ', $options );
1585 * INSERT wrapper, inserts an array into a table.
1589 * - A single associative array. The array keys are the field names, and
1590 * the values are the values to insert. The values are treated as data
1591 * and will be quoted appropriately. If NULL is inserted, this will be
1592 * converted to a database NULL.
1593 * - An array with numeric keys, holding a list of associative arrays.
1594 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1595 * each subarray must be identical to each other, and in the same order.
1597 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1600 * $options is an array of options, with boolean options encoded as values
1601 * with numeric keys, in the same style as $options in
1602 * DatabaseBase::select(). Supported options are:
1604 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1605 * any rows which cause duplicate key errors are not inserted. It's
1606 * possible to determine how many rows were successfully inserted using
1607 * DatabaseBase::affectedRows().
1609 * @param $table String Table name. This will be passed through
1610 * DatabaseBase::tableName().
1611 * @param $a Array of rows to insert
1612 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1613 * @param $options Array of options
1617 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1618 # No rows to insert, easy just return now
1619 if ( !count( $a ) ) {
1623 $table = $this->tableName( $table );
1625 if ( !is_array( $options ) ) {
1626 $options = array( $options );
1629 $options = $this->makeInsertOptions( $options );
1631 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1633 $keys = array_keys( $a[0] );
1636 $keys = array_keys( $a );
1639 $sql = 'INSERT ' . $options .
1640 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1644 foreach ( $a as $row ) {
1650 $sql .= '(' . $this->makeList( $row ) . ')';
1653 $sql .= '(' . $this->makeList( $a ) . ')';
1656 return (bool)$this->query( $sql, $fname );
1660 * Make UPDATE options for the DatabaseBase::update function
1662 * @param $options Array: The options passed to DatabaseBase::update
1665 function makeUpdateOptions( $options ) {
1666 if ( !is_array( $options ) ) {
1667 $options = array( $options );
1672 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1673 $opts[] = $this->lowPriorityOption();
1676 if ( in_array( 'IGNORE', $options ) ) {
1680 return implode( ' ', $opts );
1684 * UPDATE wrapper. Takes a condition array and a SET array.
1686 * @param $table String|array name of the table to UPDATE. This will be passed through
1687 * DatabaseBase::tableName().
1689 * @param $values Array An array of values to SET. For each array element,
1690 * the key gives the field name, and the value gives the data
1691 * to set that field to. The data will be quoted by
1692 * DatabaseBase::addQuotes().
1694 * @param $conds Array An array of conditions (WHERE). See
1695 * DatabaseBase::select() for the details of the format of
1696 * condition arrays. Use '*' to update all rows.
1698 * @param $fname String The function name of the caller (from __METHOD__),
1699 * for logging and profiling.
1701 * @param $options Array An array of UPDATE options, can be:
1702 * - IGNORE: Ignore unique key conflicts
1703 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1706 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1707 if ( is_array( $table ) ) {
1708 $table = implode( ',', array_map( array( $this, 'tableName' ), $table ) );
1710 $table = $this->tableName( $table );
1712 $opts = $this->makeUpdateOptions( $options );
1713 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1715 if ( $conds !== array() && $conds !== '*' ) {
1716 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1719 return $this->query( $sql, $fname );
1723 * Makes an encoded list of strings from an array
1724 * @param $a Array containing the data
1725 * @param $mode int Constant
1726 * - LIST_COMMA: comma separated, no field names
1727 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1728 * the documentation for $conds in DatabaseBase::select().
1729 * - LIST_OR: ORed WHERE clause (without the WHERE)
1730 * - LIST_SET: comma separated with field names, like a SET clause
1731 * - LIST_NAMES: comma separated field names
1735 function makeList( $a, $mode = LIST_COMMA
) {
1736 if ( !is_array( $a ) ) {
1737 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1743 foreach ( $a as $field => $value ) {
1745 if ( $mode == LIST_AND
) {
1747 } elseif ( $mode == LIST_OR
) {
1756 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1757 $list .= "($value)";
1758 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1760 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1761 if ( count( $value ) == 0 ) {
1762 throw new MWException( __METHOD__
. ': empty input' );
1763 } elseif ( count( $value ) == 1 ) {
1764 // Special-case single values, as IN isn't terribly efficient
1765 // Don't necessarily assume the single key is 0; we don't
1766 // enforce linear numeric ordering on other arrays here.
1767 $value = array_values( $value );
1768 $list .= $field . " = " . $this->addQuotes( $value[0] );
1770 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1772 } elseif ( $value === null ) {
1773 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1774 $list .= "$field IS ";
1775 } elseif ( $mode == LIST_SET
) {
1776 $list .= "$field = ";
1780 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1781 $list .= "$field = ";
1783 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1791 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1792 * The keys on each level may be either integers or strings.
1794 * @param $data Array: organized as 2-d
1795 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1796 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1797 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1798 * @return Mixed: string SQL fragment, or false if no items in array.
1800 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1803 foreach ( $data as $base => $sub ) {
1804 if ( count( $sub ) ) {
1805 $conds[] = $this->makeList(
1806 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1812 return $this->makeList( $conds, LIST_OR
);
1814 // Nothing to search for...
1820 * Bitwise operations
1827 function bitNot( $field ) {
1833 * @param $fieldRight
1836 function bitAnd( $fieldLeft, $fieldRight ) {
1837 return "($fieldLeft & $fieldRight)";
1842 * @param $fieldRight
1845 function bitOr( $fieldLeft, $fieldRight ) {
1846 return "($fieldLeft | $fieldRight)";
1850 * Change the current database
1852 * @todo Explain what exactly will fail if this is not overridden.
1856 * @return bool Success or failure
1858 function selectDB( $db ) {
1859 # Stub. Shouldn't cause serious problems if it's not overridden, but
1860 # if your database engine supports a concept similar to MySQL's
1861 # databases you may as well.
1862 $this->mDBname
= $db;
1867 * Get the current DB name
1869 function getDBname() {
1870 return $this->mDBname
;
1874 * Get the server hostname or IP address
1876 function getServer() {
1877 return $this->mServer
;
1881 * Format a table name ready for use in constructing an SQL query
1883 * This does two important things: it quotes the table names to clean them up,
1884 * and it adds a table prefix if only given a table name with no quotes.
1886 * All functions of this object which require a table name call this function
1887 * themselves. Pass the canonical name to such functions. This is only needed
1888 * when calling query() directly.
1890 * @param $name String: database table name
1891 * @param $format String One of:
1892 * quoted - Automatically pass the table name through addIdentifierQuotes()
1893 * so that it can be used in a query.
1894 * raw - Do not add identifier quotes to the table name
1895 * @return String: full database name
1897 function tableName( $name, $format = 'quoted' ) {
1898 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1899 # Skip the entire process when we have a string quoted on both ends.
1900 # Note that we check the end so that we will still quote any use of
1901 # use of `database`.table. But won't break things if someone wants
1902 # to query a database table with a dot in the name.
1903 if ( $this->isQuotedIdentifier( $name ) ) {
1907 # Lets test for any bits of text that should never show up in a table
1908 # name. Basically anything like JOIN or ON which are actually part of
1909 # SQL queries, but may end up inside of the table value to combine
1910 # sql. Such as how the API is doing.
1911 # Note that we use a whitespace test rather than a \b test to avoid
1912 # any remote case where a word like on may be inside of a table name
1913 # surrounded by symbols which may be considered word breaks.
1914 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1918 # Split database and table into proper variables.
1919 # We reverse the explode so that database.table and table both output
1920 # the correct table.
1921 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1922 if ( isset( $dbDetails[1] ) ) {
1923 list( $table, $database ) = $dbDetails;
1925 list( $table ) = $dbDetails;
1927 $prefix = $this->mTablePrefix
; # Default prefix
1929 # A database name has been specified in input. We don't want any
1931 if ( isset( $database ) ) {
1935 # Note that we use the long format because php will complain in in_array if
1936 # the input is not an array, and will complain in is_array if it is not set.
1937 if ( !isset( $database ) # Don't use shared database if pre selected.
1938 && isset( $wgSharedDB ) # We have a shared database
1939 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1940 && isset( $wgSharedTables )
1941 && is_array( $wgSharedTables )
1942 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1943 $database = $wgSharedDB;
1944 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1947 # Quote the $database and $table and apply the prefix if not quoted.
1948 if ( isset( $database ) ) {
1949 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1952 $table = "{$prefix}{$table}";
1953 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1954 $table = $this->addIdentifierQuotes( "{$table}" );
1957 # Merge our database and table into our final table name.
1958 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1964 * Fetch a number of table names into an array
1965 * This is handy when you need to construct SQL for joins
1968 * extract($dbr->tableNames('user','watchlist'));
1969 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1970 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1974 public function tableNames() {
1975 $inArray = func_get_args();
1978 foreach ( $inArray as $name ) {
1979 $retVal[$name] = $this->tableName( $name );
1986 * Fetch a number of table names into an zero-indexed numerical array
1987 * This is handy when you need to construct SQL for joins
1990 * list( $user, $watchlist ) = $dbr->tableNamesN('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 tableNamesN() {
1997 $inArray = func_get_args();
2000 foreach ( $inArray as $name ) {
2001 $retVal[] = $this->tableName( $name );
2008 * Get an aliased table name
2009 * e.g. tableName AS newTableName
2011 * @param $name string Table name, see tableName()
2012 * @param $alias string|bool Alias (optional)
2013 * @return string SQL name for aliased table. Will not alias a table to its own name
2015 public function tableNameWithAlias( $name, $alias = false ) {
2016 if ( !$alias ||
$alias == $name ) {
2017 return $this->tableName( $name );
2019 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2024 * Gets an array of aliased table names
2026 * @param $tables array( [alias] => table )
2027 * @return array of strings, see tableNameWithAlias()
2029 public function tableNamesWithAlias( $tables ) {
2031 foreach ( $tables as $alias => $table ) {
2032 if ( is_numeric( $alias ) ) {
2035 $retval[] = $this->tableNameWithAlias( $table, $alias );
2041 * Get the aliased table name clause for a FROM clause
2042 * which might have a JOIN and/or USE INDEX clause
2044 * @param $tables array ( [alias] => table )
2045 * @param $use_index array Same as for select()
2046 * @param $join_conds array Same as for select()
2049 protected function tableNamesWithUseIndexOrJOIN(
2050 $tables, $use_index = array(), $join_conds = array()
2054 $use_index = (array)$use_index;
2055 $join_conds = (array)$join_conds;
2057 foreach ( $tables as $alias => $table ) {
2058 if ( !is_string( $alias ) ) {
2059 // No alias? Set it equal to the table name
2062 // Is there a JOIN clause for this table?
2063 if ( isset( $join_conds[$alias] ) ) {
2064 list( $joinType, $conds ) = $join_conds[$alias];
2065 $tableClause = $joinType;
2066 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2067 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2068 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2070 $tableClause .= ' ' . $use;
2073 $on = $this->makeList( (array)$conds, LIST_AND
);
2075 $tableClause .= ' ON (' . $on . ')';
2078 $retJOIN[] = $tableClause;
2079 // Is there an INDEX clause for this table?
2080 } elseif ( isset( $use_index[$alias] ) ) {
2081 $tableClause = $this->tableNameWithAlias( $table, $alias );
2082 $tableClause .= ' ' . $this->useIndexClause(
2083 implode( ',', (array)$use_index[$alias] ) );
2085 $ret[] = $tableClause;
2087 $tableClause = $this->tableNameWithAlias( $table, $alias );
2089 $ret[] = $tableClause;
2093 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2094 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2095 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2097 // Compile our final table clause
2098 return implode( ' ', array( $straightJoins, $otherJoins ) );
2102 * Get the name of an index in a given table
2108 function indexName( $index ) {
2109 // Backwards-compatibility hack
2111 'ar_usertext_timestamp' => 'usertext_timestamp',
2112 'un_user_id' => 'user_id',
2113 'un_user_ip' => 'user_ip',
2116 if ( isset( $renamed[$index] ) ) {
2117 return $renamed[$index];
2124 * If it's a string, adds quotes and backslashes
2125 * Otherwise returns as-is
2131 function addQuotes( $s ) {
2132 if ( $s === null ) {
2135 # This will also quote numeric values. This should be harmless,
2136 # and protects against weird problems that occur when they really
2137 # _are_ strings such as article titles and string->number->string
2138 # conversion is not 1:1.
2139 return "'" . $this->strencode( $s ) . "'";
2144 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2145 * MySQL uses `backticks` while basically everything else uses double quotes.
2146 * Since MySQL is the odd one out here the double quotes are our generic
2147 * and we implement backticks in DatabaseMysql.
2153 public function addIdentifierQuotes( $s ) {
2154 return '"' . str_replace( '"', '""', $s ) . '"';
2158 * Returns if the given identifier looks quoted or not according to
2159 * the database convention for quoting identifiers .
2161 * @param $name string
2165 public function isQuotedIdentifier( $name ) {
2166 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2170 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2171 * which used quote_ident which does not follow our naming conventions
2172 * was renamed to addIdentifierQuotes.
2173 * @deprecated since 1.18 use addIdentifierQuotes
2179 function quote_ident( $s ) {
2180 wfDeprecated( __METHOD__
);
2181 return $this->addIdentifierQuotes( $s );
2185 * Escape string for safe LIKE usage.
2186 * WARNING: you should almost never use this function directly,
2187 * instead use buildLike() that escapes everything automatically
2188 * @deprecated since 1.17, warnings in 1.17, removed in ???
2194 public function escapeLike( $s ) {
2195 wfDeprecated( __METHOD__
);
2196 return $this->escapeLikeInternal( $s );
2203 protected function escapeLikeInternal( $s ) {
2204 $s = str_replace( '\\', '\\\\', $s );
2205 $s = $this->strencode( $s );
2206 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2212 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2213 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2214 * Alternatively, the function could be provided with an array of aforementioned parameters.
2216 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2217 * for subpages of 'My page title'.
2218 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2221 * @return String: fully built LIKE statement
2223 function buildLike() {
2224 $params = func_get_args();
2226 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2227 $params = $params[0];
2232 foreach ( $params as $value ) {
2233 if ( $value instanceof LikeMatch
) {
2234 $s .= $value->toString();
2236 $s .= $this->escapeLikeInternal( $value );
2240 return " LIKE '" . $s . "' ";
2244 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2248 function anyChar() {
2249 return new LikeMatch( '_' );
2253 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2257 function anyString() {
2258 return new LikeMatch( '%' );
2262 * Returns an appropriately quoted sequence value for inserting a new row.
2263 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2264 * subclass will return an integer, and save the value for insertId()
2266 * Any implementation of this function should *not* involve reusing
2267 * sequence numbers created for rolled-back transactions.
2268 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2270 function nextSequenceValue( $seqName ) {
2275 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2276 * is only needed because a) MySQL must be as efficient as possible due to
2277 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2278 * which index to pick. Anyway, other databases might have different
2279 * indexes on a given table. So don't bother overriding this unless you're
2282 function useIndexClause( $index ) {
2287 * REPLACE query wrapper.
2289 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2290 * except that when there is a duplicate key error, the old row is deleted
2291 * and the new row is inserted in its place.
2293 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2294 * perform the delete, we need to know what the unique indexes are so that
2295 * we know how to find the conflicting rows.
2297 * It may be more efficient to leave off unique indexes which are unlikely
2298 * to collide. However if you do this, you run the risk of encountering
2299 * errors which wouldn't have occurred in MySQL.
2301 * @param $table String: The table to replace the row(s) in.
2302 * @param $rows array Can be either a single row to insert, or multiple rows,
2303 * in the same format as for DatabaseBase::insert()
2304 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2305 * a field name or an array of field names
2306 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2308 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2309 $quotedTable = $this->tableName( $table );
2311 if ( count( $rows ) == 0 ) {
2316 if ( !is_array( reset( $rows ) ) ) {
2317 $rows = array( $rows );
2320 foreach( $rows as $row ) {
2321 # Delete rows which collide
2322 if ( $uniqueIndexes ) {
2323 $sql = "DELETE FROM $quotedTable WHERE ";
2325 foreach ( $uniqueIndexes as $index ) {
2332 if ( is_array( $index ) ) {
2334 foreach ( $index as $col ) {
2340 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2343 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2347 $this->query( $sql, $fname );
2350 # Now insert the row
2351 $this->insert( $table, $row );
2356 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2359 * @param $table Table name
2360 * @param $rows Rows to insert
2361 * @param $fname Caller function name
2363 * @return ResultWrapper
2365 protected function nativeReplace( $table, $rows, $fname ) {
2366 $table = $this->tableName( $table );
2369 if ( !is_array( reset( $rows ) ) ) {
2370 $rows = array( $rows );
2373 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2376 foreach ( $rows as $row ) {
2383 $sql .= '(' . $this->makeList( $row ) . ')';
2386 return $this->query( $sql, $fname );
2390 * DELETE where the condition is a join.
2392 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2393 * we use sub-selects
2395 * For safety, an empty $conds will not delete everything. If you want to
2396 * delete all rows where the join condition matches, set $conds='*'.
2398 * DO NOT put the join condition in $conds.
2400 * @param $delTable String: The table to delete from.
2401 * @param $joinTable String: The other table.
2402 * @param $delVar String: The variable to join on, in the first table.
2403 * @param $joinVar String: The variable to join on, in the second table.
2404 * @param $conds Array: Condition array of field names mapped to variables,
2405 * ANDed together in the WHERE clause
2406 * @param $fname String: Calling function name (use __METHOD__) for
2409 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2410 $fname = 'DatabaseBase::deleteJoin' )
2413 throw new DBUnexpectedError( $this,
2414 'DatabaseBase::deleteJoin() called with empty $conds' );
2417 $delTable = $this->tableName( $delTable );
2418 $joinTable = $this->tableName( $joinTable );
2419 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2420 if ( $conds != '*' ) {
2421 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2425 $this->query( $sql, $fname );
2429 * Returns the size of a text field, or -1 for "unlimited"
2431 * @param $table string
2432 * @param $field string
2436 function textFieldSize( $table, $field ) {
2437 $table = $this->tableName( $table );
2438 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2439 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2440 $row = $this->fetchObject( $res );
2444 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2454 * A string to insert into queries to show that they're low-priority, like
2455 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2456 * string and nothing bad should happen.
2458 * @return string Returns the text of the low priority option if it is
2459 * supported, or a blank string otherwise
2461 function lowPriorityOption() {
2466 * DELETE query wrapper.
2468 * @param $table Array Table name
2469 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2470 * the format. Use $conds == "*" to delete all rows
2471 * @param $fname String name of the calling function
2475 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2477 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2480 $table = $this->tableName( $table );
2481 $sql = "DELETE FROM $table";
2483 if ( $conds != '*' ) {
2484 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2487 return $this->query( $sql, $fname );
2491 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2492 * into another table.
2494 * @param $destTable string The table name to insert into
2495 * @param $srcTable string|array May be either a table name, or an array of table names
2496 * to include in a join.
2498 * @param $varMap array must be an associative array of the form
2499 * array( 'dest1' => 'source1', ...). Source items may be literals
2500 * rather than field names, but strings should be quoted with
2501 * DatabaseBase::addQuotes()
2503 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2504 * the details of the format of condition arrays. May be "*" to copy the
2507 * @param $fname string The function name of the caller, from __METHOD__
2509 * @param $insertOptions array Options for the INSERT part of the query, see
2510 * DatabaseBase::insert() for details.
2511 * @param $selectOptions array Options for the SELECT part of the query, see
2512 * DatabaseBase::select() for details.
2514 * @return ResultWrapper
2516 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2517 $fname = 'DatabaseBase::insertSelect',
2518 $insertOptions = array(), $selectOptions = array() )
2520 $destTable = $this->tableName( $destTable );
2522 if ( is_array( $insertOptions ) ) {
2523 $insertOptions = implode( ' ', $insertOptions );
2526 if ( !is_array( $selectOptions ) ) {
2527 $selectOptions = array( $selectOptions );
2530 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2532 if ( is_array( $srcTable ) ) {
2533 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2535 $srcTable = $this->tableName( $srcTable );
2538 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2539 " SELECT $startOpts " . implode( ',', $varMap ) .
2540 " FROM $srcTable $useIndex ";
2542 if ( $conds != '*' ) {
2543 if ( is_array( $conds ) ) {
2544 $conds = $this->makeList( $conds, LIST_AND
);
2546 $sql .= " WHERE $conds";
2549 $sql .= " $tailOpts";
2551 return $this->query( $sql, $fname );
2555 * Construct a LIMIT query with optional offset. This is used for query
2556 * pages. The SQL should be adjusted so that only the first $limit rows
2557 * are returned. If $offset is provided as well, then the first $offset
2558 * rows should be discarded, and the next $limit rows should be returned.
2559 * If the result of the query is not ordered, then the rows to be returned
2560 * are theoretically arbitrary.
2562 * $sql is expected to be a SELECT, if that makes a difference. For
2563 * UPDATE, limitResultForUpdate should be used.
2565 * The version provided by default works in MySQL and SQLite. It will very
2566 * likely need to be overridden for most other DBMSes.
2568 * @param $sql String SQL query we will append the limit too
2569 * @param $limit Integer the SQL limit
2570 * @param $offset Integer|false the SQL offset (default false)
2574 function limitResult( $sql, $limit, $offset = false ) {
2575 if ( !is_numeric( $limit ) ) {
2576 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2579 return "$sql LIMIT "
2580 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2589 function limitResultForUpdate( $sql, $num ) {
2590 return $this->limitResult( $sql, $num, 0 );
2594 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2595 * within the UNION construct.
2598 function unionSupportsOrderAndLimit() {
2599 return true; // True for almost every DB supported
2603 * Construct a UNION query
2604 * This is used for providing overload point for other DB abstractions
2605 * not compatible with the MySQL syntax.
2606 * @param $sqls Array: SQL statements to combine
2607 * @param $all Boolean: use UNION ALL
2608 * @return String: SQL fragment
2610 function unionQueries( $sqls, $all ) {
2611 $glue = $all ?
') UNION ALL (' : ') UNION (';
2612 return '(' . implode( $glue, $sqls ) . ')';
2616 * Returns an SQL expression for a simple conditional. This doesn't need
2617 * to be overridden unless CASE isn't supported in your DBMS.
2619 * @param $cond String: SQL expression which will result in a boolean value
2620 * @param $trueVal String: SQL expression to return if true
2621 * @param $falseVal String: SQL expression to return if false
2622 * @return String: SQL fragment
2624 function conditional( $cond, $trueVal, $falseVal ) {
2625 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2629 * Returns a comand for str_replace function in SQL query.
2630 * Uses REPLACE() in MySQL
2632 * @param $orig String: column to modify
2633 * @param $old String: column to seek
2634 * @param $new String: column to replace with
2638 function strreplace( $orig, $old, $new ) {
2639 return "REPLACE({$orig}, {$old}, {$new})";
2643 * Determines if the last failure was due to a deadlock
2648 function wasDeadlock() {
2653 * Determines if the last query error was something that should be dealt
2654 * with by pinging the connection and reissuing the query.
2659 function wasErrorReissuable() {
2664 * Determines if the last failure was due to the database being read-only.
2669 function wasReadOnlyError() {
2674 * Perform a deadlock-prone transaction.
2676 * This function invokes a callback function to perform a set of write
2677 * queries. If a deadlock occurs during the processing, the transaction
2678 * will be rolled back and the callback function will be called again.
2681 * $dbw->deadlockLoop( callback, ... );
2683 * Extra arguments are passed through to the specified callback function.
2685 * Returns whatever the callback function returned on its successful,
2686 * iteration, or false on error, for example if the retry limit was
2691 function deadlockLoop() {
2692 $myFname = 'DatabaseBase::deadlockLoop';
2695 $args = func_get_args();
2696 $function = array_shift( $args );
2697 $oldIgnore = $this->ignoreErrors( true );
2698 $tries = DEADLOCK_TRIES
;
2700 if ( is_array( $function ) ) {
2701 $fname = $function[0];
2707 $retVal = call_user_func_array( $function, $args );
2708 $error = $this->lastError();
2709 $errno = $this->lastErrno();
2710 $sql = $this->lastQuery();
2713 if ( $this->wasDeadlock() ) {
2715 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2717 $this->reportQueryError( $error, $errno, $sql, $fname );
2720 } while ( $this->wasDeadlock() && --$tries > 0 );
2722 $this->ignoreErrors( $oldIgnore );
2724 if ( $tries <= 0 ) {
2725 $this->rollback( $myFname );
2726 $this->reportQueryError( $error, $errno, $sql, $fname );
2729 $this->commit( $myFname );
2735 * Wait for the slave to catch up to a given master position.
2737 * @param $pos DBMasterPos object
2738 * @param $timeout Integer: the maximum number of seconds to wait for
2741 * @return An integer: zero if the slave was past that position already,
2742 * greater than zero if we waited for some period of time, less than
2743 * zero if we timed out.
2745 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2746 $fname = 'DatabaseBase::masterPosWait';
2747 wfProfileIn( $fname );
2749 if ( !is_null( $this->mFakeSlaveLag
) ) {
2750 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2752 if ( $wait > $timeout * 1e6
) {
2753 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2754 wfProfileOut( $fname );
2756 } elseif ( $wait > 0 ) {
2757 wfDebug( "Fake slave waiting $wait us\n" );
2759 wfProfileOut( $fname );
2762 wfDebug( "Fake slave up to date ($wait us)\n" );
2763 wfProfileOut( $fname );
2768 wfProfileOut( $fname );
2770 # Real waits are implemented in the subclass.
2775 * Get the replication position of this slave
2777 * @return DBMasterPos, or false if this is not a slave.
2779 function getSlavePos() {
2780 if ( !is_null( $this->mFakeSlaveLag
) ) {
2781 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2782 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2791 * Get the position of this master
2793 * @return DBMasterPos, or false if this is not a master
2795 function getMasterPos() {
2796 if ( $this->mFakeMaster
) {
2797 return new MySQLMasterPos( 'fake', microtime( true ) );
2804 * Begin a transaction, committing any previously open transaction
2806 * @param $fname string
2808 function begin( $fname = 'DatabaseBase::begin' ) {
2809 $this->query( 'BEGIN', $fname );
2810 $this->mTrxLevel
= 1;
2816 * @param $fname string
2818 function commit( $fname = 'DatabaseBase::commit' ) {
2819 if ( $this->mTrxLevel
) {
2820 $this->query( 'COMMIT', $fname );
2821 $this->mTrxLevel
= 0;
2826 * Rollback a transaction.
2827 * No-op on non-transactional databases.
2829 * @param $fname string
2831 function rollback( $fname = 'DatabaseBase::rollback' ) {
2832 if ( $this->mTrxLevel
) {
2833 $this->query( 'ROLLBACK', $fname, true );
2834 $this->mTrxLevel
= 0;
2839 * Creates a new table with structure copied from existing table
2840 * Note that unlike most database abstraction functions, this function does not
2841 * automatically append database prefix, because it works at a lower
2842 * abstraction level.
2843 * The table names passed to this function shall not be quoted (this
2844 * function calls addIdentifierQuotes when needed).
2846 * @param $oldName String: name of table whose structure should be copied
2847 * @param $newName String: name of table to be created
2848 * @param $temporary Boolean: whether the new table should be temporary
2849 * @param $fname String: calling function name
2850 * @return Boolean: true if operation was successful
2852 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2853 $fname = 'DatabaseBase::duplicateTableStructure' )
2855 throw new MWException(
2856 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2860 * List all tables on the database
2862 * @param $prefix Only show tables with this prefix, e.g. mw_
2863 * @param $fname String: calling function name
2865 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2866 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2870 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2871 * to the format used for inserting into timestamp fields in this DBMS.
2873 * The result is unquoted, and needs to be passed through addQuotes()
2874 * before it can be included in raw SQL.
2876 * @param $ts string|int
2880 function timestamp( $ts = 0 ) {
2881 return wfTimestamp( TS_MW
, $ts );
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. If
2887 * NULL is input, it is passed through, allowing NULL values to be inserted
2888 * into timestamp fields.
2890 * The result is unquoted, and needs to be passed through addQuotes()
2891 * before it can be included in raw SQL.
2893 * @param $ts string|int
2897 function timestampOrNull( $ts = null ) {
2898 if ( is_null( $ts ) ) {
2901 return $this->timestamp( $ts );
2906 * Take the result from a query, and wrap it in a ResultWrapper if
2907 * necessary. Boolean values are passed through as is, to indicate success
2908 * of write queries or failure.
2910 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2911 * resource, and it was necessary to call this function to convert it to
2912 * a wrapper. Nowadays, raw database objects are never exposed to external
2913 * callers, so this is unnecessary in external code. For compatibility with
2914 * old code, ResultWrapper objects are passed through unaltered.
2916 * @param $result bool|ResultWrapper
2918 * @param bool|ResultWrapper
2920 function resultObject( $result ) {
2921 if ( empty( $result ) ) {
2923 } elseif ( $result instanceof ResultWrapper
) {
2925 } elseif ( $result === true ) {
2926 // Successful write query
2929 return new ResultWrapper( $this, $result );
2934 * Return aggregated value alias
2937 * @param $valuename string
2941 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2946 * Ping the server and try to reconnect if it there is no connection
2948 * @return bool Success or failure
2951 # Stub. Not essential to override.
2956 * Get slave lag. Currently supported only by MySQL.
2958 * Note that this function will generate a fatal error on many
2959 * installations. Most callers should use LoadBalancer::safeGetLag()
2962 * @return Database replication lag in seconds
2965 return intval( $this->mFakeSlaveLag
);
2969 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2973 function maxListLen() {
2978 * Some DBMSs have a special format for inserting into blob fields, they
2979 * don't allow simple quoted strings to be inserted. To insert into such
2980 * a field, pass the data through this function before passing it to
2981 * DatabaseBase::insert().
2983 function encodeBlob( $b ) {
2988 * Some DBMSs return a special placeholder object representing blob fields
2989 * in result objects. Pass the object through this function to return the
2992 function decodeBlob( $b ) {
2997 * Override database's default connection timeout
2999 * @param $timeout Integer in seconds
3001 * @deprecated since 1.19; use setSessionOptions()
3003 public function setTimeout( $timeout ) {
3004 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3008 * Override database's default behavior. $options include:
3009 * 'connTimeout' : Set the connection timeout value in seconds.
3010 * May be useful for very long batch queries such as
3011 * full-wiki dumps, where a single query reads out over
3014 * @param $options Array
3017 public function setSessionOptions( array $options ) {}
3020 * Read and execute SQL commands from a file.
3022 * Returns true on success, error string or exception on failure (depending
3023 * on object's error ignore settings).
3025 * @param $filename String: File name to open
3026 * @param $lineCallback Callback: Optional function called before reading each line
3027 * @param $resultCallback Callback: Optional function called for each MySQL result
3028 * @param $fname String: Calling function name or false if name should be
3029 * generated dynamically using $filename
3031 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3032 wfSuppressWarnings();
3033 $fp = fopen( $filename, 'r' );
3034 wfRestoreWarnings();
3036 if ( false === $fp ) {
3037 throw new MWException( "Could not open \"{$filename}\".\n" );
3041 $fname = __METHOD__
. "( $filename )";
3045 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3047 catch ( MWException
$e ) {
3058 * Get the full path of a patch file. Originally based on archive()
3059 * from updaters.inc. Keep in mind this always returns a patch, as
3060 * it fails back to MySQL if no DB-specific patch can be found
3062 * @param $patch String The name of the patch, like patch-something.sql
3063 * @return String Full path to patch file
3065 public function patchPath( $patch ) {
3068 $dbType = $this->getType();
3069 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3070 return "$IP/maintenance/$dbType/archives/$patch";
3072 return "$IP/maintenance/archives/$patch";
3077 * Set variables to be used in sourceFile/sourceStream, in preference to the
3078 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3079 * all. If it's set to false, $GLOBALS will be used.
3081 * @param $vars False, or array mapping variable name to value.
3083 function setSchemaVars( $vars ) {
3084 $this->mSchemaVars
= $vars;
3088 * Read and execute commands from an open file handle.
3090 * Returns true on success, error string or exception on failure (depending
3091 * on object's error ignore settings).
3093 * @param $fp Resource: File handle
3094 * @param $lineCallback Callback: Optional function called before reading each line
3095 * @param $resultCallback Callback: Optional function called for each MySQL result
3096 * @param $fname String: Calling function name
3098 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3099 $fname = 'DatabaseBase::sourceStream' )
3103 $dollarquote = false;
3105 while ( ! feof( $fp ) ) {
3106 if ( $lineCallback ) {
3107 call_user_func( $lineCallback );
3110 $line = trim( fgets( $fp ) );
3111 $sl = strlen( $line ) - 1;
3117 if ( '-' == $line[0] && '-' == $line[1] ) {
3121 # # Allow dollar quoting for function declarations
3122 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3123 if ( $dollarquote ) {
3124 $dollarquote = false;
3128 $dollarquote = true;
3131 elseif ( !$dollarquote ) {
3132 if ( ';' == $line[$sl] && ( $sl < 2 ||
';' != $line[$sl - 1] ) ) {
3134 $line = substr( $line, 0, $sl );
3145 $cmd = str_replace( ';;', ";", $cmd );
3146 $cmd = $this->replaceVars( $cmd );
3147 $res = $this->query( $cmd, $fname );
3149 if ( $resultCallback ) {
3150 call_user_func( $resultCallback, $res, $this );
3153 if ( false === $res ) {
3154 $err = $this->lastError();
3155 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3167 * Database independent variable replacement. Replaces a set of variables
3168 * in an SQL statement with their contents as given by $this->getSchemaVars().
3170 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3172 * - '{$var}' should be used for text and is passed through the database's
3174 * - `{$var}` should be used for identifiers (eg: table and database names),
3175 * it is passed through the database's addIdentifierQuotes method which
3176 * can be overridden if the database uses something other than backticks.
3177 * - / *$var* / is just encoded, besides traditional table prefix and
3178 * table options its use should be avoided.
3180 * @param $ins String: SQL statement to replace variables in
3181 * @return String The new SQL statement with variables replaced
3183 protected function replaceSchemaVars( $ins ) {
3184 $vars = $this->getSchemaVars();
3185 foreach ( $vars as $var => $value ) {
3187 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3189 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3191 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3197 * Replace variables in sourced SQL
3199 * @param $ins string
3203 protected function replaceVars( $ins ) {
3204 $ins = $this->replaceSchemaVars( $ins );
3207 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3208 array( $this, 'tableNameCallback' ), $ins );
3211 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3212 array( $this, 'indexNameCallback' ), $ins );
3218 * Get schema variables. If none have been set via setSchemaVars(), then
3219 * 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
3335 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3336 if( !$this->tableExists( $tableName, $fName ) ) {
3339 $sql = "DROP TABLE " . $this->tableName( $tableName );
3340 if( $this->cascadingDeletes() ) {
3343 return $this->query( $sql, $fName );
3347 * Get search engine class. All subclasses of this need to implement this
3348 * if they wish to use searching.
3352 public function getSearchEngine() {
3353 return 'SearchEngineDummy';
3357 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3358 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3359 * because "i" sorts after all numbers.
3363 public function getInfinity() {
3368 * Encode an expiry time
3370 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3373 public function encodeExpiry( $expiry ) {
3374 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3375 return $this->getInfinity();
3377 return $this->timestamp( $expiry );
3382 * Allow or deny "big selects" for this session only. This is done by setting
3383 * the sql_big_selects session variable.
3385 * This is a MySQL-specific feature.
3387 * @param $value Mixed: true for allow, false for deny, or "default" to
3388 * restore the initial value
3390 public function setBigSelects( $value = true ) {