3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Base interface for all DBMS-specific code. At a bare minimum, all of the
20 * following must be implemented to support MediaWiki
25 interface DatabaseType
{
27 * Get the type of the DBMS, as it appears in $wgDBtype.
34 * Open a connection to the database. Usually aborts on failure
36 * @param $server String: database server host
37 * @param $user String: database user name
38 * @param $password String: database user password
39 * @param $dbName String: database name
41 * @throws DBConnectionError
43 function open( $server, $user, $password, $dbName );
46 * Fetch the next row from the given result object, in object form.
47 * Fields can be retrieved with $row->fieldname, with fields acting like
50 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
52 * @throws DBUnexpectedError Thrown if the database returns an error
54 function fetchObject( $res );
57 * Fetch the next row from the given result object, in associative array
58 * form. Fields are retrieved with $row['fieldname'].
60 * @param $res ResultWrapper result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchRow( $res );
67 * Get the number of rows in a result object
69 * @param $res Mixed: A SQL result
72 function numRows( $res );
75 * Get the number of fields in a result object
76 * @see http://www.php.net/mysql_num_fields
78 * @param $res Mixed: A SQL result
81 function numFields( $res );
84 * Get a field name in a result object
85 * @see http://www.php.net/mysql_field_name
87 * @param $res Mixed: A SQL result
91 function fieldName( $res, $n );
94 * Get the inserted value of an auto-increment row
96 * The value inserted should be fetched from nextSequenceValue()
99 * $id = $dbw->nextSequenceValue('page_page_id_seq');
100 * $dbw->insert('page',array('page_id' => $id));
101 * $id = $dbw->insertId();
108 * Change the position of the cursor in a result object
109 * @see http://www.php.net/mysql_data_seek
111 * @param $res Mixed: A SQL result
112 * @param $row Mixed: Either MySQL row or ResultWrapper
114 function dataSeek( $res, $row );
117 * Get the last error number
118 * @see http://www.php.net/mysql_errno
122 function lastErrno();
125 * Get a description of the last error
126 * @see http://www.php.net/mysql_error
130 function lastError();
133 * mysql_fetch_field() wrapper
134 * Returns false if the field doesn't exist
136 * @param $table string: table name
137 * @param $field string: field name
141 function fieldInfo( $table, $field );
144 * Get information about an index into an object
145 * @param $table string: Table name
146 * @param $index string: Index name
147 * @param $fname string: Calling function name
148 * @return Mixed: Database-specific index description class or false if the index does not exist
150 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
153 * Get the number of rows affected by the last write query
154 * @see http://www.php.net/mysql_affected_rows
158 function affectedRows();
161 * Wrapper for addslashes()
163 * @param $s string: to be slashed.
164 * @return string: slashed string.
166 function strencode( $s );
169 * Returns a wikitext link to the DB's website, e.g.,
170 * return "[http://www.mysql.com/ MySQL]";
171 * Should at least contain plain text, if for some reason
172 * your database has no website.
174 * @return string: wikitext of a link to the server software's web site
176 static function getSoftwareLink();
179 * A string describing the current software version, like from
180 * mysql_get_server_info().
182 * @return string: Version information from the database server.
184 function getServerVersion();
187 * A string describing the current software version, and possibly
188 * other details in a user-friendly way. Will be listed on Special:Version, etc.
189 * Use getServerVersion() to get machine-friendly information.
191 * @return string: Version information from the database server
193 function getServerInfo();
197 * Database abstraction object
200 abstract class DatabaseBase
implements DatabaseType
{
202 # ------------------------------------------------------------------------------
204 # ------------------------------------------------------------------------------
206 protected $mLastQuery = '';
207 protected $mDoneWrites = false;
208 protected $mPHPError = false;
210 protected $mServer, $mUser, $mPassword, $mDBname;
215 protected $mConn = null;
216 protected $mOpened = false;
218 protected $mTablePrefix;
220 protected $mTrxLevel = 0;
221 protected $mErrorCount = 0;
222 protected $mLBInfo = array();
223 protected $mFakeSlaveLag = null, $mFakeMaster = false;
224 protected $mDefaultBigSelects = null;
225 protected $mSchemaVars = false;
227 # ------------------------------------------------------------------------------
229 # ------------------------------------------------------------------------------
230 # These optionally set a variable and return the previous state
233 * A string describing the current software version, and possibly
234 * other details in a user-friendly way. Will be listed on Special:Version, etc.
235 * Use getServerVersion() to get machine-friendly information.
237 * @return string: Version information from the database server
239 public function getServerInfo() {
240 return $this->getServerVersion();
244 * Boolean, controls output of large amounts of debug information.
245 * @param $debug bool|null
246 * - true to enable debugging
247 * - false to disable debugging
248 * - omitted or null to do nothing
250 * @return The previous value of the flag
252 function debug( $debug = null ) {
253 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
257 * Turns buffering of SQL result sets on (true) or off (false). Default is
260 * Unbuffered queries are very troublesome in MySQL:
262 * - If another query is executed while the first query is being read
263 * out, the first query is killed. This means you can't call normal
264 * MediaWiki functions while you are reading an unbuffered query result
265 * from a normal wfGetDB() connection.
267 * - Unbuffered queries cause the MySQL server to use large amounts of
268 * memory and to hold broad locks which block other queries.
270 * If you want to limit client-side memory, it's almost always better to
271 * split up queries into batches using a LIMIT clause than to switch off
274 * @param $buffer null|bool
276 * @return The previous value of the flag
278 function bufferResults( $buffer = null ) {
279 if ( is_null( $buffer ) ) {
280 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
282 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
287 * Turns on (false) or off (true) the automatic generation and sending
288 * of a "we're sorry, but there has been a database error" page on
289 * database errors. Default is on (false). When turned off, the
290 * code should use lastErrno() and lastError() to handle the
291 * situation as appropriate.
293 * @param $ignoreErrors
295 * @return The previous value of the flag.
297 function ignoreErrors( $ignoreErrors = null ) {
298 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
302 * Gets or sets the current transaction level.
304 * Historically, transactions were allowed to be "nested". This is no
305 * longer supported, so this function really only returns a boolean.
307 * @param $level An integer (0 or 1), or omitted to leave it unchanged.
308 * @return The previous value
310 function trxLevel( $level = null ) {
311 return wfSetVar( $this->mTrxLevel
, $level );
315 * Get/set the number of errors logged. Only useful when errors are ignored
316 * @param $count The count to set, or omitted to leave it unchanged.
317 * @return The error count
319 function errorCount( $count = null ) {
320 return wfSetVar( $this->mErrorCount
, $count );
324 * Get/set the table prefix.
325 * @param $prefix The table prefix to set, or omitted to leave it unchanged.
326 * @return The previous table prefix.
328 function tablePrefix( $prefix = null ) {
329 return wfSetVar( $this->mTablePrefix
, $prefix );
333 * Get properties passed down from the server info array of the load
336 * @param $name string The entry of the info array to get, or null to get the
339 * @return LoadBalancer|null
341 function getLBInfo( $name = null ) {
342 if ( is_null( $name ) ) {
343 return $this->mLBInfo
;
345 if ( array_key_exists( $name, $this->mLBInfo
) ) {
346 return $this->mLBInfo
[$name];
354 * Set the LB info array, or a member of it. If called with one parameter,
355 * the LB info array is set to that parameter. If it is called with two
356 * parameters, the member with the given name is set to the given value.
361 function setLBInfo( $name, $value = null ) {
362 if ( is_null( $value ) ) {
363 $this->mLBInfo
= $name;
365 $this->mLBInfo
[$name] = $value;
370 * Set lag time in seconds for a fake slave
374 function setFakeSlaveLag( $lag ) {
375 $this->mFakeSlaveLag
= $lag;
379 * Make this connection a fake master
381 * @param $enabled bool
383 function setFakeMaster( $enabled = true ) {
384 $this->mFakeMaster
= $enabled;
388 * Returns true if this database supports (and uses) cascading deletes
392 function cascadingDeletes() {
397 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
401 function cleanupTriggers() {
406 * Returns true if this database is strict about what can be put into an IP field.
407 * Specifically, it uses a NULL value instead of an empty string.
411 function strictIPs() {
416 * Returns true if this database uses timestamps rather than integers
420 function realTimestamps() {
425 * Returns true if this database does an implicit sort when doing GROUP BY
429 function implicitGroupby() {
434 * Returns true if this database does an implicit order by when the column has an index
435 * For example: SELECT page_title FROM page LIMIT 1
437 function implicitOrderby() {
442 * Returns true if this database requires that SELECT DISTINCT queries require that all
443 ORDER BY expressions occur in the SELECT list per the SQL92 standard
447 function standardSelectDistinct() {
452 * Returns true if this database can do a native search on IP columns
453 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
457 function searchableIPs() {
462 * Returns true if this database can use functional indexes
466 function functionalIndexes() {
471 * Return the last query that went through DatabaseBase::query()
474 function lastQuery() {
475 return $this->mLastQuery
;
479 * Returns true if the connection may have been used for write queries.
480 * Should return true if unsure.
484 function doneWrites() {
485 return $this->mDoneWrites
;
489 * Is a connection to the database open?
493 return $this->mOpened
;
497 * Set a flag for this connection
499 * @param $flag Integer: DBO_* constants from Defines.php:
500 * - DBO_DEBUG: output some debug info (same as debug())
501 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
502 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
503 * - DBO_TRX: automatically start transactions
504 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
505 * and removes it in command line mode
506 * - DBO_PERSISTENT: use persistant database connection
508 function setFlag( $flag ) {
509 $this->mFlags |
= $flag;
513 * Clear a flag for this connection
515 * @param $flag: same as setFlag()'s $flag param
517 function clearFlag( $flag ) {
518 $this->mFlags
&= ~
$flag;
522 * Returns a boolean whether the flag $flag is set for this connection
524 * @param $flag: same as setFlag()'s $flag param
527 function getFlag( $flag ) {
528 return !!( $this->mFlags
& $flag );
532 * General read-only accessor
534 function getProperty( $name ) {
541 function getWikiID() {
542 if ( $this->mTablePrefix
) {
543 return "{$this->mDBname}-{$this->mTablePrefix}";
545 return $this->mDBname
;
550 * Return a path to the DBMS-specific schema file, otherwise default to tables.sql
554 public function getSchemaPath() {
556 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
557 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
559 return "$IP/maintenance/tables.sql";
563 # ------------------------------------------------------------------------------
565 # ------------------------------------------------------------------------------
569 * @param $server String: database server host
570 * @param $user String: database user name
571 * @param $password String: database user password
572 * @param $dbName String: database name
574 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
576 function __construct( $server = false, $user = false, $password = false, $dbName = false,
577 $flags = 0, $tablePrefix = 'get from global'
579 global $wgDBprefix, $wgCommandLineMode;
581 $this->mFlags
= $flags;
583 if ( $this->mFlags
& DBO_DEFAULT
) {
584 if ( $wgCommandLineMode ) {
585 $this->mFlags
&= ~DBO_TRX
;
587 $this->mFlags |
= DBO_TRX
;
591 /** Get the default table prefix*/
592 if ( $tablePrefix == 'get from global' ) {
593 $this->mTablePrefix
= $wgDBprefix;
595 $this->mTablePrefix
= $tablePrefix;
599 $this->open( $server, $user, $password, $dbName );
604 * Same as new DatabaseMysql( ... ), kept for backward compatibility
605 * @deprecated since 1.17
607 * @return DatabaseMysql
609 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
610 wfDeprecated( __METHOD__
);
611 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
615 * Given a DB type, construct the name of the appropriate child class of
616 * DatabaseBase. This is designed to replace all of the manual stuff like:
617 * $class = 'Database' . ucfirst( strtolower( $type ) );
618 * as well as validate against the canonical list of DB types we have
620 * This factory function is mostly useful for when you need to connect to a
621 * database other than the MediaWiki default (such as for external auth,
622 * an extension, et cetera). Do not use this to connect to the MediaWiki
623 * database. Example uses in core:
624 * @see LoadBalancer::reallyOpenConnection()
625 * @see ExternalUser_MediaWiki::initFromCond()
626 * @see ForeignDBRepo::getMasterDB()
627 * @see WebInstaller_DBConnect::execute()
629 * @param $dbType String A possible DB type
630 * @param $p Array An array of options to pass to the constructor.
631 * Valid options are: host, user, password, dbname, flags, tablePrefix
632 * @return DatabaseBase subclass or null
634 public final static function factory( $dbType, $p = array() ) {
635 $canonicalDBTypes = array(
636 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
638 $dbType = strtolower( $dbType );
640 if( in_array( $dbType, $canonicalDBTypes ) ) {
641 $class = 'Database' . ucfirst( $dbType );
643 isset( $p['host'] ) ?
$p['host'] : false,
644 isset( $p['user'] ) ?
$p['user'] : false,
645 isset( $p['password'] ) ?
$p['password'] : false,
646 isset( $p['dbname'] ) ?
$p['dbname'] : false,
647 isset( $p['flags'] ) ?
$p['flags'] : 0,
648 isset( $p['tablePrefix'] ) ?
$p['tablePrefix'] : 'get from global'
655 protected function installErrorHandler() {
656 $this->mPHPError
= false;
657 $this->htmlErrors
= ini_set( 'html_errors', '0' );
658 set_error_handler( array( $this, 'connectionErrorHandler' ) );
662 * @return bool|string
664 protected function restoreErrorHandler() {
665 restore_error_handler();
666 if ( $this->htmlErrors
!== false ) {
667 ini_set( 'html_errors', $this->htmlErrors
);
669 if ( $this->mPHPError
) {
670 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
671 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
678 protected function connectionErrorHandler( $errno, $errstr ) {
679 $this->mPHPError
= $errstr;
683 * Closes a database connection.
684 * if it is open : commits any open transactions
686 * @return Bool operation success. true if already closed.
689 # Stub, should probably be overridden
694 * @param $error String: fallback error message, used if none is given by DB
696 function reportConnectionError( $error = 'Unknown error' ) {
697 $myError = $this->lastError();
703 throw new DBConnectionError( $this, $error );
707 * The DBMS-dependent part of query()
709 * @param $sql String: SQL query.
710 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
712 protected abstract function doQuery( $sql );
715 * Determine whether a query writes to the DB.
716 * Should return true if unsure.
722 function isWriteQuery( $sql ) {
723 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
727 * Run an SQL query and return the result. Normally throws a DBQueryError
728 * on failure. If errors are ignored, returns false instead.
730 * In new code, the query wrappers select(), insert(), update(), delete(),
731 * etc. should be used where possible, since they give much better DBMS
732 * independence and automatically quote or validate user input in a variety
733 * of contexts. This function is generally only useful for queries which are
734 * explicitly DBMS-dependent and are unsupported by the query wrappers, such
737 * However, the query wrappers themselves should call this function.
739 * @param $sql String: SQL query
740 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
741 * comment (you can use __METHOD__ or add some extra info)
742 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
743 * maybe best to catch the exception instead?
744 * @return boolean|ResultWrapper. true for a successful write query, ResultWrapper object
745 * for a successful read query, or false on failure if $tempIgnore set
746 * @throws DBQueryError Thrown when the database returns an error of any kind
748 public function query( $sql, $fname = '', $tempIgnore = false ) {
749 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
750 if ( !Profiler
::instance()->isStub() ) {
751 # generalizeSQL will probably cut down the query to reasonable
752 # logging size most of the time. The substr is really just a sanity check.
755 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
756 $totalProf = 'DatabaseBase::query-master';
758 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
759 $totalProf = 'DatabaseBase::query';
762 wfProfileIn( $totalProf );
763 wfProfileIn( $queryProf );
766 $this->mLastQuery
= $sql;
767 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
768 # Set a flag indicating that writes have been done
769 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
770 $this->mDoneWrites
= true;
773 # Add a comment for easy SHOW PROCESSLIST interpretation
775 if ( is_object( $wgUser ) && $wgUser->isItemLoaded( 'name' ) ) {
776 $userName = $wgUser->getName();
777 if ( mb_strlen( $userName ) > 15 ) {
778 $userName = mb_substr( $userName, 0, 15 ) . '...';
780 $userName = str_replace( '/', '', $userName );
784 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
786 # If DBO_TRX is set, start a transaction
787 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
788 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
789 # avoid establishing transactions for SHOW and SET statements too -
790 # that would delay transaction initializations to once connection
791 # is really used by application
792 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
793 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
797 if ( $this->debug() ) {
801 $sqlx = substr( $commentedSql, 0, 500 );
802 $sqlx = strtr( $sqlx, "\t\n", ' ' );
805 wfDebug( "Query $cnt (master): $sqlx\n" );
807 wfDebug( "Query $cnt (slave): $sqlx\n" );
811 if ( istainted( $sql ) & TC_MYSQL
) {
812 throw new MWException( 'Tainted query found' );
815 # Do the query and handle errors
816 $ret = $this->doQuery( $commentedSql );
818 # Try reconnecting if the connection was lost
819 if ( false === $ret && $this->wasErrorReissuable() ) {
820 # Transaction is gone, like it or not
821 $this->mTrxLevel
= 0;
822 wfDebug( "Connection lost, reconnecting...\n" );
824 if ( $this->ping() ) {
825 wfDebug( "Reconnected\n" );
826 $sqlx = substr( $commentedSql, 0, 500 );
827 $sqlx = strtr( $sqlx, "\t\n", ' ' );
828 global $wgRequestTime;
829 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
830 if ( $elapsed < 300 ) {
831 # Not a database error to lose a transaction after a minute or two
832 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
834 $ret = $this->doQuery( $commentedSql );
836 wfDebug( "Failed\n" );
840 if ( false === $ret ) {
841 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
844 if ( !Profiler
::instance()->isStub() ) {
845 wfProfileOut( $queryProf );
846 wfProfileOut( $totalProf );
849 return $this->resultObject( $ret );
853 * Report a query error. Log the error, and if neither the object ignore
854 * flag nor the $tempIgnore flag is set, throw a DBQueryError.
856 * @param $error String
857 * @param $errno Integer
859 * @param $fname String
860 * @param $tempIgnore Boolean
862 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
863 # Ignore errors during error handling to avoid infinite recursion
864 $ignore = $this->ignoreErrors( true );
865 ++
$this->mErrorCount
;
867 if ( $ignore ||
$tempIgnore ) {
868 wfDebug( "SQL ERROR (ignored): $error\n" );
869 $this->ignoreErrors( $ignore );
871 $sql1line = str_replace( "\n", "\\n", $sql );
872 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
873 wfDebug( "SQL ERROR: " . $error . "\n" );
874 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
879 * Intended to be compatible with the PEAR::DB wrapper functions.
880 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
882 * ? = scalar value, quoted as necessary
883 * ! = raw SQL bit (a function for instance)
884 * & = filename; reads the file and inserts as a blob
885 * (we don't use this though...)
887 * This function should not be used directly by new code outside of the
888 * database classes. The query wrapper functions (select() etc.) should be
892 * @param $func string
896 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
897 /* MySQL doesn't support prepared statements (yet), so just
898 pack up the query for reference. We'll manually replace
900 return array( 'query' => $sql, 'func' => $func );
904 * Free a prepared query, generated by prepare().
906 function freePrepared( $prepared ) {
907 /* No-op by default */
911 * Execute a prepared query with the various arguments
912 * @param $prepared String: the prepared sql
913 * @param $args Mixed: Either an array here, or put scalars as varargs
915 * @return ResultWrapper
917 function execute( $prepared, $args = null ) {
918 if ( !is_array( $args ) ) {
920 $args = func_get_args();
921 array_shift( $args );
924 $sql = $this->fillPrepared( $prepared['query'], $args );
926 return $this->query( $sql, $prepared['func'] );
930 * Prepare & execute an SQL statement, quoting and inserting arguments
931 * in the appropriate places.
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
937 * @param $query String
940 * @return ResultWrapper
942 function safeQuery( $query, $args = null ) {
943 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
945 if ( !is_array( $args ) ) {
947 $args = func_get_args();
948 array_shift( $args );
951 $retval = $this->execute( $prepared, $args );
952 $this->freePrepared( $prepared );
958 * For faking prepared SQL statements on DBs that don't support
960 * @param $preparedQuery String: a 'preparable' SQL statement
961 * @param $args Array of arguments to fill it with
962 * @return string executable SQL
964 function fillPrepared( $preparedQuery, $args ) {
966 $this->preparedArgs
=& $args;
968 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
969 array( &$this, 'fillPreparedArg' ), $preparedQuery );
973 * preg_callback func for fillPrepared()
974 * The arguments should be in $this->preparedArgs and must not be touched
975 * while we're doing this.
977 * @param $matches Array
980 function fillPreparedArg( $matches ) {
981 switch( $matches[1] ) {
982 case '\\?': return '?';
983 case '\\!': return '!';
984 case '\\&': return '&';
987 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
989 switch( $matches[1] ) {
990 case '?': return $this->addQuotes( $arg );
991 case '!': return $arg;
993 # return $this->addQuotes( file_get_contents( $arg ) );
994 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
996 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
1001 * Free a result object returned by query() or select(). It's usually not
1002 * necessary to call this, just use unset() or let the variable holding
1003 * the result object go out of scope.
1005 * @param $res Mixed: A SQL result
1007 function freeResult( $res ) {
1011 * Simple UPDATE wrapper.
1012 * Usually throws a DBQueryError on failure.
1013 * If errors are explicitly ignored, returns success
1015 * This function exists for historical reasons, DatabaseBase::update() has a more standard
1016 * calling convention and feature set
1018 * @param $table string
1022 * @param $fname string
1026 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
1027 $table = $this->tableName( $table );
1028 $sql = "UPDATE $table SET $var = '" .
1029 $this->strencode( $value ) . "' WHERE ($cond)";
1031 return (bool)$this->query( $sql, $fname );
1035 * A SELECT wrapper which returns a single field from a single result row.
1037 * Usually throws a DBQueryError on failure. If errors are explicitly
1038 * ignored, returns false on failure.
1040 * If no result rows are returned from the query, false is returned.
1042 * @param $table string|array Table name. See DatabaseBase::select() for details.
1043 * @param $var string The field name to select. This must be a valid SQL
1044 * fragment: do not use unvalidated user input.
1045 * @param $cond string|array The condition array. See DatabaseBase::select() for details.
1046 * @param $fname string The function name of the caller.
1047 * @param $options string|array The query options. See DatabaseBase::select() for details.
1049 * @return false|mixed The value from the field, or false on failure.
1051 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField',
1052 $options = array() )
1054 if ( !is_array( $options ) ) {
1055 $options = array( $options );
1058 $options['LIMIT'] = 1;
1060 $res = $this->select( $table, $var, $cond, $fname, $options );
1062 if ( $res === false ||
!$this->numRows( $res ) ) {
1066 $row = $this->fetchRow( $res );
1068 if ( $row !== false ) {
1069 return reset( $row );
1076 * Returns an optional USE INDEX clause to go after the table, and a
1077 * string to go at the end of the query.
1079 * @param $options Array: associative array of options to be turned into
1080 * an SQL query, valid keys are listed in the function.
1082 * @see DatabaseBase::select()
1084 function makeSelectOptions( $options ) {
1085 $preLimitTail = $postLimitTail = '';
1088 $noKeyOptions = array();
1090 foreach ( $options as $key => $option ) {
1091 if ( is_numeric( $key ) ) {
1092 $noKeyOptions[$option] = true;
1096 if ( isset( $options['GROUP BY'] ) ) {
1097 $gb = is_array( $options['GROUP BY'] )
1098 ?
implode( ',', $options['GROUP BY'] )
1099 : $options['GROUP BY'];
1100 $preLimitTail .= " GROUP BY {$gb}";
1103 if ( isset( $options['HAVING'] ) ) {
1104 $preLimitTail .= " HAVING {$options['HAVING']}";
1107 if ( isset( $options['ORDER BY'] ) ) {
1108 $ob = is_array( $options['ORDER BY'] )
1109 ?
implode( ',', $options['ORDER BY'] )
1110 : $options['ORDER BY'];
1111 $preLimitTail .= " ORDER BY {$ob}";
1114 // if (isset($options['LIMIT'])) {
1115 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
1116 // isset($options['OFFSET']) ? $options['OFFSET']
1120 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
1121 $postLimitTail .= ' FOR UPDATE';
1124 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
1125 $postLimitTail .= ' LOCK IN SHARE MODE';
1128 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
1129 $startOpts .= 'DISTINCT';
1132 # Various MySQL extensions
1133 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
1134 $startOpts .= ' /*! STRAIGHT_JOIN */';
1137 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
1138 $startOpts .= ' HIGH_PRIORITY';
1141 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
1142 $startOpts .= ' SQL_BIG_RESULT';
1145 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1146 $startOpts .= ' SQL_BUFFER_RESULT';
1149 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1150 $startOpts .= ' SQL_SMALL_RESULT';
1153 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1154 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1157 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1158 $startOpts .= ' SQL_CACHE';
1161 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1162 $startOpts .= ' SQL_NO_CACHE';
1165 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1166 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1171 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1175 * Execute a SELECT query constructed using the various parameters provided.
1176 * See below for full details of the parameters.
1178 * @param $table String|Array Table name
1179 * @param $vars String|Array Field names
1180 * @param $conds String|Array Conditions
1181 * @param $fname String Caller function name
1182 * @param $options Array Query options
1183 * @param $join_conds Array Join conditions
1186 * @param $table string|array
1188 * May be either an array of table names, or a single string holding a table
1189 * name. If an array is given, table aliases can be specified, for example:
1191 * array( 'a' => 'user' )
1193 * This includes the user table in the query, with the alias "a" available
1194 * for use in field names (e.g. a.user_name).
1196 * All of the table names given here are automatically run through
1197 * DatabaseBase::tableName(), which causes the table prefix (if any) to be
1198 * added, and various other table name mappings to be performed.
1201 * @param $vars string|array
1203 * May be either a field name or an array of field names. The field names
1204 * here are complete fragments of SQL, for direct inclusion into the SELECT
1205 * query. Expressions and aliases may be specified as in SQL, for example:
1207 * array( 'MAX(rev_id) AS maxrev' )
1209 * If an expression is given, care must be taken to ensure that it is
1213 * @param $conds string|array
1215 * May be either a string containing a single condition, or an array of
1216 * conditions. If an array is given, the conditions constructed from each
1217 * element are combined with AND.
1219 * Array elements may take one of two forms:
1221 * - Elements with a numeric key are interpreted as raw SQL fragments.
1222 * - Elements with a string key are interpreted as equality conditions,
1223 * where the key is the field name.
1224 * - If the value of such an array element is a scalar (such as a
1225 * string), it will be treated as data and thus quoted appropriately.
1226 * If it is null, an IS NULL clause will be added.
1227 * - If the value is an array, an IN(...) clause will be constructed,
1228 * such that the field name may match any of the elements in the
1229 * array. The elements of the array will be quoted.
1230 * - If the field name ends with "!", this is taken as a flag which
1231 * inverts the comparison, allowing NOT IN clauses to be constructed,
1232 * for example: array( 'user_id!' => array( 1, 2, 3 ) )
1234 * Note that expressions are often DBMS-dependent in their syntax.
1235 * DBMS-independent wrappers are provided for constructing several types of
1236 * expression commonly used in condition queries. See:
1237 * - DatabaseBase::buildLike()
1238 * - DatabaseBase::conditional()
1241 * @param $options string|array
1243 * Optional: Array of query options. Boolean options are specified by
1244 * including them in the array as a string value with a numeric key, for
1247 * array( 'FOR UPDATE' )
1249 * The supported options are:
1251 * - OFFSET: Skip this many rows at the start of the result set. OFFSET
1252 * with LIMIT can theoretically be used for paging through a result set,
1253 * but this is discouraged in MediaWiki for performance reasons.
1255 * - LIMIT: Integer: return at most this many rows. The rows are sorted
1256 * and then the first rows are taken until the limit is reached. LIMIT
1257 * is applied to a result set after OFFSET.
1259 * - FOR UPDATE: Boolean: lock the returned rows so that they can't be
1260 * changed until the next COMMIT.
1262 * - DISTINCT: Boolean: return only unique result rows.
1264 * - GROUP BY: May be either an SQL fragment string naming a field or
1265 * expression to group by, or an array of such SQL fragments.
1267 * - HAVING: A string containing a HAVING clause.
1269 * - ORDER BY: May be either an SQL fragment giving a field name or
1270 * expression to order by, or an array of such SQL fragments.
1272 * - USE INDEX: This may be either a string giving the index name to use
1273 * for the query, or an array. If it is an associative array, each key
1274 * gives the table name (or alias), each value gives the index name to
1275 * use for that table. All strings are SQL fragments and so should be
1276 * validated by the caller.
1278 * - EXPLAIN: In MySQL, this causes an EXPLAIN SELECT query to be run,
1279 * instead of SELECT.
1281 * And also the following boolean MySQL extensions, see the MySQL manual
1282 * for documentation:
1284 * - LOCK IN SHARE MODE
1288 * - SQL_BUFFER_RESULT
1289 * - SQL_SMALL_RESULT
1290 * - SQL_CALC_FOUND_ROWS
1295 * @param $join_conds string|array
1297 * Optional associative array of table-specific join conditions. In the
1298 * most common case, this is unnecessary, since the join condition can be
1299 * in $conds. However, it is useful for doing a LEFT JOIN.
1301 * The key of the array contains the table name or alias. The value is an
1302 * array with two elements, numbered 0 and 1. The first gives the type of
1303 * join, the second is an SQL fragment giving the join condition for that
1304 * table. For example:
1306 * array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1308 * @return ResultWrapper. If the query returned no rows, a ResultWrapper
1309 * with no rows in it will be returned. If there was a query error, a
1310 * DBQueryError exception will be thrown, except if the "ignore errors"
1311 * option was set, in which case false will be returned.
1313 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select',
1314 $options = array(), $join_conds = array() ) {
1315 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1317 return $this->query( $sql, $fname );
1321 * The equivalent of DatabaseBase::select() except that the constructed SQL
1322 * is returned, instead of being immediately executed.
1324 * @param $table string|array Table name
1325 * @param $vars string|array Field names
1326 * @param $conds string|array Conditions
1327 * @param $fname string Caller function name
1328 * @param $options string|array Query options
1329 * @param $join_conds string|array Join conditions
1331 * @return SQL query string.
1332 * @see DatabaseBase::select()
1334 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1335 if ( is_array( $vars ) ) {
1336 $vars = implode( ',', $vars );
1339 $options = (array)$options;
1341 if ( is_array( $table ) ) {
1342 $useIndex = ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
1343 ?
$options['USE INDEX']
1345 if ( count( $join_conds ) ||
count( $useIndex ) ) {
1347 $this->tableNamesWithUseIndexOrJOIN( $table, $useIndex, $join_conds );
1349 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1351 } elseif ( $table != '' ) {
1352 if ( $table { 0 } == ' ' ) {
1353 $from = ' FROM ' . $table;
1355 $from = ' FROM ' . $this->tableName( $table );
1361 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1363 if ( !empty( $conds ) ) {
1364 if ( is_array( $conds ) ) {
1365 $conds = $this->makeList( $conds, LIST_AND
);
1367 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1369 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1372 if ( isset( $options['LIMIT'] ) ) {
1373 $sql = $this->limitResult( $sql, $options['LIMIT'],
1374 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1376 $sql = "$sql $postLimitTail";
1378 if ( isset( $options['EXPLAIN'] ) ) {
1379 $sql = 'EXPLAIN ' . $sql;
1386 * Single row SELECT wrapper. Equivalent to DatabaseBase::select(), except
1387 * that a single row object is returned. If the query returns no rows,
1388 * false is returned.
1390 * @param $table string|array Table name
1391 * @param $vars string|array Field names
1392 * @param $conds|array Conditions
1393 * @param $fname string Caller function name
1394 * @param $options string|array Query options
1395 * @param $join_conds array|string Join conditions
1397 * @return ResultWrapper|bool
1399 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow',
1400 $options = array(), $join_conds = array() )
1402 $options['LIMIT'] = 1;
1403 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1405 if ( $res === false ) {
1409 if ( !$this->numRows( $res ) ) {
1413 $obj = $this->fetchObject( $res );
1419 * Estimate rows in dataset.
1421 * MySQL allows you to estimate the number of rows that would be returned
1422 * by a SELECT query, using EXPLAIN SELECT. The estimate is provided using
1423 * index cardinality statistics, and is notoriously inaccurate, especially
1424 * when large numbers of rows have recently been added or deleted.
1426 * For DBMSs that don't support fast result size estimation, this function
1427 * will actually perform the SELECT COUNT(*).
1429 * Takes the same arguments as DatabaseBase::select().
1431 * @param $table String: table name
1432 * @param $vars Array: unused
1433 * @param $conds Array: filters on the table
1434 * @param $fname String: function name for profiling
1435 * @param $options Array: options for select
1436 * @return Integer: row count
1438 public function estimateRowCount( $table, $vars = '*', $conds = '',
1439 $fname = 'DatabaseBase::estimateRowCount', $options = array() )
1442 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1445 $row = $this->fetchRow( $res );
1446 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1453 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1454 * It's only slightly flawed. Don't use for anything important.
1456 * @param $sql String A SQL Query
1460 static function generalizeSQL( $sql ) {
1461 # This does the same as the regexp below would do, but in such a way
1462 # as to avoid crashing php on some large strings.
1463 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1465 $sql = str_replace ( "\\\\", '', $sql );
1466 $sql = str_replace ( "\\'", '', $sql );
1467 $sql = str_replace ( "\\\"", '', $sql );
1468 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1469 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1471 # All newlines, tabs, etc replaced by single space
1472 $sql = preg_replace ( '/\s+/', ' ', $sql );
1475 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1481 * Determines whether a field exists in a table
1483 * @param $table String: table name
1484 * @param $field String: filed to check on that table
1485 * @param $fname String: calling function name (optional)
1486 * @return Boolean: whether $table has filed $field
1488 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1489 $info = $this->fieldInfo( $table, $field );
1495 * Determines whether an index exists
1496 * Usually throws a DBQueryError on failure
1497 * If errors are explicitly ignored, returns NULL on failure
1501 * @param $fname string
1505 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1506 $info = $this->indexInfo( $table, $index, $fname );
1507 if ( is_null( $info ) ) {
1510 return $info !== false;
1515 * Query whether a given table exists
1517 * @param $table string
1521 function tableExists( $table ) {
1522 $table = $this->tableName( $table );
1523 $old = $this->ignoreErrors( true );
1524 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1525 $this->ignoreErrors( $old );
1531 * mysql_field_type() wrapper
1533 function fieldType( $res, $index ) {
1534 if ( $res instanceof ResultWrapper
) {
1535 $res = $res->result
;
1538 return mysql_field_type( $res, $index );
1542 * Determines if a given index is unique
1544 * @param $table string
1545 * @param $index string
1549 function indexUnique( $table, $index ) {
1550 $indexInfo = $this->indexInfo( $table, $index );
1552 if ( !$indexInfo ) {
1556 return !$indexInfo[0]->Non_unique
;
1560 * Helper for DatabaseBase::insert().
1562 * @param $options array
1565 function makeInsertOptions( $options ) {
1566 return implode( ' ', $options );
1570 * INSERT wrapper, inserts an array into a table.
1574 * - A single associative array. The array keys are the field names, and
1575 * the values are the values to insert. The values are treated as data
1576 * and will be quoted appropriately. If NULL is inserted, this will be
1577 * converted to a database NULL.
1578 * - An array with numeric keys, holding a list of associative arrays.
1579 * This causes a multi-row INSERT on DBMSs that support it. The keys in
1580 * each subarray must be identical to each other, and in the same order.
1582 * Usually throws a DBQueryError on failure. If errors are explicitly ignored,
1585 * $options is an array of options, with boolean options encoded as values
1586 * with numeric keys, in the same style as $options in
1587 * DatabaseBase::select(). Supported options are:
1589 * - IGNORE: Boolean: if present, duplicate key errors are ignored, and
1590 * any rows which cause duplicate key errors are not inserted. It's
1591 * possible to determine how many rows were successfully inserted using
1592 * DatabaseBase::affectedRows().
1594 * @param $table String Table name. This will be passed through
1595 * DatabaseBase::tableName().
1596 * @param $a Array of rows to insert
1597 * @param $fname String Calling function name (use __METHOD__) for logs/profiling
1598 * @param $options Array of options
1602 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1603 # No rows to insert, easy just return now
1604 if ( !count( $a ) ) {
1608 $table = $this->tableName( $table );
1610 if ( !is_array( $options ) ) {
1611 $options = array( $options );
1614 $options = $this->makeInsertOptions( $options );
1616 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1618 $keys = array_keys( $a[0] );
1621 $keys = array_keys( $a );
1624 $sql = 'INSERT ' . $options .
1625 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1629 foreach ( $a as $row ) {
1635 $sql .= '(' . $this->makeList( $row ) . ')';
1638 $sql .= '(' . $this->makeList( $a ) . ')';
1641 return (bool)$this->query( $sql, $fname );
1645 * Make UPDATE options for the DatabaseBase::update function
1647 * @param $options Array: The options passed to DatabaseBase::update
1650 function makeUpdateOptions( $options ) {
1651 if ( !is_array( $options ) ) {
1652 $options = array( $options );
1657 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1658 $opts[] = $this->lowPriorityOption();
1661 if ( in_array( 'IGNORE', $options ) ) {
1665 return implode( ' ', $opts );
1669 * UPDATE wrapper. Takes a condition array and a SET array.
1671 * @param $table String name of the table to UPDATE. This will be passed through
1672 * DatabaseBase::tableName().
1674 * @param $values Array: An array of values to SET. For each array element,
1675 * the key gives the field name, and the value gives the data
1676 * to set that field to. The data will be quoted by
1677 * DatabaseBase::addQuotes().
1679 * @param $conds Array: An array of conditions (WHERE). See
1680 * DatabaseBase::select() for the details of the format of
1681 * condition arrays. Use '*' to update all rows.
1683 * @param $fname String: The function name of the caller (from __METHOD__),
1684 * for logging and profiling.
1686 * @param $options Array: An array of UPDATE options, can be:
1687 * - IGNORE: Ignore unique key conflicts
1688 * - LOW_PRIORITY: MySQL-specific, see MySQL manual.
1691 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1692 $table = $this->tableName( $table );
1693 $opts = $this->makeUpdateOptions( $options );
1694 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1696 if ( $conds != '*' ) {
1697 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1700 return $this->query( $sql, $fname );
1704 * Makes an encoded list of strings from an array
1705 * @param $a Array containing the data
1706 * @param $mode int Constant
1707 * - LIST_COMMA: comma separated, no field names
1708 * - LIST_AND: ANDed WHERE clause (without the WHERE). See
1709 * the documentation for $conds in DatabaseBase::select().
1710 * - LIST_OR: ORed WHERE clause (without the WHERE)
1711 * - LIST_SET: comma separated with field names, like a SET clause
1712 * - LIST_NAMES: comma separated field names
1714 * In LIST_AND or LIST_OR modes, you can suffix a field with an exclamation
1715 * mark to generate a 'NOT IN' structure.
1718 * $db->makeList( array( 'field!' => array( 1,2,3 ) );
1721 * 'field' NOT IN ('1', '2', '3' );
1725 function makeList( $a, $mode = LIST_COMMA
) {
1726 if ( !is_array( $a ) ) {
1727 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1733 foreach ( $a as $field => $value ) {
1735 if ( $mode == LIST_AND
) {
1737 } elseif ( $mode == LIST_OR
) {
1746 // Support 'NOT IN' by suffixing fieldname with an exclamation mark
1748 if( substr($field,-1) == '!' ) {
1750 $field = substr($field, 0, -1 );
1753 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1754 $list .= "($value)";
1755 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1757 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1758 if ( count( $value ) == 0 ) {
1759 throw new MWException( __METHOD__
. ': empty input' );
1760 } elseif ( count( $value ) == 1 ) {
1761 // Special-case single values, as IN isn't terribly efficient
1762 // Don't necessarily assume the single key is 0; we don't
1763 // enforce linear numeric ordering on other arrays here.
1764 $value = array_values( $value );
1766 $operator = $not ?
' != ' : ' = ';
1767 $list .= $field . $operator . $this->addQuotes( $value[0] );
1769 $operator = $not ?
' NOT IN ' : ' IN ';
1770 $list .= $field . $operator . "(" . $this->makeList( $value ) . ")";
1772 } elseif ( $value === null ) {
1773 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1774 $list .= "$field IS ";
1778 } elseif ( $mode == LIST_SET
) {
1779 $list .= "$field = ";
1783 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1784 $list .= "$field = ";
1786 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1794 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1795 * The keys on each level may be either integers or strings.
1797 * @param $data Array: organized as 2-d
1798 * array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1799 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1800 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1801 * @return Mixed: string SQL fragment, or false if no items in array.
1803 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1806 foreach ( $data as $base => $sub ) {
1807 if ( count( $sub ) ) {
1808 $conds[] = $this->makeList(
1809 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1815 return $this->makeList( $conds, LIST_OR
);
1817 // Nothing to search for...
1823 * Build a partial where clause from a 3-d array
1824 * The keys on each level may be either integers or strings.
1826 * @param $data Array: organized as 3-d array(baseKeyVal => array(middleKeyVal => array(subKeyVal => <ignored>, ...), ...), ...)
1827 * @param $baseKey String: field name to match the base-level keys to (eg 'gtl_to_prefix')
1828 * @param $middleKey String: field name to match the middle-level keys to (eg 'gtl_to_namespace')
1829 * @param $subKey String: field name to match the sub-level keys to (eg 'gtl_to_title')
1830 * @return Mixed: string SQL fragment, or false if no items in array.
1832 function makeWhereFrom3d( $data, $baseKey, $middleKey, $subKey ) {
1834 foreach ( $data as $base => $subdata ) {
1835 foreach ( $subdata as $middle => $sub ) {
1836 if ( count( $sub ) ) {
1837 $conds[] = $this->makeList(
1838 array( $baseKey => $base,
1839 $middleKey => $middle,
1840 $subKey => array_keys( $sub ) ),
1848 return $this->makeList( $conds, LIST_OR
);
1850 // Nothing to search for...
1856 * Bitwise operations
1863 function bitNot( $field ) {
1869 * @param $fieldRight
1872 function bitAnd( $fieldLeft, $fieldRight ) {
1873 return "($fieldLeft & $fieldRight)";
1878 * @param $fieldRight
1881 function bitOr( $fieldLeft, $fieldRight ) {
1882 return "($fieldLeft | $fieldRight)";
1886 * Change the current database
1888 * @todo Explain what exactly will fail if this is not overridden.
1892 * @return bool Success or failure
1894 function selectDB( $db ) {
1895 # Stub. Shouldn't cause serious problems if it's not overridden, but
1896 # if your database engine supports a concept similar to MySQL's
1897 # databases you may as well.
1898 $this->mDBname
= $db;
1903 * Get the current DB name
1905 function getDBname() {
1906 return $this->mDBname
;
1910 * Get the server hostname or IP address
1912 function getServer() {
1913 return $this->mServer
;
1917 * Format a table name ready for use in constructing an SQL query
1919 * This does two important things: it quotes the table names to clean them up,
1920 * and it adds a table prefix if only given a table name with no quotes.
1922 * All functions of this object which require a table name call this function
1923 * themselves. Pass the canonical name to such functions. This is only needed
1924 * when calling query() directly.
1926 * @param $name String: database table name
1927 * @param $quoted Boolean: Automatically pass the table name through
1928 * addIdentifierQuotes() so that it can be used in a query.
1929 * @return String: full database name
1931 function tableName( $name, $quoted = true ) {
1932 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1933 # Skip the entire process when we have a string quoted on both ends.
1934 # Note that we check the end so that we will still quote any use of
1935 # use of `database`.table. But won't break things if someone wants
1936 # to query a database table with a dot in the name.
1937 if ( $this->isQuotedIdentifier( $name ) ) {
1941 # Lets test for any bits of text that should never show up in a table
1942 # name. Basically anything like JOIN or ON which are actually part of
1943 # SQL queries, but may end up inside of the table value to combine
1944 # sql. Such as how the API is doing.
1945 # Note that we use a whitespace test rather than a \b test to avoid
1946 # any remote case where a word like on may be inside of a table name
1947 # surrounded by symbols which may be considered word breaks.
1948 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1952 # Split database and table into proper variables.
1953 # We reverse the explode so that database.table and table both output
1954 # the correct table.
1955 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1956 if ( isset( $dbDetails[1] ) ) {
1957 list( $table, $database ) = $dbDetails;
1959 list( $table ) = $dbDetails;
1961 $prefix = $this->mTablePrefix
; # Default prefix
1963 # A database name has been specified in input. We don't want any
1965 if ( isset( $database ) ) {
1969 # Note that we use the long format because php will complain in in_array if
1970 # the input is not an array, and will complain in is_array if it is not set.
1971 if ( !isset( $database ) # Don't use shared database if pre selected.
1972 && isset( $wgSharedDB ) # We have a shared database
1973 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1974 && isset( $wgSharedTables )
1975 && is_array( $wgSharedTables )
1976 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1977 $database = $wgSharedDB;
1978 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1981 # Quote the $database and $table and apply the prefix if not quoted.
1982 if ( isset( $database ) ) {
1983 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1986 $table = "{$prefix}{$table}";
1987 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1988 $table = $this->addIdentifierQuotes( "{$table}" );
1991 # Merge our database and table into our final table name.
1992 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1998 * Fetch a number of table names into an array
1999 * This is handy when you need to construct SQL for joins
2002 * extract($dbr->tableNames('user','watchlist'));
2003 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2004 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2008 public function tableNames() {
2009 $inArray = func_get_args();
2012 foreach ( $inArray as $name ) {
2013 $retVal[$name] = $this->tableName( $name );
2020 * Fetch a number of table names into an zero-indexed numerical array
2021 * This is handy when you need to construct SQL for joins
2024 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
2025 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
2026 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
2030 public function tableNamesN() {
2031 $inArray = func_get_args();
2034 foreach ( $inArray as $name ) {
2035 $retVal[] = $this->tableName( $name );
2042 * Get an aliased table name
2043 * e.g. tableName AS newTableName
2045 * @param $name string Table name, see tableName()
2046 * @param $alias string|bool Alias (optional)
2047 * @return string SQL name for aliased table. Will not alias a table to its own name
2049 public function tableNameWithAlias( $name, $alias = false ) {
2050 if ( !$alias ||
$alias == $name ) {
2051 return $this->tableName( $name );
2053 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
2058 * Gets an array of aliased table names
2060 * @param $tables array( [alias] => table )
2061 * @return array of strings, see tableNameWithAlias()
2063 public function tableNamesWithAlias( $tables ) {
2065 foreach ( $tables as $alias => $table ) {
2066 if ( is_numeric( $alias ) ) {
2069 $retval[] = $this->tableNameWithAlias( $table, $alias );
2075 * Get the aliased table name clause for a FROM clause
2076 * which might have a JOIN and/or USE INDEX clause
2078 * @param $tables array ( [alias] => table )
2079 * @param $use_index array Same as for select()
2080 * @param $join_conds array Same as for select()
2083 protected function tableNamesWithUseIndexOrJOIN(
2084 $tables, $use_index = array(), $join_conds = array()
2088 $use_index = (array)$use_index;
2089 $join_conds = (array)$join_conds;
2091 foreach ( $tables as $alias => $table ) {
2092 if ( !is_string( $alias ) ) {
2093 // No alias? Set it equal to the table name
2096 // Is there a JOIN clause for this table?
2097 if ( isset( $join_conds[$alias] ) ) {
2098 list( $joinType, $conds ) = $join_conds[$alias];
2099 $tableClause = $joinType;
2100 $tableClause .= ' ' . $this->tableNameWithAlias( $table, $alias );
2101 if ( isset( $use_index[$alias] ) ) { // has USE INDEX?
2102 $use = $this->useIndexClause( implode( ',', (array)$use_index[$alias] ) );
2104 $tableClause .= ' ' . $use;
2107 $on = $this->makeList( (array)$conds, LIST_AND
);
2109 $tableClause .= ' ON (' . $on . ')';
2112 $retJOIN[] = $tableClause;
2113 // Is there an INDEX clause for this table?
2114 } elseif ( isset( $use_index[$alias] ) ) {
2115 $tableClause = $this->tableNameWithAlias( $table, $alias );
2116 $tableClause .= ' ' . $this->useIndexClause(
2117 implode( ',', (array)$use_index[$alias] ) );
2119 $ret[] = $tableClause;
2121 $tableClause = $this->tableNameWithAlias( $table, $alias );
2123 $ret[] = $tableClause;
2127 // We can't separate explicit JOIN clauses with ',', use ' ' for those
2128 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
2129 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
2131 // Compile our final table clause
2132 return implode( ' ', array( $straightJoins, $otherJoins ) );
2136 * Get the name of an index in a given table
2142 function indexName( $index ) {
2143 // Backwards-compatibility hack
2145 'ar_usertext_timestamp' => 'usertext_timestamp',
2146 'un_user_id' => 'user_id',
2147 'un_user_ip' => 'user_ip',
2150 if ( isset( $renamed[$index] ) ) {
2151 return $renamed[$index];
2158 * If it's a string, adds quotes and backslashes
2159 * Otherwise returns as-is
2165 function addQuotes( $s ) {
2166 if ( $s === null ) {
2169 # This will also quote numeric values. This should be harmless,
2170 # and protects against weird problems that occur when they really
2171 # _are_ strings such as article titles and string->number->string
2172 # conversion is not 1:1.
2173 return "'" . $this->strencode( $s ) . "'";
2178 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
2179 * MySQL uses `backticks` while basically everything else uses double quotes.
2180 * Since MySQL is the odd one out here the double quotes are our generic
2181 * and we implement backticks in DatabaseMysql.
2187 public function addIdentifierQuotes( $s ) {
2188 return '"' . str_replace( '"', '""', $s ) . '"';
2192 * Returns if the given identifier looks quoted or not according to
2193 * the database convention for quoting identifiers .
2195 * @param $name string
2199 public function isQuotedIdentifier( $name ) {
2200 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
2204 * Backwards compatibility, identifier quoting originated in DatabasePostgres
2205 * which used quote_ident which does not follow our naming conventions
2206 * was renamed to addIdentifierQuotes.
2207 * @deprecated since 1.18 use addIdentifierQuotes
2213 function quote_ident( $s ) {
2214 wfDeprecated( __METHOD__
);
2215 return $this->addIdentifierQuotes( $s );
2219 * Escape string for safe LIKE usage.
2220 * WARNING: you should almost never use this function directly,
2221 * instead use buildLike() that escapes everything automatically
2222 * @deprecated since 1.17, warnings in 1.17, removed in ???
2228 public function escapeLike( $s ) {
2229 wfDeprecated( __METHOD__
);
2230 return $this->escapeLikeInternal( $s );
2237 protected function escapeLikeInternal( $s ) {
2238 $s = str_replace( '\\', '\\\\', $s );
2239 $s = $this->strencode( $s );
2240 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
2246 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
2247 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
2248 * Alternatively, the function could be provided with an array of aforementioned parameters.
2250 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
2251 * for subpages of 'My page title'.
2252 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
2255 * @return String: fully built LIKE statement
2257 function buildLike() {
2258 $params = func_get_args();
2260 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
2261 $params = $params[0];
2266 foreach ( $params as $value ) {
2267 if ( $value instanceof LikeMatch
) {
2268 $s .= $value->toString();
2270 $s .= $this->escapeLikeInternal( $value );
2274 return " LIKE '" . $s . "' ";
2278 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
2282 function anyChar() {
2283 return new LikeMatch( '_' );
2287 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
2291 function anyString() {
2292 return new LikeMatch( '%' );
2296 * Returns an appropriately quoted sequence value for inserting a new row.
2297 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
2298 * subclass will return an integer, and save the value for insertId()
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
2312 function useIndexClause( $index ) {
2317 * REPLACE query wrapper.
2319 * REPLACE is a very handy MySQL extension, which functions like an INSERT
2320 * except that when there is a duplicate key error, the old row is deleted
2321 * and the new row is inserted in its place.
2323 * We simulate this with standard SQL with a DELETE followed by INSERT. To
2324 * perform the delete, we need to know what the unique indexes are so that
2325 * we know how to find the conflicting rows.
2327 * It may be more efficient to leave off unique indexes which are unlikely
2328 * to collide. However if you do this, you run the risk of encountering
2329 * errors which wouldn't have occurred in MySQL.
2331 * @param $table String: The table to replace the row(s) in.
2332 * @param $rows array Can be either a single row to insert, or multiple rows,
2333 * in the same format as for DatabaseBase::insert()
2334 * @param $uniqueIndexes array is an array of indexes. Each element may be either
2335 * a field name or an array of field names
2336 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
2338 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
2339 $quotedTable = $this->tableName( $table );
2341 if ( count( $rows ) == 0 ) {
2346 if ( !is_array( reset( $rows ) ) ) {
2347 $rows = array( $rows );
2350 foreach( $rows as $row ) {
2351 # Delete rows which collide
2352 if ( $uniqueIndexes ) {
2353 $sql = "DELETE FROM $quotedTable WHERE ";
2355 foreach ( $uniqueIndexes as $index ) {
2362 if ( is_array( $index ) ) {
2364 foreach ( $index as $col ) {
2370 $sql .= $col . '=' . $this->addQuotes( $row[$col] );
2373 $sql .= $index . '=' . $this->addQuotes( $row[$index] );
2377 $this->query( $sql, $fname );
2380 # Now insert the row
2381 $this->insert( $table, $row );
2386 * REPLACE query wrapper for MySQL and SQLite, which have a native REPLACE
2389 * @param $table Table name
2390 * @param $rows Rows to insert
2391 * @param $fname Caller function name
2393 * @return ResultWrapper
2395 protected function nativeReplace( $table, $rows, $fname ) {
2396 $table = $this->tableName( $table );
2399 if ( !is_array( reset( $rows ) ) ) {
2400 $rows = array( $rows );
2403 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
2406 foreach ( $rows as $row ) {
2413 $sql .= '(' . $this->makeList( $row ) . ')';
2416 return $this->query( $sql, $fname );
2420 * DELETE where the condition is a join.
2422 * MySQL overrides this to use a multi-table DELETE syntax, in other databases
2423 * we use sub-selects
2425 * For safety, an empty $conds will not delete everything. If you want to
2426 * delete all rows where the join condition matches, set $conds='*'.
2428 * DO NOT put the join condition in $conds.
2430 * @param $delTable String: The table to delete from.
2431 * @param $joinTable String: The other table.
2432 * @param $delVar String: The variable to join on, in the first table.
2433 * @param $joinVar String: The variable to join on, in the second table.
2434 * @param $conds Array: Condition array of field names mapped to variables,
2435 * ANDed together in the WHERE clause
2436 * @param $fname String: Calling function name (use __METHOD__) for
2439 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds,
2440 $fname = 'DatabaseBase::deleteJoin' )
2443 throw new DBUnexpectedError( $this,
2444 'DatabaseBase::deleteJoin() called with empty $conds' );
2447 $delTable = $this->tableName( $delTable );
2448 $joinTable = $this->tableName( $joinTable );
2449 $sql = "DELETE FROM $delTable WHERE $delVar IN (SELECT $joinVar FROM $joinTable ";
2450 if ( $conds != '*' ) {
2451 $sql .= 'WHERE ' . $this->makeList( $conds, LIST_AND
);
2455 $this->query( $sql, $fname );
2459 * Returns the size of a text field, or -1 for "unlimited"
2461 * @param $table string
2462 * @param $field string
2466 function textFieldSize( $table, $field ) {
2467 $table = $this->tableName( $table );
2468 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
2469 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
2470 $row = $this->fetchObject( $res );
2474 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
2484 * A string to insert into queries to show that they're low-priority, like
2485 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
2486 * string and nothing bad should happen.
2488 * @return string Returns the text of the low priority option if it is
2489 * supported, or a blank string otherwise
2491 function lowPriorityOption() {
2496 * DELETE query wrapper.
2498 * @param $table Array Table name
2499 * @param $conds String|Array of conditions. See $conds in DatabaseBase::select() for
2500 * the format. Use $conds == "*" to delete all rows
2501 * @param $fname String name of the calling function
2505 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
2507 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
2510 $table = $this->tableName( $table );
2511 $sql = "DELETE FROM $table";
2513 if ( $conds != '*' ) {
2514 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2517 return $this->query( $sql, $fname );
2521 * INSERT SELECT wrapper. Takes data from a SELECT query and inserts it
2522 * into another table.
2524 * @param $destTable string The table name to insert into
2525 * @param $srcTable string|array May be either a table name, or an array of table names
2526 * to include in a join.
2528 * @param $varMap array must be an associative array of the form
2529 * array( 'dest1' => 'source1', ...). Source items may be literals
2530 * rather than field names, but strings should be quoted with
2531 * DatabaseBase::addQuotes()
2533 * @param $conds array Condition array. See $conds in DatabaseBase::select() for
2534 * the details of the format of condition arrays. May be "*" to copy the
2537 * @param $fname string The function name of the caller, from __METHOD__
2539 * @param $insertOptions array Options for the INSERT part of the query, see
2540 * DatabaseBase::insert() for details.
2541 * @param $selectOptions array Options for the SELECT part of the query, see
2542 * DatabaseBase::select() for details.
2544 * @return ResultWrapper
2546 function insertSelect( $destTable, $srcTable, $varMap, $conds,
2547 $fname = 'DatabaseBase::insertSelect',
2548 $insertOptions = array(), $selectOptions = array() )
2550 $destTable = $this->tableName( $destTable );
2552 if ( is_array( $insertOptions ) ) {
2553 $insertOptions = implode( ' ', $insertOptions );
2556 if ( !is_array( $selectOptions ) ) {
2557 $selectOptions = array( $selectOptions );
2560 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2562 if ( is_array( $srcTable ) ) {
2563 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2565 $srcTable = $this->tableName( $srcTable );
2568 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2569 " SELECT $startOpts " . implode( ',', $varMap ) .
2570 " FROM $srcTable $useIndex ";
2572 if ( $conds != '*' ) {
2573 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2576 $sql .= " $tailOpts";
2578 return $this->query( $sql, $fname );
2582 * Construct a LIMIT query with optional offset. This is used for query
2583 * pages. The SQL should be adjusted so that only the first $limit rows
2584 * are returned. If $offset is provided as well, then the first $offset
2585 * rows should be discarded, and the next $limit rows should be returned.
2586 * If the result of the query is not ordered, then the rows to be returned
2587 * are theoretically arbitrary.
2589 * $sql is expected to be a SELECT, if that makes a difference. For
2590 * UPDATE, limitResultForUpdate should be used.
2592 * The version provided by default works in MySQL and SQLite. It will very
2593 * likely need to be overridden for most other DBMSes.
2595 * @param $sql String SQL query we will append the limit too
2596 * @param $limit Integer the SQL limit
2597 * @param $offset Integer|false the SQL offset (default false)
2601 function limitResult( $sql, $limit, $offset = false ) {
2602 if ( !is_numeric( $limit ) ) {
2603 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2606 return "$sql LIMIT "
2607 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2616 function limitResultForUpdate( $sql, $num ) {
2617 return $this->limitResult( $sql, $num, 0 );
2621 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2622 * within the UNION construct.
2625 function unionSupportsOrderAndLimit() {
2626 return true; // True for almost every DB supported
2630 * Construct a UNION query
2631 * This is used for providing overload point for other DB abstractions
2632 * not compatible with the MySQL syntax.
2633 * @param $sqls Array: SQL statements to combine
2634 * @param $all Boolean: use UNION ALL
2635 * @return String: SQL fragment
2637 function unionQueries( $sqls, $all ) {
2638 $glue = $all ?
') UNION ALL (' : ') UNION (';
2639 return '(' . implode( $glue, $sqls ) . ')';
2643 * Returns an SQL expression for a simple conditional. This doesn't need
2644 * to be overridden unless CASE isn't supported in your DBMS.
2646 * @param $cond String: SQL expression which will result in a boolean value
2647 * @param $trueVal String: SQL expression to return if true
2648 * @param $falseVal String: SQL expression to return if false
2649 * @return String: SQL fragment
2651 function conditional( $cond, $trueVal, $falseVal ) {
2652 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2656 * Returns a comand for str_replace function in SQL query.
2657 * Uses REPLACE() in MySQL
2659 * @param $orig String: column to modify
2660 * @param $old String: column to seek
2661 * @param $new String: column to replace with
2665 function strreplace( $orig, $old, $new ) {
2666 return "REPLACE({$orig}, {$old}, {$new})";
2670 * Determines if the last failure was due to a deadlock
2675 function wasDeadlock() {
2680 * Determines if the last query error was something that should be dealt
2681 * with by pinging the connection and reissuing the query.
2686 function wasErrorReissuable() {
2691 * Determines if the last failure was due to the database being read-only.
2696 function wasReadOnlyError() {
2701 * Perform a deadlock-prone transaction.
2703 * This function invokes a callback function to perform a set of write
2704 * queries. If a deadlock occurs during the processing, the transaction
2705 * will be rolled back and the callback function will be called again.
2708 * $dbw->deadlockLoop( callback, ... );
2710 * Extra arguments are passed through to the specified callback function.
2712 * Returns whatever the callback function returned on its successful,
2713 * iteration, or false on error, for example if the retry limit was
2718 function deadlockLoop() {
2719 $myFname = 'DatabaseBase::deadlockLoop';
2722 $args = func_get_args();
2723 $function = array_shift( $args );
2724 $oldIgnore = $this->ignoreErrors( true );
2725 $tries = DEADLOCK_TRIES
;
2727 if ( is_array( $function ) ) {
2728 $fname = $function[0];
2734 $retVal = call_user_func_array( $function, $args );
2735 $error = $this->lastError();
2736 $errno = $this->lastErrno();
2737 $sql = $this->lastQuery();
2740 if ( $this->wasDeadlock() ) {
2742 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2744 $this->reportQueryError( $error, $errno, $sql, $fname );
2747 } while ( $this->wasDeadlock() && --$tries > 0 );
2749 $this->ignoreErrors( $oldIgnore );
2751 if ( $tries <= 0 ) {
2752 $this->rollback( $myFname );
2753 $this->reportQueryError( $error, $errno, $sql, $fname );
2756 $this->commit( $myFname );
2762 * Wait for the slave to catch up to a given master position.
2764 * @param $pos DBMasterPos object
2765 * @param $timeout Integer: the maximum number of seconds to wait for
2768 * @return An integer: zero if the slave was past that position already,
2769 * greater than zero if we waited for some period of time, less than
2770 * zero if we timed out.
2772 function masterPosWait( DBMasterPos
$pos, $timeout ) {
2773 $fname = 'DatabaseBase::masterPosWait';
2774 wfProfileIn( $fname );
2776 if ( !is_null( $this->mFakeSlaveLag
) ) {
2777 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2779 if ( $wait > $timeout * 1e6
) {
2780 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2781 wfProfileOut( $fname );
2783 } elseif ( $wait > 0 ) {
2784 wfDebug( "Fake slave waiting $wait us\n" );
2786 wfProfileOut( $fname );
2789 wfDebug( "Fake slave up to date ($wait us)\n" );
2790 wfProfileOut( $fname );
2795 wfProfileOut( $fname );
2797 # Real waits are implemented in the subclass.
2802 * Get the replication position of this slave
2804 * @return DBMasterPos, or false if this is not a slave.
2806 function getSlavePos() {
2807 if ( !is_null( $this->mFakeSlaveLag
) ) {
2808 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2809 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2818 * Get the position of this master
2820 * @return DBMasterPos, or false if this is not a master
2822 function getMasterPos() {
2823 if ( $this->mFakeMaster
) {
2824 return new MySQLMasterPos( 'fake', microtime( true ) );
2831 * Begin a transaction, committing any previously open transaction
2833 * @param $fname string
2835 function begin( $fname = 'DatabaseBase::begin' ) {
2836 $this->query( 'BEGIN', $fname );
2837 $this->mTrxLevel
= 1;
2843 * @param $fname string
2845 function commit( $fname = 'DatabaseBase::commit' ) {
2846 if ( $this->mTrxLevel
) {
2847 $this->query( 'COMMIT', $fname );
2848 $this->mTrxLevel
= 0;
2853 * Rollback a transaction.
2854 * No-op on non-transactional databases.
2856 * @param $fname string
2858 function rollback( $fname = 'DatabaseBase::rollback' ) {
2859 if ( $this->mTrxLevel
) {
2860 $this->query( 'ROLLBACK', $fname, true );
2861 $this->mTrxLevel
= 0;
2866 * Creates a new table with structure copied from existing table
2867 * Note that unlike most database abstraction functions, this function does not
2868 * automatically append database prefix, because it works at a lower
2869 * abstraction level.
2870 * The table names passed to this function shall not be quoted (this
2871 * function calls addIdentifierQuotes when needed).
2873 * @param $oldName String: name of table whose structure should be copied
2874 * @param $newName String: name of table to be created
2875 * @param $temporary Boolean: whether the new table should be temporary
2876 * @param $fname String: calling function name
2877 * @return Boolean: true if operation was successful
2879 function duplicateTableStructure( $oldName, $newName, $temporary = false,
2880 $fname = 'DatabaseBase::duplicateTableStructure' )
2882 throw new MWException(
2883 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2887 * List all tables on the database
2889 * @param $prefix Only show tables with this prefix, e.g. mw_
2890 * @param $fname String: calling function name
2892 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2893 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2897 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2898 * to the format used for inserting into timestamp fields in this DBMS.
2900 * The result is unquoted, and needs to be passed through addQuotes()
2901 * before it can be included in raw SQL.
2903 * @param $ts string|int
2907 function timestamp( $ts = 0 ) {
2908 return wfTimestamp( TS_MW
, $ts );
2912 * Convert a timestamp in one of the formats accepted by wfTimestamp()
2913 * to the format used for inserting into timestamp fields in this DBMS. If
2914 * NULL is input, it is passed through, allowing NULL values to be inserted
2915 * into timestamp fields.
2917 * The result is unquoted, and needs to be passed through addQuotes()
2918 * before it can be included in raw SQL.
2920 * @param $ts string|int
2924 function timestampOrNull( $ts = null ) {
2925 if ( is_null( $ts ) ) {
2928 return $this->timestamp( $ts );
2933 * Take the result from a query, and wrap it in a ResultWrapper if
2934 * necessary. Boolean values are passed through as is, to indicate success
2935 * of write queries or failure.
2937 * Once upon a time, DatabaseBase::query() returned a bare MySQL result
2938 * resource, and it was necessary to call this function to convert it to
2939 * a wrapper. Nowadays, raw database objects are never exposed to external
2940 * callers, so this is unnecessary in external code. For compatibility with
2941 * old code, ResultWrapper objects are passed through unaltered.
2943 * @param $result bool|ResultWrapper
2945 * @param bool|ResultWrapper
2947 function resultObject( $result ) {
2948 if ( empty( $result ) ) {
2950 } elseif ( $result instanceof ResultWrapper
) {
2952 } elseif ( $result === true ) {
2953 // Successful write query
2956 return new ResultWrapper( $this, $result );
2961 * Return aggregated value alias
2964 * @param $valuename string
2968 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2973 * Ping the server and try to reconnect if it there is no connection
2975 * @return bool Success or failure
2978 # Stub. Not essential to override.
2984 * Currently supported only by MySQL
2985 * @return Database replication lag in seconds
2988 return intval( $this->mFakeSlaveLag
);
2992 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2996 function maxListLen() {
3001 * Some DBMSs have a special format for inserting into blob fields, they
3002 * don't allow simple quoted strings to be inserted. To insert into such
3003 * a field, pass the data through this function before passing it to
3004 * DatabaseBase::insert().
3006 function encodeBlob( $b ) {
3011 * Some DBMSs return a special placeholder object representing blob fields
3012 * in result objects. Pass the object through this function to return the
3015 function decodeBlob( $b ) {
3020 * Override database's default connection timeout. May be useful for very
3021 * long batch queries such as full-wiki dumps, where a single query reads
3022 * out over hours or days. May or may not be necessary for non-MySQL
3023 * databases. For most purposes, leaving it as a no-op should be fine.
3025 * @param $timeout Integer in seconds
3027 public function setTimeout( $timeout ) {}
3030 * Read and execute SQL commands from a file.
3032 * Returns true on success, error string or exception on failure (depending
3033 * on object's error ignore settings).
3035 * @param $filename String: File name to open
3036 * @param $lineCallback Callback: Optional function called before reading each line
3037 * @param $resultCallback Callback: Optional function called for each MySQL result
3038 * @param $fname String: Calling function name or false if name should be
3039 * generated dynamically using $filename
3041 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
3042 wfSuppressWarnings();
3043 $fp = fopen( $filename, 'r' );
3044 wfRestoreWarnings();
3046 if ( false === $fp ) {
3047 throw new MWException( "Could not open \"{$filename}\".\n" );
3051 $fname = __METHOD__
. "( $filename )";
3055 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
3057 catch ( MWException
$e ) {
3068 * Get the full path of a patch file. Originally based on archive()
3069 * from updaters.inc. Keep in mind this always returns a patch, as
3070 * it fails back to MySQL if no DB-specific patch can be found
3072 * @param $patch String The name of the patch, like patch-something.sql
3073 * @return String Full path to patch file
3075 public function patchPath( $patch ) {
3078 $dbType = $this->getType();
3079 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
3080 return "$IP/maintenance/$dbType/archives/$patch";
3082 return "$IP/maintenance/archives/$patch";
3087 * Set variables to be used in sourceFile/sourceStream, in preference to the
3088 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
3089 * all. If it's set to false, $GLOBALS will be used.
3091 * @param $vars False, or array mapping variable name to value.
3093 function setSchemaVars( $vars ) {
3094 $this->mSchemaVars
= $vars;
3098 * Read and execute commands from an open file handle.
3100 * Returns true on success, error string or exception on failure (depending
3101 * on object's error ignore settings).
3103 * @param $fp Resource: File handle
3104 * @param $lineCallback Callback: Optional function called before reading each line
3105 * @param $resultCallback Callback: Optional function called for each MySQL result
3106 * @param $fname String: Calling function name
3108 function sourceStream( $fp, $lineCallback = false, $resultCallback = false,
3109 $fname = 'DatabaseBase::sourceStream' )
3113 $dollarquote = false;
3115 while ( ! feof( $fp ) ) {
3116 if ( $lineCallback ) {
3117 call_user_func( $lineCallback );
3120 $line = trim( fgets( $fp ) );
3121 $sl = strlen( $line ) - 1;
3127 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
3131 # # Allow dollar quoting for function declarations
3132 if ( substr( $line, 0, 4 ) == '$mw$' ) {
3133 if ( $dollarquote ) {
3134 $dollarquote = false;
3138 $dollarquote = true;
3141 elseif ( !$dollarquote ) {
3142 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
3144 $line = substr( $line, 0, $sl );
3155 $cmd = str_replace( ';;', ";", $cmd );
3156 $cmd = $this->replaceVars( $cmd );
3157 $res = $this->query( $cmd, $fname );
3159 if ( $resultCallback ) {
3160 call_user_func( $resultCallback, $res, $this );
3163 if ( false === $res ) {
3164 $err = $this->lastError();
3165 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
3177 * Database independent variable replacement. Replaces a set of variables
3178 * in an SQL statement with their contents as given by $this->getSchemaVars().
3180 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables.
3182 * - '{$var}' should be used for text and is passed through the database's
3184 * - `{$var}` should be used for identifiers (eg: table and database names),
3185 * it is passed through the database's addIdentifierQuotes method which
3186 * can be overridden if the database uses something other than backticks.
3187 * - / *$var* / is just encoded, besides traditional table prefix and
3188 * table options its use should be avoided.
3190 * @param $ins String: SQL statement to replace variables in
3191 * @return String The new SQL statement with variables replaced
3193 protected function replaceSchemaVars( $ins ) {
3194 $vars = $this->getSchemaVars();
3195 foreach ( $vars as $var => $value ) {
3197 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
3199 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
3201 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
3207 * Replace variables in sourced SQL
3209 * @param $ins string
3213 protected function replaceVars( $ins ) {
3214 $ins = $this->replaceSchemaVars( $ins );
3217 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
3218 array( $this, 'tableNameCallback' ), $ins );
3221 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
3222 array( $this, 'indexNameCallback' ), $ins );
3228 * Get schema variables. If none have been set via setSchemaVars(), then
3229 * use some defaults from the current object.
3231 protected function getSchemaVars() {
3232 if ( $this->mSchemaVars
) {
3233 return $this->mSchemaVars
;
3235 return $this->getDefaultSchemaVars();
3240 * Get schema variables to use if none have been set via setSchemaVars().
3242 * Override this in derived classes to provide variables for tables.sql
3243 * and SQL patch files.
3247 protected function getDefaultSchemaVars() {
3252 * Table name callback
3254 * @param $matches array
3258 protected function tableNameCallback( $matches ) {
3259 return $this->tableName( $matches[1] );
3263 * Index name callback
3265 * @param $matches array
3269 protected function indexNameCallback( $matches ) {
3270 return $this->indexName( $matches[1] );
3274 * Build a concatenation list to feed into a SQL query
3275 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
3278 function buildConcat( $stringList ) {
3279 return 'CONCAT(' . implode( ',', $stringList ) . ')';
3283 * Acquire a named lock
3285 * Abstracted from Filestore::lock() so child classes can implement for
3288 * @param $lockName String: name of lock to aquire
3289 * @param $method String: name of method calling us
3290 * @param $timeout Integer: timeout
3293 public function lock( $lockName, $method, $timeout = 5 ) {
3300 * @param $lockName String: Name of lock to release
3301 * @param $method String: Name of method calling us
3303 * @return Returns 1 if the lock was released, 0 if the lock was not established
3304 * by this thread (in which case the lock is not released), and NULL if the named
3305 * lock did not exist
3307 public function unlock( $lockName, $method ) {
3312 * Lock specific tables
3314 * @param $read Array of tables to lock for read access
3315 * @param $write Array of tables to lock for write access
3316 * @param $method String name of caller
3317 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
3321 public function lockTables( $read, $write, $method, $lowPriority = true ) {
3326 * Unlock specific tables
3328 * @param $method String the caller
3332 public function unlockTables( $method ) {
3338 * @param $tableName string
3339 * @param $fName string
3340 * @return bool|ResultWrapper
3342 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
3343 if( !$this->tableExists( $tableName ) ) {
3346 $sql = "DROP TABLE " . $this->tableName( $tableName );
3347 if( $this->cascadingDeletes() ) {
3350 return $this->query( $sql, $fName );
3354 * Get search engine class. All subclasses of this need to implement this
3355 * if they wish to use searching.
3359 public function getSearchEngine() {
3360 return 'SearchEngineDummy';
3364 * Find out when 'infinity' is. Most DBMSes support this. This is a special
3365 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
3366 * because "i" sorts after all numbers.
3370 public function getInfinity() {
3375 * Encode an expiry time
3377 * @param $expiry String: timestamp for expiry, or the 'infinity' string
3380 public function encodeExpiry( $expiry ) {
3381 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
3382 return $this->getInfinity();
3384 return $this->timestamp( $expiry );
3389 * Allow or deny "big selects" for this session only. This is done by setting
3390 * the sql_big_selects session variable.
3392 * This is a MySQL-specific feature.
3394 * @param $value Mixed: true for allow, false for deny, or "default" to
3395 * restore the initial value
3397 public function setBigSelects( $value = true ) {