3 * @defgroup Database Database
7 * This file deals with MySQL 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 * Output page, used for reporting errors
59 * FALSE means discard output
61 function setOutputPage( $out ) {
62 wfDeprecated( __METHOD__
);
66 * Boolean, controls output of large amounts of debug information
68 function debug( $debug = null ) {
69 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
73 * Turns buffering of SQL result sets on (true) or off (false).
74 * Default is "on" and it should not be changed without good reasons.
76 function bufferResults( $buffer = null ) {
77 if ( is_null( $buffer ) ) {
78 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
80 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
85 * Turns on (false) or off (true) the automatic generation and sending
86 * of a "we're sorry, but there has been a database error" page on
87 * database errors. Default is on (false). When turned off, the
88 * code should use lastErrno() and lastError() to handle the
89 * situation as appropriate.
91 function ignoreErrors( $ignoreErrors = null ) {
92 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
96 * The current depth of nested transactions
97 * @param $level Integer: , default NULL.
99 function trxLevel( $level = null ) {
100 return wfSetVar( $this->mTrxLevel
, $level );
104 * Number of errors logged, only useful when errors are ignored
106 function errorCount( $count = null ) {
107 return wfSetVar( $this->mErrorCount
, $count );
110 function tablePrefix( $prefix = null ) {
111 return wfSetVar( $this->mTablePrefix
, $prefix );
115 * Properties passed down from the server info array of the load balancer
117 function getLBInfo( $name = null ) {
118 if ( is_null( $name ) ) {
119 return $this->mLBInfo
;
121 if ( array_key_exists( $name, $this->mLBInfo
) ) {
122 return $this->mLBInfo
[$name];
129 function setLBInfo( $name, $value = null ) {
130 if ( is_null( $value ) ) {
131 $this->mLBInfo
= $name;
133 $this->mLBInfo
[$name] = $value;
138 * Set lag time in seconds for a fake slave
140 function setFakeSlaveLag( $lag ) {
141 $this->mFakeSlaveLag
= $lag;
145 * Make this connection a fake master
147 function setFakeMaster( $enabled = true ) {
148 $this->mFakeMaster
= $enabled;
152 * Returns true if this database supports (and uses) cascading deletes
154 function cascadingDeletes() {
159 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
161 function cleanupTriggers() {
166 * Returns true if this database is strict about what can be put into an IP field.
167 * Specifically, it uses a NULL value instead of an empty string.
169 function strictIPs() {
174 * Returns true if this database uses timestamps rather than integers
176 function realTimestamps() {
181 * Returns true if this database does an implicit sort when doing GROUP BY
183 function implicitGroupby() {
188 * Returns true if this database does an implicit order by when the column has an index
189 * For example: SELECT page_title FROM page LIMIT 1
191 function implicitOrderby() {
196 * Returns true if this database requires that SELECT DISTINCT queries require that all
197 ORDER BY expressions occur in the SELECT list per the SQL92 standard
199 function standardSelectDistinct() {
204 * Returns true if this database can do a native search on IP columns
205 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
207 function searchableIPs() {
212 * Returns true if this database can use functional indexes
214 function functionalIndexes() {
219 * Return the last query that went through Database::query()
222 function lastQuery() { return $this->mLastQuery
; }
226 * Returns true if the connection may have been used for write queries.
227 * Should return true if unsure.
229 function doneWrites() { return $this->mDoneWrites
; }
232 * Is a connection to the database open?
235 function isOpen() { return $this->mOpened
; }
238 * Set a flag for this connection
240 * @param $flag Integer: DBO_* constants from Defines.php:
241 * - DBO_DEBUG: output some debug info (same as debug())
242 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
243 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
244 * - DBO_TRX: automatically start transactions
245 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
246 * and removes it in command line mode
247 * - DBO_PERSISTENT: use persistant database connection
249 function setFlag( $flag ) {
250 $this->mFlags |
= $flag;
254 * Clear a flag for this connection
256 * @param $flag: same as setFlag()'s $flag param
258 function clearFlag( $flag ) {
259 $this->mFlags
&= ~
$flag;
263 * Returns a boolean whether the flag $flag is set for this connection
265 * @param $flag: same as setFlag()'s $flag param
268 function getFlag( $flag ) {
269 return !!($this->mFlags
& $flag);
273 * General read-only accessor
275 function getProperty( $name ) {
279 function getWikiID() {
280 if( $this->mTablePrefix
) {
281 return "{$this->mDBname}-{$this->mTablePrefix}";
283 return $this->mDBname
;
288 * Get the type of the DBMS, as it appears in $wgDBtype.
291 if ( preg_match( '/^Database(\w+)$/', get_class( $this ), $m ) ) {
292 return strtolower( $m[1] );
294 throw new MWException( get_class( $this ) .'::getType: unable to determine type.' );
298 #------------------------------------------------------------------------------
300 #------------------------------------------------------------------------------
304 * @param $server String: database server host
305 * @param $user String: database user name
306 * @param $password String: database user password
307 * @param $dbName String: database name
308 * @param $failFunction
310 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
312 function __construct( $server = false, $user = false, $password = false, $dbName = false,
313 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
315 global $wgOut, $wgDBprefix, $wgCommandLineMode;
316 # Can't get a reference if it hasn't been set yet
317 if ( !isset( $wgOut ) ) {
321 $this->mFailFunction
= $failFunction;
322 $this->mFlags
= $flags;
324 if ( $this->mFlags
& DBO_DEFAULT
) {
325 if ( $wgCommandLineMode ) {
326 $this->mFlags
&= ~DBO_TRX
;
328 $this->mFlags |
= DBO_TRX
;
333 // Faster read-only access
334 if ( wfReadOnly() ) {
335 $this->mFlags |= DBO_PERSISTENT;
336 $this->mFlags &= ~DBO_TRX;
339 /** Get the default table prefix*/
340 if ( $tablePrefix == 'get from global' ) {
341 $this->mTablePrefix
= $wgDBprefix;
343 $this->mTablePrefix
= $tablePrefix;
347 $this->open( $server, $user, $password, $dbName );
352 * Same as new DatabaseMysql( ... ), kept for backward compatibility
353 * @param $server String: database server host
354 * @param $user String: database user name
355 * @param $password String: database user password
356 * @param $dbName String: database name
357 * @param failFunction
360 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
362 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
366 * Usually aborts on failure
367 * If the failFunction is set to a non-zero integer, returns success
368 * @param $server String: database server host
369 * @param $user String: database user name
370 * @param $password String: database user password
371 * @param $dbName String: database name
373 abstract function open( $server, $user, $password, $dbName );
375 protected function installErrorHandler() {
376 $this->mPHPError
= false;
377 $this->htmlErrors
= ini_set( 'html_errors', '0' );
378 set_error_handler( array( $this, 'connectionErrorHandler' ) );
381 protected function restoreErrorHandler() {
382 restore_error_handler();
383 if ( $this->htmlErrors
!== false ) {
384 ini_set( 'html_errors', $this->htmlErrors
);
386 if ( $this->mPHPError
) {
387 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
388 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
395 protected function connectionErrorHandler( $errno, $errstr ) {
396 $this->mPHPError
= $errstr;
400 * Closes a database connection.
401 * if it is open : commits any open transactions
403 * @return Bool operation success. true if already closed.
406 # Stub, should probably be overridden
411 * @param $error String: fallback error message, used if none is given by MySQL
413 function reportConnectionError( $error = 'Unknown error' ) {
414 $myError = $this->lastError();
419 if ( $this->mFailFunction
) {
420 # Legacy error handling method
421 if ( !is_int( $this->mFailFunction
) ) {
422 $ff = $this->mFailFunction
;
423 $ff( $this, $error );
427 throw new DBConnectionError( $this, $error );
432 * Determine whether a query writes to the DB.
433 * Should return true if unsure.
435 function isWriteQuery( $sql ) {
436 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
440 * Usually aborts on failure. If errors are explicitly ignored, returns success.
442 * @param $sql String: SQL query
443 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
444 * comment (you can use __METHOD__ or add some extra info)
445 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
446 * maybe best to catch the exception instead?
447 * @return true for a successful write query, ResultWrapper object for a successful read query,
448 * or false on failure if $tempIgnore set
449 * @throws DBQueryError Thrown when the database returns an error of any kind
451 public function query( $sql, $fname = '', $tempIgnore = false ) {
454 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
455 if ( isset( $wgProfiler ) ) {
456 # generalizeSQL will probably cut down the query to reasonable
457 # logging size most of the time. The substr is really just a sanity check.
459 # Who's been wasting my precious column space? -- TS
460 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
463 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
464 $totalProf = 'Database::query-master';
466 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
467 $totalProf = 'Database::query';
469 wfProfileIn( $totalProf );
470 wfProfileIn( $queryProf );
473 $this->mLastQuery
= $sql;
474 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
475 // Set a flag indicating that writes have been done
476 wfDebug( __METHOD__
.": Writes done: $sql\n" );
477 $this->mDoneWrites
= true;
480 # Add a comment for easy SHOW PROCESSLIST interpretation
483 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
484 $userName = $wgUser->getName();
485 if ( mb_strlen( $userName ) > 15 ) {
486 $userName = mb_substr( $userName, 0, 15 ) . '...';
488 $userName = str_replace( '/', '', $userName );
492 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
494 # $commentedSql = $sql;
497 # If DBO_TRX is set, start a transaction
498 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
499 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
500 // avoid establishing transactions for SHOW and SET statements too -
501 // that would delay transaction initializations to once connection
502 // is really used by application
503 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
504 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
508 if ( $this->debug() ) {
509 $sqlx = substr( $commentedSql, 0, 500 );
510 $sqlx = strtr( $sqlx, "\t\n", ' ' );
512 wfDebug( "SQL-master: $sqlx\n" );
514 wfDebug( "SQL: $sqlx\n" );
518 if ( istainted( $sql ) & TC_MYSQL
) {
519 throw new MWException( 'Tainted query found' );
522 # Do the query and handle errors
523 $ret = $this->doQuery( $commentedSql );
525 # Try reconnecting if the connection was lost
526 if ( false === $ret && $this->wasErrorReissuable() ) {
527 # Transaction is gone, like it or not
528 $this->mTrxLevel
= 0;
529 wfDebug( "Connection lost, reconnecting...\n" );
530 if ( $this->ping() ) {
531 wfDebug( "Reconnected\n" );
532 $sqlx = substr( $commentedSql, 0, 500 );
533 $sqlx = strtr( $sqlx, "\t\n", ' ' );
534 global $wgRequestTime;
535 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
536 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
537 $ret = $this->doQuery( $commentedSql );
539 wfDebug( "Failed\n" );
543 if ( false === $ret ) {
544 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
547 if ( isset( $wgProfiler ) ) {
548 wfProfileOut( $queryProf );
549 wfProfileOut( $totalProf );
551 return $this->resultObject( $ret );
555 * The DBMS-dependent part of query()
556 * @param $sql String: SQL query.
557 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
560 /*private*/ abstract function doQuery( $sql );
563 * @param $error String
564 * @param $errno Integer
566 * @param $fname String
567 * @param $tempIgnore Boolean
569 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
570 global $wgCommandLineMode;
571 # Ignore errors during error handling to avoid infinite recursion
572 $ignore = $this->ignoreErrors( true );
573 ++
$this->mErrorCount
;
575 if( $ignore ||
$tempIgnore ) {
576 wfDebug("SQL ERROR (ignored): $error\n");
577 $this->ignoreErrors( $ignore );
579 $sql1line = str_replace( "\n", "\\n", $sql );
580 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
581 wfDebug("SQL ERROR: " . $error . "\n");
582 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
588 * Intended to be compatible with the PEAR::DB wrapper functions.
589 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
591 * ? = scalar value, quoted as necessary
592 * ! = raw SQL bit (a function for instance)
593 * & = filename; reads the file and inserts as a blob
594 * (we don't use this though...)
596 function prepare( $sql, $func = 'Database::prepare' ) {
597 /* MySQL doesn't support prepared statements (yet), so just
598 pack up the query for reference. We'll manually replace
600 return array( 'query' => $sql, 'func' => $func );
603 function freePrepared( $prepared ) {
604 /* No-op for MySQL */
608 * Execute a prepared query with the various arguments
609 * @param $prepared String: the prepared sql
610 * @param $args Mixed: Either an array here, or put scalars as varargs
612 function execute( $prepared, $args = null ) {
613 if( !is_array( $args ) ) {
615 $args = func_get_args();
616 array_shift( $args );
618 $sql = $this->fillPrepared( $prepared['query'], $args );
619 return $this->query( $sql, $prepared['func'] );
623 * Prepare & execute an SQL statement, quoting and inserting arguments
624 * in the appropriate places.
625 * @param $query String
628 function safeQuery( $query, $args = null ) {
629 $prepared = $this->prepare( $query, 'Database::safeQuery' );
630 if( !is_array( $args ) ) {
632 $args = func_get_args();
633 array_shift( $args );
635 $retval = $this->execute( $prepared, $args );
636 $this->freePrepared( $prepared );
641 * For faking prepared SQL statements on DBs that don't support
643 * @param $preparedQuery String: a 'preparable' SQL statement
644 * @param $args Array of arguments to fill it with
645 * @return string executable SQL
647 function fillPrepared( $preparedQuery, $args ) {
649 $this->preparedArgs
=& $args;
650 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
651 array( &$this, 'fillPreparedArg' ), $preparedQuery );
655 * preg_callback func for fillPrepared()
656 * The arguments should be in $this->preparedArgs and must not be touched
657 * while we're doing this.
659 * @param $matches Array
663 function fillPreparedArg( $matches ) {
664 switch( $matches[1] ) {
665 case '\\?': return '?';
666 case '\\!': return '!';
667 case '\\&': return '&';
669 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
670 switch( $matches[1] ) {
671 case '?': return $this->addQuotes( $arg );
672 case '!': return $arg;
674 # return $this->addQuotes( file_get_contents( $arg ) );
675 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
677 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
682 * Free a result object
683 * @param $res Mixed: A SQL result
685 function freeResult( $res ) {
686 # Stub. Might not really need to be overridden, since results should
687 # be freed by PHP when the variable goes out of scope anyway.
691 * Fetch the next row from the given result object, in object form.
692 * Fields can be retrieved with $row->fieldname, with fields acting like
695 * @param $res SQL result object as returned from Database::query(), etc.
696 * @return MySQL row object
697 * @throws DBUnexpectedError Thrown if the database returns an error
699 abstract function fetchObject( $res );
702 * Fetch the next row from the given result object, in associative array
703 * form. Fields are retrieved with $row['fieldname'].
705 * @param $res SQL result object as returned from Database::query(), etc.
706 * @return MySQL row object
707 * @throws DBUnexpectedError Thrown if the database returns an error
709 abstract function fetchRow( $res );
712 * Get the number of rows in a result object
713 * @param $res Mixed: A SQL result
715 abstract function numRows( $res );
718 * Get the number of fields in a result object
719 * See documentation for mysql_num_fields()
720 * @param $res Mixed: A SQL result
722 abstract function numFields( $res );
725 * Get a field name in a result object
726 * See documentation for mysql_field_name():
727 * http://www.php.net/mysql_field_name
728 * @param $res Mixed: A SQL result
731 abstract function fieldName( $res, $n );
734 * Get the inserted value of an auto-increment row
736 * The value inserted should be fetched from nextSequenceValue()
739 * $id = $dbw->nextSequenceValue('page_page_id_seq');
740 * $dbw->insert('page',array('page_id' => $id));
741 * $id = $dbw->insertId();
743 abstract function insertId();
746 * Change the position of the cursor in a result object
747 * See mysql_data_seek()
748 * @param $res Mixed: A SQL result
749 * @param $row Mixed: Either MySQL row or ResultWrapper
751 abstract function dataSeek( $res, $row );
754 * Get the last error number
757 abstract function lastErrno();
760 * Get a description of the last error
761 * See mysql_error() for more details
763 abstract function lastError();
766 * Get the number of rows affected by the last write query
767 * See mysql_affected_rows() for more details
769 abstract function affectedRows();
772 * Simple UPDATE wrapper
773 * Usually aborts on failure
774 * If errors are explicitly ignored, returns success
776 * This function exists for historical reasons, Database::update() has a more standard
777 * calling convention and feature set
779 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
780 $table = $this->tableName( $table );
781 $sql = "UPDATE $table SET $var = '" .
782 $this->strencode( $value ) . "' WHERE ($cond)";
783 return (bool)$this->query( $sql, $fname );
787 * Simple SELECT wrapper, returns a single field, input must be encoded
788 * Usually aborts on failure
789 * If errors are explicitly ignored, returns FALSE on failure
791 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
792 if ( !is_array( $options ) ) {
793 $options = array( $options );
795 $options['LIMIT'] = 1;
797 $res = $this->select( $table, $var, $cond, $fname, $options );
798 if ( $res === false ||
!$this->numRows( $res ) ) {
801 $row = $this->fetchRow( $res );
802 if ( $row !== false ) {
803 $this->freeResult( $res );
804 return reset( $row );
811 * Returns an optional USE INDEX clause to go after the table, and a
812 * string to go at the end of the query
816 * @param $options Array: associative array of options to be turned into
817 * an SQL query, valid keys are listed in the function.
820 function makeSelectOptions( $options ) {
821 $preLimitTail = $postLimitTail = '';
824 $noKeyOptions = array();
825 foreach ( $options as $key => $option ) {
826 if ( is_numeric( $key ) ) {
827 $noKeyOptions[$option] = true;
831 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
832 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
833 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
835 //if (isset($options['LIMIT'])) {
836 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
837 // isset($options['OFFSET']) ? $options['OFFSET']
841 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
842 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
843 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
845 # Various MySQL extensions
846 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
847 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
848 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
849 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
850 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
851 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
852 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
853 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
855 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
856 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
861 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
867 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
868 * @param $vars Mixed: Array or string, field name(s) to be retrieved
869 * @param $conds Mixed: Array or string, condition(s) for WHERE
870 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
871 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
872 * see Database::makeSelectOptions code for list of supported stuff
873 * @param $join_conds Array: Associative array of table join conditions (optional)
874 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
875 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
877 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
879 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
880 return $this->query( $sql, $fname );
886 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
887 * @param $vars Mixed: Array or string, field name(s) to be retrieved
888 * @param $conds Mixed: Array or string, condition(s) for WHERE
889 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
890 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
891 * see Database::makeSelectOptions code for list of supported stuff
892 * @param $join_conds Array: Associative array of table join conditions (optional)
893 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
894 * @return string, the SQL text
896 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
897 if( is_array( $vars ) ) {
898 $vars = implode( ',', $vars );
900 if( !is_array( $options ) ) {
901 $options = array( $options );
903 if( is_array( $table ) ) {
904 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
905 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
907 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
908 } elseif ($table!='') {
909 if ($table{0}==' ') {
910 $from = ' FROM ' . $table;
912 $from = ' FROM ' . $this->tableName( $table );
918 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
920 if( !empty( $conds ) ) {
921 if ( is_array( $conds ) ) {
922 $conds = $this->makeList( $conds, LIST_AND
);
924 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
926 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
929 if (isset($options['LIMIT']))
930 $sql = $this->limitResult($sql, $options['LIMIT'],
931 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
932 $sql = "$sql $postLimitTail";
934 if (isset($options['EXPLAIN'])) {
935 $sql = 'EXPLAIN ' . $sql;
941 * Single row SELECT wrapper
942 * Aborts or returns FALSE on error
944 * @param $table String: table name
945 * @param $vars String: the selected variables
946 * @param $conds Array: a condition map, terms are ANDed together.
947 * Items with numeric keys are taken to be literal conditions
948 * Takes an array of selected variables, and a condition map, which is ANDed
949 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
950 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
951 * $obj- >page_id is the ID of the Astronomy article
952 * @param $fname String: Calling function name
953 * @param $options Array
954 * @param $join_conds Array
956 * @todo migrate documentation to phpdocumentor format
958 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
959 $options['LIMIT'] = 1;
960 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
961 if ( $res === false )
963 if ( !$this->numRows($res) ) {
964 $this->freeResult($res);
967 $obj = $this->fetchObject( $res );
968 $this->freeResult( $res );
974 * Estimate rows in dataset
975 * Returns estimated count - not necessarily an accurate estimate across different databases,
977 * Takes same arguments as Database::select()
979 * @param string $table table name
980 * @param array $vars unused
981 * @param array $conds filters on the table
982 * @param string $fname function name for profiling
983 * @param array $options options for select
984 * @return int row count
986 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
988 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
990 $row = $this->fetchRow( $res );
991 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
993 $this->freeResult( $res );
998 * Removes most variables from an SQL query and replaces them with X or N for numbers.
999 * It's only slightly flawed. Don't use for anything important.
1001 * @param $sql String: A SQL Query
1003 static function generalizeSQL( $sql ) {
1004 # This does the same as the regexp below would do, but in such a way
1005 # as to avoid crashing php on some large strings.
1006 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1008 $sql = str_replace ( "\\\\", '', $sql);
1009 $sql = str_replace ( "\\'", '', $sql);
1010 $sql = str_replace ( "\\\"", '', $sql);
1011 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1012 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1014 # All newlines, tabs, etc replaced by single space
1015 $sql = preg_replace ( '/\s+/', ' ', $sql);
1018 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1024 * Determines whether a field exists in a table
1025 * Usually aborts on failure
1026 * If errors are explicitly ignored, returns NULL on failure
1028 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1029 $table = $this->tableName( $table );
1030 $res = $this->query( 'DESCRIBE '.$table, $fname );
1037 while ( $row = $this->fetchObject( $res ) ) {
1038 if ( $row->Field
== $field ) {
1047 * Determines whether an index exists
1048 * Usually aborts on failure
1049 * If errors are explicitly ignored, returns NULL on failure
1051 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1052 $info = $this->indexInfo( $table, $index, $fname );
1053 if ( is_null( $info ) ) {
1056 return $info !== false;
1062 * Get information about an index into an object
1063 * Returns false if the index does not exist
1065 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1066 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1067 # SHOW INDEX should work for 3.x and up:
1068 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1069 $table = $this->tableName( $table );
1070 $index = $this->indexName( $index );
1071 $sql = 'SHOW INDEX FROM '.$table;
1072 $res = $this->query( $sql, $fname );
1078 while ( $row = $this->fetchObject( $res ) ) {
1079 if ( $row->Key_name
== $index ) {
1083 $this->freeResult($res);
1085 return empty($result) ?
false : $result;
1089 * Query whether a given table exists
1091 function tableExists( $table ) {
1092 $table = $this->tableName( $table );
1093 $old = $this->ignoreErrors( true );
1094 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1095 $this->ignoreErrors( $old );
1097 $this->freeResult( $res );
1105 * mysql_fetch_field() wrapper
1106 * Returns false if the field doesn't exist
1111 abstract function fieldInfo( $table, $field );
1114 * mysql_field_type() wrapper
1116 function fieldType( $res, $index ) {
1117 if ( $res instanceof ResultWrapper
) {
1118 $res = $res->result
;
1120 return mysql_field_type( $res, $index );
1124 * Determines if a given index is unique
1126 function indexUnique( $table, $index ) {
1127 $indexInfo = $this->indexInfo( $table, $index );
1128 if ( !$indexInfo ) {
1131 return !$indexInfo[0]->Non_unique
;
1135 * INSERT wrapper, inserts an array into a table
1137 * $a may be a single associative array, or an array of these with numeric keys, for
1140 * Usually aborts on failure
1141 * If errors are explicitly ignored, returns success
1143 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1144 # No rows to insert, easy just return now
1145 if ( !count( $a ) ) {
1149 $table = $this->tableName( $table );
1150 if ( !is_array( $options ) ) {
1151 $options = array( $options );
1153 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1155 $keys = array_keys( $a[0] );
1158 $keys = array_keys( $a );
1161 $sql = 'INSERT ' . implode( ' ', $options ) .
1162 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1166 foreach ( $a as $row ) {
1172 $sql .= '(' . $this->makeList( $row ) . ')';
1175 $sql .= '(' . $this->makeList( $a ) . ')';
1177 return (bool)$this->query( $sql, $fname );
1181 * Make UPDATE options for the Database::update function
1184 * @param $options Array: The options passed to Database::update
1187 function makeUpdateOptions( $options ) {
1188 if( !is_array( $options ) ) {
1189 $options = array( $options );
1192 if ( in_array( 'LOW_PRIORITY', $options ) )
1193 $opts[] = $this->lowPriorityOption();
1194 if ( in_array( 'IGNORE', $options ) )
1196 return implode(' ', $opts);
1200 * UPDATE wrapper, takes a condition array and a SET array
1202 * @param $table String: The table to UPDATE
1203 * @param $values Array: An array of values to SET
1204 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1205 * @param $fname String: The Class::Function calling this function
1207 * @param $options Array: An array of UPDATE options, can be one or
1208 * more of IGNORE, LOW_PRIORITY
1211 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1212 $table = $this->tableName( $table );
1213 $opts = $this->makeUpdateOptions( $options );
1214 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1215 if ( $conds != '*' ) {
1216 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1218 return $this->query( $sql, $fname );
1222 * Makes an encoded list of strings from an array
1224 * LIST_COMMA - comma separated, no field names
1225 * LIST_AND - ANDed WHERE clause (without the WHERE)
1226 * LIST_OR - ORed WHERE clause (without the WHERE)
1227 * LIST_SET - comma separated with field names, like a SET clause
1228 * LIST_NAMES - comma separated field names
1230 function makeList( $a, $mode = LIST_COMMA
) {
1231 if ( !is_array( $a ) ) {
1232 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1237 foreach ( $a as $field => $value ) {
1239 if ( $mode == LIST_AND
) {
1241 } elseif($mode == LIST_OR
) {
1249 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1250 $list .= "($value)";
1251 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1253 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1254 if( count( $value ) == 0 ) {
1255 throw new MWException( __METHOD__
.': empty input' );
1256 } elseif( count( $value ) == 1 ) {
1257 // Special-case single values, as IN isn't terribly efficient
1258 // Don't necessarily assume the single key is 0; we don't
1259 // enforce linear numeric ordering on other arrays here.
1260 $value = array_values( $value );
1261 $list .= $field." = ".$this->addQuotes( $value[0] );
1263 $list .= $field." IN (".$this->makeList($value).") ";
1265 } elseif( $value === null ) {
1266 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1267 $list .= "$field IS ";
1268 } elseif ( $mode == LIST_SET
) {
1269 $list .= "$field = ";
1273 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1274 $list .= "$field = ";
1276 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1283 * Bitwise operations
1286 function bitNot($field) {
1287 return "(~$bitField)";
1290 function bitAnd($fieldLeft, $fieldRight) {
1291 return "($fieldLeft & $fieldRight)";
1294 function bitOr($fieldLeft, $fieldRight) {
1295 return "($fieldLeft | $fieldRight)";
1299 * Change the current database
1301 * @return bool Success or failure
1303 function selectDB( $db ) {
1304 # Stub. Shouldn't cause serious problems if it's not overridden, but
1305 # if your database engine supports a concept similar to MySQL's
1306 # databases you may as well. TODO: explain what exactly will fail if
1307 # this is not overridden.
1312 * Get the current DB name
1314 function getDBname() {
1315 return $this->mDBname
;
1319 * Get the server hostname or IP address
1321 function getServer() {
1322 return $this->mServer
;
1326 * Format a table name ready for use in constructing an SQL query
1328 * This does two important things: it quotes the table names to clean them up,
1329 * and it adds a table prefix if only given a table name with no quotes.
1331 * All functions of this object which require a table name call this function
1332 * themselves. Pass the canonical name to such functions. This is only needed
1333 * when calling query() directly.
1335 * @param $name String: database table name
1336 * @return String: full database name
1338 function tableName( $name ) {
1339 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1340 # Skip the entire process when we have a string quoted on both ends.
1341 # Note that we check the end so that we will still quote any use of
1342 # use of `database`.table. But won't break things if someone wants
1343 # to query a database table with a dot in the name.
1344 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1346 # Lets test for any bits of text that should never show up in a table
1347 # name. Basically anything like JOIN or ON which are actually part of
1348 # SQL queries, but may end up inside of the table value to combine
1349 # sql. Such as how the API is doing.
1350 # Note that we use a whitespace test rather than a \b test to avoid
1351 # any remote case where a word like on may be inside of a table name
1352 # surrounded by symbols which may be considered word breaks.
1353 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1355 # Split database and table into proper variables.
1356 # We reverse the explode so that database.table and table both output
1357 # the correct table.
1358 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1359 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1360 else @list
( $table ) = $dbDetails;
1361 $prefix = $this->mTablePrefix
; # Default prefix
1363 # A database name has been specified in input. Quote the table name
1364 # because we don't want any prefixes added.
1365 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1367 # Note that we use the long format because php will complain in in_array if
1368 # the input is not an array, and will complain in is_array if it is not set.
1369 if( !isset( $database ) # Don't use shared database if pre selected.
1370 && isset( $wgSharedDB ) # We have a shared database
1371 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1372 && isset( $wgSharedTables )
1373 && is_array( $wgSharedTables )
1374 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1375 $database = $wgSharedDB;
1376 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1379 # Quote the $database and $table and apply the prefix if not quoted.
1380 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1381 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1383 # Merge our database and table into our final table name.
1384 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1386 # We're finished, return.
1391 * Fetch a number of table names into an array
1392 * This is handy when you need to construct SQL for joins
1395 * extract($dbr->tableNames('user','watchlist'));
1396 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1397 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1399 public function tableNames() {
1400 $inArray = func_get_args();
1402 foreach ( $inArray as $name ) {
1403 $retVal[$name] = $this->tableName( $name );
1409 * Fetch a number of table names into an zero-indexed numerical array
1410 * This is handy when you need to construct SQL for joins
1413 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1414 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1415 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1417 public function tableNamesN() {
1418 $inArray = func_get_args();
1420 foreach ( $inArray as $name ) {
1421 $retVal[] = $this->tableName( $name );
1429 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1432 $use_index_safe = is_array($use_index) ?
$use_index : array();
1433 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1434 foreach ( $tables as $table ) {
1435 // Is there a JOIN and INDEX clause for this table?
1436 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1437 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1438 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1439 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1440 $retJOIN[] = $tableClause;
1441 // Is there an INDEX clause?
1442 } else if ( isset($use_index_safe[$table]) ) {
1443 $tableClause = $this->tableName( $table );
1444 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1445 $ret[] = $tableClause;
1446 // Is there a JOIN clause?
1447 } else if ( isset($join_conds_safe[$table]) ) {
1448 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1449 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1450 $retJOIN[] = $tableClause;
1452 $tableClause = $this->tableName( $table );
1453 $ret[] = $tableClause;
1456 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1457 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1458 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1459 // Compile our final table clause
1460 return implode(' ',array($straightJoins,$otherJoins) );
1464 * Get the name of an index in a given table
1466 function indexName( $index ) {
1467 // Backwards-compatibility hack
1469 'ar_usertext_timestamp' => 'usertext_timestamp',
1470 'un_user_id' => 'user_id',
1471 'un_user_ip' => 'user_ip',
1473 if( isset( $renamed[$index] ) ) {
1474 return $renamed[$index];
1481 * Wrapper for addslashes()
1482 * @param $s String: to be slashed.
1483 * @return String: slashed string.
1485 abstract function strencode( $s );
1488 * If it's a string, adds quotes and backslashes
1489 * Otherwise returns as-is
1491 function addQuotes( $s ) {
1492 if ( $s === null ) {
1495 # This will also quote numeric values. This should be harmless,
1496 # and protects against weird problems that occur when they really
1497 # _are_ strings such as article titles and string->number->string
1498 # conversion is not 1:1.
1499 return "'" . $this->strencode( $s ) . "'";
1504 * Escape string for safe LIKE usage.
1505 * WARNING: you should almost never use this function directly,
1506 * instead use buildLike() that escapes everything automatically
1508 function escapeLike( $s ) {
1509 $s = str_replace( '\\', '\\\\', $s );
1510 $s = $this->strencode( $s );
1511 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1516 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1517 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1518 * Alternatively, the function could be provided with an array of aforementioned parameters.
1520 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1521 * for subpages of 'My page title'.
1522 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1524 * @ return String: fully built LIKE statement
1526 function buildLike() {
1527 $params = func_get_args();
1528 if (count($params) > 0 && is_array($params[0])) {
1529 $params = $params[0];
1533 foreach( $params as $value) {
1534 if( $value instanceof LikeMatch
) {
1535 $s .= $value->toString();
1537 $s .= $this->escapeLike( $value );
1540 return " LIKE '" . $s . "' ";
1544 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1546 function anyChar() {
1547 return new LikeMatch( '_' );
1551 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1553 function anyString() {
1554 return new LikeMatch( '%' );
1558 * Returns an appropriately quoted sequence value for inserting a new row.
1559 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1560 * subclass will return an integer, and save the value for insertId()
1562 function nextSequenceValue( $seqName ) {
1567 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1568 * is only needed because a) MySQL must be as efficient as possible due to
1569 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1570 * which index to pick. Anyway, other databases might have different
1571 * indexes on a given table. So don't bother overriding this unless you're
1574 function useIndexClause( $index ) {
1579 * REPLACE query wrapper
1580 * PostgreSQL simulates this with a DELETE followed by INSERT
1581 * $row is the row to insert, an associative array
1582 * $uniqueIndexes is an array of indexes. Each element may be either a
1583 * field name or an array of field names
1585 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1586 * However if you do this, you run the risk of encountering errors which wouldn't have
1589 * @todo migrate comment to phodocumentor format
1591 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1592 $table = $this->tableName( $table );
1595 if ( !is_array( reset( $rows ) ) ) {
1596 $rows = array( $rows );
1599 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1601 foreach ( $rows as $row ) {
1607 $sql .= '(' . $this->makeList( $row ) . ')';
1609 return $this->query( $sql, $fname );
1613 * DELETE where the condition is a join
1614 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1616 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1617 * join condition matches, set $conds='*'
1619 * DO NOT put the join condition in $conds
1621 * @param $delTable String: The table to delete from.
1622 * @param $joinTable String: The other table.
1623 * @param $delVar String: The variable to join on, in the first table.
1624 * @param $joinVar String: The variable to join on, in the second table.
1625 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1626 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1628 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1630 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1633 $delTable = $this->tableName( $delTable );
1634 $joinTable = $this->tableName( $joinTable );
1635 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1636 if ( $conds != '*' ) {
1637 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1640 return $this->query( $sql, $fname );
1644 * Returns the size of a text field, or -1 for "unlimited"
1646 function textFieldSize( $table, $field ) {
1647 $table = $this->tableName( $table );
1648 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1649 $res = $this->query( $sql, 'Database::textFieldSize' );
1650 $row = $this->fetchObject( $res );
1651 $this->freeResult( $res );
1654 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1663 * A string to insert into queries to show that they're low-priority, like
1664 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1665 * string and nothing bad should happen.
1667 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1669 function lowPriorityOption() {
1674 * DELETE query wrapper
1676 * Use $conds == "*" to delete all rows
1678 function delete( $table, $conds, $fname = 'Database::delete' ) {
1680 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1682 $table = $this->tableName( $table );
1683 $sql = "DELETE FROM $table";
1684 if ( $conds != '*' ) {
1685 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1687 return $this->query( $sql, $fname );
1691 * INSERT SELECT wrapper
1692 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1693 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1694 * $conds may be "*" to copy the whole table
1695 * srcTable may be an array of tables.
1697 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1698 $insertOptions = array(), $selectOptions = array() )
1700 $destTable = $this->tableName( $destTable );
1701 if ( is_array( $insertOptions ) ) {
1702 $insertOptions = implode( ' ', $insertOptions );
1704 if( !is_array( $selectOptions ) ) {
1705 $selectOptions = array( $selectOptions );
1707 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1708 if( is_array( $srcTable ) ) {
1709 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1711 $srcTable = $this->tableName( $srcTable );
1713 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1714 " SELECT $startOpts " . implode( ',', $varMap ) .
1715 " FROM $srcTable $useIndex ";
1716 if ( $conds != '*' ) {
1717 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1719 $sql .= " $tailOpts";
1720 return $this->query( $sql, $fname );
1724 * Construct a LIMIT query with optional offset. This is used for query
1725 * pages. The SQL should be adjusted so that only the first $limit rows
1726 * are returned. If $offset is provided as well, then the first $offset
1727 * rows should be discarded, and the next $limit rows should be returned.
1728 * If the result of the query is not ordered, then the rows to be returned
1729 * are theoretically arbitrary.
1731 * $sql is expected to be a SELECT, if that makes a difference. For
1732 * UPDATE, limitResultForUpdate should be used.
1734 * The version provided by default works in MySQL and SQLite. It will very
1735 * likely need to be overridden for most other DBMSes.
1737 * @param $sql String: SQL query we will append the limit too
1738 * @param $limit Integer: the SQL limit
1739 * @param $offset Integer the SQL offset (default false)
1741 function limitResult( $sql, $limit, $offset=false ) {
1742 if( !is_numeric( $limit ) ) {
1743 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1745 return "$sql LIMIT "
1746 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1749 function limitResultForUpdate( $sql, $num ) {
1750 return $this->limitResult( $sql, $num, 0 );
1754 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1755 * within the UNION construct.
1758 function unionSupportsOrderAndLimit() {
1759 return true; // True for almost every DB supported
1763 * Construct a UNION query
1764 * This is used for providing overload point for other DB abstractions
1765 * not compatible with the MySQL syntax.
1766 * @param $sqls Array: SQL statements to combine
1767 * @param $all Boolean: use UNION ALL
1768 * @return String: SQL fragment
1770 function unionQueries($sqls, $all) {
1771 $glue = $all ?
') UNION ALL (' : ') UNION (';
1772 return '('.implode( $glue, $sqls ) . ')';
1776 * Returns an SQL expression for a simple conditional. This doesn't need
1777 * to be overridden unless CASE isn't supported in your DBMS.
1779 * @param $cond String: SQL expression which will result in a boolean value
1780 * @param $trueVal String: SQL expression to return if true
1781 * @param $falseVal String: SQL expression to return if false
1782 * @return String: SQL fragment
1784 function conditional( $cond, $trueVal, $falseVal ) {
1785 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1789 * Returns a comand for str_replace function in SQL query.
1790 * Uses REPLACE() in MySQL
1792 * @param $orig String: column to modify
1793 * @param $old String: column to seek
1794 * @param $new String: column to replace with
1796 function strreplace( $orig, $old, $new ) {
1797 return "REPLACE({$orig}, {$old}, {$new})";
1801 * Determines if the last failure was due to a deadlock
1804 function wasDeadlock() {
1809 * Determines if the last query error was something that should be dealt
1810 * with by pinging the connection and reissuing the query.
1813 function wasErrorReissuable() {
1818 * Determines if the last failure was due to the database being read-only.
1821 function wasReadOnlyError() {
1826 * Perform a deadlock-prone transaction.
1828 * This function invokes a callback function to perform a set of write
1829 * queries. If a deadlock occurs during the processing, the transaction
1830 * will be rolled back and the callback function will be called again.
1833 * $dbw->deadlockLoop( callback, ... );
1835 * Extra arguments are passed through to the specified callback function.
1837 * Returns whatever the callback function returned on its successful,
1838 * iteration, or false on error, for example if the retry limit was
1841 function deadlockLoop() {
1842 $myFname = 'Database::deadlockLoop';
1845 $args = func_get_args();
1846 $function = array_shift( $args );
1847 $oldIgnore = $this->ignoreErrors( true );
1848 $tries = DEADLOCK_TRIES
;
1849 if ( is_array( $function ) ) {
1850 $fname = $function[0];
1855 $retVal = call_user_func_array( $function, $args );
1856 $error = $this->lastError();
1857 $errno = $this->lastErrno();
1858 $sql = $this->lastQuery();
1861 if ( $this->wasDeadlock() ) {
1863 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1865 $this->reportQueryError( $error, $errno, $sql, $fname );
1868 } while( $this->wasDeadlock() && --$tries > 0 );
1869 $this->ignoreErrors( $oldIgnore );
1870 if ( $tries <= 0 ) {
1871 $this->query( 'ROLLBACK', $myFname );
1872 $this->reportQueryError( $error, $errno, $sql, $fname );
1875 $this->query( 'COMMIT', $myFname );
1881 * Do a SELECT MASTER_POS_WAIT()
1883 * @param $pos MySQLMasterPos object
1884 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1886 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1887 $fname = 'Database::masterPosWait';
1888 wfProfileIn( $fname );
1890 # Commit any open transactions
1891 if ( $this->mTrxLevel
) {
1895 if ( !is_null( $this->mFakeSlaveLag
) ) {
1896 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1897 if ( $wait > $timeout * 1e6
) {
1898 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1899 wfProfileOut( $fname );
1901 } elseif ( $wait > 0 ) {
1902 wfDebug( "Fake slave waiting $wait us\n" );
1904 wfProfileOut( $fname );
1907 wfDebug( "Fake slave up to date ($wait us)\n" );
1908 wfProfileOut( $fname );
1913 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1914 $encFile = $this->addQuotes( $pos->file
);
1915 $encPos = intval( $pos->pos
);
1916 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1917 $res = $this->doQuery( $sql );
1918 if ( $res && $row = $this->fetchRow( $res ) ) {
1919 $this->freeResult( $res );
1920 wfProfileOut( $fname );
1923 wfProfileOut( $fname );
1929 * Get the position of the master from SHOW SLAVE STATUS
1931 function getSlavePos() {
1932 if ( !is_null( $this->mFakeSlaveLag
) ) {
1933 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1934 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1937 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1938 $row = $this->fetchObject( $res );
1940 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1941 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1948 * Get the position of the master from SHOW MASTER STATUS
1950 function getMasterPos() {
1951 if ( $this->mFakeMaster
) {
1952 return new MySQLMasterPos( 'fake', microtime( true ) );
1954 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1955 $row = $this->fetchObject( $res );
1957 return new MySQLMasterPos( $row->File
, $row->Position
);
1964 * Begin a transaction, committing any previously open transaction
1966 function begin( $fname = 'Database::begin' ) {
1967 $this->query( 'BEGIN', $fname );
1968 $this->mTrxLevel
= 1;
1974 function commit( $fname = 'Database::commit' ) {
1975 $this->query( 'COMMIT', $fname );
1976 $this->mTrxLevel
= 0;
1980 * Rollback a transaction.
1981 * No-op on non-transactional databases.
1983 function rollback( $fname = 'Database::rollback' ) {
1984 $this->query( 'ROLLBACK', $fname, true );
1985 $this->mTrxLevel
= 0;
1989 * Begin a transaction, committing any previously open transaction
1990 * @deprecated use begin()
1992 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1997 * Commit transaction, if one is open
1998 * @deprecated use commit()
2000 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2005 * Creates a new table with structure copied from existing table
2006 * Note that unlike most database abstraction functions, this function does not
2007 * automatically append database prefix, because it works at a lower
2008 * abstraction level.
2010 * @param $oldName String: name of table whose structure should be copied
2011 * @param $newName String: name of table to be created
2012 * @param $temporary Boolean: whether the new table should be temporary
2013 * @return Boolean: true if operation was successful
2015 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2016 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2020 * Return MW-style timestamp used for MySQL schema
2022 function timestamp( $ts=0 ) {
2023 return wfTimestamp(TS_MW
,$ts);
2027 * Local database timestamp format or null
2029 function timestampOrNull( $ts = null ) {
2030 if( is_null( $ts ) ) {
2033 return $this->timestamp( $ts );
2040 function resultObject( $result ) {
2041 if( empty( $result ) ) {
2043 } elseif ( $result instanceof ResultWrapper
) {
2045 } elseif ( $result === true ) {
2046 // Successful write query
2049 return new ResultWrapper( $this, $result );
2054 * Return aggregated value alias
2056 function aggregateValue ($valuedata,$valuename='value') {
2061 * Returns a wikitext link to the DB's website, e.g.,
2062 * return "[http://www.mysql.com/ MySQL]";
2063 * Should at least contain plain text, if for some reason
2064 * your database has no website.
2066 * @return String: wikitext of a link to the server software's web site
2068 abstract function getSoftwareLink();
2071 * A string describing the current software version, like from
2072 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2074 * @return String: Version information from the database
2076 abstract function getServerVersion();
2079 * Ping the server and try to reconnect if it there is no connection
2081 * @return bool Success or failure
2084 # Stub. Not essential to override.
2090 * At the moment, this will only work if the DB user has the PROCESS privilege
2093 if ( !is_null( $this->mFakeSlaveLag
) ) {
2094 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2095 return $this->mFakeSlaveLag
;
2097 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
2098 # Find slave SQL thread
2099 while ( $row = $this->fetchObject( $res ) ) {
2100 /* This should work for most situations - when default db
2101 * for thread is not specified, it had no events executed,
2102 * and therefore it doesn't know yet how lagged it is.
2104 * Relay log I/O thread does not select databases.
2106 if ( $row->User
== 'system user' &&
2107 $row->State
!= 'Waiting for master to send event' &&
2108 $row->State
!= 'Connecting to master' &&
2109 $row->State
!= 'Queueing master event to the relay log' &&
2110 $row->State
!= 'Waiting for master update' &&
2111 $row->State
!= 'Requesting binlog dump' &&
2112 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
2113 $row->State
!= 'Reconnecting after a failed master event read' &&
2114 $row->State
!= 'Registering slave on master'
2116 # This is it, return the time (except -ve)
2117 if ( $row->Time
> 0x7fffffff ) {
2128 * Get status information from SHOW STATUS in an associative array
2130 function getStatus($which="%") {
2131 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2133 while ( $row = $this->fetchObject( $res ) ) {
2134 $status[$row->Variable_name
] = $row->Value
;
2140 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2142 function maxListLen() {
2146 function encodeBlob($b) {
2150 function decodeBlob($b) {
2155 * Override database's default connection timeout. May be useful for very
2156 * long batch queries such as full-wiki dumps, where a single query reads
2157 * out over hours or days. May or may not be necessary for non-MySQL
2158 * databases. For most purposes, leaving it as a no-op should be fine.
2160 * @param $timeout Integer in seconds
2162 public function setTimeout( $timeout ) {}
2165 * Read and execute SQL commands from a file.
2166 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2167 * @param $filename String: File name to open
2168 * @param $lineCallback Callback: Optional function called before reading each line
2169 * @param $resultCallback Callback: Optional function called for each MySQL result
2171 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2172 $fp = fopen( $filename, 'r' );
2173 if ( false === $fp ) {
2174 throw new MWException( "Could not open \"{$filename}\".\n" );
2176 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2182 * Get the full path of a patch file. Originally based on archive()
2183 * from updaters.inc. Keep in mind this always returns a patch, as
2184 * it fails back to MySQL if no DB-specific patch can be found
2186 * @param $patch String The name of the patch, like patch-something.sql
2187 * @return String Full path to patch file
2189 public static function patchPath( $patch ) {
2190 global $wgDBtype, $IP;
2191 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
2192 return "$IP/maintenance/$wgDBtype/archives/$name";
2194 return "$IP/maintenance/archives/$name";
2199 * Read and execute commands from an open file handle
2200 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2201 * @param $fp String: File handle
2202 * @param $lineCallback Callback: Optional function called before reading each line
2203 * @param $resultCallback Callback: Optional function called for each MySQL result
2205 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2208 $dollarquote = false;
2210 while ( ! feof( $fp ) ) {
2211 if ( $lineCallback ) {
2212 call_user_func( $lineCallback );
2214 $line = trim( fgets( $fp, 1024 ) );
2215 $sl = strlen( $line ) - 1;
2217 if ( $sl < 0 ) { continue; }
2218 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2220 ## Allow dollar quoting for function declarations
2221 if (substr($line,0,4) == '$mw$') {
2223 $dollarquote = false;
2227 $dollarquote = true;
2230 else if (!$dollarquote) {
2231 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2233 $line = substr( $line, 0, $sl );
2237 if ( $cmd != '' ) { $cmd .= ' '; }
2241 $cmd = str_replace(';;', ";", $cmd);
2242 $cmd = $this->replaceVars( $cmd );
2243 $res = $this->query( $cmd, __METHOD__
);
2244 if ( $resultCallback ) {
2245 call_user_func( $resultCallback, $res, $this );
2248 if ( false === $res ) {
2249 $err = $this->lastError();
2250 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2262 * Replace variables in sourced SQL
2264 protected function replaceVars( $ins ) {
2266 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2267 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2268 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2271 // Ordinary variables
2272 foreach ( $varnames as $var ) {
2273 if( isset( $GLOBALS[$var] ) ) {
2274 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2275 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2276 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2277 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2282 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2283 array( $this, 'tableNameCallback' ), $ins );
2286 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2287 array( $this, 'indexNameCallback' ), $ins );
2292 * Table name callback
2295 protected function tableNameCallback( $matches ) {
2296 return $this->tableName( $matches[1] );
2300 * Index name callback
2302 protected function indexNameCallback( $matches ) {
2303 return $this->indexName( $matches[1] );
2307 * Build a concatenation list to feed into a SQL query
2308 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2311 function buildConcat( $stringList ) {
2312 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2316 * Acquire a named lock
2318 * Abstracted from Filestore::lock() so child classes can implement for
2321 * @param $lockName String: Name of lock to aquire
2322 * @param $method String: Name of method calling us
2325 public function lock( $lockName, $method, $timeout = 5 ) {
2332 * @param $lockName String: Name of lock to release
2333 * @param $method String: Name of method calling us
2335 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2336 * @return Returns 1 if the lock was released, 0 if the lock was not established
2337 * by this thread (in which case the lock is not released), and NULL if the named
2338 * lock did not exist
2340 public function unlock( $lockName, $method ) {
2345 * Lock specific tables
2347 * @param $read Array of tables to lock for read access
2348 * @param $write Array of tables to lock for write access
2349 * @param $method String name of caller
2350 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2352 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2357 * Unlock specific tables
2359 * @param $method String the caller
2361 public function unlockTables( $method ) {
2366 * Get search engine class. All subclasses of this
2367 * need to implement this if they wish to use searching.
2371 public function getSearchEngine() {
2372 return "SearchMySQL";
2376 * Allow or deny "big selects" for this session only. This is done by setting
2377 * the sql_big_selects session variable.
2379 * This is a MySQL-specific feature.
2381 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2383 public function setBigSelects( $value = true ) {
2389 /******************************************************************************
2391 *****************************************************************************/
2400 function DBObject($data) {
2401 $this->mData
= $data;
2409 return $this->mData
;
2417 * This allows us to distinguish a blob from a normal string and an array of strings
2421 function __construct($data) {
2422 $this->mData
= $data;
2425 return $this->mData
;
2434 private $name, $tablename, $default, $max_length, $nullable,
2435 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2436 function __construct ($info) {
2437 $this->name
= $info->name
;
2438 $this->tablename
= $info->table
;
2439 $this->default = $info->def
;
2440 $this->max_length
= $info->max_length
;
2441 $this->nullable
= !$info->not_null
;
2442 $this->is_pk
= $info->primary_key
;
2443 $this->is_unique
= $info->unique_key
;
2444 $this->is_multiple
= $info->multiple_key
;
2445 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2446 $this->type
= $info->type
;
2453 function tableName() {
2454 return $this->tableName
;
2457 function defaultValue() {
2458 return $this->default;
2461 function maxLength() {
2462 return $this->max_length
;
2465 function nullable() {
2466 return $this->nullable
;
2470 return $this->is_key
;
2473 function isMultipleKey() {
2474 return $this->is_multiple
;
2482 /******************************************************************************
2484 *****************************************************************************/
2487 * Database error base class
2490 class DBError
extends MWException
{
2494 * Construct a database error
2495 * @param $db Database object which threw the error
2496 * @param $error A simple error message to be used for debugging
2498 function __construct( DatabaseBase
&$db, $error ) {
2500 parent
::__construct( $error );
2503 function getText() {
2504 global $wgShowDBErrorBacktrace;
2505 $s = $this->getMessage() . "\n";
2506 if ( $wgShowDBErrorBacktrace ) {
2507 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2516 class DBConnectionError
extends DBError
{
2519 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2520 $msg = 'DB connection error';
2521 if ( trim( $error ) != '' ) {
2524 $this->error
= $error;
2525 parent
::__construct( $db, $msg );
2528 function useOutputPage() {
2529 // Not likely to work
2533 function useMessageCache() {
2534 // Not likely to work
2538 function getLogMessage() {
2539 # Don't send to the exception log
2543 function getPageTitle() {
2544 global $wgSitename, $wgLang;
2545 $header = "$wgSitename has a problem";
2546 if ( $wgLang instanceof Language
) {
2547 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2553 function getHTML() {
2554 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2556 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2557 $again = 'Try waiting a few minutes and reloading.';
2558 $info = '(Can\'t contact the database server: $1)';
2560 if ( $wgLang instanceof Language
) {
2561 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2562 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2563 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2566 # No database access
2567 if ( is_object( $wgMessageCache ) ) {
2568 $wgMessageCache->disable();
2571 if ( trim( $this->error
) == '' ) {
2572 $this->error
= $this->db
->getProperty('mServer');
2575 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2576 $text = str_replace( '$1', $this->error
, $noconnect );
2578 if ( $wgShowDBErrorBacktrace ) {
2579 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2582 $extra = $this->searchForm();
2584 if( $wgUseFileCache ) {
2586 $cache = $this->fileCachedPage();
2587 # Cached version on file system?
2588 if( $cache !== null ) {
2589 # Hack: extend the body for error messages
2590 $cache = str_replace( array('</html>','</body>'), '', $cache );
2591 # Add cache notice...
2592 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2593 # Localize it if possible...
2594 if( $wgLang instanceof Language
) {
2595 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2597 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2598 # Output cached page with notices on bottom and re-close body
2599 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2601 } catch( MWException
$e ) {
2602 // Do nothing, just use the default page
2605 # Headers needed here - output is just the error message
2606 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2609 function searchForm() {
2610 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2611 $usegoogle = "You can try searching via Google in the meantime.";
2612 $outofdate = "Note that their indexes of our content may be out of date.";
2613 $googlesearch = "Search";
2615 if ( $wgLang instanceof Language
) {
2616 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2617 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2618 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2621 $search = htmlspecialchars(@$_REQUEST['search']);
2624 <div style="margin: 1.5em">$usegoogle<br />
2625 <small>$outofdate</small></div>
2626 <!-- SiteSearch Google -->
2627 <form method="get" action="http://www.google.com/search" id="googlesearch">
2628 <input type="hidden" name="domains" value="$wgServer" />
2629 <input type="hidden" name="num" value="50" />
2630 <input type="hidden" name="ie" value="$wgInputEncoding" />
2631 <input type="hidden" name="oe" value="$wgInputEncoding" />
2633 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2635 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2636 <input type="submit" name="btnG" value="$googlesearch" />
2638 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2639 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2642 <!-- SiteSearch Google -->
2647 function fileCachedPage() {
2648 global $wgTitle, $title, $wgLang, $wgOut;
2649 if( $wgOut->isDisabled() ) return; // Done already?
2650 $mainpage = 'Main Page';
2651 if ( $wgLang instanceof Language
) {
2652 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2657 } elseif( $title ) {
2658 $t = Title
::newFromURL( $title );
2660 $t = Title
::newFromText( $mainpage );
2663 $cache = new HTMLFileCache( $t );
2664 if( $cache->isFileCached() ) {
2665 return $cache->fetchPageText();
2671 function htmlBodyOnly() {
2680 class DBQueryError
extends DBError
{
2681 public $error, $errno, $sql, $fname;
2683 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2684 $message = "A database error has occurred\n" .
2686 "Function: $fname\n" .
2687 "Error: $errno $error\n";
2689 parent
::__construct( $db, $message );
2690 $this->error
= $error;
2691 $this->errno
= $errno;
2693 $this->fname
= $fname;
2696 function getText() {
2697 global $wgShowDBErrorBacktrace;
2698 if ( $this->useMessageCache() ) {
2699 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2700 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2701 if ( $wgShowDBErrorBacktrace ) {
2702 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2706 return parent
::getText();
2711 global $wgShowSQLErrors;
2712 if( !$wgShowSQLErrors ) {
2713 return $this->msg( 'sqlhidden', 'SQL hidden' );
2719 function getLogMessage() {
2720 # Don't send to the exception log
2724 function getPageTitle() {
2725 return $this->msg( 'databaseerror', 'Database error' );
2728 function getHTML() {
2729 global $wgShowDBErrorBacktrace;
2730 if ( $this->useMessageCache() ) {
2731 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2732 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2734 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2736 if ( $wgShowDBErrorBacktrace ) {
2737 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2746 class DBUnexpectedError
extends DBError
{}
2750 * Result wrapper for grabbing data queried by someone else
2753 class ResultWrapper
implements Iterator
{
2754 var $db, $result, $pos = 0, $currentRow = null;
2757 * Create a new result object from a result resource and a Database object
2759 function ResultWrapper( $database, $result ) {
2760 $this->db
= $database;
2761 if ( $result instanceof ResultWrapper
) {
2762 $this->result
= $result->result
;
2764 $this->result
= $result;
2769 * Get the number of rows in a result object
2771 function numRows() {
2772 return $this->db
->numRows( $this );
2776 * Fetch the next row from the given result object, in object form.
2777 * Fields can be retrieved with $row->fieldname, with fields acting like
2780 * @param $res SQL result object as returned from Database::query(), etc.
2781 * @return MySQL row object
2782 * @throws DBUnexpectedError Thrown if the database returns an error
2784 function fetchObject() {
2785 return $this->db
->fetchObject( $this );
2789 * Fetch the next row from the given result object, in associative array
2790 * form. Fields are retrieved with $row['fieldname'].
2792 * @param $res SQL result object as returned from Database::query(), etc.
2793 * @return MySQL row object
2794 * @throws DBUnexpectedError Thrown if the database returns an error
2796 function fetchRow() {
2797 return $this->db
->fetchRow( $this );
2801 * Free a result object
2804 $this->db
->freeResult( $this );
2805 unset( $this->result
);
2810 * Change the position of the cursor in a result object
2811 * See mysql_data_seek()
2813 function seek( $row ) {
2814 $this->db
->dataSeek( $this, $row );
2817 /*********************
2818 * Iterator functions
2819 * Note that using these in combination with the non-iterator functions
2820 * above may cause rows to be skipped or repeated.
2824 if ($this->numRows()) {
2825 $this->db
->dataSeek($this, 0);
2828 $this->currentRow
= null;
2831 function current() {
2832 if ( is_null( $this->currentRow
) ) {
2835 return $this->currentRow
;
2844 $this->currentRow
= $this->fetchObject();
2845 return $this->currentRow
;
2849 return $this->current() !== false;
2854 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2855 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2860 public function __construct( $s ) {
2864 public function toString() {