1ca563ba5493b2657ffed5bbe399cc08b8e6e921
3 * @defgroup Database Database
7 * This file deals with MySQL interface functions
8 * and query specifics/optimisations
11 /** Number of times to re-try an operation in case of deadlock */
12 define( 'DEADLOCK_TRIES', 4 );
13 /** Minimum time to wait before retry, in microseconds */
14 define( 'DEADLOCK_DELAY_MIN', 500000 );
15 /** Maximum time to wait before retry */
16 define( 'DEADLOCK_DELAY_MAX', 1500000 );
19 * Database abstraction object
24 #------------------------------------------------------------------------------
26 #------------------------------------------------------------------------------
28 protected $mLastQuery = '';
29 protected $mPHPError = false;
31 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
32 protected $mOpened = false;
34 protected $mFailFunction;
35 protected $mTablePrefix;
37 protected $mTrxLevel = 0;
38 protected $mErrorCount = 0;
39 protected $mLBInfo = array();
40 protected $mFakeSlaveLag = null, $mFakeMaster = false;
42 #------------------------------------------------------------------------------
44 #------------------------------------------------------------------------------
45 # These optionally set a variable and return the previous state
48 * Fail function, takes a Database as a parameter
49 * Set to false for default, 1 for ignore errors
51 function failFunction( $function = NULL ) {
52 return wfSetVar( $this->mFailFunction
, $function );
56 * Output page, used for reporting errors
57 * FALSE means discard output
59 function setOutputPage( $out ) {
60 wfDeprecated( __METHOD__
);
64 * Boolean, controls output of large amounts of debug information
66 function debug( $debug = NULL ) {
67 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
71 * Turns buffering of SQL result sets on (true) or off (false).
72 * Default is "on" and it should not be changed without good reasons.
74 function bufferResults( $buffer = NULL ) {
75 if ( is_null( $buffer ) ) {
76 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
78 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
83 * Turns on (false) or off (true) the automatic generation and sending
84 * of a "we're sorry, but there has been a database error" page on
85 * database errors. Default is on (false). When turned off, the
86 * code should use lastErrno() and lastError() to handle the
87 * situation as appropriate.
89 function ignoreErrors( $ignoreErrors = NULL ) {
90 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
94 * The current depth of nested transactions
95 * @param $level Integer: , default NULL.
97 function trxLevel( $level = NULL ) {
98 return wfSetVar( $this->mTrxLevel
, $level );
102 * Number of errors logged, only useful when errors are ignored
104 function errorCount( $count = NULL ) {
105 return wfSetVar( $this->mErrorCount
, $count );
108 function tablePrefix( $prefix = null ) {
109 return wfSetVar( $this->mTablePrefix
, $prefix );
113 * Properties passed down from the server info array of the load balancer
115 function getLBInfo( $name = NULL ) {
116 if ( is_null( $name ) ) {
117 return $this->mLBInfo
;
119 if ( array_key_exists( $name, $this->mLBInfo
) ) {
120 return $this->mLBInfo
[$name];
127 function setLBInfo( $name, $value = NULL ) {
128 if ( is_null( $value ) ) {
129 $this->mLBInfo
= $name;
131 $this->mLBInfo
[$name] = $value;
136 * Set lag time in seconds for a fake slave
138 function setFakeSlaveLag( $lag ) {
139 $this->mFakeSlaveLag
= $lag;
143 * Make this connection a fake master
145 function setFakeMaster( $enabled = true ) {
146 $this->mFakeMaster
= $enabled;
150 * Returns true if this database supports (and uses) cascading deletes
152 function cascadingDeletes() {
157 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
159 function cleanupTriggers() {
164 * Returns true if this database is strict about what can be put into an IP field.
165 * Specifically, it uses a NULL value instead of an empty string.
167 function strictIPs() {
172 * Returns true if this database uses timestamps rather than integers
174 function realTimestamps() {
179 * Returns true if this database does an implicit sort when doing GROUP BY
181 function implicitGroupby() {
186 * Returns true if this database does an implicit order by when the column has an index
187 * For example: SELECT page_title FROM page LIMIT 1
189 function implicitOrderby() {
194 * Returns true if this database can do a native search on IP columns
195 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
197 function searchableIPs() {
202 * Returns true if this database can use functional indexes
204 function functionalIndexes() {
209 * Return the last query that went through Database::query()
212 function lastQuery() { return $this->mLastQuery
; }
215 * Is a connection to the database open?
218 function isOpen() { return $this->mOpened
; }
220 function setFlag( $flag ) {
221 $this->mFlags |
= $flag;
224 function clearFlag( $flag ) {
225 $this->mFlags
&= ~
$flag;
228 function getFlag( $flag ) {
229 return !!($this->mFlags
& $flag);
233 * General read-only accessor
235 function getProperty( $name ) {
239 function getWikiID() {
240 if( $this->mTablePrefix
) {
241 return "{$this->mDBname}-{$this->mTablePrefix}";
243 return $this->mDBname
;
247 #------------------------------------------------------------------------------
249 #------------------------------------------------------------------------------
253 * @param string $server database server host
254 * @param string $user database user name
255 * @param string $password database user password
256 * @param string $dbname database name
257 * @param failFunction
259 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
261 function __construct( $server = false, $user = false, $password = false, $dbName = false,
262 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
264 global $wgOut, $wgDBprefix, $wgCommandLineMode;
265 # Can't get a reference if it hasn't been set yet
266 if ( !isset( $wgOut ) ) {
270 $this->mFailFunction
= $failFunction;
271 $this->mFlags
= $flags;
273 if ( $this->mFlags
& DBO_DEFAULT
) {
274 if ( $wgCommandLineMode ) {
275 $this->mFlags
&= ~DBO_TRX
;
277 $this->mFlags |
= DBO_TRX
;
282 // Faster read-only access
283 if ( wfReadOnly() ) {
284 $this->mFlags |= DBO_PERSISTENT;
285 $this->mFlags &= ~DBO_TRX;
288 /** Get the default table prefix*/
289 if ( $tablePrefix == 'get from global' ) {
290 $this->mTablePrefix
= $wgDBprefix;
292 $this->mTablePrefix
= $tablePrefix;
296 $this->open( $server, $user, $password, $dbName );
302 * @param failFunction
305 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
307 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
311 * Usually aborts on failure
312 * If the failFunction is set to a non-zero integer, returns success
314 function open( $server, $user, $password, $dbName ) {
315 global $wgAllDBsAreLocalhost;
316 wfProfileIn( __METHOD__
);
318 # Test for missing mysql.so
319 # First try to load it
320 if (!@extension_loaded
('mysql')) {
325 # Otherwise we get a suppressed fatal error, which is very hard to track down
326 if ( !function_exists( 'mysql_connect' ) ) {
327 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
330 # Debugging hack -- fake cluster
331 if ( $wgAllDBsAreLocalhost ) {
332 $realServer = 'localhost';
334 $realServer = $server;
337 $this->mServer
= $server;
338 $this->mUser
= $user;
339 $this->mPassword
= $password;
340 $this->mDBname
= $dbName;
344 wfProfileIn("dbconnect-$server");
346 # The kernel's default SYN retransmission period is far too slow for us,
347 # so we use a short timeout plus a manual retry. Retrying means that a small
348 # but finite rate of SYN packet loss won't cause user-visible errors.
349 $this->mConn
= false;
350 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
355 $this->installErrorHandler();
356 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
360 if ( $this->mFlags
& DBO_PERSISTENT
) {
361 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
363 # Create a new connection...
364 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
366 if ($this->mConn
=== false) {
368 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
371 $phpError = $this->restoreErrorHandler();
372 # Always log connection errors
373 if ( !$this->mConn
) {
374 $error = $this->lastError();
378 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
379 wfDebug( "DB connection error\n" );
380 wfDebug( "Server: $server, User: $user, Password: " .
381 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
385 wfProfileOut("dbconnect-$server");
387 if ( $dbName != '' && $this->mConn
!== false ) {
388 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
390 $error = "Error selecting database $dbName on server {$this->mServer} " .
391 "from client host " . wfHostname() . "\n";
392 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
397 $success = (bool)$this->mConn
;
401 $version = $this->getServerVersion();
402 if ( version_compare( $version, '4.1' ) >= 0 ) {
403 // Tell the server we're communicating with it in UTF-8.
404 // This may engage various charset conversions.
407 $this->query( 'SET NAMES utf8', __METHOD__
);
409 // Turn off strict mode
410 $this->query( "SET sql_mode = ''", __METHOD__
);
413 // Turn off strict mode if it is on
415 $this->reportConnectionError( $phpError );
418 $this->mOpened
= $success;
419 wfProfileOut( __METHOD__
);
424 protected function installErrorHandler() {
425 $this->mPHPError
= false;
426 $this->htmlErrors
= ini_set( 'html_errors', '0' );
427 set_error_handler( array( $this, 'connectionErrorHandler' ) );
430 protected function restoreErrorHandler() {
431 restore_error_handler();
432 if ( $this->htmlErrors
!== false ) {
433 ini_set( 'html_errors', $this->htmlErrors
);
435 if ( $this->mPHPError
) {
436 $error = preg_replace( '!\[<a.*</a>\]!', '', $this->mPHPError
);
437 $error = preg_replace( '!^.*?:(.*)$!', '$1', $error );
444 protected function connectionErrorHandler( $errno, $errstr ) {
445 $this->mPHPError
= $errstr;
449 * Closes a database connection.
450 * if it is open : commits any open transactions
452 * @return bool operation success. true if already closed.
456 $this->mOpened
= false;
457 if ( $this->mConn
) {
458 if ( $this->trxLevel() ) {
459 $this->immediateCommit();
461 return mysql_close( $this->mConn
);
468 * @param string $error fallback error message, used if none is given by MySQL
470 function reportConnectionError( $error = 'Unknown error' ) {
471 $myError = $this->lastError();
476 if ( $this->mFailFunction
) {
477 # Legacy error handling method
478 if ( !is_int( $this->mFailFunction
) ) {
479 $ff = $this->mFailFunction
;
480 $ff( $this, $error );
484 throw new DBConnectionError( $this, $error );
489 * Usually aborts on failure. If errors are explicitly ignored, returns success.
491 * @param $sql String: SQL query
492 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
493 * comment (you can use __METHOD__ or add some extra info)
494 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
495 * maybe best to catch the exception instead?
496 * @return true for a successful write query, ResultWrapper object for a successful read query,
497 * or false on failure if $tempIgnore set
498 * @throws DBQueryError Thrown when the database returns an error of any kind
500 public function query( $sql, $fname = '', $tempIgnore = false ) {
503 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
504 if ( isset( $wgProfiler ) ) {
505 # generalizeSQL will probably cut down the query to reasonable
506 # logging size most of the time. The substr is really just a sanity check.
508 # Who's been wasting my precious column space? -- TS
509 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
512 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
513 $totalProf = 'Database::query-master';
515 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
516 $totalProf = 'Database::query';
518 wfProfileIn( $totalProf );
519 wfProfileIn( $queryProf );
522 $this->mLastQuery
= $sql;
524 # Add a comment for easy SHOW PROCESSLIST interpretation
527 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
528 $userName = $wgUser->getName();
529 if ( mb_strlen( $userName ) > 15 ) {
530 $userName = mb_substr( $userName, 0, 15 ) . '...';
532 $userName = str_replace( '/', '', $userName );
536 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
538 # $commentedSql = $sql;
541 # If DBO_TRX is set, start a transaction
542 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
543 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
544 // avoid establishing transactions for SHOW and SET statements too -
545 // that would delay transaction initializations to once connection
546 // is really used by application
547 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
548 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
552 if ( $this->debug() ) {
553 $sqlx = substr( $commentedSql, 0, 500 );
554 $sqlx = strtr( $sqlx, "\t\n", ' ' );
556 wfDebug( "SQL-master: $sqlx\n" );
558 wfDebug( "SQL: $sqlx\n" );
562 # Do the query and handle errors
563 $ret = $this->doQuery( $commentedSql );
565 # Try reconnecting if the connection was lost
566 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
567 # Transaction is gone, like it or not
568 $this->mTrxLevel
= 0;
569 wfDebug( "Connection lost, reconnecting...\n" );
570 if ( $this->ping() ) {
571 wfDebug( "Reconnected\n" );
572 $sqlx = substr( $commentedSql, 0, 500 );
573 $sqlx = strtr( $sqlx, "\t\n", ' ' );
574 global $wgRequestTime;
575 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
576 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
577 $ret = $this->doQuery( $commentedSql );
579 wfDebug( "Failed\n" );
583 if ( false === $ret ) {
584 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
587 if ( isset( $wgProfiler ) ) {
588 wfProfileOut( $queryProf );
589 wfProfileOut( $totalProf );
591 return $this->resultObject( $ret );
595 * The DBMS-dependent part of query()
596 * @param $sql String: SQL query.
597 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
600 /*private*/ function doQuery( $sql ) {
601 if( $this->bufferResults() ) {
602 $ret = mysql_query( $sql, $this->mConn
);
604 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
613 * @param string $fname
614 * @param bool $tempIgnore
616 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
617 global $wgCommandLineMode;
618 # Ignore errors during error handling to avoid infinite recursion
619 $ignore = $this->ignoreErrors( true );
620 ++
$this->mErrorCount
;
622 if( $ignore ||
$tempIgnore ) {
623 wfDebug("SQL ERROR (ignored): $error\n");
624 $this->ignoreErrors( $ignore );
626 $sql1line = str_replace( "\n", "\\n", $sql );
627 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
628 wfDebug("SQL ERROR: " . $error . "\n");
629 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
635 * Intended to be compatible with the PEAR::DB wrapper functions.
636 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
638 * ? = scalar value, quoted as necessary
639 * ! = raw SQL bit (a function for instance)
640 * & = filename; reads the file and inserts as a blob
641 * (we don't use this though...)
643 function prepare( $sql, $func = 'Database::prepare' ) {
644 /* MySQL doesn't support prepared statements (yet), so just
645 pack up the query for reference. We'll manually replace
647 return array( 'query' => $sql, 'func' => $func );
650 function freePrepared( $prepared ) {
651 /* No-op for MySQL */
655 * Execute a prepared query with the various arguments
656 * @param string $prepared the prepared sql
657 * @param mixed $args Either an array here, or put scalars as varargs
659 function execute( $prepared, $args = null ) {
660 if( !is_array( $args ) ) {
662 $args = func_get_args();
663 array_shift( $args );
665 $sql = $this->fillPrepared( $prepared['query'], $args );
666 return $this->query( $sql, $prepared['func'] );
670 * Prepare & execute an SQL statement, quoting and inserting arguments
671 * in the appropriate places.
672 * @param string $query
673 * @param string $args ...
675 function safeQuery( $query, $args = null ) {
676 $prepared = $this->prepare( $query, 'Database::safeQuery' );
677 if( !is_array( $args ) ) {
679 $args = func_get_args();
680 array_shift( $args );
682 $retval = $this->execute( $prepared, $args );
683 $this->freePrepared( $prepared );
688 * For faking prepared SQL statements on DBs that don't support
690 * @param string $preparedSql - a 'preparable' SQL statement
691 * @param array $args - array of arguments to fill it with
692 * @return string executable SQL
694 function fillPrepared( $preparedQuery, $args ) {
696 $this->preparedArgs
=& $args;
697 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
698 array( &$this, 'fillPreparedArg' ), $preparedQuery );
702 * preg_callback func for fillPrepared()
703 * The arguments should be in $this->preparedArgs and must not be touched
704 * while we're doing this.
706 * @param array $matches
710 function fillPreparedArg( $matches ) {
711 switch( $matches[1] ) {
712 case '\\?': return '?';
713 case '\\!': return '!';
714 case '\\&': return '&';
716 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
717 switch( $matches[1] ) {
718 case '?': return $this->addQuotes( $arg );
719 case '!': return $arg;
721 # return $this->addQuotes( file_get_contents( $arg ) );
722 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
724 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
729 * @param mixed $res A SQL result
732 * Free a result object
734 function freeResult( $res ) {
735 if ( $res instanceof ResultWrapper
) {
738 if ( !@/**/mysql_free_result( $res ) ) {
739 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
744 * Fetch the next row from the given result object, in object form.
745 * Fields can be retrieved with $row->fieldname, with fields acting like
748 * @param $res SQL result object as returned from Database::query(), etc.
749 * @return MySQL row object
750 * @throws DBUnexpectedError Thrown if the database returns an error
752 function fetchObject( $res ) {
753 if ( $res instanceof ResultWrapper
) {
756 @/**/$row = mysql_fetch_object( $res );
757 if( $this->lastErrno() ) {
758 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
764 * Fetch the next row from the given result object, in associative array
765 * form. Fields are retrieved with $row['fieldname'].
767 * @param $res SQL result object as returned from Database::query(), etc.
768 * @return MySQL row object
769 * @throws DBUnexpectedError Thrown if the database returns an error
771 function fetchRow( $res ) {
772 if ( $res instanceof ResultWrapper
) {
775 @/**/$row = mysql_fetch_array( $res );
776 if ( $this->lastErrno() ) {
777 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
783 * Get the number of rows in a result object
785 function numRows( $res ) {
786 if ( $res instanceof ResultWrapper
) {
789 @/**/$n = mysql_num_rows( $res );
790 if( $this->lastErrno() ) {
791 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
797 * Get the number of fields in a result object
798 * See documentation for mysql_num_fields()
800 function numFields( $res ) {
801 if ( $res instanceof ResultWrapper
) {
804 return mysql_num_fields( $res );
808 * Get a field name in a result object
809 * See documentation for mysql_field_name():
810 * http://www.php.net/mysql_field_name
812 function fieldName( $res, $n ) {
813 if ( $res instanceof ResultWrapper
) {
816 return mysql_field_name( $res, $n );
820 * Get the inserted value of an auto-increment row
822 * The value inserted should be fetched from nextSequenceValue()
825 * $id = $dbw->nextSequenceValue('page_page_id_seq');
826 * $dbw->insert('page',array('page_id' => $id));
827 * $id = $dbw->insertId();
829 function insertId() { return mysql_insert_id( $this->mConn
); }
832 * Change the position of the cursor in a result object
833 * See mysql_data_seek()
835 function dataSeek( $res, $row ) {
836 if ( $res instanceof ResultWrapper
) {
839 return mysql_data_seek( $res, $row );
843 * Get the last error number
846 function lastErrno() {
847 if ( $this->mConn
) {
848 return mysql_errno( $this->mConn
);
850 return mysql_errno();
855 * Get a description of the last error
856 * See mysql_error() for more details
858 function lastError() {
859 if ( $this->mConn
) {
860 # Even if it's non-zero, it can still be invalid
861 wfSuppressWarnings();
862 $error = mysql_error( $this->mConn
);
864 $error = mysql_error();
868 $error = mysql_error();
871 $error .= ' (' . $this->mServer
. ')';
876 * Get the number of rows affected by the last write query
877 * See mysql_affected_rows() for more details
879 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
880 /**#@-*/ // end of template : @param $result
883 * Simple UPDATE wrapper
884 * Usually aborts on failure
885 * If errors are explicitly ignored, returns success
887 * This function exists for historical reasons, Database::update() has a more standard
888 * calling convention and feature set
890 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
892 $table = $this->tableName( $table );
893 $sql = "UPDATE $table SET $var = '" .
894 $this->strencode( $value ) . "' WHERE ($cond)";
895 return (bool)$this->query( $sql, $fname );
899 * Simple SELECT wrapper, returns a single field, input must be encoded
900 * Usually aborts on failure
901 * If errors are explicitly ignored, returns FALSE on failure
903 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
904 if ( !is_array( $options ) ) {
905 $options = array( $options );
907 $options['LIMIT'] = 1;
909 $res = $this->select( $table, $var, $cond, $fname, $options );
910 if ( $res === false ||
!$this->numRows( $res ) ) {
913 $row = $this->fetchRow( $res );
914 if ( $row !== false ) {
915 $this->freeResult( $res );
923 * Returns an optional USE INDEX clause to go after the table, and a
924 * string to go at the end of the query
928 * @param array $options an associative array of options to be turned into
929 * an SQL query, valid keys are listed in the function.
932 function makeSelectOptions( $options ) {
933 $preLimitTail = $postLimitTail = '';
936 $noKeyOptions = array();
937 foreach ( $options as $key => $option ) {
938 if ( is_numeric( $key ) ) {
939 $noKeyOptions[$option] = true;
943 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
944 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
945 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
947 //if (isset($options['LIMIT'])) {
948 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
949 // isset($options['OFFSET']) ? $options['OFFSET']
953 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
954 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
955 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
957 # Various MySQL extensions
958 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
959 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
960 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
961 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
962 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
963 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
964 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
965 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
967 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
968 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
973 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
979 * @param mixed $table Array or string, table name(s) (prefix auto-added)
980 * @param mixed $vars Array or string, field name(s) to be retrieved
981 * @param mixed $conds Array or string, condition(s) for WHERE
982 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
983 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
984 * see Database::makeSelectOptions code for list of supported stuff
985 * @param array $join_conds Associative array of table join conditions (optional)
986 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
987 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
989 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
991 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
992 return $this->query( $sql, $fname );
998 * @param mixed $table Array or string, table name(s) (prefix auto-added)
999 * @param mixed $vars Array or string, field name(s) to be retrieved
1000 * @param mixed $conds Array or string, condition(s) for WHERE
1001 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
1002 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
1003 * see Database::makeSelectOptions code for list of supported stuff
1004 * @param array $join_conds Associative array of table join conditions (optional)
1005 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
1006 * @return string, the SQL text
1008 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1009 if( is_array( $vars ) ) {
1010 $vars = implode( ',', $vars );
1012 if( !is_array( $options ) ) {
1013 $options = array( $options );
1015 if( is_array( $table ) ) {
1016 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1017 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1019 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1020 } elseif ($table!='') {
1021 if ($table{0}==' ') {
1022 $from = ' FROM ' . $table;
1024 $from = ' FROM ' . $this->tableName( $table );
1030 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1032 if( !empty( $conds ) ) {
1033 if ( is_array( $conds ) ) {
1034 $conds = $this->makeList( $conds, LIST_AND
);
1036 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1038 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1041 if (isset($options['LIMIT']))
1042 $sql = $this->limitResult($sql, $options['LIMIT'],
1043 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1044 $sql = "$sql $postLimitTail";
1046 if (isset($options['EXPLAIN'])) {
1047 $sql = 'EXPLAIN ' . $sql;
1053 * Single row SELECT wrapper
1054 * Aborts or returns FALSE on error
1056 * $vars: the selected variables
1057 * $conds: a condition map, terms are ANDed together.
1058 * Items with numeric keys are taken to be literal conditions
1059 * Takes an array of selected variables, and a condition map, which is ANDed
1060 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1061 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1062 * $obj- >page_id is the ID of the Astronomy article
1064 * @todo migrate documentation to phpdocumentor format
1066 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1067 $options['LIMIT'] = 1;
1068 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1069 if ( $res === false )
1071 if ( !$this->numRows($res) ) {
1072 $this->freeResult($res);
1075 $obj = $this->fetchObject( $res );
1076 $this->freeResult( $res );
1082 * Estimate rows in dataset
1083 * Returns estimated count, based on EXPLAIN output
1084 * Takes same arguments as Database::select()
1087 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1088 $options['EXPLAIN']=true;
1089 $res = $this->select ($table, $vars, $conds, $fname, $options );
1090 if ( $res === false )
1092 if (!$this->numRows($res)) {
1093 $this->freeResult($res);
1099 while( $plan = $this->fetchObject( $res ) ) {
1100 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1103 $this->freeResult($res);
1109 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1110 * It's only slightly flawed. Don't use for anything important.
1112 * @param string $sql A SQL Query
1115 static function generalizeSQL( $sql ) {
1116 # This does the same as the regexp below would do, but in such a way
1117 # as to avoid crashing php on some large strings.
1118 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1120 $sql = str_replace ( "\\\\", '', $sql);
1121 $sql = str_replace ( "\\'", '', $sql);
1122 $sql = str_replace ( "\\\"", '', $sql);
1123 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1124 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1126 # All newlines, tabs, etc replaced by single space
1127 $sql = preg_replace ( '/\s+/', ' ', $sql);
1130 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1136 * Determines whether a field exists in a table
1137 * Usually aborts on failure
1138 * If errors are explicitly ignored, returns NULL on failure
1140 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1141 $table = $this->tableName( $table );
1142 $res = $this->query( 'DESCRIBE '.$table, $fname );
1149 while ( $row = $this->fetchObject( $res ) ) {
1150 if ( $row->Field
== $field ) {
1159 * Determines whether an index exists
1160 * Usually aborts on failure
1161 * If errors are explicitly ignored, returns NULL on failure
1163 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1164 $info = $this->indexInfo( $table, $index, $fname );
1165 if ( is_null( $info ) ) {
1168 return $info !== false;
1174 * Get information about an index into an object
1175 * Returns false if the index does not exist
1177 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1178 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1179 # SHOW INDEX should work for 3.x and up:
1180 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1181 $table = $this->tableName( $table );
1182 $sql = 'SHOW INDEX FROM '.$table;
1183 $res = $this->query( $sql, $fname );
1189 while ( $row = $this->fetchObject( $res ) ) {
1190 if ( $row->Key_name
== $index ) {
1194 $this->freeResult($res);
1196 return empty($result) ?
false : $result;
1200 * Query whether a given table exists
1202 function tableExists( $table ) {
1203 $table = $this->tableName( $table );
1204 $old = $this->ignoreErrors( true );
1205 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1206 $this->ignoreErrors( $old );
1208 $this->freeResult( $res );
1216 * mysql_fetch_field() wrapper
1217 * Returns false if the field doesn't exist
1222 function fieldInfo( $table, $field ) {
1223 $table = $this->tableName( $table );
1224 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1225 $n = mysql_num_fields( $res->result
);
1226 for( $i = 0; $i < $n; $i++
) {
1227 $meta = mysql_fetch_field( $res->result
, $i );
1228 if( $field == $meta->name
) {
1229 return new MySQLField($meta);
1236 * mysql_field_type() wrapper
1238 function fieldType( $res, $index ) {
1239 if ( $res instanceof ResultWrapper
) {
1240 $res = $res->result
;
1242 return mysql_field_type( $res, $index );
1246 * Determines if a given index is unique
1248 function indexUnique( $table, $index ) {
1249 $indexInfo = $this->indexInfo( $table, $index );
1250 if ( !$indexInfo ) {
1253 return !$indexInfo[0]->Non_unique
;
1257 * INSERT wrapper, inserts an array into a table
1259 * $a may be a single associative array, or an array of these with numeric keys, for
1262 * Usually aborts on failure
1263 * If errors are explicitly ignored, returns success
1265 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1266 # No rows to insert, easy just return now
1267 if ( !count( $a ) ) {
1271 $table = $this->tableName( $table );
1272 if ( !is_array( $options ) ) {
1273 $options = array( $options );
1275 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1277 $keys = array_keys( $a[0] );
1280 $keys = array_keys( $a );
1283 $sql = 'INSERT ' . implode( ' ', $options ) .
1284 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1288 foreach ( $a as $row ) {
1294 $sql .= '(' . $this->makeList( $row ) . ')';
1297 $sql .= '(' . $this->makeList( $a ) . ')';
1299 return (bool)$this->query( $sql, $fname );
1303 * Make UPDATE options for the Database::update function
1306 * @param array $options The options passed to Database::update
1309 function makeUpdateOptions( $options ) {
1310 if( !is_array( $options ) ) {
1311 $options = array( $options );
1314 if ( in_array( 'LOW_PRIORITY', $options ) )
1315 $opts[] = $this->lowPriorityOption();
1316 if ( in_array( 'IGNORE', $options ) )
1318 return implode(' ', $opts);
1322 * UPDATE wrapper, takes a condition array and a SET array
1324 * @param string $table The table to UPDATE
1325 * @param array $values An array of values to SET
1326 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1327 * @param string $fname The Class::Function calling this function
1329 * @param array $options An array of UPDATE options, can be one or
1330 * more of IGNORE, LOW_PRIORITY
1333 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1334 $table = $this->tableName( $table );
1335 $opts = $this->makeUpdateOptions( $options );
1336 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1337 if ( $conds != '*' ) {
1338 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1340 return $this->query( $sql, $fname );
1344 * Makes an encoded list of strings from an array
1346 * LIST_COMMA - comma separated, no field names
1347 * LIST_AND - ANDed WHERE clause (without the WHERE)
1348 * LIST_OR - ORed WHERE clause (without the WHERE)
1349 * LIST_SET - comma separated with field names, like a SET clause
1350 * LIST_NAMES - comma separated field names
1352 function makeList( $a, $mode = LIST_COMMA
) {
1353 if ( !is_array( $a ) ) {
1354 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1359 foreach ( $a as $field => $value ) {
1361 if ( $mode == LIST_AND
) {
1363 } elseif($mode == LIST_OR
) {
1371 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1372 $list .= "($value)";
1373 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1375 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1376 if( count( $value ) == 0 ) {
1377 throw new MWException( __METHOD__
.': empty input' );
1378 } elseif( count( $value ) == 1 ) {
1379 // Special-case single values, as IN isn't terribly efficient
1380 // Don't necessarily assume the single key is 0; we don't
1381 // enforce linear numeric ordering on other arrays here.
1382 $value = array_values( $value );
1383 $list .= $field." = ".$this->addQuotes( $value[0] );
1385 $list .= $field." IN (".$this->makeList($value).") ";
1387 } elseif( is_null($value) ) {
1388 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1389 $list .= "$field IS ";
1390 } elseif ( $mode == LIST_SET
) {
1391 $list .= "$field = ";
1395 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1396 $list .= "$field = ";
1398 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1405 * Change the current database
1407 function selectDB( $db ) {
1408 $this->mDBname
= $db;
1409 return mysql_select_db( $db, $this->mConn
);
1413 * Get the current DB name
1415 function getDBname() {
1416 return $this->mDBname
;
1420 * Get the server hostname or IP address
1422 function getServer() {
1423 return $this->mServer
;
1427 * Format a table name ready for use in constructing an SQL query
1429 * This does two important things: it quotes the table names to clean them up,
1430 * and it adds a table prefix if only given a table name with no quotes.
1432 * All functions of this object which require a table name call this function
1433 * themselves. Pass the canonical name to such functions. This is only needed
1434 * when calling query() directly.
1436 * @param string $name database table name
1437 * @return string full database name
1439 function tableName( $name ) {
1440 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1441 # Skip the entire process when we have a string quoted on both ends.
1442 # Note that we check the end so that we will still quote any use of
1443 # use of `database`.table. But won't break things if someone wants
1444 # to query a database table with a dot in the name.
1445 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1447 # Lets test for any bits of text that should never show up in a table
1448 # name. Basically anything like JOIN or ON which are actually part of
1449 # SQL queries, but may end up inside of the table value to combine
1450 # sql. Such as how the API is doing.
1451 # Note that we use a whitespace test rather than a \b test to avoid
1452 # any remote case where a word like on may be inside of a table name
1453 # surrounded by symbols which may be considered word breaks.
1454 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1456 # Split database and table into proper variables.
1457 # We reverse the explode so that database.table and table both output
1458 # the correct table.
1459 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1460 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1461 else @list
( $table ) = $dbDetails;
1462 $prefix = $this->mTablePrefix
; # Default prefix
1464 # A database name has been specified in input. Quote the table name
1465 # because we don't want any prefixes added.
1466 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1468 # Note that we use the long format because php will complain in in_array if
1469 # the input is not an array, and will complain in is_array if it is not set.
1470 if( !isset( $database ) # Don't use shared database if pre selected.
1471 && isset( $wgSharedDB ) # We have a shared database
1472 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1473 && isset( $wgSharedTables )
1474 && is_array( $wgSharedTables )
1475 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1476 $database = $wgSharedDB;
1477 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1480 # Quote the $database and $table and apply the prefix if not quoted.
1481 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1482 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1484 # Merge our database and table into our final table name.
1485 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1487 # We're finished, return.
1492 * Fetch a number of table names into an array
1493 * This is handy when you need to construct SQL for joins
1496 * extract($dbr->tableNames('user','watchlist'));
1497 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1498 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1500 public function tableNames() {
1501 $inArray = func_get_args();
1503 foreach ( $inArray as $name ) {
1504 $retVal[$name] = $this->tableName( $name );
1510 * Fetch a number of table names into an zero-indexed numerical array
1511 * This is handy when you need to construct SQL for joins
1514 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1515 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1516 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1518 public function tableNamesN() {
1519 $inArray = func_get_args();
1521 foreach ( $inArray as $name ) {
1522 $retVal[] = $this->tableName( $name );
1530 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1533 $use_index_safe = is_array($use_index) ?
$use_index : array();
1534 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1535 foreach ( $tables as $table ) {
1536 // Is there a JOIN and INDEX clause for this table?
1537 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1538 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1539 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1540 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1541 $retJOIN[] = $tableClause;
1542 // Is there an INDEX clause?
1543 } else if ( isset($use_index_safe[$table]) ) {
1544 $tableClause = $this->tableName( $table );
1545 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1546 $ret[] = $tableClause;
1547 // Is there a JOIN clause?
1548 } else if ( isset($join_conds_safe[$table]) ) {
1549 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1550 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1551 $retJOIN[] = $tableClause;
1553 $tableClause = $this->tableName( $table );
1554 $ret[] = $tableClause;
1557 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1558 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1559 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1560 // Compile our final table clause
1561 return implode(' ',array($straightJoins,$otherJoins) );
1565 * Wrapper for addslashes()
1566 * @param string $s String to be slashed.
1567 * @return string slashed string.
1569 function strencode( $s ) {
1570 return mysql_real_escape_string( $s, $this->mConn
);
1574 * If it's a string, adds quotes and backslashes
1575 * Otherwise returns as-is
1577 function addQuotes( $s ) {
1578 if ( is_null( $s ) ) {
1581 # This will also quote numeric values. This should be harmless,
1582 # and protects against weird problems that occur when they really
1583 # _are_ strings such as article titles and string->number->string
1584 # conversion is not 1:1.
1585 return "'" . $this->strencode( $s ) . "'";
1590 * Escape string for safe LIKE usage
1592 function escapeLike( $s ) {
1593 $s=$this->strencode( $s );
1594 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1599 * Returns an appropriately quoted sequence value for inserting a new row.
1600 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1601 * subclass will return an integer, and save the value for insertId()
1603 function nextSequenceValue( $seqName ) {
1609 * PostgreSQL doesn't have them and returns ""
1611 function useIndexClause( $index ) {
1612 return "FORCE INDEX ($index)";
1616 * REPLACE query wrapper
1617 * PostgreSQL simulates this with a DELETE followed by INSERT
1618 * $row is the row to insert, an associative array
1619 * $uniqueIndexes is an array of indexes. Each element may be either a
1620 * field name or an array of field names
1622 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1623 * However if you do this, you run the risk of encountering errors which wouldn't have
1626 * @todo migrate comment to phodocumentor format
1628 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1629 $table = $this->tableName( $table );
1632 if ( !is_array( reset( $rows ) ) ) {
1633 $rows = array( $rows );
1636 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1638 foreach ( $rows as $row ) {
1644 $sql .= '(' . $this->makeList( $row ) . ')';
1646 return $this->query( $sql, $fname );
1650 * DELETE where the condition is a join
1651 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1653 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1654 * join condition matches, set $conds='*'
1656 * DO NOT put the join condition in $conds
1658 * @param string $delTable The table to delete from.
1659 * @param string $joinTable The other table.
1660 * @param string $delVar The variable to join on, in the first table.
1661 * @param string $joinVar The variable to join on, in the second table.
1662 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1664 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1666 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1669 $delTable = $this->tableName( $delTable );
1670 $joinTable = $this->tableName( $joinTable );
1671 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1672 if ( $conds != '*' ) {
1673 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1676 return $this->query( $sql, $fname );
1680 * Returns the size of a text field, or -1 for "unlimited"
1682 function textFieldSize( $table, $field ) {
1683 $table = $this->tableName( $table );
1684 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1685 $res = $this->query( $sql, 'Database::textFieldSize' );
1686 $row = $this->fetchObject( $res );
1687 $this->freeResult( $res );
1690 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1699 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1701 function lowPriorityOption() {
1702 return 'LOW_PRIORITY';
1706 * DELETE query wrapper
1708 * Use $conds == "*" to delete all rows
1710 function delete( $table, $conds, $fname = 'Database::delete' ) {
1712 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1714 $table = $this->tableName( $table );
1715 $sql = "DELETE FROM $table";
1716 if ( $conds != '*' ) {
1717 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1719 return $this->query( $sql, $fname );
1723 * INSERT SELECT wrapper
1724 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1725 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1726 * $conds may be "*" to copy the whole table
1727 * srcTable may be an array of tables.
1729 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1730 $insertOptions = array(), $selectOptions = array() )
1732 $destTable = $this->tableName( $destTable );
1733 if ( is_array( $insertOptions ) ) {
1734 $insertOptions = implode( ' ', $insertOptions );
1736 if( !is_array( $selectOptions ) ) {
1737 $selectOptions = array( $selectOptions );
1739 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1740 if( is_array( $srcTable ) ) {
1741 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1743 $srcTable = $this->tableName( $srcTable );
1745 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1746 " SELECT $startOpts " . implode( ',', $varMap ) .
1747 " FROM $srcTable $useIndex ";
1748 if ( $conds != '*' ) {
1749 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1751 $sql .= " $tailOpts";
1752 return $this->query( $sql, $fname );
1756 * Construct a LIMIT query with optional offset
1757 * This is used for query pages
1758 * $sql string SQL query we will append the limit too
1759 * $limit integer the SQL limit
1760 * $offset integer the SQL offset (default false)
1762 function limitResult($sql, $limit, $offset=false) {
1763 if( !is_numeric($limit) ) {
1764 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1766 return "$sql LIMIT "
1767 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1770 function limitResultForUpdate($sql, $num) {
1771 return $this->limitResult($sql, $num, 0);
1775 * Returns an SQL expression for a simple conditional.
1778 * @param string $cond SQL expression which will result in a boolean value
1779 * @param string $trueVal SQL expression to return if true
1780 * @param string $falseVal SQL expression to return if false
1781 * @return string SQL fragment
1783 function conditional( $cond, $trueVal, $falseVal ) {
1784 return " IF($cond, $trueVal, $falseVal) ";
1788 * Returns a comand for str_replace function in SQL query.
1789 * Uses REPLACE() in MySQL
1791 * @param string $orig String or column to modify
1792 * @param string $old String or column to seek
1793 * @param string $new String or column to replace with
1795 function strreplace( $orig, $old, $new ) {
1796 return "REPLACE({$orig}, {$old}, {$new})";
1800 * Determines if the last failure was due to a deadlock
1802 function wasDeadlock() {
1803 return $this->lastErrno() == 1213;
1807 * Perform a deadlock-prone transaction.
1809 * This function invokes a callback function to perform a set of write
1810 * queries. If a deadlock occurs during the processing, the transaction
1811 * will be rolled back and the callback function will be called again.
1814 * $dbw->deadlockLoop( callback, ... );
1816 * Extra arguments are passed through to the specified callback function.
1818 * Returns whatever the callback function returned on its successful,
1819 * iteration, or false on error, for example if the retry limit was
1822 function deadlockLoop() {
1823 $myFname = 'Database::deadlockLoop';
1826 $args = func_get_args();
1827 $function = array_shift( $args );
1828 $oldIgnore = $this->ignoreErrors( true );
1829 $tries = DEADLOCK_TRIES
;
1830 if ( is_array( $function ) ) {
1831 $fname = $function[0];
1836 $retVal = call_user_func_array( $function, $args );
1837 $error = $this->lastError();
1838 $errno = $this->lastErrno();
1839 $sql = $this->lastQuery();
1842 if ( $this->wasDeadlock() ) {
1844 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1846 $this->reportQueryError( $error, $errno, $sql, $fname );
1849 } while( $this->wasDeadlock() && --$tries > 0 );
1850 $this->ignoreErrors( $oldIgnore );
1851 if ( $tries <= 0 ) {
1852 $this->query( 'ROLLBACK', $myFname );
1853 $this->reportQueryError( $error, $errno, $sql, $fname );
1856 $this->query( 'COMMIT', $myFname );
1862 * Do a SELECT MASTER_POS_WAIT()
1864 * @param string $file the binlog file
1865 * @param string $pos the binlog position
1866 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1868 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1869 $fname = 'Database::masterPosWait';
1870 wfProfileIn( $fname );
1872 # Commit any open transactions
1873 if ( $this->mTrxLevel
) {
1874 $this->immediateCommit();
1877 if ( !is_null( $this->mFakeSlaveLag
) ) {
1878 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1879 if ( $wait > $timeout * 1e6
) {
1880 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1881 wfProfileOut( $fname );
1883 } elseif ( $wait > 0 ) {
1884 wfDebug( "Fake slave waiting $wait us\n" );
1886 wfProfileOut( $fname );
1889 wfDebug( "Fake slave up to date ($wait us)\n" );
1890 wfProfileOut( $fname );
1895 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1896 $encFile = $this->addQuotes( $pos->file
);
1897 $encPos = intval( $pos->pos
);
1898 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1899 $res = $this->doQuery( $sql );
1900 if ( $res && $row = $this->fetchRow( $res ) ) {
1901 $this->freeResult( $res );
1902 wfProfileOut( $fname );
1905 wfProfileOut( $fname );
1911 * Get the position of the master from SHOW SLAVE STATUS
1913 function getSlavePos() {
1914 if ( !is_null( $this->mFakeSlaveLag
) ) {
1915 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1916 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1919 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1920 $row = $this->fetchObject( $res );
1922 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $row->Exec_master_log_pos
);
1929 * Get the position of the master from SHOW MASTER STATUS
1931 function getMasterPos() {
1932 if ( $this->mFakeMaster
) {
1933 return new MySQLMasterPos( 'fake', microtime( true ) );
1935 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1936 $row = $this->fetchObject( $res );
1938 return new MySQLMasterPos( $row->File
, $row->Position
);
1945 * Begin a transaction, committing any previously open transaction
1947 function begin( $fname = 'Database::begin' ) {
1948 $this->query( 'BEGIN', $fname );
1949 $this->mTrxLevel
= 1;
1955 function commit( $fname = 'Database::commit' ) {
1956 $this->query( 'COMMIT', $fname );
1957 $this->mTrxLevel
= 0;
1961 * Rollback a transaction.
1962 * No-op on non-transactional databases.
1964 function rollback( $fname = 'Database::rollback' ) {
1965 $this->query( 'ROLLBACK', $fname, true );
1966 $this->mTrxLevel
= 0;
1970 * Begin a transaction, committing any previously open transaction
1971 * @deprecated use begin()
1973 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1978 * Commit transaction, if one is open
1979 * @deprecated use commit()
1981 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1986 * Return MW-style timestamp used for MySQL schema
1988 function timestamp( $ts=0 ) {
1989 return wfTimestamp(TS_MW
,$ts);
1993 * Local database timestamp format or null
1995 function timestampOrNull( $ts = null ) {
1996 if( is_null( $ts ) ) {
1999 return $this->timestamp( $ts );
2006 function resultObject( $result ) {
2007 if( empty( $result ) ) {
2009 } elseif ( $result instanceof ResultWrapper
) {
2011 } elseif ( $result === true ) {
2012 // Successful write query
2015 return new ResultWrapper( $this, $result );
2020 * Return aggregated value alias
2022 function aggregateValue ($valuedata,$valuename='value') {
2027 * @return string wikitext of a link to the server software's web site
2029 function getSoftwareLink() {
2030 return "[http://www.mysql.com/ MySQL]";
2034 * @return string Version information from the database
2036 function getServerVersion() {
2037 return mysql_get_server_info( $this->mConn
);
2041 * Ping the server and try to reconnect if it there is no connection
2044 if( !function_exists( 'mysql_ping' ) ) {
2045 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2048 $ping = mysql_ping( $this->mConn
);
2053 // Need to reconnect manually in MySQL client 5.0.13+
2054 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2055 mysql_close( $this->mConn
);
2056 $this->mOpened
= false;
2057 $this->mConn
= false;
2058 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2066 * At the moment, this will only work if the DB user has the PROCESS privilege
2069 if ( !is_null( $this->mFakeSlaveLag
) ) {
2070 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2071 return $this->mFakeSlaveLag
;
2073 $res = $this->query( 'SHOW PROCESSLIST' );
2074 # Find slave SQL thread
2075 while ( $row = $this->fetchObject( $res ) ) {
2076 /* This should work for most situations - when default db
2077 * for thread is not specified, it had no events executed,
2078 * and therefore it doesn't know yet how lagged it is.
2080 * Relay log I/O thread does not select databases.
2082 if ( $row->User
== 'system user' &&
2083 $row->State
!= 'Waiting for master to send event' &&
2084 $row->State
!= 'Connecting to master' &&
2085 $row->State
!= 'Queueing master event to the relay log' &&
2086 $row->State
!= 'Waiting for master update' &&
2087 $row->State
!= 'Requesting binlog dump'
2089 # This is it, return the time (except -ve)
2090 if ( $row->Time
> 0x7fffffff ) {
2101 * Get status information from SHOW STATUS in an associative array
2103 function getStatus($which="%") {
2104 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2106 while ( $row = $this->fetchObject( $res ) ) {
2107 $status[$row->Variable_name
] = $row->Value
;
2113 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2115 function maxListLen() {
2119 function encodeBlob($b) {
2123 function decodeBlob($b) {
2128 * Override database's default connection timeout.
2129 * May be useful for very long batch queries such as
2130 * full-wiki dumps, where a single query reads out
2131 * over hours or days.
2132 * @param int $timeout in seconds
2134 public function setTimeout( $timeout ) {
2135 $this->query( "SET net_read_timeout=$timeout" );
2136 $this->query( "SET net_write_timeout=$timeout" );
2140 * Read and execute SQL commands from a file.
2141 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2142 * @param string $filename File name to open
2143 * @param callback $lineCallback Optional function called before reading each line
2144 * @param callback $resultCallback Optional function called for each MySQL result
2146 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2147 $fp = fopen( $filename, 'r' );
2148 if ( false === $fp ) {
2149 throw new MWException( "Could not open \"{$filename}\".\n" );
2151 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2157 * Read and execute commands from an open file handle
2158 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2159 * @param string $fp File handle
2160 * @param callback $lineCallback Optional function called before reading each line
2161 * @param callback $resultCallback Optional function called for each MySQL result
2163 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2166 $dollarquote = false;
2168 while ( ! feof( $fp ) ) {
2169 if ( $lineCallback ) {
2170 call_user_func( $lineCallback );
2172 $line = trim( fgets( $fp, 1024 ) );
2173 $sl = strlen( $line ) - 1;
2175 if ( $sl < 0 ) { continue; }
2176 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2178 ## Allow dollar quoting for function declarations
2179 if (substr($line,0,4) == '$mw$') {
2181 $dollarquote = false;
2185 $dollarquote = true;
2188 else if (!$dollarquote) {
2189 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2191 $line = substr( $line, 0, $sl );
2195 if ( '' != $cmd ) { $cmd .= ' '; }
2199 $cmd = str_replace(';;', ";", $cmd);
2200 $cmd = $this->replaceVars( $cmd );
2201 $res = $this->query( $cmd, __METHOD__
);
2202 if ( $resultCallback ) {
2203 call_user_func( $resultCallback, $res, $this );
2206 if ( false === $res ) {
2207 $err = $this->lastError();
2208 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2220 * Replace variables in sourced SQL
2222 protected function replaceVars( $ins ) {
2224 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2225 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2226 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2229 // Ordinary variables
2230 foreach ( $varnames as $var ) {
2231 if( isset( $GLOBALS[$var] ) ) {
2232 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2233 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2234 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2235 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2240 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2241 array( &$this, 'tableNameCallback' ), $ins );
2246 * Table name callback
2249 protected function tableNameCallback( $matches ) {
2250 return $this->tableName( $matches[1] );
2254 * Build a concatenation list to feed into a SQL query
2256 function buildConcat( $stringList ) {
2257 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2263 * Abstracted from Filestore::lock() so child classes can implement for
2266 * @param string $lockName Name of lock to aquire
2267 * @param string $method Name of method calling us
2270 public function lock( $lockName, $method ) {
2271 $lockName = $this->addQuotes( $lockName );
2272 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2273 $row = $this->fetchObject( $result );
2274 $this->freeResult( $result );
2276 if( $row->lockstatus
== 1 ) {
2279 wfDebug( __METHOD__
." failed to acquire lock\n" );
2286 * @todo fixme - Figure out a way to return a bool
2287 * based on successful lock release.
2289 * @param string $lockName Name of lock to release
2290 * @param string $method Name of method calling us
2292 public function unlock( $lockName, $method ) {
2293 $lockName = $this->addQuotes( $lockName );
2294 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2295 $this->freeResult( $result );
2299 * Get search engine class. All subclasses of this
2300 * need to implement this if they wish to use searching.
2304 public function getSearchEngine() {
2305 return "SearchMySQL";
2310 * Database abstraction object for mySQL
2311 * Inherit all methods and properties of Database::Database()
2316 class DatabaseMysql
extends Database
{
2320 /******************************************************************************
2322 *****************************************************************************/
2331 function DBObject($data) {
2332 $this->mData
= $data;
2340 return $this->mData
;
2348 * This allows us to distinguish a blob from a normal string and an array of strings
2352 function __construct($data) {
2353 $this->mData
= $data;
2356 return $this->mData
;
2365 private $name, $tablename, $default, $max_length, $nullable,
2366 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2367 function __construct ($info) {
2368 $this->name
= $info->name
;
2369 $this->tablename
= $info->table
;
2370 $this->default = $info->def
;
2371 $this->max_length
= $info->max_length
;
2372 $this->nullable
= !$info->not_null
;
2373 $this->is_pk
= $info->primary_key
;
2374 $this->is_unique
= $info->unique_key
;
2375 $this->is_multiple
= $info->multiple_key
;
2376 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2377 $this->type
= $info->type
;
2384 function tableName() {
2385 return $this->tableName
;
2388 function defaultValue() {
2389 return $this->default;
2392 function maxLength() {
2393 return $this->max_length
;
2396 function nullable() {
2397 return $this->nullable
;
2401 return $this->is_key
;
2404 function isMultipleKey() {
2405 return $this->is_multiple
;
2413 /******************************************************************************
2415 *****************************************************************************/
2418 * Database error base class
2421 class DBError
extends MWException
{
2425 * Construct a database error
2426 * @param Database $db The database object which threw the error
2427 * @param string $error A simple error message to be used for debugging
2429 function __construct( Database
&$db, $error ) {
2431 parent
::__construct( $error );
2438 class DBConnectionError
extends DBError
{
2441 function __construct( Database
&$db, $error = 'unknown error' ) {
2442 $msg = 'DB connection error';
2443 if ( trim( $error ) != '' ) {
2446 $this->error
= $error;
2447 parent
::__construct( $db, $msg );
2450 function useOutputPage() {
2451 // Not likely to work
2455 function useMessageCache() {
2456 // Not likely to work
2460 function getText() {
2461 return $this->getMessage() . "\n";
2464 function getLogMessage() {
2465 # Don't send to the exception log
2469 function getPageTitle() {
2471 return "$wgSitename has a problem";
2474 function getHTML() {
2475 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2476 global $wgSitename, $wgServer, $wgMessageCache;
2478 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2479 # Hard coding strings instead.
2481 $noconnect = "<p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p>Try waiting a few minutes and reloading.</p><p><small>(Can't contact the database server: $1)</small></p>";
2482 $mainpage = 'Main Page';
2483 $searchdisabled = <<<EOT
2484 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2485 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2489 <!-- SiteSearch Google -->
2490 <FORM method=GET action=\"http://www.google.com/search\">
2491 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2492 <A HREF=\"http://www.google.com/\">
2493 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2494 border=\"0\" ALT=\"Google\"></A>
2497 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2498 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2500 <input type=hidden name=domains value=\"$wgServer\"><br /><input type=radio name=sitesearch value=\"\"> WWW <input type=radio name=sitesearch value=\"$wgServer\" checked> $wgServer <br />
2501 <input type='hidden' name='ie' value='$2'>
2502 <input type='hidden' name='oe' value='$2'>
2506 <!-- SiteSearch Google -->";
2507 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2509 # No database access
2510 if ( is_object( $wgMessageCache ) ) {
2511 $wgMessageCache->disable();
2514 if ( trim( $this->error
) == '' ) {
2515 $this->error
= $this->db
->getProperty('mServer');
2518 $text = str_replace( '$1', $this->error
, $noconnect );
2521 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2522 $text .= '</p><p>Backtrace:</p><p>' .
2523 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2527 if($wgUseFileCache) {
2532 $t = Title
::newFromURL( $title );
2533 } elseif (@/**/$_REQUEST['search']) {
2534 $search = $_REQUEST['search'];
2535 return $searchdisabled .
2536 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2537 $wgInputEncoding ), $googlesearch );
2539 $t = Title
::newFromText( $mainpage );
2543 $cache = new HTMLFileCache( $t );
2544 if( $cache->isFileCached() ) {
2545 // @todo, FIXME: $msg is not defined on the next line.
2546 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2547 $cachederror . "</b></p>\n";
2549 $tag = '<div id="article">';
2550 $text = str_replace(
2553 $cache->fetchPageText() );
2564 class DBQueryError
extends DBError
{
2565 public $error, $errno, $sql, $fname;
2567 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2568 $message = "A database error has occurred\n" .
2570 "Function: $fname\n" .
2571 "Error: $errno $error\n";
2573 parent
::__construct( $db, $message );
2574 $this->error
= $error;
2575 $this->errno
= $errno;
2577 $this->fname
= $fname;
2580 function getText() {
2581 if ( $this->useMessageCache() ) {
2582 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2583 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2585 return $this->getMessage();
2590 global $wgShowSQLErrors;
2591 if( !$wgShowSQLErrors ) {
2592 return $this->msg( 'sqlhidden', 'SQL hidden' );
2598 function getLogMessage() {
2599 # Don't send to the exception log
2603 function getPageTitle() {
2604 return $this->msg( 'databaseerror', 'Database error' );
2607 function getHTML() {
2608 if ( $this->useMessageCache() ) {
2609 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2610 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2612 return nl2br( htmlspecialchars( $this->getMessage() ) );
2620 class DBUnexpectedError
extends DBError
{}
2624 * Result wrapper for grabbing data queried by someone else
2627 class ResultWrapper
implements Iterator
{
2628 var $db, $result, $pos = 0, $currentRow = null;
2631 * Create a new result object from a result resource and a Database object
2633 function ResultWrapper( $database, $result ) {
2634 $this->db
= $database;
2635 if ( $result instanceof ResultWrapper
) {
2636 $this->result
= $result->result
;
2638 $this->result
= $result;
2643 * Get the number of rows in a result object
2645 function numRows() {
2646 return $this->db
->numRows( $this->result
);
2650 * Fetch the next row from the given result object, in object form.
2651 * Fields can be retrieved with $row->fieldname, with fields acting like
2654 * @param $res SQL result object as returned from Database::query(), etc.
2655 * @return MySQL row object
2656 * @throws DBUnexpectedError Thrown if the database returns an error
2658 function fetchObject() {
2659 return $this->db
->fetchObject( $this->result
);
2663 * Fetch the next row from the given result object, in associative array
2664 * form. Fields are retrieved with $row['fieldname'].
2666 * @param $res SQL result object as returned from Database::query(), etc.
2667 * @return MySQL row object
2668 * @throws DBUnexpectedError Thrown if the database returns an error
2670 function fetchRow() {
2671 return $this->db
->fetchRow( $this->result
);
2675 * Free a result object
2678 $this->db
->freeResult( $this->result
);
2679 unset( $this->result
);
2684 * Change the position of the cursor in a result object
2685 * See mysql_data_seek()
2687 function seek( $row ) {
2688 $this->db
->dataSeek( $this->result
, $row );
2691 /*********************
2692 * Iterator functions
2693 * Note that using these in combination with the non-iterator functions
2694 * above may cause rows to be skipped or repeated.
2698 if ($this->numRows()) {
2699 $this->db
->dataSeek($this->result
, 0);
2702 $this->currentRow
= null;
2705 function current() {
2706 if ( is_null( $this->currentRow
) ) {
2709 return $this->currentRow
;
2718 $this->currentRow
= $this->fetchObject();
2719 return $this->currentRow
;
2723 return $this->current() !== false;
2727 class MySQLMasterPos
{
2730 function __construct( $file, $pos ) {
2731 $this->file
= $file;
2735 function __toString() {
2736 return "{$this->file}/{$this->pos}";