* Move lock()/unlock() to DatabaseMysql, declare abstract
[mediawiki.git] / includes / db / Database.php
blobd6789c17cfebf306d8d054c47ee58077d65495fc
1 <?php
2 /**
3 * @defgroup Database Database
5 * @file
6 * @ingroup Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
9 */
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 );
18 /**
19 * Database abstraction object
20 * @ingroup Database
22 abstract class DatabaseBase {
24 #------------------------------------------------------------------------------
25 # Variables
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;
37 protected $mFlags;
38 protected $mTrxLevel = 0;
39 protected $mErrorCount = 0;
40 protected $mLBInfo = array();
41 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 protected $mDefaultBigSelects = null;
44 #------------------------------------------------------------------------------
45 # Accessors
46 #------------------------------------------------------------------------------
47 # These optionally set a variable and return the previous state
49 /**
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 );
57 /**
58 * Output page, used for reporting errors
59 * FALSE means discard output
61 function setOutputPage( $out ) {
62 wfDeprecated( __METHOD__ );
65 /**
66 * Boolean, controls output of large amounts of debug information
68 function debug( $debug = NULL ) {
69 return wfSetBit( $this->mFlags, DBO_DEBUG, $debug );
72 /**
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 );
79 } else {
80 return !wfSetBit( $this->mFlags, DBO_NOBUFFER, !$buffer );
84 /**
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 );
95 /**
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;
120 } else {
121 if ( array_key_exists( $name, $this->mLBInfo ) ) {
122 return $this->mLBInfo[$name];
123 } else {
124 return NULL;
129 function setLBInfo( $name, $value = NULL ) {
130 if ( is_null( $value ) ) {
131 $this->mLBInfo = $name;
132 } else {
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() {
155 return false;
159 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
161 function cleanupTriggers() {
162 return false;
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() {
170 return false;
174 * Returns true if this database uses timestamps rather than integers
176 function realTimestamps() {
177 return false;
181 * Returns true if this database does an implicit sort when doing GROUP BY
183 function implicitGroupby() {
184 return true;
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() {
192 return true;
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() {
200 return false;
204 * Returns true if this database can use functional indexes
206 function functionalIndexes() {
207 return false;
211 * Return the last query that went through Database::query()
212 * @return String
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?
225 * @return Boolean
227 function isOpen() { return $this->mOpened; }
229 function setFlag( $flag ) {
230 $this->mFlags |= $flag;
233 function clearFlag( $flag ) {
234 $this->mFlags &= ~$flag;
237 function getFlag( $flag ) {
238 return !!($this->mFlags & $flag);
242 * General read-only accessor
244 function getProperty( $name ) {
245 return $this->$name;
248 function getWikiID() {
249 if( $this->mTablePrefix ) {
250 return "{$this->mDBname}-{$this->mTablePrefix}";
251 } else {
252 return $this->mDBname;
256 #------------------------------------------------------------------------------
257 # Other functions
258 #------------------------------------------------------------------------------
261 * Constructor.
262 * @param $server String: database server host
263 * @param $user String: database user name
264 * @param $password String: database user password
265 * @param $dbName String: database name
266 * @param $failFunction
267 * @param $flags
268 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
270 function __construct( $server = false, $user = false, $password = false, $dbName = false,
271 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
273 global $wgOut, $wgDBprefix, $wgCommandLineMode;
274 # Can't get a reference if it hasn't been set yet
275 if ( !isset( $wgOut ) ) {
276 $wgOut = NULL;
279 $this->mFailFunction = $failFunction;
280 $this->mFlags = $flags;
282 if ( $this->mFlags & DBO_DEFAULT ) {
283 if ( $wgCommandLineMode ) {
284 $this->mFlags &= ~DBO_TRX;
285 } else {
286 $this->mFlags |= DBO_TRX;
291 // Faster read-only access
292 if ( wfReadOnly() ) {
293 $this->mFlags |= DBO_PERSISTENT;
294 $this->mFlags &= ~DBO_TRX;
297 /** Get the default table prefix*/
298 if ( $tablePrefix == 'get from global' ) {
299 $this->mTablePrefix = $wgDBprefix;
300 } else {
301 $this->mTablePrefix = $tablePrefix;
304 if ( $server ) {
305 $this->open( $server, $user, $password, $dbName );
310 * Same as new DatabaseMysql( ... ), kept for backward compatibility
311 * @param $server String: database server host
312 * @param $user String: database user name
313 * @param $password String: database user password
314 * @param $dbName String: database name
315 * @param failFunction
316 * @param $flags
318 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
320 return new DatabaseMysql( $server, $user, $password, $dbName, $failFunction, $flags );
324 * Usually aborts on failure
325 * If the failFunction is set to a non-zero integer, returns success
326 * @param $server String: database server host
327 * @param $user String: database user name
328 * @param $password String: database user password
329 * @param $dbName String: database name
331 abstract function open( $server, $user, $password, $dbName );
333 protected function installErrorHandler() {
334 $this->mPHPError = false;
335 $this->htmlErrors = ini_set( 'html_errors', '0' );
336 set_error_handler( array( $this, 'connectionErrorHandler' ) );
339 protected function restoreErrorHandler() {
340 restore_error_handler();
341 if ( $this->htmlErrors !== false ) {
342 ini_set( 'html_errors', $this->htmlErrors );
344 if ( $this->mPHPError ) {
345 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError );
346 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
347 return $error;
348 } else {
349 return false;
353 protected function connectionErrorHandler( $errno, $errstr ) {
354 $this->mPHPError = $errstr;
358 * Closes a database connection.
359 * if it is open : commits any open transactions
361 * @return Bool operation success. true if already closed.
363 function close() {
364 # Stub, should probably be overridden
365 return true;
369 * @param $error String: fallback error message, used if none is given by MySQL
371 function reportConnectionError( $error = 'Unknown error' ) {
372 $myError = $this->lastError();
373 if ( $myError ) {
374 $error = $myError;
377 if ( $this->mFailFunction ) {
378 # Legacy error handling method
379 if ( !is_int( $this->mFailFunction ) ) {
380 $ff = $this->mFailFunction;
381 $ff( $this, $error );
383 } else {
384 # New method
385 throw new DBConnectionError( $this, $error );
390 * Determine whether a query writes to the DB.
391 * Should return true if unsure.
393 function isWriteQuery( $sql ) {
394 return !preg_match( '/^(?:SELECT|BEGIN|COMMIT|SET|SHOW)\b/i', $sql );
398 * Usually aborts on failure. If errors are explicitly ignored, returns success.
400 * @param $sql String: SQL query
401 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
402 * comment (you can use __METHOD__ or add some extra info)
403 * @param $tempIgnore Boolean: Whether to avoid throwing an exception on errors...
404 * maybe best to catch the exception instead?
405 * @return true for a successful write query, ResultWrapper object for a successful read query,
406 * or false on failure if $tempIgnore set
407 * @throws DBQueryError Thrown when the database returns an error of any kind
409 public function query( $sql, $fname = '', $tempIgnore = false ) {
410 global $wgProfiler;
412 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
413 if ( isset( $wgProfiler ) ) {
414 # generalizeSQL will probably cut down the query to reasonable
415 # logging size most of the time. The substr is really just a sanity check.
417 # Who's been wasting my precious column space? -- TS
418 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
420 if ( $isMaster ) {
421 $queryProf = 'query-m: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
422 $totalProf = 'Database::query-master';
423 } else {
424 $queryProf = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
425 $totalProf = 'Database::query';
427 wfProfileIn( $totalProf );
428 wfProfileIn( $queryProf );
431 $this->mLastQuery = $sql;
432 if ( !$this->mDoneWrites && $this->isWriteQuery( $sql ) ) {
433 // Set a flag indicating that writes have been done
434 wfDebug( __METHOD__.": Writes done: $sql\n" );
435 $this->mDoneWrites = true;
438 # Add a comment for easy SHOW PROCESSLIST interpretation
439 #if ( $fname ) {
440 global $wgUser;
441 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject) ) {
442 $userName = $wgUser->getName();
443 if ( mb_strlen( $userName ) > 15 ) {
444 $userName = mb_substr( $userName, 0, 15 ) . '...';
446 $userName = str_replace( '/', '', $userName );
447 } else {
448 $userName = '';
450 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
451 #} else {
452 # $commentedSql = $sql;
455 # If DBO_TRX is set, start a transaction
456 if ( ( $this->mFlags & DBO_TRX ) && !$this->trxLevel() &&
457 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
458 // avoid establishing transactions for SHOW and SET statements too -
459 // that would delay transaction initializations to once connection
460 // is really used by application
461 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
462 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
463 $this->begin();
466 if ( $this->debug() ) {
467 $sqlx = substr( $commentedSql, 0, 500 );
468 $sqlx = strtr( $sqlx, "\t\n", ' ' );
469 if ( $isMaster ) {
470 wfDebug( "SQL-master: $sqlx\n" );
471 } else {
472 wfDebug( "SQL: $sqlx\n" );
476 if ( istainted( $sql ) & TC_MYSQL ) {
477 throw new MWException( 'Tainted query found' );
480 # Do the query and handle errors
481 $ret = $this->doQuery( $commentedSql );
483 # Try reconnecting if the connection was lost
484 if ( false === $ret && $this->wasErrorReissuable() ) {
485 # Transaction is gone, like it or not
486 $this->mTrxLevel = 0;
487 wfDebug( "Connection lost, reconnecting...\n" );
488 if ( $this->ping() ) {
489 wfDebug( "Reconnected\n" );
490 $sqlx = substr( $commentedSql, 0, 500 );
491 $sqlx = strtr( $sqlx, "\t\n", ' ' );
492 global $wgRequestTime;
493 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
494 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
495 $ret = $this->doQuery( $commentedSql );
496 } else {
497 wfDebug( "Failed\n" );
501 if ( false === $ret ) {
502 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
505 if ( isset( $wgProfiler ) ) {
506 wfProfileOut( $queryProf );
507 wfProfileOut( $totalProf );
509 return $this->resultObject( $ret );
513 * The DBMS-dependent part of query()
514 * @param $sql String: SQL query.
515 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
516 * @private
518 /*private*/ abstract function doQuery( $sql );
521 * @param $error String
522 * @param $errno Integer
523 * @param $sql String
524 * @param $fname String
525 * @param $tempIgnore Boolean
527 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
528 global $wgCommandLineMode;
529 # Ignore errors during error handling to avoid infinite recursion
530 $ignore = $this->ignoreErrors( true );
531 ++$this->mErrorCount;
533 if( $ignore || $tempIgnore ) {
534 wfDebug("SQL ERROR (ignored): $error\n");
535 $this->ignoreErrors( $ignore );
536 } else {
537 $sql1line = str_replace( "\n", "\\n", $sql );
538 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
539 wfDebug("SQL ERROR: " . $error . "\n");
540 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
546 * Intended to be compatible with the PEAR::DB wrapper functions.
547 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
549 * ? = scalar value, quoted as necessary
550 * ! = raw SQL bit (a function for instance)
551 * & = filename; reads the file and inserts as a blob
552 * (we don't use this though...)
554 function prepare( $sql, $func = 'Database::prepare' ) {
555 /* MySQL doesn't support prepared statements (yet), so just
556 pack up the query for reference. We'll manually replace
557 the bits later. */
558 return array( 'query' => $sql, 'func' => $func );
561 function freePrepared( $prepared ) {
562 /* No-op for MySQL */
566 * Execute a prepared query with the various arguments
567 * @param $prepared String: the prepared sql
568 * @param $args Mixed: Either an array here, or put scalars as varargs
570 function execute( $prepared, $args = null ) {
571 if( !is_array( $args ) ) {
572 # Pull the var args
573 $args = func_get_args();
574 array_shift( $args );
576 $sql = $this->fillPrepared( $prepared['query'], $args );
577 return $this->query( $sql, $prepared['func'] );
581 * Prepare & execute an SQL statement, quoting and inserting arguments
582 * in the appropriate places.
583 * @param $query String
584 * @param $args ...
586 function safeQuery( $query, $args = null ) {
587 $prepared = $this->prepare( $query, 'Database::safeQuery' );
588 if( !is_array( $args ) ) {
589 # Pull the var args
590 $args = func_get_args();
591 array_shift( $args );
593 $retval = $this->execute( $prepared, $args );
594 $this->freePrepared( $prepared );
595 return $retval;
599 * For faking prepared SQL statements on DBs that don't support
600 * it directly.
601 * @param $preparedQuery String: a 'preparable' SQL statement
602 * @param $args Array of arguments to fill it with
603 * @return string executable SQL
605 function fillPrepared( $preparedQuery, $args ) {
606 reset( $args );
607 $this->preparedArgs =& $args;
608 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
609 array( &$this, 'fillPreparedArg' ), $preparedQuery );
613 * preg_callback func for fillPrepared()
614 * The arguments should be in $this->preparedArgs and must not be touched
615 * while we're doing this.
617 * @param $matches Array
618 * @return String
619 * @private
621 function fillPreparedArg( $matches ) {
622 switch( $matches[1] ) {
623 case '\\?': return '?';
624 case '\\!': return '!';
625 case '\\&': return '&';
627 list( /* $n */ , $arg ) = each( $this->preparedArgs );
628 switch( $matches[1] ) {
629 case '?': return $this->addQuotes( $arg );
630 case '!': return $arg;
631 case '&':
632 # return $this->addQuotes( file_get_contents( $arg ) );
633 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
634 default:
635 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
640 * Free a result object
641 * @param $res Mixed: A SQL result
643 function freeResult( $res ) {
644 # Stub. Might not really need to be overridden, since results should
645 # be freed by PHP when the variable goes out of scope anyway.
649 * Fetch the next row from the given result object, in object form.
650 * Fields can be retrieved with $row->fieldname, with fields acting like
651 * member variables.
653 * @param $res SQL result object as returned from Database::query(), etc.
654 * @return MySQL row object
655 * @throws DBUnexpectedError Thrown if the database returns an error
657 abstract function fetchObject( $res );
660 * Fetch the next row from the given result object, in associative array
661 * form. Fields are retrieved with $row['fieldname'].
663 * @param $res SQL result object as returned from Database::query(), etc.
664 * @return MySQL row object
665 * @throws DBUnexpectedError Thrown if the database returns an error
667 abstract function fetchRow( $res );
670 * Get the number of rows in a result object
671 * @param $res Mixed: A SQL result
673 abstract function numRows( $res );
676 * Get the number of fields in a result object
677 * See documentation for mysql_num_fields()
678 * @param $res Mixed: A SQL result
680 abstract function numFields( $res );
683 * Get a field name in a result object
684 * See documentation for mysql_field_name():
685 * http://www.php.net/mysql_field_name
686 * @param $res Mixed: A SQL result
687 * @param $n Integer
689 abstract function fieldName( $res, $n );
692 * Get the inserted value of an auto-increment row
694 * The value inserted should be fetched from nextSequenceValue()
696 * Example:
697 * $id = $dbw->nextSequenceValue('page_page_id_seq');
698 * $dbw->insert('page',array('page_id' => $id));
699 * $id = $dbw->insertId();
701 abstract function insertId();
704 * Change the position of the cursor in a result object
705 * See mysql_data_seek()
706 * @param $res Mixed: A SQL result
707 * @param $row Mixed: Either MySQL row or ResultWrapper
709 abstract function dataSeek( $res, $row );
712 * Get the last error number
713 * See mysql_errno()
715 abstract function lastErrno();
718 * Get a description of the last error
719 * See mysql_error() for more details
721 abstract function lastError();
724 * Get the number of rows affected by the last write query
725 * See mysql_affected_rows() for more details
727 abstract function affectedRows();
730 * Simple UPDATE wrapper
731 * Usually aborts on failure
732 * If errors are explicitly ignored, returns success
734 * This function exists for historical reasons, Database::update() has a more standard
735 * calling convention and feature set
737 function set( $table, $var, $value, $cond, $fname = 'Database::set' ) {
738 $table = $this->tableName( $table );
739 $sql = "UPDATE $table SET $var = '" .
740 $this->strencode( $value ) . "' WHERE ($cond)";
741 return (bool)$this->query( $sql, $fname );
745 * Simple SELECT wrapper, returns a single field, input must be encoded
746 * Usually aborts on failure
747 * If errors are explicitly ignored, returns FALSE on failure
749 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
750 if ( !is_array( $options ) ) {
751 $options = array( $options );
753 $options['LIMIT'] = 1;
755 $res = $this->select( $table, $var, $cond, $fname, $options );
756 if ( $res === false || !$this->numRows( $res ) ) {
757 return false;
759 $row = $this->fetchRow( $res );
760 if ( $row !== false ) {
761 $this->freeResult( $res );
762 return reset( $row );
763 } else {
764 return false;
769 * Returns an optional USE INDEX clause to go after the table, and a
770 * string to go at the end of the query
772 * @private
774 * @param $options Array: associative array of options to be turned into
775 * an SQL query, valid keys are listed in the function.
776 * @return Array
778 function makeSelectOptions( $options ) {
779 $preLimitTail = $postLimitTail = '';
780 $startOpts = '';
782 $noKeyOptions = array();
783 foreach ( $options as $key => $option ) {
784 if ( is_numeric( $key ) ) {
785 $noKeyOptions[$option] = true;
789 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
790 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
791 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
793 //if (isset($options['LIMIT'])) {
794 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
795 // isset($options['OFFSET']) ? $options['OFFSET']
796 // : false);
799 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
800 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
801 if ( isset( $noKeyOptions['DISTINCT'] ) || isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
803 # Various MySQL extensions
804 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
805 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
806 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
807 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
808 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
809 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
810 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
811 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
813 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
814 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
815 } else {
816 $useIndex = '';
819 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
823 * SELECT wrapper
825 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
826 * @param $vars Mixed: Array or string, field name(s) to be retrieved
827 * @param $conds Mixed: Array or string, condition(s) for WHERE
828 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
829 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
830 * see Database::makeSelectOptions code for list of supported stuff
831 * @param $join_conds Array: Associative array of table join conditions (optional)
832 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
833 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
835 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
837 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
838 return $this->query( $sql, $fname );
842 * SELECT wrapper
844 * @param $table Mixed: Array or string, table name(s) (prefix auto-added)
845 * @param $vars Mixed: Array or string, field name(s) to be retrieved
846 * @param $conds Mixed: Array or string, condition(s) for WHERE
847 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
848 * @param $options Array: Associative array of options (e.g. array('GROUP BY' => 'page_title')),
849 * see Database::makeSelectOptions code for list of supported stuff
850 * @param $join_conds Array: Associative array of table join conditions (optional)
851 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
852 * @return string, the SQL text
854 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
855 if( is_array( $vars ) ) {
856 $vars = implode( ',', $vars );
858 if( !is_array( $options ) ) {
859 $options = array( $options );
861 if( is_array( $table ) ) {
862 if ( !empty($join_conds) || ( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
863 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
864 else
865 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
866 } elseif ($table!='') {
867 if ($table{0}==' ') {
868 $from = ' FROM ' . $table;
869 } else {
870 $from = ' FROM ' . $this->tableName( $table );
872 } else {
873 $from = '';
876 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
878 if( !empty( $conds ) ) {
879 if ( is_array( $conds ) ) {
880 $conds = $this->makeList( $conds, LIST_AND );
882 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
883 } else {
884 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
887 if (isset($options['LIMIT']))
888 $sql = $this->limitResult($sql, $options['LIMIT'],
889 isset($options['OFFSET']) ? $options['OFFSET'] : false);
890 $sql = "$sql $postLimitTail";
892 if (isset($options['EXPLAIN'])) {
893 $sql = 'EXPLAIN ' . $sql;
895 return $sql;
899 * Single row SELECT wrapper
900 * Aborts or returns FALSE on error
902 * @param $table String: table name
903 * @param $vars String: the selected variables
904 * @param $conds Array: a condition map, terms are ANDed together.
905 * Items with numeric keys are taken to be literal conditions
906 * Takes an array of selected variables, and a condition map, which is ANDed
907 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
908 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
909 * $obj- >page_id is the ID of the Astronomy article
910 * @param $fname String: Calling function name
911 * @param $options Array
912 * @param $join_conds Array
914 * @todo migrate documentation to phpdocumentor format
916 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
917 $options['LIMIT'] = 1;
918 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
919 if ( $res === false )
920 return false;
921 if ( !$this->numRows($res) ) {
922 $this->freeResult($res);
923 return false;
925 $obj = $this->fetchObject( $res );
926 $this->freeResult( $res );
927 return $obj;
932 * Estimate rows in dataset
933 * Returns estimated count, based on EXPLAIN output
934 * Takes same arguments as Database::select()
937 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
938 $options['EXPLAIN']=true;
939 $res = $this->select ($table, $vars, $conds, $fname, $options );
940 if ( $res === false )
941 return false;
942 if (!$this->numRows($res)) {
943 $this->freeResult($res);
944 return 0;
947 $rows=1;
949 while( $plan = $this->fetchObject( $res ) ) {
950 $rows *= ($plan->rows > 0)?$plan->rows:1; // avoid resetting to zero
953 $this->freeResult($res);
954 return $rows;
959 * Removes most variables from an SQL query and replaces them with X or N for numbers.
960 * It's only slightly flawed. Don't use for anything important.
962 * @param $sql String: A SQL Query
964 static function generalizeSQL( $sql ) {
965 # This does the same as the regexp below would do, but in such a way
966 # as to avoid crashing php on some large strings.
967 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
969 $sql = str_replace ( "\\\\", '', $sql);
970 $sql = str_replace ( "\\'", '', $sql);
971 $sql = str_replace ( "\\\"", '', $sql);
972 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
973 $sql = preg_replace ('/".*"/s', "'X'", $sql);
975 # All newlines, tabs, etc replaced by single space
976 $sql = preg_replace ( '/\s+/', ' ', $sql);
978 # All numbers => N
979 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
981 return $sql;
985 * Determines whether a field exists in a table
986 * Usually aborts on failure
987 * If errors are explicitly ignored, returns NULL on failure
989 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
990 $table = $this->tableName( $table );
991 $res = $this->query( 'DESCRIBE '.$table, $fname );
992 if ( !$res ) {
993 return NULL;
996 $found = false;
998 while ( $row = $this->fetchObject( $res ) ) {
999 if ( $row->Field == $field ) {
1000 $found = true;
1001 break;
1004 return $found;
1008 * Determines whether an index exists
1009 * Usually aborts on failure
1010 * If errors are explicitly ignored, returns NULL on failure
1012 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1013 $info = $this->indexInfo( $table, $index, $fname );
1014 if ( is_null( $info ) ) {
1015 return NULL;
1016 } else {
1017 return $info !== false;
1023 * Get information about an index into an object
1024 * Returns false if the index does not exist
1026 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1027 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1028 # SHOW INDEX should work for 3.x and up:
1029 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1030 $table = $this->tableName( $table );
1031 $index = $this->indexName( $index );
1032 $sql = 'SHOW INDEX FROM '.$table;
1033 $res = $this->query( $sql, $fname );
1034 if ( !$res ) {
1035 return NULL;
1038 $result = array();
1039 while ( $row = $this->fetchObject( $res ) ) {
1040 if ( $row->Key_name == $index ) {
1041 $result[] = $row;
1044 $this->freeResult($res);
1046 return empty($result) ? false : $result;
1050 * Query whether a given table exists
1052 function tableExists( $table ) {
1053 $table = $this->tableName( $table );
1054 $old = $this->ignoreErrors( true );
1055 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1056 $this->ignoreErrors( $old );
1057 if( $res ) {
1058 $this->freeResult( $res );
1059 return true;
1060 } else {
1061 return false;
1066 * mysql_fetch_field() wrapper
1067 * Returns false if the field doesn't exist
1069 * @param $table
1070 * @param $field
1072 abstract function fieldInfo( $table, $field );
1075 * mysql_field_type() wrapper
1077 function fieldType( $res, $index ) {
1078 if ( $res instanceof ResultWrapper ) {
1079 $res = $res->result;
1081 return mysql_field_type( $res, $index );
1085 * Determines if a given index is unique
1087 function indexUnique( $table, $index ) {
1088 $indexInfo = $this->indexInfo( $table, $index );
1089 if ( !$indexInfo ) {
1090 return NULL;
1092 return !$indexInfo[0]->Non_unique;
1096 * INSERT wrapper, inserts an array into a table
1098 * $a may be a single associative array, or an array of these with numeric keys, for
1099 * multi-row insert.
1101 * Usually aborts on failure
1102 * If errors are explicitly ignored, returns success
1104 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1105 # No rows to insert, easy just return now
1106 if ( !count( $a ) ) {
1107 return true;
1110 $table = $this->tableName( $table );
1111 if ( !is_array( $options ) ) {
1112 $options = array( $options );
1114 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1115 $multi = true;
1116 $keys = array_keys( $a[0] );
1117 } else {
1118 $multi = false;
1119 $keys = array_keys( $a );
1122 $sql = 'INSERT ' . implode( ' ', $options ) .
1123 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1125 if ( $multi ) {
1126 $first = true;
1127 foreach ( $a as $row ) {
1128 if ( $first ) {
1129 $first = false;
1130 } else {
1131 $sql .= ',';
1133 $sql .= '(' . $this->makeList( $row ) . ')';
1135 } else {
1136 $sql .= '(' . $this->makeList( $a ) . ')';
1138 return (bool)$this->query( $sql, $fname );
1142 * Make UPDATE options for the Database::update function
1144 * @private
1145 * @param $options Array: The options passed to Database::update
1146 * @return string
1148 function makeUpdateOptions( $options ) {
1149 if( !is_array( $options ) ) {
1150 $options = array( $options );
1152 $opts = array();
1153 if ( in_array( 'LOW_PRIORITY', $options ) )
1154 $opts[] = $this->lowPriorityOption();
1155 if ( in_array( 'IGNORE', $options ) )
1156 $opts[] = 'IGNORE';
1157 return implode(' ', $opts);
1161 * UPDATE wrapper, takes a condition array and a SET array
1163 * @param $table String: The table to UPDATE
1164 * @param $values Array: An array of values to SET
1165 * @param $conds Array: An array of conditions (WHERE). Use '*' to update all rows.
1166 * @param $fname String: The Class::Function calling this function
1167 * (for the log)
1168 * @param $options Array: An array of UPDATE options, can be one or
1169 * more of IGNORE, LOW_PRIORITY
1170 * @return Boolean
1172 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1173 $table = $this->tableName( $table );
1174 $opts = $this->makeUpdateOptions( $options );
1175 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET );
1176 if ( $conds != '*' ) {
1177 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND );
1179 return $this->query( $sql, $fname );
1183 * Makes an encoded list of strings from an array
1184 * $mode:
1185 * LIST_COMMA - comma separated, no field names
1186 * LIST_AND - ANDed WHERE clause (without the WHERE)
1187 * LIST_OR - ORed WHERE clause (without the WHERE)
1188 * LIST_SET - comma separated with field names, like a SET clause
1189 * LIST_NAMES - comma separated field names
1191 function makeList( $a, $mode = LIST_COMMA ) {
1192 if ( !is_array( $a ) ) {
1193 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1196 $first = true;
1197 $list = '';
1198 foreach ( $a as $field => $value ) {
1199 if ( !$first ) {
1200 if ( $mode == LIST_AND ) {
1201 $list .= ' AND ';
1202 } elseif($mode == LIST_OR) {
1203 $list .= ' OR ';
1204 } else {
1205 $list .= ',';
1207 } else {
1208 $first = false;
1210 if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
1211 $list .= "($value)";
1212 } elseif ( ($mode == LIST_SET) && is_numeric( $field ) ) {
1213 $list .= "$value";
1214 } elseif ( ($mode == LIST_AND || $mode == LIST_OR) && is_array($value) ) {
1215 if( count( $value ) == 0 ) {
1216 throw new MWException( __METHOD__.': empty input' );
1217 } elseif( count( $value ) == 1 ) {
1218 // Special-case single values, as IN isn't terribly efficient
1219 // Don't necessarily assume the single key is 0; we don't
1220 // enforce linear numeric ordering on other arrays here.
1221 $value = array_values( $value );
1222 $list .= $field." = ".$this->addQuotes( $value[0] );
1223 } else {
1224 $list .= $field." IN (".$this->makeList($value).") ";
1226 } elseif( $value === null ) {
1227 if ( $mode == LIST_AND || $mode == LIST_OR ) {
1228 $list .= "$field IS ";
1229 } elseif ( $mode == LIST_SET ) {
1230 $list .= "$field = ";
1232 $list .= 'NULL';
1233 } else {
1234 if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
1235 $list .= "$field = ";
1237 $list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
1240 return $list;
1244 * Bitwise operations
1247 function bitNot($field) {
1248 return "(~$bitField)";
1251 function bitAnd($fieldLeft, $fieldRight) {
1252 return "($fieldLeft & $fieldRight)";
1255 function bitOr($fieldLeft, $fieldRight) {
1256 return "($fieldLeft | $fieldRight)";
1260 * Change the current database
1262 * @return bool Success or failure
1264 function selectDB( $db ) {
1265 # Stub. Shouldn't cause serious problems if it's not overridden, but
1266 # if your database engine supports a concept similar to MySQL's
1267 # databases you may as well. TODO: explain what exactly will fail if
1268 # this is not overridden.
1269 return true;
1273 * Get the current DB name
1275 function getDBname() {
1276 return $this->mDBname;
1280 * Get the server hostname or IP address
1282 function getServer() {
1283 return $this->mServer;
1287 * Format a table name ready for use in constructing an SQL query
1289 * This does two important things: it quotes the table names to clean them up,
1290 * and it adds a table prefix if only given a table name with no quotes.
1292 * All functions of this object which require a table name call this function
1293 * themselves. Pass the canonical name to such functions. This is only needed
1294 * when calling query() directly.
1296 * @param $name String: database table name
1297 * @return String: full database name
1299 function tableName( $name ) {
1300 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1301 # Skip the entire process when we have a string quoted on both ends.
1302 # Note that we check the end so that we will still quote any use of
1303 # use of `database`.table. But won't break things if someone wants
1304 # to query a database table with a dot in the name.
1305 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1307 # Lets test for any bits of text that should never show up in a table
1308 # name. Basically anything like JOIN or ON which are actually part of
1309 # SQL queries, but may end up inside of the table value to combine
1310 # sql. Such as how the API is doing.
1311 # Note that we use a whitespace test rather than a \b test to avoid
1312 # any remote case where a word like on may be inside of a table name
1313 # surrounded by symbols which may be considered word breaks.
1314 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1316 # Split database and table into proper variables.
1317 # We reverse the explode so that database.table and table both output
1318 # the correct table.
1319 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1320 if( isset( $dbDetails[1] ) ) @list( $table, $database ) = $dbDetails;
1321 else @list( $table ) = $dbDetails;
1322 $prefix = $this->mTablePrefix; # Default prefix
1324 # A database name has been specified in input. Quote the table name
1325 # because we don't want any prefixes added.
1326 if( isset($database) ) $table = ( $table[0] == '`' ? $table : "`{$table}`" );
1328 # Note that we use the long format because php will complain in in_array if
1329 # the input is not an array, and will complain in is_array if it is not set.
1330 if( !isset( $database ) # Don't use shared database if pre selected.
1331 && isset( $wgSharedDB ) # We have a shared database
1332 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1333 && isset( $wgSharedTables )
1334 && is_array( $wgSharedTables )
1335 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1336 $database = $wgSharedDB;
1337 $prefix = isset( $wgSharedPrefix ) ? $wgSharedPrefix : $prefix;
1340 # Quote the $database and $table and apply the prefix if not quoted.
1341 if( isset($database) ) $database = ( $database[0] == '`' ? $database : "`{$database}`" );
1342 $table = ( $table[0] == '`' ? $table : "`{$prefix}{$table}`" );
1344 # Merge our database and table into our final table name.
1345 $tableName = ( isset($database) ? "{$database}.{$table}" : "{$table}" );
1347 # We're finished, return.
1348 return $tableName;
1352 * Fetch a number of table names into an array
1353 * This is handy when you need to construct SQL for joins
1355 * Example:
1356 * extract($dbr->tableNames('user','watchlist'));
1357 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1358 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1360 public function tableNames() {
1361 $inArray = func_get_args();
1362 $retVal = array();
1363 foreach ( $inArray as $name ) {
1364 $retVal[$name] = $this->tableName( $name );
1366 return $retVal;
1370 * Fetch a number of table names into an zero-indexed numerical array
1371 * This is handy when you need to construct SQL for joins
1373 * Example:
1374 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1375 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1376 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1378 public function tableNamesN() {
1379 $inArray = func_get_args();
1380 $retVal = array();
1381 foreach ( $inArray as $name ) {
1382 $retVal[] = $this->tableName( $name );
1384 return $retVal;
1388 * @private
1390 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1391 $ret = array();
1392 $retJOIN = array();
1393 $use_index_safe = is_array($use_index) ? $use_index : array();
1394 $join_conds_safe = is_array($join_conds) ? $join_conds : array();
1395 foreach ( $tables as $table ) {
1396 // Is there a JOIN and INDEX clause for this table?
1397 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1398 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1399 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1400 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1401 $retJOIN[] = $tableClause;
1402 // Is there an INDEX clause?
1403 } else if ( isset($use_index_safe[$table]) ) {
1404 $tableClause = $this->tableName( $table );
1405 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1406 $ret[] = $tableClause;
1407 // Is there a JOIN clause?
1408 } else if ( isset($join_conds_safe[$table]) ) {
1409 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1410 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND) . ')';
1411 $retJOIN[] = $tableClause;
1412 } else {
1413 $tableClause = $this->tableName( $table );
1414 $ret[] = $tableClause;
1417 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1418 $straightJoins = !empty($ret) ? implode( ',', $ret ) : "";
1419 $otherJoins = !empty($retJOIN) ? implode( ' ', $retJOIN ) : "";
1420 // Compile our final table clause
1421 return implode(' ',array($straightJoins,$otherJoins) );
1425 * Get the name of an index in a given table
1427 function indexName( $index ) {
1428 // Backwards-compatibility hack
1429 $renamed = array(
1430 'ar_usertext_timestamp' => 'usertext_timestamp',
1431 'un_user_id' => 'user_id',
1432 'un_user_ip' => 'user_ip',
1434 if( isset( $renamed[$index] ) ) {
1435 return $renamed[$index];
1436 } else {
1437 return $index;
1442 * Wrapper for addslashes()
1443 * @param $s String: to be slashed.
1444 * @return String: slashed string.
1446 abstract function strencode( $s );
1449 * If it's a string, adds quotes and backslashes
1450 * Otherwise returns as-is
1452 function addQuotes( $s ) {
1453 if ( $s === null ) {
1454 return 'NULL';
1455 } else {
1456 # This will also quote numeric values. This should be harmless,
1457 # and protects against weird problems that occur when they really
1458 # _are_ strings such as article titles and string->number->string
1459 # conversion is not 1:1.
1460 return "'" . $this->strencode( $s ) . "'";
1465 * Escape string for safe LIKE usage
1467 function escapeLike( $s ) {
1468 $s=str_replace('\\','\\\\',$s);
1469 $s=$this->strencode( $s );
1470 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1471 return $s;
1475 * Returns an appropriately quoted sequence value for inserting a new row.
1476 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1477 * subclass will return an integer, and save the value for insertId()
1479 function nextSequenceValue( $seqName ) {
1480 return NULL;
1484 * USE INDEX clause. Unlikely to be useful for anything but MySQL. This
1485 * is only needed because a) MySQL must be as efficient as possible due to
1486 * its use on Wikipedia, and b) MySQL 4.0 is kind of dumb sometimes about
1487 * which index to pick. Anyway, other databases might have different
1488 * indexes on a given table. So don't bother overriding this unless you're
1489 * MySQL.
1491 function useIndexClause( $index ) {
1492 return '';
1496 * REPLACE query wrapper
1497 * PostgreSQL simulates this with a DELETE followed by INSERT
1498 * $row is the row to insert, an associative array
1499 * $uniqueIndexes is an array of indexes. Each element may be either a
1500 * field name or an array of field names
1502 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1503 * However if you do this, you run the risk of encountering errors which wouldn't have
1504 * occurred in MySQL
1506 * @todo migrate comment to phodocumentor format
1508 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1509 $table = $this->tableName( $table );
1511 # Single row case
1512 if ( !is_array( reset( $rows ) ) ) {
1513 $rows = array( $rows );
1516 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1517 $first = true;
1518 foreach ( $rows as $row ) {
1519 if ( $first ) {
1520 $first = false;
1521 } else {
1522 $sql .= ',';
1524 $sql .= '(' . $this->makeList( $row ) . ')';
1526 return $this->query( $sql, $fname );
1530 * DELETE where the condition is a join
1531 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1533 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1534 * join condition matches, set $conds='*'
1536 * DO NOT put the join condition in $conds
1538 * @param $delTable String: The table to delete from.
1539 * @param $joinTable String: The other table.
1540 * @param $delVar String: The variable to join on, in the first table.
1541 * @param $joinVar String: The variable to join on, in the second table.
1542 * @param $conds Array: Condition array of field names mapped to variables, ANDed together in the WHERE clause
1543 * @param $fname String: Calling function name (use __METHOD__) for logs/profiling
1545 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1546 if ( !$conds ) {
1547 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1550 $delTable = $this->tableName( $delTable );
1551 $joinTable = $this->tableName( $joinTable );
1552 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1553 if ( $conds != '*' ) {
1554 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
1557 return $this->query( $sql, $fname );
1561 * Returns the size of a text field, or -1 for "unlimited"
1563 function textFieldSize( $table, $field ) {
1564 $table = $this->tableName( $table );
1565 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1566 $res = $this->query( $sql, 'Database::textFieldSize' );
1567 $row = $this->fetchObject( $res );
1568 $this->freeResult( $res );
1570 $m = array();
1571 if ( preg_match( '/\((.*)\)/', $row->Type, $m ) ) {
1572 $size = $m[1];
1573 } else {
1574 $size = -1;
1576 return $size;
1580 * A string to insert into queries to show that they're low-priority, like
1581 * MySQL's LOW_PRIORITY. If no such feature exists, return an empty
1582 * string and nothing bad should happen.
1584 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1586 function lowPriorityOption() {
1587 return '';
1591 * DELETE query wrapper
1593 * Use $conds == "*" to delete all rows
1595 function delete( $table, $conds, $fname = 'Database::delete' ) {
1596 if ( !$conds ) {
1597 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1599 $table = $this->tableName( $table );
1600 $sql = "DELETE FROM $table";
1601 if ( $conds != '*' ) {
1602 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1604 return $this->query( $sql, $fname );
1608 * INSERT SELECT wrapper
1609 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1610 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1611 * $conds may be "*" to copy the whole table
1612 * srcTable may be an array of tables.
1614 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1615 $insertOptions = array(), $selectOptions = array() )
1617 $destTable = $this->tableName( $destTable );
1618 if ( is_array( $insertOptions ) ) {
1619 $insertOptions = implode( ' ', $insertOptions );
1621 if( !is_array( $selectOptions ) ) {
1622 $selectOptions = array( $selectOptions );
1624 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1625 if( is_array( $srcTable ) ) {
1626 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1627 } else {
1628 $srcTable = $this->tableName( $srcTable );
1630 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1631 " SELECT $startOpts " . implode( ',', $varMap ) .
1632 " FROM $srcTable $useIndex ";
1633 if ( $conds != '*' ) {
1634 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
1636 $sql .= " $tailOpts";
1637 return $this->query( $sql, $fname );
1641 * Construct a LIMIT query with optional offset. This is used for query
1642 * pages. The SQL should be adjusted so that only the first $limit rows
1643 * are returned. If $offset is provided as well, then the first $offset
1644 * rows should be discarded, and the next $limit rows should be returned.
1645 * If the result of the query is not ordered, then the rows to be returned
1646 * are theoretically arbitrary.
1648 * $sql is expected to be a SELECT, if that makes a difference. For
1649 * UPDATE, limitResultForUpdate should be used.
1651 * The version provided by default works in MySQL and SQLite. It will very
1652 * likely need to be overridden for most other DBMSes.
1654 * @param $sql String: SQL query we will append the limit too
1655 * @param $limit Integer: the SQL limit
1656 * @param $offset Integer the SQL offset (default false)
1658 function limitResult( $sql, $limit, $offset=false ) {
1659 if( !is_numeric( $limit ) ) {
1660 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1662 return "$sql LIMIT "
1663 . ( (is_numeric($offset) && $offset != 0) ? "{$offset}," : "" )
1664 . "{$limit} ";
1666 function limitResultForUpdate( $sql, $num ) {
1667 return $this->limitResult( $sql, $num, 0 );
1671 * Construct a UNION query
1672 * This is used for providing overload point for other DB abstractions
1673 * not compatible with the MySQL syntax.
1674 * @param $sqls Array: SQL statements to combine
1675 * @param $all Boolean: use UNION ALL
1676 * @return String: SQL fragment
1678 function unionQueries($sqls, $all) {
1679 $glue = $all ? ') UNION ALL (' : ') UNION (';
1680 return '('.implode( $glue, $sqls ) . ')';
1684 * Returns an SQL expression for a simple conditional. This doesn't need
1685 * to be overridden unless CASE isn't supported in your DBMS.
1687 * @param $cond String: SQL expression which will result in a boolean value
1688 * @param $trueVal String: SQL expression to return if true
1689 * @param $falseVal String: SQL expression to return if false
1690 * @return String: SQL fragment
1692 function conditional( $cond, $trueVal, $falseVal ) {
1693 return " (CASE WHEN $cond THEN $trueVal ELSE $falseVal END) ";
1697 * Returns a comand for str_replace function in SQL query.
1698 * Uses REPLACE() in MySQL
1700 * @param $orig String: column to modify
1701 * @param $old String: column to seek
1702 * @param $new String: column to replace with
1704 function strreplace( $orig, $old, $new ) {
1705 return "REPLACE({$orig}, {$old}, {$new})";
1709 * Determines if the last failure was due to a deadlock
1711 function wasDeadlock() {
1712 return $this->lastErrno() == 1213;
1716 * Determines if the last query error was something that should be dealt
1717 * with by pinging the connection and reissuing the query
1719 function wasErrorReissuable() {
1720 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
1724 * Perform a deadlock-prone transaction.
1726 * This function invokes a callback function to perform a set of write
1727 * queries. If a deadlock occurs during the processing, the transaction
1728 * will be rolled back and the callback function will be called again.
1730 * Usage:
1731 * $dbw->deadlockLoop( callback, ... );
1733 * Extra arguments are passed through to the specified callback function.
1735 * Returns whatever the callback function returned on its successful,
1736 * iteration, or false on error, for example if the retry limit was
1737 * reached.
1739 function deadlockLoop() {
1740 $myFname = 'Database::deadlockLoop';
1742 $this->begin();
1743 $args = func_get_args();
1744 $function = array_shift( $args );
1745 $oldIgnore = $this->ignoreErrors( true );
1746 $tries = DEADLOCK_TRIES;
1747 if ( is_array( $function ) ) {
1748 $fname = $function[0];
1749 } else {
1750 $fname = $function;
1752 do {
1753 $retVal = call_user_func_array( $function, $args );
1754 $error = $this->lastError();
1755 $errno = $this->lastErrno();
1756 $sql = $this->lastQuery();
1758 if ( $errno ) {
1759 if ( $this->wasDeadlock() ) {
1760 # Retry
1761 usleep( mt_rand( DEADLOCK_DELAY_MIN, DEADLOCK_DELAY_MAX ) );
1762 } else {
1763 $this->reportQueryError( $error, $errno, $sql, $fname );
1766 } while( $this->wasDeadlock() && --$tries > 0 );
1767 $this->ignoreErrors( $oldIgnore );
1768 if ( $tries <= 0 ) {
1769 $this->query( 'ROLLBACK', $myFname );
1770 $this->reportQueryError( $error, $errno, $sql, $fname );
1771 return false;
1772 } else {
1773 $this->query( 'COMMIT', $myFname );
1774 return $retVal;
1779 * Do a SELECT MASTER_POS_WAIT()
1781 * @param $pos MySQLMasterPos object
1782 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
1784 function masterPosWait( MySQLMasterPos $pos, $timeout ) {
1785 $fname = 'Database::masterPosWait';
1786 wfProfileIn( $fname );
1788 # Commit any open transactions
1789 if ( $this->mTrxLevel ) {
1790 $this->immediateCommit();
1793 if ( !is_null( $this->mFakeSlaveLag ) ) {
1794 $wait = intval( ( $pos->pos - microtime(true) + $this->mFakeSlaveLag ) * 1e6 );
1795 if ( $wait > $timeout * 1e6 ) {
1796 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1797 wfProfileOut( $fname );
1798 return -1;
1799 } elseif ( $wait > 0 ) {
1800 wfDebug( "Fake slave waiting $wait us\n" );
1801 usleep( $wait );
1802 wfProfileOut( $fname );
1803 return 1;
1804 } else {
1805 wfDebug( "Fake slave up to date ($wait us)\n" );
1806 wfProfileOut( $fname );
1807 return 0;
1811 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1812 $encFile = $this->addQuotes( $pos->file );
1813 $encPos = intval( $pos->pos );
1814 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1815 $res = $this->doQuery( $sql );
1816 if ( $res && $row = $this->fetchRow( $res ) ) {
1817 $this->freeResult( $res );
1818 wfProfileOut( $fname );
1819 return $row[0];
1820 } else {
1821 wfProfileOut( $fname );
1822 return false;
1827 * Get the position of the master from SHOW SLAVE STATUS
1829 function getSlavePos() {
1830 if ( !is_null( $this->mFakeSlaveLag ) ) {
1831 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag );
1832 wfDebug( __METHOD__.": fake slave pos = $pos\n" );
1833 return $pos;
1835 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1836 $row = $this->fetchObject( $res );
1837 if ( $row ) {
1838 $pos = isset($row->Exec_master_log_pos) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
1839 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
1840 } else {
1841 return false;
1846 * Get the position of the master from SHOW MASTER STATUS
1848 function getMasterPos() {
1849 if ( $this->mFakeMaster ) {
1850 return new MySQLMasterPos( 'fake', microtime( true ) );
1852 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1853 $row = $this->fetchObject( $res );
1854 if ( $row ) {
1855 return new MySQLMasterPos( $row->File, $row->Position );
1856 } else {
1857 return false;
1862 * Begin a transaction, committing any previously open transaction
1864 function begin( $fname = 'Database::begin' ) {
1865 $this->query( 'BEGIN', $fname );
1866 $this->mTrxLevel = 1;
1870 * End a transaction
1872 function commit( $fname = 'Database::commit' ) {
1873 $this->query( 'COMMIT', $fname );
1874 $this->mTrxLevel = 0;
1878 * Rollback a transaction.
1879 * No-op on non-transactional databases.
1881 function rollback( $fname = 'Database::rollback' ) {
1882 $this->query( 'ROLLBACK', $fname, true );
1883 $this->mTrxLevel = 0;
1887 * Begin a transaction, committing any previously open transaction
1888 * @deprecated use begin()
1890 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1891 $this->begin();
1895 * Commit transaction, if one is open
1896 * @deprecated use commit()
1898 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1899 $this->commit();
1903 * Return MW-style timestamp used for MySQL schema
1905 function timestamp( $ts=0 ) {
1906 return wfTimestamp(TS_MW,$ts);
1910 * Local database timestamp format or null
1912 function timestampOrNull( $ts = null ) {
1913 if( is_null( $ts ) ) {
1914 return null;
1915 } else {
1916 return $this->timestamp( $ts );
1921 * @todo document
1923 function resultObject( $result ) {
1924 if( empty( $result ) ) {
1925 return false;
1926 } elseif ( $result instanceof ResultWrapper ) {
1927 return $result;
1928 } elseif ( $result === true ) {
1929 // Successful write query
1930 return $result;
1931 } else {
1932 return new ResultWrapper( $this, $result );
1937 * Return aggregated value alias
1939 function aggregateValue ($valuedata,$valuename='value') {
1940 return $valuename;
1944 * Returns a wikitext link to the DB's website, e.g.,
1945 * return "[http://www.mysql.com/ MySQL]";
1946 * Should probably be overridden to at least contain plain text, if for
1947 * some reason your database has no website.
1949 * @return String: wikitext of a link to the server software's web site
1951 function getSoftwareLink() {
1952 return '(no software link given)';
1956 * A string describing the current software version, like from
1957 * mysql_get_server_info(). Will be listed on Special:Version, etc.
1959 * @return String: Version information from the database
1961 abstract function getServerVersion();
1964 * Ping the server and try to reconnect if it there is no connection
1966 * @return bool Success or failure
1968 function ping() {
1969 # Stub. Not essential to override.
1970 return true;
1974 * Get slave lag.
1975 * At the moment, this will only work if the DB user has the PROCESS privilege
1977 function getLag() {
1978 if ( !is_null( $this->mFakeSlaveLag ) ) {
1979 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
1980 return $this->mFakeSlaveLag;
1982 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
1983 # Find slave SQL thread
1984 while ( $row = $this->fetchObject( $res ) ) {
1985 /* This should work for most situations - when default db
1986 * for thread is not specified, it had no events executed,
1987 * and therefore it doesn't know yet how lagged it is.
1989 * Relay log I/O thread does not select databases.
1991 if ( $row->User == 'system user' &&
1992 $row->State != 'Waiting for master to send event' &&
1993 $row->State != 'Connecting to master' &&
1994 $row->State != 'Queueing master event to the relay log' &&
1995 $row->State != 'Waiting for master update' &&
1996 $row->State != 'Requesting binlog dump'
1998 # This is it, return the time (except -ve)
1999 if ( $row->Time > 0x7fffffff ) {
2000 return false;
2001 } else {
2002 return $row->Time;
2006 return false;
2010 * Get status information from SHOW STATUS in an associative array
2012 function getStatus($which="%") {
2013 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2014 $status = array();
2015 while ( $row = $this->fetchObject( $res ) ) {
2016 $status[$row->Variable_name] = $row->Value;
2018 return $status;
2022 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2024 function maxListLen() {
2025 return 0;
2028 function encodeBlob($b) {
2029 return $b;
2032 function decodeBlob($b) {
2033 return $b;
2037 * Override database's default connection timeout. May be useful for very
2038 * long batch queries such as full-wiki dumps, where a single query reads
2039 * out over hours or days. May or may not be necessary for non-MySQL
2040 * databases. For most purposes, leaving it as a no-op should be fine.
2042 * @param $timeout Integer in seconds
2044 public function setTimeout( $timeout ) {}
2047 * Read and execute SQL commands from a file.
2048 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2049 * @param $filename String: File name to open
2050 * @param $lineCallback Callback: Optional function called before reading each line
2051 * @param $resultCallback Callback: Optional function called for each MySQL result
2053 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2054 $fp = fopen( $filename, 'r' );
2055 if ( false === $fp ) {
2056 throw new MWException( "Could not open \"{$filename}\".\n" );
2058 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2059 fclose( $fp );
2060 return $error;
2064 * Read and execute commands from an open file handle
2065 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2066 * @param $fp String: File handle
2067 * @param $lineCallback Callback: Optional function called before reading each line
2068 * @param $resultCallback Callback: Optional function called for each MySQL result
2070 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2071 $cmd = "";
2072 $done = false;
2073 $dollarquote = false;
2075 while ( ! feof( $fp ) ) {
2076 if ( $lineCallback ) {
2077 call_user_func( $lineCallback );
2079 $line = trim( fgets( $fp, 1024 ) );
2080 $sl = strlen( $line ) - 1;
2082 if ( $sl < 0 ) { continue; }
2083 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2085 ## Allow dollar quoting for function declarations
2086 if (substr($line,0,4) == '$mw$') {
2087 if ($dollarquote) {
2088 $dollarquote = false;
2089 $done = true;
2091 else {
2092 $dollarquote = true;
2095 else if (!$dollarquote) {
2096 if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
2097 $done = true;
2098 $line = substr( $line, 0, $sl );
2102 if ( '' != $cmd ) { $cmd .= ' '; }
2103 $cmd .= "$line\n";
2105 if ( $done ) {
2106 $cmd = str_replace(';;', ";", $cmd);
2107 $cmd = $this->replaceVars( $cmd );
2108 $res = $this->query( $cmd, __METHOD__ );
2109 if ( $resultCallback ) {
2110 call_user_func( $resultCallback, $res, $this );
2113 if ( false === $res ) {
2114 $err = $this->lastError();
2115 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2118 $cmd = '';
2119 $done = false;
2122 return true;
2127 * Replace variables in sourced SQL
2129 protected function replaceVars( $ins ) {
2130 $varnames = array(
2131 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2132 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2133 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2136 // Ordinary variables
2137 foreach ( $varnames as $var ) {
2138 if( isset( $GLOBALS[$var] ) ) {
2139 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2140 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2141 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2142 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2146 // Table prefixes
2147 $ins = preg_replace_callback( '!/\*(?:\$wgDBprefix|_)\*/([a-zA-Z_0-9]*)!',
2148 array( $this, 'tableNameCallback' ), $ins );
2150 // Index names
2151 $ins = preg_replace_callback( '!/\*i\*/([a-zA-Z_0-9]*)!',
2152 array( $this, 'indexNameCallback' ), $ins );
2153 return $ins;
2157 * Table name callback
2158 * @private
2160 protected function tableNameCallback( $matches ) {
2161 return $this->tableName( $matches[1] );
2165 * Index name callback
2167 protected function indexNameCallback( $matches ) {
2168 return $this->indexName( $matches[1] );
2172 * Build a concatenation list to feed into a SQL query
2174 function buildConcat( $stringList ) {
2175 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2179 * Acquire a named lock
2181 * Abstracted from Filestore::lock() so child classes can implement for
2182 * their own needs.
2184 * @param $lockName String: Name of lock to aquire
2185 * @param $method String: Name of method calling us
2186 * @return bool
2188 abstract public function lock( $lockName, $method, $timeout = 5 );
2191 * Release a lock.
2193 * @param $lockName String: Name of lock to release
2194 * @param $method String: Name of method calling us
2196 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
2197 * @return Returns 1 if the lock was released, 0 if the lock was not established
2198 * by this thread (in which case the lock is not released), and NULL if the named
2199 * lock did not exist
2201 abstract public function unlock( $lockName, $method );
2204 * Lock specific tables
2206 * @param $read Array of tables to lock for read access
2207 * @param $write Array of tables to lock for write access
2208 * @param $method String name of caller
2210 abstract public function lockTables( $read, $write, $method );
2213 * Unlock specific tables
2215 * @param $method String the caller
2217 abstract public function unlockTables( $method );
2220 * Get search engine class. All subclasses of this
2221 * need to implement this if they wish to use searching.
2223 * @return String
2225 public function getSearchEngine() {
2226 return "SearchMySQL";
2230 * Allow or deny "big selects" for this session only. This is done by setting
2231 * the sql_big_selects session variable.
2233 * This is a MySQL-specific feature.
2235 * @param mixed $value true for allow, false for deny, or "default" to restore the initial value
2237 public function setBigSelects( $value = true ) {
2238 if ( $value === 'default' ) {
2239 if ( $this->mDefaultBigSelects === null ) {
2240 # Function hasn't been called before so it must already be set to the default
2241 return;
2242 } else {
2243 $value = $this->mDefaultBigSelects;
2245 } elseif ( $this->mDefaultBigSelects === null ) {
2246 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
2248 $encValue = $value ? '1' : '0';
2249 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
2254 /******************************************************************************
2255 * Utility classes
2256 *****************************************************************************/
2259 * Utility class.
2260 * @ingroup Database
2262 class DBObject {
2263 public $mData;
2265 function DBObject($data) {
2266 $this->mData = $data;
2269 function isLOB() {
2270 return false;
2273 function data() {
2274 return $this->mData;
2279 * Utility class
2280 * @ingroup Database
2282 * This allows us to distinguish a blob from a normal string and an array of strings
2284 class Blob {
2285 private $mData;
2286 function __construct($data) {
2287 $this->mData = $data;
2289 function fetch() {
2290 return $this->mData;
2295 * Utility class.
2296 * @ingroup Database
2298 class MySQLField {
2299 private $name, $tablename, $default, $max_length, $nullable,
2300 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2301 function __construct ($info) {
2302 $this->name = $info->name;
2303 $this->tablename = $info->table;
2304 $this->default = $info->def;
2305 $this->max_length = $info->max_length;
2306 $this->nullable = !$info->not_null;
2307 $this->is_pk = $info->primary_key;
2308 $this->is_unique = $info->unique_key;
2309 $this->is_multiple = $info->multiple_key;
2310 $this->is_key = ($this->is_pk || $this->is_unique || $this->is_multiple);
2311 $this->type = $info->type;
2314 function name() {
2315 return $this->name;
2318 function tableName() {
2319 return $this->tableName;
2322 function defaultValue() {
2323 return $this->default;
2326 function maxLength() {
2327 return $this->max_length;
2330 function nullable() {
2331 return $this->nullable;
2334 function isKey() {
2335 return $this->is_key;
2338 function isMultipleKey() {
2339 return $this->is_multiple;
2342 function type() {
2343 return $this->type;
2347 /******************************************************************************
2348 * Error classes
2349 *****************************************************************************/
2352 * Database error base class
2353 * @ingroup Database
2355 class DBError extends MWException {
2356 public $db;
2359 * Construct a database error
2360 * @param $db Database object which threw the error
2361 * @param $error A simple error message to be used for debugging
2363 function __construct( DatabaseBase &$db, $error ) {
2364 $this->db =& $db;
2365 parent::__construct( $error );
2370 * @ingroup Database
2372 class DBConnectionError extends DBError {
2373 public $error;
2375 function __construct( DatabaseBase &$db, $error = 'unknown error' ) {
2376 $msg = 'DB connection error';
2377 if ( trim( $error ) != '' ) {
2378 $msg .= ": $error";
2380 $this->error = $error;
2381 parent::__construct( $db, $msg );
2384 function useOutputPage() {
2385 // Not likely to work
2386 return false;
2389 function useMessageCache() {
2390 // Not likely to work
2391 return false;
2394 function getText() {
2395 return $this->getMessage() . "\n";
2398 function getLogMessage() {
2399 # Don't send to the exception log
2400 return false;
2403 function getPageTitle() {
2404 global $wgSitename, $wgLang;
2405 $header = "$wgSitename has a problem";
2406 if ( $wgLang instanceof Language ) {
2407 $header = htmlspecialchars( $wgLang->getMessage( 'dberr-header' ) );
2410 return $header;
2413 function getHTML() {
2414 global $wgLang, $wgMessageCache, $wgUseFileCache;
2416 $sorry = 'Sorry! This site is experiencing technical difficulties.';
2417 $again = 'Try waiting a few minutes and reloading.';
2418 $info = '(Can\'t contact the database server: $1)';
2420 if ( $wgLang instanceof Language ) {
2421 $sorry = htmlspecialchars( $wgLang->getMessage( 'dberr-problems' ) );
2422 $again = htmlspecialchars( $wgLang->getMessage( 'dberr-again' ) );
2423 $info = htmlspecialchars( $wgLang->getMessage( 'dberr-info' ) );
2426 # No database access
2427 if ( is_object( $wgMessageCache ) ) {
2428 $wgMessageCache->disable();
2431 if ( trim( $this->error ) == '' ) {
2432 $this->error = $this->db->getProperty('mServer');
2435 $noconnect = "<p><strong>$sorry</strong><br />$again</p><p><small>$info</small></p>";
2436 $text = str_replace( '$1', $this->error, $noconnect );
2439 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2440 $text .= '</p><p>Backtrace:</p><p>' .
2441 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2442 "</p>\n";
2445 $extra = $this->searchForm();
2447 if( $wgUseFileCache ) {
2448 try {
2449 $cache = $this->fileCachedPage();
2450 # Cached version on file system?
2451 if( $cache !== null ) {
2452 # Hack: extend the body for error messages
2453 $cache = str_replace( array('</html>','</body>'), '', $cache );
2454 # Add cache notice...
2455 $cachederror = "This is a cached copy of the requested page, and may not be up to date. ";
2456 # Localize it if possible...
2457 if( $wgLang instanceof Language ) {
2458 $cachederror = htmlspecialchars( $wgLang->getMessage( 'dberr-cachederror' ) );
2460 $warning = "<div style='color:red;font-size:150%;font-weight:bold;'>$cachederror</div>";
2461 # Output cached page with notices on bottom and re-close body
2462 return "{$cache}{$warning}<hr />$text<hr />$extra</body></html>";
2464 } catch( MWException $e ) {
2465 // Do nothing, just use the default page
2468 # Headers needed here - output is just the error message
2469 return $this->htmlHeader()."$text<hr />$extra".$this->htmlFooter();
2472 function searchForm() {
2473 global $wgSitename, $wgServer, $wgLang, $wgInputEncoding;
2474 $usegoogle = "You can try searching via Google in the meantime.";
2475 $outofdate = "Note that their indexes of our content may be out of date.";
2476 $googlesearch = "Search";
2478 if ( $wgLang instanceof Language ) {
2479 $usegoogle = htmlspecialchars( $wgLang->getMessage( 'dberr-usegoogle' ) );
2480 $outofdate = htmlspecialchars( $wgLang->getMessage( 'dberr-outofdate' ) );
2481 $googlesearch = htmlspecialchars( $wgLang->getMessage( 'searchbutton' ) );
2484 $search = htmlspecialchars(@$_REQUEST['search']);
2486 $trygoogle = <<<EOT
2487 <div style="margin: 1.5em">$usegoogle<br />
2488 <small>$outofdate</small></div>
2489 <!-- SiteSearch Google -->
2490 <form method="get" action="http://www.google.com/search" id="googlesearch">
2491 <input type="hidden" name="domains" value="$wgServer" />
2492 <input type="hidden" name="num" value="50" />
2493 <input type="hidden" name="ie" value="$wgInputEncoding" />
2494 <input type="hidden" name="oe" value="$wgInputEncoding" />
2496 <img src="http://www.google.com/logos/Logo_40wht.gif" alt="" style="float:left; margin-left: 1.5em; margin-right: 1.5em;" />
2498 <input type="text" name="q" size="31" maxlength="255" value="$search" />
2499 <input type="submit" name="btnG" value="$googlesearch" />
2500 <div>
2501 <input type="radio" name="sitesearch" id="gwiki" value="$wgServer" checked="checked" /><label for="gwiki">$wgSitename</label>
2502 <input type="radio" name="sitesearch" id="gWWW" value="" /><label for="gWWW">WWW</label>
2503 </div>
2504 </form>
2505 <!-- SiteSearch Google -->
2506 EOT;
2507 return $trygoogle;
2510 function fileCachedPage() {
2511 global $wgTitle, $title, $wgLang, $wgOut;
2512 if( $wgOut->isDisabled() ) return; // Done already?
2513 $mainpage = 'Main Page';
2514 if ( $wgLang instanceof Language ) {
2515 $mainpage = htmlspecialchars( $wgLang->getMessage( 'mainpage' ) );
2518 if( $wgTitle ) {
2519 $t =& $wgTitle;
2520 } elseif( $title ) {
2521 $t = Title::newFromURL( $title );
2522 } else {
2523 $t = Title::newFromText( $mainpage );
2526 $cache = new HTMLFileCache( $t );
2527 if( $cache->isFileCached() ) {
2528 return $cache->fetchPageText();
2529 } else {
2530 return '';
2534 function htmlBodyOnly() {
2535 return true;
2541 * @ingroup Database
2543 class DBQueryError extends DBError {
2544 public $error, $errno, $sql, $fname;
2546 function __construct( DatabaseBase &$db, $error, $errno, $sql, $fname ) {
2547 $message = "A database error has occurred\n" .
2548 "Query: $sql\n" .
2549 "Function: $fname\n" .
2550 "Error: $errno $error\n";
2552 parent::__construct( $db, $message );
2553 $this->error = $error;
2554 $this->errno = $errno;
2555 $this->sql = $sql;
2556 $this->fname = $fname;
2559 function getText() {
2560 if ( $this->useMessageCache() ) {
2561 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2562 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) ) . "\n";
2563 } else {
2564 return $this->getMessage();
2568 function getSQL() {
2569 global $wgShowSQLErrors;
2570 if( !$wgShowSQLErrors ) {
2571 return $this->msg( 'sqlhidden', 'SQL hidden' );
2572 } else {
2573 return $this->sql;
2577 function getLogMessage() {
2578 # Don't send to the exception log
2579 return false;
2582 function getPageTitle() {
2583 return $this->msg( 'databaseerror', 'Database error' );
2586 function getHTML() {
2587 if ( $this->useMessageCache() ) {
2588 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2589 htmlspecialchars( $this->fname ), $this->errno, htmlspecialchars( $this->error ) );
2590 } else {
2591 return nl2br( htmlspecialchars( $this->getMessage() ) );
2597 * @ingroup Database
2599 class DBUnexpectedError extends DBError {}
2603 * Result wrapper for grabbing data queried by someone else
2604 * @ingroup Database
2606 class ResultWrapper implements Iterator {
2607 var $db, $result, $pos = 0, $currentRow = null;
2610 * Create a new result object from a result resource and a Database object
2612 function ResultWrapper( $database, $result ) {
2613 $this->db = $database;
2614 if ( $result instanceof ResultWrapper ) {
2615 $this->result = $result->result;
2616 } else {
2617 $this->result = $result;
2622 * Get the number of rows in a result object
2624 function numRows() {
2625 return $this->db->numRows( $this );
2629 * Fetch the next row from the given result object, in object form.
2630 * Fields can be retrieved with $row->fieldname, with fields acting like
2631 * member variables.
2633 * @param $res SQL result object as returned from Database::query(), etc.
2634 * @return MySQL row object
2635 * @throws DBUnexpectedError Thrown if the database returns an error
2637 function fetchObject() {
2638 return $this->db->fetchObject( $this );
2642 * Fetch the next row from the given result object, in associative array
2643 * form. Fields are retrieved with $row['fieldname'].
2645 * @param $res SQL result object as returned from Database::query(), etc.
2646 * @return MySQL row object
2647 * @throws DBUnexpectedError Thrown if the database returns an error
2649 function fetchRow() {
2650 return $this->db->fetchRow( $this );
2654 * Free a result object
2656 function free() {
2657 $this->db->freeResult( $this );
2658 unset( $this->result );
2659 unset( $this->db );
2663 * Change the position of the cursor in a result object
2664 * See mysql_data_seek()
2666 function seek( $row ) {
2667 $this->db->dataSeek( $this, $row );
2670 /*********************
2671 * Iterator functions
2672 * Note that using these in combination with the non-iterator functions
2673 * above may cause rows to be skipped or repeated.
2676 function rewind() {
2677 if ($this->numRows()) {
2678 $this->db->dataSeek($this, 0);
2680 $this->pos = 0;
2681 $this->currentRow = null;
2684 function current() {
2685 if ( is_null( $this->currentRow ) ) {
2686 $this->next();
2688 return $this->currentRow;
2691 function key() {
2692 return $this->pos;
2695 function next() {
2696 $this->pos++;
2697 $this->currentRow = $this->fetchObject();
2698 return $this->currentRow;
2701 function valid() {
2702 return $this->current() !== false;