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.
31 public function getType();
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 public 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 /*private*/ 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 public 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 public function fetchRow( $res );
77 * Get the number of rows in a result object
79 * @param $res Mixed: A SQL result
82 public 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 public 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 public 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();
115 public function 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 public function dataSeek( $res, $row );
127 * Get the last error number
128 * @see http://www.php.net/mysql_errno
132 public function lastErrno();
135 * Get a description of the last error
136 * @see http://www.php.net/mysql_error
140 public 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 public 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 public function affectedRows();
169 * Wrapper for addslashes()
171 * @param $s string: to be slashed.
172 * @return string: slashed string.
174 public 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 public 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 public 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 public 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;
229 # ------------------------------------------------------------------------------
231 # ------------------------------------------------------------------------------
232 # These optionally set a variable and return the previous state
235 * A string describing the current software version, and possibly
236 * other details in a user-friendly way. Will be listed on Special:Version, etc.
237 * Use getServerVersion() to get machine-friendly information.
239 * @return string: Version information from the database server
241 public function getServerInfo() {
242 return $this->getServerVersion();
246 * Boolean, controls output of large amounts of debug information
248 function debug( $debug = null ) {
249 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
253 * Turns buffering of SQL result sets on (true) or off (false).
254 * Default is "on" and it should not be changed without good reasons.
256 function bufferResults( $buffer = null ) {
257 if ( is_null( $buffer ) ) {
258 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
260 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
265 * Turns on (false) or off (true) the automatic generation and sending
266 * of a "we're sorry, but there has been a database error" page on
267 * database errors. Default is on (false). When turned off, the
268 * code should use lastErrno() and lastError() to handle the
269 * situation as appropriate.
271 function ignoreErrors( $ignoreErrors = null ) {
272 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
276 * The current depth of nested transactions
277 * @param $level Integer: , default NULL.
279 function trxLevel( $level = null ) {
280 return wfSetVar( $this->mTrxLevel
, $level );
284 * Number of errors logged, only useful when errors are ignored
286 function errorCount( $count = null ) {
287 return wfSetVar( $this->mErrorCount
, $count );
290 function tablePrefix( $prefix = null ) {
291 return wfSetVar( $this->mTablePrefix
, $prefix );
295 * Properties passed down from the server info array of the load balancer
297 function getLBInfo( $name = null ) {
298 if ( is_null( $name ) ) {
299 return $this->mLBInfo
;
301 if ( array_key_exists( $name, $this->mLBInfo
) ) {
302 return $this->mLBInfo
[$name];
309 function setLBInfo( $name, $value = null ) {
310 if ( is_null( $value ) ) {
311 $this->mLBInfo
= $name;
313 $this->mLBInfo
[$name] = $value;
318 * Set lag time in seconds for a fake slave
320 function setFakeSlaveLag( $lag ) {
321 $this->mFakeSlaveLag
= $lag;
325 * Make this connection a fake master
327 function setFakeMaster( $enabled = true ) {
328 $this->mFakeMaster
= $enabled;
332 * Returns true if this database supports (and uses) cascading deletes
334 function cascadingDeletes() {
339 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
341 function cleanupTriggers() {
346 * Returns true if this database is strict about what can be put into an IP field.
347 * Specifically, it uses a NULL value instead of an empty string.
349 function strictIPs() {
354 * Returns true if this database uses timestamps rather than integers
356 function realTimestamps() {
361 * Returns true if this database does an implicit sort when doing GROUP BY
363 function implicitGroupby() {
368 * Returns true if this database does an implicit order by when the column has an index
369 * For example: SELECT page_title FROM page LIMIT 1
371 function implicitOrderby() {
376 * Returns true if this database requires that SELECT DISTINCT queries require that all
377 ORDER BY expressions occur in the SELECT list per the SQL92 standard
379 function standardSelectDistinct() {
384 * Returns true if this database can do a native search on IP columns
385 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
387 function searchableIPs() {
392 * Returns true if this database can use functional indexes
394 function functionalIndexes() {
399 * Return the last query that went through DatabaseBase::query()
402 function lastQuery() { return $this->mLastQuery
; }
406 * Returns true if the connection may have been used for write queries.
407 * Should return true if unsure.
409 function doneWrites() { return $this->mDoneWrites
; }
412 * Is a connection to the database open?
415 function isOpen() { return $this->mOpened
; }
418 * Set a flag for this connection
420 * @param $flag Integer: DBO_* constants from Defines.php:
421 * - DBO_DEBUG: output some debug info (same as debug())
422 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
423 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
424 * - DBO_TRX: automatically start transactions
425 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
426 * and removes it in command line mode
427 * - DBO_PERSISTENT: use persistant database connection
429 function setFlag( $flag ) {
430 $this->mFlags |
= $flag;
434 * Clear a flag for this connection
436 * @param $flag: same as setFlag()'s $flag param
438 function clearFlag( $flag ) {
439 $this->mFlags
&= ~
$flag;
443 * Returns a boolean whether the flag $flag is set for this connection
445 * @param $flag: same as setFlag()'s $flag param
448 function getFlag( $flag ) {
449 return !!( $this->mFlags
& $flag );
453 * General read-only accessor
455 function getProperty( $name ) {
459 function getWikiID() {
460 if ( $this->mTablePrefix
) {
461 return "{$this->mDBname}-{$this->mTablePrefix}";
463 return $this->mDBname
;
468 * Return a path to the DBMS-specific schema, otherwise default to tables.sql
470 public function getSchema() {
472 if ( file_exists( "$IP/maintenance/" . $this->getType() . "/tables.sql" ) ) {
473 return "$IP/maintenance/" . $this->getType() . "/tables.sql";
475 return "$IP/maintenance/tables.sql";
479 # ------------------------------------------------------------------------------
481 # ------------------------------------------------------------------------------
485 * @param $server String: database server host
486 * @param $user String: database user name
487 * @param $password String: database user password
488 * @param $dbName String: database name
490 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
492 function __construct( $server = false, $user = false, $password = false, $dbName = false,
493 $flags = 0, $tablePrefix = 'get from global'
495 global $wgOut, $wgDBprefix, $wgCommandLineMode;
497 # Can't get a reference if it hasn't been set yet
498 if ( !isset( $wgOut ) ) {
501 $this->mFlags
= $flags;
503 if ( $this->mFlags
& DBO_DEFAULT
) {
504 if ( $wgCommandLineMode ) {
505 $this->mFlags
&= ~DBO_TRX
;
507 $this->mFlags |
= DBO_TRX
;
512 // Faster read-only access
513 if ( wfReadOnly() ) {
514 $this->mFlags |= DBO_PERSISTENT;
515 $this->mFlags &= ~DBO_TRX;
518 /** Get the default table prefix*/
519 if ( $tablePrefix == 'get from global' ) {
520 $this->mTablePrefix
= $wgDBprefix;
522 $this->mTablePrefix
= $tablePrefix;
526 $this->open( $server, $user, $password, $dbName );
531 * Same as new DatabaseMysql( ... ), kept for backward compatibility
532 * @param $server String: database server host
533 * @param $user String: database user name
534 * @param $password String: database user password
535 * @param $dbName String: database name
538 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 ) {
539 wfDeprecated( __METHOD__
);
540 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
543 protected function installErrorHandler() {
544 $this->mPHPError
= false;
545 $this->htmlErrors
= ini_set( 'html_errors', '0' );
546 set_error_handler( array( $this, 'connectionErrorHandler' ) );
549 protected function restoreErrorHandler() {
550 restore_error_handler();
551 if ( $this->htmlErrors
!== false ) {
552 ini_set( 'html_errors', $this->htmlErrors
);
554 if ( $this->mPHPError
) {
555 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
556 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
563 protected function connectionErrorHandler( $errno, $errstr ) {
564 $this->mPHPError
= $errstr;
568 * Closes a database connection.
569 * if it is open : commits any open transactions
571 * @return Bool operation success. true if already closed.
574 # Stub, should probably be overridden
579 * @param $error String: fallback error message, used if none is given by DB
581 function reportConnectionError( $error = 'Unknown error' ) {
582 $myError = $this->lastError();
588 throw new DBConnectionError( $this, $error );
592 * Determine whether a query writes to the DB.
593 * Should return true if unsure.
595 function isWriteQuery( $sql ) {
596 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
600 * Usually aborts on failure. If errors are explicitly ignored, returns success.
602 * @param $sql String: SQL query
603 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
604 * comment (you can use __METHOD__ or add some extra info)
605 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
606 * maybe best to catch the exception instead?
607 * @return true for a successful write query, ResultWrapper object for a successful read query,
608 * or false on failure if $tempIgnore set
609 * @throws DBQueryError Thrown when the database returns an error of any kind
611 public function query( $sql, $fname = '', $tempIgnore = false ) {
614 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
615 if ( isset( $wgProfiler ) ) {
616 # generalizeSQL will probably cut down the query to reasonable
617 # logging size most of the time. The substr is really just a sanity check.
619 # Who's been wasting my precious column space? -- TS
620 # $profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
623 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
624 $totalProf = 'DatabaseBase::query-master';
626 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
627 $totalProf = 'DatabaseBase::query';
630 wfProfileIn( $totalProf );
631 wfProfileIn( $queryProf );
634 $this->mLastQuery
= $sql;
635 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
636 // Set a flag indicating that writes have been done
637 wfDebug( __METHOD__
. ": Writes done: $sql\n" );
638 $this->mDoneWrites
= true;
641 # Add a comment for easy SHOW PROCESSLIST interpretation
644 if ( is_object( $wgUser ) && $wgUser->mDataLoaded
) {
645 $userName = $wgUser->getName();
646 if ( mb_strlen( $userName ) > 15 ) {
647 $userName = mb_substr( $userName, 0, 15 ) . '...';
649 $userName = str_replace( '/', '', $userName );
653 $commentedSql = preg_replace( '/\s/', " /* $fname $userName */ ", $sql, 1 );
655 # $commentedSql = $sql;
658 # If DBO_TRX is set, start a transaction
659 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
660 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK' ) {
661 // avoid establishing transactions for SHOW and SET statements too -
662 // that would delay transaction initializations to once connection
663 // is really used by application
664 $sqlstart = substr( $sql, 0, 10 ); // very much worth it, benchmark certified(tm)
665 if ( strpos( $sqlstart, "SHOW " ) !== 0 and strpos( $sqlstart, "SET " ) !== 0 )
669 if ( $this->debug() ) {
673 $sqlx = substr( $commentedSql, 0, 500 );
674 $sqlx = strtr( $sqlx, "\t\n", ' ' );
677 wfDebug( "Query $cnt (master): $sqlx\n" );
679 wfDebug( "Query $cnt (slave): $sqlx\n" );
683 if ( istainted( $sql ) & TC_MYSQL
) {
684 throw new MWException( 'Tainted query found' );
687 # Do the query and handle errors
688 $ret = $this->doQuery( $commentedSql );
690 # Try reconnecting if the connection was lost
691 if ( false === $ret && $this->wasErrorReissuable() ) {
692 # Transaction is gone, like it or not
693 $this->mTrxLevel
= 0;
694 wfDebug( "Connection lost, reconnecting...\n" );
696 if ( $this->ping() ) {
697 wfDebug( "Reconnected\n" );
698 $sqlx = substr( $commentedSql, 0, 500 );
699 $sqlx = strtr( $sqlx, "\t\n", ' ' );
700 global $wgRequestTime;
701 $elapsed = round( microtime( true ) - $wgRequestTime, 3 );
702 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
703 $ret = $this->doQuery( $commentedSql );
705 wfDebug( "Failed\n" );
709 if ( false === $ret ) {
710 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
713 if ( isset( $wgProfiler ) ) {
714 wfProfileOut( $queryProf );
715 wfProfileOut( $totalProf );
718 return $this->resultObject( $ret );
722 * @param $error String
723 * @param $errno Integer
725 * @param $fname String
726 * @param $tempIgnore Boolean
728 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
729 # Ignore errors during error handling to avoid infinite recursion
730 $ignore = $this->ignoreErrors( true );
731 ++
$this->mErrorCount
;
733 if ( $ignore ||
$tempIgnore ) {
734 wfDebug( "SQL ERROR (ignored): $error\n" );
735 $this->ignoreErrors( $ignore );
737 $sql1line = str_replace( "\n", "\\n", $sql );
738 wfLogDBError( "$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n" );
739 wfDebug( "SQL ERROR: " . $error . "\n" );
740 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
746 * Intended to be compatible with the PEAR::DB wrapper functions.
747 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
749 * ? = scalar value, quoted as necessary
750 * ! = raw SQL bit (a function for instance)
751 * & = filename; reads the file and inserts as a blob
752 * (we don't use this though...)
754 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
755 /* MySQL doesn't support prepared statements (yet), so just
756 pack up the query for reference. We'll manually replace
758 return array( 'query' => $sql, 'func' => $func );
761 function freePrepared( $prepared ) {
762 /* No-op by default */
766 * Execute a prepared query with the various arguments
767 * @param $prepared String: the prepared sql
768 * @param $args Mixed: Either an array here, or put scalars as varargs
770 function execute( $prepared, $args = null ) {
771 if ( !is_array( $args ) ) {
773 $args = func_get_args();
774 array_shift( $args );
777 $sql = $this->fillPrepared( $prepared['query'], $args );
779 return $this->query( $sql, $prepared['func'] );
783 * Prepare & execute an SQL statement, quoting and inserting arguments
784 * in the appropriate places.
785 * @param $query String
788 function safeQuery( $query, $args = null ) {
789 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
791 if ( !is_array( $args ) ) {
793 $args = func_get_args();
794 array_shift( $args );
797 $retval = $this->execute( $prepared, $args );
798 $this->freePrepared( $prepared );
804 * For faking prepared SQL statements on DBs that don't support
806 * @param $preparedQuery String: a 'preparable' SQL statement
807 * @param $args Array of arguments to fill it with
808 * @return string executable SQL
810 function fillPrepared( $preparedQuery, $args ) {
812 $this->preparedArgs
=& $args;
814 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
815 array( &$this, 'fillPreparedArg' ), $preparedQuery );
819 * preg_callback func for fillPrepared()
820 * The arguments should be in $this->preparedArgs and must not be touched
821 * while we're doing this.
823 * @param $matches Array
827 function fillPreparedArg( $matches ) {
828 switch( $matches[1] ) {
829 case '\\?': return '?';
830 case '\\!': return '!';
831 case '\\&': return '&';
834 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
836 switch( $matches[1] ) {
837 case '?': return $this->addQuotes( $arg );
838 case '!': return $arg;
840 # return $this->addQuotes( file_get_contents( $arg ) );
841 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
843 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
848 * Free a result object
849 * @param $res Mixed: A SQL result
851 function freeResult( $res ) {
852 # Stub. Might not really need to be overridden, since results should
853 # be freed by PHP when the variable goes out of scope anyway.
857 * Simple UPDATE wrapper
858 * Usually aborts on failure
859 * If errors are explicitly ignored, returns success
861 * This function exists for historical reasons, DatabaseBase::update() has a more standard
862 * calling convention and feature set
864 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
865 $table = $this->tableName( $table );
866 $sql = "UPDATE $table SET $var = '" .
867 $this->strencode( $value ) . "' WHERE ($cond)";
869 return (bool)$this->query( $sql, $fname );
873 * Simple SELECT wrapper, returns a single field, input must be encoded
874 * Usually aborts on failure
875 * If errors are explicitly ignored, returns FALSE on failure
877 function selectField( $table, $var, $cond = '', $fname = 'DatabaseBase::selectField', $options = array() ) {
878 if ( !is_array( $options ) ) {
879 $options = array( $options );
882 $options['LIMIT'] = 1;
884 $res = $this->select( $table, $var, $cond, $fname, $options );
886 if ( $res === false ||
!$this->numRows( $res ) ) {
890 $row = $this->fetchRow( $res );
892 if ( $row !== false ) {
893 return reset( $row );
900 * Returns an optional USE INDEX clause to go after the table, and a
901 * string to go at the end of the query
905 * @param $options Array: associative array of options to be turned into
906 * an SQL query, valid keys are listed in the function.
909 function makeSelectOptions( $options ) {
910 $preLimitTail = $postLimitTail = '';
913 $noKeyOptions = array();
915 foreach ( $options as $key => $option ) {
916 if ( is_numeric( $key ) ) {
917 $noKeyOptions[$option] = true;
921 if ( isset( $options['GROUP BY'] ) ) {
922 $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
925 if ( isset( $options['HAVING'] ) ) {
926 $preLimitTail .= " HAVING {$options['HAVING']}";
929 if ( isset( $options['ORDER BY'] ) ) {
930 $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
933 // if (isset($options['LIMIT'])) {
934 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
935 // isset($options['OFFSET']) ? $options['OFFSET']
939 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) {
940 $postLimitTail .= ' FOR UPDATE';
943 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) {
944 $postLimitTail .= ' LOCK IN SHARE MODE';
947 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) {
948 $startOpts .= 'DISTINCT';
951 # Various MySQL extensions
952 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) {
953 $startOpts .= ' /*! STRAIGHT_JOIN */';
956 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) {
957 $startOpts .= ' HIGH_PRIORITY';
960 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) {
961 $startOpts .= ' SQL_BIG_RESULT';
964 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) {
965 $startOpts .= ' SQL_BUFFER_RESULT';
968 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) {
969 $startOpts .= ' SQL_SMALL_RESULT';
972 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) {
973 $startOpts .= ' SQL_CALC_FOUND_ROWS';
976 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) {
977 $startOpts .= ' SQL_CACHE';
980 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) {
981 $startOpts .= ' SQL_NO_CACHE';
984 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
985 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
990 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
996 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
997 * @param $vars Mixed: Array or string, field name(s) to be retrieved
998 * @param $conds Mixed: Array or string, condition(s) for WHERE
999 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1000 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1001 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1002 * @param $join_conds Array: Associative array of table join conditions (optional)
1003 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1004 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
1006 function select( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1007 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
1009 return $this->query( $sql, $fname );
1015 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
1016 * @param $vars Mixed: Array or string, field name(s) to be retrieved
1017 * @param $conds Mixed: Array or string, condition(s) for WHERE
1018 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1019 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1020 * see DatabaseBase::makeSelectOptions code for list of supported stuff
1021 * @param $join_conds Array: Associative array of table join conditions (optional)
1022 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1023 * @return string, the SQL text
1025 function selectSQLText( $table, $vars, $conds = '', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
1026 if ( is_array( $vars ) ) {
1027 $vars = implode( ',', $vars );
1030 if ( !is_array( $options ) ) {
1031 $options = array( $options );
1034 if ( is_array( $table ) ) {
1035 if ( !empty( $join_conds ) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) ) {
1036 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1038 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1040 } elseif ( $table != '' ) {
1041 if ( $table { 0 } == ' ' ) {
1042 $from = ' FROM ' . $table;
1044 $from = ' FROM ' . $this->tableName( $table );
1050 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1052 if ( !empty( $conds ) ) {
1053 if ( is_array( $conds ) ) {
1054 $conds = $this->makeList( $conds, LIST_AND
);
1056 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1058 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1061 if ( isset( $options['LIMIT'] ) )
1062 $sql = $this->limitResult( $sql, $options['LIMIT'],
1063 isset( $options['OFFSET'] ) ?
$options['OFFSET'] : false );
1064 $sql = "$sql $postLimitTail";
1066 if ( isset( $options['EXPLAIN'] ) ) {
1067 $sql = 'EXPLAIN ' . $sql;
1074 * Single row SELECT wrapper
1075 * Aborts or returns FALSE on error
1077 * @param $table String: table name
1078 * @param $vars String: the selected variables
1079 * @param $conds Array: a condition map, terms are ANDed together.
1080 * Items with numeric keys are taken to be literal conditions
1081 * Takes an array of selected variables, and a condition map, which is ANDed
1082 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1083 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1084 * $obj- >page_id is the ID of the Astronomy article
1085 * @param $fname String: Calling function name
1086 * @param $options Array
1087 * @param $join_conds Array
1089 * @todo migrate documentation to phpdocumentor format
1091 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
1092 $options['LIMIT'] = 1;
1093 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1095 if ( $res === false ) {
1099 if ( !$this->numRows( $res ) ) {
1103 $obj = $this->fetchObject( $res );
1109 * Estimate rows in dataset
1110 * Returns estimated count - not necessarily an accurate estimate across different databases,
1112 * Takes same arguments as DatabaseBase::select()
1114 * @param $table String: table name
1115 * @param $vars Array: unused
1116 * @param $conds Array: filters on the table
1117 * @param $fname String: function name for profiling
1118 * @param $options Array: options for select
1119 * @return Integer: row count
1121 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
1123 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
1126 $row = $this->fetchRow( $res );
1127 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
1134 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1135 * It's only slightly flawed. Don't use for anything important.
1137 * @param $sql String: A SQL Query
1139 static function generalizeSQL( $sql ) {
1140 # This does the same as the regexp below would do, but in such a way
1141 # as to avoid crashing php on some large strings.
1142 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1144 $sql = str_replace ( "\\\\", '', $sql );
1145 $sql = str_replace ( "\\'", '', $sql );
1146 $sql = str_replace ( "\\\"", '', $sql );
1147 $sql = preg_replace ( "/'.*'/s", "'X'", $sql );
1148 $sql = preg_replace ( '/".*"/s', "'X'", $sql );
1150 # All newlines, tabs, etc replaced by single space
1151 $sql = preg_replace ( '/\s+/', ' ', $sql );
1154 $sql = preg_replace ( '/-?[0-9]+/s', 'N', $sql );
1160 * Determines whether a field exists in a table
1162 * @param $table String: table name
1163 * @param $field String: filed to check on that table
1164 * @param $fname String: calling function name (optional)
1165 * @return Boolean: whether $table has filed $field
1167 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1168 $info = $this->fieldInfo( $table, $field );
1174 * Determines whether an index exists
1175 * Usually aborts on failure
1176 * If errors are explicitly ignored, returns NULL on failure
1178 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1179 $info = $this->indexInfo( $table, $index, $fname );
1180 if ( is_null( $info ) ) {
1183 return $info !== false;
1188 * Query whether a given table exists
1190 function tableExists( $table ) {
1191 $table = $this->tableName( $table );
1192 $old = $this->ignoreErrors( true );
1193 $res = $this->query( "SELECT 1 FROM $table LIMIT 1", __METHOD__
);
1194 $this->ignoreErrors( $old );
1200 * mysql_field_type() wrapper
1202 function fieldType( $res, $index ) {
1203 if ( $res instanceof ResultWrapper
) {
1204 $res = $res->result
;
1207 return mysql_field_type( $res, $index );
1211 * Determines if a given index is unique
1213 function indexUnique( $table, $index ) {
1214 $indexInfo = $this->indexInfo( $table, $index );
1216 if ( !$indexInfo ) {
1220 return !$indexInfo[0]->Non_unique
;
1224 * INSERT wrapper, inserts an array into a table
1226 * $a may be a single associative array, or an array of these with numeric keys, for
1229 * Usually aborts on failure
1230 * If errors are explicitly ignored, returns success
1232 * @param $table String: table name (prefix auto-added)
1233 * @param $a Array: Array of rows to insert
1234 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1235 * @param $options Mixed: Associative array of options
1239 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1240 # No rows to insert, easy just return now
1241 if ( !count( $a ) ) {
1245 $table = $this->tableName( $table );
1247 if ( !is_array( $options ) ) {
1248 $options = array( $options );
1251 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1253 $keys = array_keys( $a[0] );
1256 $keys = array_keys( $a );
1259 $sql = 'INSERT ' . implode( ' ', $options ) .
1260 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1264 foreach ( $a as $row ) {
1270 $sql .= '(' . $this->makeList( $row ) . ')';
1273 $sql .= '(' . $this->makeList( $a ) . ')';
1276 return (bool)$this->query( $sql, $fname );
1280 * Make UPDATE options for the DatabaseBase::update function
1283 * @param $options Array: The options passed to DatabaseBase::update
1286 function makeUpdateOptions( $options ) {
1287 if ( !is_array( $options ) ) {
1288 $options = array( $options );
1293 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1294 $opts[] = $this->lowPriorityOption();
1297 if ( in_array( 'IGNORE', $options ) ) {
1301 return implode( ' ', $opts );
1305 * UPDATE wrapper, takes a condition array and a SET array
1307 * @param $table String: The table to UPDATE
1308 * @param $values Array: An array of values to SET
1309 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1310 * @param $fname String: The Class::Function calling this function
1312 * @param $options Array: An array of UPDATE options, can be one or
1313 * more of IGNORE, LOW_PRIORITY
1316 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1317 $table = $this->tableName( $table );
1318 $opts = $this->makeUpdateOptions( $options );
1319 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1321 if ( $conds != '*' ) {
1322 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1325 return $this->query( $sql, $fname );
1329 * Makes an encoded list of strings from an array
1331 * LIST_COMMA - comma separated, no field names
1332 * LIST_AND - ANDed WHERE clause (without the WHERE)
1333 * LIST_OR - ORed WHERE clause (without the WHERE)
1334 * LIST_SET - comma separated with field names, like a SET clause
1335 * LIST_NAMES - comma separated field names
1337 function makeList( $a, $mode = LIST_COMMA
) {
1338 if ( !is_array( $a ) ) {
1339 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1345 foreach ( $a as $field => $value ) {
1347 if ( $mode == LIST_AND
) {
1349 } elseif ( $mode == LIST_OR
) {
1358 if ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1359 $list .= "($value)";
1360 } elseif ( ( $mode == LIST_SET
) && is_numeric( $field ) ) {
1362 } elseif ( ( $mode == LIST_AND ||
$mode == LIST_OR
) && is_array( $value ) ) {
1363 if ( count( $value ) == 0 ) {
1364 throw new MWException( __METHOD__
. ': empty input' );
1365 } elseif ( count( $value ) == 1 ) {
1366 // Special-case single values, as IN isn't terribly efficient
1367 // Don't necessarily assume the single key is 0; we don't
1368 // enforce linear numeric ordering on other arrays here.
1369 $value = array_values( $value );
1370 $list .= $field . " = " . $this->addQuotes( $value[0] );
1372 $list .= $field . " IN (" . $this->makeList( $value ) . ") ";
1374 } elseif ( $value === null ) {
1375 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1376 $list .= "$field IS ";
1377 } elseif ( $mode == LIST_SET
) {
1378 $list .= "$field = ";
1382 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1383 $list .= "$field = ";
1385 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1393 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1394 * The keys on each level may be either integers or strings.
1396 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1397 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1398 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1399 * @return Mixed: string SQL fragment, or false if no items in array.
1401 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1404 foreach ( $data as $base => $sub ) {
1405 if ( count( $sub ) ) {
1406 $conds[] = $this->makeList(
1407 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1413 return $this->makeList( $conds, LIST_OR
);
1415 // Nothing to search for...
1421 * Bitwise operations
1424 function bitNot( $field ) {
1428 function bitAnd( $fieldLeft, $fieldRight ) {
1429 return "($fieldLeft & $fieldRight)";
1432 function bitOr( $fieldLeft, $fieldRight ) {
1433 return "($fieldLeft | $fieldRight)";
1437 * Change the current database
1439 * @todo Explain what exactly will fail if this is not overridden.
1440 * @return bool Success or failure
1442 function selectDB( $db ) {
1443 # Stub. Shouldn't cause serious problems if it's not overridden, but
1444 # if your database engine supports a concept similar to MySQL's
1445 # databases you may as well.
1450 * Get the current DB name
1452 function getDBname() {
1453 return $this->mDBname
;
1457 * Get the server hostname or IP address
1459 function getServer() {
1460 return $this->mServer
;
1464 * Format a table name ready for use in constructing an SQL query
1466 * This does two important things: it quotes the table names to clean them up,
1467 * and it adds a table prefix if only given a table name with no quotes.
1469 * All functions of this object which require a table name call this function
1470 * themselves. Pass the canonical name to such functions. This is only needed
1471 * when calling query() directly.
1473 * @param $name String: database table name
1474 * @return String: full database name
1476 function tableName( $name ) {
1477 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1478 # Skip the entire process when we have a string quoted on both ends.
1479 # Note that we check the end so that we will still quote any use of
1480 # use of `database`.table. But won't break things if someone wants
1481 # to query a database table with a dot in the name.
1482 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1486 # Lets test for any bits of text that should never show up in a table
1487 # name. Basically anything like JOIN or ON which are actually part of
1488 # SQL queries, but may end up inside of the table value to combine
1489 # sql. Such as how the API is doing.
1490 # Note that we use a whitespace test rather than a \b test to avoid
1491 # any remote case where a word like on may be inside of a table name
1492 # surrounded by symbols which may be considered word breaks.
1493 if ( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1497 # Split database and table into proper variables.
1498 # We reverse the explode so that database.table and table both output
1499 # the correct table.
1500 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1501 if ( isset( $dbDetails[1] ) ) {
1502 @list
( $table, $database ) = $dbDetails;
1504 @list
( $table ) = $dbDetails;
1506 $prefix = $this->mTablePrefix
; # Default prefix
1508 # A database name has been specified in input. Quote the table name
1509 # because we don't want any prefixes added.
1510 if ( isset( $database ) ) {
1511 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1514 # Note that we use the long format because php will complain in in_array if
1515 # the input is not an array, and will complain in is_array if it is not set.
1516 if ( !isset( $database ) # Don't use shared database if pre selected.
1517 && isset( $wgSharedDB ) # We have a shared database
1518 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1519 && isset( $wgSharedTables )
1520 && is_array( $wgSharedTables )
1521 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1522 $database = $wgSharedDB;
1523 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1526 # Quote the $database and $table and apply the prefix if not quoted.
1527 if ( isset( $database ) ) {
1528 $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1530 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1532 # Merge our database and table into our final table name.
1533 $tableName = ( isset( $database ) ?
"{$database}.{$table}" : "{$table}" );
1539 * Fetch a number of table names into an array
1540 * This is handy when you need to construct SQL for joins
1543 * extract($dbr->tableNames('user','watchlist'));
1544 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1545 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1547 public function tableNames() {
1548 $inArray = func_get_args();
1551 foreach ( $inArray as $name ) {
1552 $retVal[$name] = $this->tableName( $name );
1559 * Fetch a number of table names into an zero-indexed numerical array
1560 * This is handy when you need to construct SQL for joins
1563 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1564 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1565 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1567 public function tableNamesN() {
1568 $inArray = func_get_args();
1571 foreach ( $inArray as $name ) {
1572 $retVal[] = $this->tableName( $name );
1581 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1584 $use_index_safe = is_array( $use_index ) ?
$use_index : array();
1585 $join_conds_safe = is_array( $join_conds ) ?
$join_conds : array();
1587 foreach ( $tables as $table ) {
1588 // Is there a JOIN and INDEX clause for this table?
1589 if ( isset( $join_conds_safe[$table] ) && isset( $use_index_safe[$table] ) ) {
1590 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1591 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1592 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
);
1595 $tableClause .= ' ON (' . $on . ')';
1598 $retJOIN[] = $tableClause;
1599 // Is there an INDEX clause?
1600 } else if ( isset( $use_index_safe[$table] ) ) {
1601 $tableClause = $this->tableName( $table );
1602 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1603 $ret[] = $tableClause;
1604 // Is there a JOIN clause?
1605 } else if ( isset( $join_conds_safe[$table] ) ) {
1606 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1607 $on = $this->makeList( (array)$join_conds_safe[$table][1], LIST_AND
);
1610 $tableClause .= ' ON (' . $on . ')';
1613 $retJOIN[] = $tableClause;
1615 $tableClause = $this->tableName( $table );
1616 $ret[] = $tableClause;
1620 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1621 $straightJoins = !empty( $ret ) ?
implode( ',', $ret ) : "";
1622 $otherJoins = !empty( $retJOIN ) ?
implode( ' ', $retJOIN ) : "";
1624 // Compile our final table clause
1625 return implode( ' ', array( $straightJoins, $otherJoins ) );
1629 * Get the name of an index in a given table
1631 function indexName( $index ) {
1632 // Backwards-compatibility hack
1634 'ar_usertext_timestamp' => 'usertext_timestamp',
1635 'un_user_id' => 'user_id',
1636 'un_user_ip' => 'user_ip',
1639 if ( isset( $renamed[$index] ) ) {
1640 return $renamed[$index];
1647 * If it's a string, adds quotes and backslashes
1648 * Otherwise returns as-is
1650 function addQuotes( $s ) {
1651 if ( $s === null ) {
1654 # This will also quote numeric values. This should be harmless,
1655 # and protects against weird problems that occur when they really
1656 # _are_ strings such as article titles and string->number->string
1657 # conversion is not 1:1.
1658 return "'" . $this->strencode( $s ) . "'";
1663 * Escape string for safe LIKE usage.
1664 * WARNING: you should almost never use this function directly,
1665 * instead use buildLike() that escapes everything automatically
1666 * Deprecated in 1.17, warnings in 1.17, removed in ???
1668 public function escapeLike( $s ) {
1669 wfDeprecated( __METHOD__
);
1670 return $this->escapeLikeInternal( $s );
1673 protected function escapeLikeInternal( $s ) {
1674 $s = str_replace( '\\', '\\\\', $s );
1675 $s = $this->strencode( $s );
1676 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1682 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1683 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1684 * Alternatively, the function could be provided with an array of aforementioned parameters.
1686 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1687 * for subpages of 'My page title'.
1688 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1691 * @return String: fully built LIKE statement
1693 function buildLike() {
1694 $params = func_get_args();
1696 if ( count( $params ) > 0 && is_array( $params[0] ) ) {
1697 $params = $params[0];
1702 foreach ( $params as $value ) {
1703 if ( $value instanceof LikeMatch
) {
1704 $s .= $value->toString();
1706 $s .= $this->escapeLikeInternal( $value );
1710 return " LIKE '" . $s . "' ";
1714 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1716 function anyChar() {
1717 return new LikeMatch( '_' );
1721 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1723 function anyString() {
1724 return new LikeMatch( '%' );
1728 * Returns an appropriately quoted sequence value for inserting a new row.
1729 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1730 * subclass will return an integer, and save the value for insertId()
1732 function nextSequenceValue( $seqName ) {
1737 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1738 * is only needed because a) MySQL must be as efficient as possible due to
1739 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1740 * which index to pick. Anyway, other databases might have different
1741 * indexes on a given table. So don't bother overriding this unless you're
1744 function useIndexClause( $index ) {
1749 * REPLACE query wrapper
1750 * PostgreSQL simulates this with a DELETE followed by INSERT
1751 * $row is the row to insert, an associative array
1752 * $uniqueIndexes is an array of indexes. Each element may be either a
1753 * field name or an array of field names
1755 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1756 * However if you do this, you run the risk of encountering errors which wouldn't have
1759 * @param $table String: The table to replace the row(s) in.
1760 * @param $uniqueIndexes Array: An associative array of indexes
1761 * @param $rows Array: Array of rows to replace
1762 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1764 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1765 $table = $this->tableName( $table );
1768 if ( !is_array( reset( $rows ) ) ) {
1769 $rows = array( $rows );
1772 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) . ') VALUES ';
1775 foreach ( $rows as $row ) {
1782 $sql .= '(' . $this->makeList( $row ) . ')';
1785 return $this->query( $sql, $fname );
1789 * DELETE where the condition is a join
1790 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1792 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1793 * join condition matches, set $conds='*'
1795 * DO NOT put the join condition in $conds
1797 * @param $delTable String: The table to delete from.
1798 * @param $joinTable String: The other table.
1799 * @param $delVar String: The variable to join on, in the first table.
1800 * @param $joinVar String: The variable to join on, in the second table.
1801 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1802 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1804 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1806 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1809 $delTable = $this->tableName( $delTable );
1810 $joinTable = $this->tableName( $joinTable );
1811 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1813 if ( $conds != '*' ) {
1814 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1817 return $this->query( $sql, $fname );
1821 * Returns the size of a text field, or -1 for "unlimited"
1823 function textFieldSize( $table, $field ) {
1824 $table = $this->tableName( $table );
1825 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1826 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1827 $row = $this->fetchObject( $res );
1831 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1841 * A string to insert into queries to show that they're low-priority, like
1842 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1843 * string and nothing bad should happen.
1845 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1847 function lowPriorityOption() {
1852 * DELETE query wrapper
1854 * Use $conds == "*" to delete all rows
1856 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1858 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1861 $table = $this->tableName( $table );
1862 $sql = "DELETE FROM $table";
1864 if ( $conds != '*' ) {
1865 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1868 return $this->query( $sql, $fname );
1872 * INSERT SELECT wrapper
1873 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1874 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1875 * $conds may be "*" to copy the whole table
1876 * srcTable may be an array of tables.
1878 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1879 $insertOptions = array(), $selectOptions = array() )
1881 $destTable = $this->tableName( $destTable );
1883 if ( is_array( $insertOptions ) ) {
1884 $insertOptions = implode( ' ', $insertOptions );
1887 if ( !is_array( $selectOptions ) ) {
1888 $selectOptions = array( $selectOptions );
1891 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1893 if ( is_array( $srcTable ) ) {
1894 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1896 $srcTable = $this->tableName( $srcTable );
1899 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1900 " SELECT $startOpts " . implode( ',', $varMap ) .
1901 " FROM $srcTable $useIndex ";
1903 if ( $conds != '*' ) {
1904 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1907 $sql .= " $tailOpts";
1909 return $this->query( $sql, $fname );
1913 * Construct a LIMIT query with optional offset. This is used for query
1914 * pages. The SQL should be adjusted so that only the first $limit rows
1915 * are returned. If $offset is provided as well, then the first $offset
1916 * rows should be discarded, and the next $limit rows should be returned.
1917 * If the result of the query is not ordered, then the rows to be returned
1918 * are theoretically arbitrary.
1920 * $sql is expected to be a SELECT, if that makes a difference. For
1921 * UPDATE, limitResultForUpdate should be used.
1923 * The version provided by default works in MySQL and SQLite. It will very
1924 * likely need to be overridden for most other DBMSes.
1926 * @param $sql String: SQL query we will append the limit too
1927 * @param $limit Integer: the SQL limit
1928 * @param $offset Integer the SQL offset (default false)
1930 function limitResult( $sql, $limit, $offset = false ) {
1931 if ( !is_numeric( $limit ) ) {
1932 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1935 return "$sql LIMIT "
1936 . ( ( is_numeric( $offset ) && $offset != 0 ) ?
"{$offset}," : "" )
1940 function limitResultForUpdate( $sql, $num ) {
1941 return $this->limitResult( $sql, $num, 0 );
1945 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1946 * within the UNION construct.
1949 function unionSupportsOrderAndLimit() {
1950 return true; // True for almost every DB supported
1954 * Construct a UNION query
1955 * This is used for providing overload point for other DB abstractions
1956 * not compatible with the MySQL syntax.
1957 * @param $sqls Array: SQL statements to combine
1958 * @param $all Boolean: use UNION ALL
1959 * @return String: SQL fragment
1961 function unionQueries( $sqls, $all ) {
1962 $glue = $all ?
') UNION ALL (' : ') UNION (';
1963 return '(' . implode( $glue, $sqls ) . ')';
1967 * Returns an SQL expression for a simple conditional. This doesn't need
1968 * to be overridden unless CASE isn't supported in your DBMS.
1970 * @param $cond String: SQL expression which will result in a boolean value
1971 * @param $trueVal String: SQL expression to return if true
1972 * @param $falseVal String: SQL expression to return if false
1973 * @return String: SQL fragment
1975 function conditional( $cond, $trueVal, $falseVal ) {
1976 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1980 * Returns a comand for str_replace function in SQL query.
1981 * Uses REPLACE() in MySQL
1983 * @param $orig String: column to modify
1984 * @param $old String: column to seek
1985 * @param $new String: column to replace with
1987 function strreplace( $orig, $old, $new ) {
1988 return "REPLACE({$orig}, {$old}, {$new})";
1992 * Convert a field to an unix timestamp
1994 * @param $field String: field name
1995 * @return String: SQL statement
1997 public function unixTimestamp( $field ) {
1998 return "EXTRACT(epoch FROM $field)";
2002 * Determines if the last failure was due to a deadlock
2005 function wasDeadlock() {
2010 * Determines if the last query error was something that should be dealt
2011 * with by pinging the connection and reissuing the query.
2014 function wasErrorReissuable() {
2019 * Determines if the last failure was due to the database being read-only.
2022 function wasReadOnlyError() {
2027 * Perform a deadlock-prone transaction.
2029 * This function invokes a callback function to perform a set of write
2030 * queries. If a deadlock occurs during the processing, the transaction
2031 * will be rolled back and the callback function will be called again.
2034 * $dbw->deadlockLoop( callback, ... );
2036 * Extra arguments are passed through to the specified callback function.
2038 * Returns whatever the callback function returned on its successful,
2039 * iteration, or false on error, for example if the retry limit was
2042 function deadlockLoop() {
2043 $myFname = 'DatabaseBase::deadlockLoop';
2046 $args = func_get_args();
2047 $function = array_shift( $args );
2048 $oldIgnore = $this->ignoreErrors( true );
2049 $tries = DEADLOCK_TRIES
;
2051 if ( is_array( $function ) ) {
2052 $fname = $function[0];
2058 $retVal = call_user_func_array( $function, $args );
2059 $error = $this->lastError();
2060 $errno = $this->lastErrno();
2061 $sql = $this->lastQuery();
2064 if ( $this->wasDeadlock() ) {
2066 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
2068 $this->reportQueryError( $error, $errno, $sql, $fname );
2071 } while ( $this->wasDeadlock() && --$tries > 0 );
2073 $this->ignoreErrors( $oldIgnore );
2075 if ( $tries <= 0 ) {
2076 $this->rollback( $myFname );
2077 $this->reportQueryError( $error, $errno, $sql, $fname );
2080 $this->commit( $myFname );
2086 * Do a SELECT MASTER_POS_WAIT()
2088 * @param $pos MySQLMasterPos object
2089 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
2091 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
2092 $fname = 'DatabaseBase::masterPosWait';
2093 wfProfileIn( $fname );
2095 # Commit any open transactions
2096 if ( $this->mTrxLevel
) {
2100 if ( !is_null( $this->mFakeSlaveLag
) ) {
2101 $wait = intval( ( $pos->pos
- microtime( true ) +
$this->mFakeSlaveLag
) * 1e6
);
2103 if ( $wait > $timeout * 1e6
) {
2104 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
2105 wfProfileOut( $fname );
2107 } elseif ( $wait > 0 ) {
2108 wfDebug( "Fake slave waiting $wait us\n" );
2110 wfProfileOut( $fname );
2113 wfDebug( "Fake slave up to date ($wait us)\n" );
2114 wfProfileOut( $fname );
2119 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2120 $encFile = $this->addQuotes( $pos->file
);
2121 $encPos = intval( $pos->pos
);
2122 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2123 $res = $this->doQuery( $sql );
2125 if ( $res && $row = $this->fetchRow( $res ) ) {
2126 wfProfileOut( $fname );
2129 wfProfileOut( $fname );
2135 * Get the position of the master from SHOW SLAVE STATUS
2137 function getSlavePos() {
2138 if ( !is_null( $this->mFakeSlaveLag
) ) {
2139 $pos = new MySQLMasterPos( 'fake', microtime( true ) - $this->mFakeSlaveLag
);
2140 wfDebug( __METHOD__
. ": fake slave pos = $pos\n" );
2144 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2145 $row = $this->fetchObject( $res );
2148 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2149 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2156 * Get the position of the master from SHOW MASTER STATUS
2158 function getMasterPos() {
2159 if ( $this->mFakeMaster
) {
2160 return new MySQLMasterPos( 'fake', microtime( true ) );
2163 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2164 $row = $this->fetchObject( $res );
2167 return new MySQLMasterPos( $row->File
, $row->Position
);
2174 * Begin a transaction, committing any previously open transaction
2176 function begin( $fname = 'DatabaseBase::begin' ) {
2177 $this->query( 'BEGIN', $fname );
2178 $this->mTrxLevel
= 1;
2184 function commit( $fname = 'DatabaseBase::commit' ) {
2185 if ( $this->mTrxLevel
) {
2186 $this->query( 'COMMIT', $fname );
2187 $this->mTrxLevel
= 0;
2192 * Rollback a transaction.
2193 * No-op on non-transactional databases.
2195 function rollback( $fname = 'DatabaseBase::rollback' ) {
2196 if ( $this->mTrxLevel
) {
2197 $this->query( 'ROLLBACK', $fname, true );
2198 $this->mTrxLevel
= 0;
2203 * Begin a transaction, committing any previously open transaction
2204 * @deprecated use begin()
2206 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2207 wfDeprecated( __METHOD__
);
2212 * Commit transaction, if one is open
2213 * @deprecated use commit()
2215 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2216 wfDeprecated( __METHOD__
);
2221 * Creates a new table with structure copied from existing table
2222 * Note that unlike most database abstraction functions, this function does not
2223 * automatically append database prefix, because it works at a lower
2224 * abstraction level.
2226 * @param $oldName String: name of table whose structure should be copied
2227 * @param $newName String: name of table to be created
2228 * @param $temporary Boolean: whether the new table should be temporary
2229 * @param $fname String: calling function name
2230 * @return Boolean: true if operation was successful
2232 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2233 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2237 * Return MW-style timestamp used for MySQL schema
2239 function timestamp( $ts = 0 ) {
2240 return wfTimestamp( TS_MW
, $ts );
2244 * Local database timestamp format or null
2246 function timestampOrNull( $ts = null ) {
2247 if ( is_null( $ts ) ) {
2250 return $this->timestamp( $ts );
2257 function resultObject( $result ) {
2258 if ( empty( $result ) ) {
2260 } elseif ( $result instanceof ResultWrapper
) {
2262 } elseif ( $result === true ) {
2263 // Successful write query
2266 return new ResultWrapper( $this, $result );
2271 * Return aggregated value alias
2273 function aggregateValue ( $valuedata, $valuename = 'value' ) {
2278 * Ping the server and try to reconnect if it there is no connection
2280 * @return bool Success or failure
2283 # Stub. Not essential to override.
2289 * Currently supported only by MySQL
2290 * @return Database replication lag in seconds
2293 return intval( $this->mFakeSlaveLag
);
2297 * Get status information from SHOW STATUS in an associative array
2299 function getStatus( $which = "%" ) {
2300 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2303 foreach ( $res as $row ) {
2304 $status[$row->Variable_name
] = $row->Value
;
2311 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2313 function maxListLen() {
2317 function encodeBlob( $b ) {
2321 function decodeBlob( $b ) {
2326 * Override database's default connection timeout. May be useful for very
2327 * long batch queries such as full-wiki dumps, where a single query reads
2328 * out over hours or days. May or may not be necessary for non-MySQL
2329 * databases. For most purposes, leaving it as a no-op should be fine.
2331 * @param $timeout Integer in seconds
2333 public function setTimeout( $timeout ) {}
2336 * Read and execute SQL commands from a file.
2337 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2338 * @param $filename String: File name to open
2339 * @param $lineCallback Callback: Optional function called before reading each line
2340 * @param $resultCallback Callback: Optional function called for each MySQL result
2341 * @param $fname String: Calling function name or false if name should be generated dynamically
2344 function sourceFile( $filename, $lineCallback = false, $resultCallback = false, $fname = false ) {
2345 $fp = fopen( $filename, 'r' );
2347 if ( false === $fp ) {
2348 if ( !defined( "MEDIAWIKI_INSTALL" ) )
2349 throw new MWException( "Could not open \"{$filename}\".\n" );
2351 return "Could not open \"{$filename}\".\n";
2355 $fname = __METHOD__
. "( $filename )";
2359 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback, $fname );
2361 catch ( MWException
$e ) {
2362 if ( defined( "MEDIAWIKI_INSTALL" ) ) {
2363 $error = $e->getMessage();
2376 * Get the full path of a patch file. Originally based on archive()
2377 * from updaters.inc. Keep in mind this always returns a patch, as
2378 * it fails back to MySQL if no DB-specific patch can be found
2380 * @param $patch String The name of the patch, like patch-something.sql
2381 * @return String Full path to patch file
2383 public function patchPath( $patch ) {
2386 $dbType = $this->getType();
2387 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
2388 return "$IP/maintenance/$dbType/archives/$patch";
2390 return "$IP/maintenance/archives/$patch";
2395 * Read and execute commands from an open file handle
2396 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2397 * @param $fp String: File handle
2398 * @param $lineCallback Callback: Optional function called before reading each line
2399 * @param $resultCallback Callback: Optional function called for each MySQL result
2400 * @param $fname String: Calling function name
2402 function sourceStream( $fp, $lineCallback = false, $resultCallback = false, $fname = 'DatabaseBase::sourceStream' ) {
2405 $dollarquote = false;
2407 while ( ! feof( $fp ) ) {
2408 if ( $lineCallback ) {
2409 call_user_func( $lineCallback );
2412 $line = trim( fgets( $fp, 1024 ) );
2413 $sl = strlen( $line ) - 1;
2419 if ( '-' == $line { 0 } && '-' == $line { 1 } ) {
2423 # # Allow dollar quoting for function declarations
2424 if ( substr( $line, 0, 4 ) == '$mw$' ) {
2425 if ( $dollarquote ) {
2426 $dollarquote = false;
2430 $dollarquote = true;
2433 else if ( !$dollarquote ) {
2434 if ( ';' == $line { $sl } && ( $sl < 2 ||
';' != $line { $sl - 1 } ) ) {
2436 $line = substr( $line, 0, $sl );
2447 $cmd = str_replace( ';;', ";", $cmd );
2448 $cmd = $this->replaceVars( $cmd );
2449 $res = $this->query( $cmd, $fname );
2451 if ( $resultCallback ) {
2452 call_user_func( $resultCallback, $res, $this );
2455 if ( false === $res ) {
2456 $err = $this->lastError();
2457 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2469 * Replace variables in sourced SQL
2471 protected function replaceVars( $ins ) {
2473 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2474 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2475 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2478 // Ordinary variables
2479 foreach ( $varnames as $var ) {
2480 if ( isset( $GLOBALS[$var] ) ) {
2481 $val = $this->addQuotes( $GLOBALS[$var] ); // FIXME: safety check?
2482 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2483 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2484 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2489 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2490 array( $this, 'tableNameCallback' ), $ins );
2493 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2494 array( $this, 'indexNameCallback' ), $ins );
2500 * Table name callback
2503 protected function tableNameCallback( $matches ) {
2504 return $this->tableName( $matches[1] );
2508 * Index name callback
2510 protected function indexNameCallback( $matches ) {
2511 return $this->indexName( $matches[1] );
2515 * Build a concatenation list to feed into a SQL query
2516 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2519 function buildConcat( $stringList ) {
2520 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2524 * Acquire a named lock
2526 * Abstracted from Filestore::lock() so child classes can implement for
2529 * @param $lockName String: name of lock to aquire
2530 * @param $method String: name of method calling us
2531 * @param $timeout Integer: timeout
2534 public function lock( $lockName, $method, $timeout = 5 ) {
2541 * @param $lockName String: Name of lock to release
2542 * @param $method String: Name of method calling us
2544 * @return Returns 1 if the lock was released, 0 if the lock was not established
2545 * by this thread (in which case the lock is not released), and NULL if the named
2546 * lock did not exist
2548 public function unlock( $lockName, $method ) {
2553 * Lock specific tables
2555 * @param $read Array of tables to lock for read access
2556 * @param $write Array of tables to lock for write access
2557 * @param $method String name of caller
2558 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2560 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2565 * Unlock specific tables
2567 * @param $method String the caller
2569 public function unlockTables( $method ) {
2574 * Get search engine class. All subclasses of this need to implement this
2575 * if they wish to use searching.
2579 public function getSearchEngine() {
2580 return 'SearchEngineDummy';
2584 * Allow or deny "big selects" for this session only. This is done by setting
2585 * the sql_big_selects session variable.
2587 * This is a MySQL-specific feature.
2589 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2591 public function setBigSelects( $value = true ) {
2596 /******************************************************************************
2598 *****************************************************************************/
2607 function __construct( $data ) {
2608 $this->mData
= $data;
2616 return $this->mData
;
2624 * This allows us to distinguish a blob from a normal string and an array of strings
2629 function __construct( $data ) {
2630 $this->mData
= $data;
2634 return $this->mData
;
2639 * Base for all database-specific classes representing information about database fields
2650 * Name of table this field belongs to
2653 function tableName();
2662 * Whether this field can store NULL values
2665 function isNullable();
2668 /******************************************************************************
2670 *****************************************************************************/
2673 * Database error base class
2676 class DBError
extends MWException
{
2680 * Construct a database error
2681 * @param $db Database object which threw the error
2682 * @param $error A simple error message to be used for debugging
2684 function __construct( DatabaseBase
&$db, $error ) {
2686 parent
::__construct( $error );
2689 function getText() {
2690 global $wgShowDBErrorBacktrace;
2692 $s = $this->getMessage() . "\n";
2694 if ( $wgShowDBErrorBacktrace ) {
2695 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2705 class DBConnectionError
extends DBError
{
2708 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2709 $msg = 'DB connection error';
2711 if ( trim( $error ) != '' ) {
2715 $this->error
= $error;
2717 parent
::__construct( $db, $msg );
2720 function useOutputPage() {
2721 // Not likely to work
2725 function useMessageCache() {
2726 // Not likely to work
2730 function getLogMessage() {
2731 # Don't send to the exception log
2735 function getPageTitle() {
2736 global $wgSitename, $wgLang;
2738 $header = "$wgSitename has a problem";
2740 if ( $wgLang instanceof Language
) {
2741 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2747 function getHTML() {
2748 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2750 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2751 $again = 'Try waiting a few minutes and reloading.';
2752 $info = '(Can\'t contact the database server: $1)';
2754 if ( $wgLang instanceof Language
) {
2755 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2756 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2757 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2760 # No database access
2761 if ( is_object( $wgMessageCache ) ) {
2762 $wgMessageCache->disable();
2765 if ( trim( $this->error
) == '' ) {
2766 $this->error
= $this->db
->getProperty( 'mServer' );
2769 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2770 $text = str_replace( '$1', $this->error
, $noconnect );
2772 if ( $wgShowDBErrorBacktrace ) {
2773 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2776 $extra = $this->searchForm();
2778 if ( $wgUseFileCache ) {
2780 $cache = $this->fileCachedPage();
2781 # Cached version on file system?
2782 if ( $cache !== null ) {
2783 # Hack: extend the body for error messages
2784 $cache = str_replace( array( '</html>', '</body>' ), '', $cache );
2785 # Add cache notice...
2786 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2788 # Localize it if possible...
2789 if ( $wgLang instanceof Language
) {
2790 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2793 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2795 # Output cached page with notices on bottom and re-close body
2796 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2798 } catch ( MWException
$e ) {
2799 // Do nothing, just use the default page
2803 # Headers needed here - output is just the error message
2804 return $this->htmlHeader() . "$text<hr />$extra" . $this->htmlFooter();
2807 function searchForm() {
2808 global $wgSitename, $wgServer, $wgLang;
2810 $usegoogle = "You can try searching via Google in the meantime.";
2811 $outofdate = "Note that their indexes of our content may be out of date.";
2812 $googlesearch = "Search";
2814 if ( $wgLang instanceof Language
) {
2815 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2816 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2817 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2820 $search = htmlspecialchars( @$_REQUEST['search'] );
2822 $server = htmlspecialchars( $wgServer );
2823 $sitename = htmlspecialchars( $wgSitename );
2826 <div style="margin: 1.5em">$usegoogle<br />
2827 <small>$outofdate</small></div>
2828 <!-- SiteSearch Google -->
2829 <form method="get" action="http://www.google.com/search" id="googlesearch">
2830 <input type="hidden" name="domains" value="$server" />
2831 <input type="hidden" name="num" value="50" />
2832 <input type="hidden" name="ie" value="UTF-8" />
2833 <input type="hidden" name="oe" value="UTF-8" />
2835 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2836 <input type="submit" name="btnG" value="$googlesearch" />
2838 <input type="radio" name="sitesearch" id="gwiki" value="$server" checked="checked" /><label for="gwiki">$sitename</label>
2839 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2842 <!-- SiteSearch Google -->
2847 function fileCachedPage() {
2848 global $wgTitle, $title, $wgLang, $wgOut;
2850 if ( $wgOut->isDisabled() ) {
2851 return; // Done already?
2854 $mainpage = 'Main Page';
2856 if ( $wgLang instanceof Language
) {
2857 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2862 } elseif ( $title ) {
2863 $t = Title
::newFromURL( $title );
2865 $t = Title
::newFromText( $mainpage );
2868 $cache = new HTMLFileCache( $t );
2869 if ( $cache->isFileCached() ) {
2870 return $cache->fetchPageText();
2876 function htmlBodyOnly() {
2884 class DBQueryError
extends DBError
{
2885 public $error, $errno, $sql, $fname;
2887 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2888 $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" .
2890 "Function: $fname\n" .
2891 "Error: $errno $error\n";
2893 parent
::__construct( $db, $message );
2895 $this->error
= $error;
2896 $this->errno
= $errno;
2898 $this->fname
= $fname;
2901 function getText() {
2902 global $wgShowDBErrorBacktrace;
2904 if ( $this->useMessageCache() ) {
2905 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2906 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2908 if ( $wgShowDBErrorBacktrace ) {
2909 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2914 return parent
::getText();
2919 global $wgShowSQLErrors;
2921 if ( !$wgShowSQLErrors ) {
2922 return $this->msg( 'sqlhidden', 'SQL hidden' );
2928 function getLogMessage() {
2929 # Don't send to the exception log
2933 function getPageTitle() {
2934 return $this->msg( 'databaseerror', 'Database error' );
2937 function getHTML() {
2938 global $wgShowDBErrorBacktrace;
2940 if ( $this->useMessageCache() ) {
2941 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2942 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2944 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2947 if ( $wgShowDBErrorBacktrace ) {
2948 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2958 class DBUnexpectedError
extends DBError
{}
2962 * Result wrapper for grabbing data queried by someone else
2965 class ResultWrapper
implements Iterator
{
2966 var $db, $result, $pos = 0, $currentRow = null;
2969 * Create a new result object from a result resource and a Database object
2971 function __construct( $database, $result ) {
2972 $this->db
= $database;
2974 if ( $result instanceof ResultWrapper
) {
2975 $this->result
= $result->result
;
2977 $this->result
= $result;
2982 * Get the number of rows in a result object
2984 function numRows() {
2985 return $this->db
->numRows( $this );
2989 * Fetch the next row from the given result object, in object form.
2990 * Fields can be retrieved with $row->fieldname, with fields acting like
2993 * @return MySQL row object
2994 * @throws DBUnexpectedError Thrown if the database returns an error
2996 function fetchObject() {
2997 return $this->db
->fetchObject( $this );
3001 * Fetch the next row from the given result object, in associative array
3002 * form. Fields are retrieved with $row['fieldname'].
3004 * @return MySQL row object
3005 * @throws DBUnexpectedError Thrown if the database returns an error
3007 function fetchRow() {
3008 return $this->db
->fetchRow( $this );
3012 * Free a result object
3015 $this->db
->freeResult( $this );
3016 unset( $this->result
);
3021 * Change the position of the cursor in a result object
3022 * See mysql_data_seek()
3024 function seek( $row ) {
3025 $this->db
->dataSeek( $this, $row );
3028 /*********************
3029 * Iterator functions
3030 * Note that using these in combination with the non-iterator functions
3031 * above may cause rows to be skipped or repeated.
3035 if ( $this->numRows() ) {
3036 $this->db
->dataSeek( $this, 0 );
3039 $this->currentRow
= null;
3042 function current() {
3043 if ( is_null( $this->currentRow
) ) {
3046 return $this->currentRow
;
3055 $this->currentRow
= $this->fetchObject();
3056 return $this->currentRow
;
3060 return $this->current() !== false;
3065 * Overloads the relevant methods of the real ResultsWrapper so it
3066 * doesn't go anywhere near an actual database.
3068 class FakeResultWrapper
extends ResultWrapper
{
3069 var $result = array();
3070 var $db = null; // And it's going to stay that way :D
3072 var $currentRow = null;
3074 function __construct( $array ) {
3075 $this->result
= $array;
3078 function numRows() {
3079 return count( $this->result
);
3082 function fetchRow() {
3083 $this->currentRow
= $this->result
[$this->pos++
];
3084 return $this->currentRow
;
3087 function seek( $row ) {
3093 // Callers want to be able to access fields with $this->fieldName
3094 function fetchObject() {
3095 $this->currentRow
= $this->result
[$this->pos++
];
3096 return (object)$this->currentRow
;
3101 $this->currentRow
= null;
3106 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
3107 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
3112 public function __construct( $s ) {
3116 public function toString() {