5ac0c2420b91bb602be51f8707f6955153eb9149
3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * Fetch the next row from the given result object, in object form.
47 * Fields can be retrieved with $row->fieldname, with fields acting like
50 * @param $res ResultWrapper|object as returned from DatabaseBase::query(), etc.
52 * @throws DBUnexpectedError Thrown if the database returns an error
54 function fetchObject( $res );
57 * Fetch the next row from the given result object, in associative array
58 * form. Fields are retrieved with $row['fieldname'].
60 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchRow( $res );
67 * Get the number of rows in a result object
69 * @param $res Mixed: A SQL result
72 function numRows( $res );
75 * Get the number of fields in a result object
76 * @see http://www.php.net/mysql_num_fields
78 * @param $res Mixed: A SQL result
81 function numFields( $res );
84 * Get a field name in a result object
85 * @see http://www.php.net/mysql_field_name
87 * @param $res Mixed: A SQL result
91 function fieldName( $res, $n );
94 * Get the inserted value of an auto-increment row
96 * The value inserted should be fetched from nextSequenceValue()
99 * $id = $dbw->nextSequenceValue('page_page_id_seq');
100 * $dbw->insert('page',array('page_id' => $id));
101 * $id = $dbw->insertId();
108 * Change the position of the cursor in a result object
109 * @see http://www.php.net/mysql_data_seek
111 * @param $res Mixed: A SQL result
112 * @param $row Mixed: Either MySQL row or ResultWrapper
114 function dataSeek( $res, $row );
117 * Get the last error number
118 * @see http://www.php.net/mysql_errno
122 function lastErrno();
125 * Get a description of the last error
126 * @see http://www.php.net/mysql_error
130 function lastError();
133 * mysql_fetch_field() wrapper
134 * Returns false if the field doesn't exist
136 * @param $table string: table name
137 * @param $field string: field name
141 function fieldInfo( $table, $field );
144 * Get information about an index into an object
145 * @param $table string: Table name
146 * @param $index string: Index name
147 * @param $fname string: Calling function name
148 * @return Mixed: Database-specific index description class or false if the index does not exist
150 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info().
182 * @return string: Version information from the database server.
184 function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 function getServerInfo();
197 * Database abstraction object
200 abstract class DatabaseBase
implements DatabaseType
{
202 # ------------------------------------------------------------------------------
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mDBname;
215 protected $mConn = null;
216 protected $mOpened = false;
218 protected $mTablePrefix;
220 protected $mTrxLevel = 0;
221 protected $mErrorCount = 0;
222 protected $mLBInfo = array();
223 protected $mFakeSlaveLag = null, $mFakeMaster = false;
224 protected $mDefaultBigSelects = null;
225 protected $mSchemaVars = false;
227 protected $preparedArgs;
229 protected $htmlErrors;
231 protected $delimiter = ';';
233 # ------------------------------------------------------------------------------
235 # ------------------------------------------------------------------------------
236 # These optionally set a variable and return the previous state
239 * A string describing the current software version, and possibly
240 * other details in a user-friendly way. Will be listed on Special:Version, etc.
241 * Use getServerVersion() to get machine-friendly information.
243 * @return string: Version information from the database server
245 public function getServerInfo() {
246 return $this->getServerVersion();
250 * Boolean, controls output of large amounts of debug information.
251 * @param $debug bool|null
252 * - true to enable debugging
253 * - false to disable debugging
254 * - omitted or null to do nothing
256 * @return The previous value of the flag
258 function debug( $debug = null ) {
259 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
263 * Turns buffering of SQL result sets on (true) or off (false). Default is
266 * Unbuffered queries are very troublesome in MySQL:
268 * - If another query is executed while the first query is being read
269 * out, the first query is killed. This means you can't call normal
270 * MediaWiki functions while you are reading an unbuffered query result
271 * from a normal wfGetDB() connection.
273 * - Unbuffered queries cause the MySQL server to use large amounts of
274 * memory and to hold broad locks which block other queries.
276 * If you want to limit client-side memory, it's almost always better to
277 * split up queries into batches using a LIMIT clause than to switch off
280 * @param $buffer null|bool
282 * @return The previous value of the flag
284 function bufferResults( $buffer = null ) {
285 if ( is_null( $buffer ) ) {
286 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
288 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
293 * Turns on (false) or off (true) the automatic generation and sending
294 * of a "we're sorry, but there has been a database error" page on
295 * database errors. Default is on (false). When turned off, the
296 * code should use lastErrno() and lastError() to handle the
297 * situation as appropriate.
299 * @param $ignoreErrors bool|null
301 * @return bool The previous value of the flag.
303 function ignoreErrors( $ignoreErrors = null ) {
304 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
308 * Gets or sets the current transaction level.
310 * Historically, transactions were allowed to be "nested". This is no
311 * longer supported, so this function really only returns a boolean.
313 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
314 * @return The previous value
316 function trxLevel( $level = null ) {
317 return wfSetVar( $this->mTrxLevel
, $level );
321 * Get/set the number of errors logged. Only useful when errors are ignored
322 * @param $count The count to set, or omitted to leave it unchanged.
323 * @return The error count
325 function errorCount( $count = null ) {
326 return wfSetVar( $this->mErrorCount
, $count );
330 * Get/set the table prefix.
331 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
332 * @return The previous table prefix.
334 function tablePrefix( $prefix = null ) {
335 return wfSetVar( $this->mTablePrefix
, $prefix );
339 * Get properties passed down from the server info array of the load
342 * @param $name string The entry of the info array to get, or null to get the
345 * @return LoadBalancer|null
347 function getLBInfo( $name = null ) {
348 if ( is_null( $name ) ) {
349 return $this->mLBInfo
;
351 if ( array_key_exists( $name, $this->mLBInfo
) ) {
352 return $this->mLBInfo
[$name];
360 * Set the LB info array, or a member of it. If called with one parameter,
361 * the LB info array is set to that parameter. If it is called with two
362 * parameters, the member with the given name is set to the given value.
367 function setLBInfo( $name, $value = null ) {
368 if ( is_null( $value ) ) {
369 $this->mLBInfo
= $name;
371 $this->mLBInfo
[$name] = $value;
376 * Set lag time in seconds for a fake slave
380 function setFakeSlaveLag( $lag ) {
381 $this->mFakeSlaveLag
= $lag;
385 * Make this connection a fake master
387 * @param $enabled bool
389 function setFakeMaster( $enabled = true ) {
390 $this->mFakeMaster
= $enabled;
394 * Returns true if this database supports (and uses) cascading deletes
398 function cascadingDeletes() {
403 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
407 function cleanupTriggers() {
412 * Returns true if this database is strict about what can be put into an IP field.
413 * Specifically, it uses a NULL value instead of an empty string.
417 function strictIPs() {
422 * Returns true if this database uses timestamps rather than integers
426 function realTimestamps() {
431 * Returns true if this database does an implicit sort when doing GROUP BY
435 function implicitGroupby() {
440 * Returns true if this database does an implicit order by when the column has an index
441 * For example: SELECT page_title FROM page LIMIT 1
445 function implicitOrderby() {
450 * Returns true if this database requires that SELECT DISTINCT queries require that all
451 ORDER BY expressions occur in the SELECT list per the SQL92 standard
455 function standardSelectDistinct() {
460 * Returns true if this database can do a native search on IP columns
461 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
465 function searchableIPs() {
470 * Returns true if this database can use functional indexes
474 function functionalIndexes() {
479 * Return the last query that went through DatabaseBase::query()
482 function lastQuery() {
483 return $this->mLastQuery
;
487 * Returns true if the connection may have been used for write queries.
488 * Should return true if unsure.
492 function doneWrites() {
493 return $this->mDoneWrites
;
497 * Is a connection to the database open?
501 return $this->mOpened
;
505 * Set a flag for this connection
507 * @param $flag Integer: DBO_* constants from Defines.php:
508 * - DBO_DEBUG: output some debug info (same as debug())
509 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
510 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
511 * - DBO_TRX: automatically start transactions
512 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
513 * and removes it in command line mode
514 * - DBO_PERSISTENT: use persistant database connection
516 function setFlag( $flag ) {
517 $this->mFlags |
= $flag;
521 * Clear a flag for this connection
523 * @param $flag: same as setFlag()'s $flag param
525 function clearFlag( $flag ) {
526 $this->mFlags
&= ~
$flag;
530 * Returns a boolean whether the flag $flag is set for this connection
532 * @param $flag: same as setFlag()'s $flag param
535 function getFlag( $flag ) {
536 return !!( $this->mFlags
& $flag );
540 * General read-only accessor
542 * @param $name string
546 function getProperty( $name ) {
553 function getWikiID() {
554 if ( $this->mTablePrefix
) {
555 return "{$this->mDBname}-{$this->mTablePrefix}";
557 return $this->mDBname
;
562 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
566 public function getSchemaPath() {
568 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
569 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
571 return "$IP/maintenance/tables.sql";
575 # ------------------------------------------------------------------------------
577 # ------------------------------------------------------------------------------
581 * @param $server String: database server host
582 * @param $user String: database user name
583 * @param $password String: database user password
584 * @param $dbName String: database name
586 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
588 function __construct( $server = false, $user = false, $password = false, $dbName = false,
589 $flags = 0, $tablePrefix = 'get from global'
591 global $wgDBprefix, $wgCommandLineMode;
593 $this->mFlags
= $flags;
595 if ( $this->mFlags
& DBO_DEFAULT
) {
596 if ( $wgCommandLineMode ) {
597 $this->mFlags
&= ~DBO_TRX
;
599 $this->mFlags |
= DBO_TRX
;
603 /** Get the default table prefix*/
604 if ( $tablePrefix == 'get from global' ) {
605 $this->mTablePrefix
= $wgDBprefix;
607 $this->mTablePrefix
= $tablePrefix;
611 $this->open( $server, $user, $password, $dbName );
616 * Called by serialize. Throw an exception when DB connection is serialized.
617 * This causes problems on some database engines because the connection is
618 * not restored on unserialize.
620 public function __sleep() {
621 throw new MWException( 'Database serialization may cause problems, since the connection is not restored on wakeup.' );
625 * Same as new DatabaseMysql( ... ), kept for backward compatibility
626 * @deprecated since 1.17
633 * @return DatabaseMysql
635 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
636 wfDeprecated( __METHOD__
, '1.17' );
637 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
641 * Same as new factory( ... ), kept for backward compatibility
642 * @deprecated since 1.18
643 * @see Database::factory()
645 public final static function newFromType( $dbType, $p = array() ) {
646 wfDeprecated( __METHOD__
, '1.18' );
647 if ( isset( $p['tableprefix'] ) ) {
648 $p['tablePrefix'] = $p['tableprefix'];
650 return self
::factory( $dbType, $p );
654 * Given a DB type, construct the name of the appropriate child class of
655 * DatabaseBase. This is designed to replace all of the manual stuff like:
656 * $class = 'Database' . ucfirst( strtolower( $type ) );
657 * as well as validate against the canonical list of DB types we have
659 * This factory function is mostly useful for when you need to connect to a
660 * database other than the MediaWiki default (such as for external auth,
661 * an extension, et cetera). Do not use this to connect to the MediaWiki
662 * database. Example uses in core:
663 * @see LoadBalancer::reallyOpenConnection()
664 * @see ExternalUser_MediaWiki::initFromCond()
665 * @see ForeignDBRepo::getMasterDB()
666 * @see WebInstaller_DBConnect::execute()
668 * @param $dbType String A possible DB type
669 * @param $p Array An array of options to pass to the constructor.
670 * Valid options are: host, user, password, dbname, flags, tablePrefix
671 * @return DatabaseBase subclass or null
673 public final static function factory( $dbType, $p = array() ) {
674 $canonicalDBTypes = array(
675 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
677 $dbType = strtolower( $dbType );
678 $class = 'Database' . ucfirst( $dbType );
680 if( in_array( $dbType, $canonicalDBTypes ) ) {
682 isset( $p['host'] ) ?
$p['host'] : false,
683 isset( $p['user'] ) ?
$p['user'] : false,
684 isset( $p['password'] ) ?
$p['password'] : false,
685 isset( $p['dbname'] ) ?
$p['dbname'] : false,
686 isset( $p['flags'] ) ?
$p['flags'] : 0,
687 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
689 } elseif ( class_exists( $class ) && is_subclass_of( $class, 'DatabaseBase' ) ) {
690 return new $class( $p );
696 protected function installErrorHandler() {
697 $this->mPHPError
= false;
698 $this->htmlErrors
= ini_set( 'html_errors', '0' );
699 set_error_handler( array( $this, 'connectionErrorHandler' ) );
703 * @return bool|string
705 protected function restoreErrorHandler() {
706 restore_error_handler();
707 if ( $this->htmlErrors
!== false ) {
708 ini_set( 'html_errors', $this->htmlErrors
);
710 if ( $this->mPHPError
) {
711 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
712 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
723 protected function connectionErrorHandler( $errno, $errstr ) {
724 $this->mPHPError
= $errstr;
728 * Closes a database connection.
729 * if it is open : commits any open transactions
731 * @return Bool operation success. true if already closed.
734 # Stub, should probably be overridden
739 * @param $error String: fallback error message, used if none is given by DB
741 function reportConnectionError( $error = 'Unknown error' ) {
742 $myError = $this->lastError();
748 throw new DBConnectionError( $this, $error );
752 * The DBMS-dependent part of query()
754 * @param $sql String: SQL query.
755 * @return ResultWrapper Result object to feed to fetchObject, fetchRow, ...; or false on failure
757 protected abstract function doQuery( $sql );
760 * Determine whether a query writes to the DB.
761 * Should return true if unsure.
767 function isWriteQuery( $sql ) {
768 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
772 * Run an SQL query and return the result. Normally throws a DBQueryError
773 * on failure. If errors are ignored, returns false instead.
775 * In new code, the query wrappers select(), insert(), update(), delete(),
776 * etc. should be used where possible, since they give much better DBMS
777 * independence and automatically quote or validate user input in a variety
778 * of contexts. This function is generally only useful for queries which are
779 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
782 * However, the query wrappers themselves should call this function.
784 * @param $sql String: SQL query
785 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
786 * comment (you can use __METHOD__ or add some extra info)
787 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
788 * maybe best to catch the exception instead?
789 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
790 * for a successful read query, or false on failure if $tempIgnore set
791 * @throws DBQueryError Thrown when the database returns an error of any kind
793 public function query( $sql, $fname = '', $tempIgnore = false ) {
794 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
795 if ( !Profiler
::instance()->isStub() ) {
796 # generalizeSQL will probably cut down the query to reasonable
797 # logging size most of the time. The substr is really just a sanity check.
800 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
801 $totalProf = 'DatabaseBase::query-master';
803 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
804 $totalProf = 'DatabaseBase::query';
807 wfProfileIn( $totalProf );
808 wfProfileIn( $queryProf );
811 $this->mLastQuery
= $sql;
812 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
813 # Set a flag indicating that writes have been done
814 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
815 $this->mDoneWrites
= true;
818 # Add a comment for easy SHOW PROCESSLIST interpretation
820 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
821 $userName = $wgUser->getName();
822 if ( mb_strlen( $userName ) > 15 ) {
823 $userName = mb_substr( $userName, 0, 15 ) . '...';
825 $userName = str_replace( '/', '', $userName );
829 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
831 # If DBO_TRX is set, start a transaction
832 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
833 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
834 # avoid establishing transactions for SHOW and SET statements too -
835 # that would delay transaction initializations to once connection
836 # is really used by application
837 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
838 if ( strpos( $sqlstart, "SHOW " ) !== 0 && strpos( $sqlstart, "SET " ) !== 0 )
839 $this->begin( __METHOD__
. " ($fname)" );
842 if ( $this->debug() ) {
846 $sqlx = substr( $commentedSql, 0, 500 );
847 $sqlx = strtr( $sqlx, "\t\n", ' ' );
849 $master = $isMaster ?
'master' : 'slave';
850 wfDebug( "Query {$this->mDBname} ($cnt) ($master): $sqlx\n" );
853 if ( istainted( $sql ) & TC_MYSQL
) {
854 throw new MWException( 'Tainted query found' );
857 $queryId = MWDebug
::query( $sql, $fname, $isMaster );
859 # Do the query and handle errors
860 $ret = $this->doQuery( $commentedSql );
862 MWDebug
::queryTime( $queryId );
864 # Try reconnecting if the connection was lost
865 if ( false === $ret && $this->wasErrorReissuable() ) {
866 # Transaction is gone, like it or not
867 $this->mTrxLevel
= 0;
868 wfDebug( "Connection lost, reconnecting...\n" );
870 if ( $this->ping() ) {
871 wfDebug( "Reconnected\n" );
872 $sqlx = substr( $commentedSql, 0, 500 );
873 $sqlx = strtr( $sqlx, "\t\n", ' ' );
874 global $wgRequestTime;
875 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
876 if ( $elapsed < 300 ) {
877 # Not a database error to lose a transaction after a minute or two
878 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
880 $ret = $this->doQuery( $commentedSql );
882 wfDebug( "Failed\n" );
886 if ( false === $ret ) {
887 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
890 if ( !Profiler
::instance()->isStub() ) {
891 wfProfileOut( $queryProf );
892 wfProfileOut( $totalProf );
895 return $this->resultObject( $ret );
899 * Report a query error. Log the error, and if neither the object ignore
900 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
902 * @param $error String
903 * @param $errno Integer
905 * @param $fname String
906 * @param $tempIgnore Boolean
908 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
909 # Ignore errors during error handling to avoid infinite recursion
910 $ignore = $this->ignoreErrors( true );
911 ++
$this->mErrorCount
;
913 if ( $ignore ||
$tempIgnore ) {
914 wfDebug( "SQL ERROR (ignored): $error\n" );
915 $this->ignoreErrors( $ignore );
917 $sql1line = str_replace( "\n", "\\n", $sql );
918 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
919 wfDebug( "SQL ERROR: " . $error . "\n" );
920 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
925 * Intended to be compatible with the PEAR::DB wrapper functions.
926 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
928 * ? = scalar value, quoted as necessary
929 * ! = raw SQL bit (a function for instance)
930 * & = filename; reads the file and inserts as a blob
931 * (we don't use this though...)
933 * This function should not be used directly by new code outside of the
934 * database classes. The query wrapper functions (select() etc.) should be
938 * @param $func string
942 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
943 /* MySQL doesn't support prepared statements (yet), so just
944 pack up the query for reference. We'll manually replace
946 return array( 'query' => $sql, 'func' => $func );
950 * Free a prepared query, generated by prepare().
953 function freePrepared( $prepared ) {
954 /* No-op by default */
958 * Execute a prepared query with the various arguments
959 * @param $prepared String: the prepared sql
960 * @param $args Mixed: Either an array here, or put scalars as varargs
962 * @return ResultWrapper
964 function execute( $prepared, $args = null ) {
965 if ( !is_array( $args ) ) {
967 $args = func_get_args();
968 array_shift( $args );
971 $sql = $this->fillPrepared( $prepared['query'], $args );
973 return $this->query( $sql, $prepared['func'] );
977 * Prepare & execute an SQL statement, quoting and inserting arguments
978 * in the appropriate places.
980 * This function should not be used directly by new code outside of the
981 * database classes. The query wrapper functions (select() etc.) should be
984 * @param $query String
987 * @return ResultWrapper
989 function safeQuery( $query, $args = null ) {
990 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
992 if ( !is_array( $args ) ) {
994 $args = func_get_args();
995 array_shift( $args );
998 $retval = $this->execute( $prepared, $args );
999 $this->freePrepared( $prepared );
1005 * For faking prepared SQL statements on DBs that don't support
1007 * @param $preparedQuery String: a 'preparable' SQL statement
1008 * @param $args Array of arguments to fill it with
1009 * @return string executable SQL
1011 function fillPrepared( $preparedQuery, $args ) {
1013 $this->preparedArgs
=& $args;
1015 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
1016 array( &$this, 'fillPreparedArg' ), $preparedQuery );
1020 * preg_callback func for fillPrepared()
1021 * The arguments should be in $this->preparedArgs and must not be touched
1022 * while we're doing this.
1024 * @param $matches Array
1027 function fillPreparedArg( $matches ) {
1028 switch( $matches[1] ) {
1029 case '\\?': return '?';
1030 case '\\!': return '!';
1031 case '\\&': return '&';
1034 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
1036 switch( $matches[1] ) {
1037 case '?': return $this->addQuotes( $arg );
1038 case '!': return $arg;
1040 # return $this->addQuotes( file_get_contents( $arg ) );
1041 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
1043 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1048 * Free a result object returned by query() or select(). It's usually not
1049 * necessary to call this, just use unset() or let the variable holding
1050 * the result object go out of scope.
1052 * @param $res Mixed: A SQL result
1054 function freeResult( $res ) {
1058 * Simple UPDATE wrapper.
1059 * Usually throws a DBQueryError on failure.
1060 * If errors are explicitly ignored, returns success
1062 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1063 * calling convention and feature set
1065 * @param $table string
1069 * @param $fname string
1073 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1074 $table = $this->tableName( $table );
1075 $sql = "UPDATE $table SET $var = '" .
1076 $this->strencode( $value ) . "' WHERE ($cond)";
1078 return (bool)$this->query( $sql, $fname );
1082 * A SELECT wrapper which returns a single field from a single result row.
1084 * Usually throws a DBQueryError on failure. If errors are explicitly
1085 * ignored, returns false on failure.
1087 * If no result rows are returned from the query, false is returned.
1089 * @param $table string|array Table name. See DatabaseBase::select() for details.
1090 * @param $var string The field name to select. This must be a valid SQL
1091 * fragment: do not use unvalidated user input.
1092 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1093 * @param $fname string The function name of the caller.
1094 * @param $options string|array The query options. See DatabaseBase::select() for details.
1096 * @return false|mixed The value from the field, or false on failure.
1098 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1099 $options = array() )
1101 if ( !is_array( $options ) ) {
1102 $options = array( $options );
1105 $options['LIMIT'] = 1;
1107 $res = $this->select( $table, $var, $cond, $fname, $options );
1109 if ( $res === false ||
!$this->numRows( $res ) ) {
1113 $row = $this->fetchRow( $res );
1115 if ( $row !== false ) {
1116 return reset( $row );
1123 * Returns an optional USE INDEX clause to go after the table, and a
1124 * string to go at the end of the query.
1126 * @param $options Array: associative array of options to be turned into
1127 * an SQL query, valid keys are listed in the function.
1129 * @see DatabaseBase::select()
1131 function makeSelectOptions( $options ) {
1132 $preLimitTail = $postLimitTail = '';
1135 $noKeyOptions = array();
1137 foreach ( $options as $key => $option ) {
1138 if ( is_numeric( $key ) ) {
1139 $noKeyOptions[$option] = true;
1143 if ( isset( $options['GROUP BY'] ) ) {
1144 $gb = is_array( $options['GROUP BY'] )
1145 ?
implode( ',', $options['GROUP BY'] )
1146 : $options['GROUP BY'];
1147 $preLimitTail .= " GROUP BY {$gb}";
1150 if ( isset( $options['HAVING'] ) ) {
1151 $preLimitTail .= " HAVING {$options['HAVING']}";
1154 if ( isset( $options['ORDER BY'] ) ) {
1155 $ob = is_array( $options['ORDER BY'] )
1156 ?
implode( ',', $options['ORDER BY'] )
1157 : $options['ORDER BY'];
1158 $preLimitTail .= " ORDER BY {$ob}";
1161 // if (isset($options['LIMIT'])) {
1162 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1163 // isset($options['OFFSET']) ? $options['OFFSET']
1167 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1168 $postLimitTail .= ' FOR UPDATE';
1171 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1172 $postLimitTail .= ' LOCK IN SHARE MODE';
1175 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1176 $startOpts .= 'DISTINCT';
1179 # Various MySQL extensions
1180 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1181 $startOpts .= ' /*! STRAIGHT_JOIN */';
1184 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1185 $startOpts .= ' HIGH_PRIORITY';
1188 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1189 $startOpts .= ' SQL_BIG_RESULT';
1192 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1193 $startOpts .= ' SQL_BUFFER_RESULT';
1196 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1197 $startOpts .= ' SQL_SMALL_RESULT';
1200 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1201 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1204 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1205 $startOpts .= ' SQL_CACHE';
1208 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1209 $startOpts .= ' SQL_NO_CACHE';
1212 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1213 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1218 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1222 * Execute a SELECT query constructed using the various parameters provided.
1223 * See below for full details of the parameters.
1225 * @param $table String|Array Table name
1226 * @param $vars String|Array Field names
1227 * @param $conds String|Array Conditions
1228 * @param $fname String Caller function name
1229 * @param $options Array Query options
1230 * @param $join_conds Array Join conditions
1232 * @param $table string|array
1234 * May be either an array of table names, or a single string holding a table
1235 * name. If an array is given, table aliases can be specified, for example:
1237 * array( 'a' => 'user' )
1239 * This includes the user table in the query, with the alias "a" available
1240 * for use in field names (e.g. a.user_name).
1242 * All of the table names given here are automatically run through
1243 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1244 * added, and various other table name mappings to be performed.
1247 * @param $vars string|array
1249 * May be either a field name or an array of field names. The field names
1250 * here are complete fragments of SQL, for direct inclusion into the SELECT
1251 * query. Expressions and aliases may be specified as in SQL, for example:
1253 * array( 'MAX(rev_id) AS maxrev' )
1255 * If an expression is given, care must be taken to ensure that it is
1259 * @param $conds string|array
1261 * May be either a string containing a single condition, or an array of
1262 * conditions. If an array is given, the conditions constructed from each
1263 * element are combined with AND.
1265 * Array elements may take one of two forms:
1267 * - Elements with a numeric key are interpreted as raw SQL fragments.
1268 * - Elements with a string key are interpreted as equality conditions,
1269 * where the key is the field name.
1270 * - If the value of such an array element is a scalar (such as a
1271 * string), it will be treated as data and thus quoted appropriately.
1272 * If it is null, an IS NULL clause will be added.
1273 * - If the value is an array, an IN(...) clause will be constructed,
1274 * such that the field name may match any of the elements in the
1275 * array. The elements of the array will be quoted.
1277 * Note that expressions are often DBMS-dependent in their syntax.
1278 * DBMS-independent wrappers are provided for constructing several types of
1279 * expression commonly used in condition queries. See:
1280 * - DatabaseBase::buildLike()
1281 * - DatabaseBase::conditional()
1284 * @param $options string|array
1286 * Optional: Array of query options. Boolean options are specified by
1287 * including them in the array as a string value with a numeric key, for
1290 * array( 'FOR UPDATE' )
1292 * The supported options are:
1294 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1295 * with LIMIT can theoretically be used for paging through a result set,
1296 * but this is discouraged in MediaWiki for performance reasons.
1298 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1299 * and then the first rows are taken until the limit is reached. LIMIT
1300 * is applied to a result set after OFFSET.
1302 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1303 * changed until the next COMMIT.
1305 * - DISTINCT: Boolean: return only unique result rows.
1307 * - GROUP BY: May be either an SQL fragment string naming a field or
1308 * expression to group by, or an array of such SQL fragments.
1310 * - HAVING: A string containing a HAVING clause.
1312 * - ORDER BY: May be either an SQL fragment giving a field name or
1313 * expression to order by, or an array of such SQL fragments.
1315 * - USE INDEX: This may be either a string giving the index name to use
1316 * for the query, or an array. If it is an associative array, each key
1317 * gives the table name (or alias), each value gives the index name to
1318 * use for that table. All strings are SQL fragments and so should be
1319 * validated by the caller.
1321 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1322 * instead of SELECT.
1324 * And also the following boolean MySQL extensions, see the MySQL manual
1325 * for documentation:
1327 * - LOCK IN SHARE MODE
1331 * - SQL_BUFFER_RESULT
1332 * - SQL_SMALL_RESULT
1333 * - SQL_CALC_FOUND_ROWS
1338 * @param $join_conds string|array
1340 * Optional associative array of table-specific join conditions. In the
1341 * most common case, this is unnecessary, since the join condition can be
1342 * in $conds. However, it is useful for doing a LEFT JOIN.
1344 * The key of the array contains the table name or alias. The value is an
1345 * array with two elements, numbered 0 and 1. The first gives the type of
1346 * join, the second is an SQL fragment giving the join condition for that
1347 * table. For example:
1349 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1351 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1352 * with no rows in it will be returned. If there was a query error, a
1353 * DBQueryError exception will be thrown, except if the "ignore errors"
1354 * option was set, in which case false will be returned.
1356 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1357 $options = array(), $join_conds = array() ) {
1358 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1360 return $this->query( $sql, $fname );
1364 * The equivalent of DatabaseBase::select() except that the constructed SQL
1365 * is returned, instead of being immediately executed.
1367 * @param $table string|array Table name
1368 * @param $vars string|array Field names
1369 * @param $conds string|array Conditions
1370 * @param $fname string Caller function name
1371 * @param $options string|array Query options
1372 * @param $join_conds string|array Join conditions
1374 * @return SQL query string.
1375 * @see DatabaseBase::select()
1377 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1378 if ( is_array( $vars ) ) {
1379 $vars = implode( ',', $vars );
1382 $options = (array)$options;
1384 if ( is_array( $table ) ) {
1385 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1386 ?
$options['USE INDEX']
1388 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1390 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1392 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1394 } elseif ( $table != '' ) {
1395 if ( $table[0] == ' ' ) {
1396 $from = ' FROM ' . $table;
1398 $from = ' FROM ' . $this->tableName( $table );
1404 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1406 if ( !empty( $conds ) ) {
1407 if ( is_array( $conds ) ) {
1408 $conds = $this->makeList( $conds, LIST_AND
);
1410 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1412 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1415 if ( isset( $options['LIMIT'] ) ) {
1416 $sql = $this->limitResult( $sql, $options['LIMIT'],
1417 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1419 $sql = "$sql $postLimitTail";
1421 if ( isset( $options['EXPLAIN'] ) ) {
1422 $sql = 'EXPLAIN ' . $sql;
1429 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1430 * that a single row object is returned. If the query returns no rows,
1431 * false is returned.
1433 * @param $table string|array Table name
1434 * @param $vars string|array Field names
1435 * @param $conds|array Conditions
1436 * @param $fname string Caller function name
1437 * @param $options string|array Query options
1438 * @param $join_conds array|string Join conditions
1440 * @return ResultWrapper|bool
1442 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1443 $options = array(), $join_conds = array() )
1445 $options['LIMIT'] = 1;
1446 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1448 if ( $res === false ) {
1452 if ( !$this->numRows( $res ) ) {
1456 $obj = $this->fetchObject( $res );
1462 * Estimate rows in dataset.
1464 * MySQL allows you to estimate the number of rows that would be returned
1465 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1466 * index cardinality statistics, and is notoriously inaccurate, especially
1467 * when large numbers of rows have recently been added or deleted.
1469 * For DBMSs that don't support fast result size estimation, this function
1470 * will actually perform the SELECT COUNT(*).
1472 * Takes the same arguments as DatabaseBase::select().
1474 * @param $table String: table name
1475 * @param Array|string $vars : unused
1476 * @param Array|string $conds : filters on the table
1477 * @param $fname String: function name for profiling
1478 * @param $options Array: options for select
1479 * @return Integer: row count
1481 public function estimateRowCount( $table, $vars = '*', $conds = '',
1482 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1485 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1488 $row = $this->fetchRow( $res );
1489 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1496 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1497 * It's only slightly flawed. Don't use for anything important.
1499 * @param $sql String A SQL Query
1503 static function generalizeSQL( $sql ) {
1504 # This does the same as the regexp below would do, but in such a way
1505 # as to avoid crashing php on some large strings.
1506 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1508 $sql = str_replace ( "\\\\", '', $sql );
1509 $sql = str_replace ( "\\'", '', $sql );
1510 $sql = str_replace ( "\\\"", '', $sql );
1511 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1512 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1514 # All newlines, tabs, etc replaced by single space
1515 $sql = preg_replace ( '/\s+/', ' ', $sql );
1518 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1524 * Determines whether a field exists in a table
1526 * @param $table String: table name
1527 * @param $field String: filed to check on that table
1528 * @param $fname String: calling function name (optional)
1529 * @return Boolean: whether $table has filed $field
1531 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1532 $info = $this->fieldInfo( $table, $field );
1538 * Determines whether an index exists
1539 * Usually throws a DBQueryError on failure
1540 * If errors are explicitly ignored, returns NULL on failure
1544 * @param $fname string
1548 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1549 $info = $this->indexInfo( $table, $index, $fname );
1550 if ( is_null( $info ) ) {
1553 return $info !== false;
1558 * Query whether a given table exists
1560 * @param $table string
1561 * @param $fname string
1565 function tableExists( $table, $fname = __METHOD__
) {
1566 $table = $this->tableName( $table );
1567 $old = $this->ignoreErrors( true );
1568 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", $fname );
1569 $this->ignoreErrors( $old );
1575 * mysql_field_type() wrapper
1580 function fieldType( $res, $index ) {
1581 if ( $res instanceof ResultWrapper
) {
1582 $res = $res->result
;
1585 return mysql_field_type( $res, $index );
1589 * Determines if a given index is unique
1591 * @param $table string
1592 * @param $index string
1596 function indexUnique( $table, $index ) {
1597 $indexInfo = $this->indexInfo( $table, $index );
1599 if ( !$indexInfo ) {
1603 return !$indexInfo[0]->Non_unique
;
1607 * Helper for DatabaseBase::insert().
1609 * @param $options array
1612 function makeInsertOptions( $options ) {
1613 return implode( ' ', $options );
1617 * INSERT wrapper, inserts an array into a table.
1621 * - A single associative array. The array keys are the field names, and
1622 * the values are the values to insert. The values are treated as data
1623 * and will be quoted appropriately. If NULL is inserted, this will be
1624 * converted to a database NULL.
1625 * - An array with numeric keys, holding a list of associative arrays.
1626 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1627 * each subarray must be identical to each other, and in the same order.
1629 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1632 * $options is an array of options, with boolean options encoded as values
1633 * with numeric keys, in the same style as $options in
1634 * DatabaseBase::select(). Supported options are:
1636 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1637 * any rows which cause duplicate key errors are not inserted. It's
1638 * possible to determine how many rows were successfully inserted using
1639 * DatabaseBase::affectedRows().
1641 * @param $table String Table name. This will be passed through
1642 * DatabaseBase::tableName().
1643 * @param $a Array of rows to insert
1644 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1645 * @param $options Array of options
1649 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1650 # No rows to insert, easy just return now
1651 if ( !count( $a ) ) {
1655 $table = $this->tableName( $table );
1657 if ( !is_array( $options ) ) {
1658 $options = array( $options );
1661 $options = $this->makeInsertOptions( $options );
1663 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1665 $keys = array_keys( $a[0] );
1668 $keys = array_keys( $a );
1671 $sql = 'INSERT ' . $options .
1672 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1676 foreach ( $a as $row ) {
1682 $sql .= '(' . $this->makeList( $row ) . ')';
1685 $sql .= '(' . $this->makeList( $a ) . ')';
1688 return (bool)$this->query( $sql, $fname );
1692 * Make UPDATE options for the DatabaseBase::update function
1694 * @param $options Array: The options passed to DatabaseBase::update
1697 function makeUpdateOptions( $options ) {
1698 if ( !is_array( $options ) ) {
1699 $options = array( $options );
1704 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1705 $opts[] = $this->lowPriorityOption();
1708 if ( in_array( 'IGNORE', $options ) ) {
1712 return implode( ' ', $opts );
1716 * UPDATE wrapper. Takes a condition array and a SET array.
1718 * @param $table String name of the table to UPDATE. This will be passed through
1719 * DatabaseBase::tableName().
1721 * @param $values Array: An array of values to SET. For each array element,
1722 * the key gives the field name, and the value gives the data
1723 * to set that field to. The data will be quoted by
1724 * DatabaseBase::addQuotes().
1726 * @param $conds Array: An array of conditions (WHERE). See
1727 * DatabaseBase::select() for the details of the format of
1728 * condition arrays. Use '*' to update all rows.
1730 * @param $fname String: The function name of the caller (from __METHOD__),
1731 * for logging and profiling.
1733 * @param $options Array: An array of UPDATE options, can be:
1734 * - IGNORE: Ignore unique key conflicts
1735 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1738 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1739 $table = $this->tableName( $table );
1740 $opts = $this->makeUpdateOptions( $options );
1741 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1743 if ( $conds !== array() && $conds !== '*' ) {
1744 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1747 return $this->query( $sql, $fname );
1751 * Makes an encoded list of strings from an array
1752 * @param $a Array containing the data
1753 * @param $mode int Constant
1754 * - LIST_COMMA: comma separated, no field names
1755 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1756 * the documentation for $conds in DatabaseBase::select().
1757 * - LIST_OR: ORed WHERE clause (without the WHERE)
1758 * - LIST_SET: comma separated with field names, like a SET clause
1759 * - LIST_NAMES: comma separated field names
1763 function makeList( $a, $mode = LIST_COMMA
) {
1764 if ( !is_array( $a ) ) {
1765 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1771 foreach ( $a as $field => $value ) {
1773 if ( $mode == LIST_AND
) {
1775 } elseif ( $mode == LIST_OR
) {
1784 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1785 $list .= "($value)";
1786 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1788 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1789 if ( count( $value ) == 0 ) {
1790 throw new MWException( __METHOD__
. ': empty input' );
1791 } elseif ( count( $value ) == 1 ) {
1792 // Special-case single values, as IN isn't terribly efficient
1793 // Don't necessarily assume the single key is 0; we don't
1794 // enforce linear numeric ordering on other arrays here.
1795 $value = array_values( $value );
1796 $list .= $field . " = " . $this->addQuotes( $value[0] );
1798 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1800 } elseif ( $value === null ) {
1801 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1802 $list .= "$field IS ";
1803 } elseif ( $mode == LIST_SET
) {
1804 $list .= "$field = ";
1808 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1809 $list .= "$field = ";
1811 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1819 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1820 * The keys on each level may be either integers or strings.
1822 * @param $data Array: organized as 2-d
1823 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1824 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1825 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1826 * @return Mixed: string SQL fragment, or false if no items in array.
1828 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1831 foreach ( $data as $base => $sub ) {
1832 if ( count( $sub ) ) {
1833 $conds[] = $this->makeList(
1834 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1840 return $this->makeList( $conds, LIST_OR
);
1842 // Nothing to search for...
1848 * Bitwise operations
1855 function bitNot( $field ) {
1861 * @param $fieldRight
1864 function bitAnd( $fieldLeft, $fieldRight ) {
1865 return "($fieldLeft & $fieldRight)";
1870 * @param $fieldRight
1873 function bitOr( $fieldLeft, $fieldRight ) {
1874 return "($fieldLeft | $fieldRight)";
1878 * Change the current database
1880 * @todo Explain what exactly will fail if this is not overridden.
1884 * @return bool Success or failure
1886 function selectDB( $db ) {
1887 # Stub. Shouldn't cause serious problems if it's not overridden, but
1888 # if your database engine supports a concept similar to MySQL's
1889 # databases you may as well.
1890 $this->mDBname
= $db;
1895 * Get the current DB name
1897 function getDBname() {
1898 return $this->mDBname
;
1902 * Get the server hostname or IP address
1904 function getServer() {
1905 return $this->mServer
;
1909 * Format a table name ready for use in constructing an SQL query
1911 * This does two important things: it quotes the table names to clean them up,
1912 * and it adds a table prefix if only given a table name with no quotes.
1914 * All functions of this object which require a table name call this function
1915 * themselves. Pass the canonical name to such functions. This is only needed
1916 * when calling query() directly.
1918 * @param $name String: database table name
1919 * @param $format String One of:
1920 * quoted - Automatically pass the table name through addIdentifierQuotes()
1921 * so that it can be used in a query.
1922 * raw - Do not add identifier quotes to the table name
1923 * @return String: full database name
1925 function tableName( $name, $format = 'quoted' ) {
1926 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1927 # Skip the entire process when we have a string quoted on both ends.
1928 # Note that we check the end so that we will still quote any use of
1929 # use of `database`.table. But won't break things if someone wants
1930 # to query a database table with a dot in the name.
1931 if ( $this->isQuotedIdentifier( $name ) ) {
1935 # Lets test for any bits of text that should never show up in a table
1936 # name. Basically anything like JOIN or ON which are actually part of
1937 # SQL queries, but may end up inside of the table value to combine
1938 # sql. Such as how the API is doing.
1939 # Note that we use a whitespace test rather than a \b test to avoid
1940 # any remote case where a word like on may be inside of a table name
1941 # surrounded by symbols which may be considered word breaks.
1942 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1946 # Split database and table into proper variables.
1947 # We reverse the explode so that database.table and table both output
1948 # the correct table.
1949 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1950 if ( isset( $dbDetails[1] ) ) {
1951 list( $table, $database ) = $dbDetails;
1953 list( $table ) = $dbDetails;
1955 $prefix = $this->mTablePrefix
; # Default prefix
1957 # A database name has been specified in input. We don't want any
1959 if ( isset( $database ) ) {
1963 # Note that we use the long format because php will complain in in_array if
1964 # the input is not an array, and will complain in is_array if it is not set.
1965 if ( !isset( $database ) # Don't use shared database if pre selected.
1966 && isset( $wgSharedDB ) # We have a shared database
1967 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1968 && isset( $wgSharedTables )
1969 && is_array( $wgSharedTables )
1970 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1971 $database = $wgSharedDB;
1972 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1975 # Quote the $database and $table and apply the prefix if not quoted.
1976 if ( isset( $database ) ) {
1977 $database = ( $format == 'quoted' ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1980 $table = "{$prefix}{$table}";
1981 if ( $format == 'quoted' && !$this->isQuotedIdentifier( $table ) ) {
1982 $table = $this->addIdentifierQuotes( "{$table}" );
1985 # Merge our database and table into our final table name.
1986 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1992 * Fetch a number of table names into an array
1993 * This is handy when you need to construct SQL for joins
1996 * extract($dbr->tableNames('user','watchlist'));
1997 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1998 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2002 public function tableNames() {
2003 $inArray = func_get_args();
2006 foreach ( $inArray as $name ) {
2007 $retVal[$name] = $this->tableName( $name );
2014 * Fetch a number of table names into an zero-indexed numerical array
2015 * This is handy when you need to construct SQL for joins
2018 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2019 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2020 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2024 public function tableNamesN() {
2025 $inArray = func_get_args();
2028 foreach ( $inArray as $name ) {
2029 $retVal[] = $this->tableName( $name );
2036 * Get an aliased table name
2037 * e.g. tableName AS newTableName
2039 * @param $name string Table name, see tableName()
2040 * @param $alias string|bool Alias (optional)
2041 * @return string SQL name for aliased table. Will not alias a table to its own name
2043 public function tableNameWithAlias( $name, $alias = false ) {
2044 if ( !$alias ||
$alias == $name ) {
2045 return $this->tableName( $name );
2047 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2052 * Gets an array of aliased table names
2054 * @param $tables array( [alias] => table )
2055 * @return array of strings, see tableNameWithAlias()
2057 public function tableNamesWithAlias( $tables ) {
2059 foreach ( $tables as $alias => $table ) {
2060 if ( is_numeric( $alias ) ) {
2063 $retval[] = $this->tableNameWithAlias( $table, $alias );
2069 * Get the aliased table name clause for a FROM clause
2070 * which might have a JOIN and/or USE INDEX clause
2072 * @param $tables array ( [alias] => table )
2073 * @param $use_index array Same as for select()
2074 * @param $join_conds array Same as for select()
2077 protected function tableNamesWithUseIndexOrJOIN(
2078 $tables, $use_index = array(), $join_conds = array()
2082 $use_index = (array)$use_index;
2083 $join_conds = (array)$join_conds;
2085 foreach ( $tables as $alias => $table ) {
2086 if ( !is_string( $alias ) ) {
2087 // No alias? Set it equal to the table name
2090 // Is there a JOIN clause for this table?
2091 if ( isset( $join_conds[$alias] ) ) {
2092 list( $joinType, $conds ) = $join_conds[$alias];
2093 $tableClause = $joinType;
2094 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2095 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2096 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2098 $tableClause .= ' ' . $use;
2101 $on = $this->makeList( (array)$conds, LIST_AND
);
2103 $tableClause .= ' ON (' . $on . ')';
2106 $retJOIN[] = $tableClause;
2107 // Is there an INDEX clause for this table?
2108 } elseif ( isset( $use_index[$alias] ) ) {
2109 $tableClause = $this->tableNameWithAlias( $table, $alias );
2110 $tableClause .= ' ' . $this->useIndexClause(
2111 implode( ',', (array)$use_index[$alias] ) );
2113 $ret[] = $tableClause;
2115 $tableClause = $this->tableNameWithAlias( $table, $alias );
2117 $ret[] = $tableClause;
2121 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2122 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2123 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2125 // Compile our final table clause
2126 return implode( ' ', array( $straightJoins, $otherJoins ) );
2130 * Get the name of an index in a given table
2136 function indexName( $index ) {
2137 // Backwards-compatibility hack
2139 'ar_usertext_timestamp' => 'usertext_timestamp',
2140 'un_user_id' => 'user_id',
2141 'un_user_ip' => 'user_ip',
2144 if ( isset( $renamed[$index] ) ) {
2145 return $renamed[$index];
2152 * If it's a string, adds quotes and backslashes
2153 * Otherwise returns as-is
2159 function addQuotes( $s ) {
2160 if ( $s === null ) {
2163 # This will also quote numeric values. This should be harmless,
2164 # and protects against weird problems that occur when they really
2165 # _are_ strings such as article titles and string->number->string
2166 # conversion is not 1:1.
2167 return "'" . $this->strencode( $s ) . "'";
2172 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2173 * MySQL uses `backticks` while basically everything else uses double quotes.
2174 * Since MySQL is the odd one out here the double quotes are our generic
2175 * and we implement backticks in DatabaseMysql.
2181 public function addIdentifierQuotes( $s ) {
2182 return '"' . str_replace( '"', '""', $s ) . '"';
2186 * Returns if the given identifier looks quoted or not according to
2187 * the database convention for quoting identifiers .
2189 * @param $name string
2193 public function isQuotedIdentifier( $name ) {
2194 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2198 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2199 * which used quote_ident which does not follow our naming conventions
2200 * was renamed to addIdentifierQuotes.
2201 * @deprecated since 1.18 use addIdentifierQuotes
2207 function quote_ident( $s ) {
2208 wfDeprecated( __METHOD__
, '1.18' );
2209 return $this->addIdentifierQuotes( $s );
2213 * Escape string for safe LIKE usage.
2214 * WARNING: you should almost never use this function directly,
2215 * instead use buildLike() that escapes everything automatically
2216 * @deprecated since 1.17, warnings in 1.17, removed in ???
2222 public function escapeLike( $s ) {
2223 wfDeprecated( __METHOD__
, '1.17' );
2224 return $this->escapeLikeInternal( $s );
2231 protected function escapeLikeInternal( $s ) {
2232 $s = str_replace( '\\', '\\\\', $s );
2233 $s = $this->strencode( $s );
2234 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2240 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2241 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2242 * Alternatively, the function could be provided with an array of aforementioned parameters.
2244 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2245 * for subpages of 'My page title'.
2246 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2249 * @return String: fully built LIKE statement
2251 function buildLike() {
2252 $params = func_get_args();
2254 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2255 $params = $params[0];
2260 foreach ( $params as $value ) {
2261 if ( $value instanceof LikeMatch
) {
2262 $s .= $value->toString();
2264 $s .= $this->escapeLikeInternal( $value );
2268 return " LIKE '" . $s . "' ";
2272 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2276 function anyChar() {
2277 return new LikeMatch( '_' );
2281 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2285 function anyString() {
2286 return new LikeMatch( '%' );
2290 * Returns an appropriately quoted sequence value for inserting a new row.
2291 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2292 * subclass will return an integer, and save the value for insertId()
2294 * Any implementation of this function should *not* involve reusing
2295 * sequence numbers created for rolled-back transactions.
2296 * See http://bugs.mysql.com/bug.php?id=30767 for details.
2297 * @param $seqName string
2300 function nextSequenceValue( $seqName ) {
2305 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
2306 * is only needed because a) MySQL must be as efficient as possible due to
2307 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
2308 * which index to pick. Anyway, other databases might have different
2309 * indexes on a given table. So don't bother overriding this unless you're
2314 function useIndexClause( $index ) {
2319 * REPLACE query wrapper.
2321 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2322 * except that when there is a duplicate key error, the old row is deleted
2323 * and the new row is inserted in its place.
2325 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2326 * perform the delete, we need to know what the unique indexes are so that
2327 * we know how to find the conflicting rows.
2329 * It may be more efficient to leave off unique indexes which are unlikely
2330 * to collide. However if you do this, you run the risk of encountering
2331 * errors which wouldn't have occurred in MySQL.
2333 * @param $table String: The table to replace the row(s) in.
2334 * @param $rows array Can be either a single row to insert, or multiple rows,
2335 * in the same format as for DatabaseBase::insert()
2336 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2337 * a field name or an array of field names
2338 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2340 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2341 $quotedTable = $this->tableName( $table );
2343 if ( count( $rows ) == 0 ) {
2348 if ( !is_array( reset( $rows ) ) ) {
2349 $rows = array( $rows );
2352 foreach( $rows as $row ) {
2353 # Delete rows which collide
2354 if ( $uniqueIndexes ) {
2355 $sql = "DELETE FROM $quotedTable WHERE ";
2357 foreach ( $uniqueIndexes as $index ) {
2364 if ( is_array( $index ) ) {
2366 foreach ( $index as $col ) {
2372 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2375 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2379 $this->query( $sql, $fname );
2382 # Now insert the row
2383 $this->insert( $table, $row );
2388 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2391 * @param $table string Table name
2392 * @param $rows array Rows to insert
2393 * @param $fname string Caller function name
2395 * @return ResultWrapper
2397 protected function nativeReplace( $table, $rows, $fname ) {
2398 $table = $this->tableName( $table );
2401 if ( !is_array( reset( $rows ) ) ) {
2402 $rows = array( $rows );
2405 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2408 foreach ( $rows as $row ) {
2415 $sql .= '(' . $this->makeList( $row ) . ')';
2418 return $this->query( $sql, $fname );
2422 * DELETE where the condition is a join.
2424 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2425 * we use sub-selects
2427 * For safety, an empty $conds will not delete everything. If you want to
2428 * delete all rows where the join condition matches, set $conds='*'.
2430 * DO NOT put the join condition in $conds.
2432 * @param $delTable String: The table to delete from.
2433 * @param $joinTable String: The other table.
2434 * @param $delVar String: The variable to join on, in the first table.
2435 * @param $joinVar String: The variable to join on, in the second table.
2436 * @param $conds Array: Condition array of field names mapped to variables,
2437 * ANDed together in the WHERE clause
2438 * @param $fname String: Calling function name (use __METHOD__) for
2441 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2442 $fname = 'DatabaseBase::deleteJoin' )
2445 throw new DBUnexpectedError( $this,
2446 'DatabaseBase::deleteJoin() called with empty $conds' );
2449 $delTable = $this->tableName( $delTable );
2450 $joinTable = $this->tableName( $joinTable );
2451 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2452 if ( $conds != '*' ) {
2453 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2457 $this->query( $sql, $fname );
2461 * Returns the size of a text field, or -1 for "unlimited"
2463 * @param $table string
2464 * @param $field string
2468 function textFieldSize( $table, $field ) {
2469 $table = $this->tableName( $table );
2470 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2471 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2472 $row = $this->fetchObject( $res );
2476 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2486 * A string to insert into queries to show that they're low-priority, like
2487 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2488 * string and nothing bad should happen.
2490 * @return string Returns the text of the low priority option if it is
2491 * supported, or a blank string otherwise
2493 function lowPriorityOption() {
2498 * DELETE query wrapper.
2500 * @param $table Array Table name
2501 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2502 * the format. Use $conds == "*" to delete all rows
2503 * @param $fname String name of the calling function
2507 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2509 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2512 $table = $this->tableName( $table );
2513 $sql = "DELETE FROM $table";
2515 if ( $conds != '*' ) {
2516 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2519 return $this->query( $sql, $fname );
2523 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2524 * into another table.
2526 * @param $destTable string The table name to insert into
2527 * @param $srcTable string|array May be either a table name, or an array of table names
2528 * to include in a join.
2530 * @param $varMap array must be an associative array of the form
2531 * array( 'dest1' => 'source1', ...). Source items may be literals
2532 * rather than field names, but strings should be quoted with
2533 * DatabaseBase::addQuotes()
2535 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2536 * the details of the format of condition arrays. May be "*" to copy the
2539 * @param $fname string The function name of the caller, from __METHOD__
2541 * @param $insertOptions array Options for the INSERT part of the query, see
2542 * DatabaseBase::insert() for details.
2543 * @param $selectOptions array Options for the SELECT part of the query, see
2544 * DatabaseBase::select() for details.
2546 * @return ResultWrapper
2548 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2549 $fname = 'DatabaseBase::insertSelect',
2550 $insertOptions = array(), $selectOptions = array() )
2552 $destTable = $this->tableName( $destTable );
2554 if ( is_array( $insertOptions ) ) {
2555 $insertOptions = implode( ' ', $insertOptions );
2558 if ( !is_array( $selectOptions ) ) {
2559 $selectOptions = array( $selectOptions );
2562 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2564 if ( is_array( $srcTable ) ) {
2565 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2567 $srcTable = $this->tableName( $srcTable );
2570 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2571 " SELECT $startOpts " . implode( ',', $varMap ) .
2572 " FROM $srcTable $useIndex ";
2574 if ( $conds != '*' ) {
2575 if ( is_array( $conds ) ) {
2576 $conds = $this->makeList( $conds, LIST_AND
);
2578 $sql .= " WHERE $conds";
2581 $sql .= " $tailOpts";
2583 return $this->query( $sql, $fname );
2587 * Construct a LIMIT query with optional offset. This is used for query
2588 * pages. The SQL should be adjusted so that only the first $limit rows
2589 * are returned. If $offset is provided as well, then the first $offset
2590 * rows should be discarded, and the next $limit rows should be returned.
2591 * If the result of the query is not ordered, then the rows to be returned
2592 * are theoretically arbitrary.
2594 * $sql is expected to be a SELECT, if that makes a difference. For
2595 * UPDATE, limitResultForUpdate should be used.
2597 * The version provided by default works in MySQL and SQLite. It will very
2598 * likely need to be overridden for most other DBMSes.
2600 * @param $sql String SQL query we will append the limit too
2601 * @param $limit Integer the SQL limit
2602 * @param $offset Integer|false the SQL offset (default false)
2606 function limitResult( $sql, $limit, $offset = false ) {
2607 if ( !is_numeric( $limit ) ) {
2608 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2611 return "$sql LIMIT "
2612 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2621 function limitResultForUpdate( $sql, $num ) {
2622 return $this->limitResult( $sql, $num, 0 );
2626 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2627 * within the UNION construct.
2630 function unionSupportsOrderAndLimit() {
2631 return true; // True for almost every DB supported
2635 * Construct a UNION query
2636 * This is used for providing overload point for other DB abstractions
2637 * not compatible with the MySQL syntax.
2638 * @param $sqls Array: SQL statements to combine
2639 * @param $all Boolean: use UNION ALL
2640 * @return String: SQL fragment
2642 function unionQueries( $sqls, $all ) {
2643 $glue = $all ?
') UNION ALL (' : ') UNION (';
2644 return '(' . implode( $glue, $sqls ) . ')';
2648 * Returns an SQL expression for a simple conditional. This doesn't need
2649 * to be overridden unless CASE isn't supported in your DBMS.
2651 * @param $cond String: SQL expression which will result in a boolean value
2652 * @param $trueVal String: SQL expression to return if true
2653 * @param $falseVal String: SQL expression to return if false
2654 * @return String: SQL fragment
2656 function conditional( $cond, $trueVal, $falseVal ) {
2657 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2661 * Returns a comand for str_replace function in SQL query.
2662 * Uses REPLACE() in MySQL
2664 * @param $orig String: column to modify
2665 * @param $old String: column to seek
2666 * @param $new String: column to replace with
2670 function strreplace( $orig, $old, $new ) {
2671 return "REPLACE({$orig}, {$old}, {$new})";
2675 * Determines how long the server has been up
2680 function getServerUptime() {
2685 * Determines if the last failure was due to a deadlock
2690 function wasDeadlock() {
2695 * Determines if the last failure was due to a lock timeout
2700 function wasLockTimeout() {
2705 * Determines if the last query error was something that should be dealt
2706 * with by pinging the connection and reissuing the query.
2711 function wasErrorReissuable() {
2716 * Determines if the last failure was due to the database being read-only.
2721 function wasReadOnlyError() {
2726 * Perform a deadlock-prone transaction.
2728 * This function invokes a callback function to perform a set of write
2729 * queries. If a deadlock occurs during the processing, the transaction
2730 * will be rolled back and the callback function will be called again.
2733 * $dbw->deadlockLoop( callback, ... );
2735 * Extra arguments are passed through to the specified callback function.
2737 * Returns whatever the callback function returned on its successful,
2738 * iteration, or false on error, for example if the retry limit was
2743 function deadlockLoop() {
2745 $this->begin( __METHOD__
);
2746 $args = func_get_args();
2747 $function = array_shift( $args );
2748 $oldIgnore = $this->ignoreErrors( true );
2749 $tries = DEADLOCK_TRIES
;
2751 if ( is_array( $function ) ) {
2752 $fname = $function[0];
2758 $retVal = call_user_func_array( $function, $args );
2759 $error = $this->lastError();
2760 $errno = $this->lastErrno();
2761 $sql = $this->lastQuery();
2764 if ( $this->wasDeadlock() ) {
2766 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2768 $this->reportQueryError( $error, $errno, $sql, $fname );
2771 } while ( $this->wasDeadlock() && --$tries > 0 );
2773 $this->ignoreErrors( $oldIgnore );
2775 if ( $tries <= 0 ) {
2776 $this->rollback( __METHOD__
);
2777 $this->reportQueryError( $error, $errno, $sql, $fname );
2780 $this->commit( __METHOD__
);
2786 * Wait for the slave to catch up to a given master position.
2788 * @param $pos DBMasterPos object
2789 * @param $timeout Integer: the maximum number of seconds to wait for
2792 * @return An integer: zero if the slave was past that position already,
2793 * greater than zero if we waited for some period of time, less than
2794 * zero if we timed out.
2796 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2797 wfProfileIn( __METHOD__
);
2799 if ( !is_null( $this->mFakeSlaveLag
) ) {
2800 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2802 if ( $wait > $timeout * 1e6
) {
2803 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2804 wfProfileOut( __METHOD__
);
2806 } elseif ( $wait > 0 ) {
2807 wfDebug( "Fake slave waiting $wait us\n" );
2809 wfProfileOut( __METHOD__
);
2812 wfDebug( "Fake slave up to date ($wait us)\n" );
2813 wfProfileOut( __METHOD__
);
2818 wfProfileOut( __METHOD__
);
2820 # Real waits are implemented in the subclass.
2825 * Get the replication position of this slave
2827 * @return DBMasterPos, or false if this is not a slave.
2829 function getSlavePos() {
2830 if ( !is_null( $this->mFakeSlaveLag
) ) {
2831 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2832 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2841 * Get the position of this master
2843 * @return DBMasterPos, or false if this is not a master
2845 function getMasterPos() {
2846 if ( $this->mFakeMaster
) {
2847 return new MySQLMasterPos( 'fake', microtime( true ) );
2854 * Begin a transaction, committing any previously open transaction
2856 * @param $fname string
2858 function begin( $fname = 'DatabaseBase::begin' ) {
2859 $this->query( 'BEGIN', $fname );
2860 $this->mTrxLevel
= 1;
2866 * @param $fname string
2868 function commit( $fname = 'DatabaseBase::commit' ) {
2869 if ( $this->mTrxLevel
) {
2870 $this->query( 'COMMIT', $fname );
2871 $this->mTrxLevel
= 0;
2876 * Rollback a transaction.
2877 * No-op on non-transactional databases.
2879 * @param $fname string
2881 function rollback( $fname = 'DatabaseBase::rollback' ) {
2882 if ( $this->mTrxLevel
) {
2883 $this->query( 'ROLLBACK', $fname, true );
2884 $this->mTrxLevel
= 0;
2889 * Creates a new table with structure copied from existing table
2890 * Note that unlike most database abstraction functions, this function does not
2891 * automatically append database prefix, because it works at a lower
2892 * abstraction level.
2893 * The table names passed to this function shall not be quoted (this
2894 * function calls addIdentifierQuotes when needed).
2896 * @param $oldName String: name of table whose structure should be copied
2897 * @param $newName String: name of table to be created
2898 * @param $temporary Boolean: whether the new table should be temporary
2899 * @param $fname String: calling function name
2900 * @return Boolean: true if operation was successful
2902 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2903 $fname = 'DatabaseBase::duplicateTableStructure' )
2905 throw new MWException(
2906 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2910 * List all tables on the database
2912 * @param $prefix Only show tables with this prefix, e.g. mw_
2913 * @param $fname String: calling function name
2915 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2916 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2920 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2921 * to the format used for inserting into timestamp fields in this DBMS.
2923 * The result is unquoted, and needs to be passed through addQuotes()
2924 * before it can be included in raw SQL.
2926 * @param $ts string|int
2930 function timestamp( $ts = 0 ) {
2931 return wfTimestamp( TS_MW
, $ts );
2935 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2936 * to the format used for inserting into timestamp fields in this DBMS. If
2937 * NULL is input, it is passed through, allowing NULL values to be inserted
2938 * into timestamp fields.
2940 * The result is unquoted, and needs to be passed through addQuotes()
2941 * before it can be included in raw SQL.
2943 * @param $ts string|int
2947 function timestampOrNull( $ts = null ) {
2948 if ( is_null( $ts ) ) {
2951 return $this->timestamp( $ts );
2956 * Take the result from a query, and wrap it in a ResultWrapper if
2957 * necessary. Boolean values are passed through as is, to indicate success
2958 * of write queries or failure.
2960 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2961 * resource, and it was necessary to call this function to convert it to
2962 * a wrapper. Nowadays, raw database objects are never exposed to external
2963 * callers, so this is unnecessary in external code. For compatibility with
2964 * old code, ResultWrapper objects are passed through unaltered.
2966 * @param $result bool|ResultWrapper
2968 * @return bool|ResultWrapper
2970 function resultObject( $result ) {
2971 if ( empty( $result ) ) {
2973 } elseif ( $result instanceof ResultWrapper
) {
2975 } elseif ( $result === true ) {
2976 // Successful write query
2979 return new ResultWrapper( $this, $result );
2984 * Return aggregated value alias
2987 * @param $valuename string
2991 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2996 * Ping the server and try to reconnect if it there is no connection
2998 * @return bool Success or failure
3001 # Stub. Not essential to override.
3006 * Get slave lag. Currently supported only by MySQL.
3008 * Note that this function will generate a fatal error on many
3009 * installations. Most callers should use LoadBalancer::safeGetLag()
3012 * @return Database replication lag in seconds
3015 return intval( $this->mFakeSlaveLag
);
3019 * Return the maximum number of items allowed in a list, or 0 for unlimited.
3023 function maxListLen() {
3028 * Some DBMSs have a special format for inserting into blob fields, they
3029 * don't allow simple quoted strings to be inserted. To insert into such
3030 * a field, pass the data through this function before passing it to
3031 * DatabaseBase::insert().
3035 function encodeBlob( $b ) {
3040 * Some DBMSs return a special placeholder object representing blob fields
3041 * in result objects. Pass the object through this function to return the
3046 function decodeBlob( $b ) {
3051 * Override database's default connection timeout
3053 * @param $timeout Integer in seconds
3055 * @deprecated since 1.19; use setSessionOptions()
3057 public function setTimeout( $timeout ) {
3058 wfDeprecated( __METHOD__
, '1.19' );
3059 $this->setSessionOptions( array( 'connTimeout' => $timeout ) );
3063 * Override database's default behavior. $options include:
3064 * 'connTimeout' : Set the connection timeout value in seconds.
3065 * May be useful for very long batch queries such as
3066 * full-wiki dumps, where a single query reads out over
3069 * @param $options Array
3072 public function setSessionOptions( array $options ) {}
3075 * Read and execute SQL commands from a file.
3077 * Returns true on success, error string or exception on failure (depending
3078 * on object's error ignore settings).
3080 * @param $filename String: File name to open
3081 * @param $lineCallback Callback: Optional function called before reading each line
3082 * @param $resultCallback Callback: Optional function called for each MySQL result
3083 * @param $fname String: Calling function name or false if name should be
3084 * generated dynamically using $filename
3085 * @return bool|string
3087 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3088 wfSuppressWarnings();
3089 $fp = fopen( $filename, 'r' );
3090 wfRestoreWarnings();
3092 if ( false === $fp ) {
3093 throw new MWException( "Could not open \"{$filename}\".\n" );
3097 $fname = __METHOD__
. "( $filename )";
3101 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3103 catch ( MWException
$e ) {
3114 * Get the full path of a patch file. Originally based on archive()
3115 * from updaters.inc. Keep in mind this always returns a patch, as
3116 * it fails back to MySQL if no DB-specific patch can be found
3118 * @param $patch String The name of the patch, like patch-something.sql
3119 * @return String Full path to patch file
3121 public function patchPath( $patch ) {
3124 $dbType = $this->getType();
3125 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3126 return "$IP/maintenance/$dbType/archives/$patch";
3128 return "$IP/maintenance/archives/$patch";
3133 * Set variables to be used in sourceFile/sourceStream, in preference to the
3134 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3135 * all. If it's set to false, $GLOBALS will be used.
3137 * @param $vars False, or array mapping variable name to value.
3139 function setSchemaVars( $vars ) {
3140 $this->mSchemaVars
= $vars;
3144 * Read and execute commands from an open file handle.
3146 * Returns true on success, error string or exception on failure (depending
3147 * on object's error ignore settings).
3149 * @param $fp Resource: File handle
3150 * @param $lineCallback Callback: Optional function called before reading each line
3151 * @param $resultCallback Callback: Optional function called for each MySQL result
3152 * @param $fname String: Calling function name
3153 * @param $inputCallback Callback: Optional function called for each complete line (ended with ;) sent
3154 * @return bool|string
3156 public function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3157 $fname = 'DatabaseBase::sourceStream', $inputCallback = false )
3161 while ( !feof( $fp ) ) {
3162 if ( $lineCallback ) {
3163 call_user_func( $lineCallback );
3166 $line = trim( fgets( $fp ) );
3168 if ( $line == '' ) {
3172 if ( '-' == $line[0] && '-' == $line[1] ) {
3180 $done = $this->streamStatementEnd( $cmd, $line );
3184 if ( $done ||
feof( $fp ) ) {
3185 $cmd = $this->replaceVars( $cmd );
3186 if ( $inputCallback ) {
3187 call_user_func( $inputCallback, $cmd );
3189 $res = $this->query( $cmd, $fname );
3191 if ( $resultCallback ) {
3192 call_user_func( $resultCallback, $res, $this );
3195 if ( false === $res ) {
3196 $err = $this->lastError();
3197 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3208 * Called by sourceStream() to check if we've reached a statement end
3210 * @param $sql String SQL assembled so far
3211 * @param $newLine String New line about to be added to $sql
3212 * @return Bool Whether $newLine contains end of the statement
3214 public function streamStatementEnd( &$sql, &$newLine ) {
3215 if ( $this->delimiter
) {
3217 $newLine = preg_replace( '/' . preg_quote( $this->delimiter
, '/' ) . '$/', '', $newLine );
3218 if ( $newLine != $prev ) {
3226 * Database independent variable replacement. Replaces a set of variables
3227 * in an SQL statement with their contents as given by $this->getSchemaVars().
3229 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3231 * - '{$var}' should be used for text and is passed through the database's
3233 * - `{$var}` should be used for identifiers (eg: table and database names),
3234 * it is passed through the database's addIdentifierQuotes method which
3235 * can be overridden if the database uses something other than backticks.
3236 * - / *$var* / is just encoded, besides traditional table prefix and
3237 * table options its use should be avoided.
3239 * @param $ins String: SQL statement to replace variables in
3240 * @return String The new SQL statement with variables replaced
3242 protected function replaceSchemaVars( $ins ) {
3243 $vars = $this->getSchemaVars();
3244 foreach ( $vars as $var => $value ) {
3246 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3248 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3250 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3256 * Replace variables in sourced SQL
3258 * @param $ins string
3262 protected function replaceVars( $ins ) {
3263 $ins = $this->replaceSchemaVars( $ins );
3266 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3267 array( $this, 'tableNameCallback' ), $ins );
3270 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3271 array( $this, 'indexNameCallback' ), $ins );
3277 * Get schema variables. If none have been set via setSchemaVars(), then
3278 * use some defaults from the current object.
3282 protected function getSchemaVars() {
3283 if ( $this->mSchemaVars
) {
3284 return $this->mSchemaVars
;
3286 return $this->getDefaultSchemaVars();
3291 * Get schema variables to use if none have been set via setSchemaVars().
3293 * Override this in derived classes to provide variables for tables.sql
3294 * and SQL patch files.
3298 protected function getDefaultSchemaVars() {
3303 * Table name callback
3305 * @param $matches array
3309 protected function tableNameCallback( $matches ) {
3310 return $this->tableName( $matches[1] );
3314 * Index name callback
3316 * @param $matches array
3320 protected function indexNameCallback( $matches ) {
3321 return $this->indexName( $matches[1] );
3325 * Build a concatenation list to feed into a SQL query
3326 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3329 function buildConcat( $stringList ) {
3330 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3334 * Acquire a named lock
3336 * Abstracted from Filestore::lock() so child classes can implement for
3339 * @param $lockName String: name of lock to aquire
3340 * @param $method String: name of method calling us
3341 * @param $timeout Integer: timeout
3344 public function lock( $lockName, $method, $timeout = 5 ) {
3351 * @param $lockName String: Name of lock to release
3352 * @param $method String: Name of method calling us
3354 * @return Returns 1 if the lock was released, 0 if the lock was not established
3355 * by this thread (in which case the lock is not released), and NULL if the named
3356 * lock did not exist
3358 public function unlock( $lockName, $method ) {
3363 * Lock specific tables
3365 * @param $read Array of tables to lock for read access
3366 * @param $write Array of tables to lock for write access
3367 * @param $method String name of caller
3368 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3372 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3377 * Unlock specific tables
3379 * @param $method String the caller
3383 public function unlockTables( $method ) {
3389 * @param $tableName string
3390 * @param $fName string
3391 * @return bool|ResultWrapper
3394 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3395 if( !$this->tableExists( $tableName, $fName ) ) {
3398 $sql = "DROP TABLE " . $this->tableName( $tableName );
3399 if( $this->cascadingDeletes() ) {
3402 return $this->query( $sql, $fName );
3406 * Get search engine class. All subclasses of this need to implement this
3407 * if they wish to use searching.
3411 public function getSearchEngine() {
3412 return 'SearchEngineDummy';
3416 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3417 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3418 * because "i" sorts after all numbers.
3422 public function getInfinity() {
3427 * Encode an expiry time
3429 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3432 public function encodeExpiry( $expiry ) {
3433 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3434 return $this->getInfinity();
3436 return $this->timestamp( $expiry );
3441 * Allow or deny "big selects" for this session only. This is done by setting
3442 * the sql_big_selects session variable.
3444 * This is a MySQL-specific feature.
3446 * @param $value Mixed: true for allow, false for deny, or "default" to
3447 * restore the initial value
3449 public function setBigSelects( $value = true ) {