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
149 function fieldInfo( $table, $field );
152 * Get information about an index into an object
153 * @param $table string: Table name
154 * @param $index string: Index name
155 * @param $fname string: Calling function name
156 * @return Mixed: Database-specific index description class or false if the index does not exist
158 function indexInfo( $table, $index, $fname = 'Database::indexInfo' );
161 * Get the number of rows affected by the last write query
162 * @see http://www.php.net/mysql_affected_rows
166 function affectedRows();
169 * Wrapper for addslashes()
171 * @param $s string: to be slashed.
172 * @return string: slashed string.
174 function strencode( $s );
177 * Returns a wikitext link to the DB's website, e.g.,
178 * return "[http://www.mysql.com/ MySQL]";
179 * Should at least contain plain text, if for some reason
180 * your database has no website.
182 * @return string: wikitext of a link to the server software's web site
184 static function getSoftwareLink();
187 * A string describing the current software version, like from
188 * mysql_get_server_info().
190 * @return string: Version information from the database server.
192 function getServerVersion();
195 * A string describing the current software version, and possibly
196 * other details in a user-friendly way. Will be listed on Special:Version, etc.
197 * Use getServerVersion() to get machine-friendly information.
199 * @return string: Version information from the database server
201 function getServerInfo();
205 * Database abstraction object
208 abstract class DatabaseBase
implements DatabaseType
{
210 # ------------------------------------------------------------------------------
212 # ------------------------------------------------------------------------------
214 protected $mLastQuery = '';
215 protected $mDoneWrites = false;
216 protected $mPHPError = false;
218 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
219 protected $mOpened = false;
221 protected $mTablePrefix;
223 protected $mTrxLevel = 0;
224 protected $mErrorCount = 0;
225 protected $mLBInfo = array();
226 protected $mFakeSlaveLag = null, $mFakeMaster = false;
227 protected $mDefaultBigSelects = null;
228 protected $mSchemaVars = false;
230 # ------------------------------------------------------------------------------
232 # ------------------------------------------------------------------------------
233 # These optionally set a variable and return the previous state
236 * A string describing the current software version, and possibly
237 * other details in a user-friendly way. Will be listed on Special:Version, etc.
238 * Use getServerVersion() to get machine-friendly information.
240 * @return string: Version information from the database server
242 public function getServerInfo() {
243 return $this->getServerVersion();
247 * Boolean, controls output of large amounts of debug information
249 function debug( $debug = null ) {
250 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
254 * Turns buffering of SQL result sets on (true) or off (false).
255 * Default is "on" and it should not be changed without good reasons.
257 function bufferResults( $buffer = null ) {
258 if ( is_null( $buffer ) ) {
259 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
261 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
266 * Turns on (false) or off (true) the automatic generation and sending
267 * of a "we're sorry, but there has been a database error" page on
268 * database errors. Default is on (false). When turned off, the
269 * code should use lastErrno() and lastError() to handle the
270 * situation as appropriate.
272 function ignoreErrors( $ignoreErrors = null ) {
273 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
277 * The current depth of nested transactions
278 * @param $level Integer: , default NULL.
280 function trxLevel( $level = null ) {
281 return wfSetVar( $this->mTrxLevel
, $level );
285 * Number of errors logged, only useful when errors are ignored
287 function errorCount( $count = null ) {
288 return wfSetVar( $this->mErrorCount
, $count );
291 function tablePrefix( $prefix = null ) {
292 return wfSetVar( $this->mTablePrefix
, $prefix, true );
296 * Properties passed down from the server info array of the load balancer
298 function getLBInfo( $name = null ) {
299 if ( is_null( $name ) ) {
300 return $this->mLBInfo
;
302 if ( array_key_exists( $name, $this->mLBInfo
) ) {
303 return $this->mLBInfo
[$name];
310 function setLBInfo( $name, $value = null ) {
311 if ( is_null( $value ) ) {
312 $this->mLBInfo
= $name;
314 $this->mLBInfo
[$name] = $value;
319 * Set lag time in seconds for a fake slave
321 function setFakeSlaveLag( $lag ) {
322 $this->mFakeSlaveLag
= $lag;
326 * Make this connection a fake master
328 function setFakeMaster( $enabled = true ) {
329 $this->mFakeMaster
= $enabled;
333 * Returns true if this database supports (and uses) cascading deletes
335 function cascadingDeletes() {
340 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
342 function cleanupTriggers() {
347 * Returns true if this database is strict about what can be put into an IP field.
348 * Specifically, it uses a NULL value instead of an empty string.
350 function strictIPs() {
355 * Returns true if this database uses timestamps rather than integers
357 function realTimestamps() {
362 * Returns true if this database does an implicit sort when doing GROUP BY
364 function implicitGroupby() {
369 * Returns true if this database does an implicit order by when the column has an index
370 * For example: SELECT page_title FROM page LIMIT 1
372 function implicitOrderby() {
377 * Returns true if this database requires that SELECT DISTINCT queries require that all
378 ORDER BY expressions occur in the SELECT list per the SQL92 standard
380 function standardSelectDistinct() {
385 * Returns true if this database can do a native search on IP columns
386 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
388 function searchableIPs() {
393 * Returns true if this database can use functional indexes
395 function functionalIndexes() {
400 * Return the last query that went through DatabaseBase::query()
403 function lastQuery() { return $this->mLastQuery
; }
407 * Returns true if the connection may have been used for write queries.
408 * Should return true if unsure.
410 function doneWrites() { return $this->mDoneWrites
; }
413 * Is a connection to the database open?
416 function isOpen() { return $this->mOpened
; }
419 * Set a flag for this connection
421 * @param $flag Integer: DBO_* constants from Defines.php:
422 * - DBO_DEBUG: output some debug info (same as debug())
423 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
424 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
425 * - DBO_TRX: automatically start transactions
426 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
427 * and removes it in command line mode
428 * - DBO_PERSISTENT: use persistant database connection
430 function setFlag( $flag ) {
431 $this->mFlags |
= $flag;
435 * Clear a flag for this connection
437 * @param $flag: same as setFlag()'s $flag param
439 function clearFlag( $flag ) {
440 $this->mFlags
&= ~
$flag;
444 * Returns a boolean whether the flag $flag is set for this connection
446 * @param $flag: same as setFlag()'s $flag param
449 function getFlag( $flag ) {
450 return !!( $this->mFlags
& $flag );
454 * General read-only accessor
456 function getProperty( $name ) {
460 function getWikiID() {
461 if ( $this->mTablePrefix
) {
462 return "{$this->mDBname}-{$this->mTablePrefix}";
464 return $this->mDBname
;
469 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
471 public function getSchema() {
473 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
474 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
476 return "$IP/maintenance/tables.sql";
480 # ------------------------------------------------------------------------------
482 # ------------------------------------------------------------------------------
486 * @param $server String: database server host
487 * @param $user String: database user name
488 * @param $password String: database user password
489 * @param $dbName String: database name
491 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
493 function __construct( $server = false, $user = false, $password = false, $dbName = false,
494 $flags = 0, $tablePrefix = 'get from global'
496 global $wgOut, $wgDBprefix, $wgCommandLineMode;
498 # Can't get a reference if it hasn't been set yet
499 if ( !isset( $wgOut ) ) {
502 $this->mFlags
= $flags;
504 if ( $this->mFlags
& DBO_DEFAULT
) {
505 if ( $wgCommandLineMode ) {
506 $this->mFlags
&= ~DBO_TRX
;
508 $this->mFlags |
= DBO_TRX
;
512 /** Get the default table prefix*/
513 if ( $tablePrefix == 'get from global' ) {
514 $this->mTablePrefix
= $wgDBprefix;
516 $this->mTablePrefix
= $tablePrefix;
520 $this->open( $server, $user, $password, $dbName );
525 * Same as new DatabaseMysql( ... ), kept for backward compatibility
528 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
529 wfDeprecated( __METHOD__
);
530 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
534 * Given a DB type, construct the name of the appropriate child class of
535 * DatabaseBase. This is designed to replace all of the manual stuff like:
536 * $class = 'Database' . ucfirst( strtolower( $type ) );
537 * as well as validate against the canonical list of DB types we have
539 * This factory function is mostly useful for when you need to connect to a
540 * database other than the MediaWiki default (such as for external auth,
541 * an extension, et cetera). Do not use this to connect to the MediaWiki
542 * database. Example uses in core:
543 * @see LoadBalancer::reallyOpenConnection()
544 * @see ExternalUser_MediaWiki::initFromCond()
545 * @see ForeignDBRepo::getMasterDB()
546 * @see WebInstaller_DBConnect::execute()
548 * @param $dbType String A possible DB type
549 * @param $p Array An array of options to pass to the constructor.
550 * Valid options are: host, user, password, dbname, flags, tableprefix
551 * @return DatabaseBase subclass or null
553 public final static function newFromType( $dbType, $p = array() ) {
554 $canonicalDBTypes = array(
555 'mysql', 'postgres', 'sqlite', 'oracle', 'mssql', 'ibm_db2'
557 $dbType = strtolower( $dbType );
559 if( in_array( $dbType, $canonicalDBTypes ) ) {
560 $class = 'Database' . ucfirst( $dbType );
562 isset( $p['host'] ) ?
$p['host'] : false,
563 isset( $p['user'] ) ?
$p['user'] : false,
564 isset( $p['password'] ) ?
$p['password'] : false,
565 isset( $p['dbname'] ) ?
$p['dbname'] : false,
566 isset( $p['flags'] ) ?
$p['flags'] : 0,
567 isset( $p['tableprefix'] ) ?
$p['tableprefix'] : 'get from global'
574 protected function installErrorHandler() {
575 $this->mPHPError
= false;
576 $this->htmlErrors
= ini_set( 'html_errors', '0' );
577 set_error_handler( array( $this, 'connectionErrorHandler' ) );
580 protected function restoreErrorHandler() {
581 restore_error_handler();
582 if ( $this->htmlErrors
!== false ) {
583 ini_set( 'html_errors', $this->htmlErrors
);
585 if ( $this->mPHPError
) {
586 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
587 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
594 protected function connectionErrorHandler( $errno, $errstr ) {
595 $this->mPHPError
= $errstr;
599 * Closes a database connection.
600 * if it is open : commits any open transactions
602 * @return Bool operation success. true if already closed.
605 # Stub, should probably be overridden
610 * @param $error String: fallback error message, used if none is given by DB
612 function reportConnectionError( $error = 'Unknown error' ) {
613 $myError = $this->lastError();
619 throw new DBConnectionError( $this, $error );
623 * Determine whether a query writes to the DB.
624 * Should return true if unsure.
626 function isWriteQuery( $sql ) {
627 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
631 * Usually aborts on failure. If errors are explicitly ignored, returns success.
633 * @param $sql String: SQL query
634 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
635 * comment (you can use __METHOD__ or add some extra info)
636 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
637 * maybe best to catch the exception instead?
638 * @return boolean or ResultWrapper. true for a successful write query, ResultWrapper object for a successful read query,
639 * or false on failure if $tempIgnore set
640 * @throws DBQueryError Thrown when the database returns an error of any kind
642 public function query( $sql, $fname = '', $tempIgnore = false ) {
645 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
646 if ( isset( $wgProfiler ) ) {
647 # generalizeSQL will probably cut down the query to reasonable
648 # logging size most of the time. The substr is really just a sanity check.
650 # Who's been wasting my precious column space? -- TS
651 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
654 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
655 $totalProf = 'DatabaseBase::query-master';
657 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
658 $totalProf = 'DatabaseBase::query';
661 wfProfileIn( $totalProf );
662 wfProfileIn( $queryProf );
665 $this->mLastQuery
= $sql;
666 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
667 // Set a flag indicating that writes have been done
668 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
669 $this->mDoneWrites
= true;
672 # Add a comment for easy SHOW PROCESSLIST interpretation
675 if ( is_object( $wgUser ) && $wgUser->mDataLoaded
) {
676 $userName = $wgUser->getName();
677 if ( mb_strlen( $userName ) > 15 ) {
678 $userName = mb_substr( $userName, 0, 15 ) . '...';
680 $userName = str_replace( '/', '', $userName );
684 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
686 # $commentedSql = $sql;
689 # If DBO_TRX is set, start a transaction
690 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
691 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
692 // avoid establishing transactions for SHOW and SET statements too -
693 // that would delay transaction initializations to once connection
694 // is really used by application
695 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
696 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
700 if ( $this->debug() ) {
704 $sqlx = substr( $commentedSql, 0, 500 );
705 $sqlx = strtr( $sqlx, "\t\n", ' ' );
708 wfDebug( "Query $cnt (master): $sqlx\n" );
710 wfDebug( "Query $cnt (slave): $sqlx\n" );
714 if ( istainted( $sql ) & TC_MYSQL
) {
715 throw new MWException( 'Tainted query found' );
718 # Do the query and handle errors
719 $ret = $this->doQuery( $commentedSql );
721 # Try reconnecting if the connection was lost
722 if ( false === $ret && $this->wasErrorReissuable() ) {
723 # Transaction is gone, like it or not
724 $this->mTrxLevel
= 0;
725 wfDebug( "Connection lost, reconnecting...\n" );
727 if ( $this->ping() ) {
728 wfDebug( "Reconnected\n" );
729 $sqlx = substr( $commentedSql, 0, 500 );
730 $sqlx = strtr( $sqlx, "\t\n", ' ' );
731 global $wgRequestTime;
732 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
733 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
734 $ret = $this->doQuery( $commentedSql );
736 wfDebug( "Failed\n" );
740 if ( false === $ret ) {
741 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
744 if ( isset( $wgProfiler ) ) {
745 wfProfileOut( $queryProf );
746 wfProfileOut( $totalProf );
749 return $this->resultObject( $ret );
753 * @param $error String
754 * @param $errno Integer
756 * @param $fname String
757 * @param $tempIgnore Boolean
759 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
760 # Ignore errors during error handling to avoid infinite recursion
761 $ignore = $this->ignoreErrors( true );
762 ++
$this->mErrorCount
;
764 if ( $ignore ||
$tempIgnore ) {
765 wfDebug( "SQL ERROR (ignored): $error\n" );
766 $this->ignoreErrors( $ignore );
768 $sql1line = str_replace( "\n", "\\n", $sql );
769 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
770 wfDebug( "SQL ERROR: " . $error . "\n" );
771 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
777 * Intended to be compatible with the PEAR::DB wrapper functions.
778 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
780 * ? = scalar value, quoted as necessary
781 * ! = raw SQL bit (a function for instance)
782 * & = filename; reads the file and inserts as a blob
783 * (we don't use this though...)
785 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
786 /* MySQL doesn't support prepared statements (yet), so just
787 pack up the query for reference. We'll manually replace
789 return array( 'query' => $sql, 'func' => $func );
792 function freePrepared( $prepared ) {
793 /* No-op by default */
797 * Execute a prepared query with the various arguments
798 * @param $prepared String: the prepared sql
799 * @param $args Mixed: Either an array here, or put scalars as varargs
801 function execute( $prepared, $args = null ) {
802 if ( !is_array( $args ) ) {
804 $args = func_get_args();
805 array_shift( $args );
808 $sql = $this->fillPrepared( $prepared['query'], $args );
810 return $this->query( $sql, $prepared['func'] );
814 * Prepare & execute an SQL statement, quoting and inserting arguments
815 * in the appropriate places.
816 * @param $query String
819 function safeQuery( $query, $args = null ) {
820 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
822 if ( !is_array( $args ) ) {
824 $args = func_get_args();
825 array_shift( $args );
828 $retval = $this->execute( $prepared, $args );
829 $this->freePrepared( $prepared );
835 * For faking prepared SQL statements on DBs that don't support
837 * @param $preparedQuery String: a 'preparable' SQL statement
838 * @param $args Array of arguments to fill it with
839 * @return string executable SQL
841 function fillPrepared( $preparedQuery, $args ) {
843 $this->preparedArgs
=& $args;
845 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
846 array( &$this, 'fillPreparedArg' ), $preparedQuery );
850 * preg_callback func for fillPrepared()
851 * The arguments should be in $this->preparedArgs and must not be touched
852 * while we're doing this.
854 * @param $matches Array
858 function fillPreparedArg( $matches ) {
859 switch( $matches[1] ) {
860 case '\\?': return '?';
861 case '\\!': return '!';
862 case '\\&': return '&';
865 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
867 switch( $matches[1] ) {
868 case '?': return $this->addQuotes( $arg );
869 case '!': return $arg;
871 # return $this->addQuotes( file_get_contents( $arg ) );
872 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
874 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
879 * Free a result object
880 * @param $res Mixed: A SQL result
882 function freeResult( $res ) {
883 # Stub. Might not really need to be overridden, since results should
884 # be freed by PHP when the variable goes out of scope anyway.
888 * Simple UPDATE wrapper
889 * Usually aborts on failure
890 * If errors are explicitly ignored, returns success
892 * This function exists for historical reasons, DatabaseBase::update() has a more standard
893 * calling convention and feature set
895 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
896 $table = $this->tableName( $table );
897 $sql = "UPDATE $table SET $var = '" .
898 $this->strencode( $value ) . "' WHERE ($cond)";
900 return (bool)$this->query( $sql, $fname );
904 * Simple SELECT wrapper, returns a single field, input must be encoded
905 * Usually aborts on failure
906 * If errors are explicitly ignored, returns FALSE on failure
908 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
909 if ( !is_array( $options ) ) {
910 $options = array( $options );
913 $options['LIMIT'] = 1;
915 $res = $this->select( $table, $var, $cond, $fname, $options );
917 if ( $res === false ||
!$this->numRows( $res ) ) {
921 $row = $this->fetchRow( $res );
923 if ( $row !== false ) {
924 return reset( $row );
931 * Returns an optional USE INDEX clause to go after the table, and a
932 * string to go at the end of the query
936 * @param $options Array: associative array of options to be turned into
937 * an SQL query, valid keys are listed in the function.
940 function makeSelectOptions( $options ) {
941 $preLimitTail = $postLimitTail = '';
944 $noKeyOptions = array();
946 foreach ( $options as $key => $option ) {
947 if ( is_numeric( $key ) ) {
948 $noKeyOptions[$option] = true;
952 if ( isset( $options['GROUP BY'] ) ) {
953 $gb = is_array( $options['GROUP BY'] )
954 ?
implode( ',', $options['GROUP BY'] )
955 : $options['GROUP BY'];
956 $preLimitTail .= " GROUP BY {$gb}";
959 if ( isset( $options['HAVING'] ) ) {
960 $preLimitTail .= " HAVING {$options['HAVING']}";
963 if ( isset( $options['ORDER BY'] ) ) {
964 $ob = is_array( $options['ORDER BY'] )
965 ?
implode( ',', $options['ORDER BY'] )
966 : $options['ORDER BY'];
967 $preLimitTail .= " ORDER BY {$ob}";
970 // if (isset($options['LIMIT'])) {
971 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
972 // isset($options['OFFSET']) ? $options['OFFSET']
976 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
977 $postLimitTail .= ' FOR UPDATE';
980 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
981 $postLimitTail .= ' LOCK IN SHARE MODE';
984 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
985 $startOpts .= 'DISTINCT';
988 # Various MySQL extensions
989 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
990 $startOpts .= ' /*! STRAIGHT_JOIN */';
993 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
994 $startOpts .= ' HIGH_PRIORITY';
997 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
998 $startOpts .= ' SQL_BIG_RESULT';
1001 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
1002 $startOpts .= ' SQL_BUFFER_RESULT';
1005 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
1006 $startOpts .= ' SQL_SMALL_RESULT';
1009 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
1010 $startOpts .= ' SQL_CALC_FOUND_ROWS';
1013 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
1014 $startOpts .= ' SQL_CACHE';
1017 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
1018 $startOpts .= ' SQL_NO_CACHE';
1021 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
1022 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
1027 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
1033 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1034 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1035 * @param $conds Mixed: Array or string, condition(s) for WHERE
1036 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1037 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1038 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1039 * @param $join_conds Array: Associative array of table join conditions (optional)
1040 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1041 * @return mixed Database result resource (feed to DatabaseBase::fetchObject 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 * @todo migrate documentation to phpdocumentor format
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 * @return String: full database name
1517 function tableName( $name ) {
1518 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1519 # Skip the entire process when we have a string quoted on both ends.
1520 # Note that we check the end so that we will still quote any use of
1521 # use of `database`.table. But won't break things if someone wants
1522 # to query a database table with a dot in the name.
1523 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1527 # Lets test for any bits of text that should never show up in a table
1528 # name. Basically anything like JOIN or ON which are actually part of
1529 # SQL queries, but may end up inside of the table value to combine
1530 # sql. Such as how the API is doing.
1531 # Note that we use a whitespace test rather than a \b test to avoid
1532 # any remote case where a word like on may be inside of a table name
1533 # surrounded by symbols which may be considered word breaks.
1534 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1538 # Split database and table into proper variables.
1539 # We reverse the explode so that database.table and table both output
1540 # the correct table.
1541 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1542 if ( isset( $dbDetails[1] ) ) {
1543 @list
( $table, $database ) = $dbDetails;
1545 @list
( $table ) = $dbDetails;
1547 $prefix = $this->mTablePrefix
; # Default prefix
1549 # A database name has been specified in input. Quote the table name
1550 # because we don't want any prefixes added.
1551 if ( isset( $database ) ) {
1552 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1555 # Note that we use the long format because php will complain in in_array if
1556 # the input is not an array, and will complain in is_array if it is not set.
1557 if ( !isset( $database ) # Don't use shared database if pre selected.
1558 && isset( $wgSharedDB ) # We have a shared database
1559 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1560 && isset( $wgSharedTables )
1561 && is_array( $wgSharedTables )
1562 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1563 $database = $wgSharedDB;
1564 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1567 # Quote the $database and $table and apply the prefix if not quoted.
1568 if ( isset( $database ) ) {
1569 $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1571 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1573 # Merge our database and table into our final table name.
1574 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1580 * Fetch a number of table names into an array
1581 * This is handy when you need to construct SQL for joins
1584 * extract($dbr->tableNames('user','watchlist'));
1585 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1586 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1588 public function tableNames() {
1589 $inArray = func_get_args();
1592 foreach ( $inArray as $name ) {
1593 $retVal[$name] = $this->tableName( $name );
1600 * Fetch a number of table names into an zero-indexed numerical array
1601 * This is handy when you need to construct SQL for joins
1604 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1605 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1606 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1608 public function tableNamesN() {
1609 $inArray = func_get_args();
1612 foreach ( $inArray as $name ) {
1613 $retVal[] = $this->tableName( $name );
1620 * Get an aliased table name
1621 * e.g. tableName AS newTableName
1623 * @param $name string Table name, see tableName()
1624 * @param $alias string Alias (optional)
1625 * @return string SQL name for aliased table. Will not alias a table to its own name
1627 public function tableNameWithAlias( $name, $alias = false ) {
1628 if ( !$alias ||
$alias == $name ) {
1629 return $this->tableName( $name );
1631 return $this->tableName( $name ) . ' ' . $this->addIdentifierQuotes( $alias );
1636 * Gets an array of aliased table names
1638 * @param $tables array( [alias] => table )
1639 * @return array of strings, see tableNameWithAlias()
1641 public function tableNamesWithAlias( $tables ) {
1643 foreach ( $tables as $alias => $table ) {
1644 if ( is_numeric( $alias ) ) {
1647 $retval[] = $this->tableNameWithAlias( $table, $alias );
1655 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1658 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1659 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1661 foreach ( $tables as $alias => $table ) {
1662 if ( !is_string( $alias ) ) {
1663 // No alias? Set it equal to the table name
1666 // Is there a JOIN and INDEX clause for this table?
1667 if ( isset( $join_conds_safe[$alias] ) && isset( $use_index_safe[$alias] ) ) {
1668 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1669 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1670 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1672 $tableClause .= ' ON (' . $on . ')';
1675 $retJOIN[] = $tableClause;
1676 // Is there an INDEX clause?
1677 } else if ( isset( $use_index_safe[$alias] ) ) {
1678 $tableClause = $this->tableNameWithAlias( $table, $alias );
1679 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$alias] ) );
1680 $ret[] = $tableClause;
1681 // Is there a JOIN clause?
1682 } else if ( isset( $join_conds_safe[$alias] ) ) {
1683 $tableClause = $join_conds_safe[$alias][0] . ' ' . $this->tableNameWithAlias( $table, $alias );
1684 $on = $this->makeList( (array)$join_conds_safe[$alias][1], LIST_AND
);
1686 $tableClause .= ' ON (' . $on . ')';
1689 $retJOIN[] = $tableClause;
1691 $tableClause = $this->tableNameWithAlias( $table, $alias );
1692 $ret[] = $tableClause;
1696 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1697 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1698 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1700 // Compile our final table clause
1701 return implode( ' ', array( $straightJoins, $otherJoins ) );
1705 * Get the name of an index in a given table
1707 function indexName( $index ) {
1708 // Backwards-compatibility hack
1710 'ar_usertext_timestamp' => 'usertext_timestamp',
1711 'un_user_id' => 'user_id',
1712 'un_user_ip' => 'user_ip',
1715 if ( isset( $renamed[$index] ) ) {
1716 return $renamed[$index];
1723 * If it's a string, adds quotes and backslashes
1724 * Otherwise returns as-is
1726 function addQuotes( $s ) {
1727 if ( $s === null ) {
1730 # This will also quote numeric values. This should be harmless,
1731 # and protects against weird problems that occur when they really
1732 # _are_ strings such as article titles and string->number->string
1733 # conversion is not 1:1.
1734 return "'" . $this->strencode( $s ) . "'";
1739 * Quotes an identifier using `backticks` or "double quotes" depending on the database type.
1740 * MySQL uses `backticks` while basically everything else uses double quotes.
1741 * Since MySQL is the odd one out here the double quotes are our generic
1742 * and we implement backticks in DatabaseMysql.
1744 public function addIdentifierQuotes( $s ) {
1745 return '"' . str_replace( '"', '""', $s ) . '"';
1749 * Backwards compatibility, identifier quoting originated in DatabasePostgres
1750 * which used quote_ident which does not follow our naming conventions
1751 * was renamed to addIdentifierQuotes.
1752 * @deprecated use addIdentifierQuotes
1754 function quote_ident( $s ) {
1755 wfDeprecated( __METHOD__
);
1756 return $this->addIdentifierQuotes( $s );
1760 * Escape string for safe LIKE usage.
1761 * WARNING: you should almost never use this function directly,
1762 * instead use buildLike() that escapes everything automatically
1763 * Deprecated in 1.17, warnings in 1.17, removed in ???
1765 public function escapeLike( $s ) {
1766 wfDeprecated( __METHOD__
);
1767 return $this->escapeLikeInternal( $s );
1770 protected function escapeLikeInternal( $s ) {
1771 $s = str_replace( '\\', '\\\\', $s );
1772 $s = $this->strencode( $s );
1773 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1779 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1780 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1781 * Alternatively, the function could be provided with an array of aforementioned parameters.
1783 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1784 * for subpages of 'My page title'.
1785 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1788 * @return String: fully built LIKE statement
1790 function buildLike() {
1791 $params = func_get_args();
1793 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1794 $params = $params[0];
1799 foreach ( $params as $value ) {
1800 if ( $value instanceof LikeMatch
) {
1801 $s .= $value->toString();
1803 $s .= $this->escapeLikeInternal( $value );
1807 return " LIKE '" . $s . "' ";
1811 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1813 function anyChar() {
1814 return new LikeMatch( '_' );
1818 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1820 function anyString() {
1821 return new LikeMatch( '%' );
1825 * Returns an appropriately quoted sequence value for inserting a new row.
1826 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1827 * subclass will return an integer, and save the value for insertId()
1829 function nextSequenceValue( $seqName ) {
1834 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1835 * is only needed because a) MySQL must be as efficient as possible due to
1836 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1837 * which index to pick. Anyway, other databases might have different
1838 * indexes on a given table. So don't bother overriding this unless you're
1841 function useIndexClause( $index ) {
1846 * REPLACE query wrapper
1847 * PostgreSQL simulates this with a DELETE followed by INSERT
1848 * $row is the row to insert, an associative array
1849 * $uniqueIndexes is an array of indexes. Each element may be either a
1850 * field name or an array of field names
1852 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1853 * However if you do this, you run the risk of encountering errors which wouldn't have
1856 * @param $table String: The table to replace the row(s) in.
1857 * @param $uniqueIndexes Array: An associative array of indexes
1858 * @param $rows Array: Array of rows to replace
1859 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1861 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1862 $table = $this->tableName( $table );
1865 if ( !is_array( reset( $rows ) ) ) {
1866 $rows = array( $rows );
1869 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1872 foreach ( $rows as $row ) {
1879 $sql .= '(' . $this->makeList( $row ) . ')';
1882 return $this->query( $sql, $fname );
1886 * DELETE where the condition is a join
1887 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1889 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1890 * join condition matches, set $conds='*'
1892 * DO NOT put the join condition in $conds
1894 * @param $delTable String: The table to delete from.
1895 * @param $joinTable String: The other table.
1896 * @param $delVar String: The variable to join on, in the first table.
1897 * @param $joinVar String: The variable to join on, in the second table.
1898 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1899 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1901 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1903 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1906 $delTable = $this->tableName( $delTable );
1907 $joinTable = $this->tableName( $joinTable );
1908 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1910 if ( $conds != '*' ) {
1911 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1914 return $this->query( $sql, $fname );
1918 * Returns the size of a text field, or -1 for "unlimited"
1920 function textFieldSize( $table, $field ) {
1921 $table = $this->tableName( $table );
1922 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1923 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1924 $row = $this->fetchObject( $res );
1928 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1938 * A string to insert into queries to show that they're low-priority, like
1939 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1940 * string and nothing bad should happen.
1942 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1944 function lowPriorityOption() {
1949 * DELETE query wrapper
1951 * Use $conds == "*" to delete all rows
1953 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1955 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1958 $table = $this->tableName( $table );
1959 $sql = "DELETE FROM $table";
1961 if ( $conds != '*' ) {
1962 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1965 return $this->query( $sql, $fname );
1969 * INSERT SELECT wrapper
1970 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1971 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1972 * $conds may be "*" to copy the whole table
1973 * srcTable may be an array of tables.
1975 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1976 $insertOptions = array(), $selectOptions = array() )
1978 $destTable = $this->tableName( $destTable );
1980 if ( is_array( $insertOptions ) ) {
1981 $insertOptions = implode( ' ', $insertOptions );
1984 if ( !is_array( $selectOptions ) ) {
1985 $selectOptions = array( $selectOptions );
1988 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1990 if ( is_array( $srcTable ) ) {
1991 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1993 $srcTable = $this->tableName( $srcTable );
1996 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1997 " SELECT $startOpts " . implode( ',', $varMap ) .
1998 " FROM $srcTable $useIndex ";
2000 if ( $conds != '*' ) {
2001 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
2004 $sql .= " $tailOpts";
2006 return $this->query( $sql, $fname );
2010 * Construct a LIMIT query with optional offset. This is used for query
2011 * pages. The SQL should be adjusted so that only the first $limit rows
2012 * are returned. If $offset is provided as well, then the first $offset
2013 * rows should be discarded, and the next $limit rows should be returned.
2014 * If the result of the query is not ordered, then the rows to be returned
2015 * are theoretically arbitrary.
2017 * $sql is expected to be a SELECT, if that makes a difference. For
2018 * UPDATE, limitResultForUpdate should be used.
2020 * The version provided by default works in MySQL and SQLite. It will very
2021 * likely need to be overridden for most other DBMSes.
2023 * @param $sql String: SQL query we will append the limit too
2024 * @param $limit Integer: the SQL limit
2025 * @param $offset Integer the SQL offset (default false)
2027 function limitResult( $sql, $limit, $offset = false ) {
2028 if ( !is_numeric( $limit ) ) {
2029 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
2032 return "$sql LIMIT "
2033 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
2037 function limitResultForUpdate( $sql, $num ) {
2038 return $this->limitResult( $sql, $num, 0 );
2042 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
2043 * within the UNION construct.
2046 function unionSupportsOrderAndLimit() {
2047 return true; // True for almost every DB supported
2051 * Construct a UNION query
2052 * This is used for providing overload point for other DB abstractions
2053 * not compatible with the MySQL syntax.
2054 * @param $sqls Array: SQL statements to combine
2055 * @param $all Boolean: use UNION ALL
2056 * @return String: SQL fragment
2058 function unionQueries( $sqls, $all ) {
2059 $glue = $all ?
') UNION ALL (' : ') UNION (';
2060 return '(' . implode( $glue, $sqls ) . ')';
2064 * Returns an SQL expression for a simple conditional. This doesn't need
2065 * to be overridden unless CASE isn't supported in your DBMS.
2067 * @param $cond String: SQL expression which will result in a boolean value
2068 * @param $trueVal String: SQL expression to return if true
2069 * @param $falseVal String: SQL expression to return if false
2070 * @return String: SQL fragment
2072 function conditional( $cond, $trueVal, $falseVal ) {
2073 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
2077 * Returns a comand for str_replace function in SQL query.
2078 * Uses REPLACE() in MySQL
2080 * @param $orig String: column to modify
2081 * @param $old String: column to seek
2082 * @param $new String: column to replace with
2084 function strreplace( $orig, $old, $new ) {
2085 return "REPLACE({$orig}, {$old}, {$new})";
2089 * Determines if the last failure was due to a deadlock
2092 function wasDeadlock() {
2097 * Determines if the last query error was something that should be dealt
2098 * with by pinging the connection and reissuing the query.
2101 function wasErrorReissuable() {
2106 * Determines if the last failure was due to the database being read-only.
2109 function wasReadOnlyError() {
2114 * Perform a deadlock-prone transaction.
2116 * This function invokes a callback function to perform a set of write
2117 * queries. If a deadlock occurs during the processing, the transaction
2118 * will be rolled back and the callback function will be called again.
2121 * $dbw->deadlockLoop( callback, ... );
2123 * Extra arguments are passed through to the specified callback function.
2125 * Returns whatever the callback function returned on its successful,
2126 * iteration, or false on error, for example if the retry limit was
2129 function deadlockLoop() {
2130 $myFname = 'DatabaseBase::deadlockLoop';
2133 $args = func_get_args();
2134 $function = array_shift( $args );
2135 $oldIgnore = $this->ignoreErrors( true );
2136 $tries = DEADLOCK_TRIES
;
2138 if ( is_array( $function ) ) {
2139 $fname = $function[0];
2145 $retVal = call_user_func_array( $function, $args );
2146 $error = $this->lastError();
2147 $errno = $this->lastErrno();
2148 $sql = $this->lastQuery();
2151 if ( $this->wasDeadlock() ) {
2153 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2155 $this->reportQueryError( $error, $errno, $sql, $fname );
2158 } while ( $this->wasDeadlock() && --$tries > 0 );
2160 $this->ignoreErrors( $oldIgnore );
2162 if ( $tries <= 0 ) {
2163 $this->rollback( $myFname );
2164 $this->reportQueryError( $error, $errno, $sql, $fname );
2167 $this->commit( $myFname );
2173 * Do a SELECT MASTER_POS_WAIT()
2175 * @param $pos MySQLMasterPos object
2176 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2178 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2179 $fname = 'DatabaseBase::masterPosWait';
2180 wfProfileIn( $fname );
2182 # Commit any open transactions
2183 if ( $this->mTrxLevel
) {
2187 if ( !is_null( $this->mFakeSlaveLag
) ) {
2188 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2190 if ( $wait > $timeout * 1e6
) {
2191 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2192 wfProfileOut( $fname );
2194 } elseif ( $wait > 0 ) {
2195 wfDebug( "Fake slave waiting $wait us\n" );
2197 wfProfileOut( $fname );
2200 wfDebug( "Fake slave up to date ($wait us)\n" );
2201 wfProfileOut( $fname );
2206 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2207 $encFile = $this->addQuotes( $pos->file
);
2208 $encPos = intval( $pos->pos
);
2209 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2210 $res = $this->doQuery( $sql );
2212 if ( $res && $row = $this->fetchRow( $res ) ) {
2213 wfProfileOut( $fname );
2216 wfProfileOut( $fname );
2222 * Get the position of the master from SHOW SLAVE STATUS
2224 function getSlavePos() {
2225 if ( !is_null( $this->mFakeSlaveLag
) ) {
2226 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2227 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2231 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2232 $row = $this->fetchObject( $res );
2235 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2236 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2243 * Get the position of the master from SHOW MASTER STATUS
2245 function getMasterPos() {
2246 if ( $this->mFakeMaster
) {
2247 return new MySQLMasterPos( 'fake', microtime( true ) );
2250 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2251 $row = $this->fetchObject( $res );
2254 return new MySQLMasterPos( $row->File
, $row->Position
);
2261 * Begin a transaction, committing any previously open transaction
2263 function begin( $fname = 'DatabaseBase::begin' ) {
2264 $this->query( 'BEGIN', $fname );
2265 $this->mTrxLevel
= 1;
2271 function commit( $fname = 'DatabaseBase::commit' ) {
2272 if ( $this->mTrxLevel
) {
2273 $this->query( 'COMMIT', $fname );
2274 $this->mTrxLevel
= 0;
2279 * Rollback a transaction.
2280 * No-op on non-transactional databases.
2282 function rollback( $fname = 'DatabaseBase::rollback' ) {
2283 if ( $this->mTrxLevel
) {
2284 $this->query( 'ROLLBACK', $fname, true );
2285 $this->mTrxLevel
= 0;
2290 * Begin a transaction, committing any previously open transaction
2291 * @deprecated use begin()
2293 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2294 wfDeprecated( __METHOD__
);
2299 * Commit transaction, if one is open
2300 * @deprecated use commit()
2302 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2303 wfDeprecated( __METHOD__
);
2308 * Creates a new table with structure copied from existing table
2309 * Note that unlike most database abstraction functions, this function does not
2310 * automatically append database prefix, because it works at a lower
2311 * abstraction level.
2313 * @param $oldName String: name of table whose structure should be copied
2314 * @param $newName String: name of table to be created
2315 * @param $temporary Boolean: whether the new table should be temporary
2316 * @param $fname String: calling function name
2317 * @return Boolean: true if operation was successful
2319 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2320 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2324 * List all tables on the database
2326 * @param $prefix Only show tables with this prefix, e.g. mw_
2327 * @param $fname String: calling function name
2329 function listTables( $prefix = null, $fname = 'DatabaseBase::listTables' ) {
2330 throw new MWException( 'DatabaseBase::listTables is not implemented in descendant class' );
2334 * Return MW-style timestamp used for MySQL schema
2336 function timestamp( $ts = 0 ) {
2337 return wfTimestamp( TS_MW
, $ts );
2341 * Local database timestamp format or null
2343 function timestampOrNull( $ts = null ) {
2344 if ( is_null( $ts ) ) {
2347 return $this->timestamp( $ts );
2354 function resultObject( $result ) {
2355 if ( empty( $result ) ) {
2357 } elseif ( $result instanceof ResultWrapper
) {
2359 } elseif ( $result === true ) {
2360 // Successful write query
2363 return new ResultWrapper( $this, $result );
2368 * Return aggregated value alias
2370 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2375 * Ping the server and try to reconnect if it there is no connection
2377 * @return bool Success or failure
2380 # Stub. Not essential to override.
2386 * Currently supported only by MySQL
2387 * @return Database replication lag in seconds
2390 return intval( $this->mFakeSlaveLag
);
2394 * Get status information from SHOW STATUS in an associative array
2396 function getStatus( $which = "%" ) {
2397 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2400 foreach ( $res as $row ) {
2401 $status[$row->Variable_name
] = $row->Value
;
2408 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2410 function maxListLen() {
2414 function encodeBlob( $b ) {
2418 function decodeBlob( $b ) {
2423 * Override database's default connection timeout. May be useful for very
2424 * long batch queries such as full-wiki dumps, where a single query reads
2425 * out over hours or days. May or may not be necessary for non-MySQL
2426 * databases. For most purposes, leaving it as a no-op should be fine.
2428 * @param $timeout Integer in seconds
2430 public function setTimeout( $timeout ) {}
2433 * Read and execute SQL commands from a file.
2434 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2435 * @param $filename String: File name to open
2436 * @param $lineCallback Callback: Optional function called before reading each line
2437 * @param $resultCallback Callback: Optional function called for each MySQL result
2438 * @param $fname String: Calling function name or false if name should be generated dynamically
2441 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2442 wfSuppressWarnings();
2443 $fp = fopen( $filename, 'r' );
2444 wfRestoreWarnings();
2446 if ( false === $fp ) {
2447 throw new MWException( "Could not open \"{$filename}\".\n" );
2451 $fname = __METHOD__
. "( $filename )";
2455 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2457 catch ( MWException
$e ) {
2468 * Get the full path of a patch file. Originally based on archive()
2469 * from updaters.inc. Keep in mind this always returns a patch, as
2470 * it fails back to MySQL if no DB-specific patch can be found
2472 * @param $patch String The name of the patch, like patch-something.sql
2473 * @return String Full path to patch file
2475 public function patchPath( $patch ) {
2478 $dbType = $this->getType();
2479 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2480 return "$IP/maintenance/$dbType/archives/$patch";
2482 return "$IP/maintenance/archives/$patch";
2487 * Set variables to be used in sourceFile/sourceStream, in preference to the
2488 * ones in $GLOBALS. If an array is set here, $GLOBALS will not be used at
2489 * all. If it's set to false, $GLOBALS will be used.
2491 * @param $vars False, or array mapping variable name to value.
2493 function setSchemaVars( $vars ) {
2494 $this->mSchemaVars
= $vars;
2498 * Read and execute commands from an open file handle
2499 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2500 * @param $fp Resource: File handle
2501 * @param $lineCallback Callback: Optional function called before reading each line
2502 * @param $resultCallback Callback: Optional function called for each MySQL result
2503 * @param $fname String: Calling function name
2505 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2508 $dollarquote = false;
2510 while ( ! feof( $fp ) ) {
2511 if ( $lineCallback ) {
2512 call_user_func( $lineCallback );
2515 $line = trim( fgets( $fp, 1024 ) );
2516 $sl = strlen( $line ) - 1;
2522 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2526 # # Allow dollar quoting for function declarations
2527 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2528 if ( $dollarquote ) {
2529 $dollarquote = false;
2533 $dollarquote = true;
2536 else if ( !$dollarquote ) {
2537 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2539 $line = substr( $line, 0, $sl );
2550 $cmd = str_replace( ';;', ";", $cmd );
2551 $cmd = $this->replaceVars( $cmd );
2552 $res = $this->query( $cmd, $fname );
2554 if ( $resultCallback ) {
2555 call_user_func( $resultCallback, $res, $this );
2558 if ( false === $res ) {
2559 $err = $this->lastError();
2560 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2572 * Database independent variable replacement, replaces a set of variables
2573 * in a sql statement with their contents as given by $this->getSchemaVars().
2574 * Supports '{$var}' `{$var}` and / *$var* / (without the spaces) style variables
2576 * '{$var}' should be used for text and is passed through the database's addQuotes method
2577 * `{$var}` should be used for identifiers (eg: table and database names), it is passed through
2578 * the database's addIdentifierQuotes method which can be overridden if the database
2579 * uses something other than backticks.
2580 * / *$var* / is just encoded, besides traditional dbprefix and tableoptions it's use should be avoided
2582 * @param $ins String: SQL statement to replace variables in
2583 * @return String The new SQL statement with variables replaced
2585 protected function replaceSchemaVars( $ins ) {
2586 $vars = $this->getSchemaVars();
2587 foreach ( $vars as $var => $value ) {
2589 $ins = str_replace( '\'{$' . $var . '}\'', $this->addQuotes( $value ), $ins );
2591 $ins = str_replace( '`{$' . $var . '}`', $this->addIdentifierQuotes( $value ), $ins );
2593 $ins = str_replace( '/*$' . $var . '*/', $this->strencode( $value ) , $ins );
2599 * Replace variables in sourced SQL
2601 protected function replaceVars( $ins ) {
2602 $ins = $this->replaceSchemaVars( $ins );
2605 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2606 array( $this, 'tableNameCallback' ), $ins );
2609 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2610 array( $this, 'indexNameCallback' ), $ins );
2616 * Get schema variables. If none have been set via setSchemaVars(), then
2617 * use some defaults from the current object.
2619 protected function getSchemaVars() {
2620 if ( $this->mSchemaVars
) {
2621 return $this->mSchemaVars
;
2623 return $this->getDefaultSchemaVars();
2628 * Get schema variables to use if none have been set via setSchemaVars().
2629 * Override this in derived classes to provide variables for tables.sql
2630 * and SQL patch files.
2632 protected function getDefaultSchemaVars() {
2637 * Table name callback
2640 protected function tableNameCallback( $matches ) {
2641 return $this->tableName( $matches[1] );
2645 * Index name callback
2647 protected function indexNameCallback( $matches ) {
2648 return $this->indexName( $matches[1] );
2652 * Build a concatenation list to feed into a SQL query
2653 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2656 function buildConcat( $stringList ) {
2657 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2661 * Acquire a named lock
2663 * Abstracted from Filestore::lock() so child classes can implement for
2666 * @param $lockName String: name of lock to aquire
2667 * @param $method String: name of method calling us
2668 * @param $timeout Integer: timeout
2671 public function lock( $lockName, $method, $timeout = 5 ) {
2678 * @param $lockName String: Name of lock to release
2679 * @param $method String: Name of method calling us
2681 * @return Returns 1 if the lock was released, 0 if the lock was not established
2682 * by this thread (in which case the lock is not released), and NULL if the named
2683 * lock did not exist
2685 public function unlock( $lockName, $method ) {
2690 * Lock specific tables
2692 * @param $read Array of tables to lock for read access
2693 * @param $write Array of tables to lock for write access
2694 * @param $method String name of caller
2695 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2697 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2702 * Unlock specific tables
2704 * @param $method String the caller
2706 public function unlockTables( $method ) {
2713 public function dropTable( $tableName, $fName = 'DatabaseBase::dropTable' ) {
2714 if( !$this->tableExists( $tableName ) ) {
2717 $sql = "DROP TABLE " . $this->tableName( $tableName );
2718 if( $this->cascadingDeletes() ) {
2721 return $this->query( $sql, $fName );
2725 * Get search engine class. All subclasses of this need to implement this
2726 * if they wish to use searching.
2730 public function getSearchEngine() {
2731 return 'SearchEngineDummy';
2735 * Find out when 'infinity' is. Most DBMSes support this. This is a special
2736 * keyword for timestamps in PostgreSQL, and works with CHAR(14) as well
2737 * because "i" sorts after all numbers.
2741 public function getInfinity() {
2746 * Allow or deny "big selects" for this session only. This is done by setting
2747 * the sql_big_selects session variable.
2749 * This is a MySQL-specific feature.
2751 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2753 public function setBigSelects( $value = true ) {
2758 /******************************************************************************
2760 *****************************************************************************/
2769 function __construct( $data ) {
2770 $this->mData
= $data;
2778 return $this->mData
;
2786 * This allows us to distinguish a blob from a normal string and an array of strings
2791 function __construct( $data ) {
2792 $this->mData
= $data;
2796 return $this->mData
;
2801 * Base for all database-specific classes representing information about database fields
2812 * Name of table this field belongs to
2815 function tableName();
2824 * Whether this field can store NULL values
2827 function isNullable();
2830 /******************************************************************************
2832 *****************************************************************************/
2835 * Database error base class
2838 class DBError
extends MWException
{
2842 * Construct a database error
2843 * @param $db Database object which threw the error
2844 * @param $error String A simple error message to be used for debugging
2846 function __construct( DatabaseBase
&$db, $error ) {
2848 parent
::__construct( $error );
2851 function getText() {
2852 global $wgShowDBErrorBacktrace;
2854 $s = $this->getMessage() . "\n";
2856 if ( $wgShowDBErrorBacktrace ) {
2857 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2867 class DBConnectionError
extends DBError
{
2870 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2871 $msg = 'DB connection error';
2873 if ( trim( $error ) != '' ) {
2877 $this->error
= $error;
2879 parent
::__construct( $db, $msg );
2882 function useOutputPage() {
2883 // Not likely to work
2887 function useMessageCache() {
2888 // Not likely to work
2892 function getLogMessage() {
2893 # Don't send to the exception log
2897 function getPageTitle() {
2898 global $wgSitename, $wgLang;
2900 $header = "$wgSitename has a problem";
2902 if ( $wgLang instanceof Language
) {
2903 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2909 function getHTML() {
2910 global $wgLang, $wgUseFileCache, $wgShowDBErrorBacktrace;
2912 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2913 $again = 'Try waiting a few minutes and reloading.';
2914 $info = '(Can\'t contact the database server: $1)';
2916 if ( $wgLang instanceof Language
) {
2917 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2918 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2919 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2922 # No database access
2923 MessageCache
::singleton()->disable();
2925 if ( trim( $this->error
) == '' ) {
2926 $this->error
= $this->db
->getProperty( 'mServer' );
2929 $this->error
= Html
::element( 'span', array( 'dir' => 'ltr' ), $this->error
);
2931 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2932 $text = str_replace( '$1', $this->error
, $noconnect );
2934 if ( $wgShowDBErrorBacktrace ) {
2935 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2938 $extra = $this->searchForm();
2940 if ( $wgUseFileCache ) {
2942 $cache = $this->fileCachedPage();
2943 # Cached version on file system?
2944 if ( $cache !== null ) {
2945 # Hack: extend the body for error messages
2946 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2947 # Add cache notice...
2948 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2950 # Localize it if possible...
2951 if ( $wgLang instanceof Language
) {
2952 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2955 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2957 # Output cached page with notices on bottom and re-close body
2958 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2960 } catch ( MWException
$e ) {
2961 // Do nothing, just use the default page
2965 # Headers needed here - output is just the error message
2966 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2969 function searchForm() {
2970 global $wgSitename, $wgServer, $wgLang;
2972 $usegoogle = "You can try searching via Google in the meantime.";
2973 $outofdate = "Note that their indexes of our content may be out of date.";
2974 $googlesearch = "Search";
2976 if ( $wgLang instanceof Language
) {
2977 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2978 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2979 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2982 $search = htmlspecialchars( @$_REQUEST['search'] );
2984 $server = htmlspecialchars( $wgServer );
2985 $sitename = htmlspecialchars( $wgSitename );
2988 <div style="margin: 1.5em">$usegoogle<br />
2989 <small>$outofdate</small></div>
2990 <!-- SiteSearch Google -->
2991 <form method="get" action="http://www.google.com/search" id="googlesearch">
2992 <input type="hidden" name="domains" value="$server" />
2993 <input type="hidden" name="num" value="50" />
2994 <input type="hidden" name="ie" value="UTF-8" />
2995 <input type="hidden" name="oe" value="UTF-8" />
2997 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2998 <input type="submit" name="btnG" value="$googlesearch" />
3000 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
3001 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
3004 <!-- SiteSearch Google -->
3009 private function fileCachedPage() {
3010 global $wgTitle, $wgLang, $wgOut;
3012 if ( $wgOut->isDisabled() ) {
3013 return; // Done already?
3016 $mainpage = 'Main Page';
3018 if ( $wgLang instanceof Language
) {
3019 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
3025 $t = Title
::newFromText( $mainpage );
3028 $cache = new HTMLFileCache( $t );
3029 if ( $cache->isFileCached() ) {
3030 return $cache->fetchPageText();
3036 function htmlBodyOnly() {
3044 class DBQueryError
extends DBError
{
3045 public $error, $errno, $sql, $fname;
3047 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
3048 $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" .
3050 "Function: $fname\n" .
3051 "Error: $errno $error\n";
3053 parent
::__construct( $db, $message );
3055 $this->error
= $error;
3056 $this->errno
= $errno;
3058 $this->fname
= $fname;
3061 function getText() {
3062 global $wgShowDBErrorBacktrace;
3064 if ( $this->useMessageCache() ) {
3065 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
3066 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
3068 if ( $wgShowDBErrorBacktrace ) {
3069 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
3074 return parent
::getText();
3079 global $wgShowSQLErrors;
3081 if ( !$wgShowSQLErrors ) {
3082 return $this->msg( 'sqlhidden', 'SQL hidden' );
3088 function getLogMessage() {
3089 # Don't send to the exception log
3093 function getPageTitle() {
3094 return $this->msg( 'databaseerror', 'Database error' );
3097 function getHTML() {
3098 global $wgShowDBErrorBacktrace;
3100 if ( $this->useMessageCache() ) {
3101 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
3102 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
3104 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
3107 if ( $wgShowDBErrorBacktrace ) {
3108 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
3118 class DBUnexpectedError
extends DBError
{}
3122 * Result wrapper for grabbing data queried by someone else
3125 class ResultWrapper
implements Iterator
{
3126 var $db, $result, $pos = 0, $currentRow = null;
3129 * Create a new result object from a result resource and a Database object
3131 * @param DatabaseBase $database
3132 * @param resource $result
3134 function __construct( $database, $result ) {
3135 $this->db
= $database;
3137 if ( $result instanceof ResultWrapper
) {
3138 $this->result
= $result->result
;
3140 $this->result
= $result;
3145 * Get the number of rows in a result object
3149 function numRows() {
3150 return $this->db
->numRows( $this );
3154 * Fetch the next row from the given result object, in object form.
3155 * Fields can be retrieved with $row->fieldname, with fields acting like
3158 * @return MySQL row object
3159 * @throws DBUnexpectedError Thrown if the database returns an error
3161 function fetchObject() {
3162 return $this->db
->fetchObject( $this );
3166 * Fetch the next row from the given result object, in associative array
3167 * form. Fields are retrieved with $row['fieldname'].
3169 * @return MySQL row object
3170 * @throws DBUnexpectedError Thrown if the database returns an error
3172 function fetchRow() {
3173 return $this->db
->fetchRow( $this );
3177 * Free a result object
3180 $this->db
->freeResult( $this );
3181 unset( $this->result
);
3186 * Change the position of the cursor in a result object.
3187 * See mysql_data_seek()
3189 * @param $row integer
3191 function seek( $row ) {
3192 $this->db
->dataSeek( $this, $row );
3195 /*********************
3196 * Iterator functions
3197 * Note that using these in combination with the non-iterator functions
3198 * above may cause rows to be skipped or repeated.
3202 if ( $this->numRows() ) {
3203 $this->db
->dataSeek( $this, 0 );
3206 $this->currentRow
= null;
3209 function current() {
3210 if ( is_null( $this->currentRow
) ) {
3213 return $this->currentRow
;
3222 $this->currentRow
= $this->fetchObject();
3223 return $this->currentRow
;
3227 return $this->current() !== false;
3232 * Overloads the relevant methods of the real ResultsWrapper so it
3233 * doesn't go anywhere near an actual database.
3235 class FakeResultWrapper
extends ResultWrapper
{
3236 var $result = array();
3237 var $db = null; // And it's going to stay that way :D
3239 var $currentRow = null;
3241 function __construct( $array ) {
3242 $this->result
= $array;
3245 function numRows() {
3246 return count( $this->result
);
3249 function fetchRow() {
3250 $this->currentRow
= $this->result
[$this->pos++
];
3251 return $this->currentRow
;
3254 function seek( $row ) {
3260 // Callers want to be able to access fields with $this->fieldName
3261 function fetchObject() {
3262 $this->currentRow
= $this->result
[$this->pos++
];
3263 return (object)$this->currentRow
;
3268 $this->currentRow
= null;
3273 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3274 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3280 * Store a string into a LikeMatch marker object.
3284 public function __construct( $s ) {
3289 * Return the original stored string.
3293 public function toString() {