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 $mTablePrefix;
37 protected $mTrxLevel = 0;
38 protected $mErrorCount = 0;
39 protected $mLBInfo = array();
40 protected $mFakeSlaveLag = null, $mFakeMaster = false;
41 protected $mDefaultBigSelects = null;
43 #------------------------------------------------------------------------------
45 #------------------------------------------------------------------------------
46 # These optionally set a variable and return the previous state
49 * Boolean, controls output of large amounts of debug information
51 function debug( $debug = null ) {
52 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
56 * Turns buffering of SQL result sets on (true) or off (false).
57 * Default is "on" and it should not be changed without good reasons.
59 function bufferResults( $buffer = null ) {
60 if ( is_null( $buffer ) ) {
61 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
63 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
68 * Turns on (false) or off (true) the automatic generation and sending
69 * of a "we're sorry, but there has been a database error" page on
70 * database errors. Default is on (false). When turned off, the
71 * code should use lastErrno() and lastError() to handle the
72 * situation as appropriate.
74 function ignoreErrors( $ignoreErrors = null ) {
75 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
79 * The current depth of nested transactions
80 * @param $level Integer: , default NULL.
82 function trxLevel( $level = null ) {
83 return wfSetVar( $this->mTrxLevel
, $level );
87 * Number of errors logged, only useful when errors are ignored
89 function errorCount( $count = null ) {
90 return wfSetVar( $this->mErrorCount
, $count );
93 function tablePrefix( $prefix = null ) {
94 return wfSetVar( $this->mTablePrefix
, $prefix );
98 * Properties passed down from the server info array of the load balancer
100 function getLBInfo( $name = null ) {
101 if ( is_null( $name ) ) {
102 return $this->mLBInfo
;
104 if ( array_key_exists( $name, $this->mLBInfo
) ) {
105 return $this->mLBInfo
[$name];
112 function setLBInfo( $name, $value = null ) {
113 if ( is_null( $value ) ) {
114 $this->mLBInfo
= $name;
116 $this->mLBInfo
[$name] = $value;
121 * Set lag time in seconds for a fake slave
123 function setFakeSlaveLag( $lag ) {
124 $this->mFakeSlaveLag
= $lag;
128 * Make this connection a fake master
130 function setFakeMaster( $enabled = true ) {
131 $this->mFakeMaster
= $enabled;
135 * Returns true if this database supports (and uses) cascading deletes
137 function cascadingDeletes() {
142 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
144 function cleanupTriggers() {
149 * Returns true if this database is strict about what can be put into an IP field.
150 * Specifically, it uses a NULL value instead of an empty string.
152 function strictIPs() {
157 * Returns true if this database uses timestamps rather than integers
159 function realTimestamps() {
164 * Returns true if this database does an implicit sort when doing GROUP BY
166 function implicitGroupby() {
171 * Returns true if this database does an implicit order by when the column has an index
172 * For example: SELECT page_title FROM page LIMIT 1
174 function implicitOrderby() {
179 * Returns true if this database requires that SELECT DISTINCT queries require that all
180 ORDER BY expressions occur in the SELECT list per the SQL92 standard
182 function standardSelectDistinct() {
187 * Returns true if this database can do a native search on IP columns
188 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
190 function searchableIPs() {
195 * Returns true if this database can use functional indexes
197 function functionalIndexes() {
202 * Return the last query that went through Database::query()
205 function lastQuery() { return $this->mLastQuery
; }
209 * Returns true if the connection may have been used for write queries.
210 * Should return true if unsure.
212 function doneWrites() { return $this->mDoneWrites
; }
215 * Is a connection to the database open?
218 function isOpen() { return $this->mOpened
; }
221 * Set a flag for this connection
223 * @param $flag Integer: DBO_* constants from Defines.php:
224 * - DBO_DEBUG: output some debug info (same as debug())
225 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
226 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
227 * - DBO_TRX: automatically start transactions
228 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
229 * and removes it in command line mode
230 * - DBO_PERSISTENT: use persistant database connection
232 function setFlag( $flag ) {
233 $this->mFlags |
= $flag;
237 * Clear a flag for this connection
239 * @param $flag: same as setFlag()'s $flag param
241 function clearFlag( $flag ) {
242 $this->mFlags
&= ~
$flag;
246 * Returns a boolean whether the flag $flag is set for this connection
248 * @param $flag: same as setFlag()'s $flag param
251 function getFlag( $flag ) {
252 return !!($this->mFlags
& $flag);
256 * General read-only accessor
258 function getProperty( $name ) {
262 function getWikiID() {
263 if( $this->mTablePrefix
) {
264 return "{$this->mDBname}-{$this->mTablePrefix}";
266 return $this->mDBname
;
271 * Get the type of the DBMS, as it appears in $wgDBtype.
273 abstract function getType();
275 #------------------------------------------------------------------------------
277 #------------------------------------------------------------------------------
281 * @param $server String: database server host
282 * @param $user String: database user name
283 * @param $password String: database user password
284 * @param $dbName String: database name
286 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
288 function __construct( $server = false, $user = false, $password = false, $dbName = false,
289 $flags = 0, $tablePrefix = 'get from global' ) {
291 global $wgOut, $wgDBprefix, $wgCommandLineMode;
292 # Can't get a reference if it hasn't been set yet
293 if ( !isset( $wgOut ) ) {
297 $this->mFlags
= $flags;
299 if ( $this->mFlags
& DBO_DEFAULT
) {
300 if ( $wgCommandLineMode ) {
301 $this->mFlags
&= ~DBO_TRX
;
303 $this->mFlags |
= DBO_TRX
;
308 // Faster read-only access
309 if ( wfReadOnly() ) {
310 $this->mFlags |= DBO_PERSISTENT;
311 $this->mFlags &= ~DBO_TRX;
314 /** Get the default table prefix*/
315 if ( $tablePrefix == 'get from global' ) {
316 $this->mTablePrefix
= $wgDBprefix;
318 $this->mTablePrefix
= $tablePrefix;
322 $this->open( $server, $user, $password, $dbName );
327 * Same as new DatabaseMysql( ... ), kept for backward compatibility
328 * @param $server String: database server host
329 * @param $user String: database user name
330 * @param $password String: database user password
331 * @param $dbName String: database name
334 static function newFromParams( $server, $user, $password, $dbName, $flags = 0 )
336 wfDeprecated( __METHOD__
);
337 return new DatabaseMysql( $server, $user, $password, $dbName, $flags );
341 * Usually aborts on failure
342 * @param $server String: database server host
343 * @param $user String: database user name
344 * @param $password String: database user password
345 * @param $dbName String: database name
347 abstract function open( $server, $user, $password, $dbName );
349 protected function installErrorHandler() {
350 $this->mPHPError
= false;
351 $this->htmlErrors
= ini_set( 'html_errors', '0' );
352 set_error_handler( array( $this, 'connectionErrorHandler' ) );
355 protected function restoreErrorHandler() {
356 restore_error_handler();
357 if ( $this->htmlErrors
!== false ) {
358 ini_set( 'html_errors', $this->htmlErrors
);
360 if ( $this->mPHPError
) {
361 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
362 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
369 protected function connectionErrorHandler( $errno, $errstr ) {
370 $this->mPHPError
= $errstr;
374 * Closes a database connection.
375 * if it is open : commits any open transactions
377 * @return Bool operation success. true if already closed.
380 # Stub, should probably be overridden
385 * @param $error String: fallback error message, used if none is given by DB
387 function reportConnectionError( $error = 'Unknown error' ) {
388 $myError = $this->lastError();
393 throw new DBConnectionError( $this, $error );
397 * Determine whether a query writes to the DB.
398 * Should return true if unsure.
400 function isWriteQuery( $sql ) {
401 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
405 * Usually aborts on failure. If errors are explicitly ignored, returns success.
407 * @param $sql String: SQL query
408 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
409 * comment (you can use __METHOD__ or add some extra info)
410 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
411 * maybe best to catch the exception instead?
412 * @return true for a successful write query, ResultWrapper object for a successful read query,
413 * or false on failure if $tempIgnore set
414 * @throws DBQueryError Thrown when the database returns an error of any kind
416 public function query( $sql, $fname = '', $tempIgnore = false ) {
419 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
420 if ( isset( $wgProfiler ) ) {
421 # generalizeSQL will probably cut down the query to reasonable
422 # logging size most of the time. The substr is really just a sanity check.
424 # Who's been wasting my precious column space? -- TS
425 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
428 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
429 $totalProf = 'Database::query-master';
431 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
432 $totalProf = 'Database::query';
434 wfProfileIn( $totalProf );
435 wfProfileIn( $queryProf );
438 $this->mLastQuery
= $sql;
439 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
440 // Set a flag indicating that writes have been done
441 wfDebug( __METHOD__
.": Writes done: $sql\n" );
442 $this->mDoneWrites
= true;
445 # Add a comment for easy SHOW PROCESSLIST interpretation
448 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
449 $userName = $wgUser->getName();
450 if ( mb_strlen( $userName ) > 15 ) {
451 $userName = mb_substr( $userName, 0, 15 ) . '...';
453 $userName = str_replace( '/', '', $userName );
457 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
459 # $commentedSql = $sql;
462 # If DBO_TRX is set, start a transaction
463 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
464 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
465 // avoid establishing transactions for SHOW and SET statements too -
466 // that would delay transaction initializations to once connection
467 // is really used by application
468 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
469 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
473 if ( $this->debug() ) {
476 $sqlx = substr( $commentedSql, 0, 500 );
477 $sqlx = strtr( $sqlx, "\t\n", ' ' );
479 wfDebug( "Query $cnt (master): $sqlx\n" );
481 wfDebug( "Query $cnt (slave): $sqlx\n" );
485 if ( istainted( $sql ) & TC_MYSQL
) {
486 throw new MWException( 'Tainted query found' );
489 # Do the query and handle errors
490 $ret = $this->doQuery( $commentedSql );
492 # Try reconnecting if the connection was lost
493 if ( false === $ret && $this->wasErrorReissuable() ) {
494 # Transaction is gone, like it or not
495 $this->mTrxLevel
= 0;
496 wfDebug( "Connection lost, reconnecting...\n" );
497 if ( $this->ping() ) {
498 wfDebug( "Reconnected\n" );
499 $sqlx = substr( $commentedSql, 0, 500 );
500 $sqlx = strtr( $sqlx, "\t\n", ' ' );
501 global $wgRequestTime;
502 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
503 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
504 $ret = $this->doQuery( $commentedSql );
506 wfDebug( "Failed\n" );
510 if ( false === $ret ) {
511 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
514 if ( isset( $wgProfiler ) ) {
515 wfProfileOut( $queryProf );
516 wfProfileOut( $totalProf );
518 return $this->resultObject( $ret );
522 * The DBMS-dependent part of query()
523 * @param $sql String: SQL query.
524 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
527 /*private*/ abstract function doQuery( $sql );
530 * @param $error String
531 * @param $errno Integer
533 * @param $fname String
534 * @param $tempIgnore Boolean
536 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
537 # Ignore errors during error handling to avoid infinite recursion
538 $ignore = $this->ignoreErrors( true );
539 ++
$this->mErrorCount
;
541 if( $ignore ||
$tempIgnore ) {
542 wfDebug("SQL ERROR (ignored): $error\n");
543 $this->ignoreErrors( $ignore );
545 $sql1line = str_replace( "\n", "\\n", $sql );
546 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
547 wfDebug("SQL ERROR: " . $error . "\n");
548 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
554 * Intended to be compatible with the PEAR::DB wrapper functions.
555 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
557 * ? = scalar value, quoted as necessary
558 * ! = raw SQL bit (a function for instance)
559 * & = filename; reads the file and inserts as a blob
560 * (we don't use this though...)
562 function prepare( $sql, $func = 'Database::prepare' ) {
563 /* MySQL doesn't support prepared statements (yet), so just
564 pack up the query for reference. We'll manually replace
566 return array( 'query' => $sql, 'func' => $func );
569 function freePrepared( $prepared ) {
570 /* No-op by default */
574 * Execute a prepared query with the various arguments
575 * @param $prepared String: the prepared sql
576 * @param $args Mixed: Either an array here, or put scalars as varargs
578 function execute( $prepared, $args = null ) {
579 if( !is_array( $args ) ) {
581 $args = func_get_args();
582 array_shift( $args );
584 $sql = $this->fillPrepared( $prepared['query'], $args );
585 return $this->query( $sql, $prepared['func'] );
589 * Prepare & execute an SQL statement, quoting and inserting arguments
590 * in the appropriate places.
591 * @param $query String
594 function safeQuery( $query, $args = null ) {
595 $prepared = $this->prepare( $query, 'Database::safeQuery' );
596 if( !is_array( $args ) ) {
598 $args = func_get_args();
599 array_shift( $args );
601 $retval = $this->execute( $prepared, $args );
602 $this->freePrepared( $prepared );
607 * For faking prepared SQL statements on DBs that don't support
609 * @param $preparedQuery String: a 'preparable' SQL statement
610 * @param $args Array of arguments to fill it with
611 * @return string executable SQL
613 function fillPrepared( $preparedQuery, $args ) {
615 $this->preparedArgs
=& $args;
616 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
617 array( &$this, 'fillPreparedArg' ), $preparedQuery );
621 * preg_callback func for fillPrepared()
622 * The arguments should be in $this->preparedArgs and must not be touched
623 * while we're doing this.
625 * @param $matches Array
629 function fillPreparedArg( $matches ) {
630 switch( $matches[1] ) {
631 case '\\?': return '?';
632 case '\\!': return '!';
633 case '\\&': return '&';
635 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
636 switch( $matches[1] ) {
637 case '?': return $this->addQuotes( $arg );
638 case '!': return $arg;
640 # return $this->addQuotes( file_get_contents( $arg ) );
641 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
643 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
648 * Free a result object
649 * @param $res Mixed: A SQL result
651 function freeResult( $res ) {
652 # Stub. Might not really need to be overridden, since results should
653 # be freed by PHP when the variable goes out of scope anyway.
657 * Fetch the next row from the given result object, in object form.
658 * Fields can be retrieved with $row->fieldname, with fields acting like
661 * @param $res SQL result object as returned from Database::query(), etc.
663 * @throws DBUnexpectedError Thrown if the database returns an error
665 abstract function fetchObject( $res );
668 * Fetch the next row from the given result object, in associative array
669 * form. Fields are retrieved with $row['fieldname'].
671 * @param $res SQL result object as returned from Database::query(), etc.
673 * @throws DBUnexpectedError Thrown if the database returns an error
675 abstract function fetchRow( $res );
678 * Get the number of rows in a result object
679 * @param $res Mixed: A SQL result
681 abstract function numRows( $res );
684 * Get the number of fields in a result object
685 * See documentation for mysql_num_fields()
686 * @param $res Mixed: A SQL result
688 abstract function numFields( $res );
691 * Get a field name in a result object
692 * See documentation for mysql_field_name():
693 * http://www.php.net/mysql_field_name
694 * @param $res Mixed: A SQL result
697 abstract function fieldName( $res, $n );
700 * Get the inserted value of an auto-increment row
702 * The value inserted should be fetched from nextSequenceValue()
705 * $id = $dbw->nextSequenceValue('page_page_id_seq');
706 * $dbw->insert('page',array('page_id' => $id));
707 * $id = $dbw->insertId();
709 abstract function insertId();
712 * Change the position of the cursor in a result object
713 * See mysql_data_seek()
714 * @param $res Mixed: A SQL result
715 * @param $row Mixed: Either MySQL row or ResultWrapper
717 abstract function dataSeek( $res, $row );
720 * Get the last error number
723 abstract function lastErrno();
726 * Get a description of the last error
727 * See mysql_error() for more details
729 abstract function lastError();
732 * Get the number of rows affected by the last write query
733 * See mysql_affected_rows() for more details
735 abstract function affectedRows();
738 * Simple UPDATE wrapper
739 * Usually aborts on failure
740 * If errors are explicitly ignored, returns success
742 * This function exists for historical reasons, Database::update() has a more standard
743 * calling convention and feature set
745 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
746 $table = $this->tableName( $table );
747 $sql = "UPDATE $table SET $var = '" .
748 $this->strencode( $value ) . "' WHERE ($cond)";
749 return (bool)$this->query( $sql, $fname );
753 * Simple SELECT wrapper, returns a single field, input must be encoded
754 * Usually aborts on failure
755 * If errors are explicitly ignored, returns FALSE on failure
757 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
758 if ( !is_array( $options ) ) {
759 $options = array( $options );
761 $options['LIMIT'] = 1;
763 $res = $this->select( $table, $var, $cond, $fname, $options );
764 if ( $res === false ||
!$this->numRows( $res ) ) {
767 $row = $this->fetchRow( $res );
768 if ( $row !== false ) {
769 return reset( $row );
776 * Returns an optional USE INDEX clause to go after the table, and a
777 * string to go at the end of the query
781 * @param $options Array: associative array of options to be turned into
782 * an SQL query, valid keys are listed in the function.
785 function makeSelectOptions( $options ) {
786 $preLimitTail = $postLimitTail = '';
789 $noKeyOptions = array();
790 foreach ( $options as $key => $option ) {
791 if ( is_numeric( $key ) ) {
792 $noKeyOptions[$option] = true;
796 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
797 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
798 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
800 //if (isset($options['LIMIT'])) {
801 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
802 // isset($options['OFFSET']) ? $options['OFFSET']
806 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
807 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
808 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
810 # Various MySQL extensions
811 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
812 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
813 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
814 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
815 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
816 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
817 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
818 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
820 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
821 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
826 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
832 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
833 * @param $vars Mixed: Array or string, field name(s) to be retrieved
834 * @param $conds Mixed: Array or string, condition(s) for WHERE
835 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
836 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
837 * see Database::makeSelectOptions code for list of supported stuff
838 * @param $join_conds Array: Associative array of table join conditions (optional)
839 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
840 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
842 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
844 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
845 return $this->query( $sql, $fname );
851 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
852 * @param $vars Mixed: Array or string, field name(s) to be retrieved
853 * @param $conds Mixed: Array or string, condition(s) for WHERE
854 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
855 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
856 * see Database::makeSelectOptions code for list of supported stuff
857 * @param $join_conds Array: Associative array of table join conditions (optional)
858 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
859 * @return string, the SQL text
861 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
862 if( is_array( $vars ) ) {
863 $vars = implode( ',', $vars );
865 if( !is_array( $options ) ) {
866 $options = array( $options );
868 if( is_array( $table ) ) {
869 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
870 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
872 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
873 } elseif ($table!='') {
874 if ($table{0}==' ') {
875 $from = ' FROM ' . $table;
877 $from = ' FROM ' . $this->tableName( $table );
883 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
885 if( !empty( $conds ) ) {
886 if ( is_array( $conds ) ) {
887 $conds = $this->makeList( $conds, LIST_AND
);
889 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
891 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
894 if (isset($options['LIMIT']))
895 $sql = $this->limitResult($sql, $options['LIMIT'],
896 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
897 $sql = "$sql $postLimitTail";
899 if (isset($options['EXPLAIN'])) {
900 $sql = 'EXPLAIN ' . $sql;
906 * Single row SELECT wrapper
907 * Aborts or returns FALSE on error
909 * @param $table String: table name
910 * @param $vars String: the selected variables
911 * @param $conds Array: a condition map, terms are ANDed together.
912 * Items with numeric keys are taken to be literal conditions
913 * Takes an array of selected variables, and a condition map, which is ANDed
914 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
915 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
916 * $obj- >page_id is the ID of the Astronomy article
917 * @param $fname String: Calling function name
918 * @param $options Array
919 * @param $join_conds Array
921 * @todo migrate documentation to phpdocumentor format
923 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
924 $options['LIMIT'] = 1;
925 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
926 if ( $res === false )
928 if ( !$this->numRows($res) ) {
931 $obj = $this->fetchObject( $res );
936 * Estimate rows in dataset
937 * Returns estimated count - not necessarily an accurate estimate across different databases,
939 * Takes same arguments as Database::select()
941 * @param $table String: table name
942 * @param $vars Array: unused
943 * @param $conds Array: filters on the table
944 * @param $fname String: function name for profiling
945 * @param $options Array: options for select
946 * @return Integer: row count
948 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
950 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
952 $row = $this->fetchRow( $res );
953 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
959 * Removes most variables from an SQL query and replaces them with X or N for numbers.
960 * It's only slightly flawed. Don't use for anything important.
962 * @param $sql String: A SQL Query
964 static function generalizeSQL( $sql ) {
965 # This does the same as the regexp below would do, but in such a way
966 # as to avoid crashing php on some large strings.
967 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
969 $sql = str_replace ( "\\\\", '', $sql);
970 $sql = str_replace ( "\\'", '', $sql);
971 $sql = str_replace ( "\\\"", '', $sql);
972 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
973 $sql = preg_replace ('/".*"/s', "'X'", $sql);
975 # All newlines, tabs, etc replaced by single space
976 $sql = preg_replace ( '/\s+/', ' ', $sql);
979 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
985 * Determines whether a field exists in a table
987 * @param $table String: table name
988 * @param $field String: filed to check on that table
989 * @param $fname String: calling function name (optional)
990 * @return Boolean: whether $table has filed $field
992 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
993 $info = $this->fieldInfo( $table, $field );
998 * Determines whether an index exists
999 * Usually aborts on failure
1000 * If errors are explicitly ignored, returns NULL on failure
1002 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1003 $info = $this->indexInfo( $table, $index, $fname );
1004 if ( is_null( $info ) ) {
1007 return $info !== false;
1013 * Get information about an index into an object
1014 * Returns false if the index does not exist
1016 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1017 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1018 # SHOW INDEX should work for 3.x and up:
1019 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1020 $table = $this->tableName( $table );
1021 $index = $this->indexName( $index );
1022 $sql = 'SHOW INDEX FROM '.$table;
1023 $res = $this->query( $sql, $fname );
1029 while ( $row = $this->fetchObject( $res ) ) {
1030 if ( $row->Key_name
== $index ) {
1035 return empty($result) ?
false : $result;
1039 * Query whether a given table exists
1041 function tableExists( $table ) {
1042 $table = $this->tableName( $table );
1043 $old = $this->ignoreErrors( true );
1044 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1045 $this->ignoreErrors( $old );
1050 * mysql_fetch_field() wrapper
1051 * Returns false if the field doesn't exist
1056 abstract function fieldInfo( $table, $field );
1059 * mysql_field_type() wrapper
1061 function fieldType( $res, $index ) {
1062 if ( $res instanceof ResultWrapper
) {
1063 $res = $res->result
;
1065 return mysql_field_type( $res, $index );
1069 * Determines if a given index is unique
1071 function indexUnique( $table, $index ) {
1072 $indexInfo = $this->indexInfo( $table, $index );
1073 if ( !$indexInfo ) {
1076 return !$indexInfo[0]->Non_unique
;
1080 * INSERT wrapper, inserts an array into a table
1082 * $a may be a single associative array, or an array of these with numeric keys, for
1085 * Usually aborts on failure
1086 * If errors are explicitly ignored, returns success
1088 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1089 # No rows to insert, easy just return now
1090 if ( !count( $a ) ) {
1094 $table = $this->tableName( $table );
1095 if ( !is_array( $options ) ) {
1096 $options = array( $options );
1098 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1100 $keys = array_keys( $a[0] );
1103 $keys = array_keys( $a );
1106 $sql = 'INSERT ' . implode( ' ', $options ) .
1107 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1111 foreach ( $a as $row ) {
1117 $sql .= '(' . $this->makeList( $row ) . ')';
1120 $sql .= '(' . $this->makeList( $a ) . ')';
1122 return (bool)$this->query( $sql, $fname );
1126 * Make UPDATE options for the Database::update function
1129 * @param $options Array: The options passed to Database::update
1132 function makeUpdateOptions( $options ) {
1133 if( !is_array( $options ) ) {
1134 $options = array( $options );
1137 if ( in_array( 'LOW_PRIORITY', $options ) )
1138 $opts[] = $this->lowPriorityOption();
1139 if ( in_array( 'IGNORE', $options ) )
1141 return implode(' ', $opts);
1145 * UPDATE wrapper, takes a condition array and a SET array
1147 * @param $table String: The table to UPDATE
1148 * @param $values Array: An array of values to SET
1149 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1150 * @param $fname String: The Class::Function calling this function
1152 * @param $options Array: An array of UPDATE options, can be one or
1153 * more of IGNORE, LOW_PRIORITY
1156 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1157 $table = $this->tableName( $table );
1158 $opts = $this->makeUpdateOptions( $options );
1159 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1160 if ( $conds != '*' ) {
1161 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1163 return $this->query( $sql, $fname );
1167 * Makes an encoded list of strings from an array
1169 * LIST_COMMA - comma separated, no field names
1170 * LIST_AND - ANDed WHERE clause (without the WHERE)
1171 * LIST_OR - ORed WHERE clause (without the WHERE)
1172 * LIST_SET - comma separated with field names, like a SET clause
1173 * LIST_NAMES - comma separated field names
1175 function makeList( $a, $mode = LIST_COMMA
) {
1176 if ( !is_array( $a ) ) {
1177 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1182 foreach ( $a as $field => $value ) {
1184 if ( $mode == LIST_AND
) {
1186 } elseif($mode == LIST_OR
) {
1194 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1195 $list .= "($value)";
1196 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1198 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1199 if( count( $value ) == 0 ) {
1200 throw new MWException( __METHOD__
.': empty input' );
1201 } elseif( count( $value ) == 1 ) {
1202 // Special-case single values, as IN isn't terribly efficient
1203 // Don't necessarily assume the single key is 0; we don't
1204 // enforce linear numeric ordering on other arrays here.
1205 $value = array_values( $value );
1206 $list .= $field." = ".$this->addQuotes( $value[0] );
1208 $list .= $field." IN (".$this->makeList($value).") ";
1210 } elseif( $value === null ) {
1211 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1212 $list .= "$field IS ";
1213 } elseif ( $mode == LIST_SET
) {
1214 $list .= "$field = ";
1218 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1219 $list .= "$field = ";
1221 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1228 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1229 * The keys on each level may be either integers or strings.
1231 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1232 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1233 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1234 * @return Mixed: string SQL fragment, or false if no items in array.
1236 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1238 foreach ( $data as $base => $sub ) {
1239 if ( count( $sub ) ) {
1240 $conds[] = $this->makeList(
1241 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1247 return $this->makeList( $conds, LIST_OR
);
1249 // Nothing to search for...
1255 * Bitwise operations
1258 function bitNot($field) {
1262 function bitAnd($fieldLeft, $fieldRight) {
1263 return "($fieldLeft & $fieldRight)";
1266 function bitOr($fieldLeft, $fieldRight) {
1267 return "($fieldLeft | $fieldRight)";
1271 * Change the current database
1273 * @return bool Success or failure
1275 function selectDB( $db ) {
1276 # Stub. Shouldn't cause serious problems if it's not overridden, but
1277 # if your database engine supports a concept similar to MySQL's
1278 # databases you may as well. TODO: explain what exactly will fail if
1279 # this is not overridden.
1284 * Get the current DB name
1286 function getDBname() {
1287 return $this->mDBname
;
1291 * Get the server hostname or IP address
1293 function getServer() {
1294 return $this->mServer
;
1298 * Format a table name ready for use in constructing an SQL query
1300 * This does two important things: it quotes the table names to clean them up,
1301 * and it adds a table prefix if only given a table name with no quotes.
1303 * All functions of this object which require a table name call this function
1304 * themselves. Pass the canonical name to such functions. This is only needed
1305 * when calling query() directly.
1307 * @param $name String: database table name
1308 * @return String: full database name
1310 function tableName( $name ) {
1311 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1312 # Skip the entire process when we have a string quoted on both ends.
1313 # Note that we check the end so that we will still quote any use of
1314 # use of `database`.table. But won't break things if someone wants
1315 # to query a database table with a dot in the name.
1316 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1318 # Lets test for any bits of text that should never show up in a table
1319 # name. Basically anything like JOIN or ON which are actually part of
1320 # SQL queries, but may end up inside of the table value to combine
1321 # sql. Such as how the API is doing.
1322 # Note that we use a whitespace test rather than a \b test to avoid
1323 # any remote case where a word like on may be inside of a table name
1324 # surrounded by symbols which may be considered word breaks.
1325 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1327 # Split database and table into proper variables.
1328 # We reverse the explode so that database.table and table both output
1329 # the correct table.
1330 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1331 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1332 else @list
( $table ) = $dbDetails;
1333 $prefix = $this->mTablePrefix
; # Default prefix
1335 # A database name has been specified in input. Quote the table name
1336 # because we don't want any prefixes added.
1337 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1339 # Note that we use the long format because php will complain in in_array if
1340 # the input is not an array, and will complain in is_array if it is not set.
1341 if( !isset( $database ) # Don't use shared database if pre selected.
1342 && isset( $wgSharedDB ) # We have a shared database
1343 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1344 && isset( $wgSharedTables )
1345 && is_array( $wgSharedTables )
1346 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1347 $database = $wgSharedDB;
1348 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1351 # Quote the $database and $table and apply the prefix if not quoted.
1352 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1353 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1355 # Merge our database and table into our final table name.
1356 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1358 # We're finished, return.
1363 * Fetch a number of table names into an array
1364 * This is handy when you need to construct SQL for joins
1367 * extract($dbr->tableNames('user','watchlist'));
1368 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1369 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1371 public function tableNames() {
1372 $inArray = func_get_args();
1374 foreach ( $inArray as $name ) {
1375 $retVal[$name] = $this->tableName( $name );
1381 * Fetch a number of table names into an zero-indexed numerical array
1382 * This is handy when you need to construct SQL for joins
1385 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1386 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1387 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1389 public function tableNamesN() {
1390 $inArray = func_get_args();
1392 foreach ( $inArray as $name ) {
1393 $retVal[] = $this->tableName( $name );
1401 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1404 $use_index_safe = is_array($use_index) ?
$use_index : array();
1405 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1406 foreach ( $tables as $table ) {
1407 // Is there a JOIN and INDEX clause for this table?
1408 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1409 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1410 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1411 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1413 $tableClause .= ' ON (' . $on . ')';
1415 $retJOIN[] = $tableClause;
1416 // Is there an INDEX clause?
1417 } else if ( isset($use_index_safe[$table]) ) {
1418 $tableClause = $this->tableName( $table );
1419 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1420 $ret[] = $tableClause;
1421 // Is there a JOIN clause?
1422 } else if ( isset($join_conds_safe[$table]) ) {
1423 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1424 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1426 $tableClause .= ' ON (' . $on . ')';
1428 $retJOIN[] = $tableClause;
1430 $tableClause = $this->tableName( $table );
1431 $ret[] = $tableClause;
1434 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1435 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1436 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1437 // Compile our final table clause
1438 return implode(' ',array($straightJoins,$otherJoins) );
1442 * Get the name of an index in a given table
1444 function indexName( $index ) {
1445 // Backwards-compatibility hack
1447 'ar_usertext_timestamp' => 'usertext_timestamp',
1448 'un_user_id' => 'user_id',
1449 'un_user_ip' => 'user_ip',
1451 if( isset( $renamed[$index] ) ) {
1452 return $renamed[$index];
1459 * Wrapper for addslashes()
1460 * @param $s String: to be slashed.
1461 * @return String: slashed string.
1463 abstract function strencode( $s );
1466 * If it's a string, adds quotes and backslashes
1467 * Otherwise returns as-is
1469 function addQuotes( $s ) {
1470 if ( $s === null ) {
1473 # This will also quote numeric values. This should be harmless,
1474 # and protects against weird problems that occur when they really
1475 # _are_ strings such as article titles and string->number->string
1476 # conversion is not 1:1.
1477 return "'" . $this->strencode( $s ) . "'";
1482 * Escape string for safe LIKE usage.
1483 * WARNING: you should almost never use this function directly,
1484 * instead use buildLike() that escapes everything automatically
1485 * Deprecated in 1.17, warnings in 1.17, removed in ???
1487 public function escapeLike( $s ) {
1488 wfDeprecated( __METHOD__
);
1489 return $this->escapeLikeInternal( $s );
1492 protected function escapeLikeInternal( $s ) {
1493 $s = str_replace( '\\', '\\\\', $s );
1494 $s = $this->strencode( $s );
1495 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1500 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1501 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1502 * Alternatively, the function could be provided with an array of aforementioned parameters.
1504 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1505 * for subpages of 'My page title'.
1506 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1509 * @return String: fully built LIKE statement
1511 function buildLike() {
1512 $params = func_get_args();
1513 if (count($params) > 0 && is_array($params[0])) {
1514 $params = $params[0];
1518 foreach( $params as $value) {
1519 if( $value instanceof LikeMatch
) {
1520 $s .= $value->toString();
1522 $s .= $this->escapeLikeInternal( $value );
1525 return " LIKE '" . $s . "' ";
1529 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1531 function anyChar() {
1532 return new LikeMatch( '_' );
1536 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1538 function anyString() {
1539 return new LikeMatch( '%' );
1543 * Returns an appropriately quoted sequence value for inserting a new row.
1544 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1545 * subclass will return an integer, and save the value for insertId()
1547 function nextSequenceValue( $seqName ) {
1552 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1553 * is only needed because a) MySQL must be as efficient as possible due to
1554 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1555 * which index to pick. Anyway, other databases might have different
1556 * indexes on a given table. So don't bother overriding this unless you're
1559 function useIndexClause( $index ) {
1564 * REPLACE query wrapper
1565 * PostgreSQL simulates this with a DELETE followed by INSERT
1566 * $row is the row to insert, an associative array
1567 * $uniqueIndexes is an array of indexes. Each element may be either a
1568 * field name or an array of field names
1570 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1571 * However if you do this, you run the risk of encountering errors which wouldn't have
1574 * @todo migrate comment to phodocumentor format
1576 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1577 $table = $this->tableName( $table );
1580 if ( !is_array( reset( $rows ) ) ) {
1581 $rows = array( $rows );
1584 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1586 foreach ( $rows as $row ) {
1592 $sql .= '(' . $this->makeList( $row ) . ')';
1594 return $this->query( $sql, $fname );
1598 * DELETE where the condition is a join
1599 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1601 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1602 * join condition matches, set $conds='*'
1604 * DO NOT put the join condition in $conds
1606 * @param $delTable String: The table to delete from.
1607 * @param $joinTable String: The other table.
1608 * @param $delVar String: The variable to join on, in the first table.
1609 * @param $joinVar String: The variable to join on, in the second table.
1610 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1611 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1613 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1615 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1618 $delTable = $this->tableName( $delTable );
1619 $joinTable = $this->tableName( $joinTable );
1620 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1621 if ( $conds != '*' ) {
1622 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1625 return $this->query( $sql, $fname );
1629 * Returns the size of a text field, or -1 for "unlimited"
1631 function textFieldSize( $table, $field ) {
1632 $table = $this->tableName( $table );
1633 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1634 $res = $this->query( $sql, 'Database::textFieldSize' );
1635 $row = $this->fetchObject( $res );
1638 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1647 * A string to insert into queries to show that they're low-priority, like
1648 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1649 * string and nothing bad should happen.
1651 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1653 function lowPriorityOption() {
1658 * DELETE query wrapper
1660 * Use $conds == "*" to delete all rows
1662 function delete( $table, $conds, $fname = 'Database::delete' ) {
1664 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1666 $table = $this->tableName( $table );
1667 $sql = "DELETE FROM $table";
1668 if ( $conds != '*' ) {
1669 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1671 return $this->query( $sql, $fname );
1675 * INSERT SELECT wrapper
1676 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1677 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1678 * $conds may be "*" to copy the whole table
1679 * srcTable may be an array of tables.
1681 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1682 $insertOptions = array(), $selectOptions = array() )
1684 $destTable = $this->tableName( $destTable );
1685 if ( is_array( $insertOptions ) ) {
1686 $insertOptions = implode( ' ', $insertOptions );
1688 if( !is_array( $selectOptions ) ) {
1689 $selectOptions = array( $selectOptions );
1691 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1692 if( is_array( $srcTable ) ) {
1693 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1695 $srcTable = $this->tableName( $srcTable );
1697 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1698 " SELECT $startOpts " . implode( ',', $varMap ) .
1699 " FROM $srcTable $useIndex ";
1700 if ( $conds != '*' ) {
1701 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1703 $sql .= " $tailOpts";
1704 return $this->query( $sql, $fname );
1708 * Construct a LIMIT query with optional offset. This is used for query
1709 * pages. The SQL should be adjusted so that only the first $limit rows
1710 * are returned. If $offset is provided as well, then the first $offset
1711 * rows should be discarded, and the next $limit rows should be returned.
1712 * If the result of the query is not ordered, then the rows to be returned
1713 * are theoretically arbitrary.
1715 * $sql is expected to be a SELECT, if that makes a difference. For
1716 * UPDATE, limitResultForUpdate should be used.
1718 * The version provided by default works in MySQL and SQLite. It will very
1719 * likely need to be overridden for most other DBMSes.
1721 * @param $sql String: SQL query we will append the limit too
1722 * @param $limit Integer: the SQL limit
1723 * @param $offset Integer the SQL offset (default false)
1725 function limitResult( $sql, $limit, $offset=false ) {
1726 if( !is_numeric( $limit ) ) {
1727 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1729 return "$sql LIMIT "
1730 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1733 function limitResultForUpdate( $sql, $num ) {
1734 return $this->limitResult( $sql, $num, 0 );
1738 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1739 * within the UNION construct.
1742 function unionSupportsOrderAndLimit() {
1743 return true; // True for almost every DB supported
1747 * Construct a UNION query
1748 * This is used for providing overload point for other DB abstractions
1749 * not compatible with the MySQL syntax.
1750 * @param $sqls Array: SQL statements to combine
1751 * @param $all Boolean: use UNION ALL
1752 * @return String: SQL fragment
1754 function unionQueries($sqls, $all) {
1755 $glue = $all ?
') UNION ALL (' : ') UNION (';
1756 return '('.implode( $glue, $sqls ) . ')';
1760 * Returns an SQL expression for a simple conditional. This doesn't need
1761 * to be overridden unless CASE isn't supported in your DBMS.
1763 * @param $cond String: SQL expression which will result in a boolean value
1764 * @param $trueVal String: SQL expression to return if true
1765 * @param $falseVal String: SQL expression to return if false
1766 * @return String: SQL fragment
1768 function conditional( $cond, $trueVal, $falseVal ) {
1769 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1773 * Returns a comand for str_replace function in SQL query.
1774 * Uses REPLACE() in MySQL
1776 * @param $orig String: column to modify
1777 * @param $old String: column to seek
1778 * @param $new String: column to replace with
1780 function strreplace( $orig, $old, $new ) {
1781 return "REPLACE({$orig}, {$old}, {$new})";
1785 * Determines if the last failure was due to a deadlock
1788 function wasDeadlock() {
1793 * Determines if the last query error was something that should be dealt
1794 * with by pinging the connection and reissuing the query.
1797 function wasErrorReissuable() {
1802 * Determines if the last failure was due to the database being read-only.
1805 function wasReadOnlyError() {
1810 * Perform a deadlock-prone transaction.
1812 * This function invokes a callback function to perform a set of write
1813 * queries. If a deadlock occurs during the processing, the transaction
1814 * will be rolled back and the callback function will be called again.
1817 * $dbw->deadlockLoop( callback, ... );
1819 * Extra arguments are passed through to the specified callback function.
1821 * Returns whatever the callback function returned on its successful,
1822 * iteration, or false on error, for example if the retry limit was
1825 function deadlockLoop() {
1826 $myFname = 'Database::deadlockLoop';
1829 $args = func_get_args();
1830 $function = array_shift( $args );
1831 $oldIgnore = $this->ignoreErrors( true );
1832 $tries = DEADLOCK_TRIES
;
1833 if ( is_array( $function ) ) {
1834 $fname = $function[0];
1839 $retVal = call_user_func_array( $function, $args );
1840 $error = $this->lastError();
1841 $errno = $this->lastErrno();
1842 $sql = $this->lastQuery();
1845 if ( $this->wasDeadlock() ) {
1847 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1849 $this->reportQueryError( $error, $errno, $sql, $fname );
1852 } while( $this->wasDeadlock() && --$tries > 0 );
1853 $this->ignoreErrors( $oldIgnore );
1854 if ( $tries <= 0 ) {
1855 $this->rollback( $myFname );
1856 $this->reportQueryError( $error, $errno, $sql, $fname );
1859 $this->commit( $myFname );
1865 * Do a SELECT MASTER_POS_WAIT()
1867 * @param $pos MySQLMasterPos object
1868 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1870 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1871 $fname = 'Database::masterPosWait';
1872 wfProfileIn( $fname );
1874 # Commit any open transactions
1875 if ( $this->mTrxLevel
) {
1879 if ( !is_null( $this->mFakeSlaveLag
) ) {
1880 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1881 if ( $wait > $timeout * 1e6
) {
1882 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1883 wfProfileOut( $fname );
1885 } elseif ( $wait > 0 ) {
1886 wfDebug( "Fake slave waiting $wait us\n" );
1888 wfProfileOut( $fname );
1891 wfDebug( "Fake slave up to date ($wait us)\n" );
1892 wfProfileOut( $fname );
1897 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1898 $encFile = $this->addQuotes( $pos->file
);
1899 $encPos = intval( $pos->pos
);
1900 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1901 $res = $this->doQuery( $sql );
1902 if ( $res && $row = $this->fetchRow( $res ) ) {
1903 wfProfileOut( $fname );
1906 wfProfileOut( $fname );
1912 * Get the position of the master from SHOW SLAVE STATUS
1914 function getSlavePos() {
1915 if ( !is_null( $this->mFakeSlaveLag
) ) {
1916 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1917 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1920 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1921 $row = $this->fetchObject( $res );
1923 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1924 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1931 * Get the position of the master from SHOW MASTER STATUS
1933 function getMasterPos() {
1934 if ( $this->mFakeMaster
) {
1935 return new MySQLMasterPos( 'fake', microtime( true ) );
1937 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1938 $row = $this->fetchObject( $res );
1940 return new MySQLMasterPos( $row->File
, $row->Position
);
1947 * Begin a transaction, committing any previously open transaction
1949 function begin( $fname = 'Database::begin' ) {
1950 $this->query( 'BEGIN', $fname );
1951 $this->mTrxLevel
= 1;
1957 function commit( $fname = 'Database::commit' ) {
1958 if( $this->mTrxLevel
) {
1959 $this->query( 'COMMIT', $fname );
1960 $this->mTrxLevel
= 0;
1965 * Rollback a transaction.
1966 * No-op on non-transactional databases.
1968 function rollback( $fname = 'Database::rollback' ) {
1969 if( $this->mTrxLevel
) {
1970 $this->query( 'ROLLBACK', $fname, true );
1971 $this->mTrxLevel
= 0;
1976 * Begin a transaction, committing any previously open transaction
1977 * @deprecated use begin()
1979 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1980 wfDeprecated( __METHOD__
);
1985 * Commit transaction, if one is open
1986 * @deprecated use commit()
1988 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1989 wfDeprecated( __METHOD__
);
1994 * Creates a new table with structure copied from existing table
1995 * Note that unlike most database abstraction functions, this function does not
1996 * automatically append database prefix, because it works at a lower
1997 * abstraction level.
1999 * @param $oldName String: name of table whose structure should be copied
2000 * @param $newName String: name of table to be created
2001 * @param $temporary Boolean: whether the new table should be temporary
2002 * @param $fname String: calling function name
2003 * @return Boolean: true if operation was successful
2005 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2006 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2010 * Return MW-style timestamp used for MySQL schema
2012 function timestamp( $ts=0 ) {
2013 return wfTimestamp(TS_MW
,$ts);
2017 * Local database timestamp format or null
2019 function timestampOrNull( $ts = null ) {
2020 if( is_null( $ts ) ) {
2023 return $this->timestamp( $ts );
2030 function resultObject( $result ) {
2031 if( empty( $result ) ) {
2033 } elseif ( $result instanceof ResultWrapper
) {
2035 } elseif ( $result === true ) {
2036 // Successful write query
2039 return new ResultWrapper( $this, $result );
2044 * Return aggregated value alias
2046 function aggregateValue ($valuedata,$valuename='value') {
2051 * Returns a wikitext link to the DB's website, e.g.,
2052 * return "[http://www.mysql.com/ MySQL]";
2053 * Should at least contain plain text, if for some reason
2054 * your database has no website.
2056 * @return String: wikitext of a link to the server software's web site
2058 abstract function getSoftwareLink();
2061 * A string describing the current software version, like from
2062 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2064 * @return String: Version information from the database
2066 abstract function getServerVersion();
2069 * Ping the server and try to reconnect if it there is no connection
2071 * @return bool Success or failure
2074 # Stub. Not essential to override.
2080 * Currently supported only by MySQL
2081 * @return Database replication lag in seconds
2084 return $this->mFakeSlaveLag
;
2088 * Get status information from SHOW STATUS in an associative array
2090 function getStatus($which="%") {
2091 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2093 while ( $row = $this->fetchObject( $res ) ) {
2094 $status[$row->Variable_name
] = $row->Value
;
2100 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2102 function maxListLen() {
2106 function encodeBlob($b) {
2110 function decodeBlob($b) {
2115 * Override database's default connection timeout. May be useful for very
2116 * long batch queries such as full-wiki dumps, where a single query reads
2117 * out over hours or days. May or may not be necessary for non-MySQL
2118 * databases. For most purposes, leaving it as a no-op should be fine.
2120 * @param $timeout Integer in seconds
2122 public function setTimeout( $timeout ) {}
2125 * Read and execute SQL commands from a file.
2126 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2127 * @param $filename String: File name to open
2128 * @param $lineCallback Callback: Optional function called before reading each line
2129 * @param $resultCallback Callback: Optional function called for each MySQL result
2131 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2132 $fp = fopen( $filename, 'r' );
2133 if ( false === $fp ) {
2134 if (!defined("MEDIAWIKI_INSTALL"))
2135 throw new MWException( "Could not open \"{$filename}\".\n" );
2137 return "Could not open \"{$filename}\".\n";
2140 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2142 catch( MWException
$e ) {
2143 if ( defined("MEDIAWIKI_INSTALL") ) {
2144 $error = $e->getMessage();
2156 * Get the full path of a patch file. Originally based on archive()
2157 * from updaters.inc. Keep in mind this always returns a patch, as
2158 * it fails back to MySQL if no DB-specific patch can be found
2160 * @param $patch String The name of the patch, like patch-something.sql
2161 * @return String Full path to patch file
2163 public static function patchPath( $patch ) {
2164 global $wgDBtype, $IP;
2165 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2166 return "$IP/maintenance/$wgDBtype/archives/$patch";
2168 return "$IP/maintenance/archives/$patch";
2173 * Read and execute commands from an open file handle
2174 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2175 * @param $fp String: File handle
2176 * @param $lineCallback Callback: Optional function called before reading each line
2177 * @param $resultCallback Callback: Optional function called for each MySQL result
2179 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2182 $dollarquote = false;
2184 while ( ! feof( $fp ) ) {
2185 if ( $lineCallback ) {
2186 call_user_func( $lineCallback );
2188 $line = trim( fgets( $fp, 1024 ) );
2189 $sl = strlen( $line ) - 1;
2191 if ( $sl < 0 ) { continue; }
2192 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2194 ## Allow dollar quoting for function declarations
2195 if (substr($line,0,4) == '$mw$') {
2197 $dollarquote = false;
2201 $dollarquote = true;
2204 else if (!$dollarquote) {
2205 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2207 $line = substr( $line, 0, $sl );
2211 if ( $cmd != '' ) { $cmd .= ' '; }
2215 $cmd = str_replace(';;', ";", $cmd);
2216 $cmd = $this->replaceVars( $cmd );
2217 $res = $this->query( $cmd, __METHOD__
);
2218 if ( $resultCallback ) {
2219 call_user_func( $resultCallback, $res, $this );
2222 if ( false === $res ) {
2223 $err = $this->lastError();
2224 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2236 * Replace variables in sourced SQL
2238 protected function replaceVars( $ins ) {
2240 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2241 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2242 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2245 // Ordinary variables
2246 foreach ( $varnames as $var ) {
2247 if( isset( $GLOBALS[$var] ) ) {
2248 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2249 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2250 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2251 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2256 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2257 array( $this, 'tableNameCallback' ), $ins );
2260 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2261 array( $this, 'indexNameCallback' ), $ins );
2266 * Table name callback
2269 protected function tableNameCallback( $matches ) {
2270 return $this->tableName( $matches[1] );
2274 * Index name callback
2276 protected function indexNameCallback( $matches ) {
2277 return $this->indexName( $matches[1] );
2281 * Build a concatenation list to feed into a SQL query
2282 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2285 function buildConcat( $stringList ) {
2286 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2290 * Acquire a named lock
2292 * Abstracted from Filestore::lock() so child classes can implement for
2295 * @param $lockName String: name of lock to aquire
2296 * @param $method String: name of method calling us
2297 * @param $timeout Integer: timeout
2300 public function lock( $lockName, $method, $timeout = 5 ) {
2307 * @param $lockName String: Name of lock to release
2308 * @param $method String: Name of method calling us
2310 * @return Returns 1 if the lock was released, 0 if the lock was not established
2311 * by this thread (in which case the lock is not released), and NULL if the named
2312 * lock did not exist
2314 public function unlock( $lockName, $method ) {
2319 * Lock specific tables
2321 * @param $read Array of tables to lock for read access
2322 * @param $write Array of tables to lock for write access
2323 * @param $method String name of caller
2324 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2326 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2331 * Unlock specific tables
2333 * @param $method String the caller
2335 public function unlockTables( $method ) {
2340 * Get search engine class. All subclasses of this need to implement this
2341 * if they wish to use searching.
2345 public function getSearchEngine() {
2346 return 'SearchEngineDummy';
2350 * Allow or deny "big selects" for this session only. This is done by setting
2351 * the sql_big_selects session variable.
2353 * This is a MySQL-specific feature.
2355 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2357 public function setBigSelects( $value = true ) {
2363 /******************************************************************************
2365 *****************************************************************************/
2374 function DBObject($data) {
2375 $this->mData
= $data;
2383 return $this->mData
;
2391 * This allows us to distinguish a blob from a normal string and an array of strings
2395 function __construct($data) {
2396 $this->mData
= $data;
2399 return $this->mData
;
2408 private $name, $tablename, $default, $max_length, $nullable,
2409 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2410 function __construct ($info) {
2411 $this->name
= $info->name
;
2412 $this->tablename
= $info->table
;
2413 $this->default = $info->def
;
2414 $this->max_length
= $info->max_length
;
2415 $this->nullable
= !$info->not_null
;
2416 $this->is_pk
= $info->primary_key
;
2417 $this->is_unique
= $info->unique_key
;
2418 $this->is_multiple
= $info->multiple_key
;
2419 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2420 $this->type
= $info->type
;
2427 function tableName() {
2428 return $this->tableName
;
2431 function defaultValue() {
2432 return $this->default;
2435 function maxLength() {
2436 return $this->max_length
;
2439 function nullable() {
2440 return $this->nullable
;
2444 return $this->is_key
;
2447 function isMultipleKey() {
2448 return $this->is_multiple
;
2456 /******************************************************************************
2458 *****************************************************************************/
2461 * Database error base class
2464 class DBError
extends MWException
{
2468 * Construct a database error
2469 * @param $db Database object which threw the error
2470 * @param $error A simple error message to be used for debugging
2472 function __construct( DatabaseBase
&$db, $error ) {
2474 parent
::__construct( $error );
2477 function getText() {
2478 global $wgShowDBErrorBacktrace;
2479 $s = $this->getMessage() . "\n";
2480 if ( $wgShowDBErrorBacktrace ) {
2481 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2490 class DBConnectionError
extends DBError
{
2493 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2494 $msg = 'DB connection error';
2495 if ( trim( $error ) != '' ) {
2498 $this->error
= $error;
2499 parent
::__construct( $db, $msg );
2502 function useOutputPage() {
2503 // Not likely to work
2507 function useMessageCache() {
2508 // Not likely to work
2512 function getLogMessage() {
2513 # Don't send to the exception log
2517 function getPageTitle() {
2518 global $wgSitename, $wgLang;
2519 $header = "$wgSitename has a problem";
2520 if ( $wgLang instanceof Language
) {
2521 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2527 function getHTML() {
2528 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2530 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2531 $again = 'Try waiting a few minutes and reloading.';
2532 $info = '(Can\'t contact the database server: $1)';
2534 if ( $wgLang instanceof Language
) {
2535 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2536 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2537 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2540 # No database access
2541 if ( is_object( $wgMessageCache ) ) {
2542 $wgMessageCache->disable();
2545 if ( trim( $this->error
) == '' ) {
2546 $this->error
= $this->db
->getProperty('mServer');
2549 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2550 $text = str_replace( '$1', $this->error
, $noconnect );
2552 if ( $wgShowDBErrorBacktrace ) {
2553 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2556 $extra = $this->searchForm();
2558 if( $wgUseFileCache ) {
2560 $cache = $this->fileCachedPage();
2561 # Cached version on file system?
2562 if( $cache !== null ) {
2563 # Hack: extend the body for error messages
2564 $cache = str_replace( array('</html>','</body>'), '', $cache );
2565 # Add cache notice...
2566 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2567 # Localize it if possible...
2568 if( $wgLang instanceof Language
) {
2569 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2571 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2572 # Output cached page with notices on bottom and re-close body
2573 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2575 } catch( MWException
$e ) {
2576 // Do nothing, just use the default page
2579 # Headers needed here - output is just the error message
2580 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2583 function searchForm() {
2584 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2585 $usegoogle = "You can try searching via Google in the meantime.";
2586 $outofdate = "Note that their indexes of our content may be out of date.";
2587 $googlesearch = "Search";
2589 if ( $wgLang instanceof Language
) {
2590 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2591 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2592 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2595 $search = htmlspecialchars(@$_REQUEST['search']);
2598 <div style="margin: 1.5em">$usegoogle<br />
2599 <small>$outofdate</small></div>
2600 <!-- SiteSearch Google -->
2601 <form method="get" action="http://www.google.com/search" id="googlesearch">
2602 <input type="hidden" name="domains" value="$wgServer" />
2603 <input type="hidden" name="num" value="50" />
2604 <input type="hidden" name="ie" value="$wgInputEncoding" />
2605 <input type="hidden" name="oe" value="$wgInputEncoding" />
2607 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2608 <input type="submit" name="btnG" value="$googlesearch" />
2610 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2611 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2614 <!-- SiteSearch Google -->
2619 function fileCachedPage() {
2620 global $wgTitle, $title, $wgLang, $wgOut;
2621 if( $wgOut->isDisabled() ) return; // Done already?
2622 $mainpage = 'Main Page';
2623 if ( $wgLang instanceof Language
) {
2624 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2629 } elseif( $title ) {
2630 $t = Title
::newFromURL( $title );
2632 $t = Title
::newFromText( $mainpage );
2635 $cache = new HTMLFileCache( $t );
2636 if( $cache->isFileCached() ) {
2637 return $cache->fetchPageText();
2643 function htmlBodyOnly() {
2652 class DBQueryError
extends DBError
{
2653 public $error, $errno, $sql, $fname;
2655 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2656 $message = "A database error has occurred\n" .
2658 "Function: $fname\n" .
2659 "Error: $errno $error\n";
2661 parent
::__construct( $db, $message );
2662 $this->error
= $error;
2663 $this->errno
= $errno;
2665 $this->fname
= $fname;
2668 function getText() {
2669 global $wgShowDBErrorBacktrace;
2670 if ( $this->useMessageCache() ) {
2671 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2672 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2673 if ( $wgShowDBErrorBacktrace ) {
2674 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2678 return parent
::getText();
2683 global $wgShowSQLErrors;
2684 if( !$wgShowSQLErrors ) {
2685 return $this->msg( 'sqlhidden', 'SQL hidden' );
2691 function getLogMessage() {
2692 # Don't send to the exception log
2696 function getPageTitle() {
2697 return $this->msg( 'databaseerror', 'Database error' );
2700 function getHTML() {
2701 global $wgShowDBErrorBacktrace;
2702 if ( $this->useMessageCache() ) {
2703 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2704 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2706 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2708 if ( $wgShowDBErrorBacktrace ) {
2709 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2718 class DBUnexpectedError
extends DBError
{}
2722 * Result wrapper for grabbing data queried by someone else
2725 class ResultWrapper
implements Iterator
{
2726 var $db, $result, $pos = 0, $currentRow = null;
2729 * Create a new result object from a result resource and a Database object
2731 function ResultWrapper( $database, $result ) {
2732 $this->db
= $database;
2733 if ( $result instanceof ResultWrapper
) {
2734 $this->result
= $result->result
;
2736 $this->result
= $result;
2741 * Get the number of rows in a result object
2743 function numRows() {
2744 return $this->db
->numRows( $this );
2748 * Fetch the next row from the given result object, in object form.
2749 * Fields can be retrieved with $row->fieldname, with fields acting like
2752 * @return MySQL row object
2753 * @throws DBUnexpectedError Thrown if the database returns an error
2755 function fetchObject() {
2756 return $this->db
->fetchObject( $this );
2760 * Fetch the next row from the given result object, in associative array
2761 * form. Fields are retrieved with $row['fieldname'].
2763 * @return MySQL row object
2764 * @throws DBUnexpectedError Thrown if the database returns an error
2766 function fetchRow() {
2767 return $this->db
->fetchRow( $this );
2771 * Free a result object
2774 $this->db
->freeResult( $this );
2775 unset( $this->result
);
2780 * Change the position of the cursor in a result object
2781 * See mysql_data_seek()
2783 function seek( $row ) {
2784 $this->db
->dataSeek( $this, $row );
2787 /*********************
2788 * Iterator functions
2789 * Note that using these in combination with the non-iterator functions
2790 * above may cause rows to be skipped or repeated.
2794 if ($this->numRows()) {
2795 $this->db
->dataSeek($this, 0);
2798 $this->currentRow
= null;
2801 function current() {
2802 if ( is_null( $this->currentRow
) ) {
2805 return $this->currentRow
;
2814 $this->currentRow
= $this->fetchObject();
2815 return $this->currentRow
;
2819 return $this->current() !== false;
2823 /* Overloads the relevant methods of the real ResultsWrapper so it
2824 * doesn't go anywhere near an actual database.
2826 class FakeResultWrapper
extends ResultWrapper
{
2828 var $result = array();
2829 var $db = null; // And it's going to stay that way :D
2831 var $currentRow = null;
2833 function __construct( $array ){
2834 $this->result
= $array;
2837 function numRows() {
2838 return count( $this->result
);
2841 function fetchRow() {
2842 $this->currentRow
= $this->result
[$this->pos++
];
2843 return $this->currentRow
;
2846 function seek( $row ) {
2852 // Callers want to be able to access fields with $this->fieldName
2853 function fetchObject(){
2854 $this->currentRow
= $this->result
[$this->pos++
];
2855 return (object)$this->currentRow
;
2860 $this->currentRow
= null;
2865 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2866 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2871 public function __construct( $s ) {
2875 public function toString() {