7bb13dfba7e52b16ad142bdf013e251e006a6f55
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 ) {
643 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
644 if ( isset( $wgProfiler ) ) {
645 # generalizeSQL will probably cut down the query to reasonable
646 # logging size most of the time. The substr is really just a sanity check.
648 # Who's been wasting my precious column space? -- TS
649 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
652 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
653 $totalProf = 'DatabaseBase::query-master';
655 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
656 $totalProf = 'DatabaseBase::query';
659 wfProfileIn( $totalProf );
660 wfProfileIn( $queryProf );
663 $this->mLastQuery
= $sql;
664 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
665 // Set a flag indicating that writes have been done
666 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
667 $this->mDoneWrites
= true;
670 # Add a comment for easy SHOW PROCESSLIST interpretation
673 if ( is_object( $wgUser ) && $wgUser->mDataLoaded
) {
674 $userName = $wgUser->getName();
675 if ( mb_strlen( $userName ) > 15 ) {
676 $userName = mb_substr( $userName, 0, 15 ) . '...';
678 $userName = str_replace( '/', '', $userName );
682 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
684 # $commentedSql = $sql;
687 # If DBO_TRX is set, start a transaction
688 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
689 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
690 // avoid establishing transactions for SHOW and SET statements too -
691 // that would delay transaction initializations to once connection
692 // is really used by application
693 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
694 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
698 if ( $this->debug() ) {
702 $sqlx = substr( $commentedSql, 0, 500 );
703 $sqlx = strtr( $sqlx, "\t\n", ' ' );
706 wfDebug( "Query $cnt (master): $sqlx\n" );
708 wfDebug( "Query $cnt (slave): $sqlx\n" );
712 if ( istainted( $sql ) & TC_MYSQL
) {
713 throw new MWException( 'Tainted query found' );
716 # Do the query and handle errors
717 $ret = $this->doQuery( $commentedSql );
719 # Try reconnecting if the connection was lost
720 if ( false === $ret && $this->wasErrorReissuable() ) {
721 # Transaction is gone, like it or not
722 $this->mTrxLevel
= 0;
723 wfDebug( "Connection lost, reconnecting...\n" );
725 if ( $this->ping() ) {
726 wfDebug( "Reconnected\n" );
727 $sqlx = substr( $commentedSql, 0, 500 );
728 $sqlx = strtr( $sqlx, "\t\n", ' ' );
729 global $wgRequestTime;
730 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
731 if ( $elapsed < 300 ) {
732 # Not a database error to lose a transaction after a minute or two
733 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
735 $ret = $this->doQuery( $commentedSql );
737 wfDebug( "Failed\n" );
741 if ( false === $ret ) {
742 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
745 if ( isset( $wgProfiler ) ) {
746 wfProfileOut( $queryProf );
747 wfProfileOut( $totalProf );
750 return $this->resultObject( $ret );
754 * @param $error String
755 * @param $errno Integer
757 * @param $fname String
758 * @param $tempIgnore Boolean
760 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
761 # Ignore errors during error handling to avoid infinite recursion
762 $ignore = $this->ignoreErrors( true );
763 ++
$this->mErrorCount
;
765 if ( $ignore ||
$tempIgnore ) {
766 wfDebug( "SQL ERROR (ignored): $error\n" );
767 $this->ignoreErrors( $ignore );
769 $sql1line = str_replace( "\n", "\\n", $sql );
770 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
771 wfDebug( "SQL ERROR: " . $error . "\n" );
772 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
778 * Intended to be compatible with the PEAR::DB wrapper functions.
779 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
781 * ? = scalar value, quoted as necessary
782 * ! = raw SQL bit (a function for instance)
783 * & = filename; reads the file and inserts as a blob
784 * (we don't use this though...)
786 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
787 /* MySQL doesn't support prepared statements (yet), so just
788 pack up the query for reference. We'll manually replace
790 return array( 'query' => $sql, 'func' => $func );
793 function freePrepared( $prepared ) {
794 /* No-op by default */
798 * Execute a prepared query with the various arguments
799 * @param $prepared String: the prepared sql
800 * @param $args Mixed: Either an array here, or put scalars as varargs
802 function execute( $prepared, $args = null ) {
803 if ( !is_array( $args ) ) {
805 $args = func_get_args();
806 array_shift( $args );
809 $sql = $this->fillPrepared( $prepared['query'], $args );
811 return $this->query( $sql, $prepared['func'] );
815 * Prepare & execute an SQL statement, quoting and inserting arguments
816 * in the appropriate places.
817 * @param $query String
820 function safeQuery( $query, $args = null ) {
821 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
823 if ( !is_array( $args ) ) {
825 $args = func_get_args();
826 array_shift( $args );
829 $retval = $this->execute( $prepared, $args );
830 $this->freePrepared( $prepared );
836 * For faking prepared SQL statements on DBs that don't support
838 * @param $preparedQuery String: a 'preparable' SQL statement
839 * @param $args Array of arguments to fill it with
840 * @return string executable SQL
842 function fillPrepared( $preparedQuery, $args ) {
844 $this->preparedArgs
=& $args;
846 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
847 array( &$this, 'fillPreparedArg' ), $preparedQuery );
851 * preg_callback func for fillPrepared()
852 * The arguments should be in $this->preparedArgs and must not be touched
853 * while we're doing this.
855 * @param $matches Array
859 function fillPreparedArg( $matches ) {
860 switch( $matches[1] ) {
861 case '\\?': return '?';
862 case '\\!': return '!';
863 case '\\&': return '&';
866 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
868 switch( $matches[1] ) {
869 case '?': return $this->addQuotes( $arg );
870 case '!': return $arg;
872 # return $this->addQuotes( file_get_contents( $arg ) );
873 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
875 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
880 * Free a result object
881 * @param $res Mixed: A SQL result
883 function freeResult( $res ) {
884 # Stub. Might not really need to be overridden, since results should
885 # be freed by PHP when the variable goes out of scope anyway.
889 * Simple UPDATE wrapper
890 * Usually aborts on failure
891 * If errors are explicitly ignored, returns success
893 * This function exists for historical reasons, DatabaseBase::update() has a more standard
894 * calling convention and feature set
896 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
897 $table = $this->tableName( $table );
898 $sql = "UPDATE $table SET $var = '" .
899 $this->strencode( $value ) . "' WHERE ($cond)";
901 return (bool)$this->query( $sql, $fname );
905 * Simple SELECT wrapper, returns a single field, input must be encoded
906 * Usually aborts on failure
907 * If errors are explicitly ignored, returns FALSE on failure
909 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
910 if ( !is_array( $options ) ) {
911 $options = array( $options );
914 $options['LIMIT'] = 1;
916 $res = $this->select( $table, $var, $cond, $fname, $options );
918 if ( $res === false ||
!$this->numRows( $res ) ) {
922 $row = $this->fetchRow( $res );
924 if ( $row !== false ) {
925 return reset( $row );
932 * Returns an optional USE INDEX clause to go after the table, and a
933 * string to go at the end of the query
937 * @param $options Array: associative array of options to be turned into
938 * an SQL query, valid keys are listed in the function.
941 function makeSelectOptions( $options ) {
942 $preLimitTail = $postLimitTail = '';
945 $noKeyOptions = array();
947 foreach ( $options as $key => $option ) {
948 if ( is_numeric( $key ) ) {
949 $noKeyOptions[$option] = true;
953 if ( isset( $options['GROUP BY'] ) ) {
954 $gb = is_array( $options['GROUP BY'] )
955 ?
implode( ',', $options['GROUP BY'] )
956 : $options['GROUP BY'];
957 $preLimitTail .= " GROUP BY {$gb}";
960 if ( isset( $options['HAVING'] ) ) {
961 $preLimitTail .= " HAVING {$options['HAVING']}";
964 if ( isset( $options['ORDER BY'] ) ) {
965 $ob = is_array( $options['ORDER BY'] )
966 ?
implode( ',', $options['ORDER BY'] )
967 : $options['ORDER BY'];
968 $preLimitTail .= " ORDER BY {$ob}";
971 // if (isset($options['LIMIT'])) {
972 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
973 // isset($options['OFFSET']) ? $options['OFFSET']
977 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
978 $postLimitTail .= ' FOR UPDATE';
981 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
982 $postLimitTail .= ' LOCK IN SHARE MODE';
985 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
986 $startOpts .= 'DISTINCT';
989 # Various MySQL extensions
990 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
991 $startOpts .= ' /*! STRAIGHT_JOIN */';
994 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
995 $startOpts .= ' HIGH_PRIORITY';
998 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
999 $startOpts .= ' SQL_BIG_RESULT';
1002 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1003 $startOpts .= ' SQL_BUFFER_RESULT';
1006 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1007 $startOpts .= ' SQL_SMALL_RESULT';
1010 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1011 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1014 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1015 $startOpts .= ' SQL_CACHE';
1018 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1019 $startOpts .= ' SQL_NO_CACHE';
1022 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1023 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1028 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1034 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1035 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1036 * @param $conds Mixed: Array or string, condition(s) for WHERE
1037 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1038 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1039 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1040 * @param $join_conds Array: Associative array of table join conditions (optional)
1041 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1042 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1044 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1045 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1047 return $this->query( $sql, $fname );
1053 * @param $table Mixed: Array or string, table name(s) (prefix auto-added). Array keys are table aliases (optional)
1054 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1055 * @param $conds Mixed: Array or string, condition(s) for WHERE
1056 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1057 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1058 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1059 * @param $join_conds Array: Associative array of table join conditions (optional)
1060 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1061 * @return string, the SQL text
1063 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1064 if ( is_array( $vars ) ) {
1065 $vars = implode( ',', $vars );
1068 if ( !is_array( $options ) ) {
1069 $options = array( $options );
1072 if ( is_array( $table ) ) {
1073 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1074 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1076 $from = ' FROM ' . implode( ',', $this->tableNamesWithAlias( $table ) );
1078 } elseif ( $table != '' ) {
1079 if ( $table { 0 } == ' ' ) {
1080 $from = ' FROM ' . $table;
1082 $from = ' FROM ' . $this->tableName( $table );
1088 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1090 if ( !empty( $conds ) ) {
1091 if ( is_array( $conds ) ) {
1092 $conds = $this->makeList( $conds, LIST_AND
);
1094 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1096 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1099 if ( isset( $options['LIMIT'] ) )
1100 $sql = $this->limitResult( $sql, $options['LIMIT'],
1101 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1102 $sql = "$sql $postLimitTail";
1104 if ( isset( $options['EXPLAIN'] ) ) {
1105 $sql = 'EXPLAIN ' . $sql;
1112 * Single row SELECT wrapper
1113 * Aborts or returns FALSE on error
1115 * @param $table String: table name
1116 * @param $vars String: the selected variables
1117 * @param $conds Array: a condition map, terms are ANDed together.
1118 * Items with numeric keys are taken to be literal conditions
1119 * Takes an array of selected variables, and a condition map, which is ANDed
1120 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1121 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1122 * $obj- >page_id is the ID of the Astronomy article
1123 * @param $fname String: Calling function name
1124 * @param $options Array
1125 * @param $join_conds Array
1127 * @return ResultWrapper|Bool
1129 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1130 $options['LIMIT'] = 1;
1131 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1133 if ( $res === false ) {
1137 if ( !$this->numRows( $res ) ) {
1141 $obj = $this->fetchObject( $res );
1147 * Estimate rows in dataset
1148 * Returns estimated count - not necessarily an accurate estimate across different databases,
1150 * Takes same arguments as DatabaseBase::select()
1152 * @param $table String: table name
1153 * @param $vars Array: unused
1154 * @param $conds Array: filters on the table
1155 * @param $fname String: function name for profiling
1156 * @param $options Array: options for select
1157 * @return Integer: row count
1159 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1161 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1164 $row = $this->fetchRow( $res );
1165 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1172 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1173 * It's only slightly flawed. Don't use for anything important.
1175 * @param $sql String: A SQL Query
1177 static function generalizeSQL( $sql ) {
1178 # This does the same as the regexp below would do, but in such a way
1179 # as to avoid crashing php on some large strings.
1180 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1182 $sql = str_replace ( "\\\\", '', $sql );
1183 $sql = str_replace ( "\\'", '', $sql );
1184 $sql = str_replace ( "\\\"", '', $sql );
1185 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1186 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1188 # All newlines, tabs, etc replaced by single space
1189 $sql = preg_replace ( '/\s+/', ' ', $sql );
1192 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1198 * Determines whether a field exists in a table
1200 * @param $table String: table name
1201 * @param $field String: filed to check on that table
1202 * @param $fname String: calling function name (optional)
1203 * @return Boolean: whether $table has filed $field
1205 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1206 $info = $this->fieldInfo( $table, $field );
1212 * Determines whether an index exists
1213 * Usually aborts on failure
1214 * If errors are explicitly ignored, returns NULL on failure
1216 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1217 $info = $this->indexInfo( $table, $index, $fname );
1218 if ( is_null( $info ) ) {
1221 return $info !== false;
1226 * Query whether a given table exists
1228 function tableExists( $table ) {
1229 $table = $this->tableName( $table );
1230 $old = $this->ignoreErrors( true );
1231 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1232 $this->ignoreErrors( $old );
1238 * mysql_field_type() wrapper
1240 function fieldType( $res, $index ) {
1241 if ( $res instanceof ResultWrapper
) {
1242 $res = $res->result
;
1245 return mysql_field_type( $res, $index );
1249 * Determines if a given index is unique
1251 function indexUnique( $table, $index ) {
1252 $indexInfo = $this->indexInfo( $table, $index );
1254 if ( !$indexInfo ) {
1258 return !$indexInfo[0]->Non_unique
;
1262 * INSERT wrapper, inserts an array into a table
1264 * $a may be a single associative array, or an array of these with numeric keys, for
1267 * Usually aborts on failure
1268 * If errors are explicitly ignored, returns success
1270 * @param $table String: table name (prefix auto-added)
1271 * @param $a Array: Array of rows to insert
1272 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1273 * @param $options Mixed: Associative array of options
1277 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1278 # No rows to insert, easy just return now
1279 if ( !count( $a ) ) {
1283 $table = $this->tableName( $table );
1285 if ( !is_array( $options ) ) {
1286 $options = array( $options );
1289 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1291 $keys = array_keys( $a[0] );
1294 $keys = array_keys( $a );
1297 $sql = 'INSERT ' . implode( ' ', $options ) .
1298 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1302 foreach ( $a as $row ) {
1308 $sql .= '(' . $this->makeList( $row ) . ')';
1311 $sql .= '(' . $this->makeList( $a ) . ')';
1314 return (bool)$this->query( $sql, $fname );
1318 * Make UPDATE options for the DatabaseBase::update function
1321 * @param $options Array: The options passed to DatabaseBase::update
1324 function makeUpdateOptions( $options ) {
1325 if ( !is_array( $options ) ) {
1326 $options = array( $options );
1331 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1332 $opts[] = $this->lowPriorityOption();
1335 if ( in_array( 'IGNORE', $options ) ) {
1339 return implode( ' ', $opts );
1343 * UPDATE wrapper, takes a condition array and a SET array
1345 * @param $table String: The table to UPDATE
1346 * @param $values Array: An array of values to SET
1347 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1348 * @param $fname String: The Class::Function calling this function
1350 * @param $options Array: An array of UPDATE options, can be one or
1351 * more of IGNORE, LOW_PRIORITY
1354 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1355 $table = $this->tableName( $table );
1356 $opts = $this->makeUpdateOptions( $options );
1357 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1359 if ( $conds != '*' ) {
1360 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1363 return $this->query( $sql, $fname );
1367 * Makes an encoded list of strings from an array
1370 * LIST_COMMA - comma separated, no field names
1371 * LIST_AND - ANDed WHERE clause (without the WHERE)
1372 * LIST_OR - ORed WHERE clause (without the WHERE)
1373 * LIST_SET - comma separated with field names, like a SET clause
1374 * LIST_NAMES - comma separated field names
1378 function makeList( $a, $mode = LIST_COMMA
) {
1379 if ( !is_array( $a ) ) {
1380 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1386 foreach ( $a as $field => $value ) {
1388 if ( $mode == LIST_AND
) {
1390 } elseif ( $mode == LIST_OR
) {
1399 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1400 $list .= "($value)";
1401 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1403 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1404 if ( count( $value ) == 0 ) {
1405 throw new MWException( __METHOD__
. ': empty input' );
1406 } elseif ( count( $value ) == 1 ) {
1407 // Special-case single values, as IN isn't terribly efficient
1408 // Don't necessarily assume the single key is 0; we don't
1409 // enforce linear numeric ordering on other arrays here.
1410 $value = array_values( $value );
1411 $list .= $field . " = " . $this->addQuotes( $value[0] );
1413 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1415 } elseif ( $value === null ) {
1416 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1417 $list .= "$field IS ";
1418 } elseif ( $mode == LIST_SET
) {
1419 $list .= "$field = ";
1423 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1424 $list .= "$field = ";
1426 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1434 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1435 * The keys on each level may be either integers or strings.
1437 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1438 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1439 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1440 * @return Mixed: string SQL fragment, or false if no items in array.
1442 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1445 foreach ( $data as $base => $sub ) {
1446 if ( count( $sub ) ) {
1447 $conds[] = $this->makeList(
1448 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1454 return $this->makeList( $conds, LIST_OR
);
1456 // Nothing to search for...
1462 * Bitwise operations
1465 function bitNot( $field ) {
1469 function bitAnd( $fieldLeft, $fieldRight ) {
1470 return "($fieldLeft & $fieldRight)";
1473 function bitOr( $fieldLeft, $fieldRight ) {
1474 return "($fieldLeft | $fieldRight)";
1478 * Change the current database
1480 * @todo Explain what exactly will fail if this is not overridden.
1481 * @return bool Success or failure
1483 function selectDB( $db ) {
1484 # Stub. Shouldn't cause serious problems if it's not overridden, but
1485 # if your database engine supports a concept similar to MySQL's
1486 # databases you may as well.
1487 $this->mDBname
= $db;
1492 * Get the current DB name
1494 function getDBname() {
1495 return $this->mDBname
;
1499 * Get the server hostname or IP address
1501 function getServer() {
1502 return $this->mServer
;
1506 * Format a table name ready for use in constructing an SQL query
1508 * This does two important things: it quotes the table names to clean them up,
1509 * and it adds a table prefix if only given a table name with no quotes.
1511 * All functions of this object which require a table name call this function
1512 * themselves. Pass the canonical name to such functions. This is only needed
1513 * when calling query() directly.
1515 * @param $name String: database table name
1516 * @param $quoted Boolean: Automatically pass the table name through
1517 * addIdentifierQuotes() so that it can be used in a query.
1518 * @return String: full database name
1520 function tableName( $name, $quoted = true ) {
1521 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1522 # Skip the entire process when we have a string quoted on both ends.
1523 # Note that we check the end so that we will still quote any use of
1524 # use of `database`.table. But won't break things if someone wants
1525 # to query a database table with a dot in the name.
1526 if ( $this->isQuotedIdentifier( $name ) ) {
1530 # Lets test for any bits of text that should never show up in a table
1531 # name. Basically anything like JOIN or ON which are actually part of
1532 # SQL queries, but may end up inside of the table value to combine
1533 # sql. Such as how the API is doing.
1534 # Note that we use a whitespace test rather than a \b test to avoid
1535 # any remote case where a word like on may be inside of a table name
1536 # surrounded by symbols which may be considered word breaks.
1537 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1541 # Split database and table into proper variables.
1542 # We reverse the explode so that database.table and table both output
1543 # the correct table.
1544 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1545 if ( isset( $dbDetails[1] ) ) {
1546 @list
( $table, $database ) = $dbDetails;
1548 @list
( $table ) = $dbDetails;
1550 $prefix = $this->mTablePrefix
; # Default prefix
1552 # Note that we use the long format because php will complain in in_array if
1553 # the input is not an array, and will complain in is_array if it is not set.
1554 if ( !isset( $database ) # Don't use shared database if pre selected.
1555 && isset( $wgSharedDB ) # We have a shared database
1556 && !$this->isQuotedIdentifier( $table ) # Paranoia check to prevent shared tables listing '`table`'
1557 && isset( $wgSharedTables )
1558 && is_array( $wgSharedTables )
1559 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1560 $database = $wgSharedDB;
1561 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1564 # Quote the $database and $table and apply the prefix if not quoted.
1565 if ( isset( $database ) ) {
1566 $database = ( !$quoted ||
$this->isQuotedIdentifier( $database ) ?
$database : $this->addIdentifierQuotes( $database ) );
1569 $table = ( !$quoted ||
$this->isQuotedIdentifier( $table ) ?
$table : $this->addIdentifierQuotes( "{$prefix}{$table}" ) );
1571 # Merge our database and table into our final table name.
1572 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1578 * Fetch a number of table names into an array
1579 * This is handy when you need to construct SQL for joins
1582 * extract($dbr->tableNames('user','watchlist'));
1583 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1584 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1586 public function tableNames() {
1587 $inArray = func_get_args();
1590 foreach ( $inArray as $name ) {
1591 $retVal[$name] = $this->tableName( $name );
1598 * Fetch a number of table names into an zero-indexed numerical array
1599 * This is handy when you need to construct SQL for joins
1602 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1603 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1604 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1606 public function tableNamesN() {
1607 $inArray = func_get_args();
1610 foreach ( $inArray as $name ) {
1611 $retVal[] = $this->tableName( $name );
1618 * Get an aliased table name
1619 * e.g. tableName AS newTableName
1621 * @param $name string Table name, see tableName()
1622 * @param $alias string Alias (optional)
1623 * @return string SQL name for aliased table. Will not alias a table to its own name
1625 public function tableNameWithAlias( $name, $alias = false ) {
1626 if ( !$alias ||
$alias == $name ) {
1627 return $this->tableName( $name );
1629 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1634 * Gets an array of aliased table names
1636 * @param $tables array( [alias] => table )
1637 * @return array of strings, see tableNameWithAlias()
1639 public function tableNamesWithAlias( $tables ) {
1641 foreach ( $tables as $alias => $table ) {
1642 if ( is_numeric( $alias ) ) {
1645 $retval[] = $this->tableNameWithAlias( $table, $alias );
1653 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1656 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1657 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1659 foreach ( $tables as $alias => $table ) {
1660 if ( !is_string( $alias ) ) {
1661 // No alias? Set it equal to the table name
1664 // Is there a JOIN and INDEX clause for this table?
1665 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1666 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1667 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1668 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1670 $tableClause .= ' ON (' . $on . ')';
1673 $retJOIN[] = $tableClause;
1674 // Is there an INDEX clause?
1675 } else if ( isset( $use_index_safe[$alias] ) ) {
1676 $tableClause = $this->tableNameWithAlias( $table, $alias );
1677 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1678 $ret[] = $tableClause;
1679 // Is there a JOIN clause?
1680 } else if ( isset( $join_conds_safe[$alias] ) ) {
1681 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1682 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1684 $tableClause .= ' ON (' . $on . ')';
1687 $retJOIN[] = $tableClause;
1689 $tableClause = $this->tableNameWithAlias( $table, $alias );
1690 $ret[] = $tableClause;
1694 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1695 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1696 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1698 // Compile our final table clause
1699 return implode( ' ', array( $straightJoins, $otherJoins ) );
1703 * Get the name of an index in a given table
1705 function indexName( $index ) {
1706 // Backwards-compatibility hack
1708 'ar_usertext_timestamp' => 'usertext_timestamp',
1709 'un_user_id' => 'user_id',
1710 'un_user_ip' => 'user_ip',
1713 if ( isset( $renamed[$index] ) ) {
1714 return $renamed[$index];
1721 * If it's a string, adds quotes and backslashes
1722 * Otherwise returns as-is
1724 function addQuotes( $s ) {
1725 if ( $s === null ) {
1728 # This will also quote numeric values. This should be harmless,
1729 # and protects against weird problems that occur when they really
1730 # _are_ strings such as article titles and string->number->string
1731 # conversion is not 1:1.
1732 return "'" . $this->strencode( $s ) . "'";
1737 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1738 * MySQL uses `backticks` while basically everything else uses double quotes.
1739 * Since MySQL is the odd one out here the double quotes are our generic
1740 * and we implement backticks in DatabaseMysql.
1742 public function addIdentifierQuotes( $s ) {
1743 return '"' . str_replace( '"', '""', $s ) . '"';
1747 * Returns if the given identifier looks quoted or not according to
1748 * the database convention for quoting identifiers .
1751 public function isQuotedIdentifier( $name ) {
1752 return $name[0] == '"' && substr( $name, -1, 1 ) == '"';
1756 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1757 * which used quote_ident which does not follow our naming conventions
1758 * was renamed to addIdentifierQuotes.
1759 * @deprecated use addIdentifierQuotes
1761 function quote_ident( $s ) {
1762 wfDeprecated( __METHOD__
);
1763 return $this->addIdentifierQuotes( $s );
1767 * Escape string for safe LIKE usage.
1768 * WARNING: you should almost never use this function directly,
1769 * instead use buildLike() that escapes everything automatically
1770 * Deprecated in 1.17, warnings in 1.17, removed in ???
1772 public function escapeLike( $s ) {
1773 wfDeprecated( __METHOD__
);
1774 return $this->escapeLikeInternal( $s );
1777 protected function escapeLikeInternal( $s ) {
1778 $s = str_replace( '\\', '\\\\', $s );
1779 $s = $this->strencode( $s );
1780 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1786 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1787 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1788 * Alternatively, the function could be provided with an array of aforementioned parameters.
1790 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1791 * for subpages of 'My page title'.
1792 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1795 * @return String: fully built LIKE statement
1797 function buildLike() {
1798 $params = func_get_args();
1800 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1801 $params = $params[0];
1806 foreach ( $params as $value ) {
1807 if ( $value instanceof LikeMatch
) {
1808 $s .= $value->toString();
1810 $s .= $this->escapeLikeInternal( $value );
1814 return " LIKE '" . $s . "' ";
1818 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1820 function anyChar() {
1821 return new LikeMatch( '_' );
1825 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1827 function anyString() {
1828 return new LikeMatch( '%' );
1832 * Returns an appropriately quoted sequence value for inserting a new row.
1833 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1834 * subclass will return an integer, and save the value for insertId()
1836 function nextSequenceValue( $seqName ) {
1841 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1842 * is only needed because a) MySQL must be as efficient as possible due to
1843 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1844 * which index to pick. Anyway, other databases might have different
1845 * indexes on a given table. So don't bother overriding this unless you're
1848 function useIndexClause( $index ) {
1853 * REPLACE query wrapper
1854 * PostgreSQL simulates this with a DELETE followed by INSERT
1855 * $row is the row to insert, an associative array
1856 * $uniqueIndexes is an array of indexes. Each element may be either a
1857 * field name or an array of field names
1859 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1860 * However if you do this, you run the risk of encountering errors which wouldn't have
1863 * @param $table String: The table to replace the row(s) in.
1864 * @param $uniqueIndexes Array: An associative array of indexes
1865 * @param $rows Array: Array of rows to replace
1866 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1868 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1869 $table = $this->tableName( $table );
1872 if ( !is_array( reset( $rows ) ) ) {
1873 $rows = array( $rows );
1876 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1879 foreach ( $rows as $row ) {
1886 $sql .= '(' . $this->makeList( $row ) . ')';
1889 return $this->query( $sql, $fname );
1893 * DELETE where the condition is a join
1894 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1896 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1897 * join condition matches, set $conds='*'
1899 * DO NOT put the join condition in $conds
1901 * @param $delTable String: The table to delete from.
1902 * @param $joinTable String: The other table.
1903 * @param $delVar String: The variable to join on, in the first table.
1904 * @param $joinVar String: The variable to join on, in the second table.
1905 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1906 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1908 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1910 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1913 $delTable = $this->tableName( $delTable );
1914 $joinTable = $this->tableName( $joinTable );
1915 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1917 if ( $conds != '*' ) {
1918 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1921 return $this->query( $sql, $fname );
1925 * Returns the size of a text field, or -1 for "unlimited"
1927 function textFieldSize( $table, $field ) {
1928 $table = $this->tableName( $table );
1929 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1930 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1931 $row = $this->fetchObject( $res );
1935 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1945 * A string to insert into queries to show that they're low-priority, like
1946 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1947 * string and nothing bad should happen.
1949 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1951 function lowPriorityOption() {
1956 * DELETE query wrapper
1958 * Use $conds == "*" to delete all rows
1960 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1962 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1965 $table = $this->tableName( $table );
1966 $sql = "DELETE FROM $table";
1968 if ( $conds != '*' ) {
1969 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1972 return $this->query( $sql, $fname );
1976 * INSERT SELECT wrapper
1977 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1978 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1979 * $conds may be "*" to copy the whole table
1980 * srcTable may be an array of tables.
1982 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1983 $insertOptions = array(), $selectOptions = array() )
1985 $destTable = $this->tableName( $destTable );
1987 if ( is_array( $insertOptions ) ) {
1988 $insertOptions = implode( ' ', $insertOptions );
1991 if ( !is_array( $selectOptions ) ) {
1992 $selectOptions = array( $selectOptions );
1995 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1997 if ( is_array( $srcTable ) ) {
1998 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
2000 $srcTable = $this->tableName( $srcTable );
2003 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
2004 " SELECT $startOpts " . implode( ',', $varMap ) .
2005 " FROM $srcTable $useIndex ";
2007 if ( $conds != '*' ) {
2008 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2011 $sql .= " $tailOpts";
2013 return $this->query( $sql, $fname );
2017 * Construct a LIMIT query with optional offset. This is used for query
2018 * pages. The SQL should be adjusted so that only the first $limit rows
2019 * are returned. If $offset is provided as well, then the first $offset
2020 * rows should be discarded, and the next $limit rows should be returned.
2021 * If the result of the query is not ordered, then the rows to be returned
2022 * are theoretically arbitrary.
2024 * $sql is expected to be a SELECT, if that makes a difference. For
2025 * UPDATE, limitResultForUpdate should be used.
2027 * The version provided by default works in MySQL and SQLite. It will very
2028 * likely need to be overridden for most other DBMSes.
2030 * @param $sql String: SQL query we will append the limit too
2031 * @param $limit Integer: the SQL limit
2032 * @param $offset Integer the SQL offset (default false)
2034 function limitResult( $sql, $limit, $offset = false ) {
2035 if ( !is_numeric( $limit ) ) {
2036 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2039 return "$sql LIMIT "
2040 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2044 function limitResultForUpdate( $sql, $num ) {
2045 return $this->limitResult( $sql, $num, 0 );
2049 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2050 * within the UNION construct.
2053 function unionSupportsOrderAndLimit() {
2054 return true; // True for almost every DB supported
2058 * Construct a UNION query
2059 * This is used for providing overload point for other DB abstractions
2060 * not compatible with the MySQL syntax.
2061 * @param $sqls Array: SQL statements to combine
2062 * @param $all Boolean: use UNION ALL
2063 * @return String: SQL fragment
2065 function unionQueries( $sqls, $all ) {
2066 $glue = $all ?
') UNION ALL (' : ') UNION (';
2067 return '(' . implode( $glue, $sqls ) . ')';
2071 * Returns an SQL expression for a simple conditional. This doesn't need
2072 * to be overridden unless CASE isn't supported in your DBMS.
2074 * @param $cond String: SQL expression which will result in a boolean value
2075 * @param $trueVal String: SQL expression to return if true
2076 * @param $falseVal String: SQL expression to return if false
2077 * @return String: SQL fragment
2079 function conditional( $cond, $trueVal, $falseVal ) {
2080 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2084 * Returns a comand for str_replace function in SQL query.
2085 * Uses REPLACE() in MySQL
2087 * @param $orig String: column to modify
2088 * @param $old String: column to seek
2089 * @param $new String: column to replace with
2091 function strreplace( $orig, $old, $new ) {
2092 return "REPLACE({$orig}, {$old}, {$new})";
2096 * Determines if the last failure was due to a deadlock
2099 function wasDeadlock() {
2104 * Determines if the last query error was something that should be dealt
2105 * with by pinging the connection and reissuing the query.
2108 function wasErrorReissuable() {
2113 * Determines if the last failure was due to the database being read-only.
2116 function wasReadOnlyError() {
2121 * Perform a deadlock-prone transaction.
2123 * This function invokes a callback function to perform a set of write
2124 * queries. If a deadlock occurs during the processing, the transaction
2125 * will be rolled back and the callback function will be called again.
2128 * $dbw->deadlockLoop( callback, ... );
2130 * Extra arguments are passed through to the specified callback function.
2132 * Returns whatever the callback function returned on its successful,
2133 * iteration, or false on error, for example if the retry limit was
2136 function deadlockLoop() {
2137 $myFname = 'DatabaseBase::deadlockLoop';
2140 $args = func_get_args();
2141 $function = array_shift( $args );
2142 $oldIgnore = $this->ignoreErrors( true );
2143 $tries = DEADLOCK_TRIES
;
2145 if ( is_array( $function ) ) {
2146 $fname = $function[0];
2152 $retVal = call_user_func_array( $function, $args );
2153 $error = $this->lastError();
2154 $errno = $this->lastErrno();
2155 $sql = $this->lastQuery();
2158 if ( $this->wasDeadlock() ) {
2160 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2162 $this->reportQueryError( $error, $errno, $sql, $fname );
2165 } while ( $this->wasDeadlock() && --$tries > 0 );
2167 $this->ignoreErrors( $oldIgnore );
2169 if ( $tries <= 0 ) {
2170 $this->rollback( $myFname );
2171 $this->reportQueryError( $error, $errno, $sql, $fname );
2174 $this->commit( $myFname );
2180 * Do a SELECT MASTER_POS_WAIT()
2182 * @param $pos MySQLMasterPos object
2183 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2185 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2186 $fname = 'DatabaseBase::masterPosWait';
2187 wfProfileIn( $fname );
2189 # Commit any open transactions
2190 if ( $this->mTrxLevel
) {
2194 if ( !is_null( $this->mFakeSlaveLag
) ) {
2195 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2197 if ( $wait > $timeout * 1e6
) {
2198 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2199 wfProfileOut( $fname );
2201 } elseif ( $wait > 0 ) {
2202 wfDebug( "Fake slave waiting $wait us\n" );
2204 wfProfileOut( $fname );
2207 wfDebug( "Fake slave up to date ($wait us)\n" );
2208 wfProfileOut( $fname );
2213 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2214 $encFile = $this->addQuotes( $pos->file
);
2215 $encPos = intval( $pos->pos
);
2216 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2217 $res = $this->doQuery( $sql );
2219 if ( $res && $row = $this->fetchRow( $res ) ) {
2220 wfProfileOut( $fname );
2223 wfProfileOut( $fname );
2229 * Get the position of the master from SHOW SLAVE STATUS
2231 function getSlavePos() {
2232 if ( !is_null( $this->mFakeSlaveLag
) ) {
2233 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2234 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2238 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2239 $row = $this->fetchObject( $res );
2242 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2243 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2250 * Get the position of the master from SHOW MASTER STATUS
2252 function getMasterPos() {
2253 if ( $this->mFakeMaster
) {
2254 return new MySQLMasterPos( 'fake', microtime( true ) );
2257 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2258 $row = $this->fetchObject( $res );
2261 return new MySQLMasterPos( $row->File
, $row->Position
);
2268 * Begin a transaction, committing any previously open transaction
2270 function begin( $fname = 'DatabaseBase::begin' ) {
2271 $this->query( 'BEGIN', $fname );
2272 $this->mTrxLevel
= 1;
2278 function commit( $fname = 'DatabaseBase::commit' ) {
2279 if ( $this->mTrxLevel
) {
2280 $this->query( 'COMMIT', $fname );
2281 $this->mTrxLevel
= 0;
2286 * Rollback a transaction.
2287 * No-op on non-transactional databases.
2289 function rollback( $fname = 'DatabaseBase::rollback' ) {
2290 if ( $this->mTrxLevel
) {
2291 $this->query( 'ROLLBACK', $fname, true );
2292 $this->mTrxLevel
= 0;
2297 * Begin a transaction, committing any previously open transaction
2298 * @deprecated use begin()
2300 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2301 wfDeprecated( __METHOD__
);
2306 * Commit transaction, if one is open
2307 * @deprecated use commit()
2309 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2310 wfDeprecated( __METHOD__
);
2315 * Creates a new table with structure copied from existing table
2316 * Note that unlike most database abstraction functions, this function does not
2317 * automatically append database prefix, because it works at a lower
2318 * abstraction level.
2320 * @param $oldName String: name of table whose structure should be copied
2321 * @param $newName String: name of table to be created
2322 * @param $temporary Boolean: whether the new table should be temporary
2323 * @param $fname String: calling function name
2324 * @return Boolean: true if operation was successful
2326 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2327 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2331 * List all tables on the database
2333 * @param $prefix Only show tables with this prefix, e.g. mw_
2334 * @param $fname String: calling function name
2336 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2337 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2341 * Return MW-style timestamp used for MySQL schema
2343 function timestamp( $ts = 0 ) {
2344 return wfTimestamp( TS_MW
, $ts );
2348 * Local database timestamp format or null
2350 function timestampOrNull( $ts = null ) {
2351 if ( is_null( $ts ) ) {
2354 return $this->timestamp( $ts );
2361 function resultObject( $result ) {
2362 if ( empty( $result ) ) {
2364 } elseif ( $result instanceof ResultWrapper
) {
2366 } elseif ( $result === true ) {
2367 // Successful write query
2370 return new ResultWrapper( $this, $result );
2375 * Return aggregated value alias
2377 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2382 * Ping the server and try to reconnect if it there is no connection
2384 * @return bool Success or failure
2387 # Stub. Not essential to override.
2393 * Currently supported only by MySQL
2394 * @return Database replication lag in seconds
2397 return intval( $this->mFakeSlaveLag
);
2401 * Get status information from SHOW STATUS in an associative array
2403 function getStatus( $which = "%" ) {
2404 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2407 foreach ( $res as $row ) {
2408 $status[$row->Variable_name
] = $row->Value
;
2415 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2417 function maxListLen() {
2421 function encodeBlob( $b ) {
2425 function decodeBlob( $b ) {
2430 * Override database's default connection timeout. May be useful for very
2431 * long batch queries such as full-wiki dumps, where a single query reads
2432 * out over hours or days. May or may not be necessary for non-MySQL
2433 * databases. For most purposes, leaving it as a no-op should be fine.
2435 * @param $timeout Integer in seconds
2437 public function setTimeout( $timeout ) {}
2440 * Read and execute SQL commands from a file.
2441 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2442 * @param $filename String: File name to open
2443 * @param $lineCallback Callback: Optional function called before reading each line
2444 * @param $resultCallback Callback: Optional function called for each MySQL result
2445 * @param $fname String: Calling function name or false if name should be generated dynamically
2448 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2449 wfSuppressWarnings();
2450 $fp = fopen( $filename, 'r' );
2451 wfRestoreWarnings();
2453 if ( false === $fp ) {
2454 throw new MWException( "Could not open \"{$filename}\".\n" );
2458 $fname = __METHOD__
. "( $filename )";
2462 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2464 catch ( MWException
$e ) {
2475 * Get the full path of a patch file. Originally based on archive()
2476 * from updaters.inc. Keep in mind this always returns a patch, as
2477 * it fails back to MySQL if no DB-specific patch can be found
2479 * @param $patch String The name of the patch, like patch-something.sql
2480 * @return String Full path to patch file
2482 public function patchPath( $patch ) {
2485 $dbType = $this->getType();
2486 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2487 return "$IP/maintenance/$dbType/archives/$patch";
2489 return "$IP/maintenance/archives/$patch";
2494 * Set variables to be used in sourceFile/sourceStream, in preference to the
2495 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2496 * all. If it's set to false, $GLOBALS will be used.
2498 * @param $vars False, or array mapping variable name to value.
2500 function setSchemaVars( $vars ) {
2501 $this->mSchemaVars
= $vars;
2505 * Read and execute commands from an open file handle
2506 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2507 * @param $fp Resource: File handle
2508 * @param $lineCallback Callback: Optional function called before reading each line
2509 * @param $resultCallback Callback: Optional function called for each MySQL result
2510 * @param $fname String: Calling function name
2512 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2515 $dollarquote = false;
2517 while ( ! feof( $fp ) ) {
2518 if ( $lineCallback ) {
2519 call_user_func( $lineCallback );
2522 $line = trim( fgets( $fp, 1024 ) );
2523 $sl = strlen( $line ) - 1;
2529 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2533 # # Allow dollar quoting for function declarations
2534 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2535 if ( $dollarquote ) {
2536 $dollarquote = false;
2540 $dollarquote = true;
2543 else if ( !$dollarquote ) {
2544 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2546 $line = substr( $line, 0, $sl );
2557 $cmd = str_replace( ';;', ";", $cmd );
2558 $cmd = $this->replaceVars( $cmd );
2559 $res = $this->query( $cmd, $fname );
2561 if ( $resultCallback ) {
2562 call_user_func( $resultCallback, $res, $this );
2565 if ( false === $res ) {
2566 $err = $this->lastError();
2567 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2579 * Database independent variable replacement, replaces a set of variables
2580 * in a sql statement with their contents as given by $this->getSchemaVars().
2581 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2583 * '{$var}' should be used for text and is passed through the database's addQuotes method
2584 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2585 * the database's addIdentifierQuotes method which can be overridden if the database
2586 * uses something other than backticks.
2587 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2589 * @param $ins String: SQL statement to replace variables in
2590 * @return String The new SQL statement with variables replaced
2592 protected function replaceSchemaVars( $ins ) {
2593 $vars = $this->getSchemaVars();
2594 foreach ( $vars as $var => $value ) {
2596 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2598 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2600 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2606 * Replace variables in sourced SQL
2608 protected function replaceVars( $ins ) {
2609 $ins = $this->replaceSchemaVars( $ins );
2612 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2613 array( $this, 'tableNameCallback' ), $ins );
2616 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2617 array( $this, 'indexNameCallback' ), $ins );
2623 * Get schema variables. If none have been set via setSchemaVars(), then
2624 * use some defaults from the current object.
2626 protected function getSchemaVars() {
2627 if ( $this->mSchemaVars
) {
2628 return $this->mSchemaVars
;
2630 return $this->getDefaultSchemaVars();
2635 * Get schema variables to use if none have been set via setSchemaVars().
2636 * Override this in derived classes to provide variables for tables.sql
2637 * and SQL patch files.
2639 protected function getDefaultSchemaVars() {
2644 * Table name callback
2647 protected function tableNameCallback( $matches ) {
2648 return $this->tableName( $matches[1] );
2652 * Index name callback
2654 protected function indexNameCallback( $matches ) {
2655 return $this->indexName( $matches[1] );
2659 * Build a concatenation list to feed into a SQL query
2660 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2663 function buildConcat( $stringList ) {
2664 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2668 * Acquire a named lock
2670 * Abstracted from Filestore::lock() so child classes can implement for
2673 * @param $lockName String: name of lock to aquire
2674 * @param $method String: name of method calling us
2675 * @param $timeout Integer: timeout
2678 public function lock( $lockName, $method, $timeout = 5 ) {
2685 * @param $lockName String: Name of lock to release
2686 * @param $method String: Name of method calling us
2688 * @return Returns 1 if the lock was released, 0 if the lock was not established
2689 * by this thread (in which case the lock is not released), and NULL if the named
2690 * lock did not exist
2692 public function unlock( $lockName, $method ) {
2697 * Lock specific tables
2699 * @param $read Array of tables to lock for read access
2700 * @param $write Array of tables to lock for write access
2701 * @param $method String name of caller
2702 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2704 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2709 * Unlock specific tables
2711 * @param $method String the caller
2713 public function unlockTables( $method ) {
2720 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2721 if( !$this->tableExists( $tableName ) ) {
2724 $sql = "DROP TABLE " . $this->tableName( $tableName );
2725 if( $this->cascadingDeletes() ) {
2728 return $this->query( $sql, $fName );
2732 * Get search engine class. All subclasses of this need to implement this
2733 * if they wish to use searching.
2737 public function getSearchEngine() {
2738 return 'SearchEngineDummy';
2742 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2743 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2744 * because "i" sorts after all numbers.
2748 public function getInfinity() {
2753 * Encode an expiry time
2755 * @param $expiry String: timestamp for expiry, or the 'infinity' string
2758 public function encodeExpiry( $expiry ) {
2759 if ( $expiry == '' ||
$expiry == $this->getInfinity() ) {
2760 return $this->getInfinity();
2762 return $this->timestamp( $expiry );
2767 * Allow or deny "big selects" for this session only. This is done by setting
2768 * the sql_big_selects session variable.
2770 * This is a MySQL-specific feature.
2772 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2774 public function setBigSelects( $value = true ) {
2779 /******************************************************************************
2781 *****************************************************************************/
2790 function __construct( $data ) {
2791 $this->mData
= $data;
2799 return $this->mData
;
2807 * This allows us to distinguish a blob from a normal string and an array of strings
2812 function __construct( $data ) {
2813 $this->mData
= $data;
2817 return $this->mData
;
2822 * Base for all database-specific classes representing information about database fields
2833 * Name of table this field belongs to
2836 function tableName();
2845 * Whether this field can store NULL values
2848 function isNullable();
2851 /******************************************************************************
2853 *****************************************************************************/
2856 * Database error base class
2859 class DBError
extends MWException
{
2863 * Construct a database error
2864 * @param $db Database object which threw the error
2865 * @param $error String A simple error message to be used for debugging
2867 function __construct( DatabaseBase
&$db, $error ) {
2869 parent
::__construct( $error );
2872 function getText() {
2873 global $wgShowDBErrorBacktrace;
2875 $s = $this->getMessage() . "\n";
2877 if ( $wgShowDBErrorBacktrace ) {
2878 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2888 class DBConnectionError
extends DBError
{
2891 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2892 $msg = 'DB connection error';
2894 if ( trim( $error ) != '' ) {
2898 $this->error
= $error;
2900 parent
::__construct( $db, $msg );
2903 function useOutputPage() {
2904 // Not likely to work
2908 function useMessageCache() {
2909 // Not likely to work
2913 function getLogMessage() {
2914 # Don't send to the exception log
2918 function getPageTitle() {
2919 global $wgSitename, $wgLang;
2921 $header = "$wgSitename has a problem";
2923 if ( $wgLang instanceof Language
) {
2924 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2930 function getHTML() {
2931 global $wgLang, $wgUseFileCache, $wgShowDBErrorBacktrace;
2933 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2934 $again = 'Try waiting a few minutes and reloading.';
2935 $info = '(Can\'t contact the database server: $1)';
2937 if ( $wgLang instanceof Language
) {
2938 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2939 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2940 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2943 # No database access
2944 MessageCache
::singleton()->disable();
2946 if ( trim( $this->error
) == '' ) {
2947 $this->error
= $this->db
->getProperty( 'mServer' );
2950 $this->error
= Html
::element( 'span', array( 'dir' => 'ltr' ), $this->error
);
2952 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2953 $text = str_replace( '$1', $this->error
, $noconnect );
2955 if ( $wgShowDBErrorBacktrace ) {
2956 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2959 $extra = $this->searchForm();
2961 if ( $wgUseFileCache ) {
2963 $cache = $this->fileCachedPage();
2964 # Cached version on file system?
2965 if ( $cache !== null ) {
2966 # Hack: extend the body for error messages
2967 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2968 # Add cache notice...
2969 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2971 # Localize it if possible...
2972 if ( $wgLang instanceof Language
) {
2973 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2976 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2978 # Output cached page with notices on bottom and re-close body
2979 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2981 } catch ( MWException
$e ) {
2982 // Do nothing, just use the default page
2986 # Headers needed here - output is just the error message
2987 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2990 function searchForm() {
2991 global $wgSitename, $wgServer, $wgLang;
2993 $usegoogle = "You can try searching via Google in the meantime.";
2994 $outofdate = "Note that their indexes of our content may be out of date.";
2995 $googlesearch = "Search";
2997 if ( $wgLang instanceof Language
) {
2998 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2999 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
3000 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
3003 $search = htmlspecialchars( @$_REQUEST['search'] );
3005 $server = htmlspecialchars( $wgServer );
3006 $sitename = htmlspecialchars( $wgSitename );
3009 <div style="margin: 1.5em">$usegoogle<br />
3010 <small>$outofdate</small></div>
3011 <!-- SiteSearch Google -->
3012 <form method="get" action="http://www.google.com/search" id="googlesearch">
3013 <input type="hidden" name="domains" value="$server" />
3014 <input type="hidden" name="num" value="50" />
3015 <input type="hidden" name="ie" value="UTF-8" />
3016 <input type="hidden" name="oe" value="UTF-8" />
3018 <input type="text" name="q" size="31" maxlength="255" value="$search" />
3019 <input type="submit" name="btnG" value="$googlesearch" />
3021 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
3022 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
3025 <!-- SiteSearch Google -->
3030 private function fileCachedPage() {
3031 global $wgTitle, $wgLang, $wgOut;
3033 if ( $wgOut->isDisabled() ) {
3034 return; // Done already?
3037 $mainpage = 'Main Page';
3039 if ( $wgLang instanceof Language
) {
3040 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
3046 $t = Title
::newFromText( $mainpage );
3049 $cache = new HTMLFileCache( $t );
3050 if ( $cache->isFileCached() ) {
3051 return $cache->fetchPageText();
3057 function htmlBodyOnly() {
3065 class DBQueryError
extends DBError
{
3066 public $error, $errno, $sql, $fname;
3068 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
3069 $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" .
3071 "Function: $fname\n" .
3072 "Error: $errno $error\n";
3074 parent
::__construct( $db, $message );
3076 $this->error
= $error;
3077 $this->errno
= $errno;
3079 $this->fname
= $fname;
3082 function getText() {
3083 global $wgShowDBErrorBacktrace;
3085 if ( $this->useMessageCache() ) {
3086 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
3087 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
3089 if ( $wgShowDBErrorBacktrace ) {
3090 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
3095 return parent
::getText();
3100 global $wgShowSQLErrors;
3102 if ( !$wgShowSQLErrors ) {
3103 return $this->msg( 'sqlhidden', 'SQL hidden' );
3109 function getLogMessage() {
3110 # Don't send to the exception log
3114 function getPageTitle() {
3115 return $this->msg( 'databaseerror', 'Database error' );
3118 function getHTML() {
3119 global $wgShowDBErrorBacktrace;
3121 if ( $this->useMessageCache() ) {
3122 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
3123 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
3125 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
3128 if ( $wgShowDBErrorBacktrace ) {
3129 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3139 class DBUnexpectedError
extends DBError
{}
3143 * Result wrapper for grabbing data queried by someone else
3146 class ResultWrapper
implements Iterator
{
3147 var $db, $result, $pos = 0, $currentRow = null;
3150 * Create a new result object from a result resource and a Database object
3152 * @param DatabaseBase $database
3153 * @param resource $result
3155 function __construct( $database, $result ) {
3156 $this->db
= $database;
3158 if ( $result instanceof ResultWrapper
) {
3159 $this->result
= $result->result
;
3161 $this->result
= $result;
3166 * Get the number of rows in a result object
3170 function numRows() {
3171 return $this->db
->numRows( $this );
3175 * Fetch the next row from the given result object, in object form.
3176 * Fields can be retrieved with $row->fieldname, with fields acting like
3180 * @throws DBUnexpectedError Thrown if the database returns an error
3182 function fetchObject() {
3183 return $this->db
->fetchObject( $this );
3187 * Fetch the next row from the given result object, in associative array
3188 * form. Fields are retrieved with $row['fieldname'].
3191 * @throws DBUnexpectedError Thrown if the database returns an error
3193 function fetchRow() {
3194 return $this->db
->fetchRow( $this );
3198 * Free a result object
3201 $this->db
->freeResult( $this );
3202 unset( $this->result
);
3207 * Change the position of the cursor in a result object.
3208 * See mysql_data_seek()
3210 * @param $row integer
3212 function seek( $row ) {
3213 $this->db
->dataSeek( $this, $row );
3216 /*********************
3217 * Iterator functions
3218 * Note that using these in combination with the non-iterator functions
3219 * above may cause rows to be skipped or repeated.
3223 if ( $this->numRows() ) {
3224 $this->db
->dataSeek( $this, 0 );
3227 $this->currentRow
= null;
3230 function current() {
3231 if ( is_null( $this->currentRow
) ) {
3234 return $this->currentRow
;
3243 $this->currentRow
= $this->fetchObject();
3244 return $this->currentRow
;
3248 return $this->current() !== false;
3253 * Overloads the relevant methods of the real ResultsWrapper so it
3254 * doesn't go anywhere near an actual database.
3256 class FakeResultWrapper
extends ResultWrapper
{
3257 var $result = array();
3258 var $db = null; // And it's going to stay that way :D
3260 var $currentRow = null;
3262 function __construct( $array ) {
3263 $this->result
= $array;
3266 function numRows() {
3267 return count( $this->result
);
3270 function fetchRow() {
3271 $this->currentRow
= $this->result
[$this->pos++
];
3272 return $this->currentRow
;
3275 function seek( $row ) {
3281 // Callers want to be able to access fields with $this->fieldName
3282 function fetchObject() {
3283 $this->currentRow
= $this->result
[$this->pos++
];
3284 return (object)$this->currentRow
;
3289 $this->currentRow
= null;
3294 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3295 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3301 * Store a string into a LikeMatch marker object.
3305 public function __construct( $s ) {
3310 * Return the original stored string.
3314 public function toString() {