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 * Usually aborts on failure
1021 * If errors are explicitly ignored, returns NULL on failure
1023 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1024 $table = $this->tableName( $table );
1025 $res = $this->query( 'DESCRIBE '.$table, $fname );
1032 while ( $row = $this->fetchObject( $res ) ) {
1033 if ( $row->Field
== $field ) {
1042 * Determines whether an index exists
1043 * Usually aborts on failure
1044 * If errors are explicitly ignored, returns NULL on failure
1046 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1047 $info = $this->indexInfo( $table, $index, $fname );
1048 if ( is_null( $info ) ) {
1051 return $info !== false;
1057 * Get information about an index into an object
1058 * Returns false if the index does not exist
1060 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1061 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1062 # SHOW INDEX should work for 3.x and up:
1063 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1064 $table = $this->tableName( $table );
1065 $index = $this->indexName( $index );
1066 $sql = 'SHOW INDEX FROM '.$table;
1067 $res = $this->query( $sql, $fname );
1073 while ( $row = $this->fetchObject( $res ) ) {
1074 if ( $row->Key_name
== $index ) {
1078 $this->freeResult($res);
1080 return empty($result) ?
false : $result;
1084 * Query whether a given table exists
1086 function tableExists( $table ) {
1087 $table = $this->tableName( $table );
1088 $old = $this->ignoreErrors( true );
1089 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1090 $this->ignoreErrors( $old );
1092 $this->freeResult( $res );
1100 * mysql_fetch_field() wrapper
1101 * Returns false if the field doesn't exist
1106 abstract function fieldInfo( $table, $field );
1109 * mysql_field_type() wrapper
1111 function fieldType( $res, $index ) {
1112 if ( $res instanceof ResultWrapper
) {
1113 $res = $res->result
;
1115 return mysql_field_type( $res, $index );
1119 * Determines if a given index is unique
1121 function indexUnique( $table, $index ) {
1122 $indexInfo = $this->indexInfo( $table, $index );
1123 if ( !$indexInfo ) {
1126 return !$indexInfo[0]->Non_unique
;
1130 * INSERT wrapper, inserts an array into a table
1132 * $a may be a single associative array, or an array of these with numeric keys, for
1135 * Usually aborts on failure
1136 * If errors are explicitly ignored, returns success
1138 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1139 # No rows to insert, easy just return now
1140 if ( !count( $a ) ) {
1144 $table = $this->tableName( $table );
1145 if ( !is_array( $options ) ) {
1146 $options = array( $options );
1148 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1150 $keys = array_keys( $a[0] );
1153 $keys = array_keys( $a );
1156 $sql = 'INSERT ' . implode( ' ', $options ) .
1157 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1161 foreach ( $a as $row ) {
1167 $sql .= '(' . $this->makeList( $row ) . ')';
1170 $sql .= '(' . $this->makeList( $a ) . ')';
1172 return (bool)$this->query( $sql, $fname );
1176 * Make UPDATE options for the Database::update function
1179 * @param $options Array: The options passed to Database::update
1182 function makeUpdateOptions( $options ) {
1183 if( !is_array( $options ) ) {
1184 $options = array( $options );
1187 if ( in_array( 'LOW_PRIORITY', $options ) )
1188 $opts[] = $this->lowPriorityOption();
1189 if ( in_array( 'IGNORE', $options ) )
1191 return implode(' ', $opts);
1195 * UPDATE wrapper, takes a condition array and a SET array
1197 * @param $table String: The table to UPDATE
1198 * @param $values Array: An array of values to SET
1199 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1200 * @param $fname String: The Class::Function calling this function
1202 * @param $options Array: An array of UPDATE options, can be one or
1203 * more of IGNORE, LOW_PRIORITY
1206 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1207 $table = $this->tableName( $table );
1208 $opts = $this->makeUpdateOptions( $options );
1209 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1210 if ( $conds != '*' ) {
1211 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1213 return $this->query( $sql, $fname );
1217 * Makes an encoded list of strings from an array
1219 * LIST_COMMA - comma separated, no field names
1220 * LIST_AND - ANDed WHERE clause (without the WHERE)
1221 * LIST_OR - ORed WHERE clause (without the WHERE)
1222 * LIST_SET - comma separated with field names, like a SET clause
1223 * LIST_NAMES - comma separated field names
1225 function makeList( $a, $mode = LIST_COMMA
) {
1226 if ( !is_array( $a ) ) {
1227 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1232 foreach ( $a as $field => $value ) {
1234 if ( $mode == LIST_AND
) {
1236 } elseif($mode == LIST_OR
) {
1244 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1245 $list .= "($value)";
1246 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1248 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1249 if( count( $value ) == 0 ) {
1250 throw new MWException( __METHOD__
.': empty input' );
1251 } elseif( count( $value ) == 1 ) {
1252 // Special-case single values, as IN isn't terribly efficient
1253 // Don't necessarily assume the single key is 0; we don't
1254 // enforce linear numeric ordering on other arrays here.
1255 $value = array_values( $value );
1256 $list .= $field." = ".$this->addQuotes( $value[0] );
1258 $list .= $field." IN (".$this->makeList($value).") ";
1260 } elseif( $value === null ) {
1261 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1262 $list .= "$field IS ";
1263 } elseif ( $mode == LIST_SET
) {
1264 $list .= "$field = ";
1268 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1269 $list .= "$field = ";
1271 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1278 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1279 * The keys on each level may be either integers or strings.
1281 * @param array $data organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1282 * @param string $baseKey field name to match the base-level keys to (eg 'pl_namespace')
1283 * @param string $subKey field name to match the sub-level keys to (eg 'pl_title')
1284 * @return mixed string SQL fragment, or false if no items in array.
1286 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1288 foreach ( $data as $base => $sub ) {
1289 if ( count( $sub ) ) {
1290 $conds[] = $this->makeList(
1291 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1297 return $this->makeList( $conds, LIST_OR
);
1299 // Nothing to search for...
1305 * Bitwise operations
1308 function bitNot($field) {
1309 return "(~$bitField)";
1312 function bitAnd($fieldLeft, $fieldRight) {
1313 return "($fieldLeft & $fieldRight)";
1316 function bitOr($fieldLeft, $fieldRight) {
1317 return "($fieldLeft | $fieldRight)";
1321 * Change the current database
1323 * @return bool Success or failure
1325 function selectDB( $db ) {
1326 # Stub. Shouldn't cause serious problems if it's not overridden, but
1327 # if your database engine supports a concept similar to MySQL's
1328 # databases you may as well. TODO: explain what exactly will fail if
1329 # this is not overridden.
1334 * Get the current DB name
1336 function getDBname() {
1337 return $this->mDBname
;
1341 * Get the server hostname or IP address
1343 function getServer() {
1344 return $this->mServer
;
1348 * Format a table name ready for use in constructing an SQL query
1350 * This does two important things: it quotes the table names to clean them up,
1351 * and it adds a table prefix if only given a table name with no quotes.
1353 * All functions of this object which require a table name call this function
1354 * themselves. Pass the canonical name to such functions. This is only needed
1355 * when calling query() directly.
1357 * @param $name String: database table name
1358 * @return String: full database name
1360 function tableName( $name ) {
1361 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1362 # Skip the entire process when we have a string quoted on both ends.
1363 # Note that we check the end so that we will still quote any use of
1364 # use of `database`.table. But won't break things if someone wants
1365 # to query a database table with a dot in the name.
1366 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1368 # Lets test for any bits of text that should never show up in a table
1369 # name. Basically anything like JOIN or ON which are actually part of
1370 # SQL queries, but may end up inside of the table value to combine
1371 # sql. Such as how the API is doing.
1372 # Note that we use a whitespace test rather than a \b test to avoid
1373 # any remote case where a word like on may be inside of a table name
1374 # surrounded by symbols which may be considered word breaks.
1375 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1377 # Split database and table into proper variables.
1378 # We reverse the explode so that database.table and table both output
1379 # the correct table.
1380 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1381 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1382 else @list
( $table ) = $dbDetails;
1383 $prefix = $this->mTablePrefix
; # Default prefix
1385 # A database name has been specified in input. Quote the table name
1386 # because we don't want any prefixes added.
1387 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1389 # Note that we use the long format because php will complain in in_array if
1390 # the input is not an array, and will complain in is_array if it is not set.
1391 if( !isset( $database ) # Don't use shared database if pre selected.
1392 && isset( $wgSharedDB ) # We have a shared database
1393 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1394 && isset( $wgSharedTables )
1395 && is_array( $wgSharedTables )
1396 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1397 $database = $wgSharedDB;
1398 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1401 # Quote the $database and $table and apply the prefix if not quoted.
1402 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1403 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1405 # Merge our database and table into our final table name.
1406 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1408 # We're finished, return.
1413 * Fetch a number of table names into an array
1414 * This is handy when you need to construct SQL for joins
1417 * extract($dbr->tableNames('user','watchlist'));
1418 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1419 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1421 public function tableNames() {
1422 $inArray = func_get_args();
1424 foreach ( $inArray as $name ) {
1425 $retVal[$name] = $this->tableName( $name );
1431 * Fetch a number of table names into an zero-indexed numerical array
1432 * This is handy when you need to construct SQL for joins
1435 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1436 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1437 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1439 public function tableNamesN() {
1440 $inArray = func_get_args();
1442 foreach ( $inArray as $name ) {
1443 $retVal[] = $this->tableName( $name );
1451 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1454 $use_index_safe = is_array($use_index) ?
$use_index : array();
1455 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1456 foreach ( $tables as $table ) {
1457 // Is there a JOIN and INDEX clause for this table?
1458 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1459 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1460 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1461 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1462 $retJOIN[] = $tableClause;
1463 // Is there an INDEX clause?
1464 } else if ( isset($use_index_safe[$table]) ) {
1465 $tableClause = $this->tableName( $table );
1466 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1467 $ret[] = $tableClause;
1468 // Is there a JOIN clause?
1469 } else if ( isset($join_conds_safe[$table]) ) {
1470 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1471 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1472 $retJOIN[] = $tableClause;
1474 $tableClause = $this->tableName( $table );
1475 $ret[] = $tableClause;
1478 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1479 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1480 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1481 // Compile our final table clause
1482 return implode(' ',array($straightJoins,$otherJoins) );
1486 * Get the name of an index in a given table
1488 function indexName( $index ) {
1489 // Backwards-compatibility hack
1491 'ar_usertext_timestamp' => 'usertext_timestamp',
1492 'un_user_id' => 'user_id',
1493 'un_user_ip' => 'user_ip',
1495 if( isset( $renamed[$index] ) ) {
1496 return $renamed[$index];
1503 * Wrapper for addslashes()
1504 * @param $s String: to be slashed.
1505 * @return String: slashed string.
1507 abstract function strencode( $s );
1510 * If it's a string, adds quotes and backslashes
1511 * Otherwise returns as-is
1513 function addQuotes( $s ) {
1514 if ( $s === null ) {
1517 # This will also quote numeric values. This should be harmless,
1518 # and protects against weird problems that occur when they really
1519 # _are_ strings such as article titles and string->number->string
1520 # conversion is not 1:1.
1521 return "'" . $this->strencode( $s ) . "'";
1526 * Escape string for safe LIKE usage.
1527 * WARNING: you should almost never use this function directly,
1528 * instead use buildLike() that escapes everything automatically
1530 function escapeLike( $s ) {
1531 $s = str_replace( '\\', '\\\\', $s );
1532 $s = $this->strencode( $s );
1533 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1538 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1539 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1540 * Alternatively, the function could be provided with an array of aforementioned parameters.
1542 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1543 * for subpages of 'My page title'.
1544 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1546 * @ return String: fully built LIKE statement
1548 function buildLike() {
1549 $params = func_get_args();
1550 if (count($params) > 0 && is_array($params[0])) {
1551 $params = $params[0];
1555 foreach( $params as $value) {
1556 if( $value instanceof LikeMatch
) {
1557 $s .= $value->toString();
1559 $s .= $this->escapeLike( $value );
1562 return " LIKE '" . $s . "' ";
1566 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1568 function anyChar() {
1569 return new LikeMatch( '_' );
1573 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1575 function anyString() {
1576 return new LikeMatch( '%' );
1580 * Returns an appropriately quoted sequence value for inserting a new row.
1581 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1582 * subclass will return an integer, and save the value for insertId()
1584 function nextSequenceValue( $seqName ) {
1589 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1590 * is only needed because a) MySQL must be as efficient as possible due to
1591 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1592 * which index to pick. Anyway, other databases might have different
1593 * indexes on a given table. So don't bother overriding this unless you're
1596 function useIndexClause( $index ) {
1601 * REPLACE query wrapper
1602 * PostgreSQL simulates this with a DELETE followed by INSERT
1603 * $row is the row to insert, an associative array
1604 * $uniqueIndexes is an array of indexes. Each element may be either a
1605 * field name or an array of field names
1607 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1608 * However if you do this, you run the risk of encountering errors which wouldn't have
1611 * @todo migrate comment to phodocumentor format
1613 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1614 $table = $this->tableName( $table );
1617 if ( !is_array( reset( $rows ) ) ) {
1618 $rows = array( $rows );
1621 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1623 foreach ( $rows as $row ) {
1629 $sql .= '(' . $this->makeList( $row ) . ')';
1631 return $this->query( $sql, $fname );
1635 * DELETE where the condition is a join
1636 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1638 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1639 * join condition matches, set $conds='*'
1641 * DO NOT put the join condition in $conds
1643 * @param $delTable String: The table to delete from.
1644 * @param $joinTable String: The other table.
1645 * @param $delVar String: The variable to join on, in the first table.
1646 * @param $joinVar String: The variable to join on, in the second table.
1647 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1648 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1650 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1652 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1655 $delTable = $this->tableName( $delTable );
1656 $joinTable = $this->tableName( $joinTable );
1657 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1658 if ( $conds != '*' ) {
1659 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1662 return $this->query( $sql, $fname );
1666 * Returns the size of a text field, or -1 for "unlimited"
1668 function textFieldSize( $table, $field ) {
1669 $table = $this->tableName( $table );
1670 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1671 $res = $this->query( $sql, 'Database::textFieldSize' );
1672 $row = $this->fetchObject( $res );
1673 $this->freeResult( $res );
1676 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1685 * A string to insert into queries to show that they're low-priority, like
1686 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1687 * string and nothing bad should happen.
1689 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1691 function lowPriorityOption() {
1696 * DELETE query wrapper
1698 * Use $conds == "*" to delete all rows
1700 function delete( $table, $conds, $fname = 'Database::delete' ) {
1702 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1704 $table = $this->tableName( $table );
1705 $sql = "DELETE FROM $table";
1706 if ( $conds != '*' ) {
1707 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1709 return $this->query( $sql, $fname );
1713 * INSERT SELECT wrapper
1714 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1715 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1716 * $conds may be "*" to copy the whole table
1717 * srcTable may be an array of tables.
1719 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1720 $insertOptions = array(), $selectOptions = array() )
1722 $destTable = $this->tableName( $destTable );
1723 if ( is_array( $insertOptions ) ) {
1724 $insertOptions = implode( ' ', $insertOptions );
1726 if( !is_array( $selectOptions ) ) {
1727 $selectOptions = array( $selectOptions );
1729 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1730 if( is_array( $srcTable ) ) {
1731 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1733 $srcTable = $this->tableName( $srcTable );
1735 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1736 " SELECT $startOpts " . implode( ',', $varMap ) .
1737 " FROM $srcTable $useIndex ";
1738 if ( $conds != '*' ) {
1739 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1741 $sql .= " $tailOpts";
1742 return $this->query( $sql, $fname );
1746 * Construct a LIMIT query with optional offset. This is used for query
1747 * pages. The SQL should be adjusted so that only the first $limit rows
1748 * are returned. If $offset is provided as well, then the first $offset
1749 * rows should be discarded, and the next $limit rows should be returned.
1750 * If the result of the query is not ordered, then the rows to be returned
1751 * are theoretically arbitrary.
1753 * $sql is expected to be a SELECT, if that makes a difference. For
1754 * UPDATE, limitResultForUpdate should be used.
1756 * The version provided by default works in MySQL and SQLite. It will very
1757 * likely need to be overridden for most other DBMSes.
1759 * @param $sql String: SQL query we will append the limit too
1760 * @param $limit Integer: the SQL limit
1761 * @param $offset Integer the SQL offset (default false)
1763 function limitResult( $sql, $limit, $offset=false ) {
1764 if( !is_numeric( $limit ) ) {
1765 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1767 return "$sql LIMIT "
1768 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1771 function limitResultForUpdate( $sql, $num ) {
1772 return $this->limitResult( $sql, $num, 0 );
1776 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1777 * within the UNION construct.
1780 function unionSupportsOrderAndLimit() {
1781 return true; // True for almost every DB supported
1785 * Construct a UNION query
1786 * This is used for providing overload point for other DB abstractions
1787 * not compatible with the MySQL syntax.
1788 * @param $sqls Array: SQL statements to combine
1789 * @param $all Boolean: use UNION ALL
1790 * @return String: SQL fragment
1792 function unionQueries($sqls, $all) {
1793 $glue = $all ?
') UNION ALL (' : ') UNION (';
1794 return '('.implode( $glue, $sqls ) . ')';
1798 * Returns an SQL expression for a simple conditional. This doesn't need
1799 * to be overridden unless CASE isn't supported in your DBMS.
1801 * @param $cond String: SQL expression which will result in a boolean value
1802 * @param $trueVal String: SQL expression to return if true
1803 * @param $falseVal String: SQL expression to return if false
1804 * @return String: SQL fragment
1806 function conditional( $cond, $trueVal, $falseVal ) {
1807 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1811 * Returns a comand for str_replace function in SQL query.
1812 * Uses REPLACE() in MySQL
1814 * @param $orig String: column to modify
1815 * @param $old String: column to seek
1816 * @param $new String: column to replace with
1818 function strreplace( $orig, $old, $new ) {
1819 return "REPLACE({$orig}, {$old}, {$new})";
1823 * Determines if the last failure was due to a deadlock
1826 function wasDeadlock() {
1831 * Determines if the last query error was something that should be dealt
1832 * with by pinging the connection and reissuing the query.
1835 function wasErrorReissuable() {
1840 * Determines if the last failure was due to the database being read-only.
1843 function wasReadOnlyError() {
1848 * Perform a deadlock-prone transaction.
1850 * This function invokes a callback function to perform a set of write
1851 * queries. If a deadlock occurs during the processing, the transaction
1852 * will be rolled back and the callback function will be called again.
1855 * $dbw->deadlockLoop( callback, ... );
1857 * Extra arguments are passed through to the specified callback function.
1859 * Returns whatever the callback function returned on its successful,
1860 * iteration, or false on error, for example if the retry limit was
1863 function deadlockLoop() {
1864 $myFname = 'Database::deadlockLoop';
1867 $args = func_get_args();
1868 $function = array_shift( $args );
1869 $oldIgnore = $this->ignoreErrors( true );
1870 $tries = DEADLOCK_TRIES
;
1871 if ( is_array( $function ) ) {
1872 $fname = $function[0];
1877 $retVal = call_user_func_array( $function, $args );
1878 $error = $this->lastError();
1879 $errno = $this->lastErrno();
1880 $sql = $this->lastQuery();
1883 if ( $this->wasDeadlock() ) {
1885 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1887 $this->reportQueryError( $error, $errno, $sql, $fname );
1890 } while( $this->wasDeadlock() && --$tries > 0 );
1891 $this->ignoreErrors( $oldIgnore );
1892 if ( $tries <= 0 ) {
1893 $this->query( 'ROLLBACK', $myFname );
1894 $this->reportQueryError( $error, $errno, $sql, $fname );
1897 $this->query( 'COMMIT', $myFname );
1903 * Do a SELECT MASTER_POS_WAIT()
1905 * @param $pos MySQLMasterPos object
1906 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1908 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1909 $fname = 'Database::masterPosWait';
1910 wfProfileIn( $fname );
1912 # Commit any open transactions
1913 if ( $this->mTrxLevel
) {
1917 if ( !is_null( $this->mFakeSlaveLag
) ) {
1918 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1919 if ( $wait > $timeout * 1e6
) {
1920 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1921 wfProfileOut( $fname );
1923 } elseif ( $wait > 0 ) {
1924 wfDebug( "Fake slave waiting $wait us\n" );
1926 wfProfileOut( $fname );
1929 wfDebug( "Fake slave up to date ($wait us)\n" );
1930 wfProfileOut( $fname );
1935 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1936 $encFile = $this->addQuotes( $pos->file
);
1937 $encPos = intval( $pos->pos
);
1938 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1939 $res = $this->doQuery( $sql );
1940 if ( $res && $row = $this->fetchRow( $res ) ) {
1941 $this->freeResult( $res );
1942 wfProfileOut( $fname );
1945 wfProfileOut( $fname );
1951 * Get the position of the master from SHOW SLAVE STATUS
1953 function getSlavePos() {
1954 if ( !is_null( $this->mFakeSlaveLag
) ) {
1955 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1956 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1959 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1960 $row = $this->fetchObject( $res );
1962 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
1963 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
1970 * Get the position of the master from SHOW MASTER STATUS
1972 function getMasterPos() {
1973 if ( $this->mFakeMaster
) {
1974 return new MySQLMasterPos( 'fake', microtime( true ) );
1976 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1977 $row = $this->fetchObject( $res );
1979 return new MySQLMasterPos( $row->File
, $row->Position
);
1986 * Begin a transaction, committing any previously open transaction
1988 function begin( $fname = 'Database::begin' ) {
1989 $this->query( 'BEGIN', $fname );
1990 $this->mTrxLevel
= 1;
1996 function commit( $fname = 'Database::commit' ) {
1997 $this->query( 'COMMIT', $fname );
1998 $this->mTrxLevel
= 0;
2002 * Rollback a transaction.
2003 * No-op on non-transactional databases.
2005 function rollback( $fname = 'Database::rollback' ) {
2006 $this->query( 'ROLLBACK', $fname, true );
2007 $this->mTrxLevel
= 0;
2011 * Begin a transaction, committing any previously open transaction
2012 * @deprecated use begin()
2014 function immediateBegin( $fname = 'Database::immediateBegin' ) {
2019 * Commit transaction, if one is open
2020 * @deprecated use commit()
2022 function immediateCommit( $fname = 'Database::immediateCommit' ) {
2027 * Creates a new table with structure copied from existing table
2028 * Note that unlike most database abstraction functions, this function does not
2029 * automatically append database prefix, because it works at a lower
2030 * abstraction level.
2032 * @param $oldName String: name of table whose structure should be copied
2033 * @param $newName String: name of table to be created
2034 * @param $temporary Boolean: whether the new table should be temporary
2035 * @return Boolean: true if operation was successful
2037 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'Database::duplicateTableStructure' ) {
2038 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2042 * Return MW-style timestamp used for MySQL schema
2044 function timestamp( $ts=0 ) {
2045 return wfTimestamp(TS_MW
,$ts);
2049 * Local database timestamp format or null
2051 function timestampOrNull( $ts = null ) {
2052 if( is_null( $ts ) ) {
2055 return $this->timestamp( $ts );
2062 function resultObject( $result ) {
2063 if( empty( $result ) ) {
2065 } elseif ( $result instanceof ResultWrapper
) {
2067 } elseif ( $result === true ) {
2068 // Successful write query
2071 return new ResultWrapper( $this, $result );
2076 * Return aggregated value alias
2078 function aggregateValue ($valuedata,$valuename='value') {
2083 * Returns a wikitext link to the DB's website, e.g.,
2084 * return "[http://www.mysql.com/ MySQL]";
2085 * Should at least contain plain text, if for some reason
2086 * your database has no website.
2088 * @return String: wikitext of a link to the server software's web site
2090 abstract function getSoftwareLink();
2093 * A string describing the current software version, like from
2094 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2096 * @return String: Version information from the database
2098 abstract function getServerVersion();
2101 * Ping the server and try to reconnect if it there is no connection
2103 * @return bool Success or failure
2106 # Stub. Not essential to override.
2112 * At the moment, this will only work if the DB user has the PROCESS privilege
2115 if ( !is_null( $this->mFakeSlaveLag
) ) {
2116 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2117 return $this->mFakeSlaveLag
;
2119 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
2120 # Find slave SQL thread
2121 while ( $row = $this->fetchObject( $res ) ) {
2122 /* This should work for most situations - when default db
2123 * for thread is not specified, it had no events executed,
2124 * and therefore it doesn't know yet how lagged it is.
2126 * Relay log I/O thread does not select databases.
2128 if ( $row->User
== 'system user' &&
2129 $row->State
!= 'Waiting for master to send event' &&
2130 $row->State
!= 'Connecting to master' &&
2131 $row->State
!= 'Queueing master event to the relay log' &&
2132 $row->State
!= 'Waiting for master update' &&
2133 $row->State
!= 'Requesting binlog dump' &&
2134 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
2135 $row->State
!= 'Reconnecting after a failed master event read' &&
2136 $row->State
!= 'Registering slave on master'
2138 # This is it, return the time (except -ve)
2139 if ( $row->Time
> 0x7fffffff ) {
2150 * Get status information from SHOW STATUS in an associative array
2152 function getStatus($which="%") {
2153 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2155 while ( $row = $this->fetchObject( $res ) ) {
2156 $status[$row->Variable_name
] = $row->Value
;
2162 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2164 function maxListLen() {
2168 function encodeBlob($b) {
2172 function decodeBlob($b) {
2177 * Override database's default connection timeout. May be useful for very
2178 * long batch queries such as full-wiki dumps, where a single query reads
2179 * out over hours or days. May or may not be necessary for non-MySQL
2180 * databases. For most purposes, leaving it as a no-op should be fine.
2182 * @param $timeout Integer in seconds
2184 public function setTimeout( $timeout ) {}
2187 * Read and execute SQL commands from a file.
2188 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2189 * @param $filename String: File name to open
2190 * @param $lineCallback Callback: Optional function called before reading each line
2191 * @param $resultCallback Callback: Optional function called for each MySQL result
2193 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2194 $fp = fopen( $filename, 'r' );
2195 if ( false === $fp ) {
2196 if (!defined("MEDIAWIKI_INSTALL"))
2197 throw new MWException( "Could not open \"{$filename}\".\n" );
2199 return "Could not open \"{$filename}\".\n";
2202 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2204 catch( MWException
$e ) {
2205 if ( defined("MEDIAWIKI_INSTALL") ) {
2206 $error = $e->getMessage();
2218 * Get the full path of a patch file. Originally based on archive()
2219 * from updaters.inc. Keep in mind this always returns a patch, as
2220 * it fails back to MySQL if no DB-specific patch can be found
2222 * @param $patch String The name of the patch, like patch-something.sql
2223 * @return String Full path to patch file
2225 public static function patchPath( $patch ) {
2226 global $wgDBtype, $IP;
2227 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2228 return "$IP/maintenance/$wgDBtype/archives/$patch";
2230 return "$IP/maintenance/archives/$patch";
2235 * Read and execute commands from an open file handle
2236 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2237 * @param $fp String: File handle
2238 * @param $lineCallback Callback: Optional function called before reading each line
2239 * @param $resultCallback Callback: Optional function called for each MySQL result
2241 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2244 $dollarquote = false;
2246 while ( ! feof( $fp ) ) {
2247 if ( $lineCallback ) {
2248 call_user_func( $lineCallback );
2250 $line = trim( fgets( $fp, 1024 ) );
2251 $sl = strlen( $line ) - 1;
2253 if ( $sl < 0 ) { continue; }
2254 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2256 ## Allow dollar quoting for function declarations
2257 if (substr($line,0,4) == '$mw$') {
2259 $dollarquote = false;
2263 $dollarquote = true;
2266 else if (!$dollarquote) {
2267 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2269 $line = substr( $line, 0, $sl );
2273 if ( $cmd != '' ) { $cmd .= ' '; }
2277 $cmd = str_replace(';;', ";", $cmd);
2278 $cmd = $this->replaceVars( $cmd );
2279 $res = $this->query( $cmd, __METHOD__
);
2280 if ( $resultCallback ) {
2281 call_user_func( $resultCallback, $res, $this );
2284 if ( false === $res ) {
2285 $err = $this->lastError();
2286 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2298 * Replace variables in sourced SQL
2300 protected function replaceVars( $ins ) {
2302 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2303 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2304 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2307 // Ordinary variables
2308 foreach ( $varnames as $var ) {
2309 if( isset( $GLOBALS[$var] ) ) {
2310 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2311 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2312 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2313 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2318 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2319 array( $this, 'tableNameCallback' ), $ins );
2322 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2323 array( $this, 'indexNameCallback' ), $ins );
2328 * Table name callback
2331 protected function tableNameCallback( $matches ) {
2332 return $this->tableName( $matches[1] );
2336 * Index name callback
2338 protected function indexNameCallback( $matches ) {
2339 return $this->indexName( $matches[1] );
2343 * Build a concatenation list to feed into a SQL query
2344 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2347 function buildConcat( $stringList ) {
2348 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2352 * Acquire a named lock
2354 * Abstracted from Filestore::lock() so child classes can implement for
2357 * @param $lockName String: Name of lock to aquire
2358 * @param $method String: Name of method calling us
2361 public function lock( $lockName, $method, $timeout = 5 ) {
2368 * @param $lockName String: Name of lock to release
2369 * @param $method String: Name of method calling us
2371 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2372 * @return Returns 1 if the lock was released, 0 if the lock was not established
2373 * by this thread (in which case the lock is not released), and NULL if the named
2374 * lock did not exist
2376 public function unlock( $lockName, $method ) {
2381 * Lock specific tables
2383 * @param $read Array of tables to lock for read access
2384 * @param $write Array of tables to lock for write access
2385 * @param $method String name of caller
2386 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2388 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2393 * Unlock specific tables
2395 * @param $method String the caller
2397 public function unlockTables( $method ) {
2402 * Get search engine class. All subclasses of this
2403 * need to implement this if they wish to use searching.
2407 public function getSearchEngine() {
2408 return "SearchMySQL";
2412 * Allow or deny "big selects" for this session only. This is done by setting
2413 * the sql_big_selects session variable.
2415 * This is a MySQL-specific feature.
2417 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2419 public function setBigSelects( $value = true ) {
2425 /******************************************************************************
2427 *****************************************************************************/
2436 function DBObject($data) {
2437 $this->mData
= $data;
2445 return $this->mData
;
2453 * This allows us to distinguish a blob from a normal string and an array of strings
2457 function __construct($data) {
2458 $this->mData
= $data;
2461 return $this->mData
;
2470 private $name, $tablename, $default, $max_length, $nullable,
2471 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2472 function __construct ($info) {
2473 $this->name
= $info->name
;
2474 $this->tablename
= $info->table
;
2475 $this->default = $info->def
;
2476 $this->max_length
= $info->max_length
;
2477 $this->nullable
= !$info->not_null
;
2478 $this->is_pk
= $info->primary_key
;
2479 $this->is_unique
= $info->unique_key
;
2480 $this->is_multiple
= $info->multiple_key
;
2481 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2482 $this->type
= $info->type
;
2489 function tableName() {
2490 return $this->tableName
;
2493 function defaultValue() {
2494 return $this->default;
2497 function maxLength() {
2498 return $this->max_length
;
2501 function nullable() {
2502 return $this->nullable
;
2506 return $this->is_key
;
2509 function isMultipleKey() {
2510 return $this->is_multiple
;
2518 /******************************************************************************
2520 *****************************************************************************/
2523 * Database error base class
2526 class DBError
extends MWException
{
2530 * Construct a database error
2531 * @param $db Database object which threw the error
2532 * @param $error A simple error message to be used for debugging
2534 function __construct( DatabaseBase
&$db, $error ) {
2536 parent
::__construct( $error );
2539 function getText() {
2540 global $wgShowDBErrorBacktrace;
2541 $s = $this->getMessage() . "\n";
2542 if ( $wgShowDBErrorBacktrace ) {
2543 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2552 class DBConnectionError
extends DBError
{
2555 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2556 $msg = 'DB connection error';
2557 if ( trim( $error ) != '' ) {
2560 $this->error
= $error;
2561 parent
::__construct( $db, $msg );
2564 function useOutputPage() {
2565 // Not likely to work
2569 function useMessageCache() {
2570 // Not likely to work
2574 function getLogMessage() {
2575 # Don't send to the exception log
2579 function getPageTitle() {
2580 global $wgSitename, $wgLang;
2581 $header = "$wgSitename has a problem";
2582 if ( $wgLang instanceof Language
) {
2583 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2589 function getHTML() {
2590 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2592 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2593 $again = 'Try waiting a few minutes and reloading.';
2594 $info = '(Can\'t contact the database server: $1)';
2596 if ( $wgLang instanceof Language
) {
2597 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2598 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2599 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2602 # No database access
2603 if ( is_object( $wgMessageCache ) ) {
2604 $wgMessageCache->disable();
2607 if ( trim( $this->error
) == '' ) {
2608 $this->error
= $this->db
->getProperty('mServer');
2611 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2612 $text = str_replace( '$1', $this->error
, $noconnect );
2614 if ( $wgShowDBErrorBacktrace ) {
2615 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2618 $extra = $this->searchForm();
2620 if( $wgUseFileCache ) {
2622 $cache = $this->fileCachedPage();
2623 # Cached version on file system?
2624 if( $cache !== null ) {
2625 # Hack: extend the body for error messages
2626 $cache = str_replace( array('</html>','</body>'), '', $cache );
2627 # Add cache notice...
2628 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2629 # Localize it if possible...
2630 if( $wgLang instanceof Language
) {
2631 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2633 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2634 # Output cached page with notices on bottom and re-close body
2635 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2637 } catch( MWException
$e ) {
2638 // Do nothing, just use the default page
2641 # Headers needed here - output is just the error message
2642 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2645 function searchForm() {
2646 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2647 $usegoogle = "You can try searching via Google in the meantime.";
2648 $outofdate = "Note that their indexes of our content may be out of date.";
2649 $googlesearch = "Search";
2651 if ( $wgLang instanceof Language
) {
2652 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2653 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2654 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2657 $search = htmlspecialchars(@$_REQUEST['search']);
2660 <div style="margin: 1.5em">$usegoogle<br />
2661 <small>$outofdate</small></div>
2662 <!-- SiteSearch Google -->
2663 <form method="get" action="http://www.google.com/search" id="googlesearch">
2664 <input type="hidden" name="domains" value="$wgServer" />
2665 <input type="hidden" name="num" value="50" />
2666 <input type="hidden" name="ie" value="$wgInputEncoding" />
2667 <input type="hidden" name="oe" value="$wgInputEncoding" />
2669 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2670 <input type="submit" name="btnG" value="$googlesearch" />
2672 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2673 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2676 <!-- SiteSearch Google -->
2681 function fileCachedPage() {
2682 global $wgTitle, $title, $wgLang, $wgOut;
2683 if( $wgOut->isDisabled() ) return; // Done already?
2684 $mainpage = 'Main Page';
2685 if ( $wgLang instanceof Language
) {
2686 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2691 } elseif( $title ) {
2692 $t = Title
::newFromURL( $title );
2694 $t = Title
::newFromText( $mainpage );
2697 $cache = new HTMLFileCache( $t );
2698 if( $cache->isFileCached() ) {
2699 return $cache->fetchPageText();
2705 function htmlBodyOnly() {
2714 class DBQueryError
extends DBError
{
2715 public $error, $errno, $sql, $fname;
2717 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2718 $message = "A database error has occurred\n" .
2720 "Function: $fname\n" .
2721 "Error: $errno $error\n";
2723 parent
::__construct( $db, $message );
2724 $this->error
= $error;
2725 $this->errno
= $errno;
2727 $this->fname
= $fname;
2730 function getText() {
2731 global $wgShowDBErrorBacktrace;
2732 if ( $this->useMessageCache() ) {
2733 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2734 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2735 if ( $wgShowDBErrorBacktrace ) {
2736 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2740 return parent
::getText();
2745 global $wgShowSQLErrors;
2746 if( !$wgShowSQLErrors ) {
2747 return $this->msg( 'sqlhidden', 'SQL hidden' );
2753 function getLogMessage() {
2754 # Don't send to the exception log
2758 function getPageTitle() {
2759 return $this->msg( 'databaseerror', 'Database error' );
2762 function getHTML() {
2763 global $wgShowDBErrorBacktrace;
2764 if ( $this->useMessageCache() ) {
2765 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2766 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2768 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2770 if ( $wgShowDBErrorBacktrace ) {
2771 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2780 class DBUnexpectedError
extends DBError
{}
2784 * Result wrapper for grabbing data queried by someone else
2787 class ResultWrapper
implements Iterator
{
2788 var $db, $result, $pos = 0, $currentRow = null;
2791 * Create a new result object from a result resource and a Database object
2793 function ResultWrapper( $database, $result ) {
2794 $this->db
= $database;
2795 if ( $result instanceof ResultWrapper
) {
2796 $this->result
= $result->result
;
2798 $this->result
= $result;
2803 * Get the number of rows in a result object
2805 function numRows() {
2806 return $this->db
->numRows( $this );
2810 * Fetch the next row from the given result object, in object form.
2811 * Fields can be retrieved with $row->fieldname, with fields acting like
2814 * @param $res SQL result object as returned from Database::query(), etc.
2815 * @return MySQL row object
2816 * @throws DBUnexpectedError Thrown if the database returns an error
2818 function fetchObject() {
2819 return $this->db
->fetchObject( $this );
2823 * Fetch the next row from the given result object, in associative array
2824 * form. Fields are retrieved with $row['fieldname'].
2826 * @param $res SQL result object as returned from Database::query(), etc.
2827 * @return MySQL row object
2828 * @throws DBUnexpectedError Thrown if the database returns an error
2830 function fetchRow() {
2831 return $this->db
->fetchRow( $this );
2835 * Free a result object
2838 $this->db
->freeResult( $this );
2839 unset( $this->result
);
2844 * Change the position of the cursor in a result object
2845 * See mysql_data_seek()
2847 function seek( $row ) {
2848 $this->db
->dataSeek( $this, $row );
2851 /*********************
2852 * Iterator functions
2853 * Note that using these in combination with the non-iterator functions
2854 * above may cause rows to be skipped or repeated.
2858 if ($this->numRows()) {
2859 $this->db
->dataSeek($this, 0);
2862 $this->currentRow
= null;
2865 function current() {
2866 if ( is_null( $this->currentRow
) ) {
2869 return $this->currentRow
;
2878 $this->currentRow
= $this->fetchObject();
2879 return $this->currentRow
;
2883 return $this->current() !== false;
2888 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2889 * and thus need no escaping. Don't instantiate it manually, use Database::anyChar() and anyString() instead.
2894 public function __construct( $s ) {
2898 public function toString() {