3 * @defgroup Database Database
7 * This file deals with database interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Database abstraction object
22 abstract class DatabaseBase
{
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mDoneWrites = false;
30 protected $mPHPError = false;
32 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
33 protected $mOpened = false;
35 protected $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 * Boolean, controls output of large amounts of debug information
60 function debug( $debug = null ) {
61 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
65 * Turns buffering of SQL result sets on (true) or off (false).
66 * Default is "on" and it should not be changed without good reasons.
68 function bufferResults( $buffer = null ) {
69 if ( is_null( $buffer ) ) {
70 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
72 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
77 * Turns on (false) or off (true) the automatic generation and sending
78 * of a "we're sorry, but there has been a database error" page on
79 * database errors. Default is on (false). When turned off, the
80 * code should use lastErrno() and lastError() to handle the
81 * situation as appropriate.
83 function ignoreErrors( $ignoreErrors = null ) {
84 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
88 * The current depth of nested transactions
89 * @param $level Integer: , default NULL.
91 function trxLevel( $level = null ) {
92 return wfSetVar( $this->mTrxLevel
, $level );
96 * Number of errors logged, only useful when errors are ignored
98 function errorCount( $count = null ) {
99 return wfSetVar( $this->mErrorCount
, $count );
102 function tablePrefix( $prefix = null ) {
103 return wfSetVar( $this->mTablePrefix
, $prefix );
107 * Properties passed down from the server info array of the load balancer
109 function getLBInfo( $name = null ) {
110 if ( is_null( $name ) ) {
111 return $this->mLBInfo
;
113 if ( array_key_exists( $name, $this->mLBInfo
) ) {
114 return $this->mLBInfo
[$name];
121 function setLBInfo( $name, $value = null ) {
122 if ( is_null( $value ) ) {
123 $this->mLBInfo
= $name;
125 $this->mLBInfo
[$name] = $value;
130 * Set lag time in seconds for a fake slave
132 function setFakeSlaveLag( $lag ) {
133 $this->mFakeSlaveLag
= $lag;
137 * Make this connection a fake master
139 function setFakeMaster( $enabled = true ) {
140 $this->mFakeMaster
= $enabled;
144 * Returns true if this database supports (and uses) cascading deletes
146 function cascadingDeletes() {
151 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
153 function cleanupTriggers() {
158 * Returns true if this database is strict about what can be put into an IP field.
159 * Specifically, it uses a NULL value instead of an empty string.
161 function strictIPs() {
166 * Returns true if this database uses timestamps rather than integers
168 function realTimestamps() {
173 * Returns true if this database does an implicit sort when doing GROUP BY
175 function implicitGroupby() {
180 * Returns true if this database does an implicit order by when the column has an index
181 * For example: SELECT page_title FROM page LIMIT 1
183 function implicitOrderby() {
188 * Returns true if this database requires that SELECT DISTINCT queries require that all
189 ORDER BY expressions occur in the SELECT list per the SQL92 standard
191 function standardSelectDistinct() {
196 * Returns true if this database can do a native search on IP columns
197 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
199 function searchableIPs() {
204 * Returns true if this database can use functional indexes
206 function functionalIndexes() {
211 * Return the last query that went through DatabaseBase::query()
214 function lastQuery() { return $this->mLastQuery
; }
218 * Returns true if the connection may have been used for write queries.
219 * Should return true if unsure.
221 function doneWrites() { return $this->mDoneWrites
; }
224 * Is a connection to the database open?
227 function isOpen() { return $this->mOpened
; }
230 * Set a flag for this connection
232 * @param $flag Integer: DBO_* constants from Defines.php:
233 * - DBO_DEBUG: output some debug info (same as debug())
234 * - DBO_NOBUFFER: don't buffer results (inverse of bufferResults())
235 * - DBO_IGNORE: ignore errors (same as ignoreErrors())
236 * - DBO_TRX: automatically start transactions
237 * - DBO_DEFAULT: automatically sets DBO_TRX if not in command line mode
238 * and removes it in command line mode
239 * - DBO_PERSISTENT: use persistant database connection
241 function setFlag( $flag ) {
242 $this->mFlags |
= $flag;
246 * Clear a flag for this connection
248 * @param $flag: same as setFlag()'s $flag param
250 function clearFlag( $flag ) {
251 $this->mFlags
&= ~
$flag;
255 * Returns a boolean whether the flag $flag is set for this connection
257 * @param $flag: same as setFlag()'s $flag param
260 function getFlag( $flag ) {
261 return !!($this->mFlags
& $flag);
265 * General read-only accessor
267 function getProperty( $name ) {
271 function getWikiID() {
272 if( $this->mTablePrefix
) {
273 return "{$this->mDBname}-{$this->mTablePrefix}";
275 return $this->mDBname
;
280 * Get the type of the DBMS, as it appears in $wgDBtype.
282 abstract function getType();
284 #------------------------------------------------------------------------------
286 #------------------------------------------------------------------------------
290 * @param $server String: database server host
291 * @param $user String: database user name
292 * @param $password String: database user password
293 * @param $dbName String: database name
294 * @param $failFunction
296 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
298 function __construct( $server = false, $user = false, $password = false, $dbName = false,
299 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
301 global $wgOut, $wgDBprefix, $wgCommandLineMode;
302 # Can't get a reference if it hasn't been set yet
303 if ( !isset( $wgOut ) ) {
307 $this->mFailFunction
= $failFunction;
308 $this->mFlags
= $flags;
310 if ( $this->mFlags
& DBO_DEFAULT
) {
311 if ( $wgCommandLineMode ) {
312 $this->mFlags
&= ~DBO_TRX
;
314 $this->mFlags |
= DBO_TRX
;
319 // Faster read-only access
320 if ( wfReadOnly() ) {
321 $this->mFlags |= DBO_PERSISTENT;
322 $this->mFlags &= ~DBO_TRX;
325 /** Get the default table prefix*/
326 if ( $tablePrefix == 'get from global' ) {
327 $this->mTablePrefix
= $wgDBprefix;
329 $this->mTablePrefix
= $tablePrefix;
333 $this->open( $server, $user, $password, $dbName );
338 * Same as new DatabaseMysql( ... ), kept for backward compatibility
339 * @param $server String: database server host
340 * @param $user String: database user name
341 * @param $password String: database user password
342 * @param $dbName String: database name
343 * @param failFunction
346 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
348 wfDeprecated( __METHOD__
);
349 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
353 * Usually aborts on failure
354 * If the failFunction is set to a non-zero integer, returns success
355 * @param $server String: database server host
356 * @param $user String: database user name
357 * @param $password String: database user password
358 * @param $dbName String: database name
360 abstract function open( $server, $user, $password, $dbName );
362 protected function installErrorHandler() {
363 $this->mPHPError
= false;
364 $this->htmlErrors
= ini_set( 'html_errors', '0' );
365 set_error_handler( array( $this, 'connectionErrorHandler' ) );
368 protected function restoreErrorHandler() {
369 restore_error_handler();
370 if ( $this->htmlErrors
!== false ) {
371 ini_set( 'html_errors', $this->htmlErrors
);
373 if ( $this->mPHPError
) {
374 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
375 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
382 protected function connectionErrorHandler( $errno, $errstr ) {
383 $this->mPHPError
= $errstr;
387 * Closes a database connection.
388 * if it is open : commits any open transactions
390 * @return Bool operation success. true if already closed.
393 # Stub, should probably be overridden
398 * @param $error String: fallback error message, used if none is given by DB
400 function reportConnectionError( $error = 'Unknown error' ) {
401 $myError = $this->lastError();
406 if ( $this->mFailFunction
) {
407 # Legacy error handling method
408 if ( !is_int( $this->mFailFunction
) ) {
409 $ff = $this->mFailFunction
;
410 $ff( $this, $error );
414 throw new DBConnectionError( $this, $error );
419 * Determine whether a query writes to the DB.
420 * Should return true if unsure.
422 function isWriteQuery( $sql ) {
423 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW|\(SELECT)\b/i', $sql );
427 * Usually aborts on failure. If errors are explicitly ignored, returns success.
429 * @param $sql String: SQL query
430 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
431 * comment (you can use __METHOD__ or add some extra info)
432 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
433 * maybe best to catch the exception instead?
434 * @return true for a successful write query, ResultWrapper object for a successful read query,
435 * or false on failure if $tempIgnore set
436 * @throws DBQueryError Thrown when the database returns an error of any kind
438 public function query( $sql, $fname = '', $tempIgnore = false ) {
441 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
442 if ( isset( $wgProfiler ) ) {
443 # generalizeSQL will probably cut down the query to reasonable
444 # logging size most of the time. The substr is really just a sanity check.
446 # Who's been wasting my precious column space? -- TS
447 #$profName = 'query: ' . $fname . ' ' . substr( DatabaseBase::generalizeSQL( $sql ), 0, 255 );
450 $queryProf = 'query-m: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
451 $totalProf = 'DatabaseBase::query-master';
453 $queryProf = 'query: ' . substr( DatabaseBase
::generalizeSQL( $sql ), 0, 255 );
454 $totalProf = 'DatabaseBase::query';
456 wfProfileIn( $totalProf );
457 wfProfileIn( $queryProf );
460 $this->mLastQuery
= $sql;
461 if ( !$this->mDoneWrites
&& $this->isWriteQuery( $sql ) ) {
462 // Set a flag indicating that writes have been done
463 wfDebug( __METHOD__
.": Writes done: $sql\n" );
464 $this->mDoneWrites
= true;
467 # Add a comment for easy SHOW PROCESSLIST interpretation
470 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
471 $userName = $wgUser->getName();
472 if ( mb_strlen( $userName ) > 15 ) {
473 $userName = mb_substr( $userName, 0, 15 ) . '...';
475 $userName = str_replace( '/', '', $userName );
479 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
481 # $commentedSql = $sql;
484 # If DBO_TRX is set, start a transaction
485 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
486 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
487 // avoid establishing transactions for SHOW and SET statements too -
488 // that would delay transaction initializations to once connection
489 // is really used by application
490 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
491 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
495 if ( $this->debug() ) {
498 $sqlx = substr( $commentedSql, 0, 500 );
499 $sqlx = strtr( $sqlx, "\t\n", ' ' );
501 wfDebug( "Query $cnt (master): $sqlx\n" );
503 wfDebug( "Query $cnt (slave): $sqlx\n" );
507 if ( istainted( $sql ) & TC_MYSQL
) {
508 throw new MWException( 'Tainted query found' );
511 # Do the query and handle errors
512 $ret = $this->doQuery( $commentedSql );
514 # Try reconnecting if the connection was lost
515 if ( false === $ret && $this->wasErrorReissuable() ) {
516 # Transaction is gone, like it or not
517 $this->mTrxLevel
= 0;
518 wfDebug( "Connection lost, reconnecting...\n" );
519 if ( $this->ping() ) {
520 wfDebug( "Reconnected\n" );
521 $sqlx = substr( $commentedSql, 0, 500 );
522 $sqlx = strtr( $sqlx, "\t\n", ' ' );
523 global $wgRequestTime;
524 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
525 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
526 $ret = $this->doQuery( $commentedSql );
528 wfDebug( "Failed\n" );
532 if ( false === $ret ) {
533 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
536 if ( isset( $wgProfiler ) ) {
537 wfProfileOut( $queryProf );
538 wfProfileOut( $totalProf );
540 return $this->resultObject( $ret );
544 * The DBMS-dependent part of query()
545 * @param $sql String: SQL query.
546 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
549 /*private*/ abstract function doQuery( $sql );
552 * @param $error String
553 * @param $errno Integer
555 * @param $fname String
556 * @param $tempIgnore Boolean
558 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
559 # Ignore errors during error handling to avoid infinite recursion
560 $ignore = $this->ignoreErrors( true );
561 ++
$this->mErrorCount
;
563 if( $ignore ||
$tempIgnore ) {
564 wfDebug("SQL ERROR (ignored): $error\n");
565 $this->ignoreErrors( $ignore );
567 $sql1line = str_replace( "\n", "\\n", $sql );
568 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
569 wfDebug("SQL ERROR: " . $error . "\n");
570 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
576 * Intended to be compatible with the PEAR::DB wrapper functions.
577 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
579 * ? = scalar value, quoted as necessary
580 * ! = raw SQL bit (a function for instance)
581 * & = filename; reads the file and inserts as a blob
582 * (we don't use this though...)
584 function prepare( $sql, $func = 'DatabaseBase::prepare' ) {
585 /* MySQL doesn't support prepared statements (yet), so just
586 pack up the query for reference. We'll manually replace
588 return array( 'query' => $sql, 'func' => $func );
591 function freePrepared( $prepared ) {
592 /* No-op by default */
596 * Execute a prepared query with the various arguments
597 * @param $prepared String: the prepared sql
598 * @param $args Mixed: Either an array here, or put scalars as varargs
600 function execute( $prepared, $args = null ) {
601 if( !is_array( $args ) ) {
603 $args = func_get_args();
604 array_shift( $args );
606 $sql = $this->fillPrepared( $prepared['query'], $args );
607 return $this->query( $sql, $prepared['func'] );
611 * Prepare & execute an SQL statement, quoting and inserting arguments
612 * in the appropriate places.
613 * @param $query String
616 function safeQuery( $query, $args = null ) {
617 $prepared = $this->prepare( $query, 'DatabaseBase::safeQuery' );
618 if( !is_array( $args ) ) {
620 $args = func_get_args();
621 array_shift( $args );
623 $retval = $this->execute( $prepared, $args );
624 $this->freePrepared( $prepared );
629 * For faking prepared SQL statements on DBs that don't support
631 * @param $preparedQuery String: a 'preparable' SQL statement
632 * @param $args Array of arguments to fill it with
633 * @return string executable SQL
635 function fillPrepared( $preparedQuery, $args ) {
637 $this->preparedArgs
=& $args;
638 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
639 array( &$this, 'fillPreparedArg' ), $preparedQuery );
643 * preg_callback func for fillPrepared()
644 * The arguments should be in $this->preparedArgs and must not be touched
645 * while we're doing this.
647 * @param $matches Array
651 function fillPreparedArg( $matches ) {
652 switch( $matches[1] ) {
653 case '\\?': return '?';
654 case '\\!': return '!';
655 case '\\&': return '&';
657 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
658 switch( $matches[1] ) {
659 case '?': return $this->addQuotes( $arg );
660 case '!': return $arg;
662 # return $this->addQuotes( file_get_contents( $arg ) );
663 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
665 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
670 * Free a result object
671 * @param $res Mixed: A SQL result
673 function freeResult( $res ) {
674 # Stub. Might not really need to be overridden, since results should
675 # be freed by PHP when the variable goes out of scope anyway.
679 * Fetch the next row from the given result object, in object form.
680 * Fields can be retrieved with $row->fieldname, with fields acting like
683 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
685 * @throws DBUnexpectedError Thrown if the database returns an error
687 abstract function fetchObject( $res );
690 * Fetch the next row from the given result object, in associative array
691 * form. Fields are retrieved with $row['fieldname'].
693 * @param $res SQL result object as returned from DatabaseBase::query(), etc.
695 * @throws DBUnexpectedError Thrown if the database returns an error
697 abstract function fetchRow( $res );
700 * Get the number of rows in a result object
701 * @param $res Mixed: A SQL result
703 abstract function numRows( $res );
706 * Get the number of fields in a result object
707 * See documentation for mysql_num_fields()
708 * @param $res Mixed: A SQL result
710 abstract function numFields( $res );
713 * Get a field name in a result object
714 * See documentation for mysql_field_name():
715 * http://www.php.net/mysql_field_name
716 * @param $res Mixed: A SQL result
719 abstract function fieldName( $res, $n );
722 * Get the inserted value of an auto-increment row
724 * The value inserted should be fetched from nextSequenceValue()
727 * $id = $dbw->nextSequenceValue('page_page_id_seq');
728 * $dbw->insert('page',array('page_id' => $id));
729 * $id = $dbw->insertId();
731 abstract function insertId();
734 * Change the position of the cursor in a result object
735 * See mysql_data_seek()
736 * @param $res Mixed: A SQL result
737 * @param $row Mixed: Either MySQL row or ResultWrapper
739 abstract function dataSeek( $res, $row );
742 * Get the last error number
745 abstract function lastErrno();
748 * Get a description of the last error
749 * See mysql_error() for more details
751 abstract function lastError();
754 * Get the number of rows affected by the last write query
755 * See mysql_affected_rows() for more details
757 abstract function affectedRows();
760 * Simple UPDATE wrapper
761 * Usually aborts on failure
762 * If errors are explicitly ignored, returns success
764 * This function exists for historical reasons, DatabaseBase::update() has a more standard
765 * calling convention and feature set
767 function set( $table, $var, $value, $cond, $fname = 'DatabaseBase::set' ) {
768 $table = $this->tableName( $table );
769 $sql = "UPDATE $table SET $var = '" .
770 $this->strencode( $value ) . "' WHERE ($cond)";
771 return (bool)$this->query( $sql, $fname );
775 * Simple SELECT wrapper, returns a single field, input must be encoded
776 * Usually aborts on failure
777 * If errors are explicitly ignored, returns FALSE on failure
779 function selectField( $table, $var, $cond='', $fname = 'DatabaseBase::selectField', $options = array() ) {
780 if ( !is_array( $options ) ) {
781 $options = array( $options );
783 $options['LIMIT'] = 1;
785 $res = $this->select( $table, $var, $cond, $fname, $options );
786 if ( $res === false ||
!$this->numRows( $res ) ) {
789 $row = $this->fetchRow( $res );
790 if ( $row !== false ) {
791 return reset( $row );
798 * Returns an optional USE INDEX clause to go after the table, and a
799 * string to go at the end of the query
803 * @param $options Array: associative array of options to be turned into
804 * an SQL query, valid keys are listed in the function.
807 function makeSelectOptions( $options ) {
808 $preLimitTail = $postLimitTail = '';
811 $noKeyOptions = array();
812 foreach ( $options as $key => $option ) {
813 if ( is_numeric( $key ) ) {
814 $noKeyOptions[$option] = true;
818 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
819 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
820 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
822 //if (isset($options['LIMIT'])) {
823 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
824 // isset($options['OFFSET']) ? $options['OFFSET']
828 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
829 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
830 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
832 # Various MySQL extensions
833 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
834 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
835 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
836 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
837 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
838 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
839 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
840 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
842 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
843 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
848 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
854 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
855 * @param $vars Mixed: Array or string, field name(s) to be retrieved
856 * @param $conds Mixed: Array or string, condition(s) for WHERE
857 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
858 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
859 * see DatabaseBase::makeSelectOptions code for list of supported stuff
860 * @param $join_conds Array: Associative array of table join conditions (optional)
861 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
862 * @return mixed Database result resource (feed to DatabaseBase::fetchObject or whatever), or false on failure
864 function select( $table, $vars, $conds='', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
865 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
866 return $this->query( $sql, $fname );
872 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
873 * @param $vars Mixed: Array or string, field name(s) to be retrieved
874 * @param $conds Mixed: Array or string, condition(s) for WHERE
875 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
876 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
877 * see DatabaseBase::makeSelectOptions code for list of supported stuff
878 * @param $join_conds Array: Associative array of table join conditions (optional)
879 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
880 * @return string, the SQL text
882 function selectSQLText( $table, $vars, $conds='', $fname = 'DatabaseBase::select', $options = array(), $join_conds = array() ) {
883 if( is_array( $vars ) ) {
884 $vars = implode( ',', $vars );
886 if( !is_array( $options ) ) {
887 $options = array( $options );
889 if( is_array( $table ) ) {
890 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
891 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
893 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
894 } elseif ($table!='') {
895 if ($table{0}==' ') {
896 $from = ' FROM ' . $table;
898 $from = ' FROM ' . $this->tableName( $table );
904 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
906 if( !empty( $conds ) ) {
907 if ( is_array( $conds ) ) {
908 $conds = $this->makeList( $conds, LIST_AND
);
910 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
912 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
915 if (isset($options['LIMIT']))
916 $sql = $this->limitResult($sql, $options['LIMIT'],
917 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
918 $sql = "$sql $postLimitTail";
920 if (isset($options['EXPLAIN'])) {
921 $sql = 'EXPLAIN ' . $sql;
927 * Single row SELECT wrapper
928 * Aborts or returns FALSE on error
930 * @param $table String: table name
931 * @param $vars String: the selected variables
932 * @param $conds Array: a condition map, terms are ANDed together.
933 * Items with numeric keys are taken to be literal conditions
934 * Takes an array of selected variables, and a condition map, which is ANDed
935 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
936 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
937 * $obj- >page_id is the ID of the Astronomy article
938 * @param $fname String: Calling function name
939 * @param $options Array
940 * @param $join_conds Array
942 * @todo migrate documentation to phpdocumentor format
944 function selectRow( $table, $vars, $conds, $fname = 'DatabaseBase::selectRow', $options = array(), $join_conds = array() ) {
945 $options['LIMIT'] = 1;
946 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
947 if ( $res === false )
949 if ( !$this->numRows($res) ) {
952 $obj = $this->fetchObject( $res );
957 * Estimate rows in dataset
958 * Returns estimated count - not necessarily an accurate estimate across different databases,
960 * Takes same arguments as DatabaseBase::select()
962 * @param $table String: table name
963 * @param $vars Array: unused
964 * @param $conds Array: filters on the table
965 * @param $fname String: function name for profiling
966 * @param $options Array: options for select
967 * @return Integer: row count
969 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseBase::estimateRowCount', $options = array() ) {
971 $res = $this->select ( $table, 'COUNT(*) AS rowcount', $conds, $fname, $options );
973 $row = $this->fetchRow( $res );
974 $rows = ( isset( $row['rowcount'] ) ) ?
$row['rowcount'] : 0;
980 * Removes most variables from an SQL query and replaces them with X or N for numbers.
981 * It's only slightly flawed. Don't use for anything important.
983 * @param $sql String: A SQL Query
985 static function generalizeSQL( $sql ) {
986 # This does the same as the regexp below would do, but in such a way
987 # as to avoid crashing php on some large strings.
988 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
990 $sql = str_replace ( "\\\\", '', $sql);
991 $sql = str_replace ( "\\'", '', $sql);
992 $sql = str_replace ( "\\\"", '', $sql);
993 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
994 $sql = preg_replace ('/".*"/s', "'X'", $sql);
996 # All newlines, tabs, etc replaced by single space
997 $sql = preg_replace ( '/\s+/', ' ', $sql);
1000 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1006 * Determines whether a field exists in a table
1008 * @param $table String: table name
1009 * @param $field String: filed to check on that table
1010 * @param $fname String: calling function name (optional)
1011 * @return Boolean: whether $table has filed $field
1013 function fieldExists( $table, $field, $fname = 'DatabaseBase::fieldExists' ) {
1014 $info = $this->fieldInfo( $table, $field );
1019 * Determines whether an index exists
1020 * Usually aborts on failure
1021 * If errors are explicitly ignored, returns NULL on failure
1023 function indexExists( $table, $index, $fname = 'DatabaseBase::indexExists' ) {
1024 $info = $this->indexInfo( $table, $index, $fname );
1025 if ( is_null( $info ) ) {
1028 return $info !== false;
1034 * Get information about an index into an object
1035 * Returns false if the index does not exist
1037 function indexInfo( $table, $index, $fname = 'DatabaseBase::indexInfo' ) {
1038 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1039 # SHOW INDEX should work for 3.x and up:
1040 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1041 $table = $this->tableName( $table );
1042 $index = $this->indexName( $index );
1043 $sql = 'SHOW INDEX FROM '.$table;
1044 $res = $this->query( $sql, $fname );
1050 while ( $row = $this->fetchObject( $res ) ) {
1051 if ( $row->Key_name
== $index ) {
1056 return empty($result) ?
false : $result;
1060 * Query whether a given table exists
1062 function tableExists( $table ) {
1063 $table = $this->tableName( $table );
1064 $old = $this->ignoreErrors( true );
1065 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1066 $this->ignoreErrors( $old );
1071 * mysql_fetch_field() wrapper
1072 * Returns false if the field doesn't exist
1077 abstract function fieldInfo( $table, $field );
1080 * mysql_field_type() wrapper
1082 function fieldType( $res, $index ) {
1083 if ( $res instanceof ResultWrapper
) {
1084 $res = $res->result
;
1086 return mysql_field_type( $res, $index );
1090 * Determines if a given index is unique
1092 function indexUnique( $table, $index ) {
1093 $indexInfo = $this->indexInfo( $table, $index );
1094 if ( !$indexInfo ) {
1097 return !$indexInfo[0]->Non_unique
;
1101 * INSERT wrapper, inserts an array into a table
1103 * $a may be a single associative array, or an array of these with numeric keys, for
1106 * Usually aborts on failure
1107 * If errors are explicitly ignored, returns success
1109 * @param $table String: table name (prefix auto-added)
1110 * @param $a Array: Array of rows to insert
1111 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1112 * @param $options Mixed: Associative array of options
1116 function insert( $table, $a, $fname = 'DatabaseBase::insert', $options = array() ) {
1117 # No rows to insert, easy just return now
1118 if ( !count( $a ) ) {
1122 $table = $this->tableName( $table );
1123 if ( !is_array( $options ) ) {
1124 $options = array( $options );
1126 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1128 $keys = array_keys( $a[0] );
1131 $keys = array_keys( $a );
1134 $sql = 'INSERT ' . implode( ' ', $options ) .
1135 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1139 foreach ( $a as $row ) {
1145 $sql .= '(' . $this->makeList( $row ) . ')';
1148 $sql .= '(' . $this->makeList( $a ) . ')';
1151 return (bool)$this->query( $sql, $fname );
1155 * INSERT ... ON DUPE UPDATE wrapper, inserts an array into a table, optionally updating if
1156 * duplicate primary key found
1158 * $a may be a single associative array, or an array of these with numeric keys, for
1161 * Usually aborts on failure
1162 * If errors are explicitly ignored, returns success
1164 * @param $table String: table name (prefix auto-added)
1165 * @param $a Array: Array of rows to insert
1166 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1167 * @param $options Mixed: Associative array of options (ignored)
1168 * @param $onDupeUpdate Array: Associative array of fields to update on duplicate
1172 function insertOrUpdate( $table, $a, $fname = 'DatabaseBase::insertOnDupeUpdate', $options = array(), $onDupeUpdate = array() ) {
1174 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1175 $keys = array_keys( $a[0] );
1177 $keys = array_keys( $a );
1180 //Get what is only to be set if inserted
1181 $where = array_diff( $a, $onDupeUpdate );
1183 $res = $this->select(
1186 $this->makeList( $where, LIST_AND
),
1191 //Where there is a different value to set if this is being "updated", use the $onDupeUpdate value for that to
1192 //replace the original option (if it was an insert), and replace the column name with the value read from
1194 foreach( $where as $k => $v ){
1195 if ( isset( $onDupeUpdate[$k] ) ){
1196 $options[$k] = str_replace( $k, $res[0]->{$k}, $onDupeUpdate[$k] );
1200 //No results, it's just an insert
1204 return (bool)$this->replace(
1213 * Make UPDATE options for the DatabaseBase::update function
1216 * @param $options Array: The options passed to DatabaseBase::update
1219 function makeUpdateOptions( $options ) {
1220 if( !is_array( $options ) ) {
1221 $options = array( $options );
1224 if ( in_array( 'LOW_PRIORITY', $options ) ) {
1225 $opts[] = $this->lowPriorityOption();
1227 if ( in_array( 'IGNORE', $options ) ) {
1230 return implode(' ', $opts);
1234 * UPDATE wrapper, takes a condition array and a SET array
1236 * @param $table String: The table to UPDATE
1237 * @param $values Array: An array of values to SET
1238 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1239 * @param $fname String: The Class::Function calling this function
1241 * @param $options Array: An array of UPDATE options, can be one or
1242 * more of IGNORE, LOW_PRIORITY
1245 function update( $table, $values, $conds, $fname = 'DatabaseBase::update', $options = array() ) {
1246 $table = $this->tableName( $table );
1247 $opts = $this->makeUpdateOptions( $options );
1248 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1249 if ( $conds != '*' ) {
1250 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1252 return $this->query( $sql, $fname );
1256 * Makes an encoded list of strings from an array
1258 * LIST_COMMA - comma separated, no field names
1259 * LIST_AND - ANDed WHERE clause (without the WHERE)
1260 * LIST_OR - ORed WHERE clause (without the WHERE)
1261 * LIST_SET - comma separated with field names, like a SET clause
1262 * LIST_NAMES - comma separated field names
1264 function makeList( $a, $mode = LIST_COMMA
) {
1265 if ( !is_array( $a ) ) {
1266 throw new DBUnexpectedError( $this, 'DatabaseBase::makeList called with incorrect parameters' );
1271 foreach ( $a as $field => $value ) {
1273 if ( $mode == LIST_AND
) {
1275 } elseif($mode == LIST_OR
) {
1283 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1284 $list .= "($value)";
1285 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1287 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1288 if( count( $value ) == 0 ) {
1289 throw new MWException( __METHOD__
.': empty input' );
1290 } elseif( count( $value ) == 1 ) {
1291 // Special-case single values, as IN isn't terribly efficient
1292 // Don't necessarily assume the single key is 0; we don't
1293 // enforce linear numeric ordering on other arrays here.
1294 $value = array_values( $value );
1295 $list .= $field." = ".$this->addQuotes( $value[0] );
1297 $list .= $field." IN (".$this->makeList($value).") ";
1299 } elseif( $value === null ) {
1300 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1301 $list .= "$field IS ";
1302 } elseif ( $mode == LIST_SET
) {
1303 $list .= "$field = ";
1307 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1308 $list .= "$field = ";
1310 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1317 * Build a partial where clause from a 2-d array such as used for LinkBatch.
1318 * The keys on each level may be either integers or strings.
1320 * @param $data Array: organized as 2-d array(baseKeyVal => array(subKeyVal => <ignored>, ...), ...)
1321 * @param $baseKey String: field name to match the base-level keys to (eg 'pl_namespace')
1322 * @param $subKey String: field name to match the sub-level keys to (eg 'pl_title')
1323 * @return Mixed: string SQL fragment, or false if no items in array.
1325 function makeWhereFrom2d( $data, $baseKey, $subKey ) {
1327 foreach ( $data as $base => $sub ) {
1328 if ( count( $sub ) ) {
1329 $conds[] = $this->makeList(
1330 array( $baseKey => $base, $subKey => array_keys( $sub ) ),
1336 return $this->makeList( $conds, LIST_OR
);
1338 // Nothing to search for...
1344 * Bitwise operations
1347 function bitNot($field) {
1351 function bitAnd($fieldLeft, $fieldRight) {
1352 return "($fieldLeft & $fieldRight)";
1355 function bitOr($fieldLeft, $fieldRight) {
1356 return "($fieldLeft | $fieldRight)";
1360 * Change the current database
1362 * @return bool Success or failure
1364 function selectDB( $db ) {
1365 # Stub. Shouldn't cause serious problems if it's not overridden, but
1366 # if your database engine supports a concept similar to MySQL's
1367 # databases you may as well. TODO: explain what exactly will fail if
1368 # this is not overridden.
1373 * Get the current DB name
1375 function getDBname() {
1376 return $this->mDBname
;
1380 * Get the server hostname or IP address
1382 function getServer() {
1383 return $this->mServer
;
1387 * Format a table name ready for use in constructing an SQL query
1389 * This does two important things: it quotes the table names to clean them up,
1390 * and it adds a table prefix if only given a table name with no quotes.
1392 * All functions of this object which require a table name call this function
1393 * themselves. Pass the canonical name to such functions. This is only needed
1394 * when calling query() directly.
1396 * @param $name String: database table name
1397 * @return String: full database name
1399 function tableName( $name ) {
1400 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1401 # Skip the entire process when we have a string quoted on both ends.
1402 # Note that we check the end so that we will still quote any use of
1403 # use of `database`.table. But won't break things if someone wants
1404 # to query a database table with a dot in the name.
1405 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) {
1409 # Lets test for any bits of text that should never show up in a table
1410 # name. Basically anything like JOIN or ON which are actually part of
1411 # SQL queries, but may end up inside of the table value to combine
1412 # sql. Such as how the API is doing.
1413 # Note that we use a whitespace test rather than a \b test to avoid
1414 # any remote case where a word like on may be inside of a table name
1415 # surrounded by symbols which may be considered word breaks.
1416 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) {
1420 # Split database and table into proper variables.
1421 # We reverse the explode so that database.table and table both output
1422 # the correct table.
1423 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1424 if( isset( $dbDetails[1] ) ) {
1425 @list
( $table, $database ) = $dbDetails;
1427 @list
( $table ) = $dbDetails;
1429 $prefix = $this->mTablePrefix
; # Default prefix
1431 # A database name has been specified in input. Quote the table name
1432 # because we don't want any prefixes added.
1433 if( isset($database) ) {
1434 $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1437 # Note that we use the long format because php will complain in in_array if
1438 # the input is not an array, and will complain in is_array if it is not set.
1439 if( !isset( $database ) # Don't use shared database if pre selected.
1440 && isset( $wgSharedDB ) # We have a shared database
1441 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1442 && isset( $wgSharedTables )
1443 && is_array( $wgSharedTables )
1444 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1445 $database = $wgSharedDB;
1446 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1449 # Quote the $database and $table and apply the prefix if not quoted.
1450 if( isset($database) ) {
1451 $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1453 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1455 # Merge our database and table into our final table name.
1456 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1458 # We're finished, return.
1463 * Fetch a number of table names into an array
1464 * This is handy when you need to construct SQL for joins
1467 * extract($dbr->tableNames('user','watchlist'));
1468 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1469 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1471 public function tableNames() {
1472 $inArray = func_get_args();
1474 foreach ( $inArray as $name ) {
1475 $retVal[$name] = $this->tableName( $name );
1481 * Fetch a number of table names into an zero-indexed numerical array
1482 * This is handy when you need to construct SQL for joins
1485 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1486 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1487 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1489 public function tableNamesN() {
1490 $inArray = func_get_args();
1492 foreach ( $inArray as $name ) {
1493 $retVal[] = $this->tableName( $name );
1501 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1504 $use_index_safe = is_array($use_index) ?
$use_index : array();
1505 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1506 foreach ( $tables as $table ) {
1507 // Is there a JOIN and INDEX clause for this table?
1508 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1509 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1510 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1511 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1513 $tableClause .= ' ON (' . $on . ')';
1515 $retJOIN[] = $tableClause;
1516 // Is there an INDEX clause?
1517 } else if ( isset($use_index_safe[$table]) ) {
1518 $tableClause = $this->tableName( $table );
1519 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1520 $ret[] = $tableClause;
1521 // Is there a JOIN clause?
1522 } else if ( isset($join_conds_safe[$table]) ) {
1523 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1524 $on = $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
);
1526 $tableClause .= ' ON (' . $on . ')';
1528 $retJOIN[] = $tableClause;
1530 $tableClause = $this->tableName( $table );
1531 $ret[] = $tableClause;
1534 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1535 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1536 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1537 // Compile our final table clause
1538 return implode(' ',array($straightJoins,$otherJoins) );
1542 * Get the name of an index in a given table
1544 function indexName( $index ) {
1545 // Backwards-compatibility hack
1547 'ar_usertext_timestamp' => 'usertext_timestamp',
1548 'un_user_id' => 'user_id',
1549 'un_user_ip' => 'user_ip',
1551 if( isset( $renamed[$index] ) ) {
1552 return $renamed[$index];
1559 * Wrapper for addslashes()
1560 * @param $s String: to be slashed.
1561 * @return String: slashed string.
1563 abstract function strencode( $s );
1566 * If it's a string, adds quotes and backslashes
1567 * Otherwise returns as-is
1569 function addQuotes( $s ) {
1570 if ( $s === null ) {
1573 # This will also quote numeric values. This should be harmless,
1574 # and protects against weird problems that occur when they really
1575 # _are_ strings such as article titles and string->number->string
1576 # conversion is not 1:1.
1577 return "'" . $this->strencode( $s ) . "'";
1582 * Escape string for safe LIKE usage.
1583 * WARNING: you should almost never use this function directly,
1584 * instead use buildLike() that escapes everything automatically
1585 * Deprecated in 1.17, warnings in 1.17, removed in ???
1587 public function escapeLike( $s ) {
1588 wfDeprecated( __METHOD__
);
1589 return $this->escapeLikeInternal( $s );
1592 protected function escapeLikeInternal( $s ) {
1593 $s = str_replace( '\\', '\\\\', $s );
1594 $s = $this->strencode( $s );
1595 $s = str_replace( array( '%', '_' ), array( '\%', '\_' ), $s );
1600 * LIKE statement wrapper, receives a variable-length argument list with parts of pattern to match
1601 * containing either string literals that will be escaped or tokens returned by anyChar() or anyString().
1602 * Alternatively, the function could be provided with an array of aforementioned parameters.
1604 * Example: $dbr->buildLike( 'My_page_title/', $dbr->anyString() ) returns a LIKE clause that searches
1605 * for subpages of 'My page title'.
1606 * Alternatively: $pattern = array( 'My_page_title/', $dbr->anyString() ); $query .= $dbr->buildLike( $pattern );
1609 * @return String: fully built LIKE statement
1611 function buildLike() {
1612 $params = func_get_args();
1613 if (count($params) > 0 && is_array($params[0])) {
1614 $params = $params[0];
1618 foreach( $params as $value) {
1619 if( $value instanceof LikeMatch
) {
1620 $s .= $value->toString();
1622 $s .= $this->escapeLikeInternal( $value );
1625 return " LIKE '" . $s . "' ";
1629 * Returns a token for buildLike() that denotes a '_' to be used in a LIKE query
1631 function anyChar() {
1632 return new LikeMatch( '_' );
1636 * Returns a token for buildLike() that denotes a '%' to be used in a LIKE query
1638 function anyString() {
1639 return new LikeMatch( '%' );
1643 * Returns an appropriately quoted sequence value for inserting a new row.
1644 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1645 * subclass will return an integer, and save the value for insertId()
1647 function nextSequenceValue( $seqName ) {
1652 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1653 * is only needed because a) MySQL must be as efficient as possible due to
1654 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1655 * which index to pick. Anyway, other databases might have different
1656 * indexes on a given table. So don't bother overriding this unless you're
1659 function useIndexClause( $index ) {
1664 * REPLACE query wrapper
1665 * PostgreSQL simulates this with a DELETE followed by INSERT
1666 * $row is the row to insert, an associative array
1667 * $uniqueIndexes is an array of indexes. Each element may be either a
1668 * field name or an array of field names
1670 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1671 * However if you do this, you run the risk of encountering errors which wouldn't have
1674 * @param $table String: The table to replace the row(s) in.
1675 * @param $uniqueIndexes Array: An associative array of indexes
1676 * @param $rows Array: Array of rows to replace
1677 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1679 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseBase::replace' ) {
1680 $table = $this->tableName( $table );
1683 if ( !is_array( reset( $rows ) ) ) {
1684 $rows = array( $rows );
1687 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1689 foreach ( $rows as $row ) {
1695 $sql .= '(' . $this->makeList( $row ) . ')';
1697 return $this->query( $sql, $fname );
1701 * DELETE where the condition is a join
1702 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1704 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1705 * join condition matches, set $conds='*'
1707 * DO NOT put the join condition in $conds
1709 * @param $delTable String: The table to delete from.
1710 * @param $joinTable String: The other table.
1711 * @param $delVar String: The variable to join on, in the first table.
1712 * @param $joinVar String: The variable to join on, in the second table.
1713 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1714 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1716 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
1718 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
1721 $delTable = $this->tableName( $delTable );
1722 $joinTable = $this->tableName( $joinTable );
1723 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1724 if ( $conds != '*' ) {
1725 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1728 return $this->query( $sql, $fname );
1732 * Returns the size of a text field, or -1 for "unlimited"
1734 function textFieldSize( $table, $field ) {
1735 $table = $this->tableName( $table );
1736 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1737 $res = $this->query( $sql, 'DatabaseBase::textFieldSize' );
1738 $row = $this->fetchObject( $res );
1741 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1750 * A string to insert into queries to show that they're low-priority, like
1751 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1752 * string and nothing bad should happen.
1754 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1756 function lowPriorityOption() {
1761 * DELETE query wrapper
1763 * Use $conds == "*" to delete all rows
1765 function delete( $table, $conds, $fname = 'DatabaseBase::delete' ) {
1767 throw new DBUnexpectedError( $this, 'DatabaseBase::delete() called with no conditions' );
1769 $table = $this->tableName( $table );
1770 $sql = "DELETE FROM $table";
1771 if ( $conds != '*' ) {
1772 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1774 return $this->query( $sql, $fname );
1778 * INSERT SELECT wrapper
1779 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1780 * Source items may be literals rather than field names, but strings should be quoted with DatabaseBase::addQuotes()
1781 * $conds may be "*" to copy the whole table
1782 * srcTable may be an array of tables.
1784 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'DatabaseBase::insertSelect',
1785 $insertOptions = array(), $selectOptions = array() )
1787 $destTable = $this->tableName( $destTable );
1788 if ( is_array( $insertOptions ) ) {
1789 $insertOptions = implode( ' ', $insertOptions );
1791 if( !is_array( $selectOptions ) ) {
1792 $selectOptions = array( $selectOptions );
1794 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1795 if( is_array( $srcTable ) ) {
1796 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1798 $srcTable = $this->tableName( $srcTable );
1800 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1801 " SELECT $startOpts " . implode( ',', $varMap ) .
1802 " FROM $srcTable $useIndex ";
1803 if ( $conds != '*' ) {
1804 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1806 $sql .= " $tailOpts";
1807 return $this->query( $sql, $fname );
1811 * Construct a LIMIT query with optional offset. This is used for query
1812 * pages. The SQL should be adjusted so that only the first $limit rows
1813 * are returned. If $offset is provided as well, then the first $offset
1814 * rows should be discarded, and the next $limit rows should be returned.
1815 * If the result of the query is not ordered, then the rows to be returned
1816 * are theoretically arbitrary.
1818 * $sql is expected to be a SELECT, if that makes a difference. For
1819 * UPDATE, limitResultForUpdate should be used.
1821 * The version provided by default works in MySQL and SQLite. It will very
1822 * likely need to be overridden for most other DBMSes.
1824 * @param $sql String: SQL query we will append the limit too
1825 * @param $limit Integer: the SQL limit
1826 * @param $offset Integer the SQL offset (default false)
1828 function limitResult( $sql, $limit, $offset=false ) {
1829 if( !is_numeric( $limit ) ) {
1830 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1832 return "$sql LIMIT "
1833 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1836 function limitResultForUpdate( $sql, $num ) {
1837 return $this->limitResult( $sql, $num, 0 );
1841 * Returns true if current database backend supports ORDER BY or LIMIT for separate subqueries
1842 * within the UNION construct.
1845 function unionSupportsOrderAndLimit() {
1846 return true; // True for almost every DB supported
1850 * Construct a UNION query
1851 * This is used for providing overload point for other DB abstractions
1852 * not compatible with the MySQL syntax.
1853 * @param $sqls Array: SQL statements to combine
1854 * @param $all Boolean: use UNION ALL
1855 * @return String: SQL fragment
1857 function unionQueries($sqls, $all) {
1858 $glue = $all ?
') UNION ALL (' : ') UNION (';
1859 return '('.implode( $glue, $sqls ) . ')';
1863 * Returns an SQL expression for a simple conditional. This doesn't need
1864 * to be overridden unless CASE isn't supported in your DBMS.
1866 * @param $cond String: SQL expression which will result in a boolean value
1867 * @param $trueVal String: SQL expression to return if true
1868 * @param $falseVal String: SQL expression to return if false
1869 * @return String: SQL fragment
1871 function conditional( $cond, $trueVal, $falseVal ) {
1872 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1876 * Returns a comand for str_replace function in SQL query.
1877 * Uses REPLACE() in MySQL
1879 * @param $orig String: column to modify
1880 * @param $old String: column to seek
1881 * @param $new String: column to replace with
1883 function strreplace( $orig, $old, $new ) {
1884 return "REPLACE({$orig}, {$old}, {$new})";
1888 * Determines if the last failure was due to a deadlock
1891 function wasDeadlock() {
1896 * Determines if the last query error was something that should be dealt
1897 * with by pinging the connection and reissuing the query.
1900 function wasErrorReissuable() {
1905 * Determines if the last failure was due to the database being read-only.
1908 function wasReadOnlyError() {
1913 * Perform a deadlock-prone transaction.
1915 * This function invokes a callback function to perform a set of write
1916 * queries. If a deadlock occurs during the processing, the transaction
1917 * will be rolled back and the callback function will be called again.
1920 * $dbw->deadlockLoop( callback, ... );
1922 * Extra arguments are passed through to the specified callback function.
1924 * Returns whatever the callback function returned on its successful,
1925 * iteration, or false on error, for example if the retry limit was
1928 function deadlockLoop() {
1929 $myFname = 'DatabaseBase::deadlockLoop';
1932 $args = func_get_args();
1933 $function = array_shift( $args );
1934 $oldIgnore = $this->ignoreErrors( true );
1935 $tries = DEADLOCK_TRIES
;
1936 if ( is_array( $function ) ) {
1937 $fname = $function[0];
1942 $retVal = call_user_func_array( $function, $args );
1943 $error = $this->lastError();
1944 $errno = $this->lastErrno();
1945 $sql = $this->lastQuery();
1948 if ( $this->wasDeadlock() ) {
1950 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1952 $this->reportQueryError( $error, $errno, $sql, $fname );
1955 } while( $this->wasDeadlock() && --$tries > 0 );
1956 $this->ignoreErrors( $oldIgnore );
1957 if ( $tries <= 0 ) {
1958 $this->rollback( $myFname );
1959 $this->reportQueryError( $error, $errno, $sql, $fname );
1962 $this->commit( $myFname );
1968 * Do a SELECT MASTER_POS_WAIT()
1970 * @param $pos MySQLMasterPos object
1971 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1973 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1974 $fname = 'DatabaseBase::masterPosWait';
1975 wfProfileIn( $fname );
1977 # Commit any open transactions
1978 if ( $this->mTrxLevel
) {
1982 if ( !is_null( $this->mFakeSlaveLag
) ) {
1983 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1984 if ( $wait > $timeout * 1e6
) {
1985 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1986 wfProfileOut( $fname );
1988 } elseif ( $wait > 0 ) {
1989 wfDebug( "Fake slave waiting $wait us\n" );
1991 wfProfileOut( $fname );
1994 wfDebug( "Fake slave up to date ($wait us)\n" );
1995 wfProfileOut( $fname );
2000 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
2001 $encFile = $this->addQuotes( $pos->file
);
2002 $encPos = intval( $pos->pos
);
2003 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
2004 $res = $this->doQuery( $sql );
2005 if ( $res && $row = $this->fetchRow( $res ) ) {
2006 wfProfileOut( $fname );
2009 wfProfileOut( $fname );
2015 * Get the position of the master from SHOW SLAVE STATUS
2017 function getSlavePos() {
2018 if ( !is_null( $this->mFakeSlaveLag
) ) {
2019 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
2020 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
2023 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
2024 $row = $this->fetchObject( $res );
2026 $pos = isset($row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
2027 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
2034 * Get the position of the master from SHOW MASTER STATUS
2036 function getMasterPos() {
2037 if ( $this->mFakeMaster
) {
2038 return new MySQLMasterPos( 'fake', microtime( true ) );
2040 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
2041 $row = $this->fetchObject( $res );
2043 return new MySQLMasterPos( $row->File
, $row->Position
);
2050 * Begin a transaction, committing any previously open transaction
2052 function begin( $fname = 'DatabaseBase::begin' ) {
2053 $this->query( 'BEGIN', $fname );
2054 $this->mTrxLevel
= 1;
2060 function commit( $fname = 'DatabaseBase::commit' ) {
2061 if( $this->mTrxLevel
) {
2062 $this->query( 'COMMIT', $fname );
2063 $this->mTrxLevel
= 0;
2068 * Rollback a transaction.
2069 * No-op on non-transactional databases.
2071 function rollback( $fname = 'DatabaseBase::rollback' ) {
2072 if( $this->mTrxLevel
) {
2073 $this->query( 'ROLLBACK', $fname, true );
2074 $this->mTrxLevel
= 0;
2079 * Begin a transaction, committing any previously open transaction
2080 * @deprecated use begin()
2082 function immediateBegin( $fname = 'DatabaseBase::immediateBegin' ) {
2083 wfDeprecated( __METHOD__
);
2088 * Commit transaction, if one is open
2089 * @deprecated use commit()
2091 function immediateCommit( $fname = 'DatabaseBase::immediateCommit' ) {
2092 wfDeprecated( __METHOD__
);
2097 * Creates a new table with structure copied from existing table
2098 * Note that unlike most database abstraction functions, this function does not
2099 * automatically append database prefix, because it works at a lower
2100 * abstraction level.
2102 * @param $oldName String: name of table whose structure should be copied
2103 * @param $newName String: name of table to be created
2104 * @param $temporary Boolean: whether the new table should be temporary
2105 * @param $fname String: calling function name
2106 * @return Boolean: true if operation was successful
2108 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseBase::duplicateTableStructure' ) {
2109 throw new MWException( 'DatabaseBase::duplicateTableStructure is not implemented in descendant class' );
2113 * Return MW-style timestamp used for MySQL schema
2115 function timestamp( $ts=0 ) {
2116 return wfTimestamp(TS_MW
,$ts);
2120 * Local database timestamp format or null
2122 function timestampOrNull( $ts = null ) {
2123 if( is_null( $ts ) ) {
2126 return $this->timestamp( $ts );
2133 function resultObject( $result ) {
2134 if( empty( $result ) ) {
2136 } elseif ( $result instanceof ResultWrapper
) {
2138 } elseif ( $result === true ) {
2139 // Successful write query
2142 return new ResultWrapper( $this, $result );
2147 * Return aggregated value alias
2149 function aggregateValue ($valuedata,$valuename='value') {
2154 * Returns a wikitext link to the DB's website, e.g.,
2155 * return "[http://www.mysql.com/ MySQL]";
2156 * Should at least contain plain text, if for some reason
2157 * your database has no website.
2159 * @return String: wikitext of a link to the server software's web site
2161 public static function getSoftwareLink() {
2162 throw new MWException( "A child class of DatabaseBase didn't implement getSoftwareLink(), shame on them" );
2166 * A string describing the current software version, like from
2167 * mysql_get_server_info(). Will be listed on Special:Version, etc.
2169 * @return String: Version information from the database
2171 abstract function getServerVersion();
2174 * Ping the server and try to reconnect if it there is no connection
2176 * @return bool Success or failure
2179 # Stub. Not essential to override.
2185 * Currently supported only by MySQL
2186 * @return Database replication lag in seconds
2189 return $this->mFakeSlaveLag
;
2193 * Get status information from SHOW STATUS in an associative array
2195 function getStatus($which="%") {
2196 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2198 while ( $row = $this->fetchObject( $res ) ) {
2199 $status[$row->Variable_name
] = $row->Value
;
2205 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2207 function maxListLen() {
2211 function encodeBlob($b) {
2215 function decodeBlob($b) {
2220 * Override database's default connection timeout. May be useful for very
2221 * long batch queries such as full-wiki dumps, where a single query reads
2222 * out over hours or days. May or may not be necessary for non-MySQL
2223 * databases. For most purposes, leaving it as a no-op should be fine.
2225 * @param $timeout Integer in seconds
2227 public function setTimeout( $timeout ) {}
2230 * Read and execute SQL commands from a file.
2231 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2232 * @param $filename String: File name to open
2233 * @param $lineCallback Callback: Optional function called before reading each line
2234 * @param $resultCallback Callback: Optional function called for each MySQL result
2236 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2237 $fp = fopen( $filename, 'r' );
2238 if ( false === $fp ) {
2239 if (!defined("MEDIAWIKI_INSTALL"))
2240 throw new MWException( "Could not open \"{$filename}\".\n" );
2242 return "Could not open \"{$filename}\".\n";
2245 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2247 catch( MWException
$e ) {
2248 if ( defined("MEDIAWIKI_INSTALL") ) {
2249 $error = $e->getMessage();
2261 * Get the full path of a patch file. Originally based on archive()
2262 * from updaters.inc. Keep in mind this always returns a patch, as
2263 * it fails back to MySQL if no DB-specific patch can be found
2265 * @param $patch String The name of the patch, like patch-something.sql
2266 * @return String Full path to patch file
2268 public static function patchPath( $patch ) {
2269 global $wgDBtype, $IP;
2270 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$patch" ) ) {
2271 return "$IP/maintenance/$wgDBtype/archives/$patch";
2273 return "$IP/maintenance/archives/$patch";
2278 * Read and execute commands from an open file handle
2279 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2280 * @param $fp String: File handle
2281 * @param $lineCallback Callback: Optional function called before reading each line
2282 * @param $resultCallback Callback: Optional function called for each MySQL result
2284 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2287 $dollarquote = false;
2289 while ( ! feof( $fp ) ) {
2290 if ( $lineCallback ) {
2291 call_user_func( $lineCallback );
2293 $line = trim( fgets( $fp, 1024 ) );
2294 $sl = strlen( $line ) - 1;
2296 if ( $sl < 0 ) { continue; }
2297 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2299 ## Allow dollar quoting for function declarations
2300 if (substr($line,0,4) == '$mw$') {
2302 $dollarquote = false;
2306 $dollarquote = true;
2309 else if (!$dollarquote) {
2310 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2312 $line = substr( $line, 0, $sl );
2316 if ( $cmd != '' ) { $cmd .= ' '; }
2320 $cmd = str_replace(';;', ";", $cmd);
2321 $cmd = $this->replaceVars( $cmd );
2322 $res = $this->query( $cmd, __METHOD__
);
2323 if ( $resultCallback ) {
2324 call_user_func( $resultCallback, $res, $this );
2327 if ( false === $res ) {
2328 $err = $this->lastError();
2329 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2341 * Replace variables in sourced SQL
2343 protected function replaceVars( $ins ) {
2345 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2346 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2347 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2350 // Ordinary variables
2351 foreach ( $varnames as $var ) {
2352 if( isset( $GLOBALS[$var] ) ) {
2353 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2354 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2355 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2356 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2361 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2362 array( $this, 'tableNameCallback' ), $ins );
2365 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2366 array( $this, 'indexNameCallback' ), $ins );
2371 * Table name callback
2374 protected function tableNameCallback( $matches ) {
2375 return $this->tableName( $matches[1] );
2379 * Index name callback
2381 protected function indexNameCallback( $matches ) {
2382 return $this->indexName( $matches[1] );
2386 * Build a concatenation list to feed into a SQL query
2387 * @param $stringList Array: list of raw SQL expressions; caller is responsible for any quoting
2390 function buildConcat( $stringList ) {
2391 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2395 * Acquire a named lock
2397 * Abstracted from Filestore::lock() so child classes can implement for
2400 * @param $lockName String: name of lock to aquire
2401 * @param $method String: name of method calling us
2402 * @param $timeout Integer: timeout
2405 public function lock( $lockName, $method, $timeout = 5 ) {
2412 * @param $lockName String: Name of lock to release
2413 * @param $method String: Name of method calling us
2415 * @return Returns 1 if the lock was released, 0 if the lock was not established
2416 * by this thread (in which case the lock is not released), and NULL if the named
2417 * lock did not exist
2419 public function unlock( $lockName, $method ) {
2424 * Lock specific tables
2426 * @param $read Array of tables to lock for read access
2427 * @param $write Array of tables to lock for write access
2428 * @param $method String name of caller
2429 * @param $lowPriority bool Whether to indicate writes to be LOW PRIORITY
2431 public function lockTables( $read, $write, $method, $lowPriority = true ) {
2436 * Unlock specific tables
2438 * @param $method String the caller
2440 public function unlockTables( $method ) {
2445 * Get search engine class. All subclasses of this need to implement this
2446 * if they wish to use searching.
2450 public function getSearchEngine() {
2451 return 'SearchEngineDummy';
2455 * Allow or deny "big selects" for this session only. This is done by setting
2456 * the sql_big_selects session variable.
2458 * This is a MySQL-specific feature.
2460 * @param $value Mixed: true for allow, false for deny, or "default" to restore the initial value
2462 public function setBigSelects( $value = true ) {
2468 /******************************************************************************
2470 *****************************************************************************/
2479 function DBObject($data) {
2480 $this->mData
= $data;
2488 return $this->mData
;
2496 * This allows us to distinguish a blob from a normal string and an array of strings
2500 function __construct($data) {
2501 $this->mData
= $data;
2504 return $this->mData
;
2513 private $name, $tablename, $default, $max_length, $nullable,
2514 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2515 function __construct ($info) {
2516 $this->name
= $info->name
;
2517 $this->tablename
= $info->table
;
2518 $this->default = $info->def
;
2519 $this->max_length
= $info->max_length
;
2520 $this->nullable
= !$info->not_null
;
2521 $this->is_pk
= $info->primary_key
;
2522 $this->is_unique
= $info->unique_key
;
2523 $this->is_multiple
= $info->multiple_key
;
2524 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2525 $this->type
= $info->type
;
2532 function tableName() {
2533 return $this->tableName
;
2536 function defaultValue() {
2537 return $this->default;
2540 function maxLength() {
2541 return $this->max_length
;
2544 function nullable() {
2545 return $this->nullable
;
2549 return $this->is_key
;
2552 function isMultipleKey() {
2553 return $this->is_multiple
;
2561 /******************************************************************************
2563 *****************************************************************************/
2566 * Database error base class
2569 class DBError
extends MWException
{
2573 * Construct a database error
2574 * @param $db Database object which threw the error
2575 * @param $error A simple error message to be used for debugging
2577 function __construct( DatabaseBase
&$db, $error ) {
2579 parent
::__construct( $error );
2582 function getText() {
2583 global $wgShowDBErrorBacktrace;
2584 $s = $this->getMessage() . "\n";
2585 if ( $wgShowDBErrorBacktrace ) {
2586 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2595 class DBConnectionError
extends DBError
{
2598 function __construct( DatabaseBase
&$db, $error = 'unknown error' ) {
2599 $msg = 'DB connection error';
2600 if ( trim( $error ) != '' ) {
2603 $this->error
= $error;
2604 parent
::__construct( $db, $msg );
2607 function useOutputPage() {
2608 // Not likely to work
2612 function useMessageCache() {
2613 // Not likely to work
2617 function getLogMessage() {
2618 # Don't send to the exception log
2622 function getPageTitle() {
2623 global $wgSitename, $wgLang;
2624 $header = "$wgSitename has a problem";
2625 if ( $wgLang instanceof Language
) {
2626 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2632 function getHTML() {
2633 global $wgLang, $wgMessageCache, $wgUseFileCache, $wgShowDBErrorBacktrace;
2635 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2636 $again = 'Try waiting a few minutes and reloading.';
2637 $info = '(Can\'t contact the database server: $1)';
2639 if ( $wgLang instanceof Language
) {
2640 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2641 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2642 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2645 # No database access
2646 if ( is_object( $wgMessageCache ) ) {
2647 $wgMessageCache->disable();
2650 if ( trim( $this->error
) == '' ) {
2651 $this->error
= $this->db
->getProperty('mServer');
2654 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2655 $text = str_replace( '$1', $this->error
, $noconnect );
2657 if ( $wgShowDBErrorBacktrace ) {
2658 $text .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2661 $extra = $this->searchForm();
2663 if( $wgUseFileCache ) {
2665 $cache = $this->fileCachedPage();
2666 # Cached version on file system?
2667 if( $cache !== null ) {
2668 # Hack: extend the body for error messages
2669 $cache = str_replace( array('</html>','</body>'), '', $cache );
2670 # Add cache notice...
2671 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2672 # Localize it if possible...
2673 if( $wgLang instanceof Language
) {
2674 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2676 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2677 # Output cached page with notices on bottom and re-close body
2678 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2680 } catch( MWException
$e ) {
2681 // Do nothing, just use the default page
2684 # Headers needed here - output is just the error message
2685 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2688 function searchForm() {
2689 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2690 $usegoogle = "You can try searching via Google in the meantime.";
2691 $outofdate = "Note that their indexes of our content may be out of date.";
2692 $googlesearch = "Search";
2694 if ( $wgLang instanceof Language
) {
2695 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2696 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2697 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2700 $search = htmlspecialchars(@$_REQUEST['search']);
2703 <div style="margin: 1.5em">$usegoogle<br />
2704 <small>$outofdate</small></div>
2705 <!-- SiteSearch Google -->
2706 <form method="get" action="http://www.google.com/search" id="googlesearch">
2707 <input type="hidden" name="domains" value="$wgServer" />
2708 <input type="hidden" name="num" value="50" />
2709 <input type="hidden" name="ie" value="$wgInputEncoding" />
2710 <input type="hidden" name="oe" value="$wgInputEncoding" />
2712 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2713 <input type="submit" name="btnG" value="$googlesearch" />
2715 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2716 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2719 <!-- SiteSearch Google -->
2724 function fileCachedPage() {
2725 global $wgTitle, $title, $wgLang, $wgOut;
2726 if( $wgOut->isDisabled() ) return; // Done already?
2727 $mainpage = 'Main Page';
2728 if ( $wgLang instanceof Language
) {
2729 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2734 } elseif( $title ) {
2735 $t = Title
::newFromURL( $title );
2737 $t = Title
::newFromText( $mainpage );
2740 $cache = new HTMLFileCache( $t );
2741 if( $cache->isFileCached() ) {
2742 return $cache->fetchPageText();
2748 function htmlBodyOnly() {
2757 class DBQueryError
extends DBError
{
2758 public $error, $errno, $sql, $fname;
2760 function __construct( DatabaseBase
&$db, $error, $errno, $sql, $fname ) {
2761 $message = "A database error has occurred\n" .
2763 "Function: $fname\n" .
2764 "Error: $errno $error\n";
2766 parent
::__construct( $db, $message );
2767 $this->error
= $error;
2768 $this->errno
= $errno;
2770 $this->fname
= $fname;
2773 function getText() {
2774 global $wgShowDBErrorBacktrace;
2775 if ( $this->useMessageCache() ) {
2776 $s = wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2777 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2778 if ( $wgShowDBErrorBacktrace ) {
2779 $s .= "Backtrace:\n" . $this->getTraceAsString() . "\n";
2783 return parent
::getText();
2788 global $wgShowSQLErrors;
2789 if( !$wgShowSQLErrors ) {
2790 return $this->msg( 'sqlhidden', 'SQL hidden' );
2796 function getLogMessage() {
2797 # Don't send to the exception log
2801 function getPageTitle() {
2802 return $this->msg( 'databaseerror', 'Database error' );
2805 function getHTML() {
2806 global $wgShowDBErrorBacktrace;
2807 if ( $this->useMessageCache() ) {
2808 $s = wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2809 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2811 $s = nl2br( htmlspecialchars( $this->getMessage() ) );
2813 if ( $wgShowDBErrorBacktrace ) {
2814 $s .= '<p>Backtrace:</p><p>' . nl2br( htmlspecialchars( $this->getTraceAsString() ) );
2823 class DBUnexpectedError
extends DBError
{}
2827 * Result wrapper for grabbing data queried by someone else
2830 class ResultWrapper
implements Iterator
{
2831 var $db, $result, $pos = 0, $currentRow = null;
2834 * Create a new result object from a result resource and a Database object
2836 function ResultWrapper( $database, $result ) {
2837 $this->db
= $database;
2838 if ( $result instanceof ResultWrapper
) {
2839 $this->result
= $result->result
;
2841 $this->result
= $result;
2846 * Get the number of rows in a result object
2848 function numRows() {
2849 return $this->db
->numRows( $this );
2853 * Fetch the next row from the given result object, in object form.
2854 * Fields can be retrieved with $row->fieldname, with fields acting like
2857 * @return MySQL row object
2858 * @throws DBUnexpectedError Thrown if the database returns an error
2860 function fetchObject() {
2861 return $this->db
->fetchObject( $this );
2865 * Fetch the next row from the given result object, in associative array
2866 * form. Fields are retrieved with $row['fieldname'].
2868 * @return MySQL row object
2869 * @throws DBUnexpectedError Thrown if the database returns an error
2871 function fetchRow() {
2872 return $this->db
->fetchRow( $this );
2876 * Free a result object
2879 $this->db
->freeResult( $this );
2880 unset( $this->result
);
2885 * Change the position of the cursor in a result object
2886 * See mysql_data_seek()
2888 function seek( $row ) {
2889 $this->db
->dataSeek( $this, $row );
2892 /*********************
2893 * Iterator functions
2894 * Note that using these in combination with the non-iterator functions
2895 * above may cause rows to be skipped or repeated.
2899 if ($this->numRows()) {
2900 $this->db
->dataSeek($this, 0);
2903 $this->currentRow
= null;
2906 function current() {
2907 if ( is_null( $this->currentRow
) ) {
2910 return $this->currentRow
;
2919 $this->currentRow
= $this->fetchObject();
2920 return $this->currentRow
;
2924 return $this->current() !== false;
2928 /* Overloads the relevant methods of the real ResultsWrapper so it
2929 * doesn't go anywhere near an actual database.
2931 class FakeResultWrapper
extends ResultWrapper
{
2933 var $result = array();
2934 var $db = null; // And it's going to stay that way :D
2936 var $currentRow = null;
2938 function __construct( $array ){
2939 $this->result
= $array;
2942 function numRows() {
2943 return count( $this->result
);
2946 function fetchRow() {
2947 $this->currentRow
= $this->result
[$this->pos++
];
2948 return $this->currentRow
;
2951 function seek( $row ) {
2957 // Callers want to be able to access fields with $this->fieldName
2958 function fetchObject(){
2959 $this->currentRow
= $this->result
[$this->pos++
];
2960 return (object)$this->currentRow
;
2965 $this->currentRow
= null;
2970 * Used by DatabaseBase::buildLike() to represent characters that have special meaning in SQL LIKE clauses
2971 * and thus need no escaping. Don't instantiate it manually, use DatabaseBase::anyChar() and anyString() instead.
2976 public function __construct( $s ) {
2980 public function toString() {