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.
290 abstract function getType();
292 #------------------------------------------------------------------------------
294 #------------------------------------------------------------------------------
298 * @param $server String: database server host
299 * @param $user String: database user name
300 * @param $password String: database user password
301 * @param $dbName String: database name
302 * @param $failFunction
304 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
306 function __construct( $server = false, $user = false, $password = false, $dbName = false,
307 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
309 global $wgOut, $wgDBprefix, $wgCommandLineMode;
310 # Can't get a reference if it hasn't been set yet
311 if ( !isset( $wgOut ) ) {
315 $this->mFailFunction
= $failFunction;
316 $this->mFlags
= $flags;
318 if ( $this->mFlags
& DBO_DEFAULT
) {
319 if ( $wgCommandLineMode ) {
320 $this->mFlags
&= ~DBO_TRX
;
322 $this->mFlags |
= DBO_TRX
;
327 // Faster read-only access
328 if ( wfReadOnly() ) {
329 $this->mFlags |= DBO_PERSISTENT;
330 $this->mFlags &= ~DBO_TRX;
333 /** Get the default table prefix*/
334 if ( $tablePrefix == 'get from global' ) {
335 $this->mTablePrefix
= $wgDBprefix;
337 $this->mTablePrefix
= $tablePrefix;
341 $this->open( $server, $user, $password, $dbName );
346 * Same as new DatabaseMysql( ... ), kept for backward compatibility
347 * @param $server String: database server host
348 * @param $user String: database user name
349 * @param $password String: database user password
350 * @param $dbName String: database name
351 * @param failFunction
354 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
356 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
360 * Usually aborts on failure
361 * If the failFunction is set to a non-zero integer, returns success
362 * @param $server String: database server host
363 * @param $user String: database user name
364 * @param $password String: database user password
365 * @param $dbName String: database name
367 abstract function open( $server, $user, $password, $dbName );
369 protected function installErrorHandler() {
370 $this->mPHPError
= false;
371 $this->htmlErrors
= ini_set( 'html_errors', '0' );
372 set_error_handler( array( $this, 'connectionErrorHandler' ) );
375 protected function restoreErrorHandler() {
376 restore_error_handler();
377 if ( $this->htmlErrors
!== false ) {
378 ini_set( 'html_errors', $this->htmlErrors
);
380 if ( $this->mPHPError
) {
381 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
382 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
389 protected function connectionErrorHandler( $errno, $errstr ) {
390 $this->mPHPError
= $errstr;
394 * Closes a database connection.
395 * if it is open : commits any open transactions
397 * @return Bool operation success. true if already closed.
400 # Stub, should probably be overridden
405 * @param $error String: fallback error message, used if none is given by MySQL
407 function reportConnectionError( $error = 'Unknown error' ) {
408 $myError = $this->lastError();
413 if ( $this->mFailFunction
) {
414 # Legacy error handling method
415 if ( !is_int( $this->mFailFunction
) ) {
416 $ff = $this->mFailFunction
;
417 $ff( $this, $error );
421 throw new DBConnectionError( $this, $error );
426 * Determine whether a query writes to the DB.
427 * Should return true if unsure.
429 function isWriteQuery( $sql ) {
430 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
434 * Usually aborts on failure. If errors are explicitly ignored, returns success.
436 * @param $sql String: SQL query
437 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
438 * comment (you can use __METHOD__ or add some extra info)
439 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
440 * maybe best to catch the exception instead?
441 * @return true for a successful write query, ResultWrapper object for a successful read query,
442 * or false on failure if $tempIgnore set
443 * @throws DBQueryError Thrown when the database returns an error of any kind
445 public function query( $sql, $fname = '', $tempIgnore = false ) {
448 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
449 if ( isset( $wgProfiler ) ) {
450 # generalizeSQL will probably cut down the query to reasonable
451 # logging size most of the time. The substr is really just a sanity check.
453 # Who's been wasting my precious column space? -- TS
454 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
457 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
458 $totalProf = 'Database::query-master';
460 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
461 $totalProf = 'Database::query';
463 wfProfileIn( $totalProf );
464 wfProfileIn( $queryProf );
467 $this->mLastQuery
= $sql;
468 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
469 // Set a flag indicating that writes have been done
470 wfDebug( __METHOD__
.": Writes done: $sql\n" );
471 $this->mDoneWrites
= true;
474 # Add a comment for easy SHOW PROCESSLIST interpretation
477 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
478 $userName = $wgUser->getName();
479 if ( mb_strlen( $userName ) > 15 ) {
480 $userName = mb_substr( $userName, 0, 15 ) . '...';
482 $userName = str_replace( '/', '', $userName );
486 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
488 # $commentedSql = $sql;
491 # If DBO_TRX is set, start a transaction
492 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
493 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
494 // avoid establishing transactions for SHOW and SET statements too -
495 // that would delay transaction initializations to once connection
496 // is really used by application
497 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
498 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
502 if ( $this->debug() ) {
503 $sqlx = substr( $commentedSql, 0, 500 );
504 $sqlx = strtr( $sqlx, "\t\n", ' ' );
506 wfDebug( "SQL-master: $sqlx\n" );
508 wfDebug( "SQL: $sqlx\n" );
512 if ( istainted( $sql ) & TC_MYSQL
) {
513 throw new MWException( 'Tainted query found' );
516 # Do the query and handle errors
517 $ret = $this->doQuery( $commentedSql );
519 # Try reconnecting if the connection was lost
520 if ( false === $ret && $this->wasErrorReissuable() ) {
521 # Transaction is gone, like it or not
522 $this->mTrxLevel
= 0;
523 wfDebug( "Connection lost, reconnecting...\n" );
524 if ( $this->ping() ) {
525 wfDebug( "Reconnected\n" );
526 $sqlx = substr( $commentedSql, 0, 500 );
527 $sqlx = strtr( $sqlx, "\t\n", ' ' );
528 global $wgRequestTime;
529 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
530 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
531 $ret = $this->doQuery( $commentedSql );
533 wfDebug( "Failed\n" );
537 if ( false === $ret ) {
538 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
541 if ( isset( $wgProfiler ) ) {
542 wfProfileOut( $queryProf );
543 wfProfileOut( $totalProf );
545 return $this->resultObject( $ret );
549 * The DBMS-dependent part of query()
550 * @param $sql String: SQL query.
551 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
554 /*private*/ abstract function doQuery( $sql );
557 * @param $error String
558 * @param $errno Integer
560 * @param $fname String
561 * @param $tempIgnore Boolean
563 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
564 global $wgCommandLineMode;
565 # Ignore errors during error handling to avoid infinite recursion
566 $ignore = $this->ignoreErrors( true );
567 ++
$this->mErrorCount
;
569 if( $ignore ||
$tempIgnore ) {
570 wfDebug("SQL ERROR (ignored): $error\n");
571 $this->ignoreErrors( $ignore );
573 $sql1line = str_replace( "\n", "\\n", $sql );
574 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
575 wfDebug("SQL ERROR: " . $error . "\n");
576 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
582 * Intended to be compatible with the PEAR::DB wrapper functions.
583 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
585 * ? = scalar value, quoted as necessary
586 * ! = raw SQL bit (a function for instance)
587 * & = filename; reads the file and inserts as a blob
588 * (we don't use this though...)
590 function prepare( $sql, $func = 'Database::prepare' ) {
591 /* MySQL doesn't support prepared statements (yet), so just
592 pack up the query for reference. We'll manually replace
594 return array( 'query' => $sql, 'func' => $func );
597 function freePrepared( $prepared ) {
598 /* No-op for MySQL */
602 * Execute a prepared query with the various arguments
603 * @param $prepared String: the prepared sql
604 * @param $args Mixed: Either an array here, or put scalars as varargs
606 function execute( $prepared, $args = null ) {
607 if( !is_array( $args ) ) {
609 $args = func_get_args();
610 array_shift( $args );
612 $sql = $this->fillPrepared( $prepared['query'], $args );
613 return $this->query( $sql, $prepared['func'] );
617 * Prepare & execute an SQL statement, quoting and inserting arguments
618 * in the appropriate places.
619 * @param $query String
622 function safeQuery( $query, $args = null ) {
623 $prepared = $this->prepare( $query, 'Database::safeQuery' );
624 if( !is_array( $args ) ) {
626 $args = func_get_args();
627 array_shift( $args );
629 $retval = $this->execute( $prepared, $args );
630 $this->freePrepared( $prepared );
635 * For faking prepared SQL statements on DBs that don't support
637 * @param $preparedQuery String: a 'preparable' SQL statement
638 * @param $args Array of arguments to fill it with
639 * @return string executable SQL
641 function fillPrepared( $preparedQuery, $args ) {
643 $this->preparedArgs
=& $args;
644 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
645 array( &$this, 'fillPreparedArg' ), $preparedQuery );
649 * preg_callback func for fillPrepared()
650 * The arguments should be in $this->preparedArgs and must not be touched
651 * while we're doing this.
653 * @param $matches Array
657 function fillPreparedArg( $matches ) {
658 switch( $matches[1] ) {
659 case '\\?': return '?';
660 case '\\!': return '!';
661 case '\\&': return '&';
663 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
664 switch( $matches[1] ) {
665 case '?': return $this->addQuotes( $arg );
666 case '!': return $arg;
668 # return $this->addQuotes( file_get_contents( $arg ) );
669 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
671 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
676 * Free a result object
677 * @param $res Mixed: A SQL result
679 function freeResult( $res ) {
680 # Stub. Might not really need to be overridden, since results should
681 # be freed by PHP when the variable goes out of scope anyway.
685 * Fetch the next row from the given result object, in object form.
686 * Fields can be retrieved with $row->fieldname, with fields acting like
689 * @param $res SQL result object as returned from Database::query(), etc.
690 * @return MySQL row object
691 * @throws DBUnexpectedError Thrown if the database returns an error
693 abstract function fetchObject( $res );
696 * Fetch the next row from the given result object, in associative array
697 * form. Fields are retrieved with $row['fieldname'].
699 * @param $res SQL result object as returned from Database::query(), etc.
700 * @return MySQL row object
701 * @throws DBUnexpectedError Thrown if the database returns an error
703 abstract function fetchRow( $res );
706 * Get the number of rows in a result object
707 * @param $res Mixed: A SQL result
709 abstract function numRows( $res );
712 * Get the number of fields in a result object
713 * See documentation for mysql_num_fields()
714 * @param $res Mixed: A SQL result
716 abstract function numFields( $res );
719 * Get a field name in a result object
720 * See documentation for mysql_field_name():
721 * http://www.php.net/mysql_field_name
722 * @param $res Mixed: A SQL result
725 abstract function fieldName( $res, $n );
728 * Get the inserted value of an auto-increment row
730 * The value inserted should be fetched from nextSequenceValue()
733 * $id = $dbw->nextSequenceValue('page_page_id_seq');
734 * $dbw->insert('page',array('page_id' => $id));
735 * $id = $dbw->insertId();
737 abstract function insertId();
740 * Change the position of the cursor in a result object
741 * See mysql_data_seek()
742 * @param $res Mixed: A SQL result
743 * @param $row Mixed: Either MySQL row or ResultWrapper
745 abstract function dataSeek( $res, $row );
748 * Get the last error number
751 abstract function lastErrno();
754 * Get a description of the last error
755 * See mysql_error() for more details
757 abstract function lastError();
760 * Get the number of rows affected by the last write query
761 * See mysql_affected_rows() for more details
763 abstract function affectedRows();
766 * Simple UPDATE wrapper
767 * Usually aborts on failure
768 * If errors are explicitly ignored, returns success
770 * This function exists for historical reasons, Database::update() has a more standard
771 * calling convention and feature set
773 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
774 $table = $this->tableName( $table );
775 $sql = "UPDATE $table SET $var = '" .
776 $this->strencode( $value ) . "' WHERE ($cond)";
777 return (bool)$this->query( $sql, $fname );
781 * Simple SELECT wrapper, returns a single field, input must be encoded
782 * Usually aborts on failure
783 * If errors are explicitly ignored, returns FALSE on failure
785 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
786 if ( !is_array( $options ) ) {
787 $options = array( $options );
789 $options['LIMIT'] = 1;
791 $res = $this->select( $table, $var, $cond, $fname, $options );
792 if ( $res === false ||
!$this->numRows( $res ) ) {
795 $row = $this->fetchRow( $res );
796 if ( $row !== false ) {
797 $this->freeResult( $res );
798 return reset( $row );
805 * Returns an optional USE INDEX clause to go after the table, and a
806 * string to go at the end of the query
810 * @param $options Array: associative array of options to be turned into
811 * an SQL query, valid keys are listed in the function.
814 function makeSelectOptions( $options ) {
815 $preLimitTail = $postLimitTail = '';
818 $noKeyOptions = array();
819 foreach ( $options as $key => $option ) {
820 if ( is_numeric( $key ) ) {
821 $noKeyOptions[$option] = true;
825 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
826 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
827 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
829 //if (isset($options['LIMIT'])) {
830 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
831 // isset($options['OFFSET']) ? $options['OFFSET']
835 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
836 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
837 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
839 # Various MySQL extensions
840 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
841 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
842 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
843 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
844 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
845 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
846 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
847 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
849 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
850 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
855 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
861 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
862 * @param $vars Mixed: Array or string, field name(s) to be retrieved
863 * @param $conds Mixed: Array or string, condition(s) for WHERE
864 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
865 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
866 * see Database::makeSelectOptions code for list of supported stuff
867 * @param $join_conds Array: Associative array of table join conditions (optional)
868 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
869 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
871 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
873 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
874 return $this->query( $sql, $fname );
880 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
881 * @param $vars Mixed: Array or string, field name(s) to be retrieved
882 * @param $conds Mixed: Array or string, condition(s) for WHERE
883 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
884 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
885 * see Database::makeSelectOptions code for list of supported stuff
886 * @param $join_conds Array: Associative array of table join conditions (optional)
887 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
888 * @return string, the SQL text
890 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
891 if( is_array( $vars ) ) {
892 $vars = implode( ',', $vars );
894 if( !is_array( $options ) ) {
895 $options = array( $options );
897 if( is_array( $table ) ) {
898 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
899 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
901 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
902 } elseif ($table!='') {
903 if ($table{0}==' ') {
904 $from = ' FROM ' . $table;
906 $from = ' FROM ' . $this->tableName( $table );
912 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
914 if( !empty( $conds ) ) {
915 if ( is_array( $conds ) ) {
916 $conds = $this->makeList( $conds, LIST_AND
);
918 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
920 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
923 if (isset($options['LIMIT']))
924 $sql = $this->limitResult($sql, $options['LIMIT'],
925 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
926 $sql = "$sql $postLimitTail";
928 if (isset($options['EXPLAIN'])) {
929 $sql = 'EXPLAIN ' . $sql;
935 * Single row SELECT wrapper
936 * Aborts or returns FALSE on error
938 * @param $table String: table name
939 * @param $vars String: the selected variables
940 * @param $conds Array: a condition map, terms are ANDed together.
941 * Items with numeric keys are taken to be literal conditions
942 * Takes an array of selected variables, and a condition map, which is ANDed
943 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
944 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
945 * $obj- >page_id is the ID of the Astronomy article
946 * @param $fname String: Calling function name
947 * @param $options Array
948 * @param $join_conds Array
950 * @todo migrate documentation to phpdocumentor format
952 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
953 $options['LIMIT'] = 1;
954 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
955 if ( $res === false )
957 if ( !$this->numRows($res) ) {
958 $this->freeResult($res);
961 $obj = $this->fetchObject( $res );
962 $this->freeResult( $res );
968 * Estimate rows in dataset
969 * Returns estimated count - not necessarily an accurate estimate across different databases,
971 * Takes same arguments as Database::select()
973 * @param string $table table name
974 * @param array $vars unused
975 * @param array $conds filters on the table
976 * @param string $fname function name for profiling
977 * @param array $options options for select
978 * @return int row count
980 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
982 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
984 $row = $this->fetchRow( $res );
985 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
987 $this->freeResult( $res );
992 * Removes most variables from an SQL query and replaces them with X or N for numbers.
993 * It's only slightly flawed. Don't use for anything important.
995 * @param $sql String: A SQL Query
997 static function generalizeSQL( $sql ) {
998 # This does the same as the regexp below would do, but in such a way
999 # as to avoid crashing php on some large strings.
1000 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1002 $sql = str_replace ( "\\\\", '', $sql);
1003 $sql = str_replace ( "\\'", '', $sql);
1004 $sql = str_replace ( "\\\"", '', $sql);
1005 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1006 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1008 # All newlines, tabs, etc replaced by single space
1009 $sql = preg_replace ( '/\s+/', ' ', $sql);
1012 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1018 * Determines whether a field exists in a table
1019 * Usually aborts on failure
1020 * If errors are explicitly ignored, returns NULL on failure
1022 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1023 $table = $this->tableName( $table );
1024 $res = $this->query( 'DESCRIBE '.$table, $fname );
1031 while ( $row = $this->fetchObject( $res ) ) {
1032 if ( $row->Field
== $field ) {
1041 * Determines whether an index exists
1042 * Usually aborts on failure
1043 * If errors are explicitly ignored, returns NULL on failure
1045 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1046 $info = $this->indexInfo( $table, $index, $fname );
1047 if ( is_null( $info ) ) {
1050 return $info !== false;
1056 * Get information about an index into an object
1057 * Returns false if the index does not exist
1059 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1060 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1061 # SHOW INDEX should work for 3.x and up:
1062 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1063 $table = $this->tableName( $table );
1064 $index = $this->indexName( $index );
1065 $sql = 'SHOW INDEX FROM '.$table;
1066 $res = $this->query( $sql, $fname );
1072 while ( $row = $this->fetchObject( $res ) ) {
1073 if ( $row->Key_name
== $index ) {
1077 $this->freeResult($res);
1079 return empty($result) ?
false : $result;
1083 * Query whether a given table exists
1085 function tableExists( $table ) {
1086 $table = $this->tableName( $table );
1087 $old = $this->ignoreErrors( true );
1088 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1089 $this->ignoreErrors( $old );
1091 $this->freeResult( $res );
1099 * mysql_fetch_field() wrapper
1100 * Returns false if the field doesn't exist
1105 abstract function fieldInfo( $table, $field );
1108 * mysql_field_type() wrapper
1110 function fieldType( $res, $index ) {
1111 if ( $res instanceof ResultWrapper
) {
1112 $res = $res->result
;
1114 return mysql_field_type( $res, $index );
1118 * Determines if a given index is unique
1120 function indexUnique( $table, $index ) {
1121 $indexInfo = $this->indexInfo( $table, $index );
1122 if ( !$indexInfo ) {
1125 return !$indexInfo[0]->Non_unique
;
1129 * INSERT wrapper, inserts an array into a table
1131 * $a may be a single associative array, or an array of these with numeric keys, for
1134 * Usually aborts on failure
1135 * If errors are explicitly ignored, returns success
1137 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1138 # No rows to insert, easy just return now
1139 if ( !count( $a ) ) {
1143 $table = $this->tableName( $table );
1144 if ( !is_array( $options ) ) {
1145 $options = array( $options );
1147 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1149 $keys = array_keys( $a[0] );
1152 $keys = array_keys( $a );
1155 $sql = 'INSERT ' . implode( ' ', $options ) .
1156 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1160 foreach ( $a as $row ) {
1166 $sql .= '(' . $this->makeList( $row ) . ')';
1169 $sql .= '(' . $this->makeList( $a ) . ')';
1171 return (bool)$this->query( $sql, $fname );
1175 * Make UPDATE options for the Database::update function
1178 * @param $options Array: The options passed to Database::update
1181 function makeUpdateOptions( $options ) {
1182 if( !is_array( $options ) ) {
1183 $options = array( $options );
1186 if ( in_array( 'LOW_PRIORITY', $options ) )
1187 $opts[] = $this->lowPriorityOption();
1188 if ( in_array( 'IGNORE', $options ) )
1190 return implode(' ', $opts);
1194 * UPDATE wrapper, takes a condition array and a SET array
1196 * @param $table String: The table to UPDATE
1197 * @param $values Array: An array of values to SET
1198 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1199 * @param $fname String: The Class::Function calling this function
1201 * @param $options Array: An array of UPDATE options, can be one or
1202 * more of IGNORE, LOW_PRIORITY
1205 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1206 $table = $this->tableName( $table );
1207 $opts = $this->makeUpdateOptions( $options );
1208 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1209 if ( $conds != '*' ) {
1210 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1212 return $this->query( $sql, $fname );
1216 * Makes an encoded list of strings from an array
1218 * LIST_COMMA - comma separated, no field names
1219 * LIST_AND - ANDed WHERE clause (without the WHERE)
1220 * LIST_OR - ORed WHERE clause (without the WHERE)
1221 * LIST_SET - comma separated with field names, like a SET clause
1222 * LIST_NAMES - comma separated field names
1224 function makeList( $a, $mode = LIST_COMMA
) {
1225 if ( !is_array( $a ) ) {
1226 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1231 foreach ( $a as $field => $value ) {
1233 if ( $mode == LIST_AND
) {
1235 } elseif($mode == LIST_OR
) {
1243 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1244 $list .= "($value)";
1245 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1247 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1248 if( count( $value ) == 0 ) {
1249 throw new MWException( __METHOD__
.': empty input' );
1250 } elseif( count( $value ) == 1 ) {
1251 // Special-case single values, as IN isn't terribly efficient
1252 // Don't necessarily assume the single key is 0; we don't
1253 // enforce linear numeric ordering on other arrays here.
1254 $value = array_values( $value );
1255 $list .= $field." = ".$this->addQuotes( $value[0] );
1257 $list .= $field." IN (".$this->makeList($value).") ";
1259 } elseif( $value === null ) {
1260 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1261 $list .= "$field IS ";
1262 } elseif ( $mode == LIST_SET
) {
1263 $list .= "$field = ";
1267 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1268 $list .= "$field = ";
1270 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1277 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1278 * The keys on each level may be either integers or strings.
1280 * @param array $data organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1281 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
1282 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
1283 * @return mixed string SQL fragment, or false if no items in array.
1285 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1287 foreach ( $data as $base => $sub ) {
1288 if ( count( $sub ) ) {
1289 $conds[] = $this->makeList(
1290 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1296 return $this->makeList( $conds, LIST_OR
);
1298 // Nothing to search for...
1304 * Bitwise operations
1307 function bitNot($field) {
1308 return "(~$bitField)";
1311 function bitAnd($fieldLeft, $fieldRight) {
1312 return "($fieldLeft & $fieldRight)";
1315 function bitOr($fieldLeft, $fieldRight) {
1316 return "($fieldLeft | $fieldRight)";
1320 * Change the current database
1322 * @return bool Success or failure
1324 function selectDB( $db ) {
1325 # Stub. Shouldn't cause serious problems if it's not overridden, but
1326 # if your database engine supports a concept similar to MySQL's
1327 # databases you may as well. TODO: explain what exactly will fail if
1328 # this is not overridden.
1333 * Get the current DB name
1335 function getDBname() {
1336 return $this->mDBname
;
1340 * Get the server hostname or IP address
1342 function getServer() {
1343 return $this->mServer
;
1347 * Format a table name ready for use in constructing an SQL query
1349 * This does two important things: it quotes the table names to clean them up,
1350 * and it adds a table prefix if only given a table name with no quotes.
1352 * All functions of this object which require a table name call this function
1353 * themselves. Pass the canonical name to such functions. This is only needed
1354 * when calling query() directly.
1356 * @param $name String: database table name
1357 * @return String: full database name
1359 function tableName( $name ) {
1360 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1361 # Skip the entire process when we have a string quoted on both ends.
1362 # Note that we check the end so that we will still quote any use of
1363 # use of `database`.table. But won't break things if someone wants
1364 # to query a database table with a dot in the name.
1365 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1367 # Lets test for any bits of text that should never show up in a table
1368 # name. Basically anything like JOIN or ON which are actually part of
1369 # SQL queries, but may end up inside of the table value to combine
1370 # sql. Such as how the API is doing.
1371 # Note that we use a whitespace test rather than a \b test to avoid
1372 # any remote case where a word like on may be inside of a table name
1373 # surrounded by symbols which may be considered word breaks.
1374 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1376 # Split database and table into proper variables.
1377 # We reverse the explode so that database.table and table both output
1378 # the correct table.
1379 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1380 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1381 else @list
( $table ) = $dbDetails;
1382 $prefix = $this->mTablePrefix
; # Default prefix
1384 # A database name has been specified in input. Quote the table name
1385 # because we don't want any prefixes added.
1386 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1388 # Note that we use the long format because php will complain in in_array if
1389 # the input is not an array, and will complain in is_array if it is not set.
1390 if( !isset( $database ) # Don't use shared database if pre selected.
1391 && isset( $wgSharedDB ) # We have a shared database
1392 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1393 && isset( $wgSharedTables )
1394 && is_array( $wgSharedTables )
1395 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1396 $database = $wgSharedDB;
1397 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1400 # Quote the $database and $table and apply the prefix if not quoted.
1401 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1402 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1404 # Merge our database and table into our final table name.
1405 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1407 # We're finished, return.
1412 * Fetch a number of table names into an array
1413 * This is handy when you need to construct SQL for joins
1416 * extract($dbr->tableNames('user','watchlist'));
1417 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1418 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1420 public function tableNames() {
1421 $inArray = func_get_args();
1423 foreach ( $inArray as $name ) {
1424 $retVal[$name] = $this->tableName( $name );
1430 * Fetch a number of table names into an zero-indexed numerical array
1431 * This is handy when you need to construct SQL for joins
1434 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1435 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1436 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1438 public function tableNamesN() {
1439 $inArray = func_get_args();
1441 foreach ( $inArray as $name ) {
1442 $retVal[] = $this->tableName( $name );
1450 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1453 $use_index_safe = is_array($use_index) ?
$use_index : array();
1454 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1455 foreach ( $tables as $table ) {
1456 // Is there a JOIN and INDEX clause for this table?
1457 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1458 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1459 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1460 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1461 $retJOIN[] = $tableClause;
1462 // Is there an INDEX clause?
1463 } else if ( isset($use_index_safe[$table]) ) {
1464 $tableClause = $this->tableName( $table );
1465 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1466 $ret[] = $tableClause;
1467 // Is there a JOIN clause?
1468 } else if ( isset($join_conds_safe[$table]) ) {
1469 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1470 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1471 $retJOIN[] = $tableClause;
1473 $tableClause = $this->tableName( $table );
1474 $ret[] = $tableClause;
1477 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1478 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1479 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1480 // Compile our final table clause
1481 return implode(' ',array($straightJoins,$otherJoins) );
1485 * Get the name of an index in a given table
1487 function indexName( $index ) {
1488 // Backwards-compatibility hack
1490 'ar_usertext_timestamp' => 'usertext_timestamp',
1491 'un_user_id' => 'user_id',
1492 'un_user_ip' => 'user_ip',
1494 if( isset( $renamed[$index] ) ) {
1495 return $renamed[$index];
1502 * Wrapper for addslashes()
1503 * @param $s String: to be slashed.
1504 * @return String: slashed string.
1506 abstract function strencode( $s );
1509 * If it's a string, adds quotes and backslashes
1510 * Otherwise returns as-is
1512 function addQuotes( $s ) {
1513 if ( $s === null ) {
1516 # This will also quote numeric values. This should be harmless,
1517 # and protects against weird problems that occur when they really
1518 # _are_ strings such as article titles and string->number->string
1519 # conversion is not 1:1.
1520 return "'" . $this->strencode( $s ) . "'";
1525 * Escape string for safe LIKE usage.
1526 * WARNING: you should almost never use this function directly,
1527 * instead use buildLike() that escapes everything automatically
1529 function escapeLike( $s ) {
1530 $s = str_replace( '\\', '\\\\', $s );
1531 $s = $this->strencode( $s );
1532 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1537 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1538 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1539 * Alternatively, the function could be provided with an array of aforementioned parameters.
1541 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1542 * for subpages of 'My page title'.
1543 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1545 * @ return String: fully built LIKE statement
1547 function buildLike() {
1548 $params = func_get_args();
1549 if (count($params) > 0 && is_array($params[0])) {
1550 $params = $params[0];
1554 foreach( $params as $value) {
1555 if( $value instanceof LikeMatch
) {
1556 $s .= $value->toString();
1558 $s .= $this->escapeLike( $value );
1561 return " LIKE '" . $s . "' ";
1565 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1567 function anyChar() {
1568 return new LikeMatch( '_' );
1572 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1574 function anyString() {
1575 return new LikeMatch( '%' );
1579 * Returns an appropriately quoted sequence value for inserting a new row.
1580 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1581 * subclass will return an integer, and save the value for insertId()
1583 function nextSequenceValue( $seqName ) {
1588 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1589 * is only needed because a) MySQL must be as efficient as possible due to
1590 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1591 * which index to pick. Anyway, other databases might have different
1592 * indexes on a given table. So don't bother overriding this unless you're
1595 function useIndexClause( $index ) {
1600 * REPLACE query wrapper
1601 * PostgreSQL simulates this with a DELETE followed by INSERT
1602 * $row is the row to insert, an associative array
1603 * $uniqueIndexes is an array of indexes. Each element may be either a
1604 * field name or an array of field names
1606 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1607 * However if you do this, you run the risk of encountering errors which wouldn't have
1610 * @todo migrate comment to phodocumentor format
1612 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1613 $table = $this->tableName( $table );
1616 if ( !is_array( reset( $rows ) ) ) {
1617 $rows = array( $rows );
1620 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1622 foreach ( $rows as $row ) {
1628 $sql .= '(' . $this->makeList( $row ) . ')';
1630 return $this->query( $sql, $fname );
1634 * DELETE where the condition is a join
1635 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1637 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1638 * join condition matches, set $conds='*'
1640 * DO NOT put the join condition in $conds
1642 * @param $delTable String: The table to delete from.
1643 * @param $joinTable String: The other table.
1644 * @param $delVar String: The variable to join on, in the first table.
1645 * @param $joinVar String: The variable to join on, in the second table.
1646 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1647 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1649 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1651 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1654 $delTable = $this->tableName( $delTable );
1655 $joinTable = $this->tableName( $joinTable );
1656 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1657 if ( $conds != '*' ) {
1658 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1661 return $this->query( $sql, $fname );
1665 * Returns the size of a text field, or -1 for "unlimited"
1667 function textFieldSize( $table, $field ) {
1668 $table = $this->tableName( $table );
1669 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1670 $res = $this->query( $sql, 'Database::textFieldSize' );
1671 $row = $this->fetchObject( $res );
1672 $this->freeResult( $res );
1675 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1684 * A string to insert into queries to show that they're low-priority, like
1685 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1686 * string and nothing bad should happen.
1688 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1690 function lowPriorityOption() {
1695 * DELETE query wrapper
1697 * Use $conds == "*" to delete all rows
1699 function delete( $table, $conds, $fname = 'Database::delete' ) {
1701 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1703 $table = $this->tableName( $table );
1704 $sql = "DELETE FROM $table";
1705 if ( $conds != '*' ) {
1706 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1708 return $this->query( $sql, $fname );
1712 * INSERT SELECT wrapper
1713 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1714 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1715 * $conds may be "*" to copy the whole table
1716 * srcTable may be an array of tables.
1718 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1719 $insertOptions = array(), $selectOptions = array() )
1721 $destTable = $this->tableName( $destTable );
1722 if ( is_array( $insertOptions ) ) {
1723 $insertOptions = implode( ' ', $insertOptions );
1725 if( !is_array( $selectOptions ) ) {
1726 $selectOptions = array( $selectOptions );
1728 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1729 if( is_array( $srcTable ) ) {
1730 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1732 $srcTable = $this->tableName( $srcTable );
1734 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1735 " SELECT $startOpts " . implode( ',', $varMap ) .
1736 " FROM $srcTable $useIndex ";
1737 if ( $conds != '*' ) {
1738 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1740 $sql .= " $tailOpts";
1741 return $this->query( $sql, $fname );
1745 * Construct a LIMIT query with optional offset. This is used for query
1746 * pages. The SQL should be adjusted so that only the first $limit rows
1747 * are returned. If $offset is provided as well, then the first $offset
1748 * rows should be discarded, and the next $limit rows should be returned.
1749 * If the result of the query is not ordered, then the rows to be returned
1750 * are theoretically arbitrary.
1752 * $sql is expected to be a SELECT, if that makes a difference. For
1753 * UPDATE, limitResultForUpdate should be used.
1755 * The version provided by default works in MySQL and SQLite. It will very
1756 * likely need to be overridden for most other DBMSes.
1758 * @param $sql String: SQL query we will append the limit too
1759 * @param $limit Integer: the SQL limit
1760 * @param $offset Integer the SQL offset (default false)
1762 function limitResult( $sql, $limit, $offset=false ) {
1763 if( !is_numeric( $limit ) ) {
1764 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1766 return "$sql LIMIT "
1767 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1770 function limitResultForUpdate( $sql, $num ) {
1771 return $this->limitResult( $sql, $num, 0 );
1775 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1776 * within the UNION construct.
1779 function unionSupportsOrderAndLimit() {
1780 return true; // True for almost every DB supported
1784 * Construct a UNION query
1785 * This is used for providing overload point for other DB abstractions
1786 * not compatible with the MySQL syntax.
1787 * @param $sqls Array: SQL statements to combine
1788 * @param $all Boolean: use UNION ALL
1789 * @return String: SQL fragment
1791 function unionQueries($sqls, $all) {
1792 $glue = $all ?
') UNION ALL (' : ') UNION (';
1793 return '('.implode( $glue, $sqls ) . ')';
1797 * Returns an SQL expression for a simple conditional. This doesn't need
1798 * to be overridden unless CASE isn't supported in your DBMS.
1800 * @param $cond String: SQL expression which will result in a boolean value
1801 * @param $trueVal String: SQL expression to return if true
1802 * @param $falseVal String: SQL expression to return if false
1803 * @return String: SQL fragment
1805 function conditional( $cond, $trueVal, $falseVal ) {
1806 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1810 * Returns a comand for str_replace function in SQL query.
1811 * Uses REPLACE() in MySQL
1813 * @param $orig String: column to modify
1814 * @param $old String: column to seek
1815 * @param $new String: column to replace with
1817 function strreplace( $orig, $old, $new ) {
1818 return "REPLACE({$orig}, {$old}, {$new})";
1822 * Determines if the last failure was due to a deadlock
1825 function wasDeadlock() {
1830 * Determines if the last query error was something that should be dealt
1831 * with by pinging the connection and reissuing the query.
1834 function wasErrorReissuable() {
1839 * Determines if the last failure was due to the database being read-only.
1842 function wasReadOnlyError() {
1847 * Perform a deadlock-prone transaction.
1849 * This function invokes a callback function to perform a set of write
1850 * queries. If a deadlock occurs during the processing, the transaction
1851 * will be rolled back and the callback function will be called again.
1854 * $dbw->deadlockLoop( callback, ... );
1856 * Extra arguments are passed through to the specified callback function.
1858 * Returns whatever the callback function returned on its successful,
1859 * iteration, or false on error, for example if the retry limit was
1862 function deadlockLoop() {
1863 $myFname = 'Database::deadlockLoop';
1866 $args = func_get_args();
1867 $function = array_shift( $args );
1868 $oldIgnore = $this->ignoreErrors( true );
1869 $tries = DEADLOCK_TRIES
;
1870 if ( is_array( $function ) ) {
1871 $fname = $function[0];
1876 $retVal = call_user_func_array( $function, $args );
1877 $error = $this->lastError();
1878 $errno = $this->lastErrno();
1879 $sql = $this->lastQuery();
1882 if ( $this->wasDeadlock() ) {
1884 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1886 $this->reportQueryError( $error, $errno, $sql, $fname );
1889 } while( $this->wasDeadlock() && --$tries > 0 );
1890 $this->ignoreErrors( $oldIgnore );
1891 if ( $tries <= 0 ) {
1892 $this->query( 'ROLLBACK', $myFname );
1893 $this->reportQueryError( $error, $errno, $sql, $fname );
1896 $this->query( 'COMMIT', $myFname );
1902 * Do a SELECT MASTER_POS_WAIT()
1904 * @param $pos MySQLMasterPos object
1905 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1907 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1908 $fname = 'Database::masterPosWait';
1909 wfProfileIn( $fname );
1911 # Commit any open transactions
1912 if ( $this->mTrxLevel
) {
1916 if ( !is_null( $this->mFakeSlaveLag
) ) {
1917 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1918 if ( $wait > $timeout * 1e6
) {
1919 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1920 wfProfileOut( $fname );
1922 } elseif ( $wait > 0 ) {
1923 wfDebug( "Fake slave waiting $wait us\n" );
1925 wfProfileOut( $fname );
1928 wfDebug( "Fake slave up to date ($wait us)\n" );
1929 wfProfileOut( $fname );
1934 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1935 $encFile = $this->addQuotes( $pos->file
);
1936 $encPos = intval( $pos->pos
);
1937 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1938 $res = $this->doQuery( $sql );
1939 if ( $res && $row = $this->fetchRow( $res ) ) {
1940 $this->freeResult( $res );
1941 wfProfileOut( $fname );
1944 wfProfileOut( $fname );
1950 * Get the position of the master from SHOW SLAVE STATUS
1952 function getSlavePos() {
1953 if ( !is_null( $this->mFakeSlaveLag
) ) {
1954 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1955 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1958 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1959 $row = $this->fetchObject( $res );
1961 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1962 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1969 * Get the position of the master from SHOW MASTER STATUS
1971 function getMasterPos() {
1972 if ( $this->mFakeMaster
) {
1973 return new MySQLMasterPos( 'fake', microtime( true ) );
1975 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1976 $row = $this->fetchObject( $res );
1978 return new MySQLMasterPos( $row->File
, $row->Position
);
1985 * Begin a transaction, committing any previously open transaction
1987 function begin( $fname = 'Database::begin' ) {
1988 $this->query( 'BEGIN', $fname );
1989 $this->mTrxLevel
= 1;
1995 function commit( $fname = 'Database::commit' ) {
1996 $this->query( 'COMMIT', $fname );
1997 $this->mTrxLevel
= 0;
2001 * Rollback a transaction.
2002 * No-op on non-transactional databases.
2004 function rollback( $fname = 'Database::rollback' ) {
2005 $this->query( 'ROLLBACK', $fname, true );
2006 $this->mTrxLevel
= 0;
2010 * Begin a transaction, committing any previously open transaction
2011 * @deprecated use begin()
2013 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2018 * Commit transaction, if one is open
2019 * @deprecated use commit()
2021 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2026 * Creates a new table with structure copied from existing table
2027 * Note that unlike most database abstraction functions, this function does not
2028 * automatically append database prefix, because it works at a lower
2029 * abstraction level.
2031 * @param $oldName String: name of table whose structure should be copied
2032 * @param $newName String: name of table to be created
2033 * @param $temporary Boolean: whether the new table should be temporary
2034 * @return Boolean: true if operation was successful
2036 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2037 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2041 * Return MW-style timestamp used for MySQL schema
2043 function timestamp( $ts=0 ) {
2044 return wfTimestamp(TS_MW
,$ts);
2048 * Local database timestamp format or null
2050 function timestampOrNull( $ts = null ) {
2051 if( is_null( $ts ) ) {
2054 return $this->timestamp( $ts );
2061 function resultObject( $result ) {
2062 if( empty( $result ) ) {
2064 } elseif ( $result instanceof ResultWrapper
) {
2066 } elseif ( $result === true ) {
2067 // Successful write query
2070 return new ResultWrapper( $this, $result );
2075 * Return aggregated value alias
2077 function aggregateValue ($valuedata,$valuename='value') {
2082 * Returns a wikitext link to the DB's website, e.g.,
2083 * return "[http://www.mysql.com/ MySQL]";
2084 * Should at least contain plain text, if for some reason
2085 * your database has no website.
2087 * @return String: wikitext of a link to the server software's web site
2089 abstract function getSoftwareLink();
2092 * A string describing the current software version, like from
2093 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2095 * @return String: Version information from the database
2097 abstract function getServerVersion();
2100 * Ping the server and try to reconnect if it there is no connection
2102 * @return bool Success or failure
2105 # Stub. Not essential to override.
2111 * At the moment, this will only work if the DB user has the PROCESS privilege
2114 if ( !is_null( $this->mFakeSlaveLag
) ) {
2115 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2116 return $this->mFakeSlaveLag
;
2118 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
2119 # Find slave SQL thread
2120 while ( $row = $this->fetchObject( $res ) ) {
2121 /* This should work for most situations - when default db
2122 * for thread is not specified, it had no events executed,
2123 * and therefore it doesn't know yet how lagged it is.
2125 * Relay log I/O thread does not select databases.
2127 if ( $row->User
== 'system user' &&
2128 $row->State
!= 'Waiting for master to send event' &&
2129 $row->State
!= 'Connecting to master' &&
2130 $row->State
!= 'Queueing master event to the relay log' &&
2131 $row->State
!= 'Waiting for master update' &&
2132 $row->State
!= 'Requesting binlog dump' &&
2133 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
2134 $row->State
!= 'Reconnecting after a failed master event read' &&
2135 $row->State
!= 'Registering slave on master'
2137 # This is it, return the time (except -ve)
2138 if ( $row->Time
> 0x7fffffff ) {
2149 * Get status information from SHOW STATUS in an associative array
2151 function getStatus($which="%") {
2152 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2154 while ( $row = $this->fetchObject( $res ) ) {
2155 $status[$row->Variable_name
] = $row->Value
;
2161 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2163 function maxListLen() {
2167 function encodeBlob($b) {
2171 function decodeBlob($b) {
2176 * Override database's default connection timeout. May be useful for very
2177 * long batch queries such as full-wiki dumps, where a single query reads
2178 * out over hours or days. May or may not be necessary for non-MySQL
2179 * databases. For most purposes, leaving it as a no-op should be fine.
2181 * @param $timeout Integer in seconds
2183 public function setTimeout( $timeout ) {}
2186 * Read and execute SQL commands from a file.
2187 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2188 * @param $filename String: File name to open
2189 * @param $lineCallback Callback: Optional function called before reading each line
2190 * @param $resultCallback Callback: Optional function called for each MySQL result
2192 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2193 $fp = fopen( $filename, 'r' );
2194 if ( false === $fp ) {
2195 throw new MWException( "Could not open \"{$filename}\".\n" );
2197 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2203 * Get the full path of a patch file. Originally based on archive()
2204 * from updaters.inc. Keep in mind this always returns a patch, as
2205 * it fails back to MySQL if no DB-specific patch can be found
2207 * @param $patch String The name of the patch, like patch-something.sql
2208 * @return String Full path to patch file
2210 public static function patchPath( $patch ) {
2211 global $wgDBtype, $IP;
2212 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2213 return "$IP/maintenance/$wgDBtype/archives/$patch";
2215 return "$IP/maintenance/archives/$patch";
2220 * Read and execute commands from an open file handle
2221 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2222 * @param $fp String: File handle
2223 * @param $lineCallback Callback: Optional function called before reading each line
2224 * @param $resultCallback Callback: Optional function called for each MySQL result
2226 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2229 $dollarquote = false;
2231 while ( ! feof( $fp ) ) {
2232 if ( $lineCallback ) {
2233 call_user_func( $lineCallback );
2235 $line = trim( fgets( $fp, 1024 ) );
2236 $sl = strlen( $line ) - 1;
2238 if ( $sl < 0 ) { continue; }
2239 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2241 ## Allow dollar quoting for function declarations
2242 if (substr($line,0,4) == '$mw$') {
2244 $dollarquote = false;
2248 $dollarquote = true;
2251 else if (!$dollarquote) {
2252 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2254 $line = substr( $line, 0, $sl );
2258 if ( $cmd != '' ) { $cmd .= ' '; }
2262 $cmd = str_replace(';;', ";", $cmd);
2263 $cmd = $this->replaceVars( $cmd );
2264 $res = $this->query( $cmd, __METHOD__
);
2265 if ( $resultCallback ) {
2266 call_user_func( $resultCallback, $res, $this );
2269 if ( false === $res ) {
2270 $err = $this->lastError();
2271 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2283 * Replace variables in sourced SQL
2285 protected function replaceVars( $ins ) {
2287 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2288 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2289 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2292 // Ordinary variables
2293 foreach ( $varnames as $var ) {
2294 if( isset( $GLOBALS[$var] ) ) {
2295 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2296 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2297 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2298 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2303 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2304 array( $this, 'tableNameCallback' ), $ins );
2307 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2308 array( $this, 'indexNameCallback' ), $ins );
2313 * Table name callback
2316 protected function tableNameCallback( $matches ) {
2317 return $this->tableName( $matches[1] );
2321 * Index name callback
2323 protected function indexNameCallback( $matches ) {
2324 return $this->indexName( $matches[1] );
2328 * Build a concatenation list to feed into a SQL query
2329 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2332 function buildConcat( $stringList ) {
2333 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2337 * Acquire a named lock
2339 * Abstracted from Filestore::lock() so child classes can implement for
2342 * @param $lockName String: Name of lock to aquire
2343 * @param $method String: Name of method calling us
2346 public function lock( $lockName, $method, $timeout = 5 ) {
2353 * @param $lockName String: Name of lock to release
2354 * @param $method String: Name of method calling us
2356 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2357 * @return Returns 1 if the lock was released, 0 if the lock was not established
2358 * by this thread (in which case the lock is not released), and NULL if the named
2359 * lock did not exist
2361 public function unlock( $lockName, $method ) {
2366 * Lock specific tables
2368 * @param $read Array of tables to lock for read access
2369 * @param $write Array of tables to lock for write access
2370 * @param $method String name of caller
2371 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2373 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2378 * Unlock specific tables
2380 * @param $method String the caller
2382 public function unlockTables( $method ) {
2387 * Get search engine class. All subclasses of this
2388 * need to implement this if they wish to use searching.
2392 public function getSearchEngine() {
2393 return "SearchMySQL";
2397 * Allow or deny "big selects" for this session only. This is done by setting
2398 * the sql_big_selects session variable.
2400 * This is a MySQL-specific feature.
2402 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2404 public function setBigSelects( $value = true ) {
2410 /******************************************************************************
2412 *****************************************************************************/
2421 function DBObject($data) {
2422 $this->mData
= $data;
2430 return $this->mData
;
2438 * This allows us to distinguish a blob from a normal string and an array of strings
2442 function __construct($data) {
2443 $this->mData
= $data;
2446 return $this->mData
;
2455 private $name, $tablename, $default, $max_length, $nullable,
2456 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2457 function __construct ($info) {
2458 $this->name
= $info->name
;
2459 $this->tablename
= $info->table
;
2460 $this->default = $info->def
;
2461 $this->max_length
= $info->max_length
;
2462 $this->nullable
= !$info->not_null
;
2463 $this->is_pk
= $info->primary_key
;
2464 $this->is_unique
= $info->unique_key
;
2465 $this->is_multiple
= $info->multiple_key
;
2466 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2467 $this->type
= $info->type
;
2474 function tableName() {
2475 return $this->tableName
;
2478 function defaultValue() {
2479 return $this->default;
2482 function maxLength() {
2483 return $this->max_length
;
2486 function nullable() {
2487 return $this->nullable
;
2491 return $this->is_key
;
2494 function isMultipleKey() {
2495 return $this->is_multiple
;
2503 /******************************************************************************
2505 *****************************************************************************/
2508 * Database error base class
2511 class DBError
extends MWException
{
2515 * Construct a database error
2516 * @param $db Database object which threw the error
2517 * @param $error A simple error message to be used for debugging
2519 function __construct( DatabaseBase
&$db, $error ) {
2521 parent
::__construct( $error );
2524 function getText() {
2525 global $wgShowDBErrorBacktrace;
2526 $s = $this->getMessage() . "\n";
2527 if ( $wgShowDBErrorBacktrace ) {
2528 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2537 class DBConnectionError
extends DBError
{
2540 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2541 $msg = 'DB connection error';
2542 if ( trim( $error ) != '' ) {
2545 $this->error
= $error;
2546 parent
::__construct( $db, $msg );
2549 function useOutputPage() {
2550 // Not likely to work
2554 function useMessageCache() {
2555 // Not likely to work
2559 function getLogMessage() {
2560 # Don't send to the exception log
2564 function getPageTitle() {
2565 global $wgSitename, $wgLang;
2566 $header = "$wgSitename has a problem";
2567 if ( $wgLang instanceof Language
) {
2568 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2574 function getHTML() {
2575 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2577 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2578 $again = 'Try waiting a few minutes and reloading.';
2579 $info = '(Can\'t contact the database server: $1)';
2581 if ( $wgLang instanceof Language
) {
2582 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2583 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2584 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2587 # No database access
2588 if ( is_object( $wgMessageCache ) ) {
2589 $wgMessageCache->disable();
2592 if ( trim( $this->error
) == '' ) {
2593 $this->error
= $this->db
->getProperty('mServer');
2596 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2597 $text = str_replace( '$1', $this->error
, $noconnect );
2599 if ( $wgShowDBErrorBacktrace ) {
2600 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2603 $extra = $this->searchForm();
2605 if( $wgUseFileCache ) {
2607 $cache = $this->fileCachedPage();
2608 # Cached version on file system?
2609 if( $cache !== null ) {
2610 # Hack: extend the body for error messages
2611 $cache = str_replace( array('</html>','</body>'), '', $cache );
2612 # Add cache notice...
2613 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2614 # Localize it if possible...
2615 if( $wgLang instanceof Language
) {
2616 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2618 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2619 # Output cached page with notices on bottom and re-close body
2620 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2622 } catch( MWException
$e ) {
2623 // Do nothing, just use the default page
2626 # Headers needed here - output is just the error message
2627 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2630 function searchForm() {
2631 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2632 $usegoogle = "You can try searching via Google in the meantime.";
2633 $outofdate = "Note that their indexes of our content may be out of date.";
2634 $googlesearch = "Search";
2636 if ( $wgLang instanceof Language
) {
2637 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2638 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2639 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2642 $search = htmlspecialchars(@$_REQUEST['search']);
2645 <div style="margin: 1.5em">$usegoogle<br />
2646 <small>$outofdate</small></div>
2647 <!-- SiteSearch Google -->
2648 <form method="get" action="http://www.google.com/search" id="googlesearch">
2649 <input type="hidden" name="domains" value="$wgServer" />
2650 <input type="hidden" name="num" value="50" />
2651 <input type="hidden" name="ie" value="$wgInputEncoding" />
2652 <input type="hidden" name="oe" value="$wgInputEncoding" />
2654 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2655 <input type="submit" name="btnG" value="$googlesearch" />
2657 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2658 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2661 <!-- SiteSearch Google -->
2666 function fileCachedPage() {
2667 global $wgTitle, $title, $wgLang, $wgOut;
2668 if( $wgOut->isDisabled() ) return; // Done already?
2669 $mainpage = 'Main Page';
2670 if ( $wgLang instanceof Language
) {
2671 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2676 } elseif( $title ) {
2677 $t = Title
::newFromURL( $title );
2679 $t = Title
::newFromText( $mainpage );
2682 $cache = new HTMLFileCache( $t );
2683 if( $cache->isFileCached() ) {
2684 return $cache->fetchPageText();
2690 function htmlBodyOnly() {
2699 class DBQueryError
extends DBError
{
2700 public $error, $errno, $sql, $fname;
2702 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2703 $message = "A database error has occurred\n" .
2705 "Function: $fname\n" .
2706 "Error: $errno $error\n";
2708 parent
::__construct( $db, $message );
2709 $this->error
= $error;
2710 $this->errno
= $errno;
2712 $this->fname
= $fname;
2715 function getText() {
2716 global $wgShowDBErrorBacktrace;
2717 if ( $this->useMessageCache() ) {
2718 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2719 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2720 if ( $wgShowDBErrorBacktrace ) {
2721 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2725 return parent
::getText();
2730 global $wgShowSQLErrors;
2731 if( !$wgShowSQLErrors ) {
2732 return $this->msg( 'sqlhidden', 'SQL hidden' );
2738 function getLogMessage() {
2739 # Don't send to the exception log
2743 function getPageTitle() {
2744 return $this->msg( 'databaseerror', 'Database error' );
2747 function getHTML() {
2748 global $wgShowDBErrorBacktrace;
2749 if ( $this->useMessageCache() ) {
2750 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2751 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2753 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2755 if ( $wgShowDBErrorBacktrace ) {
2756 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2765 class DBUnexpectedError
extends DBError
{}
2769 * Result wrapper for grabbing data queried by someone else
2772 class ResultWrapper
implements Iterator
{
2773 var $db, $result, $pos = 0, $currentRow = null;
2776 * Create a new result object from a result resource and a Database object
2778 function ResultWrapper( $database, $result ) {
2779 $this->db
= $database;
2780 if ( $result instanceof ResultWrapper
) {
2781 $this->result
= $result->result
;
2783 $this->result
= $result;
2788 * Get the number of rows in a result object
2790 function numRows() {
2791 return $this->db
->numRows( $this );
2795 * Fetch the next row from the given result object, in object form.
2796 * Fields can be retrieved with $row->fieldname, with fields acting like
2799 * @param $res SQL result object as returned from Database::query(), etc.
2800 * @return MySQL row object
2801 * @throws DBUnexpectedError Thrown if the database returns an error
2803 function fetchObject() {
2804 return $this->db
->fetchObject( $this );
2808 * Fetch the next row from the given result object, in associative array
2809 * form. Fields are retrieved with $row['fieldname'].
2811 * @param $res SQL result object as returned from Database::query(), etc.
2812 * @return MySQL row object
2813 * @throws DBUnexpectedError Thrown if the database returns an error
2815 function fetchRow() {
2816 return $this->db
->fetchRow( $this );
2820 * Free a result object
2823 $this->db
->freeResult( $this );
2824 unset( $this->result
);
2829 * Change the position of the cursor in a result object
2830 * See mysql_data_seek()
2832 function seek( $row ) {
2833 $this->db
->dataSeek( $this, $row );
2836 /*********************
2837 * Iterator functions
2838 * Note that using these in combination with the non-iterator functions
2839 * above may cause rows to be skipped or repeated.
2843 if ($this->numRows()) {
2844 $this->db
->dataSeek($this, 0);
2847 $this->currentRow
= null;
2850 function current() {
2851 if ( is_null( $this->currentRow
) ) {
2854 return $this->currentRow
;
2863 $this->currentRow
= $this->fetchObject();
2864 return $this->currentRow
;
2868 return $this->current() !== false;
2873 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2874 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2879 public function __construct( $s ) {
2883 public function toString() {