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 wfDeprecated( __METHOD__
);
357 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
361 * Usually aborts on failure
362 * If the failFunction is set to a non-zero integer, returns success
363 * @param $server String: database server host
364 * @param $user String: database user name
365 * @param $password String: database user password
366 * @param $dbName String: database name
368 abstract function open( $server, $user, $password, $dbName );
370 protected function installErrorHandler() {
371 $this->mPHPError
= false;
372 $this->htmlErrors
= ini_set( 'html_errors', '0' );
373 set_error_handler( array( $this, 'connectionErrorHandler' ) );
376 protected function restoreErrorHandler() {
377 restore_error_handler();
378 if ( $this->htmlErrors
!== false ) {
379 ini_set( 'html_errors', $this->htmlErrors
);
381 if ( $this->mPHPError
) {
382 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
383 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
390 protected function connectionErrorHandler( $errno, $errstr ) {
391 $this->mPHPError
= $errstr;
395 * Closes a database connection.
396 * if it is open : commits any open transactions
398 * @return Bool operation success. true if already closed.
401 # Stub, should probably be overridden
406 * @param $error String: fallback error message, used if none is given by DB
408 function reportConnectionError( $error = 'Unknown error' ) {
409 $myError = $this->lastError();
414 if ( $this->mFailFunction
) {
415 # Legacy error handling method
416 if ( !is_int( $this->mFailFunction
) ) {
417 $ff = $this->mFailFunction
;
418 $ff( $this, $error );
422 throw new DBConnectionError( $this, $error );
427 * Determine whether a query writes to the DB.
428 * Should return true if unsure.
430 function isWriteQuery( $sql ) {
431 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
435 * Usually aborts on failure. If errors are explicitly ignored, returns success.
437 * @param $sql String: SQL query
438 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
439 * comment (you can use __METHOD__ or add some extra info)
440 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
441 * maybe best to catch the exception instead?
442 * @return true for a successful write query, ResultWrapper object for a successful read query,
443 * or false on failure if $tempIgnore set
444 * @throws DBQueryError Thrown when the database returns an error of any kind
446 public function query( $sql, $fname = '', $tempIgnore = false ) {
449 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
450 if ( isset( $wgProfiler ) ) {
451 # generalizeSQL will probably cut down the query to reasonable
452 # logging size most of the time. The substr is really just a sanity check.
454 # Who's been wasting my precious column space? -- TS
455 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
458 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
459 $totalProf = 'Database::query-master';
461 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
462 $totalProf = 'Database::query';
464 wfProfileIn( $totalProf );
465 wfProfileIn( $queryProf );
468 $this->mLastQuery
= $sql;
469 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
470 // Set a flag indicating that writes have been done
471 wfDebug( __METHOD__
.": Writes done: $sql\n" );
472 $this->mDoneWrites
= true;
475 # Add a comment for easy SHOW PROCESSLIST interpretation
478 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
479 $userName = $wgUser->getName();
480 if ( mb_strlen( $userName ) > 15 ) {
481 $userName = mb_substr( $userName, 0, 15 ) . '...';
483 $userName = str_replace( '/', '', $userName );
487 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
489 # $commentedSql = $sql;
492 # If DBO_TRX is set, start a transaction
493 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
494 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
495 // avoid establishing transactions for SHOW and SET statements too -
496 // that would delay transaction initializations to once connection
497 // is really used by application
498 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
499 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
503 if ( $this->debug() ) {
504 $sqlx = substr( $commentedSql, 0, 500 );
505 $sqlx = strtr( $sqlx, "\t\n", ' ' );
507 wfDebug( "SQL-master: $sqlx\n" );
509 wfDebug( "SQL: $sqlx\n" );
513 if ( istainted( $sql ) & TC_MYSQL
) {
514 throw new MWException( 'Tainted query found' );
517 # Do the query and handle errors
518 $ret = $this->doQuery( $commentedSql );
520 # Try reconnecting if the connection was lost
521 if ( false === $ret && $this->wasErrorReissuable() ) {
522 # Transaction is gone, like it or not
523 $this->mTrxLevel
= 0;
524 wfDebug( "Connection lost, reconnecting...\n" );
525 if ( $this->ping() ) {
526 wfDebug( "Reconnected\n" );
527 $sqlx = substr( $commentedSql, 0, 500 );
528 $sqlx = strtr( $sqlx, "\t\n", ' ' );
529 global $wgRequestTime;
530 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
531 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
532 $ret = $this->doQuery( $commentedSql );
534 wfDebug( "Failed\n" );
538 if ( false === $ret ) {
539 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
542 if ( isset( $wgProfiler ) ) {
543 wfProfileOut( $queryProf );
544 wfProfileOut( $totalProf );
546 return $this->resultObject( $ret );
550 * The DBMS-dependent part of query()
551 * @param $sql String: SQL query.
552 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
555 /*private*/ abstract function doQuery( $sql );
558 * @param $error String
559 * @param $errno Integer
561 * @param $fname String
562 * @param $tempIgnore Boolean
564 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
565 global $wgCommandLineMode;
566 # Ignore errors during error handling to avoid infinite recursion
567 $ignore = $this->ignoreErrors( true );
568 ++
$this->mErrorCount
;
570 if( $ignore ||
$tempIgnore ) {
571 wfDebug("SQL ERROR (ignored): $error\n");
572 $this->ignoreErrors( $ignore );
574 $sql1line = str_replace( "\n", "\\n", $sql );
575 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
576 wfDebug("SQL ERROR: " . $error . "\n");
577 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
583 * Intended to be compatible with the PEAR::DB wrapper functions.
584 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
586 * ? = scalar value, quoted as necessary
587 * ! = raw SQL bit (a function for instance)
588 * & = filename; reads the file and inserts as a blob
589 * (we don't use this though...)
591 function prepare( $sql, $func = 'Database::prepare' ) {
592 /* MySQL doesn't support prepared statements (yet), so just
593 pack up the query for reference. We'll manually replace
595 return array( 'query' => $sql, 'func' => $func );
598 function freePrepared( $prepared ) {
599 /* No-op by default */
603 * Execute a prepared query with the various arguments
604 * @param $prepared String: the prepared sql
605 * @param $args Mixed: Either an array here, or put scalars as varargs
607 function execute( $prepared, $args = null ) {
608 if( !is_array( $args ) ) {
610 $args = func_get_args();
611 array_shift( $args );
613 $sql = $this->fillPrepared( $prepared['query'], $args );
614 return $this->query( $sql, $prepared['func'] );
618 * Prepare & execute an SQL statement, quoting and inserting arguments
619 * in the appropriate places.
620 * @param $query String
623 function safeQuery( $query, $args = null ) {
624 $prepared = $this->prepare( $query, 'Database::safeQuery' );
625 if( !is_array( $args ) ) {
627 $args = func_get_args();
628 array_shift( $args );
630 $retval = $this->execute( $prepared, $args );
631 $this->freePrepared( $prepared );
636 * For faking prepared SQL statements on DBs that don't support
638 * @param $preparedQuery String: a 'preparable' SQL statement
639 * @param $args Array of arguments to fill it with
640 * @return string executable SQL
642 function fillPrepared( $preparedQuery, $args ) {
644 $this->preparedArgs
=& $args;
645 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
646 array( &$this, 'fillPreparedArg' ), $preparedQuery );
650 * preg_callback func for fillPrepared()
651 * The arguments should be in $this->preparedArgs and must not be touched
652 * while we're doing this.
654 * @param $matches Array
658 function fillPreparedArg( $matches ) {
659 switch( $matches[1] ) {
660 case '\\?': return '?';
661 case '\\!': return '!';
662 case '\\&': return '&';
664 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
665 switch( $matches[1] ) {
666 case '?': return $this->addQuotes( $arg );
667 case '!': return $arg;
669 # return $this->addQuotes( file_get_contents( $arg ) );
670 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
672 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
677 * Free a result object
678 * @param $res Mixed: A SQL result
680 function freeResult( $res ) {
681 # Stub. Might not really need to be overridden, since results should
682 # be freed by PHP when the variable goes out of scope anyway.
686 * Fetch the next row from the given result object, in object form.
687 * Fields can be retrieved with $row->fieldname, with fields acting like
690 * @param $res SQL result object as returned from Database::query(), etc.
692 * @throws DBUnexpectedError Thrown if the database returns an error
694 abstract function fetchObject( $res );
697 * Fetch the next row from the given result object, in associative array
698 * form. Fields are retrieved with $row['fieldname'].
700 * @param $res SQL result object as returned from Database::query(), etc.
702 * @throws DBUnexpectedError Thrown if the database returns an error
704 abstract function fetchRow( $res );
707 * Get the number of rows in a result object
708 * @param $res Mixed: A SQL result
710 abstract function numRows( $res );
713 * Get the number of fields in a result object
714 * See documentation for mysql_num_fields()
715 * @param $res Mixed: A SQL result
717 abstract function numFields( $res );
720 * Get a field name in a result object
721 * See documentation for mysql_field_name():
722 * http://www.php.net/mysql_field_name
723 * @param $res Mixed: A SQL result
726 abstract function fieldName( $res, $n );
729 * Get the inserted value of an auto-increment row
731 * The value inserted should be fetched from nextSequenceValue()
734 * $id = $dbw->nextSequenceValue('page_page_id_seq');
735 * $dbw->insert('page',array('page_id' => $id));
736 * $id = $dbw->insertId();
738 abstract function insertId();
741 * Change the position of the cursor in a result object
742 * See mysql_data_seek()
743 * @param $res Mixed: A SQL result
744 * @param $row Mixed: Either MySQL row or ResultWrapper
746 abstract function dataSeek( $res, $row );
749 * Get the last error number
752 abstract function lastErrno();
755 * Get a description of the last error
756 * See mysql_error() for more details
758 abstract function lastError();
761 * Get the number of rows affected by the last write query
762 * See mysql_affected_rows() for more details
764 abstract function affectedRows();
767 * Simple UPDATE wrapper
768 * Usually aborts on failure
769 * If errors are explicitly ignored, returns success
771 * This function exists for historical reasons, Database::update() has a more standard
772 * calling convention and feature set
774 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
775 $table = $this->tableName( $table );
776 $sql = "UPDATE $table SET $var = '" .
777 $this->strencode( $value ) . "' WHERE ($cond)";
778 return (bool)$this->query( $sql, $fname );
782 * Simple SELECT wrapper, returns a single field, input must be encoded
783 * Usually aborts on failure
784 * If errors are explicitly ignored, returns FALSE on failure
786 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
787 if ( !is_array( $options ) ) {
788 $options = array( $options );
790 $options['LIMIT'] = 1;
792 $res = $this->select( $table, $var, $cond, $fname, $options );
793 if ( $res === false ||
!$this->numRows( $res ) ) {
796 $row = $this->fetchRow( $res );
797 if ( $row !== false ) {
798 $this->freeResult( $res );
799 return reset( $row );
806 * Returns an optional USE INDEX clause to go after the table, and a
807 * string to go at the end of the query
811 * @param $options Array: associative array of options to be turned into
812 * an SQL query, valid keys are listed in the function.
815 function makeSelectOptions( $options ) {
816 $preLimitTail = $postLimitTail = '';
819 $noKeyOptions = array();
820 foreach ( $options as $key => $option ) {
821 if ( is_numeric( $key ) ) {
822 $noKeyOptions[$option] = true;
826 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
827 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
828 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
830 //if (isset($options['LIMIT'])) {
831 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
832 // isset($options['OFFSET']) ? $options['OFFSET']
836 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
837 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
838 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
840 # Various MySQL extensions
841 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
842 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
843 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
844 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
845 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
846 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
847 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
848 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
850 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
851 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
856 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
862 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
863 * @param $vars Mixed: Array or string, field name(s) to be retrieved
864 * @param $conds Mixed: Array or string, condition(s) for WHERE
865 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
866 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
867 * see Database::makeSelectOptions code for list of supported stuff
868 * @param $join_conds Array: Associative array of table join conditions (optional)
869 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
870 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
872 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
874 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
875 return $this->query( $sql, $fname );
881 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
882 * @param $vars Mixed: Array or string, field name(s) to be retrieved
883 * @param $conds Mixed: Array or string, condition(s) for WHERE
884 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
885 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
886 * see Database::makeSelectOptions code for list of supported stuff
887 * @param $join_conds Array: Associative array of table join conditions (optional)
888 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
889 * @return string, the SQL text
891 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
892 if( is_array( $vars ) ) {
893 $vars = implode( ',', $vars );
895 if( !is_array( $options ) ) {
896 $options = array( $options );
898 if( is_array( $table ) ) {
899 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
900 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
902 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
903 } elseif ($table!='') {
904 if ($table{0}==' ') {
905 $from = ' FROM ' . $table;
907 $from = ' FROM ' . $this->tableName( $table );
913 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
915 if( !empty( $conds ) ) {
916 if ( is_array( $conds ) ) {
917 $conds = $this->makeList( $conds, LIST_AND
);
919 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
921 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
924 if (isset($options['LIMIT']))
925 $sql = $this->limitResult($sql, $options['LIMIT'],
926 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
927 $sql = "$sql $postLimitTail";
929 if (isset($options['EXPLAIN'])) {
930 $sql = 'EXPLAIN ' . $sql;
936 * Single row SELECT wrapper
937 * Aborts or returns FALSE on error
939 * @param $table String: table name
940 * @param $vars String: the selected variables
941 * @param $conds Array: a condition map, terms are ANDed together.
942 * Items with numeric keys are taken to be literal conditions
943 * Takes an array of selected variables, and a condition map, which is ANDed
944 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
945 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
946 * $obj- >page_id is the ID of the Astronomy article
947 * @param $fname String: Calling function name
948 * @param $options Array
949 * @param $join_conds Array
951 * @todo migrate documentation to phpdocumentor format
953 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
954 $options['LIMIT'] = 1;
955 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
956 if ( $res === false )
958 if ( !$this->numRows($res) ) {
959 $this->freeResult($res);
962 $obj = $this->fetchObject( $res );
963 $this->freeResult( $res );
969 * Estimate rows in dataset
970 * Returns estimated count - not necessarily an accurate estimate across different databases,
972 * Takes same arguments as Database::select()
974 * @param string $table table name
975 * @param array $vars unused
976 * @param array $conds filters on the table
977 * @param string $fname function name for profiling
978 * @param array $options options for select
979 * @return int row count
981 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
983 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
985 $row = $this->fetchRow( $res );
986 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
988 $this->freeResult( $res );
993 * Removes most variables from an SQL query and replaces them with X or N for numbers.
994 * It's only slightly flawed. Don't use for anything important.
996 * @param $sql String: A SQL Query
998 static function generalizeSQL( $sql ) {
999 # This does the same as the regexp below would do, but in such a way
1000 # as to avoid crashing php on some large strings.
1001 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1003 $sql = str_replace ( "\\\\", '', $sql);
1004 $sql = str_replace ( "\\'", '', $sql);
1005 $sql = str_replace ( "\\\"", '', $sql);
1006 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1007 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1009 # All newlines, tabs, etc replaced by single space
1010 $sql = preg_replace ( '/\s+/', ' ', $sql);
1013 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1019 * Determines whether a field exists in a table
1020 * @param $table: table name
1021 * @param $filed: filed to check on that table
1022 * @param $fname: calling function name (optional)
1023 * @return bool: whether $table has filed $field
1025 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1026 $info = $this->fieldInfo( $table, $field );
1031 * Determines whether an index exists
1032 * Usually aborts on failure
1033 * If errors are explicitly ignored, returns NULL on failure
1035 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1036 $info = $this->indexInfo( $table, $index, $fname );
1037 if ( is_null( $info ) ) {
1040 return $info !== false;
1046 * Get information about an index into an object
1047 * Returns false if the index does not exist
1049 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1050 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1051 # SHOW INDEX should work for 3.x and up:
1052 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1053 $table = $this->tableName( $table );
1054 $index = $this->indexName( $index );
1055 $sql = 'SHOW INDEX FROM '.$table;
1056 $res = $this->query( $sql, $fname );
1062 while ( $row = $this->fetchObject( $res ) ) {
1063 if ( $row->Key_name
== $index ) {
1067 $this->freeResult($res);
1069 return empty($result) ?
false : $result;
1073 * Query whether a given table exists
1075 function tableExists( $table ) {
1076 $table = $this->tableName( $table );
1077 $old = $this->ignoreErrors( true );
1078 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1079 $this->ignoreErrors( $old );
1081 $this->freeResult( $res );
1089 * mysql_fetch_field() wrapper
1090 * Returns false if the field doesn't exist
1095 abstract function fieldInfo( $table, $field );
1098 * mysql_field_type() wrapper
1100 function fieldType( $res, $index ) {
1101 if ( $res instanceof ResultWrapper
) {
1102 $res = $res->result
;
1104 return mysql_field_type( $res, $index );
1108 * Determines if a given index is unique
1110 function indexUnique( $table, $index ) {
1111 $indexInfo = $this->indexInfo( $table, $index );
1112 if ( !$indexInfo ) {
1115 return !$indexInfo[0]->Non_unique
;
1119 * INSERT wrapper, inserts an array into a table
1121 * $a may be a single associative array, or an array of these with numeric keys, for
1124 * Usually aborts on failure
1125 * If errors are explicitly ignored, returns success
1127 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1128 # No rows to insert, easy just return now
1129 if ( !count( $a ) ) {
1133 $table = $this->tableName( $table );
1134 if ( !is_array( $options ) ) {
1135 $options = array( $options );
1137 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1139 $keys = array_keys( $a[0] );
1142 $keys = array_keys( $a );
1145 $sql = 'INSERT ' . implode( ' ', $options ) .
1146 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1150 foreach ( $a as $row ) {
1156 $sql .= '(' . $this->makeList( $row ) . ')';
1159 $sql .= '(' . $this->makeList( $a ) . ')';
1161 return (bool)$this->query( $sql, $fname );
1165 * Make UPDATE options for the Database::update function
1168 * @param $options Array: The options passed to Database::update
1171 function makeUpdateOptions( $options ) {
1172 if( !is_array( $options ) ) {
1173 $options = array( $options );
1176 if ( in_array( 'LOW_PRIORITY', $options ) )
1177 $opts[] = $this->lowPriorityOption();
1178 if ( in_array( 'IGNORE', $options ) )
1180 return implode(' ', $opts);
1184 * UPDATE wrapper, takes a condition array and a SET array
1186 * @param $table String: The table to UPDATE
1187 * @param $values Array: An array of values to SET
1188 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1189 * @param $fname String: The Class::Function calling this function
1191 * @param $options Array: An array of UPDATE options, can be one or
1192 * more of IGNORE, LOW_PRIORITY
1195 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1196 $table = $this->tableName( $table );
1197 $opts = $this->makeUpdateOptions( $options );
1198 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1199 if ( $conds != '*' ) {
1200 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1202 return $this->query( $sql, $fname );
1206 * Makes an encoded list of strings from an array
1208 * LIST_COMMA - comma separated, no field names
1209 * LIST_AND - ANDed WHERE clause (without the WHERE)
1210 * LIST_OR - ORed WHERE clause (without the WHERE)
1211 * LIST_SET - comma separated with field names, like a SET clause
1212 * LIST_NAMES - comma separated field names
1214 function makeList( $a, $mode = LIST_COMMA
) {
1215 if ( !is_array( $a ) ) {
1216 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1221 foreach ( $a as $field => $value ) {
1223 if ( $mode == LIST_AND
) {
1225 } elseif($mode == LIST_OR
) {
1233 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1234 $list .= "($value)";
1235 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1237 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1238 if( count( $value ) == 0 ) {
1239 throw new MWException( __METHOD__
.': empty input' );
1240 } elseif( count( $value ) == 1 ) {
1241 // Special-case single values, as IN isn't terribly efficient
1242 // Don't necessarily assume the single key is 0; we don't
1243 // enforce linear numeric ordering on other arrays here.
1244 $value = array_values( $value );
1245 $list .= $field." = ".$this->addQuotes( $value[0] );
1247 $list .= $field." IN (".$this->makeList($value).") ";
1249 } elseif( $value === null ) {
1250 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1251 $list .= "$field IS ";
1252 } elseif ( $mode == LIST_SET
) {
1253 $list .= "$field = ";
1257 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1258 $list .= "$field = ";
1260 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1267 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1268 * The keys on each level may be either integers or strings.
1270 * @param array $data organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1271 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
1272 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
1273 * @return mixed string SQL fragment, or false if no items in array.
1275 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1277 foreach ( $data as $base => $sub ) {
1278 if ( count( $sub ) ) {
1279 $conds[] = $this->makeList(
1280 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1286 return $this->makeList( $conds, LIST_OR
);
1288 // Nothing to search for...
1294 * Bitwise operations
1297 function bitNot($field) {
1298 return "(~$bitField)";
1301 function bitAnd($fieldLeft, $fieldRight) {
1302 return "($fieldLeft & $fieldRight)";
1305 function bitOr($fieldLeft, $fieldRight) {
1306 return "($fieldLeft | $fieldRight)";
1310 * Change the current database
1312 * @return bool Success or failure
1314 function selectDB( $db ) {
1315 # Stub. Shouldn't cause serious problems if it's not overridden, but
1316 # if your database engine supports a concept similar to MySQL's
1317 # databases you may as well. TODO: explain what exactly will fail if
1318 # this is not overridden.
1323 * Get the current DB name
1325 function getDBname() {
1326 return $this->mDBname
;
1330 * Get the server hostname or IP address
1332 function getServer() {
1333 return $this->mServer
;
1337 * Format a table name ready for use in constructing an SQL query
1339 * This does two important things: it quotes the table names to clean them up,
1340 * and it adds a table prefix if only given a table name with no quotes.
1342 * All functions of this object which require a table name call this function
1343 * themselves. Pass the canonical name to such functions. This is only needed
1344 * when calling query() directly.
1346 * @param $name String: database table name
1347 * @return String: full database name
1349 function tableName( $name ) {
1350 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1351 # Skip the entire process when we have a string quoted on both ends.
1352 # Note that we check the end so that we will still quote any use of
1353 # use of `database`.table. But won't break things if someone wants
1354 # to query a database table with a dot in the name.
1355 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1357 # Lets test for any bits of text that should never show up in a table
1358 # name. Basically anything like JOIN or ON which are actually part of
1359 # SQL queries, but may end up inside of the table value to combine
1360 # sql. Such as how the API is doing.
1361 # Note that we use a whitespace test rather than a \b test to avoid
1362 # any remote case where a word like on may be inside of a table name
1363 # surrounded by symbols which may be considered word breaks.
1364 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1366 # Split database and table into proper variables.
1367 # We reverse the explode so that database.table and table both output
1368 # the correct table.
1369 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1370 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1371 else @list
( $table ) = $dbDetails;
1372 $prefix = $this->mTablePrefix
; # Default prefix
1374 # A database name has been specified in input. Quote the table name
1375 # because we don't want any prefixes added.
1376 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1378 # Note that we use the long format because php will complain in in_array if
1379 # the input is not an array, and will complain in is_array if it is not set.
1380 if( !isset( $database ) # Don't use shared database if pre selected.
1381 && isset( $wgSharedDB ) # We have a shared database
1382 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1383 && isset( $wgSharedTables )
1384 && is_array( $wgSharedTables )
1385 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1386 $database = $wgSharedDB;
1387 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1390 # Quote the $database and $table and apply the prefix if not quoted.
1391 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1392 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1394 # Merge our database and table into our final table name.
1395 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1397 # We're finished, return.
1402 * Fetch a number of table names into an array
1403 * This is handy when you need to construct SQL for joins
1406 * extract($dbr->tableNames('user','watchlist'));
1407 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1408 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1410 public function tableNames() {
1411 $inArray = func_get_args();
1413 foreach ( $inArray as $name ) {
1414 $retVal[$name] = $this->tableName( $name );
1420 * Fetch a number of table names into an zero-indexed numerical array
1421 * This is handy when you need to construct SQL for joins
1424 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1425 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1426 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1428 public function tableNamesN() {
1429 $inArray = func_get_args();
1431 foreach ( $inArray as $name ) {
1432 $retVal[] = $this->tableName( $name );
1440 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1443 $use_index_safe = is_array($use_index) ?
$use_index : array();
1444 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1445 foreach ( $tables as $table ) {
1446 // Is there a JOIN and INDEX clause for this table?
1447 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1448 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1449 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1450 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1451 $retJOIN[] = $tableClause;
1452 // Is there an INDEX clause?
1453 } else if ( isset($use_index_safe[$table]) ) {
1454 $tableClause = $this->tableName( $table );
1455 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1456 $ret[] = $tableClause;
1457 // Is there a JOIN clause?
1458 } else if ( isset($join_conds_safe[$table]) ) {
1459 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1460 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1461 $retJOIN[] = $tableClause;
1463 $tableClause = $this->tableName( $table );
1464 $ret[] = $tableClause;
1467 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1468 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1469 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1470 // Compile our final table clause
1471 return implode(' ',array($straightJoins,$otherJoins) );
1475 * Get the name of an index in a given table
1477 function indexName( $index ) {
1478 // Backwards-compatibility hack
1480 'ar_usertext_timestamp' => 'usertext_timestamp',
1481 'un_user_id' => 'user_id',
1482 'un_user_ip' => 'user_ip',
1484 if( isset( $renamed[$index] ) ) {
1485 return $renamed[$index];
1492 * Wrapper for addslashes()
1493 * @param $s String: to be slashed.
1494 * @return String: slashed string.
1496 abstract function strencode( $s );
1499 * If it's a string, adds quotes and backslashes
1500 * Otherwise returns as-is
1502 function addQuotes( $s ) {
1503 if ( $s === null ) {
1506 # This will also quote numeric values. This should be harmless,
1507 # and protects against weird problems that occur when they really
1508 # _are_ strings such as article titles and string->number->string
1509 # conversion is not 1:1.
1510 return "'" . $this->strencode( $s ) . "'";
1515 * Escape string for safe LIKE usage.
1516 * WARNING: you should almost never use this function directly,
1517 * instead use buildLike() that escapes everything automatically
1519 function escapeLike( $s ) {
1520 $s = str_replace( '\\', '\\\\', $s );
1521 $s = $this->strencode( $s );
1522 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1527 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1528 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1529 * Alternatively, the function could be provided with an array of aforementioned parameters.
1531 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1532 * for subpages of 'My page title'.
1533 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1535 * @ return String: fully built LIKE statement
1537 function buildLike() {
1538 $params = func_get_args();
1539 if (count($params) > 0 && is_array($params[0])) {
1540 $params = $params[0];
1544 foreach( $params as $value) {
1545 if( $value instanceof LikeMatch
) {
1546 $s .= $value->toString();
1548 $s .= $this->escapeLike( $value );
1551 return " LIKE '" . $s . "' ";
1555 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1557 function anyChar() {
1558 return new LikeMatch( '_' );
1562 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1564 function anyString() {
1565 return new LikeMatch( '%' );
1569 * Returns an appropriately quoted sequence value for inserting a new row.
1570 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1571 * subclass will return an integer, and save the value for insertId()
1573 function nextSequenceValue( $seqName ) {
1578 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1579 * is only needed because a) MySQL must be as efficient as possible due to
1580 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1581 * which index to pick. Anyway, other databases might have different
1582 * indexes on a given table. So don't bother overriding this unless you're
1585 function useIndexClause( $index ) {
1590 * REPLACE query wrapper
1591 * PostgreSQL simulates this with a DELETE followed by INSERT
1592 * $row is the row to insert, an associative array
1593 * $uniqueIndexes is an array of indexes. Each element may be either a
1594 * field name or an array of field names
1596 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1597 * However if you do this, you run the risk of encountering errors which wouldn't have
1600 * @todo migrate comment to phodocumentor format
1602 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1603 $table = $this->tableName( $table );
1606 if ( !is_array( reset( $rows ) ) ) {
1607 $rows = array( $rows );
1610 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1612 foreach ( $rows as $row ) {
1618 $sql .= '(' . $this->makeList( $row ) . ')';
1620 return $this->query( $sql, $fname );
1624 * DELETE where the condition is a join
1625 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1627 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1628 * join condition matches, set $conds='*'
1630 * DO NOT put the join condition in $conds
1632 * @param $delTable String: The table to delete from.
1633 * @param $joinTable String: The other table.
1634 * @param $delVar String: The variable to join on, in the first table.
1635 * @param $joinVar String: The variable to join on, in the second table.
1636 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1637 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1639 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1641 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1644 $delTable = $this->tableName( $delTable );
1645 $joinTable = $this->tableName( $joinTable );
1646 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1647 if ( $conds != '*' ) {
1648 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1651 return $this->query( $sql, $fname );
1655 * Returns the size of a text field, or -1 for "unlimited"
1657 function textFieldSize( $table, $field ) {
1658 $table = $this->tableName( $table );
1659 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1660 $res = $this->query( $sql, 'Database::textFieldSize' );
1661 $row = $this->fetchObject( $res );
1662 $this->freeResult( $res );
1665 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1674 * A string to insert into queries to show that they're low-priority, like
1675 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1676 * string and nothing bad should happen.
1678 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1680 function lowPriorityOption() {
1685 * DELETE query wrapper
1687 * Use $conds == "*" to delete all rows
1689 function delete( $table, $conds, $fname = 'Database::delete' ) {
1691 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1693 $table = $this->tableName( $table );
1694 $sql = "DELETE FROM $table";
1695 if ( $conds != '*' ) {
1696 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1698 return $this->query( $sql, $fname );
1702 * INSERT SELECT wrapper
1703 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1704 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1705 * $conds may be "*" to copy the whole table
1706 * srcTable may be an array of tables.
1708 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1709 $insertOptions = array(), $selectOptions = array() )
1711 $destTable = $this->tableName( $destTable );
1712 if ( is_array( $insertOptions ) ) {
1713 $insertOptions = implode( ' ', $insertOptions );
1715 if( !is_array( $selectOptions ) ) {
1716 $selectOptions = array( $selectOptions );
1718 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1719 if( is_array( $srcTable ) ) {
1720 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1722 $srcTable = $this->tableName( $srcTable );
1724 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1725 " SELECT $startOpts " . implode( ',', $varMap ) .
1726 " FROM $srcTable $useIndex ";
1727 if ( $conds != '*' ) {
1728 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1730 $sql .= " $tailOpts";
1731 return $this->query( $sql, $fname );
1735 * Construct a LIMIT query with optional offset. This is used for query
1736 * pages. The SQL should be adjusted so that only the first $limit rows
1737 * are returned. If $offset is provided as well, then the first $offset
1738 * rows should be discarded, and the next $limit rows should be returned.
1739 * If the result of the query is not ordered, then the rows to be returned
1740 * are theoretically arbitrary.
1742 * $sql is expected to be a SELECT, if that makes a difference. For
1743 * UPDATE, limitResultForUpdate should be used.
1745 * The version provided by default works in MySQL and SQLite. It will very
1746 * likely need to be overridden for most other DBMSes.
1748 * @param $sql String: SQL query we will append the limit too
1749 * @param $limit Integer: the SQL limit
1750 * @param $offset Integer the SQL offset (default false)
1752 function limitResult( $sql, $limit, $offset=false ) {
1753 if( !is_numeric( $limit ) ) {
1754 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1756 return "$sql LIMIT "
1757 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1760 function limitResultForUpdate( $sql, $num ) {
1761 return $this->limitResult( $sql, $num, 0 );
1765 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1766 * within the UNION construct.
1769 function unionSupportsOrderAndLimit() {
1770 return true; // True for almost every DB supported
1774 * Construct a UNION query
1775 * This is used for providing overload point for other DB abstractions
1776 * not compatible with the MySQL syntax.
1777 * @param $sqls Array: SQL statements to combine
1778 * @param $all Boolean: use UNION ALL
1779 * @return String: SQL fragment
1781 function unionQueries($sqls, $all) {
1782 $glue = $all ?
') UNION ALL (' : ') UNION (';
1783 return '('.implode( $glue, $sqls ) . ')';
1787 * Returns an SQL expression for a simple conditional. This doesn't need
1788 * to be overridden unless CASE isn't supported in your DBMS.
1790 * @param $cond String: SQL expression which will result in a boolean value
1791 * @param $trueVal String: SQL expression to return if true
1792 * @param $falseVal String: SQL expression to return if false
1793 * @return String: SQL fragment
1795 function conditional( $cond, $trueVal, $falseVal ) {
1796 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1800 * Returns a comand for str_replace function in SQL query.
1801 * Uses REPLACE() in MySQL
1803 * @param $orig String: column to modify
1804 * @param $old String: column to seek
1805 * @param $new String: column to replace with
1807 function strreplace( $orig, $old, $new ) {
1808 return "REPLACE({$orig}, {$old}, {$new})";
1812 * Determines if the last failure was due to a deadlock
1815 function wasDeadlock() {
1820 * Determines if the last query error was something that should be dealt
1821 * with by pinging the connection and reissuing the query.
1824 function wasErrorReissuable() {
1829 * Determines if the last failure was due to the database being read-only.
1832 function wasReadOnlyError() {
1837 * Perform a deadlock-prone transaction.
1839 * This function invokes a callback function to perform a set of write
1840 * queries. If a deadlock occurs during the processing, the transaction
1841 * will be rolled back and the callback function will be called again.
1844 * $dbw->deadlockLoop( callback, ... );
1846 * Extra arguments are passed through to the specified callback function.
1848 * Returns whatever the callback function returned on its successful,
1849 * iteration, or false on error, for example if the retry limit was
1852 function deadlockLoop() {
1853 $myFname = 'Database::deadlockLoop';
1856 $args = func_get_args();
1857 $function = array_shift( $args );
1858 $oldIgnore = $this->ignoreErrors( true );
1859 $tries = DEADLOCK_TRIES
;
1860 if ( is_array( $function ) ) {
1861 $fname = $function[0];
1866 $retVal = call_user_func_array( $function, $args );
1867 $error = $this->lastError();
1868 $errno = $this->lastErrno();
1869 $sql = $this->lastQuery();
1872 if ( $this->wasDeadlock() ) {
1874 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1876 $this->reportQueryError( $error, $errno, $sql, $fname );
1879 } while( $this->wasDeadlock() && --$tries > 0 );
1880 $this->ignoreErrors( $oldIgnore );
1881 if ( $tries <= 0 ) {
1882 $this->query( 'ROLLBACK', $myFname );
1883 $this->reportQueryError( $error, $errno, $sql, $fname );
1886 $this->query( 'COMMIT', $myFname );
1892 * Do a SELECT MASTER_POS_WAIT()
1894 * @param $pos MySQLMasterPos object
1895 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1897 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1898 $fname = 'Database::masterPosWait';
1899 wfProfileIn( $fname );
1901 # Commit any open transactions
1902 if ( $this->mTrxLevel
) {
1906 if ( !is_null( $this->mFakeSlaveLag
) ) {
1907 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1908 if ( $wait > $timeout * 1e6
) {
1909 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1910 wfProfileOut( $fname );
1912 } elseif ( $wait > 0 ) {
1913 wfDebug( "Fake slave waiting $wait us\n" );
1915 wfProfileOut( $fname );
1918 wfDebug( "Fake slave up to date ($wait us)\n" );
1919 wfProfileOut( $fname );
1924 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1925 $encFile = $this->addQuotes( $pos->file
);
1926 $encPos = intval( $pos->pos
);
1927 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1928 $res = $this->doQuery( $sql );
1929 if ( $res && $row = $this->fetchRow( $res ) ) {
1930 $this->freeResult( $res );
1931 wfProfileOut( $fname );
1934 wfProfileOut( $fname );
1940 * Get the position of the master from SHOW SLAVE STATUS
1942 function getSlavePos() {
1943 if ( !is_null( $this->mFakeSlaveLag
) ) {
1944 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1945 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1948 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1949 $row = $this->fetchObject( $res );
1951 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1952 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1959 * Get the position of the master from SHOW MASTER STATUS
1961 function getMasterPos() {
1962 if ( $this->mFakeMaster
) {
1963 return new MySQLMasterPos( 'fake', microtime( true ) );
1965 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1966 $row = $this->fetchObject( $res );
1968 return new MySQLMasterPos( $row->File
, $row->Position
);
1975 * Begin a transaction, committing any previously open transaction
1977 function begin( $fname = 'Database::begin' ) {
1978 $this->query( 'BEGIN', $fname );
1979 $this->mTrxLevel
= 1;
1985 function commit( $fname = 'Database::commit' ) {
1986 $this->query( 'COMMIT', $fname );
1987 $this->mTrxLevel
= 0;
1991 * Rollback a transaction.
1992 * No-op on non-transactional databases.
1994 function rollback( $fname = 'Database::rollback' ) {
1995 $this->query( 'ROLLBACK', $fname, true );
1996 $this->mTrxLevel
= 0;
2000 * Begin a transaction, committing any previously open transaction
2001 * @deprecated use begin()
2003 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2008 * Commit transaction, if one is open
2009 * @deprecated use commit()
2011 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2016 * Creates a new table with structure copied from existing table
2017 * Note that unlike most database abstraction functions, this function does not
2018 * automatically append database prefix, because it works at a lower
2019 * abstraction level.
2021 * @param $oldName String: name of table whose structure should be copied
2022 * @param $newName String: name of table to be created
2023 * @param $temporary Boolean: whether the new table should be temporary
2024 * @return Boolean: true if operation was successful
2026 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2027 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2031 * Return MW-style timestamp used for MySQL schema
2033 function timestamp( $ts=0 ) {
2034 return wfTimestamp(TS_MW
,$ts);
2038 * Local database timestamp format or null
2040 function timestampOrNull( $ts = null ) {
2041 if( is_null( $ts ) ) {
2044 return $this->timestamp( $ts );
2051 function resultObject( $result ) {
2052 if( empty( $result ) ) {
2054 } elseif ( $result instanceof ResultWrapper
) {
2056 } elseif ( $result === true ) {
2057 // Successful write query
2060 return new ResultWrapper( $this, $result );
2065 * Return aggregated value alias
2067 function aggregateValue ($valuedata,$valuename='value') {
2072 * Returns a wikitext link to the DB's website, e.g.,
2073 * return "[http://www.mysql.com/ MySQL]";
2074 * Should at least contain plain text, if for some reason
2075 * your database has no website.
2077 * @return String: wikitext of a link to the server software's web site
2079 abstract function getSoftwareLink();
2082 * A string describing the current software version, like from
2083 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2085 * @return String: Version information from the database
2087 abstract function getServerVersion();
2090 * Ping the server and try to reconnect if it there is no connection
2092 * @return bool Success or failure
2095 # Stub. Not essential to override.
2101 * Currently supported only by MySQL
2102 * @return Database replication lag in seconds
2105 return $this->mFakeSlaveLag
;
2109 * Get status information from SHOW STATUS in an associative array
2111 function getStatus($which="%") {
2112 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2114 while ( $row = $this->fetchObject( $res ) ) {
2115 $status[$row->Variable_name
] = $row->Value
;
2121 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2123 function maxListLen() {
2127 function encodeBlob($b) {
2131 function decodeBlob($b) {
2136 * Override database's default connection timeout. May be useful for very
2137 * long batch queries such as full-wiki dumps, where a single query reads
2138 * out over hours or days. May or may not be necessary for non-MySQL
2139 * databases. For most purposes, leaving it as a no-op should be fine.
2141 * @param $timeout Integer in seconds
2143 public function setTimeout( $timeout ) {}
2146 * Read and execute SQL commands from a file.
2147 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2148 * @param $filename String: File name to open
2149 * @param $lineCallback Callback: Optional function called before reading each line
2150 * @param $resultCallback Callback: Optional function called for each MySQL result
2152 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2153 $fp = fopen( $filename, 'r' );
2154 if ( false === $fp ) {
2155 if (!defined("MEDIAWIKI_INSTALL"))
2156 throw new MWException( "Could not open \"{$filename}\".\n" );
2158 return "Could not open \"{$filename}\".\n";
2161 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2163 catch( MWException
$e ) {
2164 if ( defined("MEDIAWIKI_INSTALL") ) {
2165 $error = $e->getMessage();
2177 * Get the full path of a patch file. Originally based on archive()
2178 * from updaters.inc. Keep in mind this always returns a patch, as
2179 * it fails back to MySQL if no DB-specific patch can be found
2181 * @param $patch String The name of the patch, like patch-something.sql
2182 * @return String Full path to patch file
2184 public static function patchPath( $patch ) {
2185 global $wgDBtype, $IP;
2186 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2187 return "$IP/maintenance/$wgDBtype/archives/$patch";
2189 return "$IP/maintenance/archives/$patch";
2194 * Read and execute commands from an open file handle
2195 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2196 * @param $fp String: File handle
2197 * @param $lineCallback Callback: Optional function called before reading each line
2198 * @param $resultCallback Callback: Optional function called for each MySQL result
2200 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2203 $dollarquote = false;
2205 while ( ! feof( $fp ) ) {
2206 if ( $lineCallback ) {
2207 call_user_func( $lineCallback );
2209 $line = trim( fgets( $fp, 1024 ) );
2210 $sl = strlen( $line ) - 1;
2212 if ( $sl < 0 ) { continue; }
2213 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2215 ## Allow dollar quoting for function declarations
2216 if (substr($line,0,4) == '$mw$') {
2218 $dollarquote = false;
2222 $dollarquote = true;
2225 else if (!$dollarquote) {
2226 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2228 $line = substr( $line, 0, $sl );
2232 if ( $cmd != '' ) { $cmd .= ' '; }
2236 $cmd = str_replace(';;', ";", $cmd);
2237 $cmd = $this->replaceVars( $cmd );
2238 $res = $this->query( $cmd, __METHOD__
);
2239 if ( $resultCallback ) {
2240 call_user_func( $resultCallback, $res, $this );
2243 if ( false === $res ) {
2244 $err = $this->lastError();
2245 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2257 * Replace variables in sourced SQL
2259 protected function replaceVars( $ins ) {
2261 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2262 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2263 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2266 // Ordinary variables
2267 foreach ( $varnames as $var ) {
2268 if( isset( $GLOBALS[$var] ) ) {
2269 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2270 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2271 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2272 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2277 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2278 array( $this, 'tableNameCallback' ), $ins );
2281 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2282 array( $this, 'indexNameCallback' ), $ins );
2287 * Table name callback
2290 protected function tableNameCallback( $matches ) {
2291 return $this->tableName( $matches[1] );
2295 * Index name callback
2297 protected function indexNameCallback( $matches ) {
2298 return $this->indexName( $matches[1] );
2302 * Build a concatenation list to feed into a SQL query
2303 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2306 function buildConcat( $stringList ) {
2307 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2311 * Acquire a named lock
2313 * Abstracted from Filestore::lock() so child classes can implement for
2316 * @param $lockName String: Name of lock to aquire
2317 * @param $method String: Name of method calling us
2320 public function lock( $lockName, $method, $timeout = 5 ) {
2327 * @param $lockName String: Name of lock to release
2328 * @param $method String: Name of method calling us
2330 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2331 * @return Returns 1 if the lock was released, 0 if the lock was not established
2332 * by this thread (in which case the lock is not released), and NULL if the named
2333 * lock did not exist
2335 public function unlock( $lockName, $method ) {
2340 * Lock specific tables
2342 * @param $read Array of tables to lock for read access
2343 * @param $write Array of tables to lock for write access
2344 * @param $method String name of caller
2345 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2347 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2352 * Unlock specific tables
2354 * @param $method String the caller
2356 public function unlockTables( $method ) {
2361 * Get search engine class. All subclasses of this
2362 * need to implement this if they wish to use searching.
2366 public function getSearchEngine() {
2367 return "SearchMySQL";
2371 * Allow or deny "big selects" for this session only. This is done by setting
2372 * the sql_big_selects session variable.
2374 * This is a MySQL-specific feature.
2376 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2378 public function setBigSelects( $value = true ) {
2384 /******************************************************************************
2386 *****************************************************************************/
2395 function DBObject($data) {
2396 $this->mData
= $data;
2404 return $this->mData
;
2412 * This allows us to distinguish a blob from a normal string and an array of strings
2416 function __construct($data) {
2417 $this->mData
= $data;
2420 return $this->mData
;
2429 private $name, $tablename, $default, $max_length, $nullable,
2430 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2431 function __construct ($info) {
2432 $this->name
= $info->name
;
2433 $this->tablename
= $info->table
;
2434 $this->default = $info->def
;
2435 $this->max_length
= $info->max_length
;
2436 $this->nullable
= !$info->not_null
;
2437 $this->is_pk
= $info->primary_key
;
2438 $this->is_unique
= $info->unique_key
;
2439 $this->is_multiple
= $info->multiple_key
;
2440 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2441 $this->type
= $info->type
;
2448 function tableName() {
2449 return $this->tableName
;
2452 function defaultValue() {
2453 return $this->default;
2456 function maxLength() {
2457 return $this->max_length
;
2460 function nullable() {
2461 return $this->nullable
;
2465 return $this->is_key
;
2468 function isMultipleKey() {
2469 return $this->is_multiple
;
2477 /******************************************************************************
2479 *****************************************************************************/
2482 * Database error base class
2485 class DBError
extends MWException
{
2489 * Construct a database error
2490 * @param $db Database object which threw the error
2491 * @param $error A simple error message to be used for debugging
2493 function __construct( DatabaseBase
&$db, $error ) {
2495 parent
::__construct( $error );
2498 function getText() {
2499 global $wgShowDBErrorBacktrace;
2500 $s = $this->getMessage() . "\n";
2501 if ( $wgShowDBErrorBacktrace ) {
2502 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2511 class DBConnectionError
extends DBError
{
2514 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2515 $msg = 'DB connection error';
2516 if ( trim( $error ) != '' ) {
2519 $this->error
= $error;
2520 parent
::__construct( $db, $msg );
2523 function useOutputPage() {
2524 // Not likely to work
2528 function useMessageCache() {
2529 // Not likely to work
2533 function getLogMessage() {
2534 # Don't send to the exception log
2538 function getPageTitle() {
2539 global $wgSitename, $wgLang;
2540 $header = "$wgSitename has a problem";
2541 if ( $wgLang instanceof Language
) {
2542 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2548 function getHTML() {
2549 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2551 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2552 $again = 'Try waiting a few minutes and reloading.';
2553 $info = '(Can\'t contact the database server: $1)';
2555 if ( $wgLang instanceof Language
) {
2556 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2557 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2558 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2561 # No database access
2562 if ( is_object( $wgMessageCache ) ) {
2563 $wgMessageCache->disable();
2566 if ( trim( $this->error
) == '' ) {
2567 $this->error
= $this->db
->getProperty('mServer');
2570 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2571 $text = str_replace( '$1', $this->error
, $noconnect );
2573 if ( $wgShowDBErrorBacktrace ) {
2574 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2577 $extra = $this->searchForm();
2579 if( $wgUseFileCache ) {
2581 $cache = $this->fileCachedPage();
2582 # Cached version on file system?
2583 if( $cache !== null ) {
2584 # Hack: extend the body for error messages
2585 $cache = str_replace( array('</html>','</body>'), '', $cache );
2586 # Add cache notice...
2587 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2588 # Localize it if possible...
2589 if( $wgLang instanceof Language
) {
2590 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2592 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2593 # Output cached page with notices on bottom and re-close body
2594 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2596 } catch( MWException
$e ) {
2597 // Do nothing, just use the default page
2600 # Headers needed here - output is just the error message
2601 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2604 function searchForm() {
2605 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2606 $usegoogle = "You can try searching via Google in the meantime.";
2607 $outofdate = "Note that their indexes of our content may be out of date.";
2608 $googlesearch = "Search";
2610 if ( $wgLang instanceof Language
) {
2611 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2612 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2613 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2616 $search = htmlspecialchars(@$_REQUEST['search']);
2619 <div style="margin: 1.5em">$usegoogle<br />
2620 <small>$outofdate</small></div>
2621 <!-- SiteSearch Google -->
2622 <form method="get" action="http://www.google.com/search" id="googlesearch">
2623 <input type="hidden" name="domains" value="$wgServer" />
2624 <input type="hidden" name="num" value="50" />
2625 <input type="hidden" name="ie" value="$wgInputEncoding" />
2626 <input type="hidden" name="oe" value="$wgInputEncoding" />
2628 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2629 <input type="submit" name="btnG" value="$googlesearch" />
2631 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2632 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2635 <!-- SiteSearch Google -->
2640 function fileCachedPage() {
2641 global $wgTitle, $title, $wgLang, $wgOut;
2642 if( $wgOut->isDisabled() ) return; // Done already?
2643 $mainpage = 'Main Page';
2644 if ( $wgLang instanceof Language
) {
2645 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2650 } elseif( $title ) {
2651 $t = Title
::newFromURL( $title );
2653 $t = Title
::newFromText( $mainpage );
2656 $cache = new HTMLFileCache( $t );
2657 if( $cache->isFileCached() ) {
2658 return $cache->fetchPageText();
2664 function htmlBodyOnly() {
2673 class DBQueryError
extends DBError
{
2674 public $error, $errno, $sql, $fname;
2676 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2677 $message = "A database error has occurred\n" .
2679 "Function: $fname\n" .
2680 "Error: $errno $error\n";
2682 parent
::__construct( $db, $message );
2683 $this->error
= $error;
2684 $this->errno
= $errno;
2686 $this->fname
= $fname;
2689 function getText() {
2690 global $wgShowDBErrorBacktrace;
2691 if ( $this->useMessageCache() ) {
2692 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2693 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2694 if ( $wgShowDBErrorBacktrace ) {
2695 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2699 return parent
::getText();
2704 global $wgShowSQLErrors;
2705 if( !$wgShowSQLErrors ) {
2706 return $this->msg( 'sqlhidden', 'SQL hidden' );
2712 function getLogMessage() {
2713 # Don't send to the exception log
2717 function getPageTitle() {
2718 return $this->msg( 'databaseerror', 'Database error' );
2721 function getHTML() {
2722 global $wgShowDBErrorBacktrace;
2723 if ( $this->useMessageCache() ) {
2724 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2725 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2727 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2729 if ( $wgShowDBErrorBacktrace ) {
2730 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2739 class DBUnexpectedError
extends DBError
{}
2743 * Result wrapper for grabbing data queried by someone else
2746 class ResultWrapper
implements Iterator
{
2747 var $db, $result, $pos = 0, $currentRow = null;
2750 * Create a new result object from a result resource and a Database object
2752 function ResultWrapper( $database, $result ) {
2753 $this->db
= $database;
2754 if ( $result instanceof ResultWrapper
) {
2755 $this->result
= $result->result
;
2757 $this->result
= $result;
2762 * Get the number of rows in a result object
2764 function numRows() {
2765 return $this->db
->numRows( $this );
2769 * Fetch the next row from the given result object, in object form.
2770 * Fields can be retrieved with $row->fieldname, with fields acting like
2773 * @param $res SQL result object as returned from Database::query(), etc.
2774 * @return MySQL row object
2775 * @throws DBUnexpectedError Thrown if the database returns an error
2777 function fetchObject() {
2778 return $this->db
->fetchObject( $this );
2782 * Fetch the next row from the given result object, in associative array
2783 * form. Fields are retrieved with $row['fieldname'].
2785 * @param $res SQL result object as returned from Database::query(), etc.
2786 * @return MySQL row object
2787 * @throws DBUnexpectedError Thrown if the database returns an error
2789 function fetchRow() {
2790 return $this->db
->fetchRow( $this );
2794 * Free a result object
2797 $this->db
->freeResult( $this );
2798 unset( $this->result
);
2803 * Change the position of the cursor in a result object
2804 * See mysql_data_seek()
2806 function seek( $row ) {
2807 $this->db
->dataSeek( $this, $row );
2810 /*********************
2811 * Iterator functions
2812 * Note that using these in combination with the non-iterator functions
2813 * above may cause rows to be skipped or repeated.
2817 if ($this->numRows()) {
2818 $this->db
->dataSeek($this, 0);
2821 $this->currentRow
= null;
2824 function current() {
2825 if ( is_null( $this->currentRow
) ) {
2828 return $this->currentRow
;
2837 $this->currentRow
= $this->fetchObject();
2838 return $this->currentRow
;
2842 return $this->current() !== false;
2847 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2848 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2853 public function __construct( $s ) {
2857 public function toString() {