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 * The DBMS-dependent part of query()
47 * @todo Fixme: Make this private someday
49 * @param $sql String: SQL query.
50 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
53 function doQuery( $sql );
56 * Fetch the next row from the given result object, in object form.
57 * Fields can be retrieved with $row->fieldname, with fields acting like
60 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
62 * @throws DBUnexpectedError Thrown if the database returns an error
64 function fetchObject( $res );
67 * Fetch the next row from the given result object, in associative array
68 * form. Fields are retrieved with $row['fieldname'].
70 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
72 * @throws DBUnexpectedError Thrown if the database returns an error
74 function fetchRow( $res );
77 * Get the number of rows in a result object
79 * @param $res Mixed: A SQL result
82 function numRows( $res );
85 * Get the number of fields in a result object
86 * @see http://www.php.net/mysql_num_fields
88 * @param $res Mixed: A SQL result
91 function numFields( $res );
94 * Get a field name in a result object
95 * @see http://www.php.net/mysql_field_name
97 * @param $res Mixed: A SQL result
101 function fieldName( $res, $n );
104 * Get the inserted value of an auto-increment row
106 * The value inserted should be fetched from nextSequenceValue()
109 * $id = $dbw->nextSequenceValue('page_page_id_seq');
110 * $dbw->insert('page',array('page_id' => $id));
111 * $id = $dbw->insertId();
118 * Change the position of the cursor in a result object
119 * @see http://www.php.net/mysql_data_seek
121 * @param $res Mixed: A SQL result
122 * @param $row Mixed: Either MySQL row or ResultWrapper
124 function dataSeek( $res, $row );
127 * Get the last error number
128 * @see http://www.php.net/mysql_errno
132 function lastErrno();
135 * Get a description of the last error
136 * @see http://www.php.net/mysql_error
140 function lastError();
143 * mysql_fetch_field() wrapper
144 * Returns false if the field doesn't exist
146 * @param $table string: table name
147 * @param $field string: field name
151 function fieldInfo( $table, $field );
154 * Get information about an index into an object
155 * @param $table string: Table name
156 * @param $index string: Index name
157 * @param $fname string: Calling function name
158 * @return Mixed: Database-specific index description class or false if the index does not exist
160 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
163 * Get the number of rows affected by the last write query
164 * @see http://www.php.net/mysql_affected_rows
168 function affectedRows();
171 * Wrapper for addslashes()
173 * @param $s string: to be slashed.
174 * @return string: slashed string.
176 function strencode( $s );
179 * Returns a wikitext link to the DB's website, e.g.,
180 * return "[http://www.mysql.com/ MySQL]";
181 * Should at least contain plain text, if for some reason
182 * your database has no website.
184 * @return string: wikitext of a link to the server software's web site
186 static function getSoftwareLink();
189 * A string describing the current software version, like from
190 * mysql_get_server_info().
192 * @return string: Version information from the database server.
194 function getServerVersion();
197 * A string describing the current software version, and possibly
198 * other details in a user-friendly way. Will be listed on Special:Version, etc.
199 * Use getServerVersion() to get machine-friendly information.
201 * @return string: Version information from the database server
203 function getServerInfo();
207 * Database abstraction object
210 abstract class DatabaseBase
implements DatabaseType
{
212 # ------------------------------------------------------------------------------
214 # ------------------------------------------------------------------------------
216 protected $mLastQuery = '';
217 protected $mDoneWrites = false;
218 protected $mPHPError = false;
220 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
221 protected $mOpened = false;
223 protected $mTablePrefix;
225 protected $mTrxLevel = 0;
226 protected $mErrorCount = 0;
227 protected $mLBInfo = array();
228 protected $mFakeSlaveLag = null, $mFakeMaster = false;
229 protected $mDefaultBigSelects = null;
230 protected $mSchemaVars = false;
232 # ------------------------------------------------------------------------------
234 # ------------------------------------------------------------------------------
235 # These optionally set a variable and return the previous state
238 * A string describing the current software version, and possibly
239 * other details in a user-friendly way. Will be listed on Special:Version, etc.
240 * Use getServerVersion() to get machine-friendly information.
242 * @return string: Version information from the database server
244 public function getServerInfo() {
245 return $this->getServerVersion();
249 * Boolean, controls output of large amounts of debug information
251 function debug( $debug = null ) {
252 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
256 * Turns buffering of SQL result sets on (true) or off (false).
257 * Default is "on" and it should not be changed without good reasons.
259 function bufferResults( $buffer = null ) {
260 if ( is_null( $buffer ) ) {
261 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
263 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
268 * Turns on (false) or off (true) the automatic generation and sending
269 * of a "we're sorry, but there has been a database error" page on
270 * database errors. Default is on (false). When turned off, the
271 * code should use lastErrno() and lastError() to handle the
272 * situation as appropriate.
274 function ignoreErrors( $ignoreErrors = null ) {
275 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
279 * The current depth of nested transactions
280 * @param $level Integer: , default NULL.
282 function trxLevel( $level = null ) {
283 return wfSetVar( $this->mTrxLevel
, $level );
287 * Number of errors logged, only useful when errors are ignored
289 function errorCount( $count = null ) {
290 return wfSetVar( $this->mErrorCount
, $count );
293 function tablePrefix( $prefix = null ) {
294 return wfSetVar( $this->mTablePrefix
, $prefix, true );
298 * Properties passed down from the server info array of the load balancer
300 function getLBInfo( $name = null ) {
301 if ( is_null( $name ) ) {
302 return $this->mLBInfo
;
304 if ( array_key_exists( $name, $this->mLBInfo
) ) {
305 return $this->mLBInfo
[$name];
312 function setLBInfo( $name, $value = null ) {
313 if ( is_null( $value ) ) {
314 $this->mLBInfo
= $name;
316 $this->mLBInfo
[$name] = $value;
321 * Set lag time in seconds for a fake slave
323 function setFakeSlaveLag( $lag ) {
324 $this->mFakeSlaveLag
= $lag;
328 * Make this connection a fake master
330 function setFakeMaster( $enabled = true ) {
331 $this->mFakeMaster
= $enabled;
335 * Returns true if this database supports (and uses) cascading deletes
337 function cascadingDeletes() {
342 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
344 function cleanupTriggers() {
349 * Returns true if this database is strict about what can be put into an IP field.
350 * Specifically, it uses a NULL value instead of an empty string.
352 function strictIPs() {
357 * Returns true if this database uses timestamps rather than integers
359 function realTimestamps() {
364 * Returns true if this database does an implicit sort when doing GROUP BY
366 function implicitGroupby() {
371 * Returns true if this database does an implicit order by when the column has an index
372 * For example: SELECT page_title FROM page LIMIT 1
374 function implicitOrderby() {
379 * Returns true if this database requires that SELECT DISTINCT queries require that all
380 ORDER BY expressions occur in the SELECT list per the SQL92 standard
382 function standardSelectDistinct() {
387 * Returns true if this database can do a native search on IP columns
388 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
390 function searchableIPs() {
395 * Returns true if this database can use functional indexes
397 function functionalIndexes() {
402 * Return the last query that went through DatabaseBase::query()
405 function lastQuery() { return $this->mLastQuery
; }
409 * Returns true if the connection may have been used for write queries.
410 * Should return true if unsure.
412 function doneWrites() { return $this->mDoneWrites
; }
415 * Is a connection to the database open?
418 function isOpen() { return $this->mOpened
; }
421 * Set a flag for this connection
423 * @param $flag Integer: DBO_* constants from Defines.php:
424 * - DBO_DEBUG: output some debug info (same as debug())
425 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
426 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
427 * - DBO_TRX: automatically start transactions
428 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
429 * and removes it in command line mode
430 * - DBO_PERSISTENT: use persistant database connection
432 function setFlag( $flag ) {
433 $this->mFlags |
= $flag;
437 * Clear a flag for this connection
439 * @param $flag: same as setFlag()'s $flag param
441 function clearFlag( $flag ) {
442 $this->mFlags
&= ~
$flag;
446 * Returns a boolean whether the flag $flag is set for this connection
448 * @param $flag: same as setFlag()'s $flag param
451 function getFlag( $flag ) {
452 return !!( $this->mFlags
& $flag );
456 * General read-only accessor
458 function getProperty( $name ) {
462 function getWikiID() {
463 if ( $this->mTablePrefix
) {
464 return "{$this->mDBname}-{$this->mTablePrefix}";
466 return $this->mDBname
;
471 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
473 public function getSchema() {
475 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
476 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
478 return "$IP/maintenance/tables.sql";
482 # ------------------------------------------------------------------------------
484 # ------------------------------------------------------------------------------
488 * @param $server String: database server host
489 * @param $user String: database user name
490 * @param $password String: database user password
491 * @param $dbName String: database name
493 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
495 function __construct( $server = false, $user = false, $password = false, $dbName = false,
496 $flags = 0, $tablePrefix = 'get from global'
498 global $wgDBprefix, $wgCommandLineMode;
500 $this->mFlags
= $flags;
502 if ( $this->mFlags
& DBO_DEFAULT
) {
503 if ( $wgCommandLineMode ) {
504 $this->mFlags
&= ~DBO_TRX
;
506 $this->mFlags |
= DBO_TRX
;
510 /** Get the default table prefix*/
511 if ( $tablePrefix == 'get from global' ) {
512 $this->mTablePrefix
= $wgDBprefix;
514 $this->mTablePrefix
= $tablePrefix;
518 $this->open( $server, $user, $password, $dbName );
523 * Same as new DatabaseMysql( ... ), kept for backward compatibility
526 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
527 wfDeprecated( __METHOD__
);
528 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
532 * Given a DB type, construct the name of the appropriate child class of
533 * DatabaseBase. This is designed to replace all of the manual stuff like:
534 * $class = 'Database' . ucfirst( strtolower( $type ) );
535 * as well as validate against the canonical list of DB types we have
537 * This factory function is mostly useful for when you need to connect to a
538 * database other than the MediaWiki default (such as for external auth,
539 * an extension, et cetera). Do not use this to connect to the MediaWiki
540 * database. Example uses in core:
541 * @see LoadBalancer::reallyOpenConnection()
542 * @see ExternalUser_MediaWiki::initFromCond()
543 * @see ForeignDBRepo::getMasterDB()
544 * @see WebInstaller_DBConnect::execute()
546 * @param $dbType String A possible DB type
547 * @param $p Array An array of options to pass to the constructor.
548 * Valid options are: host, user, password, dbname, flags, tableprefix
549 * @return DatabaseBase subclass or null
551 public final static function newFromType( $dbType, $p = array() ) {
552 $canonicalDBTypes = array(
553 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
555 $dbType = strtolower( $dbType );
557 if( in_array( $dbType, $canonicalDBTypes ) ) {
558 $class = 'Database' . ucfirst( $dbType );
560 isset( $p['host'] ) ?
$p['host'] : false,
561 isset( $p['user'] ) ?
$p['user'] : false,
562 isset( $p['password'] ) ?
$p['password'] : false,
563 isset( $p['dbname'] ) ?
$p['dbname'] : false,
564 isset( $p['flags'] ) ?
$p['flags'] : 0,
565 isset( $p['tableprefix'] ) ?
$p['tableprefix'] : 'get from global'
572 protected function installErrorHandler() {
573 $this->mPHPError
= false;
574 $this->htmlErrors
= ini_set( 'html_errors', '0' );
575 set_error_handler( array( $this, 'connectionErrorHandler' ) );
578 protected function restoreErrorHandler() {
579 restore_error_handler();
580 if ( $this->htmlErrors
!== false ) {
581 ini_set( 'html_errors', $this->htmlErrors
);
583 if ( $this->mPHPError
) {
584 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
585 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
592 protected function connectionErrorHandler( $errno, $errstr ) {
593 $this->mPHPError
= $errstr;
597 * Closes a database connection.
598 * if it is open : commits any open transactions
600 * @return Bool operation success. true if already closed.
603 # Stub, should probably be overridden
608 * @param $error String: fallback error message, used if none is given by DB
610 function reportConnectionError( $error = 'Unknown error' ) {
611 $myError = $this->lastError();
617 throw new DBConnectionError( $this, $error );
621 * Determine whether a query writes to the DB.
622 * Should return true if unsure.
624 function isWriteQuery( $sql ) {
625 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
629 * Usually aborts on failure. If errors are explicitly ignored, returns success.
631 * @param $sql String: SQL query
632 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
633 * comment (you can use __METHOD__ or add some extra info)
634 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
635 * maybe best to catch the exception instead?
636 * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
637 * or false on failure if $tempIgnore set
638 * @throws DBQueryError Thrown when the database returns an error of any kind
640 public function query( $sql, $fname = '', $tempIgnore = false ) {
641 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
642 if ( !Profiler
::instance()->isStub() ) {
643 # generalizeSQL will probably cut down the query to reasonable
644 # logging size most of the time. The substr is really just a sanity check.
646 # Who's been wasting my precious column space? -- TS
647 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
650 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
651 $totalProf = 'DatabaseBase::query-master';
653 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
654 $totalProf = 'DatabaseBase::query';
657 wfProfileIn( $totalProf );
658 wfProfileIn( $queryProf );
661 $this->mLastQuery
= $sql;
662 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
663 // Set a flag indicating that writes have been done
664 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
665 $this->mDoneWrites
= true;
668 # Add a comment for easy SHOW PROCESSLIST interpretation
671 if ( is_object( $wgUser ) && $wgUser->mDataLoaded
) {
672 $userName = $wgUser->getName();
673 if ( mb_strlen( $userName ) > 15 ) {
674 $userName = mb_substr( $userName, 0, 15 ) . '...';
676 $userName = str_replace( '/', '', $userName );
680 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
682 # $commentedSql = $sql;
685 # If DBO_TRX is set, start a transaction
686 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
687 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
688 // avoid establishing transactions for SHOW and SET statements too -
689 // that would delay transaction initializations to once connection
690 // is really used by application
691 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
692 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
696 if ( $this->debug() ) {
700 $sqlx = substr( $commentedSql, 0, 500 );
701 $sqlx = strtr( $sqlx, "\t\n", ' ' );
704 wfDebug( "Query $cnt (master): $sqlx\n" );
706 wfDebug( "Query $cnt (slave): $sqlx\n" );
710 if ( istainted( $sql ) & TC_MYSQL
) {
711 throw new MWException( 'Tainted query found' );
714 # Do the query and handle errors
715 $ret = $this->doQuery( $commentedSql );
717 # Try reconnecting if the connection was lost
718 if ( false === $ret && $this->wasErrorReissuable() ) {
719 # Transaction is gone, like it or not
720 $this->mTrxLevel
= 0;
721 wfDebug( "Connection lost, reconnecting...\n" );
723 if ( $this->ping() ) {
724 wfDebug( "Reconnected\n" );
725 $sqlx = substr( $commentedSql, 0, 500 );
726 $sqlx = strtr( $sqlx, "\t\n", ' ' );
727 global $wgRequestTime;
728 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
729 if ( $elapsed < 300 ) {
730 # Not a database error to lose a transaction after a minute or two
731 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
733 $ret = $this->doQuery( $commentedSql );
735 wfDebug( "Failed\n" );
739 if ( false === $ret ) {
740 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
743 if ( !Profiler
::instance()->isStub() ) {
744 wfProfileOut( $queryProf );
745 wfProfileOut( $totalProf );
748 return $this->resultObject( $ret );
752 * @param $error String
753 * @param $errno Integer
755 * @param $fname String
756 * @param $tempIgnore Boolean
758 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
759 # Ignore errors during error handling to avoid infinite recursion
760 $ignore = $this->ignoreErrors( true );
761 ++
$this->mErrorCount
;
763 if ( $ignore ||
$tempIgnore ) {
764 wfDebug( "SQL ERROR (ignored): $error\n" );
765 $this->ignoreErrors( $ignore );
767 $sql1line = str_replace( "\n", "\\n", $sql );
768 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
769 wfDebug( "SQL ERROR: " . $error . "\n" );
770 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
776 * Intended to be compatible with the PEAR::DB wrapper functions.
777 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
779 * ? = scalar value, quoted as necessary
780 * ! = raw SQL bit (a function for instance)
781 * & = filename; reads the file and inserts as a blob
782 * (we don't use this though...)
784 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
785 /* MySQL doesn't support prepared statements (yet), so just
786 pack up the query for reference. We'll manually replace
788 return array( 'query' => $sql, 'func' => $func );
791 function freePrepared( $prepared ) {
792 /* No-op by default */
796 * Execute a prepared query with the various arguments
797 * @param $prepared String: the prepared sql
798 * @param $args Mixed: Either an array here, or put scalars as varargs
800 function execute( $prepared, $args = null ) {
801 if ( !is_array( $args ) ) {
803 $args = func_get_args();
804 array_shift( $args );
807 $sql = $this->fillPrepared( $prepared['query'], $args );
809 return $this->query( $sql, $prepared['func'] );
813 * Prepare & execute an SQL statement, quoting and inserting arguments
814 * in the appropriate places.
815 * @param $query String
818 function safeQuery( $query, $args = null ) {
819 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
821 if ( !is_array( $args ) ) {
823 $args = func_get_args();
824 array_shift( $args );
827 $retval = $this->execute( $prepared, $args );
828 $this->freePrepared( $prepared );
834 * For faking prepared SQL statements on DBs that don't support
836 * @param $preparedQuery String: a 'preparable' SQL statement
837 * @param $args Array of arguments to fill it with
838 * @return string executable SQL
840 function fillPrepared( $preparedQuery, $args ) {
842 $this->preparedArgs
=& $args;
844 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
845 array( &$this, 'fillPreparedArg' ), $preparedQuery );
849 * preg_callback func for fillPrepared()
850 * The arguments should be in $this->preparedArgs and must not be touched
851 * while we're doing this.
853 * @param $matches Array
857 function fillPreparedArg( $matches ) {
858 switch( $matches[1] ) {
859 case '\\?': return '?';
860 case '\\!': return '!';
861 case '\\&': return '&';
864 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
866 switch( $matches[1] ) {
867 case '?': return $this->addQuotes( $arg );
868 case '!': return $arg;
870 # return $this->addQuotes( file_get_contents( $arg ) );
871 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
873 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
878 * Free a result object
879 * @param $res Mixed: A SQL result
881 function freeResult( $res ) {
882 # Stub. Might not really need to be overridden, since results should
883 # be freed by PHP when the variable goes out of scope anyway.
887 * Simple UPDATE wrapper
888 * Usually aborts on failure
889 * If errors are explicitly ignored, returns success
891 * This function exists for historical reasons, DatabaseBase::update() has a more standard
892 * calling convention and feature set
894 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
895 $table = $this->tableName( $table );
896 $sql = "UPDATE $table SET $var = '" .
897 $this->strencode( $value ) . "' WHERE ($cond)";
899 return (bool)$this->query( $sql, $fname );
903 * Simple SELECT wrapper, returns a single field, input must be encoded
904 * Usually aborts on failure
905 * If errors are explicitly ignored, returns FALSE on failure
907 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
908 if ( !is_array( $options ) ) {
909 $options = array( $options );
912 $options['LIMIT'] = 1;
914 $res = $this->select( $table, $var, $cond, $fname, $options );
916 if ( $res === false ||
!$this->numRows( $res ) ) {
920 $row = $this->fetchRow( $res );
922 if ( $row !== false ) {
923 return reset( $row );
930 * Returns an optional USE INDEX clause to go after the table, and a
931 * string to go at the end of the query
935 * @param $options Array: associative array of options to be turned into
936 * an SQL query, valid keys are listed in the function.
939 function makeSelectOptions( $options ) {
940 $preLimitTail = $postLimitTail = '';
943 $noKeyOptions = array();
945 foreach ( $options as $key => $option ) {
946 if ( is_numeric( $key ) ) {
947 $noKeyOptions[$option] = true;
951 if ( isset( $options['GROUP BY'] ) ) {
952 $gb = is_array( $options['GROUP BY'] )
953 ?
implode( ',', $options['GROUP BY'] )
954 : $options['GROUP BY'];
955 $preLimitTail .= " GROUP BY {$gb}";
958 if ( isset( $options['HAVING'] ) ) {
959 $preLimitTail .= " HAVING {$options['HAVING']}";
962 if ( isset( $options['ORDER BY'] ) ) {
963 $ob = is_array( $options['ORDER BY'] )
964 ?
implode( ',', $options['ORDER BY'] )
965 : $options['ORDER BY'];
966 $preLimitTail .= " ORDER BY {$ob}";
969 // if (isset($options['LIMIT'])) {
970 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
971 // isset($options['OFFSET']) ? $options['OFFSET']
975 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
976 $postLimitTail .= ' FOR UPDATE';
979 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
980 $postLimitTail .= ' LOCK IN SHARE MODE';
983 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
984 $startOpts .= 'DISTINCT';
987 # Various MySQL extensions
988 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
989 $startOpts .= ' /*! STRAIGHT_JOIN */';
992 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
993 $startOpts .= ' HIGH_PRIORITY';
996 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
997 $startOpts .= ' SQL_BIG_RESULT';
1000 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1001 $startOpts .= ' SQL_BUFFER_RESULT';
1004 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1005 $startOpts .= ' SQL_SMALL_RESULT';
1008 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1009 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1012 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1013 $startOpts .= ' SQL_CACHE';
1016 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1017 $startOpts .= ' SQL_NO_CACHE';
1020 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1021 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1026 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1032 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1033 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1034 * @param $conds Mixed: Array or string, condition(s) for WHERE
1035 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1036 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1037 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1038 * @param $join_conds Array: Associative array of table join conditions (optional)
1039 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1040 * @return ResultWrapper|Bool Database result resource (feed to DatabaseBase::fetchObject
1041 * or whatever), or false on failure
1043 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1044 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1046 return $this->query( $sql, $fname );
1052 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1053 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1054 * @param $conds Mixed: Array or string, condition(s) for WHERE
1055 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1056 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1057 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1058 * @param $join_conds Array: Associative array of table join conditions (optional)
1059 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1060 * @return string, the SQL text
1062 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1063 if ( is_array( $vars ) ) {
1064 $vars = implode( ',', $vars );
1067 if ( !is_array( $options ) ) {
1068 $options = array( $options );
1071 if ( is_array( $table ) ) {
1072 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1073 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1075 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1077 } elseif ( $table != '' ) {
1078 if ( $table { 0 } == ' ' ) {
1079 $from = ' FROM ' . $table;
1081 $from = ' FROM ' . $this->tableName( $table );
1087 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1089 if ( !empty( $conds ) ) {
1090 if ( is_array( $conds ) ) {
1091 $conds = $this->makeList( $conds, LIST_AND
);
1093 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1095 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1098 if ( isset( $options['LIMIT'] ) )
1099 $sql = $this->limitResult( $sql, $options['LIMIT'],
1100 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1101 $sql = "$sql $postLimitTail";
1103 if ( isset( $options['EXPLAIN'] ) ) {
1104 $sql = 'EXPLAIN ' . $sql;
1111 * Single row SELECT wrapper
1112 * Aborts or returns FALSE on error
1114 * @param $table String: table name
1115 * @param $vars String: the selected variables
1116 * @param $conds Array: a condition map, terms are ANDed together.
1117 * Items with numeric keys are taken to be literal conditions
1118 * Takes an array of selected variables, and a condition map, which is ANDed
1119 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1120 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1121 * $obj- >page_id is the ID of the Astronomy article
1122 * @param $fname String: Calling function name
1123 * @param $options Array
1124 * @param $join_conds Array
1126 * @return ResultWrapper|Bool
1128 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1129 $options['LIMIT'] = 1;
1130 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1132 if ( $res === false ) {
1136 if ( !$this->numRows( $res ) ) {
1140 $obj = $this->fetchObject( $res );
1146 * Estimate rows in dataset
1147 * Returns estimated count - not necessarily an accurate estimate across different databases,
1149 * Takes same arguments as DatabaseBase::select()
1151 * @param $table String: table name
1152 * @param $vars Array: unused
1153 * @param $conds Array: filters on the table
1154 * @param $fname String: function name for profiling
1155 * @param $options Array: options for select
1156 * @return Integer: row count
1158 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1160 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1163 $row = $this->fetchRow( $res );
1164 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1171 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1172 * It's only slightly flawed. Don't use for anything important.
1174 * @param $sql String: A SQL Query
1176 static function generalizeSQL( $sql ) {
1177 # This does the same as the regexp below would do, but in such a way
1178 # as to avoid crashing php on some large strings.
1179 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1181 $sql = str_replace ( "\\\\", '', $sql );
1182 $sql = str_replace ( "\\'", '', $sql );
1183 $sql = str_replace ( "\\\"", '', $sql );
1184 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1185 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1187 # All newlines, tabs, etc replaced by single space
1188 $sql = preg_replace ( '/\s+/', ' ', $sql );
1191 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1197 * Determines whether a field exists in a table
1199 * @param $table String: table name
1200 * @param $field String: filed to check on that table
1201 * @param $fname String: calling function name (optional)
1202 * @return Boolean: whether $table has filed $field
1204 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1205 $info = $this->fieldInfo( $table, $field );
1211 * Determines whether an index exists
1212 * Usually aborts on failure
1213 * If errors are explicitly ignored, returns NULL on failure
1215 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1216 $info = $this->indexInfo( $table, $index, $fname );
1217 if ( is_null( $info ) ) {
1220 return $info !== false;
1225 * Query whether a given table exists
1227 function tableExists( $table ) {
1228 $table = $this->tableName( $table );
1229 $old = $this->ignoreErrors( true );
1230 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1231 $this->ignoreErrors( $old );
1237 * mysql_field_type() wrapper
1239 function fieldType( $res, $index ) {
1240 if ( $res instanceof ResultWrapper
) {
1241 $res = $res->result
;
1244 return mysql_field_type( $res, $index );
1248 * Determines if a given index is unique
1250 function indexUnique( $table, $index ) {
1251 $indexInfo = $this->indexInfo( $table, $index );
1253 if ( !$indexInfo ) {
1257 return !$indexInfo[0]->Non_unique
;
1261 * INSERT wrapper, inserts an array into a table
1263 * $a may be a single associative array, or an array of these with numeric keys, for
1266 * Usually aborts on failure
1267 * If errors are explicitly ignored, returns success
1269 * @param $table String: table name (prefix auto-added)
1270 * @param $a Array: Array of rows to insert
1271 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1272 * @param $options Mixed: Associative array of options
1276 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1277 # No rows to insert, easy just return now
1278 if ( !count( $a ) ) {
1282 $table = $this->tableName( $table );
1284 if ( !is_array( $options ) ) {
1285 $options = array( $options );
1288 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1290 $keys = array_keys( $a[0] );
1293 $keys = array_keys( $a );
1296 $sql = 'INSERT ' . implode( ' ', $options ) .
1297 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1301 foreach ( $a as $row ) {
1307 $sql .= '(' . $this->makeList( $row ) . ')';
1310 $sql .= '(' . $this->makeList( $a ) . ')';
1313 return (bool)$this->query( $sql, $fname );
1317 * Make UPDATE options for the DatabaseBase::update function
1320 * @param $options Array: The options passed to DatabaseBase::update
1323 function makeUpdateOptions( $options ) {
1324 if ( !is_array( $options ) ) {
1325 $options = array( $options );
1330 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1331 $opts[] = $this->lowPriorityOption();
1334 if ( in_array( 'IGNORE', $options ) ) {
1338 return implode( ' ', $opts );
1342 * UPDATE wrapper, takes a condition array and a SET array
1344 * @param $table String: The table to UPDATE
1345 * @param $values Array: An array of values to SET
1346 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1347 * @param $fname String: The Class::Function calling this function
1349 * @param $options Array: An array of UPDATE options, can be one or
1350 * more of IGNORE, LOW_PRIORITY
1353 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1354 $table = $this->tableName( $table );
1355 $opts = $this->makeUpdateOptions( $options );
1356 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1358 if ( $conds != '*' ) {
1359 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1362 return $this->query( $sql, $fname );
1366 * Makes an encoded list of strings from an array
1369 * LIST_COMMA - comma separated, no field names
1370 * LIST_AND - ANDed WHERE clause (without the WHERE)
1371 * LIST_OR - ORed WHERE clause (without the WHERE)
1372 * LIST_SET - comma separated with field names, like a SET clause
1373 * LIST_NAMES - comma separated field names
1377 function makeList( $a, $mode = LIST_COMMA
) {
1378 if ( !is_array( $a ) ) {
1379 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1385 foreach ( $a as $field => $value ) {
1387 if ( $mode == LIST_AND
) {
1389 } elseif ( $mode == LIST_OR
) {
1398 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1399 $list .= "($value)";
1400 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1402 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1403 if ( count( $value ) == 0 ) {
1404 throw new MWException( __METHOD__
. ': empty input' );
1405 } elseif ( count( $value ) == 1 ) {
1406 // Special-case single values, as IN isn't terribly efficient
1407 // Don't necessarily assume the single key is 0; we don't
1408 // enforce linear numeric ordering on other arrays here.
1409 $value = array_values( $value );
1410 $list .= $field . " = " . $this->addQuotes( $value[0] );
1412 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1414 } elseif ( $value === null ) {
1415 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1416 $list .= "$field IS ";
1417 } elseif ( $mode == LIST_SET
) {
1418 $list .= "$field = ";
1422 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1423 $list .= "$field = ";
1425 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1433 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1434 * The keys on each level may be either integers or strings.
1436 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1437 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1438 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1439 * @return Mixed: string SQL fragment, or false if no items in array.
1441 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1444 foreach ( $data as $base => $sub ) {
1445 if ( count( $sub ) ) {
1446 $conds[] = $this->makeList(
1447 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1453 return $this->makeList( $conds, LIST_OR
);
1455 // Nothing to search for...
1461 * Bitwise operations
1464 function bitNot( $field ) {
1468 function bitAnd( $fieldLeft, $fieldRight ) {
1469 return "($fieldLeft & $fieldRight)";
1472 function bitOr( $fieldLeft, $fieldRight ) {
1473 return "($fieldLeft | $fieldRight)";
1477 * Change the current database
1479 * @todo Explain what exactly will fail if this is not overridden.
1480 * @return bool Success or failure
1482 function selectDB( $db ) {
1483 # Stub. Shouldn't cause serious problems if it's not overridden, but
1484 # if your database engine supports a concept similar to MySQL's
1485 # databases you may as well.
1486 $this->mDBname
= $db;
1491 * Get the current DB name
1493 function getDBname() {
1494 return $this->mDBname
;
1498 * Get the server hostname or IP address
1500 function getServer() {
1501 return $this->mServer
;
1505 * Format a table name ready for use in constructing an SQL query
1507 * This does two important things: it quotes the table names to clean them up,
1508 * and it adds a table prefix if only given a table name with no quotes.
1510 * All functions of this object which require a table name call this function
1511 * themselves. Pass the canonical name to such functions. This is only needed
1512 * when calling query() directly.
1514 * @param $name String: database table name
1515 * @param $quoted Boolean: Automatically pass the table name through
1516 * addIdentifierQuotes() so that it can be used in a query.
1517 * @return String: full database name
1519 function tableName( $name, $quoted = true ) {
1520 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1521 # Skip the entire process when we have a string quoted on both ends.
1522 # Note that we check the end so that we will still quote any use of
1523 # use of `database`.table. But won't break things if someone wants
1524 # to query a database table with a dot in the name.
1525 if ( $this->isQuotedIdentifier( $name ) ) {
1529 # Lets test for any bits of text that should never show up in a table
1530 # name. Basically anything like JOIN or ON which are actually part of
1531 # SQL queries, but may end up inside of the table value to combine
1532 # sql. Such as how the API is doing.
1533 # Note that we use a whitespace test rather than a \b test to avoid
1534 # any remote case where a word like on may be inside of a table name
1535 # surrounded by symbols which may be considered word breaks.
1536 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1540 # Split database and table into proper variables.
1541 # We reverse the explode so that database.table and table both output
1542 # the correct table.
1543 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1544 if ( isset( $dbDetails[1] ) ) {
1545 @list
( $table, $database ) = $dbDetails;
1547 @list
( $table ) = $dbDetails;
1549 $prefix = $this->mTablePrefix
; # Default prefix
1551 # Note that we use the long format because php will complain in in_array if
1552 # the input is not an array, and will complain in is_array if it is not set.
1553 if ( !isset( $database ) # Don't use shared database if pre selected.
1554 && isset( $wgSharedDB ) # We have a shared database
1555 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1556 && isset( $wgSharedTables )
1557 && is_array( $wgSharedTables )
1558 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1559 $database = $wgSharedDB;
1560 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1563 # Quote the $database and $table and apply the prefix if not quoted.
1564 if ( isset( $database ) ) {
1565 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1569 $table = "{$prefix}{$table}";
1570 if ( $quoted && !$this->isQuotedIdentifier( $table ) ) {
1571 $table = $this->addIdentifierQuotes( "{$table}" );
1574 # Merge our database and table into our final table name.
1575 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1581 * Fetch a number of table names into an array
1582 * This is handy when you need to construct SQL for joins
1585 * extract($dbr->tableNames('user','watchlist'));
1586 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1587 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1589 public function tableNames() {
1590 $inArray = func_get_args();
1593 foreach ( $inArray as $name ) {
1594 $retVal[$name] = $this->tableName( $name );
1601 * Fetch a number of table names into an zero-indexed numerical array
1602 * This is handy when you need to construct SQL for joins
1605 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1606 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1607 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1609 public function tableNamesN() {
1610 $inArray = func_get_args();
1613 foreach ( $inArray as $name ) {
1614 $retVal[] = $this->tableName( $name );
1621 * Get an aliased table name
1622 * e.g. tableName AS newTableName
1624 * @param $name string Table name, see tableName()
1625 * @param $alias string Alias (optional)
1626 * @return string SQL name for aliased table. Will not alias a table to its own name
1628 public function tableNameWithAlias( $name, $alias = false ) {
1629 if ( !$alias ||
$alias == $name ) {
1630 return $this->tableName( $name );
1632 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1637 * Gets an array of aliased table names
1639 * @param $tables array( [alias] => table )
1640 * @return array of strings, see tableNameWithAlias()
1642 public function tableNamesWithAlias( $tables ) {
1644 foreach ( $tables as $alias => $table ) {
1645 if ( is_numeric( $alias ) ) {
1648 $retval[] = $this->tableNameWithAlias( $table, $alias );
1656 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1659 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1660 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1662 foreach ( $tables as $alias => $table ) {
1663 if ( !is_string( $alias ) ) {
1664 // No alias? Set it equal to the table name
1667 // Is there a JOIN and INDEX clause for this table?
1668 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1669 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1670 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1671 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1673 $tableClause .= ' ON (' . $on . ')';
1676 $retJOIN[] = $tableClause;
1677 // Is there an INDEX clause?
1678 } else if ( isset( $use_index_safe[$alias] ) ) {
1679 $tableClause = $this->tableNameWithAlias( $table, $alias );
1680 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1681 $ret[] = $tableClause;
1682 // Is there a JOIN clause?
1683 } else if ( isset( $join_conds_safe[$alias] ) ) {
1684 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1685 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1687 $tableClause .= ' ON (' . $on . ')';
1690 $retJOIN[] = $tableClause;
1692 $tableClause = $this->tableNameWithAlias( $table, $alias );
1693 $ret[] = $tableClause;
1697 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1698 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1699 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1701 // Compile our final table clause
1702 return implode( ' ', array( $straightJoins, $otherJoins ) );
1706 * Get the name of an index in a given table
1708 function indexName( $index ) {
1709 // Backwards-compatibility hack
1711 'ar_usertext_timestamp' => 'usertext_timestamp',
1712 'un_user_id' => 'user_id',
1713 'un_user_ip' => 'user_ip',
1716 if ( isset( $renamed[$index] ) ) {
1717 return $renamed[$index];
1724 * If it's a string, adds quotes and backslashes
1725 * Otherwise returns as-is
1727 function addQuotes( $s ) {
1728 if ( $s === null ) {
1731 # This will also quote numeric values. This should be harmless,
1732 # and protects against weird problems that occur when they really
1733 # _are_ strings such as article titles and string->number->string
1734 # conversion is not 1:1.
1735 return "'" . $this->strencode( $s ) . "'";
1740 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1741 * MySQL uses `backticks` while basically everything else uses double quotes.
1742 * Since MySQL is the odd one out here the double quotes are our generic
1743 * and we implement backticks in DatabaseMysql.
1745 public function addIdentifierQuotes( $s ) {
1746 return '"' . str_replace( '"', '""', $s ) . '"';
1750 * Returns if the given identifier looks quoted or not according to
1751 * the database convention for quoting identifiers .
1754 public function isQuotedIdentifier( $name ) {
1755 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1759 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1760 * which used quote_ident which does not follow our naming conventions
1761 * was renamed to addIdentifierQuotes.
1762 * @deprecated use addIdentifierQuotes
1764 function quote_ident( $s ) {
1765 wfDeprecated( __METHOD__
);
1766 return $this->addIdentifierQuotes( $s );
1770 * Escape string for safe LIKE usage.
1771 * WARNING: you should almost never use this function directly,
1772 * instead use buildLike() that escapes everything automatically
1773 * Deprecated in 1.17, warnings in 1.17, removed in ???
1775 public function escapeLike( $s ) {
1776 wfDeprecated( __METHOD__
);
1777 return $this->escapeLikeInternal( $s );
1780 protected function escapeLikeInternal( $s ) {
1781 $s = str_replace( '\\', '\\\\', $s );
1782 $s = $this->strencode( $s );
1783 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1789 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1790 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1791 * Alternatively, the function could be provided with an array of aforementioned parameters.
1793 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1794 * for subpages of 'My page title'.
1795 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1798 * @return String: fully built LIKE statement
1800 function buildLike() {
1801 $params = func_get_args();
1803 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1804 $params = $params[0];
1809 foreach ( $params as $value ) {
1810 if ( $value instanceof LikeMatch
) {
1811 $s .= $value->toString();
1813 $s .= $this->escapeLikeInternal( $value );
1817 return " LIKE '" . $s . "' ";
1821 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1823 function anyChar() {
1824 return new LikeMatch( '_' );
1828 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1830 function anyString() {
1831 return new LikeMatch( '%' );
1835 * Returns an appropriately quoted sequence value for inserting a new row.
1836 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1837 * subclass will return an integer, and save the value for insertId()
1839 function nextSequenceValue( $seqName ) {
1844 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1845 * is only needed because a) MySQL must be as efficient as possible due to
1846 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1847 * which index to pick. Anyway, other databases might have different
1848 * indexes on a given table. So don't bother overriding this unless you're
1851 function useIndexClause( $index ) {
1856 * REPLACE query wrapper
1857 * PostgreSQL simulates this with a DELETE followed by INSERT
1858 * $row is the row to insert, an associative array
1859 * $uniqueIndexes is an array of indexes. Each element may be either a
1860 * field name or an array of field names
1862 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1863 * However if you do this, you run the risk of encountering errors which wouldn't have
1866 * @param $table String: The table to replace the row(s) in.
1867 * @param $uniqueIndexes Array: An associative array of indexes
1868 * @param $rows Array: Array of rows to replace
1869 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1871 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1872 $table = $this->tableName( $table );
1875 if ( !is_array( reset( $rows ) ) ) {
1876 $rows = array( $rows );
1879 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1882 foreach ( $rows as $row ) {
1889 $sql .= '(' . $this->makeList( $row ) . ')';
1892 return $this->query( $sql, $fname );
1896 * DELETE where the condition is a join
1897 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1899 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1900 * join condition matches, set $conds='*'
1902 * DO NOT put the join condition in $conds
1904 * @param $delTable String: The table to delete from.
1905 * @param $joinTable String: The other table.
1906 * @param $delVar String: The variable to join on, in the first table.
1907 * @param $joinVar String: The variable to join on, in the second table.
1908 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1909 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1911 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1913 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1916 $delTable = $this->tableName( $delTable );
1917 $joinTable = $this->tableName( $joinTable );
1918 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1920 if ( $conds != '*' ) {
1921 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1924 return $this->query( $sql, $fname );
1928 * Returns the size of a text field, or -1 for "unlimited"
1930 function textFieldSize( $table, $field ) {
1931 $table = $this->tableName( $table );
1932 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1933 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1934 $row = $this->fetchObject( $res );
1938 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1948 * A string to insert into queries to show that they're low-priority, like
1949 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1950 * string and nothing bad should happen.
1952 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1954 function lowPriorityOption() {
1959 * DELETE query wrapper
1961 * Use $conds == "*" to delete all rows
1963 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1965 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1968 $table = $this->tableName( $table );
1969 $sql = "DELETE FROM $table";
1971 if ( $conds != '*' ) {
1972 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1975 return $this->query( $sql, $fname );
1979 * INSERT SELECT wrapper
1980 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1981 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1982 * $conds may be "*" to copy the whole table
1983 * srcTable may be an array of tables.
1985 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1986 $insertOptions = array(), $selectOptions = array() )
1988 $destTable = $this->tableName( $destTable );
1990 if ( is_array( $insertOptions ) ) {
1991 $insertOptions = implode( ' ', $insertOptions );
1994 if ( !is_array( $selectOptions ) ) {
1995 $selectOptions = array( $selectOptions );
1998 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
2000 if ( is_array( $srcTable ) ) {
2001 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2003 $srcTable = $this->tableName( $srcTable );
2006 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2007 " SELECT $startOpts " . implode( ',', $varMap ) .
2008 " FROM $srcTable $useIndex ";
2010 if ( $conds != '*' ) {
2011 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2014 $sql .= " $tailOpts";
2016 return $this->query( $sql, $fname );
2020 * Construct a LIMIT query with optional offset. This is used for query
2021 * pages. The SQL should be adjusted so that only the first $limit rows
2022 * are returned. If $offset is provided as well, then the first $offset
2023 * rows should be discarded, and the next $limit rows should be returned.
2024 * If the result of the query is not ordered, then the rows to be returned
2025 * are theoretically arbitrary.
2027 * $sql is expected to be a SELECT, if that makes a difference. For
2028 * UPDATE, limitResultForUpdate should be used.
2030 * The version provided by default works in MySQL and SQLite. It will very
2031 * likely need to be overridden for most other DBMSes.
2033 * @param $sql String: SQL query we will append the limit too
2034 * @param $limit Integer: the SQL limit
2035 * @param $offset Integer the SQL offset (default false)
2037 function limitResult( $sql, $limit, $offset = false ) {
2038 if ( !is_numeric( $limit ) ) {
2039 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2042 return "$sql LIMIT "
2043 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2047 function limitResultForUpdate( $sql, $num ) {
2048 return $this->limitResult( $sql, $num, 0 );
2052 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2053 * within the UNION construct.
2056 function unionSupportsOrderAndLimit() {
2057 return true; // True for almost every DB supported
2061 * Construct a UNION query
2062 * This is used for providing overload point for other DB abstractions
2063 * not compatible with the MySQL syntax.
2064 * @param $sqls Array: SQL statements to combine
2065 * @param $all Boolean: use UNION ALL
2066 * @return String: SQL fragment
2068 function unionQueries( $sqls, $all ) {
2069 $glue = $all ?
') UNION ALL (' : ') UNION (';
2070 return '(' . implode( $glue, $sqls ) . ')';
2074 * Returns an SQL expression for a simple conditional. This doesn't need
2075 * to be overridden unless CASE isn't supported in your DBMS.
2077 * @param $cond String: SQL expression which will result in a boolean value
2078 * @param $trueVal String: SQL expression to return if true
2079 * @param $falseVal String: SQL expression to return if false
2080 * @return String: SQL fragment
2082 function conditional( $cond, $trueVal, $falseVal ) {
2083 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2087 * Returns a comand for str_replace function in SQL query.
2088 * Uses REPLACE() in MySQL
2090 * @param $orig String: column to modify
2091 * @param $old String: column to seek
2092 * @param $new String: column to replace with
2094 function strreplace( $orig, $old, $new ) {
2095 return "REPLACE({$orig}, {$old}, {$new})";
2099 * Determines if the last failure was due to a deadlock
2102 function wasDeadlock() {
2107 * Determines if the last query error was something that should be dealt
2108 * with by pinging the connection and reissuing the query.
2111 function wasErrorReissuable() {
2116 * Determines if the last failure was due to the database being read-only.
2119 function wasReadOnlyError() {
2124 * Perform a deadlock-prone transaction.
2126 * This function invokes a callback function to perform a set of write
2127 * queries. If a deadlock occurs during the processing, the transaction
2128 * will be rolled back and the callback function will be called again.
2131 * $dbw->deadlockLoop( callback, ... );
2133 * Extra arguments are passed through to the specified callback function.
2135 * Returns whatever the callback function returned on its successful,
2136 * iteration, or false on error, for example if the retry limit was
2139 function deadlockLoop() {
2140 $myFname = 'DatabaseBase::deadlockLoop';
2143 $args = func_get_args();
2144 $function = array_shift( $args );
2145 $oldIgnore = $this->ignoreErrors( true );
2146 $tries = DEADLOCK_TRIES
;
2148 if ( is_array( $function ) ) {
2149 $fname = $function[0];
2155 $retVal = call_user_func_array( $function, $args );
2156 $error = $this->lastError();
2157 $errno = $this->lastErrno();
2158 $sql = $this->lastQuery();
2161 if ( $this->wasDeadlock() ) {
2163 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2165 $this->reportQueryError( $error, $errno, $sql, $fname );
2168 } while ( $this->wasDeadlock() && --$tries > 0 );
2170 $this->ignoreErrors( $oldIgnore );
2172 if ( $tries <= 0 ) {
2173 $this->rollback( $myFname );
2174 $this->reportQueryError( $error, $errno, $sql, $fname );
2177 $this->commit( $myFname );
2183 * Do a SELECT MASTER_POS_WAIT()
2185 * @param $pos MySQLMasterPos object
2186 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2188 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2189 $fname = 'DatabaseBase::masterPosWait';
2190 wfProfileIn( $fname );
2192 # Commit any open transactions
2193 if ( $this->mTrxLevel
) {
2197 if ( !is_null( $this->mFakeSlaveLag
) ) {
2198 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2200 if ( $wait > $timeout * 1e6
) {
2201 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2202 wfProfileOut( $fname );
2204 } elseif ( $wait > 0 ) {
2205 wfDebug( "Fake slave waiting $wait us\n" );
2207 wfProfileOut( $fname );
2210 wfDebug( "Fake slave up to date ($wait us)\n" );
2211 wfProfileOut( $fname );
2216 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2217 $encFile = $this->addQuotes( $pos->file
);
2218 $encPos = intval( $pos->pos
);
2219 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2220 $res = $this->doQuery( $sql );
2222 if ( $res && $row = $this->fetchRow( $res ) ) {
2223 wfProfileOut( $fname );
2226 wfProfileOut( $fname );
2232 * Get the position of the master from SHOW SLAVE STATUS
2234 function getSlavePos() {
2235 if ( !is_null( $this->mFakeSlaveLag
) ) {
2236 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2237 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2241 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2242 $row = $this->fetchObject( $res );
2245 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2246 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2253 * Get the position of the master from SHOW MASTER STATUS
2255 function getMasterPos() {
2256 if ( $this->mFakeMaster
) {
2257 return new MySQLMasterPos( 'fake', microtime( true ) );
2260 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2261 $row = $this->fetchObject( $res );
2264 return new MySQLMasterPos( $row->File
, $row->Position
);
2271 * Begin a transaction, committing any previously open transaction
2273 function begin( $fname = 'DatabaseBase::begin' ) {
2274 $this->query( 'BEGIN', $fname );
2275 $this->mTrxLevel
= 1;
2281 function commit( $fname = 'DatabaseBase::commit' ) {
2282 if ( $this->mTrxLevel
) {
2283 $this->query( 'COMMIT', $fname );
2284 $this->mTrxLevel
= 0;
2289 * Rollback a transaction.
2290 * No-op on non-transactional databases.
2292 function rollback( $fname = 'DatabaseBase::rollback' ) {
2293 if ( $this->mTrxLevel
) {
2294 $this->query( 'ROLLBACK', $fname, true );
2295 $this->mTrxLevel
= 0;
2300 * Begin a transaction, committing any previously open transaction
2301 * @deprecated use begin()
2303 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2304 wfDeprecated( __METHOD__
);
2309 * Commit transaction, if one is open
2310 * @deprecated use commit()
2312 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2313 wfDeprecated( __METHOD__
);
2318 * Creates a new table with structure copied from existing table
2319 * Note that unlike most database abstraction functions, this function does not
2320 * automatically append database prefix, because it works at a lower
2321 * abstraction level.
2322 * The table names passed to this function shall not be quoted (this
2323 * function calls addIdentifierQuotes when needed).
2325 * @param $oldName String: name of table whose structure should be copied
2326 * @param $newName String: name of table to be created
2327 * @param $temporary Boolean: whether the new table should be temporary
2328 * @param $fname String: calling function name
2329 * @return Boolean: true if operation was successful
2331 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2332 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2336 * List all tables on the database
2338 * @param $prefix Only show tables with this prefix, e.g. mw_
2339 * @param $fname String: calling function name
2341 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2342 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2346 * Return MW-style timestamp used for MySQL schema
2348 function timestamp( $ts = 0 ) {
2349 return wfTimestamp( TS_MW
, $ts );
2353 * Local database timestamp format or null
2355 function timestampOrNull( $ts = null ) {
2356 if ( is_null( $ts ) ) {
2359 return $this->timestamp( $ts );
2366 function resultObject( $result ) {
2367 if ( empty( $result ) ) {
2369 } elseif ( $result instanceof ResultWrapper
) {
2371 } elseif ( $result === true ) {
2372 // Successful write query
2375 return new ResultWrapper( $this, $result );
2380 * Return aggregated value alias
2382 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2387 * Ping the server and try to reconnect if it there is no connection
2389 * @return bool Success or failure
2392 # Stub. Not essential to override.
2398 * Currently supported only by MySQL
2399 * @return Database replication lag in seconds
2402 return intval( $this->mFakeSlaveLag
);
2406 * Get status information from SHOW STATUS in an associative array
2408 function getStatus( $which = "%" ) {
2409 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2412 foreach ( $res as $row ) {
2413 $status[$row->Variable_name
] = $row->Value
;
2420 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2422 function maxListLen() {
2426 function encodeBlob( $b ) {
2430 function decodeBlob( $b ) {
2435 * Override database's default connection timeout. May be useful for very
2436 * long batch queries such as full-wiki dumps, where a single query reads
2437 * out over hours or days. May or may not be necessary for non-MySQL
2438 * databases. For most purposes, leaving it as a no-op should be fine.
2440 * @param $timeout Integer in seconds
2442 public function setTimeout( $timeout ) {}
2445 * Read and execute SQL commands from a file.
2446 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2447 * @param $filename String: File name to open
2448 * @param $lineCallback Callback: Optional function called before reading each line
2449 * @param $resultCallback Callback: Optional function called for each MySQL result
2450 * @param $fname String: Calling function name or false if name should be generated dynamically
2453 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2454 wfSuppressWarnings();
2455 $fp = fopen( $filename, 'r' );
2456 wfRestoreWarnings();
2458 if ( false === $fp ) {
2459 throw new MWException( "Could not open \"{$filename}\".\n" );
2463 $fname = __METHOD__
. "( $filename )";
2467 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2469 catch ( MWException
$e ) {
2480 * Get the full path of a patch file. Originally based on archive()
2481 * from updaters.inc. Keep in mind this always returns a patch, as
2482 * it fails back to MySQL if no DB-specific patch can be found
2484 * @param $patch String The name of the patch, like patch-something.sql
2485 * @return String Full path to patch file
2487 public function patchPath( $patch ) {
2490 $dbType = $this->getType();
2491 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2492 return "$IP/maintenance/$dbType/archives/$patch";
2494 return "$IP/maintenance/archives/$patch";
2499 * Set variables to be used in sourceFile/sourceStream, in preference to the
2500 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2501 * all. If it's set to false, $GLOBALS will be used.
2503 * @param $vars False, or array mapping variable name to value.
2505 function setSchemaVars( $vars ) {
2506 $this->mSchemaVars
= $vars;
2510 * Read and execute commands from an open file handle
2511 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2512 * @param $fp Resource: File handle
2513 * @param $lineCallback Callback: Optional function called before reading each line
2514 * @param $resultCallback Callback: Optional function called for each MySQL result
2515 * @param $fname String: Calling function name
2517 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2520 $dollarquote = false;
2522 while ( ! feof( $fp ) ) {
2523 if ( $lineCallback ) {
2524 call_user_func( $lineCallback );
2527 $line = trim( fgets( $fp, 1024 ) );
2528 $sl = strlen( $line ) - 1;
2534 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2538 # # Allow dollar quoting for function declarations
2539 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2540 if ( $dollarquote ) {
2541 $dollarquote = false;
2545 $dollarquote = true;
2548 else if ( !$dollarquote ) {
2549 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2551 $line = substr( $line, 0, $sl );
2562 $cmd = str_replace( ';;', ";", $cmd );
2563 $cmd = $this->replaceVars( $cmd );
2564 $res = $this->query( $cmd, $fname );
2566 if ( $resultCallback ) {
2567 call_user_func( $resultCallback, $res, $this );
2570 if ( false === $res ) {
2571 $err = $this->lastError();
2572 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2584 * Database independent variable replacement, replaces a set of variables
2585 * in a sql statement with their contents as given by $this->getSchemaVars().
2586 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2588 * '{$var}' should be used for text and is passed through the database's addQuotes method
2589 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2590 * the database's addIdentifierQuotes method which can be overridden if the database
2591 * uses something other than backticks.
2592 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2594 * @param $ins String: SQL statement to replace variables in
2595 * @return String The new SQL statement with variables replaced
2597 protected function replaceSchemaVars( $ins ) {
2598 $vars = $this->getSchemaVars();
2599 foreach ( $vars as $var => $value ) {
2601 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2603 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2605 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2611 * Replace variables in sourced SQL
2613 protected function replaceVars( $ins ) {
2614 $ins = $this->replaceSchemaVars( $ins );
2617 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2618 array( $this, 'tableNameCallback' ), $ins );
2621 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2622 array( $this, 'indexNameCallback' ), $ins );
2628 * Get schema variables. If none have been set via setSchemaVars(), then
2629 * use some defaults from the current object.
2631 protected function getSchemaVars() {
2632 if ( $this->mSchemaVars
) {
2633 return $this->mSchemaVars
;
2635 return $this->getDefaultSchemaVars();
2640 * Get schema variables to use if none have been set via setSchemaVars().
2641 * Override this in derived classes to provide variables for tables.sql
2642 * and SQL patch files.
2644 protected function getDefaultSchemaVars() {
2649 * Table name callback
2652 protected function tableNameCallback( $matches ) {
2653 return $this->tableName( $matches[1] );
2657 * Index name callback
2659 protected function indexNameCallback( $matches ) {
2660 return $this->indexName( $matches[1] );
2664 * Build a concatenation list to feed into a SQL query
2665 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2668 function buildConcat( $stringList ) {
2669 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2673 * Acquire a named lock
2675 * Abstracted from Filestore::lock() so child classes can implement for
2678 * @param $lockName String: name of lock to aquire
2679 * @param $method String: name of method calling us
2680 * @param $timeout Integer: timeout
2683 public function lock( $lockName, $method, $timeout = 5 ) {
2690 * @param $lockName String: Name of lock to release
2691 * @param $method String: Name of method calling us
2693 * @return Returns 1 if the lock was released, 0 if the lock was not established
2694 * by this thread (in which case the lock is not released), and NULL if the named
2695 * lock did not exist
2697 public function unlock( $lockName, $method ) {
2702 * Lock specific tables
2704 * @param $read Array of tables to lock for read access
2705 * @param $write Array of tables to lock for write access
2706 * @param $method String name of caller
2707 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2709 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2714 * Unlock specific tables
2716 * @param $method String the caller
2718 public function unlockTables( $method ) {
2725 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2726 if( !$this->tableExists( $tableName ) ) {
2729 $sql = "DROP TABLE " . $this->tableName( $tableName );
2730 if( $this->cascadingDeletes() ) {
2733 return $this->query( $sql, $fName );
2737 * Get search engine class. All subclasses of this need to implement this
2738 * if they wish to use searching.
2742 public function getSearchEngine() {
2743 return 'SearchEngineDummy';
2747 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2748 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2749 * because "i" sorts after all numbers.
2753 public function getInfinity() {
2758 * Encode an expiry time
2760 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2763 public function encodeExpiry( $expiry ) {
2764 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
2765 return $this->getInfinity();
2767 return $this->timestamp( $expiry );
2772 * Allow or deny "big selects" for this session only. This is done by setting
2773 * the sql_big_selects session variable.
2775 * This is a MySQL-specific feature.
2777 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2779 public function setBigSelects( $value = true ) {
2784 /******************************************************************************
2786 *****************************************************************************/
2795 function __construct( $data ) {
2796 $this->mData
= $data;
2804 return $this->mData
;
2812 * This allows us to distinguish a blob from a normal string and an array of strings
2817 function __construct( $data ) {
2818 $this->mData
= $data;
2822 return $this->mData
;
2827 * Base for all database-specific classes representing information about database fields
2838 * Name of table this field belongs to
2841 function tableName();
2850 * Whether this field can store NULL values
2853 function isNullable();
2856 /******************************************************************************
2858 *****************************************************************************/
2861 * Database error base class
2864 class DBError
extends MWException
{
2868 * Construct a database error
2869 * @param $db Database object which threw the error
2870 * @param $error String A simple error message to be used for debugging
2872 function __construct( DatabaseBase
&$db, $error ) {
2874 parent
::__construct( $error );
2877 protected function getContentMessage( $html ) {
2879 return nl2br( htmlspecialchars( $this->getMessage() ) );
2881 return $this->getMessage();
2885 function getText() {
2886 global $wgShowDBErrorBacktrace;
2888 $s = $this->getContentMessage( false ) . "\n";
2890 if ( $wgShowDBErrorBacktrace ) {
2891 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2897 function getHTML() {
2898 global $wgShowDBErrorBacktrace;
2900 $s = $this->getContentMessage( true );
2902 if ( $wgShowDBErrorBacktrace ) {
2903 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2913 class DBConnectionError
extends DBError
{
2916 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2917 $msg = 'DB connection error';
2919 if ( trim( $error ) != '' ) {
2923 $this->error
= $error;
2925 parent
::__construct( $db, $msg );
2928 function useOutputPage() {
2929 // Not likely to work
2933 function msg( $key, $fallback /*[, params...] */ ) {
2936 $args = array_slice( func_get_args(), 2 );
2938 if ( $this->useMessageCache() ) {
2939 $message = $wgLang->getMessage( $key );
2941 $message = $fallback;
2943 return wfMsgReplaceArgs( $message, $args );
2946 function getLogMessage() {
2947 # Don't send to the exception log
2951 function getPageTitle() {
2953 return htmlspecialchars( $this->msg( 'dberr-header', "$wgSitename has a problem" ) );
2956 function getHTML() {
2957 global $wgUseFileCache, $wgShowDBErrorBacktrace;
2959 $sorry = htmlspecialchars( $this->msg( 'dberr-problems', 'Sorry! This site is experiencing technical difficulties.' ) );
2960 $again = htmlspecialchars( $this->msg( 'dberr-again', 'Try waiting a few minutes and reloading.' ) );
2961 $info = htmlspecialchars( $this->msg( 'dberr-info', '(Can\'t contact the database server: $1)' ) );
2963 # No database access
2964 MessageCache
::singleton()->disable();
2966 if ( trim( $this->error
) == '' ) {
2967 $this->error
= $this->db
->getProperty( 'mServer' );
2970 $this->error
= Html
::element( 'span', array( 'dir' => 'ltr' ), $this->error
);
2972 $noconnect = "<h1>$sorry</h1><p>$again</p><p><small>$info</small></p>";
2973 $text = str_replace( '$1', $this->error
, $noconnect );
2975 if ( $wgShowDBErrorBacktrace ) {
2976 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2979 $extra = $this->searchForm();
2981 if ( $wgUseFileCache ) {
2983 $cache = $this->fileCachedPage();
2984 # Cached version on file system?
2985 if ( $cache !== null ) {
2986 # Hack: extend the body for error messages
2987 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2988 # Add cache notice...
2989 $cache .= '<div style="color:red;font-size:150%;font-weight:bold;">'.
2990 htmlspecialchars( $this->msg( 'dberr-cachederror',
2991 'This is a cached copy of the requested page, and may not be up to date. ' ) ) .
2994 # Output cached page with notices on bottom and re-close body
2995 return "{$cache}<hr />$text<hr />$extra</body></html>";
2997 } catch ( MWException
$e ) {
2998 // Do nothing, just use the default page
3002 # Headers needed here - output is just the error message
3003 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
3006 function searchForm() {
3007 global $wgSitename, $wgServer;
3009 $usegoogle = htmlspecialchars( $this->msg( 'dberr-usegoogle', 'You can try searching via Google in the meantime.' ) );
3010 $outofdate = htmlspecialchars( $this->msg( 'dberr-outofdate', 'Note that their indexes of our content may be out of date.' ) );
3011 $googlesearch = htmlspecialchars( $this->msg( 'searchbutton', 'Search' ) );
3013 $search = htmlspecialchars( @$_REQUEST['search'] );
3015 $server = htmlspecialchars( $wgServer );
3016 $sitename = htmlspecialchars( $wgSitename );
3019 <div style="margin: 1.5em">$usegoogle<br />
3020 <small>$outofdate</small></div>
3021 <!-- SiteSearch Google -->
3022 <form method="get" action="http://www.google.com/search" id="googlesearch">
3023 <input type="hidden" name="domains" value="$server" />
3024 <input type="hidden" name="num" value="50" />
3025 <input type="hidden" name="ie" value="UTF-8" />
3026 <input type="hidden" name="oe" value="UTF-8" />
3028 <input type="text" name="q" size="31" maxlength="255" value="$search" />
3029 <input type="submit" name="btnG" value="$googlesearch" />
3031 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
3032 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
3035 <!-- SiteSearch Google -->
3040 private function fileCachedPage() {
3041 global $wgTitle, $wgOut;
3043 if ( $wgOut->isDisabled() ) {
3044 return; // Done already?
3050 $t = Title
::newFromText( $this->msg( 'mainpage', 'Main Page' ) );
3053 $cache = new HTMLFileCache( $t );
3054 if ( $cache->isFileCached() ) {
3055 return $cache->fetchPageText();
3061 function htmlBodyOnly() {
3069 class DBQueryError
extends DBError
{
3070 public $error, $errno, $sql, $fname;
3072 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
3073 $message = "A database error has occurred. Did you forget to run maintenance/update.php after upgrading? See: http://www.mediawiki.org/wiki/Manual:Upgrading#Run_the_update_script\n" .
3075 "Function: $fname\n" .
3076 "Error: $errno $error\n";
3078 parent
::__construct( $db, $message );
3080 $this->error
= $error;
3081 $this->errno
= $errno;
3083 $this->fname
= $fname;
3086 function getContentMessage( $html ) {
3087 if ( $this->useMessageCache() ) {
3088 $msg = $html ?
'dberrortext' : 'dberrortextcl';
3089 $ret = wfMsg( $msg, $this->getSQL(),
3090 $this->fname
, $this->errno
, $this->error
);
3092 $ret = htmlspecialchars( $ret );
3096 return parent
::getContentMessage( $html );
3101 global $wgShowSQLErrors;
3103 if ( !$wgShowSQLErrors ) {
3104 return $this->msg( 'sqlhidden', 'SQL hidden' );
3110 function getLogMessage() {
3111 # Don't send to the exception log
3115 function getPageTitle() {
3116 return $this->msg( 'databaseerror', 'Database error' );
3123 class DBUnexpectedError
extends DBError
{}
3127 * Result wrapper for grabbing data queried by someone else
3130 class ResultWrapper
implements Iterator
{
3131 var $db, $result, $pos = 0, $currentRow = null;
3134 * Create a new result object from a result resource and a Database object
3136 * @param DatabaseBase $database
3137 * @param resource $result
3139 function __construct( $database, $result ) {
3140 $this->db
= $database;
3142 if ( $result instanceof ResultWrapper
) {
3143 $this->result
= $result->result
;
3145 $this->result
= $result;
3150 * Get the number of rows in a result object
3154 function numRows() {
3155 return $this->db
->numRows( $this );
3159 * Fetch the next row from the given result object, in object form.
3160 * Fields can be retrieved with $row->fieldname, with fields acting like
3164 * @throws DBUnexpectedError Thrown if the database returns an error
3166 function fetchObject() {
3167 return $this->db
->fetchObject( $this );
3171 * Fetch the next row from the given result object, in associative array
3172 * form. Fields are retrieved with $row['fieldname'].
3175 * @throws DBUnexpectedError Thrown if the database returns an error
3177 function fetchRow() {
3178 return $this->db
->fetchRow( $this );
3182 * Free a result object
3185 $this->db
->freeResult( $this );
3186 unset( $this->result
);
3191 * Change the position of the cursor in a result object.
3192 * See mysql_data_seek()
3194 * @param $row integer
3196 function seek( $row ) {
3197 $this->db
->dataSeek( $this, $row );
3200 /*********************
3201 * Iterator functions
3202 * Note that using these in combination with the non-iterator functions
3203 * above may cause rows to be skipped or repeated.
3207 if ( $this->numRows() ) {
3208 $this->db
->dataSeek( $this, 0 );
3211 $this->currentRow
= null;
3214 function current() {
3215 if ( is_null( $this->currentRow
) ) {
3218 return $this->currentRow
;
3227 $this->currentRow
= $this->fetchObject();
3228 return $this->currentRow
;
3232 return $this->current() !== false;
3237 * Overloads the relevant methods of the real ResultsWrapper so it
3238 * doesn't go anywhere near an actual database.
3240 class FakeResultWrapper
extends ResultWrapper
{
3241 var $result = array();
3242 var $db = null; // And it's going to stay that way :D
3244 var $currentRow = null;
3246 function __construct( $array ) {
3247 $this->result
= $array;
3250 function numRows() {
3251 return count( $this->result
);
3254 function fetchRow() {
3255 $this->currentRow
= $this->result
[$this->pos++
];
3256 return $this->currentRow
;
3259 function seek( $row ) {
3265 // Callers want to be able to access fields with $this->fieldName
3266 function fetchObject() {
3267 $this->currentRow
= $this->result
[$this->pos++
];
3268 return (object)$this->currentRow
;
3273 $this->currentRow
= null;
3278 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3279 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3285 * Store a string into a LikeMatch marker object.
3289 public function __construct( $s ) {
3294 * Return the original stored string.
3298 public function toString() {