4770293c9f1f2545833589e0fff3cb8762b06fd0
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 * Database abstraction object
22 abstract class DatabaseBase
{
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mDoneWrites = false;
30 protected $mPHPError = false;
32 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
33 protected $mOpened = false;
35 protected $mFailFunction;
36 protected $mTablePrefix;
38 protected $mTrxLevel = 0;
39 protected $mErrorCount = 0;
40 protected $mLBInfo = array();
41 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 protected $mDefaultBigSelects = null;
44 #------------------------------------------------------------------------------
46 #------------------------------------------------------------------------------
47 # These optionally set a variable and return the previous state
50 * Fail function, takes a Database as a parameter
51 * Set to false for default, 1 for ignore errors
53 function failFunction( $function = null ) {
54 return wfSetVar( $this->mFailFunction
, $function );
58 * Boolean, controls output of large amounts of debug information
60 function debug( $debug = null ) {
61 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
65 * Turns buffering of SQL result sets on (true) or off (false).
66 * Default is "on" and it should not be changed without good reasons.
68 function bufferResults( $buffer = null ) {
69 if ( is_null( $buffer ) ) {
70 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
72 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
77 * Turns on (false) or off (true) the automatic generation and sending
78 * of a "we're sorry, but there has been a database error" page on
79 * database errors. Default is on (false). When turned off, the
80 * code should use lastErrno() and lastError() to handle the
81 * situation as appropriate.
83 function ignoreErrors( $ignoreErrors = null ) {
84 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
88 * The current depth of nested transactions
89 * @param $level Integer: , default NULL.
91 function trxLevel( $level = null ) {
92 return wfSetVar( $this->mTrxLevel
, $level );
96 * Number of errors logged, only useful when errors are ignored
98 function errorCount( $count = null ) {
99 return wfSetVar( $this->mErrorCount
, $count );
102 function tablePrefix( $prefix = null ) {
103 return wfSetVar( $this->mTablePrefix
, $prefix );
107 * Properties passed down from the server info array of the load balancer
109 function getLBInfo( $name = null ) {
110 if ( is_null( $name ) ) {
111 return $this->mLBInfo
;
113 if ( array_key_exists( $name, $this->mLBInfo
) ) {
114 return $this->mLBInfo
[$name];
121 function setLBInfo( $name, $value = null ) {
122 if ( is_null( $value ) ) {
123 $this->mLBInfo
= $name;
125 $this->mLBInfo
[$name] = $value;
130 * Set lag time in seconds for a fake slave
132 function setFakeSlaveLag( $lag ) {
133 $this->mFakeSlaveLag
= $lag;
137 * Make this connection a fake master
139 function setFakeMaster( $enabled = true ) {
140 $this->mFakeMaster
= $enabled;
144 * Returns true if this database supports (and uses) cascading deletes
146 function cascadingDeletes() {
151 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
153 function cleanupTriggers() {
158 * Returns true if this database is strict about what can be put into an IP field.
159 * Specifically, it uses a NULL value instead of an empty string.
161 function strictIPs() {
166 * Returns true if this database uses timestamps rather than integers
168 function realTimestamps() {
173 * Returns true if this database does an implicit sort when doing GROUP BY
175 function implicitGroupby() {
180 * Returns true if this database does an implicit order by when the column has an index
181 * For example: SELECT page_title FROM page LIMIT 1
183 function implicitOrderby() {
188 * Returns true if this database requires that SELECT DISTINCT queries require that all
189 ORDER BY expressions occur in the SELECT list per the SQL92 standard
191 function standardSelectDistinct() {
196 * Returns true if this database can do a native search on IP columns
197 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
199 function searchableIPs() {
204 * Returns true if this database can use functional indexes
206 function functionalIndexes() {
211 * Return the last query that went through Database::query()
214 function lastQuery() { return $this->mLastQuery
; }
218 * Returns true if the connection may have been used for write queries.
219 * Should return true if unsure.
221 function doneWrites() { return $this->mDoneWrites
; }
224 * Is a connection to the database open?
227 function isOpen() { return $this->mOpened
; }
230 * Set a flag for this connection
232 * @param $flag Integer: DBO_* constants from Defines.php:
233 * - DBO_DEBUG: output some debug info (same as debug())
234 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
235 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
236 * - DBO_TRX: automatically start transactions
237 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
238 * and removes it in command line mode
239 * - DBO_PERSISTENT: use persistant database connection
241 function setFlag( $flag ) {
242 $this->mFlags |
= $flag;
246 * Clear a flag for this connection
248 * @param $flag: same as setFlag()'s $flag param
250 function clearFlag( $flag ) {
251 $this->mFlags
&= ~
$flag;
255 * Returns a boolean whether the flag $flag is set for this connection
257 * @param $flag: same as setFlag()'s $flag param
260 function getFlag( $flag ) {
261 return !!($this->mFlags
& $flag);
265 * General read-only accessor
267 function getProperty( $name ) {
271 function getWikiID() {
272 if( $this->mTablePrefix
) {
273 return "{$this->mDBname}-{$this->mTablePrefix}";
275 return $this->mDBname
;
280 * Get the type of the DBMS, as it appears in $wgDBtype.
282 abstract function getType();
284 #------------------------------------------------------------------------------
286 #------------------------------------------------------------------------------
290 * @param $server String: database server host
291 * @param $user String: database user name
292 * @param $password String: database user password
293 * @param $dbName String: database name
294 * @param $failFunction
296 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
298 function __construct( $server = false, $user = false, $password = false, $dbName = false,
299 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
301 global $wgOut, $wgDBprefix, $wgCommandLineMode;
302 # Can't get a reference if it hasn't been set yet
303 if ( !isset( $wgOut ) ) {
307 $this->mFailFunction
= $failFunction;
308 $this->mFlags
= $flags;
310 if ( $this->mFlags
& DBO_DEFAULT
) {
311 if ( $wgCommandLineMode ) {
312 $this->mFlags
&= ~DBO_TRX
;
314 $this->mFlags |
= DBO_TRX
;
319 // Faster read-only access
320 if ( wfReadOnly() ) {
321 $this->mFlags |= DBO_PERSISTENT;
322 $this->mFlags &= ~DBO_TRX;
325 /** Get the default table prefix*/
326 if ( $tablePrefix == 'get from global' ) {
327 $this->mTablePrefix
= $wgDBprefix;
329 $this->mTablePrefix
= $tablePrefix;
333 $this->open( $server, $user, $password, $dbName );
338 * Same as new DatabaseMysql( ... ), kept for backward compatibility
339 * @param $server String: database server host
340 * @param $user String: database user name
341 * @param $password String: database user password
342 * @param $dbName String: database name
343 * @param failFunction
346 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
348 wfDeprecated( __METHOD__
);
349 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
353 * Usually aborts on failure
354 * If the failFunction is set to a non-zero integer, returns success
355 * @param $server String: database server host
356 * @param $user String: database user name
357 * @param $password String: database user password
358 * @param $dbName String: database name
360 abstract function open( $server, $user, $password, $dbName );
362 protected function installErrorHandler() {
363 $this->mPHPError
= false;
364 $this->htmlErrors
= ini_set( 'html_errors', '0' );
365 set_error_handler( array( $this, 'connectionErrorHandler' ) );
368 protected function restoreErrorHandler() {
369 restore_error_handler();
370 if ( $this->htmlErrors
!== false ) {
371 ini_set( 'html_errors', $this->htmlErrors
);
373 if ( $this->mPHPError
) {
374 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
375 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
382 protected function connectionErrorHandler( $errno, $errstr ) {
383 $this->mPHPError
= $errstr;
387 * Closes a database connection.
388 * if it is open : commits any open transactions
390 * @return Bool operation success. true if already closed.
393 # Stub, should probably be overridden
398 * @param $error String: fallback error message, used if none is given by DB
400 function reportConnectionError( $error = 'Unknown error' ) {
401 $myError = $this->lastError();
406 if ( $this->mFailFunction
) {
407 # Legacy error handling method
408 if ( !is_int( $this->mFailFunction
) ) {
409 $ff = $this->mFailFunction
;
410 $ff( $this, $error );
414 throw new DBConnectionError( $this, $error );
419 * Determine whether a query writes to the DB.
420 * Should return true if unsure.
422 function isWriteQuery( $sql ) {
423 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
427 * Usually aborts on failure. If errors are explicitly ignored, returns success.
429 * @param $sql String: SQL query
430 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
431 * comment (you can use __METHOD__ or add some extra info)
432 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
433 * maybe best to catch the exception instead?
434 * @return true for a successful write query, ResultWrapper object for a successful read query,
435 * or false on failure if $tempIgnore set
436 * @throws DBQueryError Thrown when the database returns an error of any kind
438 public function query( $sql, $fname = '', $tempIgnore = false ) {
441 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
442 if ( isset( $wgProfiler ) ) {
443 # generalizeSQL will probably cut down the query to reasonable
444 # logging size most of the time. The substr is really just a sanity check.
446 # Who's been wasting my precious column space? -- TS
447 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
450 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
451 $totalProf = 'Database::query-master';
453 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
454 $totalProf = 'Database::query';
456 wfProfileIn( $totalProf );
457 wfProfileIn( $queryProf );
460 $this->mLastQuery
= $sql;
461 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
462 // Set a flag indicating that writes have been done
463 wfDebug( __METHOD__
.": Writes done: $sql\n" );
464 $this->mDoneWrites
= true;
467 # Add a comment for easy SHOW PROCESSLIST interpretation
470 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
471 $userName = $wgUser->getName();
472 if ( mb_strlen( $userName ) > 15 ) {
473 $userName = mb_substr( $userName, 0, 15 ) . '...';
475 $userName = str_replace( '/', '', $userName );
479 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
481 # $commentedSql = $sql;
484 # If DBO_TRX is set, start a transaction
485 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
486 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
487 // avoid establishing transactions for SHOW and SET statements too -
488 // that would delay transaction initializations to once connection
489 // is really used by application
490 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
491 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
495 if ( $this->debug() ) {
496 $sqlx = substr( $commentedSql, 0, 500 );
497 $sqlx = strtr( $sqlx, "\t\n", ' ' );
499 wfDebug( "SQL-master: $sqlx\n" );
501 wfDebug( "SQL: $sqlx\n" );
505 if ( istainted( $sql ) & TC_MYSQL
) {
506 throw new MWException( 'Tainted query found' );
509 # Do the query and handle errors
510 $ret = $this->doQuery( $commentedSql );
512 # Try reconnecting if the connection was lost
513 if ( false === $ret && $this->wasErrorReissuable() ) {
514 # Transaction is gone, like it or not
515 $this->mTrxLevel
= 0;
516 wfDebug( "Connection lost, reconnecting...\n" );
517 if ( $this->ping() ) {
518 wfDebug( "Reconnected\n" );
519 $sqlx = substr( $commentedSql, 0, 500 );
520 $sqlx = strtr( $sqlx, "\t\n", ' ' );
521 global $wgRequestTime;
522 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
523 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
524 $ret = $this->doQuery( $commentedSql );
526 wfDebug( "Failed\n" );
530 if ( false === $ret ) {
531 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
534 if ( isset( $wgProfiler ) ) {
535 wfProfileOut( $queryProf );
536 wfProfileOut( $totalProf );
538 return $this->resultObject( $ret );
542 * The DBMS-dependent part of query()
543 * @param $sql String: SQL query.
544 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
547 /*private*/ abstract function doQuery( $sql );
550 * @param $error String
551 * @param $errno Integer
553 * @param $fname String
554 * @param $tempIgnore Boolean
556 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
557 # Ignore errors during error handling to avoid infinite recursion
558 $ignore = $this->ignoreErrors( true );
559 ++
$this->mErrorCount
;
561 if( $ignore ||
$tempIgnore ) {
562 wfDebug("SQL ERROR (ignored): $error\n");
563 $this->ignoreErrors( $ignore );
565 $sql1line = str_replace( "\n", "\\n", $sql );
566 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
567 wfDebug("SQL ERROR: " . $error . "\n");
568 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
574 * Intended to be compatible with the PEAR::DB wrapper functions.
575 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
577 * ? = scalar value, quoted as necessary
578 * ! = raw SQL bit (a function for instance)
579 * & = filename; reads the file and inserts as a blob
580 * (we don't use this though...)
582 function prepare( $sql, $func = 'Database::prepare' ) {
583 /* MySQL doesn't support prepared statements (yet), so just
584 pack up the query for reference. We'll manually replace
586 return array( 'query' => $sql, 'func' => $func );
589 function freePrepared( $prepared ) {
590 /* No-op by default */
594 * Execute a prepared query with the various arguments
595 * @param $prepared String: the prepared sql
596 * @param $args Mixed: Either an array here, or put scalars as varargs
598 function execute( $prepared, $args = null ) {
599 if( !is_array( $args ) ) {
601 $args = func_get_args();
602 array_shift( $args );
604 $sql = $this->fillPrepared( $prepared['query'], $args );
605 return $this->query( $sql, $prepared['func'] );
609 * Prepare & execute an SQL statement, quoting and inserting arguments
610 * in the appropriate places.
611 * @param $query String
614 function safeQuery( $query, $args = null ) {
615 $prepared = $this->prepare( $query, 'Database::safeQuery' );
616 if( !is_array( $args ) ) {
618 $args = func_get_args();
619 array_shift( $args );
621 $retval = $this->execute( $prepared, $args );
622 $this->freePrepared( $prepared );
627 * For faking prepared SQL statements on DBs that don't support
629 * @param $preparedQuery String: a 'preparable' SQL statement
630 * @param $args Array of arguments to fill it with
631 * @return string executable SQL
633 function fillPrepared( $preparedQuery, $args ) {
635 $this->preparedArgs
=& $args;
636 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
637 array( &$this, 'fillPreparedArg' ), $preparedQuery );
641 * preg_callback func for fillPrepared()
642 * The arguments should be in $this->preparedArgs and must not be touched
643 * while we're doing this.
645 * @param $matches Array
649 function fillPreparedArg( $matches ) {
650 switch( $matches[1] ) {
651 case '\\?': return '?';
652 case '\\!': return '!';
653 case '\\&': return '&';
655 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
656 switch( $matches[1] ) {
657 case '?': return $this->addQuotes( $arg );
658 case '!': return $arg;
660 # return $this->addQuotes( file_get_contents( $arg ) );
661 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
663 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
668 * Free a result object
669 * @param $res Mixed: A SQL result
671 function freeResult( $res ) {
672 # Stub. Might not really need to be overridden, since results should
673 # be freed by PHP when the variable goes out of scope anyway.
677 * Fetch the next row from the given result object, in object form.
678 * Fields can be retrieved with $row->fieldname, with fields acting like
681 * @param $res SQL result object as returned from Database::query(), etc.
683 * @throws DBUnexpectedError Thrown if the database returns an error
685 abstract function fetchObject( $res );
688 * Fetch the next row from the given result object, in associative array
689 * form. Fields are retrieved with $row['fieldname'].
691 * @param $res SQL result object as returned from Database::query(), etc.
693 * @throws DBUnexpectedError Thrown if the database returns an error
695 abstract function fetchRow( $res );
698 * Get the number of rows in a result object
699 * @param $res Mixed: A SQL result
701 abstract function numRows( $res );
704 * Get the number of fields in a result object
705 * See documentation for mysql_num_fields()
706 * @param $res Mixed: A SQL result
708 abstract function numFields( $res );
711 * Get a field name in a result object
712 * See documentation for mysql_field_name():
713 * http://www.php.net/mysql_field_name
714 * @param $res Mixed: A SQL result
717 abstract function fieldName( $res, $n );
720 * Get the inserted value of an auto-increment row
722 * The value inserted should be fetched from nextSequenceValue()
725 * $id = $dbw->nextSequenceValue('page_page_id_seq');
726 * $dbw->insert('page',array('page_id' => $id));
727 * $id = $dbw->insertId();
729 abstract function insertId();
732 * Change the position of the cursor in a result object
733 * See mysql_data_seek()
734 * @param $res Mixed: A SQL result
735 * @param $row Mixed: Either MySQL row or ResultWrapper
737 abstract function dataSeek( $res, $row );
740 * Get the last error number
743 abstract function lastErrno();
746 * Get a description of the last error
747 * See mysql_error() for more details
749 abstract function lastError();
752 * Get the number of rows affected by the last write query
753 * See mysql_affected_rows() for more details
755 abstract function affectedRows();
758 * Simple UPDATE wrapper
759 * Usually aborts on failure
760 * If errors are explicitly ignored, returns success
762 * This function exists for historical reasons, Database::update() has a more standard
763 * calling convention and feature set
765 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
766 $table = $this->tableName( $table );
767 $sql = "UPDATE $table SET $var = '" .
768 $this->strencode( $value ) . "' WHERE ($cond)";
769 return (bool)$this->query( $sql, $fname );
773 * Simple SELECT wrapper, returns a single field, input must be encoded
774 * Usually aborts on failure
775 * If errors are explicitly ignored, returns FALSE on failure
777 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
778 if ( !is_array( $options ) ) {
779 $options = array( $options );
781 $options['LIMIT'] = 1;
783 $res = $this->select( $table, $var, $cond, $fname, $options );
784 if ( $res === false ||
!$this->numRows( $res ) ) {
787 $row = $this->fetchRow( $res );
788 if ( $row !== false ) {
789 return reset( $row );
796 * Returns an optional USE INDEX clause to go after the table, and a
797 * string to go at the end of the query
801 * @param $options Array: associative array of options to be turned into
802 * an SQL query, valid keys are listed in the function.
805 function makeSelectOptions( $options ) {
806 $preLimitTail = $postLimitTail = '';
809 $noKeyOptions = array();
810 foreach ( $options as $key => $option ) {
811 if ( is_numeric( $key ) ) {
812 $noKeyOptions[$option] = true;
816 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
817 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
818 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
820 //if (isset($options['LIMIT'])) {
821 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
822 // isset($options['OFFSET']) ? $options['OFFSET']
826 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
827 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
828 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
830 # Various MySQL extensions
831 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
832 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
833 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
834 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
835 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
836 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
837 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
838 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
840 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
841 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
846 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
852 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
853 * @param $vars Mixed: Array or string, field name(s) to be retrieved
854 * @param $conds Mixed: Array or string, condition(s) for WHERE
855 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
856 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
857 * see Database::makeSelectOptions code for list of supported stuff
858 * @param $join_conds Array: Associative array of table join conditions (optional)
859 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
860 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
862 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
864 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
865 return $this->query( $sql, $fname );
871 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
872 * @param $vars Mixed: Array or string, field name(s) to be retrieved
873 * @param $conds Mixed: Array or string, condition(s) for WHERE
874 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
875 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
876 * see Database::makeSelectOptions code for list of supported stuff
877 * @param $join_conds Array: Associative array of table join conditions (optional)
878 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
879 * @return string, the SQL text
881 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
882 if( is_array( $vars ) ) {
883 $vars = implode( ',', $vars );
885 if( !is_array( $options ) ) {
886 $options = array( $options );
888 if( is_array( $table ) ) {
889 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
890 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
892 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
893 } elseif ($table!='') {
894 if ($table{0}==' ') {
895 $from = ' FROM ' . $table;
897 $from = ' FROM ' . $this->tableName( $table );
903 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
905 if( !empty( $conds ) ) {
906 if ( is_array( $conds ) ) {
907 $conds = $this->makeList( $conds, LIST_AND
);
909 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
911 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
914 if (isset($options['LIMIT']))
915 $sql = $this->limitResult($sql, $options['LIMIT'],
916 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
917 $sql = "$sql $postLimitTail";
919 if (isset($options['EXPLAIN'])) {
920 $sql = 'EXPLAIN ' . $sql;
926 * Single row SELECT wrapper
927 * Aborts or returns FALSE on error
929 * @param $table String: table name
930 * @param $vars String: the selected variables
931 * @param $conds Array: a condition map, terms are ANDed together.
932 * Items with numeric keys are taken to be literal conditions
933 * Takes an array of selected variables, and a condition map, which is ANDed
934 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
935 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
936 * $obj- >page_id is the ID of the Astronomy article
937 * @param $fname String: Calling function name
938 * @param $options Array
939 * @param $join_conds Array
941 * @todo migrate documentation to phpdocumentor format
943 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
944 $options['LIMIT'] = 1;
945 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
946 if ( $res === false )
948 if ( !$this->numRows($res) ) {
951 $obj = $this->fetchObject( $res );
956 * Estimate rows in dataset
957 * Returns estimated count - not necessarily an accurate estimate across different databases,
959 * Takes same arguments as Database::select()
961 * @param $table String: table name
962 * @param $vars Array: unused
963 * @param $conds Array: filters on the table
964 * @param $fname String: function name for profiling
965 * @param $options Array: options for select
966 * @return Integer: row count
968 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
970 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
972 $row = $this->fetchRow( $res );
973 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
979 * Removes most variables from an SQL query and replaces them with X or N for numbers.
980 * It's only slightly flawed. Don't use for anything important.
982 * @param $sql String: A SQL Query
984 static function generalizeSQL( $sql ) {
985 # This does the same as the regexp below would do, but in such a way
986 # as to avoid crashing php on some large strings.
987 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
989 $sql = str_replace ( "\\\\", '', $sql);
990 $sql = str_replace ( "\\'", '', $sql);
991 $sql = str_replace ( "\\\"", '', $sql);
992 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
993 $sql = preg_replace ('/".*"/s', "'X'", $sql);
995 # All newlines, tabs, etc replaced by single space
996 $sql = preg_replace ( '/\s+/', ' ', $sql);
999 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1005 * Determines whether a field exists in a table
1007 * @param $table String: table name
1008 * @param $field String: filed to check on that table
1009 * @param $fname String: calling function name (optional)
1010 * @return Boolean: whether $table has filed $field
1012 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1013 $info = $this->fieldInfo( $table, $field );
1018 * Determines whether an index exists
1019 * Usually aborts on failure
1020 * If errors are explicitly ignored, returns NULL on failure
1022 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1023 $info = $this->indexInfo( $table, $index, $fname );
1024 if ( is_null( $info ) ) {
1027 return $info !== false;
1033 * Get information about an index into an object
1034 * Returns false if the index does not exist
1036 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1037 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1038 # SHOW INDEX should work for 3.x and up:
1039 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1040 $table = $this->tableName( $table );
1041 $index = $this->indexName( $index );
1042 $sql = 'SHOW INDEX FROM '.$table;
1043 $res = $this->query( $sql, $fname );
1049 while ( $row = $this->fetchObject( $res ) ) {
1050 if ( $row->Key_name
== $index ) {
1055 return empty($result) ?
false : $result;
1059 * Query whether a given table exists
1061 function tableExists( $table ) {
1062 $table = $this->tableName( $table );
1063 $old = $this->ignoreErrors( true );
1064 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1065 $this->ignoreErrors( $old );
1070 * mysql_fetch_field() wrapper
1071 * Returns false if the field doesn't exist
1076 abstract function fieldInfo( $table, $field );
1079 * mysql_field_type() wrapper
1081 function fieldType( $res, $index ) {
1082 if ( $res instanceof ResultWrapper
) {
1083 $res = $res->result
;
1085 return mysql_field_type( $res, $index );
1089 * Determines if a given index is unique
1091 function indexUnique( $table, $index ) {
1092 $indexInfo = $this->indexInfo( $table, $index );
1093 if ( !$indexInfo ) {
1096 return !$indexInfo[0]->Non_unique
;
1100 * INSERT wrapper, inserts an array into a table
1102 * $a may be a single associative array, or an array of these with numeric keys, for
1105 * Usually aborts on failure
1106 * If errors are explicitly ignored, returns success
1108 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1109 # No rows to insert, easy just return now
1110 if ( !count( $a ) ) {
1114 $table = $this->tableName( $table );
1115 if ( !is_array( $options ) ) {
1116 $options = array( $options );
1118 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1120 $keys = array_keys( $a[0] );
1123 $keys = array_keys( $a );
1126 $sql = 'INSERT ' . implode( ' ', $options ) .
1127 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1131 foreach ( $a as $row ) {
1137 $sql .= '(' . $this->makeList( $row ) . ')';
1140 $sql .= '(' . $this->makeList( $a ) . ')';
1142 return (bool)$this->query( $sql, $fname );
1146 * Make UPDATE options for the Database::update function
1149 * @param $options Array: The options passed to Database::update
1152 function makeUpdateOptions( $options ) {
1153 if( !is_array( $options ) ) {
1154 $options = array( $options );
1157 if ( in_array( 'LOW_PRIORITY', $options ) )
1158 $opts[] = $this->lowPriorityOption();
1159 if ( in_array( 'IGNORE', $options ) )
1161 return implode(' ', $opts);
1165 * UPDATE wrapper, takes a condition array and a SET array
1167 * @param $table String: The table to UPDATE
1168 * @param $values Array: An array of values to SET
1169 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1170 * @param $fname String: The Class::Function calling this function
1172 * @param $options Array: An array of UPDATE options, can be one or
1173 * more of IGNORE, LOW_PRIORITY
1176 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1177 $table = $this->tableName( $table );
1178 $opts = $this->makeUpdateOptions( $options );
1179 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1180 if ( $conds != '*' ) {
1181 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1183 return $this->query( $sql, $fname );
1187 * Makes an encoded list of strings from an array
1189 * LIST_COMMA - comma separated, no field names
1190 * LIST_AND - ANDed WHERE clause (without the WHERE)
1191 * LIST_OR - ORed WHERE clause (without the WHERE)
1192 * LIST_SET - comma separated with field names, like a SET clause
1193 * LIST_NAMES - comma separated field names
1195 function makeList( $a, $mode = LIST_COMMA
) {
1196 if ( !is_array( $a ) ) {
1197 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1202 foreach ( $a as $field => $value ) {
1204 if ( $mode == LIST_AND
) {
1206 } elseif($mode == LIST_OR
) {
1214 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1215 $list .= "($value)";
1216 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1218 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1219 if( count( $value ) == 0 ) {
1220 throw new MWException( __METHOD__
.': empty input' );
1221 } elseif( count( $value ) == 1 ) {
1222 // Special-case single values, as IN isn't terribly efficient
1223 // Don't necessarily assume the single key is 0; we don't
1224 // enforce linear numeric ordering on other arrays here.
1225 $value = array_values( $value );
1226 $list .= $field." = ".$this->addQuotes( $value[0] );
1228 $list .= $field." IN (".$this->makeList($value).") ";
1230 } elseif( $value === null ) {
1231 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1232 $list .= "$field IS ";
1233 } elseif ( $mode == LIST_SET
) {
1234 $list .= "$field = ";
1238 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1239 $list .= "$field = ";
1241 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1248 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1249 * The keys on each level may be either integers or strings.
1251 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1252 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1253 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1254 * @return Mixed: string SQL fragment, or false if no items in array.
1256 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1258 foreach ( $data as $base => $sub ) {
1259 if ( count( $sub ) ) {
1260 $conds[] = $this->makeList(
1261 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1267 return $this->makeList( $conds, LIST_OR
);
1269 // Nothing to search for...
1275 * Bitwise operations
1278 function bitNot($field) {
1279 return "(~$bitField)";
1282 function bitAnd($fieldLeft, $fieldRight) {
1283 return "($fieldLeft & $fieldRight)";
1286 function bitOr($fieldLeft, $fieldRight) {
1287 return "($fieldLeft | $fieldRight)";
1291 * Change the current database
1293 * @return bool Success or failure
1295 function selectDB( $db ) {
1296 # Stub. Shouldn't cause serious problems if it's not overridden, but
1297 # if your database engine supports a concept similar to MySQL's
1298 # databases you may as well. TODO: explain what exactly will fail if
1299 # this is not overridden.
1304 * Get the current DB name
1306 function getDBname() {
1307 return $this->mDBname
;
1311 * Get the server hostname or IP address
1313 function getServer() {
1314 return $this->mServer
;
1318 * Format a table name ready for use in constructing an SQL query
1320 * This does two important things: it quotes the table names to clean them up,
1321 * and it adds a table prefix if only given a table name with no quotes.
1323 * All functions of this object which require a table name call this function
1324 * themselves. Pass the canonical name to such functions. This is only needed
1325 * when calling query() directly.
1327 * @param $name String: database table name
1328 * @return String: full database name
1330 function tableName( $name ) {
1331 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1332 # Skip the entire process when we have a string quoted on both ends.
1333 # Note that we check the end so that we will still quote any use of
1334 # use of `database`.table. But won't break things if someone wants
1335 # to query a database table with a dot in the name.
1336 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1338 # Lets test for any bits of text that should never show up in a table
1339 # name. Basically anything like JOIN or ON which are actually part of
1340 # SQL queries, but may end up inside of the table value to combine
1341 # sql. Such as how the API is doing.
1342 # Note that we use a whitespace test rather than a \b test to avoid
1343 # any remote case where a word like on may be inside of a table name
1344 # surrounded by symbols which may be considered word breaks.
1345 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1347 # Split database and table into proper variables.
1348 # We reverse the explode so that database.table and table both output
1349 # the correct table.
1350 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1351 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1352 else @list
( $table ) = $dbDetails;
1353 $prefix = $this->mTablePrefix
; # Default prefix
1355 # A database name has been specified in input. Quote the table name
1356 # because we don't want any prefixes added.
1357 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1359 # Note that we use the long format because php will complain in in_array if
1360 # the input is not an array, and will complain in is_array if it is not set.
1361 if( !isset( $database ) # Don't use shared database if pre selected.
1362 && isset( $wgSharedDB ) # We have a shared database
1363 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1364 && isset( $wgSharedTables )
1365 && is_array( $wgSharedTables )
1366 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1367 $database = $wgSharedDB;
1368 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1371 # Quote the $database and $table and apply the prefix if not quoted.
1372 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1373 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1375 # Merge our database and table into our final table name.
1376 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1378 # We're finished, return.
1383 * Fetch a number of table names into an array
1384 * This is handy when you need to construct SQL for joins
1387 * extract($dbr->tableNames('user','watchlist'));
1388 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1389 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1391 public function tableNames() {
1392 $inArray = func_get_args();
1394 foreach ( $inArray as $name ) {
1395 $retVal[$name] = $this->tableName( $name );
1401 * Fetch a number of table names into an zero-indexed numerical array
1402 * This is handy when you need to construct SQL for joins
1405 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1406 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1407 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1409 public function tableNamesN() {
1410 $inArray = func_get_args();
1412 foreach ( $inArray as $name ) {
1413 $retVal[] = $this->tableName( $name );
1421 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1424 $use_index_safe = is_array($use_index) ?
$use_index : array();
1425 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1426 foreach ( $tables as $table ) {
1427 // Is there a JOIN and INDEX clause for this table?
1428 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1429 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1430 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1431 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1433 $tableClause .= ' ON (' . $on . ')';
1435 $retJOIN[] = $tableClause;
1436 // Is there an INDEX clause?
1437 } else if ( isset($use_index_safe[$table]) ) {
1438 $tableClause = $this->tableName( $table );
1439 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1440 $ret[] = $tableClause;
1441 // Is there a JOIN clause?
1442 } else if ( isset($join_conds_safe[$table]) ) {
1443 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1444 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1446 $tableClause .= ' ON (' . $on . ')';
1448 $retJOIN[] = $tableClause;
1450 $tableClause = $this->tableName( $table );
1451 $ret[] = $tableClause;
1454 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1455 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1456 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1457 // Compile our final table clause
1458 return implode(' ',array($straightJoins,$otherJoins) );
1462 * Get the name of an index in a given table
1464 function indexName( $index ) {
1465 // Backwards-compatibility hack
1467 'ar_usertext_timestamp' => 'usertext_timestamp',
1468 'un_user_id' => 'user_id',
1469 'un_user_ip' => 'user_ip',
1471 if( isset( $renamed[$index] ) ) {
1472 return $renamed[$index];
1479 * Wrapper for addslashes()
1480 * @param $s String: to be slashed.
1481 * @return String: slashed string.
1483 abstract function strencode( $s );
1486 * If it's a string, adds quotes and backslashes
1487 * Otherwise returns as-is
1489 function addQuotes( $s ) {
1490 if ( $s === null ) {
1493 # This will also quote numeric values. This should be harmless,
1494 # and protects against weird problems that occur when they really
1495 # _are_ strings such as article titles and string->number->string
1496 # conversion is not 1:1.
1497 return "'" . $this->strencode( $s ) . "'";
1502 * Escape string for safe LIKE usage.
1503 * WARNING: you should almost never use this function directly,
1504 * instead use buildLike() that escapes everything automatically
1505 * Deprecated in 1.17, warnings in 1.17, removed in ???
1507 public function escapeLike( $s ) {
1508 wfDeprecated( __METHOD__
);
1509 return $this->escapeLikeInternal( $s );
1512 protected function escapeLikeInternal( $s ) {
1513 $s = str_replace( '\\', '\\\\', $s );
1514 $s = $this->strencode( $s );
1515 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1520 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1521 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1522 * Alternatively, the function could be provided with an array of aforementioned parameters.
1524 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1525 * for subpages of 'My page title'.
1526 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1529 * @return String: fully built LIKE statement
1531 function buildLike() {
1532 $params = func_get_args();
1533 if (count($params) > 0 && is_array($params[0])) {
1534 $params = $params[0];
1538 foreach( $params as $value) {
1539 if( $value instanceof LikeMatch
) {
1540 $s .= $value->toString();
1542 $s .= $this->escapeLikeInternal( $value );
1545 return " LIKE '" . $s . "' ";
1549 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1551 function anyChar() {
1552 return new LikeMatch( '_' );
1556 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1558 function anyString() {
1559 return new LikeMatch( '%' );
1563 * Returns an appropriately quoted sequence value for inserting a new row.
1564 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1565 * subclass will return an integer, and save the value for insertId()
1567 function nextSequenceValue( $seqName ) {
1572 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1573 * is only needed because a) MySQL must be as efficient as possible due to
1574 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1575 * which index to pick. Anyway, other databases might have different
1576 * indexes on a given table. So don't bother overriding this unless you're
1579 function useIndexClause( $index ) {
1584 * REPLACE query wrapper
1585 * PostgreSQL simulates this with a DELETE followed by INSERT
1586 * $row is the row to insert, an associative array
1587 * $uniqueIndexes is an array of indexes. Each element may be either a
1588 * field name or an array of field names
1590 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1591 * However if you do this, you run the risk of encountering errors which wouldn't have
1594 * @todo migrate comment to phodocumentor format
1596 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1597 $table = $this->tableName( $table );
1600 if ( !is_array( reset( $rows ) ) ) {
1601 $rows = array( $rows );
1604 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1606 foreach ( $rows as $row ) {
1612 $sql .= '(' . $this->makeList( $row ) . ')';
1614 return $this->query( $sql, $fname );
1618 * DELETE where the condition is a join
1619 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1621 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1622 * join condition matches, set $conds='*'
1624 * DO NOT put the join condition in $conds
1626 * @param $delTable String: The table to delete from.
1627 * @param $joinTable String: The other table.
1628 * @param $delVar String: The variable to join on, in the first table.
1629 * @param $joinVar String: The variable to join on, in the second table.
1630 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1631 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1633 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1635 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1638 $delTable = $this->tableName( $delTable );
1639 $joinTable = $this->tableName( $joinTable );
1640 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1641 if ( $conds != '*' ) {
1642 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1645 return $this->query( $sql, $fname );
1649 * Returns the size of a text field, or -1 for "unlimited"
1651 function textFieldSize( $table, $field ) {
1652 $table = $this->tableName( $table );
1653 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1654 $res = $this->query( $sql, 'Database::textFieldSize' );
1655 $row = $this->fetchObject( $res );
1658 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1667 * A string to insert into queries to show that they're low-priority, like
1668 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1669 * string and nothing bad should happen.
1671 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1673 function lowPriorityOption() {
1678 * DELETE query wrapper
1680 * Use $conds == "*" to delete all rows
1682 function delete( $table, $conds, $fname = 'Database::delete' ) {
1684 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1686 $table = $this->tableName( $table );
1687 $sql = "DELETE FROM $table";
1688 if ( $conds != '*' ) {
1689 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1691 return $this->query( $sql, $fname );
1695 * INSERT SELECT wrapper
1696 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1697 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1698 * $conds may be "*" to copy the whole table
1699 * srcTable may be an array of tables.
1701 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1702 $insertOptions = array(), $selectOptions = array() )
1704 $destTable = $this->tableName( $destTable );
1705 if ( is_array( $insertOptions ) ) {
1706 $insertOptions = implode( ' ', $insertOptions );
1708 if( !is_array( $selectOptions ) ) {
1709 $selectOptions = array( $selectOptions );
1711 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1712 if( is_array( $srcTable ) ) {
1713 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1715 $srcTable = $this->tableName( $srcTable );
1717 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1718 " SELECT $startOpts " . implode( ',', $varMap ) .
1719 " FROM $srcTable $useIndex ";
1720 if ( $conds != '*' ) {
1721 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1723 $sql .= " $tailOpts";
1724 return $this->query( $sql, $fname );
1728 * Construct a LIMIT query with optional offset. This is used for query
1729 * pages. The SQL should be adjusted so that only the first $limit rows
1730 * are returned. If $offset is provided as well, then the first $offset
1731 * rows should be discarded, and the next $limit rows should be returned.
1732 * If the result of the query is not ordered, then the rows to be returned
1733 * are theoretically arbitrary.
1735 * $sql is expected to be a SELECT, if that makes a difference. For
1736 * UPDATE, limitResultForUpdate should be used.
1738 * The version provided by default works in MySQL and SQLite. It will very
1739 * likely need to be overridden for most other DBMSes.
1741 * @param $sql String: SQL query we will append the limit too
1742 * @param $limit Integer: the SQL limit
1743 * @param $offset Integer the SQL offset (default false)
1745 function limitResult( $sql, $limit, $offset=false ) {
1746 if( !is_numeric( $limit ) ) {
1747 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1749 return "$sql LIMIT "
1750 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1753 function limitResultForUpdate( $sql, $num ) {
1754 return $this->limitResult( $sql, $num, 0 );
1758 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1759 * within the UNION construct.
1762 function unionSupportsOrderAndLimit() {
1763 return true; // True for almost every DB supported
1767 * Construct a UNION query
1768 * This is used for providing overload point for other DB abstractions
1769 * not compatible with the MySQL syntax.
1770 * @param $sqls Array: SQL statements to combine
1771 * @param $all Boolean: use UNION ALL
1772 * @return String: SQL fragment
1774 function unionQueries($sqls, $all) {
1775 $glue = $all ?
') UNION ALL (' : ') UNION (';
1776 return '('.implode( $glue, $sqls ) . ')';
1780 * Returns an SQL expression for a simple conditional. This doesn't need
1781 * to be overridden unless CASE isn't supported in your DBMS.
1783 * @param $cond String: SQL expression which will result in a boolean value
1784 * @param $trueVal String: SQL expression to return if true
1785 * @param $falseVal String: SQL expression to return if false
1786 * @return String: SQL fragment
1788 function conditional( $cond, $trueVal, $falseVal ) {
1789 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1793 * Returns a comand for str_replace function in SQL query.
1794 * Uses REPLACE() in MySQL
1796 * @param $orig String: column to modify
1797 * @param $old String: column to seek
1798 * @param $new String: column to replace with
1800 function strreplace( $orig, $old, $new ) {
1801 return "REPLACE({$orig}, {$old}, {$new})";
1805 * Determines if the last failure was due to a deadlock
1808 function wasDeadlock() {
1813 * Determines if the last query error was something that should be dealt
1814 * with by pinging the connection and reissuing the query.
1817 function wasErrorReissuable() {
1822 * Determines if the last failure was due to the database being read-only.
1825 function wasReadOnlyError() {
1830 * Perform a deadlock-prone transaction.
1832 * This function invokes a callback function to perform a set of write
1833 * queries. If a deadlock occurs during the processing, the transaction
1834 * will be rolled back and the callback function will be called again.
1837 * $dbw->deadlockLoop( callback, ... );
1839 * Extra arguments are passed through to the specified callback function.
1841 * Returns whatever the callback function returned on its successful,
1842 * iteration, or false on error, for example if the retry limit was
1845 function deadlockLoop() {
1846 $myFname = 'Database::deadlockLoop';
1849 $args = func_get_args();
1850 $function = array_shift( $args );
1851 $oldIgnore = $this->ignoreErrors( true );
1852 $tries = DEADLOCK_TRIES
;
1853 if ( is_array( $function ) ) {
1854 $fname = $function[0];
1859 $retVal = call_user_func_array( $function, $args );
1860 $error = $this->lastError();
1861 $errno = $this->lastErrno();
1862 $sql = $this->lastQuery();
1865 if ( $this->wasDeadlock() ) {
1867 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1869 $this->reportQueryError( $error, $errno, $sql, $fname );
1872 } while( $this->wasDeadlock() && --$tries > 0 );
1873 $this->ignoreErrors( $oldIgnore );
1874 if ( $tries <= 0 ) {
1875 $this->rollback( $myFname );
1876 $this->reportQueryError( $error, $errno, $sql, $fname );
1879 $this->commit( $myFname );
1885 * Do a SELECT MASTER_POS_WAIT()
1887 * @param $pos MySQLMasterPos object
1888 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1890 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1891 $fname = 'Database::masterPosWait';
1892 wfProfileIn( $fname );
1894 # Commit any open transactions
1895 if ( $this->mTrxLevel
) {
1899 if ( !is_null( $this->mFakeSlaveLag
) ) {
1900 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1901 if ( $wait > $timeout * 1e6
) {
1902 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1903 wfProfileOut( $fname );
1905 } elseif ( $wait > 0 ) {
1906 wfDebug( "Fake slave waiting $wait us\n" );
1908 wfProfileOut( $fname );
1911 wfDebug( "Fake slave up to date ($wait us)\n" );
1912 wfProfileOut( $fname );
1917 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1918 $encFile = $this->addQuotes( $pos->file
);
1919 $encPos = intval( $pos->pos
);
1920 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1921 $res = $this->doQuery( $sql );
1922 if ( $res && $row = $this->fetchRow( $res ) ) {
1923 wfProfileOut( $fname );
1926 wfProfileOut( $fname );
1932 * Get the position of the master from SHOW SLAVE STATUS
1934 function getSlavePos() {
1935 if ( !is_null( $this->mFakeSlaveLag
) ) {
1936 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1937 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1940 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1941 $row = $this->fetchObject( $res );
1943 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1944 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1951 * Get the position of the master from SHOW MASTER STATUS
1953 function getMasterPos() {
1954 if ( $this->mFakeMaster
) {
1955 return new MySQLMasterPos( 'fake', microtime( true ) );
1957 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1958 $row = $this->fetchObject( $res );
1960 return new MySQLMasterPos( $row->File
, $row->Position
);
1967 * Begin a transaction, committing any previously open transaction
1969 function begin( $fname = 'Database::begin' ) {
1970 $this->query( 'BEGIN', $fname );
1971 $this->mTrxLevel
= 1;
1977 function commit( $fname = 'Database::commit' ) {
1978 if( $this->mTrxLevel
) {
1979 $this->query( 'COMMIT', $fname );
1980 $this->mTrxLevel
= 0;
1985 * Rollback a transaction.
1986 * No-op on non-transactional databases.
1988 function rollback( $fname = 'Database::rollback' ) {
1989 if( $this->mTrxLevel
) {
1990 $this->query( 'ROLLBACK', $fname, true );
1991 $this->mTrxLevel
= 0;
1996 * Begin a transaction, committing any previously open transaction
1997 * @deprecated use begin()
1999 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2000 wfDeprecated( __METHOD__
);
2005 * Commit transaction, if one is open
2006 * @deprecated use commit()
2008 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2009 wfDeprecated( __METHOD__
);
2014 * Creates a new table with structure copied from existing table
2015 * Note that unlike most database abstraction functions, this function does not
2016 * automatically append database prefix, because it works at a lower
2017 * abstraction level.
2019 * @param $oldName String: name of table whose structure should be copied
2020 * @param $newName String: name of table to be created
2021 * @param $temporary Boolean: whether the new table should be temporary
2022 * @param $fname String: calling function name
2023 * @return Boolean: true if operation was successful
2025 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2026 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2030 * Return MW-style timestamp used for MySQL schema
2032 function timestamp( $ts=0 ) {
2033 return wfTimestamp(TS_MW
,$ts);
2037 * Local database timestamp format or null
2039 function timestampOrNull( $ts = null ) {
2040 if( is_null( $ts ) ) {
2043 return $this->timestamp( $ts );
2050 function resultObject( $result ) {
2051 if( empty( $result ) ) {
2053 } elseif ( $result instanceof ResultWrapper
) {
2055 } elseif ( $result === true ) {
2056 // Successful write query
2059 return new ResultWrapper( $this, $result );
2064 * Return aggregated value alias
2066 function aggregateValue ($valuedata,$valuename='value') {
2071 * Returns a wikitext link to the DB's website, e.g.,
2072 * return "[http://www.mysql.com/ MySQL]";
2073 * Should at least contain plain text, if for some reason
2074 * your database has no website.
2076 * @return String: wikitext of a link to the server software's web site
2078 abstract function getSoftwareLink();
2081 * A string describing the current software version, like from
2082 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2084 * @return String: Version information from the database
2086 abstract function getServerVersion();
2089 * Ping the server and try to reconnect if it there is no connection
2091 * @return bool Success or failure
2094 # Stub. Not essential to override.
2100 * Currently supported only by MySQL
2101 * @return Database replication lag in seconds
2104 return $this->mFakeSlaveLag
;
2108 * Get status information from SHOW STATUS in an associative array
2110 function getStatus($which="%") {
2111 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2113 while ( $row = $this->fetchObject( $res ) ) {
2114 $status[$row->Variable_name
] = $row->Value
;
2120 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2122 function maxListLen() {
2126 function encodeBlob($b) {
2130 function decodeBlob($b) {
2135 * Override database's default connection timeout. May be useful for very
2136 * long batch queries such as full-wiki dumps, where a single query reads
2137 * out over hours or days. May or may not be necessary for non-MySQL
2138 * databases. For most purposes, leaving it as a no-op should be fine.
2140 * @param $timeout Integer in seconds
2142 public function setTimeout( $timeout ) {}
2145 * Read and execute SQL commands from a file.
2146 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2147 * @param $filename String: File name to open
2148 * @param $lineCallback Callback: Optional function called before reading each line
2149 * @param $resultCallback Callback: Optional function called for each MySQL result
2151 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2152 $fp = fopen( $filename, 'r' );
2153 if ( false === $fp ) {
2154 if (!defined("MEDIAWIKI_INSTALL"))
2155 throw new MWException( "Could not open \"{$filename}\".\n" );
2157 return "Could not open \"{$filename}\".\n";
2160 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2162 catch( MWException
$e ) {
2163 if ( defined("MEDIAWIKI_INSTALL") ) {
2164 $error = $e->getMessage();
2176 * Get the full path of a patch file. Originally based on archive()
2177 * from updaters.inc. Keep in mind this always returns a patch, as
2178 * it fails back to MySQL if no DB-specific patch can be found
2180 * @param $patch String The name of the patch, like patch-something.sql
2181 * @return String Full path to patch file
2183 public static function patchPath( $patch ) {
2184 global $wgDBtype, $IP;
2185 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2186 return "$IP/maintenance/$wgDBtype/archives/$patch";
2188 return "$IP/maintenance/archives/$patch";
2193 * Read and execute commands from an open file handle
2194 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2195 * @param $fp String: File handle
2196 * @param $lineCallback Callback: Optional function called before reading each line
2197 * @param $resultCallback Callback: Optional function called for each MySQL result
2199 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2202 $dollarquote = false;
2204 while ( ! feof( $fp ) ) {
2205 if ( $lineCallback ) {
2206 call_user_func( $lineCallback );
2208 $line = trim( fgets( $fp, 1024 ) );
2209 $sl = strlen( $line ) - 1;
2211 if ( $sl < 0 ) { continue; }
2212 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2214 ## Allow dollar quoting for function declarations
2215 if (substr($line,0,4) == '$mw$') {
2217 $dollarquote = false;
2221 $dollarquote = true;
2224 else if (!$dollarquote) {
2225 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2227 $line = substr( $line, 0, $sl );
2231 if ( $cmd != '' ) { $cmd .= ' '; }
2235 $cmd = str_replace(';;', ";", $cmd);
2236 $cmd = $this->replaceVars( $cmd );
2237 $res = $this->query( $cmd, __METHOD__
);
2238 if ( $resultCallback ) {
2239 call_user_func( $resultCallback, $res, $this );
2242 if ( false === $res ) {
2243 $err = $this->lastError();
2244 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2256 * Replace variables in sourced SQL
2258 protected function replaceVars( $ins ) {
2260 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2261 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2262 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2265 // Ordinary variables
2266 foreach ( $varnames as $var ) {
2267 if( isset( $GLOBALS[$var] ) ) {
2268 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2269 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2270 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2271 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2276 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2277 array( $this, 'tableNameCallback' ), $ins );
2280 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2281 array( $this, 'indexNameCallback' ), $ins );
2286 * Table name callback
2289 protected function tableNameCallback( $matches ) {
2290 return $this->tableName( $matches[1] );
2294 * Index name callback
2296 protected function indexNameCallback( $matches ) {
2297 return $this->indexName( $matches[1] );
2301 * Build a concatenation list to feed into a SQL query
2302 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2305 function buildConcat( $stringList ) {
2306 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2310 * Acquire a named lock
2312 * Abstracted from Filestore::lock() so child classes can implement for
2315 * @param $lockName String: name of lock to aquire
2316 * @param $method String: name of method calling us
2317 * @param $timeout Integer: timeout
2320 public function lock( $lockName, $method, $timeout = 5 ) {
2327 * @param $lockName String: Name of lock to release
2328 * @param $method String: Name of method calling us
2330 * @return Returns 1 if the lock was released, 0 if the lock was not established
2331 * by this thread (in which case the lock is not released), and NULL if the named
2332 * lock did not exist
2334 public function unlock( $lockName, $method ) {
2339 * Lock specific tables
2341 * @param $read Array of tables to lock for read access
2342 * @param $write Array of tables to lock for write access
2343 * @param $method String name of caller
2344 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2346 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2351 * Unlock specific tables
2353 * @param $method String the caller
2355 public function unlockTables( $method ) {
2360 * Get search engine class. All subclasses of this need to implement this
2361 * if they wish to use searching.
2365 public function getSearchEngine() {
2366 return 'SearchEngineDummy';
2370 * Allow or deny "big selects" for this session only. This is done by setting
2371 * the sql_big_selects session variable.
2373 * This is a MySQL-specific feature.
2375 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2377 public function setBigSelects( $value = true ) {
2383 /******************************************************************************
2385 *****************************************************************************/
2394 function DBObject($data) {
2395 $this->mData
= $data;
2403 return $this->mData
;
2411 * This allows us to distinguish a blob from a normal string and an array of strings
2415 function __construct($data) {
2416 $this->mData
= $data;
2419 return $this->mData
;
2428 private $name, $tablename, $default, $max_length, $nullable,
2429 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2430 function __construct ($info) {
2431 $this->name
= $info->name
;
2432 $this->tablename
= $info->table
;
2433 $this->default = $info->def
;
2434 $this->max_length
= $info->max_length
;
2435 $this->nullable
= !$info->not_null
;
2436 $this->is_pk
= $info->primary_key
;
2437 $this->is_unique
= $info->unique_key
;
2438 $this->is_multiple
= $info->multiple_key
;
2439 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2440 $this->type
= $info->type
;
2447 function tableName() {
2448 return $this->tableName
;
2451 function defaultValue() {
2452 return $this->default;
2455 function maxLength() {
2456 return $this->max_length
;
2459 function nullable() {
2460 return $this->nullable
;
2464 return $this->is_key
;
2467 function isMultipleKey() {
2468 return $this->is_multiple
;
2476 /******************************************************************************
2478 *****************************************************************************/
2481 * Database error base class
2484 class DBError
extends MWException
{
2488 * Construct a database error
2489 * @param $db Database object which threw the error
2490 * @param $error A simple error message to be used for debugging
2492 function __construct( DatabaseBase
&$db, $error ) {
2494 parent
::__construct( $error );
2497 function getText() {
2498 global $wgShowDBErrorBacktrace;
2499 $s = $this->getMessage() . "\n";
2500 if ( $wgShowDBErrorBacktrace ) {
2501 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2510 class DBConnectionError
extends DBError
{
2513 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2514 $msg = 'DB connection error';
2515 if ( trim( $error ) != '' ) {
2518 $this->error
= $error;
2519 parent
::__construct( $db, $msg );
2522 function useOutputPage() {
2523 // Not likely to work
2527 function useMessageCache() {
2528 // Not likely to work
2532 function getLogMessage() {
2533 # Don't send to the exception log
2537 function getPageTitle() {
2538 global $wgSitename, $wgLang;
2539 $header = "$wgSitename has a problem";
2540 if ( $wgLang instanceof Language
) {
2541 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2547 function getHTML() {
2548 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2550 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2551 $again = 'Try waiting a few minutes and reloading.';
2552 $info = '(Can\'t contact the database server: $1)';
2554 if ( $wgLang instanceof Language
) {
2555 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2556 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2557 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2560 # No database access
2561 if ( is_object( $wgMessageCache ) ) {
2562 $wgMessageCache->disable();
2565 if ( trim( $this->error
) == '' ) {
2566 $this->error
= $this->db
->getProperty('mServer');
2569 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2570 $text = str_replace( '$1', $this->error
, $noconnect );
2572 if ( $wgShowDBErrorBacktrace ) {
2573 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2576 $extra = $this->searchForm();
2578 if( $wgUseFileCache ) {
2580 $cache = $this->fileCachedPage();
2581 # Cached version on file system?
2582 if( $cache !== null ) {
2583 # Hack: extend the body for error messages
2584 $cache = str_replace( array('</html>','</body>'), '', $cache );
2585 # Add cache notice...
2586 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2587 # Localize it if possible...
2588 if( $wgLang instanceof Language
) {
2589 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2591 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2592 # Output cached page with notices on bottom and re-close body
2593 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2595 } catch( MWException
$e ) {
2596 // Do nothing, just use the default page
2599 # Headers needed here - output is just the error message
2600 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2603 function searchForm() {
2604 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2605 $usegoogle = "You can try searching via Google in the meantime.";
2606 $outofdate = "Note that their indexes of our content may be out of date.";
2607 $googlesearch = "Search";
2609 if ( $wgLang instanceof Language
) {
2610 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2611 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2612 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2615 $search = htmlspecialchars(@$_REQUEST['search']);
2618 <div style="margin: 1.5em">$usegoogle<br />
2619 <small>$outofdate</small></div>
2620 <!-- SiteSearch Google -->
2621 <form method="get" action="http://www.google.com/search" id="googlesearch">
2622 <input type="hidden" name="domains" value="$wgServer" />
2623 <input type="hidden" name="num" value="50" />
2624 <input type="hidden" name="ie" value="$wgInputEncoding" />
2625 <input type="hidden" name="oe" value="$wgInputEncoding" />
2627 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2628 <input type="submit" name="btnG" value="$googlesearch" />
2630 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2631 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2634 <!-- SiteSearch Google -->
2639 function fileCachedPage() {
2640 global $wgTitle, $title, $wgLang, $wgOut;
2641 if( $wgOut->isDisabled() ) return; // Done already?
2642 $mainpage = 'Main Page';
2643 if ( $wgLang instanceof Language
) {
2644 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2649 } elseif( $title ) {
2650 $t = Title
::newFromURL( $title );
2652 $t = Title
::newFromText( $mainpage );
2655 $cache = new HTMLFileCache( $t );
2656 if( $cache->isFileCached() ) {
2657 return $cache->fetchPageText();
2663 function htmlBodyOnly() {
2672 class DBQueryError
extends DBError
{
2673 public $error, $errno, $sql, $fname;
2675 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2676 $message = "A database error has occurred\n" .
2678 "Function: $fname\n" .
2679 "Error: $errno $error\n";
2681 parent
::__construct( $db, $message );
2682 $this->error
= $error;
2683 $this->errno
= $errno;
2685 $this->fname
= $fname;
2688 function getText() {
2689 global $wgShowDBErrorBacktrace;
2690 if ( $this->useMessageCache() ) {
2691 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2692 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2693 if ( $wgShowDBErrorBacktrace ) {
2694 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2698 return parent
::getText();
2703 global $wgShowSQLErrors;
2704 if( !$wgShowSQLErrors ) {
2705 return $this->msg( 'sqlhidden', 'SQL hidden' );
2711 function getLogMessage() {
2712 # Don't send to the exception log
2716 function getPageTitle() {
2717 return $this->msg( 'databaseerror', 'Database error' );
2720 function getHTML() {
2721 global $wgShowDBErrorBacktrace;
2722 if ( $this->useMessageCache() ) {
2723 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2724 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2726 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2728 if ( $wgShowDBErrorBacktrace ) {
2729 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2738 class DBUnexpectedError
extends DBError
{}
2742 * Result wrapper for grabbing data queried by someone else
2745 class ResultWrapper
implements Iterator
{
2746 var $db, $result, $pos = 0, $currentRow = null;
2749 * Create a new result object from a result resource and a Database object
2751 function ResultWrapper( $database, $result ) {
2752 $this->db
= $database;
2753 if ( $result instanceof ResultWrapper
) {
2754 $this->result
= $result->result
;
2756 $this->result
= $result;
2761 * Get the number of rows in a result object
2763 function numRows() {
2764 return $this->db
->numRows( $this );
2768 * Fetch the next row from the given result object, in object form.
2769 * Fields can be retrieved with $row->fieldname, with fields acting like
2772 * @return MySQL row object
2773 * @throws DBUnexpectedError Thrown if the database returns an error
2775 function fetchObject() {
2776 return $this->db
->fetchObject( $this );
2780 * Fetch the next row from the given result object, in associative array
2781 * form. Fields are retrieved with $row['fieldname'].
2783 * @return MySQL row object
2784 * @throws DBUnexpectedError Thrown if the database returns an error
2786 function fetchRow() {
2787 return $this->db
->fetchRow( $this );
2791 * Free a result object
2794 $this->db
->freeResult( $this );
2795 unset( $this->result
);
2800 * Change the position of the cursor in a result object
2801 * See mysql_data_seek()
2803 function seek( $row ) {
2804 $this->db
->dataSeek( $this, $row );
2807 /*********************
2808 * Iterator functions
2809 * Note that using these in combination with the non-iterator functions
2810 * above may cause rows to be skipped or repeated.
2814 if ($this->numRows()) {
2815 $this->db
->dataSeek($this, 0);
2818 $this->currentRow
= null;
2821 function current() {
2822 if ( is_null( $this->currentRow
) ) {
2825 return $this->currentRow
;
2834 $this->currentRow
= $this->fetchObject();
2835 return $this->currentRow
;
2839 return $this->current() !== false;
2843 /* Overloads the relevant methods of the real ResultsWrapper so it
2844 * doesn't go anywhere near an actual database.
2846 class FakeResultWrapper
extends ResultWrapper
{
2848 var $result = array();
2849 var $db = null; // And it's going to stay that way :D
2851 var $currentRow = null;
2853 function __construct( $array ){
2854 $this->result
= $array;
2857 function numRows() {
2858 return count( $this->result
);
2861 function fetchRow() {
2862 $this->currentRow
= $this->result
[$this->pos++
];
2863 return $this->currentRow
;
2866 function seek( $row ) {
2872 // Callers want to be able to access fields with $this->fieldName
2873 function fetchObject(){
2874 $this->currentRow
= $this->result
[$this->pos++
];
2875 return (object)$this->currentRow
;
2880 $this->currentRow
= null;
2885 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2886 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2891 public function __construct( $s ) {
2895 public function toString() {