3c37f707a7b70a7274e8169e0226f34ffb260ea7
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
260 * @param int $max, max connection attempts
261 ** After the first retry (second attempt), each retry waits 1 second
263 function __construct( $server = false, $user = false, $password = false, $dbName = false,
264 $failFunction = false, $flags = 0, $tablePrefix = 'get from global', $max = false ) {
266 global $wgOut, $wgDBprefix, $wgCommandLineMode;
267 # Can't get a reference if it hasn't been set yet
268 if ( !isset( $wgOut ) ) {
272 $this->mFailFunction
= $failFunction;
273 $this->mFlags
= $flags;
275 if ( $this->mFlags
& DBO_DEFAULT
) {
276 if ( $wgCommandLineMode ) {
277 $this->mFlags
&= ~DBO_TRX
;
279 $this->mFlags |
= DBO_TRX
;
284 // Faster read-only access
285 if ( wfReadOnly() ) {
286 $this->mFlags |= DBO_PERSISTENT;
287 $this->mFlags &= ~DBO_TRX;
290 /** Get the default table prefix*/
291 if ( $tablePrefix == 'get from global' ) {
292 $this->mTablePrefix
= $wgDBprefix;
294 $this->mTablePrefix
= $tablePrefix;
298 $this->open( $server, $user, $password, $dbName, $max );
304 * @param failFunction
307 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
309 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
313 * Usually aborts on failure
314 * If the failFunction is set to a non-zero integer, returns success
316 function open( $server, $user, $password, $dbName, $max = false ) {
317 global $wguname, $wgAllDBsAreLocalhost;
318 wfProfileIn( __METHOD__
);
320 # Test for missing mysql.so
321 # First try to load it
322 if (!@extension_loaded
('mysql')) {
327 # Otherwise we get a suppressed fatal error, which is very hard to track down
328 if ( !function_exists( 'mysql_connect' ) ) {
329 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
332 # Debugging hack -- fake cluster
333 if ( $wgAllDBsAreLocalhost ) {
334 $realServer = 'localhost';
336 $realServer = $server;
339 $this->mServer
= $server;
340 $this->mUser
= $user;
341 $this->mPassword
= $password;
342 $this->mDBname
= $dbName;
346 wfProfileIn("dbconnect-$server");
348 if( !$max ) { $max = 3; }
349 # Try to connect up to three times (by default)
350 # The kernel's default SYN retransmission period is far too slow for us,
351 # so we use a short timeout plus a manual retry.
352 $this->mConn
= false;
353 $this->installErrorHandler();
354 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
358 if ( $this->mFlags
& DBO_PERSISTENT
) {
359 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
361 # Create a new connection...
362 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
364 if ($this->mConn
=== false) {
366 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
369 $phpError = $this->restoreErrorHandler();
371 wfProfileOut("dbconnect-$server");
373 if ( $dbName != '' ) {
374 if ( $this->mConn
!== false ) {
375 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
377 $error = "Error selecting database $dbName on server {$this->mServer} " .
378 "from client host {$wguname['nodename']}\n";
379 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
383 wfDebug( "DB connection error\n" );
384 wfDebug( "Server: $server, User: $user, Password: " .
385 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
390 $success = (bool)$this->mConn
;
394 $version = $this->getServerVersion();
395 if ( version_compare( $version, '4.1' ) >= 0 ) {
396 // Tell the server we're communicating with it in UTF-8.
397 // This may engage various charset conversions.
400 $this->query( 'SET NAMES utf8', __METHOD__
);
402 // Turn off strict mode
403 $this->query( "SET sql_mode = ''", __METHOD__
);
406 // Turn off strict mode if it is on
408 $this->reportConnectionError( $phpError );
411 $this->mOpened
= $success;
412 wfProfileOut( __METHOD__
);
417 protected function installErrorHandler() {
418 $this->mPHPError
= false;
419 set_error_handler( array( $this, 'connectionErrorHandler' ) );
422 protected function restoreErrorHandler() {
423 restore_error_handler();
424 return $this->mPHPError
;
427 protected function connectionErrorHandler( $errno, $errstr ) {
428 $this->mPHPError
= $errstr;
432 * Closes a database connection.
433 * if it is open : commits any open transactions
435 * @return bool operation success. true if already closed.
439 $this->mOpened
= false;
440 if ( $this->mConn
) {
441 if ( $this->trxLevel() ) {
442 $this->immediateCommit();
444 return mysql_close( $this->mConn
);
451 * @param string $error fallback error message, used if none is given by MySQL
453 function reportConnectionError( $error = 'Unknown error' ) {
454 $myError = $this->lastError();
459 if ( $this->mFailFunction
) {
460 # Legacy error handling method
461 if ( !is_int( $this->mFailFunction
) ) {
462 $ff = $this->mFailFunction
;
463 $ff( $this, $error );
467 wfLogDBError( "Connection error: $error\n" );
468 throw new DBConnectionError( $this, $error );
473 * Usually aborts on failure. If errors are explicitly ignored, returns success.
475 * @param $sql String: SQL query
476 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
477 * comment (you can use __METHOD__ or add some extra info)
478 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
479 * maybe best to catch the exception instead?
480 * @return true for a successful write query, ResultWrapper object for a successful read query,
481 * or false on failure if $tempIgnore set
482 * @throws DBQueryError Thrown when the database returns an error of any kind
484 public function query( $sql, $fname = '', $tempIgnore = false ) {
487 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
488 if ( isset( $wgProfiler ) ) {
489 # generalizeSQL will probably cut down the query to reasonable
490 # logging size most of the time. The substr is really just a sanity check.
492 # Who's been wasting my precious column space? -- TS
493 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
496 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
497 $totalProf = 'Database::query-master';
499 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
500 $totalProf = 'Database::query';
502 wfProfileIn( $totalProf );
503 wfProfileIn( $queryProf );
506 $this->mLastQuery
= $sql;
508 # Add a comment for easy SHOW PROCESSLIST interpretation
511 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
512 $userName = $wgUser->getName();
513 if ( mb_strlen( $userName ) > 15 ) {
514 $userName = mb_substr( $userName, 0, 15 ) . '...';
516 $userName = str_replace( '/', '', $userName );
520 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
522 # $commentedSql = $sql;
525 # If DBO_TRX is set, start a transaction
526 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
527 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
528 // avoid establishing transactions for SHOW and SET statements too -
529 // that would delay transaction initializations to once connection
530 // is really used by application
531 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
532 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
536 if ( $this->debug() ) {
537 $sqlx = substr( $commentedSql, 0, 500 );
538 $sqlx = strtr( $sqlx, "\t\n", ' ' );
540 wfDebug( "SQL-master: $sqlx\n" );
542 wfDebug( "SQL: $sqlx\n" );
546 # Do the query and handle errors
547 $ret = $this->doQuery( $commentedSql );
549 # Try reconnecting if the connection was lost
550 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
551 # Transaction is gone, like it or not
552 $this->mTrxLevel
= 0;
553 wfDebug( "Connection lost, reconnecting...\n" );
554 if ( $this->ping() ) {
555 wfDebug( "Reconnected\n" );
556 $sqlx = substr( $commentedSql, 0, 500 );
557 $sqlx = strtr( $sqlx, "\t\n", ' ' );
558 global $wgRequestTime;
559 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
560 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
561 $ret = $this->doQuery( $commentedSql );
563 wfDebug( "Failed\n" );
567 if ( false === $ret ) {
568 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
571 if ( isset( $wgProfiler ) ) {
572 wfProfileOut( $queryProf );
573 wfProfileOut( $totalProf );
575 return $this->resultObject( $ret );
579 * The DBMS-dependent part of query()
580 * @param $sql String: SQL query.
581 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
584 /*private*/ function doQuery( $sql ) {
585 if( $this->bufferResults() ) {
586 $ret = mysql_query( $sql, $this->mConn
);
588 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
597 * @param string $fname
598 * @param bool $tempIgnore
600 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
601 global $wgCommandLineMode;
602 # Ignore errors during error handling to avoid infinite recursion
603 $ignore = $this->ignoreErrors( true );
604 ++
$this->mErrorCount
;
606 if( $ignore ||
$tempIgnore ) {
607 wfDebug("SQL ERROR (ignored): $error\n");
608 $this->ignoreErrors( $ignore );
610 $sql1line = str_replace( "\n", "\\n", $sql );
611 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
612 wfDebug("SQL ERROR: " . $error . "\n");
613 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
619 * Intended to be compatible with the PEAR::DB wrapper functions.
620 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
622 * ? = scalar value, quoted as necessary
623 * ! = raw SQL bit (a function for instance)
624 * & = filename; reads the file and inserts as a blob
625 * (we don't use this though...)
627 function prepare( $sql, $func = 'Database::prepare' ) {
628 /* MySQL doesn't support prepared statements (yet), so just
629 pack up the query for reference. We'll manually replace
631 return array( 'query' => $sql, 'func' => $func );
634 function freePrepared( $prepared ) {
635 /* No-op for MySQL */
639 * Execute a prepared query with the various arguments
640 * @param string $prepared the prepared sql
641 * @param mixed $args Either an array here, or put scalars as varargs
643 function execute( $prepared, $args = null ) {
644 if( !is_array( $args ) ) {
646 $args = func_get_args();
647 array_shift( $args );
649 $sql = $this->fillPrepared( $prepared['query'], $args );
650 return $this->query( $sql, $prepared['func'] );
654 * Prepare & execute an SQL statement, quoting and inserting arguments
655 * in the appropriate places.
656 * @param string $query
657 * @param string $args ...
659 function safeQuery( $query, $args = null ) {
660 $prepared = $this->prepare( $query, 'Database::safeQuery' );
661 if( !is_array( $args ) ) {
663 $args = func_get_args();
664 array_shift( $args );
666 $retval = $this->execute( $prepared, $args );
667 $this->freePrepared( $prepared );
672 * For faking prepared SQL statements on DBs that don't support
674 * @param string $preparedSql - a 'preparable' SQL statement
675 * @param array $args - array of arguments to fill it with
676 * @return string executable SQL
678 function fillPrepared( $preparedQuery, $args ) {
680 $this->preparedArgs
=& $args;
681 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
682 array( &$this, 'fillPreparedArg' ), $preparedQuery );
686 * preg_callback func for fillPrepared()
687 * The arguments should be in $this->preparedArgs and must not be touched
688 * while we're doing this.
690 * @param array $matches
694 function fillPreparedArg( $matches ) {
695 switch( $matches[1] ) {
696 case '\\?': return '?';
697 case '\\!': return '!';
698 case '\\&': return '&';
700 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
701 switch( $matches[1] ) {
702 case '?': return $this->addQuotes( $arg );
703 case '!': return $arg;
705 # return $this->addQuotes( file_get_contents( $arg ) );
706 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
708 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
713 * @param mixed $res A SQL result
716 * Free a result object
718 function freeResult( $res ) {
719 if ( $res instanceof ResultWrapper
) {
722 if ( !@/**/mysql_free_result( $res ) ) {
723 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
728 * Fetch the next row from the given result object, in object form.
729 * Fields can be retrieved with $row->fieldname, with fields acting like
732 * @param $res SQL result object as returned from Database::query(), etc.
733 * @return MySQL row object
734 * @throws DBUnexpectedError Thrown if the database returns an error
736 function fetchObject( $res ) {
737 if ( $res instanceof ResultWrapper
) {
740 @/**/$row = mysql_fetch_object( $res );
741 if( $this->lastErrno() ) {
742 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
748 * Fetch the next row from the given result object, in associative array
749 * form. Fields are retrieved with $row['fieldname'].
751 * @param $res SQL result object as returned from Database::query(), etc.
752 * @return MySQL row object
753 * @throws DBUnexpectedError Thrown if the database returns an error
755 function fetchRow( $res ) {
756 if ( $res instanceof ResultWrapper
) {
759 @/**/$row = mysql_fetch_array( $res );
760 if ( $this->lastErrno() ) {
761 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
767 * Get the number of rows in a result object
769 function numRows( $res ) {
770 if ( $res instanceof ResultWrapper
) {
773 @/**/$n = mysql_num_rows( $res );
774 if( $this->lastErrno() ) {
775 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
781 * Get the number of fields in a result object
782 * See documentation for mysql_num_fields()
784 function numFields( $res ) {
785 if ( $res instanceof ResultWrapper
) {
788 return mysql_num_fields( $res );
792 * Get a field name in a result object
793 * See documentation for mysql_field_name():
794 * http://www.php.net/mysql_field_name
796 function fieldName( $res, $n ) {
797 if ( $res instanceof ResultWrapper
) {
800 return mysql_field_name( $res, $n );
804 * Get the inserted value of an auto-increment row
806 * The value inserted should be fetched from nextSequenceValue()
809 * $id = $dbw->nextSequenceValue('page_page_id_seq');
810 * $dbw->insert('page',array('page_id' => $id));
811 * $id = $dbw->insertId();
813 function insertId() { return mysql_insert_id( $this->mConn
); }
816 * Change the position of the cursor in a result object
817 * See mysql_data_seek()
819 function dataSeek( $res, $row ) {
820 if ( $res instanceof ResultWrapper
) {
823 return mysql_data_seek( $res, $row );
827 * Get the last error number
830 function lastErrno() {
831 if ( $this->mConn
) {
832 return mysql_errno( $this->mConn
);
834 return mysql_errno();
839 * Get a description of the last error
840 * See mysql_error() for more details
842 function lastError() {
843 if ( $this->mConn
) {
844 # Even if it's non-zero, it can still be invalid
845 wfSuppressWarnings();
846 $error = mysql_error( $this->mConn
);
848 $error = mysql_error();
852 $error = mysql_error();
855 $error .= ' (' . $this->mServer
. ')';
860 * Get the number of rows affected by the last write query
861 * See mysql_affected_rows() for more details
863 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
864 /**#@-*/ // end of template : @param $result
867 * Simple UPDATE wrapper
868 * Usually aborts on failure
869 * If errors are explicitly ignored, returns success
871 * This function exists for historical reasons, Database::update() has a more standard
872 * calling convention and feature set
874 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
876 $table = $this->tableName( $table );
877 $sql = "UPDATE $table SET $var = '" .
878 $this->strencode( $value ) . "' WHERE ($cond)";
879 return (bool)$this->query( $sql, $fname );
883 * Simple SELECT wrapper, returns a single field, input must be encoded
884 * Usually aborts on failure
885 * If errors are explicitly ignored, returns FALSE on failure
887 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
888 if ( !is_array( $options ) ) {
889 $options = array( $options );
891 $options['LIMIT'] = 1;
893 $res = $this->select( $table, $var, $cond, $fname, $options );
894 if ( $res === false ||
!$this->numRows( $res ) ) {
897 $row = $this->fetchRow( $res );
898 if ( $row !== false ) {
899 $this->freeResult( $res );
907 * Returns an optional USE INDEX clause to go after the table, and a
908 * string to go at the end of the query
912 * @param array $options an associative array of options to be turned into
913 * an SQL query, valid keys are listed in the function.
916 function makeSelectOptions( $options ) {
917 $preLimitTail = $postLimitTail = '';
920 $noKeyOptions = array();
921 foreach ( $options as $key => $option ) {
922 if ( is_numeric( $key ) ) {
923 $noKeyOptions[$option] = true;
927 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
928 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
929 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
931 //if (isset($options['LIMIT'])) {
932 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
933 // isset($options['OFFSET']) ? $options['OFFSET']
937 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
938 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
939 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
941 # Various MySQL extensions
942 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
943 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
944 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
945 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
946 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
947 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
948 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
949 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
951 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
952 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
957 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
963 * @param mixed $table Array or string, table name(s) (prefix auto-added)
964 * @param mixed $vars Array or string, field name(s) to be retrieved
965 * @param mixed $conds Array or string, condition(s) for WHERE
966 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
967 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
968 * see Database::makeSelectOptions code for list of supported stuff
969 * @param array $join_conds Associative array of table join conditions (optional)
970 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
971 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
973 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
975 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
976 return $this->query( $sql, $fname );
982 * @param mixed $table Array or string, table name(s) (prefix auto-added)
983 * @param mixed $vars Array or string, field name(s) to be retrieved
984 * @param mixed $conds Array or string, condition(s) for WHERE
985 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
986 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
987 * see Database::makeSelectOptions code for list of supported stuff
988 * @param array $join_conds Associative array of table join conditions (optional)
989 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
990 * @return string, the SQL text
992 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
993 if( is_array( $vars ) ) {
994 $vars = implode( ',', $vars );
996 if( !is_array( $options ) ) {
997 $options = array( $options );
999 if( is_array( $table ) ) {
1000 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1001 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1003 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1004 } elseif ($table!='') {
1005 if ($table{0}==' ') {
1006 $from = ' FROM ' . $table;
1008 $from = ' FROM ' . $this->tableName( $table );
1014 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1016 if( !empty( $conds ) ) {
1017 if ( is_array( $conds ) ) {
1018 $conds = $this->makeList( $conds, LIST_AND
);
1020 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1022 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1025 if (isset($options['LIMIT']))
1026 $sql = $this->limitResult($sql, $options['LIMIT'],
1027 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1028 $sql = "$sql $postLimitTail";
1030 if (isset($options['EXPLAIN'])) {
1031 $sql = 'EXPLAIN ' . $sql;
1037 * Single row SELECT wrapper
1038 * Aborts or returns FALSE on error
1040 * $vars: the selected variables
1041 * $conds: a condition map, terms are ANDed together.
1042 * Items with numeric keys are taken to be literal conditions
1043 * Takes an array of selected variables, and a condition map, which is ANDed
1044 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1045 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1046 * $obj- >page_id is the ID of the Astronomy article
1048 * @todo migrate documentation to phpdocumentor format
1050 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1051 $options['LIMIT'] = 1;
1052 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1053 if ( $res === false )
1055 if ( !$this->numRows($res) ) {
1056 $this->freeResult($res);
1059 $obj = $this->fetchObject( $res );
1060 $this->freeResult( $res );
1066 * Estimate rows in dataset
1067 * Returns estimated count, based on EXPLAIN output
1068 * Takes same arguments as Database::select()
1071 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1072 $options['EXPLAIN']=true;
1073 $res = $this->select ($table, $vars, $conds, $fname, $options );
1074 if ( $res === false )
1076 if (!$this->numRows($res)) {
1077 $this->freeResult($res);
1083 while( $plan = $this->fetchObject( $res ) ) {
1084 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1087 $this->freeResult($res);
1093 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1094 * It's only slightly flawed. Don't use for anything important.
1096 * @param string $sql A SQL Query
1099 static function generalizeSQL( $sql ) {
1100 # This does the same as the regexp below would do, but in such a way
1101 # as to avoid crashing php on some large strings.
1102 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1104 $sql = str_replace ( "\\\\", '', $sql);
1105 $sql = str_replace ( "\\'", '', $sql);
1106 $sql = str_replace ( "\\\"", '', $sql);
1107 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1108 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1110 # All newlines, tabs, etc replaced by single space
1111 $sql = preg_replace ( '/\s+/', ' ', $sql);
1114 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1120 * Determines whether a field exists in a table
1121 * Usually aborts on failure
1122 * If errors are explicitly ignored, returns NULL on failure
1124 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1125 $table = $this->tableName( $table );
1126 $res = $this->query( 'DESCRIBE '.$table, $fname );
1133 while ( $row = $this->fetchObject( $res ) ) {
1134 if ( $row->Field
== $field ) {
1143 * Determines whether an index exists
1144 * Usually aborts on failure
1145 * If errors are explicitly ignored, returns NULL on failure
1147 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1148 $info = $this->indexInfo( $table, $index, $fname );
1149 if ( is_null( $info ) ) {
1152 return $info !== false;
1158 * Get information about an index into an object
1159 * Returns false if the index does not exist
1161 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1162 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1163 # SHOW INDEX should work for 3.x and up:
1164 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1165 $table = $this->tableName( $table );
1166 $sql = 'SHOW INDEX FROM '.$table;
1167 $res = $this->query( $sql, $fname );
1173 while ( $row = $this->fetchObject( $res ) ) {
1174 if ( $row->Key_name
== $index ) {
1178 $this->freeResult($res);
1180 return empty($result) ?
false : $result;
1184 * Query whether a given table exists
1186 function tableExists( $table ) {
1187 $table = $this->tableName( $table );
1188 $old = $this->ignoreErrors( true );
1189 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1190 $this->ignoreErrors( $old );
1192 $this->freeResult( $res );
1200 * mysql_fetch_field() wrapper
1201 * Returns false if the field doesn't exist
1206 function fieldInfo( $table, $field ) {
1207 $table = $this->tableName( $table );
1208 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1209 $n = mysql_num_fields( $res->result
);
1210 for( $i = 0; $i < $n; $i++
) {
1211 $meta = mysql_fetch_field( $res->result
, $i );
1212 if( $field == $meta->name
) {
1213 return new MySQLField($meta);
1220 * mysql_field_type() wrapper
1222 function fieldType( $res, $index ) {
1223 if ( $res instanceof ResultWrapper
) {
1224 $res = $res->result
;
1226 return mysql_field_type( $res, $index );
1230 * Determines if a given index is unique
1232 function indexUnique( $table, $index ) {
1233 $indexInfo = $this->indexInfo( $table, $index );
1234 if ( !$indexInfo ) {
1237 return !$indexInfo[0]->Non_unique
;
1241 * INSERT wrapper, inserts an array into a table
1243 * $a may be a single associative array, or an array of these with numeric keys, for
1246 * Usually aborts on failure
1247 * If errors are explicitly ignored, returns success
1249 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1250 # No rows to insert, easy just return now
1251 if ( !count( $a ) ) {
1255 $table = $this->tableName( $table );
1256 if ( !is_array( $options ) ) {
1257 $options = array( $options );
1259 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1261 $keys = array_keys( $a[0] );
1264 $keys = array_keys( $a );
1267 $sql = 'INSERT ' . implode( ' ', $options ) .
1268 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1272 foreach ( $a as $row ) {
1278 $sql .= '(' . $this->makeList( $row ) . ')';
1281 $sql .= '(' . $this->makeList( $a ) . ')';
1283 return (bool)$this->query( $sql, $fname );
1287 * Make UPDATE options for the Database::update function
1290 * @param array $options The options passed to Database::update
1293 function makeUpdateOptions( $options ) {
1294 if( !is_array( $options ) ) {
1295 $options = array( $options );
1298 if ( in_array( 'LOW_PRIORITY', $options ) )
1299 $opts[] = $this->lowPriorityOption();
1300 if ( in_array( 'IGNORE', $options ) )
1302 return implode(' ', $opts);
1306 * UPDATE wrapper, takes a condition array and a SET array
1308 * @param string $table The table to UPDATE
1309 * @param array $values An array of values to SET
1310 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1311 * @param string $fname The Class::Function calling this function
1313 * @param array $options An array of UPDATE options, can be one or
1314 * more of IGNORE, LOW_PRIORITY
1317 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1318 $table = $this->tableName( $table );
1319 $opts = $this->makeUpdateOptions( $options );
1320 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1321 if ( $conds != '*' ) {
1322 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1324 return $this->query( $sql, $fname );
1328 * Makes an encoded list of strings from an array
1330 * LIST_COMMA - comma separated, no field names
1331 * LIST_AND - ANDed WHERE clause (without the WHERE)
1332 * LIST_OR - ORed WHERE clause (without the WHERE)
1333 * LIST_SET - comma separated with field names, like a SET clause
1334 * LIST_NAMES - comma separated field names
1336 function makeList( $a, $mode = LIST_COMMA
) {
1337 if ( !is_array( $a ) ) {
1338 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1343 foreach ( $a as $field => $value ) {
1345 if ( $mode == LIST_AND
) {
1347 } elseif($mode == LIST_OR
) {
1355 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1356 $list .= "($value)";
1357 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1359 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1360 if( count( $value ) == 0 ) {
1361 throw new MWException( __METHOD__
.': empty input' );
1362 } elseif( count( $value ) == 1 ) {
1363 // Special-case single values, as IN isn't terribly efficient
1364 // Don't necessarily assume the single key is 0; we don't
1365 // enforce linear numeric ordering on other arrays here.
1366 $value = array_values( $value );
1367 $list .= $field." = ".$this->addQuotes( $value[0] );
1369 $list .= $field." IN (".$this->makeList($value).") ";
1371 } elseif( is_null($value) ) {
1372 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1373 $list .= "$field IS ";
1374 } elseif ( $mode == LIST_SET
) {
1375 $list .= "$field = ";
1379 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1380 $list .= "$field = ";
1382 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1389 * Change the current database
1391 function selectDB( $db ) {
1392 $this->mDBname
= $db;
1393 return mysql_select_db( $db, $this->mConn
);
1397 * Get the current DB name
1399 function getDBname() {
1400 return $this->mDBname
;
1404 * Get the server hostname or IP address
1406 function getServer() {
1407 return $this->mServer
;
1411 * Format a table name ready for use in constructing an SQL query
1413 * This does two important things: it quotes the table names to clean them up,
1414 * and it adds a table prefix if only given a table name with no quotes.
1416 * All functions of this object which require a table name call this function
1417 * themselves. Pass the canonical name to such functions. This is only needed
1418 * when calling query() directly.
1420 * @param string $name database table name
1421 * @return string full database name
1423 function tableName( $name ) {
1424 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1425 # Skip the entire process when we have a string quoted on both ends.
1426 # Note that we check the end so that we will still quote any use of
1427 # use of `database`.table. But won't break things if someone wants
1428 # to query a database table with a dot in the name.
1429 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1431 # Lets test for any bits of text that should never show up in a table
1432 # name. Basically anything like JOIN or ON which are actually part of
1433 # SQL queries, but may end up inside of the table value to combine
1434 # sql. Such as how the API is doing.
1435 # Note that we use a whitespace test rather than a \b test to avoid
1436 # any remote case where a word like on may be inside of a table name
1437 # surrounded by symbols which may be considered word breaks.
1438 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1440 # Split database and table into proper variables.
1441 # We reverse the explode so that database.table and table both output
1442 # the correct table.
1443 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1444 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1445 else @list
( $table ) = $dbDetails;
1446 $prefix = $this->mTablePrefix
; # Default prefix
1448 # A database name has been specified in input. Quote the table name
1449 # because we don't want any prefixes added.
1450 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1452 # Note that we use the long format because php will complain in in_array if
1453 # the input is not an array, and will complain in is_array if it is not set.
1454 if( !isset( $database ) # Don't use shared database if pre selected.
1455 && isset( $wgSharedDB ) # We have a shared database
1456 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1457 && isset( $wgSharedTables )
1458 && is_array( $wgSharedTables )
1459 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1460 $database = $wgSharedDB;
1461 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1464 # Quote the $database and $table and apply the prefix if not quoted.
1465 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1466 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1468 # Merge our database and table into our final table name.
1469 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1471 # We're finished, return.
1476 * Fetch a number of table names into an array
1477 * This is handy when you need to construct SQL for joins
1480 * extract($dbr->tableNames('user','watchlist'));
1481 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1482 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1484 public function tableNames() {
1485 $inArray = func_get_args();
1487 foreach ( $inArray as $name ) {
1488 $retVal[$name] = $this->tableName( $name );
1494 * Fetch a number of table names into an zero-indexed numerical array
1495 * This is handy when you need to construct SQL for joins
1498 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1499 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1500 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1502 public function tableNamesN() {
1503 $inArray = func_get_args();
1505 foreach ( $inArray as $name ) {
1506 $retVal[] = $this->tableName( $name );
1514 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1517 $use_index_safe = is_array($use_index) ?
$use_index : array();
1518 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1519 foreach ( $tables as $table ) {
1520 // Is there a JOIN and INDEX clause for this table?
1521 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1522 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1523 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1524 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1525 $retJOIN[] = $tableClause;
1526 // Is there an INDEX clause?
1527 } else if ( isset($use_index_safe[$table]) ) {
1528 $tableClause = $this->tableName( $table );
1529 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1530 $ret[] = $tableClause;
1531 // Is there a JOIN clause?
1532 } else if ( isset($join_conds_safe[$table]) ) {
1533 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1534 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1535 $retJOIN[] = $tableClause;
1537 $tableClause = $this->tableName( $table );
1538 $ret[] = $tableClause;
1541 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1542 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1543 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1544 // Compile our final table clause
1545 return implode(' ',array($straightJoins,$otherJoins) );
1549 * Wrapper for addslashes()
1550 * @param string $s String to be slashed.
1551 * @return string slashed string.
1553 function strencode( $s ) {
1554 return mysql_real_escape_string( $s, $this->mConn
);
1558 * If it's a string, adds quotes and backslashes
1559 * Otherwise returns as-is
1561 function addQuotes( $s ) {
1562 if ( is_null( $s ) ) {
1565 # This will also quote numeric values. This should be harmless,
1566 # and protects against weird problems that occur when they really
1567 # _are_ strings such as article titles and string->number->string
1568 # conversion is not 1:1.
1569 return "'" . $this->strencode( $s ) . "'";
1574 * Escape string for safe LIKE usage
1576 function escapeLike( $s ) {
1577 $s=$this->strencode( $s );
1578 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1583 * Returns an appropriately quoted sequence value for inserting a new row.
1584 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1585 * subclass will return an integer, and save the value for insertId()
1587 function nextSequenceValue( $seqName ) {
1593 * PostgreSQL doesn't have them and returns ""
1595 function useIndexClause( $index ) {
1596 return "FORCE INDEX ($index)";
1600 * REPLACE query wrapper
1601 * PostgreSQL simulates this with a DELETE followed by INSERT
1602 * $row is the row to insert, an associative array
1603 * $uniqueIndexes is an array of indexes. Each element may be either a
1604 * field name or an array of field names
1606 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1607 * However if you do this, you run the risk of encountering errors which wouldn't have
1610 * @todo migrate comment to phodocumentor format
1612 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1613 $table = $this->tableName( $table );
1616 if ( !is_array( reset( $rows ) ) ) {
1617 $rows = array( $rows );
1620 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1622 foreach ( $rows as $row ) {
1628 $sql .= '(' . $this->makeList( $row ) . ')';
1630 return $this->query( $sql, $fname );
1634 * DELETE where the condition is a join
1635 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1637 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1638 * join condition matches, set $conds='*'
1640 * DO NOT put the join condition in $conds
1642 * @param string $delTable The table to delete from.
1643 * @param string $joinTable The other table.
1644 * @param string $delVar The variable to join on, in the first table.
1645 * @param string $joinVar The variable to join on, in the second table.
1646 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1648 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1650 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1653 $delTable = $this->tableName( $delTable );
1654 $joinTable = $this->tableName( $joinTable );
1655 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1656 if ( $conds != '*' ) {
1657 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1660 return $this->query( $sql, $fname );
1664 * Returns the size of a text field, or -1 for "unlimited"
1666 function textFieldSize( $table, $field ) {
1667 $table = $this->tableName( $table );
1668 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1669 $res = $this->query( $sql, 'Database::textFieldSize' );
1670 $row = $this->fetchObject( $res );
1671 $this->freeResult( $res );
1674 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1683 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1685 function lowPriorityOption() {
1686 return 'LOW_PRIORITY';
1690 * DELETE query wrapper
1692 * Use $conds == "*" to delete all rows
1694 function delete( $table, $conds, $fname = 'Database::delete' ) {
1696 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1698 $table = $this->tableName( $table );
1699 $sql = "DELETE FROM $table";
1700 if ( $conds != '*' ) {
1701 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1703 return $this->query( $sql, $fname );
1707 * INSERT SELECT wrapper
1708 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1709 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1710 * $conds may be "*" to copy the whole table
1711 * srcTable may be an array of tables.
1713 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1714 $insertOptions = array(), $selectOptions = array() )
1716 $destTable = $this->tableName( $destTable );
1717 if ( is_array( $insertOptions ) ) {
1718 $insertOptions = implode( ' ', $insertOptions );
1720 if( !is_array( $selectOptions ) ) {
1721 $selectOptions = array( $selectOptions );
1723 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1724 if( is_array( $srcTable ) ) {
1725 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1727 $srcTable = $this->tableName( $srcTable );
1729 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1730 " SELECT $startOpts " . implode( ',', $varMap ) .
1731 " FROM $srcTable $useIndex ";
1732 if ( $conds != '*' ) {
1733 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1735 $sql .= " $tailOpts";
1736 return $this->query( $sql, $fname );
1740 * Construct a LIMIT query with optional offset
1741 * This is used for query pages
1742 * $sql string SQL query we will append the limit too
1743 * $limit integer the SQL limit
1744 * $offset integer the SQL offset (default false)
1746 function limitResult($sql, $limit, $offset=false) {
1747 if( !is_numeric($limit) ) {
1748 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1750 return "$sql LIMIT "
1751 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1754 function limitResultForUpdate($sql, $num) {
1755 return $this->limitResult($sql, $num, 0);
1759 * Returns an SQL expression for a simple conditional.
1762 * @param string $cond SQL expression which will result in a boolean value
1763 * @param string $trueVal SQL expression to return if true
1764 * @param string $falseVal SQL expression to return if false
1765 * @return string SQL fragment
1767 function conditional( $cond, $trueVal, $falseVal ) {
1768 return " IF($cond, $trueVal, $falseVal) ";
1772 * Returns a comand for str_replace function in SQL query.
1773 * Uses REPLACE() in MySQL
1775 * @param string $orig String or column to modify
1776 * @param string $old String or column to seek
1777 * @param string $new String or column to replace with
1779 function strreplace( $orig, $old, $new ) {
1780 return "REPLACE({$orig}, {$old}, {$new})";
1784 * Determines if the last failure was due to a deadlock
1786 function wasDeadlock() {
1787 return $this->lastErrno() == 1213;
1791 * Perform a deadlock-prone transaction.
1793 * This function invokes a callback function to perform a set of write
1794 * queries. If a deadlock occurs during the processing, the transaction
1795 * will be rolled back and the callback function will be called again.
1798 * $dbw->deadlockLoop( callback, ... );
1800 * Extra arguments are passed through to the specified callback function.
1802 * Returns whatever the callback function returned on its successful,
1803 * iteration, or false on error, for example if the retry limit was
1806 function deadlockLoop() {
1807 $myFname = 'Database::deadlockLoop';
1810 $args = func_get_args();
1811 $function = array_shift( $args );
1812 $oldIgnore = $this->ignoreErrors( true );
1813 $tries = DEADLOCK_TRIES
;
1814 if ( is_array( $function ) ) {
1815 $fname = $function[0];
1820 $retVal = call_user_func_array( $function, $args );
1821 $error = $this->lastError();
1822 $errno = $this->lastErrno();
1823 $sql = $this->lastQuery();
1826 if ( $this->wasDeadlock() ) {
1828 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1830 $this->reportQueryError( $error, $errno, $sql, $fname );
1833 } while( $this->wasDeadlock() && --$tries > 0 );
1834 $this->ignoreErrors( $oldIgnore );
1835 if ( $tries <= 0 ) {
1836 $this->query( 'ROLLBACK', $myFname );
1837 $this->reportQueryError( $error, $errno, $sql, $fname );
1840 $this->query( 'COMMIT', $myFname );
1846 * Do a SELECT MASTER_POS_WAIT()
1848 * @param string $file the binlog file
1849 * @param string $pos the binlog position
1850 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1852 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1853 $fname = 'Database::masterPosWait';
1854 wfProfileIn( $fname );
1856 # Commit any open transactions
1857 if ( $this->mTrxLevel
) {
1858 $this->immediateCommit();
1861 if ( !is_null( $this->mFakeSlaveLag
) ) {
1862 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1863 if ( $wait > $timeout * 1e6
) {
1864 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1865 wfProfileOut( $fname );
1867 } elseif ( $wait > 0 ) {
1868 wfDebug( "Fake slave waiting $wait us\n" );
1870 wfProfileOut( $fname );
1873 wfDebug( "Fake slave up to date ($wait us)\n" );
1874 wfProfileOut( $fname );
1879 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1880 $encFile = $this->addQuotes( $pos->file
);
1881 $encPos = intval( $pos->pos
);
1882 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1883 $res = $this->doQuery( $sql );
1884 if ( $res && $row = $this->fetchRow( $res ) ) {
1885 $this->freeResult( $res );
1886 wfProfileOut( $fname );
1889 wfProfileOut( $fname );
1895 * Get the position of the master from SHOW SLAVE STATUS
1897 function getSlavePos() {
1898 if ( !is_null( $this->mFakeSlaveLag
) ) {
1899 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1900 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1903 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1904 $row = $this->fetchObject( $res );
1906 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1913 * Get the position of the master from SHOW MASTER STATUS
1915 function getMasterPos() {
1916 if ( $this->mFakeMaster
) {
1917 return new MySQLMasterPos( 'fake', microtime( true ) );
1919 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1920 $row = $this->fetchObject( $res );
1922 return new MySQLMasterPos( $row->File
, $row->Position
);
1929 * Begin a transaction, committing any previously open transaction
1931 function begin( $fname = 'Database::begin' ) {
1932 $this->query( 'BEGIN', $fname );
1933 $this->mTrxLevel
= 1;
1939 function commit( $fname = 'Database::commit' ) {
1940 $this->query( 'COMMIT', $fname );
1941 $this->mTrxLevel
= 0;
1945 * Rollback a transaction.
1946 * No-op on non-transactional databases.
1948 function rollback( $fname = 'Database::rollback' ) {
1949 $this->query( 'ROLLBACK', $fname, true );
1950 $this->mTrxLevel
= 0;
1954 * Begin a transaction, committing any previously open transaction
1955 * @deprecated use begin()
1957 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1962 * Commit transaction, if one is open
1963 * @deprecated use commit()
1965 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1970 * Return MW-style timestamp used for MySQL schema
1972 function timestamp( $ts=0 ) {
1973 return wfTimestamp(TS_MW
,$ts);
1977 * Local database timestamp format or null
1979 function timestampOrNull( $ts = null ) {
1980 if( is_null( $ts ) ) {
1983 return $this->timestamp( $ts );
1990 function resultObject( $result ) {
1991 if( empty( $result ) ) {
1993 } elseif ( $result instanceof ResultWrapper
) {
1995 } elseif ( $result === true ) {
1996 // Successful write query
1999 return new ResultWrapper( $this, $result );
2004 * Return aggregated value alias
2006 function aggregateValue ($valuedata,$valuename='value') {
2011 * @return string wikitext of a link to the server software's web site
2013 function getSoftwareLink() {
2014 return "[http://www.mysql.com/ MySQL]";
2018 * @return string Version information from the database
2020 function getServerVersion() {
2021 return mysql_get_server_info( $this->mConn
);
2025 * Ping the server and try to reconnect if it there is no connection
2028 if( !function_exists( 'mysql_ping' ) ) {
2029 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2032 $ping = mysql_ping( $this->mConn
);
2037 // Need to reconnect manually in MySQL client 5.0.13+
2038 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2039 mysql_close( $this->mConn
);
2040 $this->mOpened
= false;
2041 $this->mConn
= false;
2042 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2050 * At the moment, this will only work if the DB user has the PROCESS privilege
2053 if ( !is_null( $this->mFakeSlaveLag
) ) {
2054 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2055 return $this->mFakeSlaveLag
;
2057 $res = $this->query( 'SHOW PROCESSLIST' );
2058 # Find slave SQL thread
2059 while ( $row = $this->fetchObject( $res ) ) {
2060 /* This should work for most situations - when default db
2061 * for thread is not specified, it had no events executed,
2062 * and therefore it doesn't know yet how lagged it is.
2064 * Relay log I/O thread does not select databases.
2066 if ( $row->User
== 'system user' &&
2067 $row->State
!= 'Waiting for master to send event' &&
2068 $row->State
!= 'Connecting to master' &&
2069 $row->State
!= 'Queueing master event to the relay log' &&
2070 $row->State
!= 'Waiting for master update' &&
2071 $row->State
!= 'Requesting binlog dump'
2073 # This is it, return the time (except -ve)
2074 if ( $row->Time
> 0x7fffffff ) {
2085 * Get status information from SHOW STATUS in an associative array
2087 function getStatus($which="%") {
2088 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2090 while ( $row = $this->fetchObject( $res ) ) {
2091 $status[$row->Variable_name
] = $row->Value
;
2097 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2099 function maxListLen() {
2103 function encodeBlob($b) {
2107 function decodeBlob($b) {
2112 * Override database's default connection timeout.
2113 * May be useful for very long batch queries such as
2114 * full-wiki dumps, where a single query reads out
2115 * over hours or days.
2116 * @param int $timeout in seconds
2118 public function setTimeout( $timeout ) {
2119 $this->query( "SET net_read_timeout=$timeout" );
2120 $this->query( "SET net_write_timeout=$timeout" );
2124 * Read and execute SQL commands from a file.
2125 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2126 * @param string $filename File name to open
2127 * @param callback $lineCallback Optional function called before reading each line
2128 * @param callback $resultCallback Optional function called for each MySQL result
2130 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2131 $fp = fopen( $filename, 'r' );
2132 if ( false === $fp ) {
2133 throw new MWException( "Could not open \"{$filename}\".\n" );
2135 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2141 * Read and execute commands from an open file handle
2142 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2143 * @param string $fp File handle
2144 * @param callback $lineCallback Optional function called before reading each line
2145 * @param callback $resultCallback Optional function called for each MySQL result
2147 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2150 $dollarquote = false;
2152 while ( ! feof( $fp ) ) {
2153 if ( $lineCallback ) {
2154 call_user_func( $lineCallback );
2156 $line = trim( fgets( $fp, 1024 ) );
2157 $sl = strlen( $line ) - 1;
2159 if ( $sl < 0 ) { continue; }
2160 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2162 ## Allow dollar quoting for function declarations
2163 if (substr($line,0,4) == '$mw$') {
2165 $dollarquote = false;
2169 $dollarquote = true;
2172 else if (!$dollarquote) {
2173 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2175 $line = substr( $line, 0, $sl );
2179 if ( '' != $cmd ) { $cmd .= ' '; }
2183 $cmd = str_replace(';;', ";", $cmd);
2184 $cmd = $this->replaceVars( $cmd );
2185 $res = $this->query( $cmd, __METHOD__
);
2186 if ( $resultCallback ) {
2187 call_user_func( $resultCallback, $res, $this );
2190 if ( false === $res ) {
2191 $err = $this->lastError();
2192 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2204 * Replace variables in sourced SQL
2206 protected function replaceVars( $ins ) {
2208 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2209 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2210 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2213 // Ordinary variables
2214 foreach ( $varnames as $var ) {
2215 if( isset( $GLOBALS[$var] ) ) {
2216 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2217 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2218 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2219 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2224 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2225 array( &$this, 'tableNameCallback' ), $ins );
2230 * Table name callback
2233 protected function tableNameCallback( $matches ) {
2234 return $this->tableName( $matches[1] );
2238 * Build a concatenation list to feed into a SQL query
2240 function buildConcat( $stringList ) {
2241 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2247 * Abstracted from Filestore::lock() so child classes can implement for
2250 * @param string $lockName Name of lock to aquire
2251 * @param string $method Name of method calling us
2254 public function lock( $lockName, $method ) {
2255 $lockName = $this->addQuotes( $lockName );
2256 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2257 $row = $this->fetchObject( $result );
2258 $this->freeResult( $result );
2260 if( $row->lockstatus
== 1 ) {
2263 wfDebug( __METHOD__
." failed to acquire lock\n" );
2270 * @todo fixme - Figure out a way to return a bool
2271 * based on successful lock release.
2273 * @param string $lockName Name of lock to release
2274 * @param string $method Name of method calling us
2276 public function unlock( $lockName, $method ) {
2277 $lockName = $this->addQuotes( $lockName );
2278 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2279 $this->freeResult( $result );
2283 * Get search engine class. All subclasses of this
2284 * need to implement this if they wish to use searching.
2288 public function getSearchEngine() {
2289 return "SearchMySQL";
2294 * Database abstraction object for mySQL
2295 * Inherit all methods and properties of Database::Database()
2300 class DatabaseMysql
extends Database
{
2304 /******************************************************************************
2306 *****************************************************************************/
2315 function DBObject($data) {
2316 $this->mData
= $data;
2324 return $this->mData
;
2332 * This allows us to distinguish a blob from a normal string and an array of strings
2336 function __construct($data) {
2337 $this->mData
= $data;
2340 return $this->mData
;
2349 private $name, $tablename, $default, $max_length, $nullable,
2350 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2351 function __construct ($info) {
2352 $this->name
= $info->name
;
2353 $this->tablename
= $info->table
;
2354 $this->default = $info->def
;
2355 $this->max_length
= $info->max_length
;
2356 $this->nullable
= !$info->not_null
;
2357 $this->is_pk
= $info->primary_key
;
2358 $this->is_unique
= $info->unique_key
;
2359 $this->is_multiple
= $info->multiple_key
;
2360 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2361 $this->type
= $info->type
;
2368 function tableName() {
2369 return $this->tableName
;
2372 function defaultValue() {
2373 return $this->default;
2376 function maxLength() {
2377 return $this->max_length
;
2380 function nullable() {
2381 return $this->nullable
;
2385 return $this->is_key
;
2388 function isMultipleKey() {
2389 return $this->is_multiple
;
2397 /******************************************************************************
2399 *****************************************************************************/
2402 * Database error base class
2405 class DBError
extends MWException
{
2409 * Construct a database error
2410 * @param Database $db The database object which threw the error
2411 * @param string $error A simple error message to be used for debugging
2413 function __construct( Database
&$db, $error ) {
2415 parent
::__construct( $error );
2422 class DBConnectionError
extends DBError
{
2425 function __construct( Database
&$db, $error = 'unknown error' ) {
2426 $msg = 'DB connection error';
2427 if ( trim( $error ) != '' ) {
2430 $this->error
= $error;
2431 parent
::__construct( $db, $msg );
2434 function useOutputPage() {
2435 // Not likely to work
2439 function useMessageCache() {
2440 // Not likely to work
2444 function getText() {
2445 return $this->getMessage() . "\n";
2448 function getLogMessage() {
2449 # Don't send to the exception log
2453 function getPageTitle() {
2455 return "$wgSitename has a problem";
2458 function getHTML() {
2459 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2460 global $wgSitename, $wgServer, $wgMessageCache;
2462 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2463 # Hard coding strings instead.
2465 $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>";
2466 $mainpage = 'Main Page';
2467 $searchdisabled = <<<EOT
2468 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2469 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2473 <!-- SiteSearch Google -->
2474 <FORM method=GET action=\"http://www.google.com/search\">
2475 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2476 <A HREF=\"http://www.google.com/\">
2477 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2478 border=\"0\" ALT=\"Google\"></A>
2481 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2482 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2484 <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 />
2485 <input type='hidden' name='ie' value='$2'>
2486 <input type='hidden' name='oe' value='$2'>
2490 <!-- SiteSearch Google -->";
2491 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2493 # No database access
2494 if ( is_object( $wgMessageCache ) ) {
2495 $wgMessageCache->disable();
2498 if ( trim( $this->error
) == '' ) {
2499 $this->error
= $this->db
->getProperty('mServer');
2502 $text = str_replace( '$1', $this->error
, $noconnect );
2503 $text .= wfGetSiteNotice();
2505 if($wgUseFileCache) {
2510 $t = Title
::newFromURL( $title );
2511 } elseif (@/**/$_REQUEST['search']) {
2512 $search = $_REQUEST['search'];
2513 return $searchdisabled .
2514 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2515 $wgInputEncoding ), $googlesearch );
2517 $t = Title
::newFromText( $mainpage );
2521 $cache = new HTMLFileCache( $t );
2522 if( $cache->isFileCached() ) {
2523 // @todo, FIXME: $msg is not defined on the next line.
2524 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2525 $cachederror . "</b></p>\n";
2527 $tag = '<div id="article">';
2528 $text = str_replace(
2531 $cache->fetchPageText() );
2542 class DBQueryError
extends DBError
{
2543 public $error, $errno, $sql, $fname;
2545 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2546 $message = "A database error has occurred\n" .
2548 "Function: $fname\n" .
2549 "Error: $errno $error\n";
2551 parent
::__construct( $db, $message );
2552 $this->error
= $error;
2553 $this->errno
= $errno;
2555 $this->fname
= $fname;
2558 function getText() {
2559 if ( $this->useMessageCache() ) {
2560 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2561 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2563 return $this->getMessage();
2568 global $wgShowSQLErrors;
2569 if( !$wgShowSQLErrors ) {
2570 return $this->msg( 'sqlhidden', 'SQL hidden' );
2576 function getLogMessage() {
2577 # Don't send to the exception log
2581 function getPageTitle() {
2582 return $this->msg( 'databaseerror', 'Database error' );
2585 function getHTML() {
2586 if ( $this->useMessageCache() ) {
2587 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2588 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2590 return nl2br( htmlspecialchars( $this->getMessage() ) );
2598 class DBUnexpectedError
extends DBError
{}
2602 * Result wrapper for grabbing data queried by someone else
2605 class ResultWrapper
implements Iterator
{
2606 var $db, $result, $pos = 0, $currentRow = null;
2609 * Create a new result object from a result resource and a Database object
2611 function ResultWrapper( $database, $result ) {
2612 $this->db
= $database;
2613 if ( $result instanceof ResultWrapper
) {
2614 $this->result
= $result->result
;
2616 $this->result
= $result;
2621 * Get the number of rows in a result object
2623 function numRows() {
2624 return $this->db
->numRows( $this->result
);
2628 * Fetch the next row from the given result object, in object form.
2629 * Fields can be retrieved with $row->fieldname, with fields acting like
2632 * @param $res SQL result object as returned from Database::query(), etc.
2633 * @return MySQL row object
2634 * @throws DBUnexpectedError Thrown if the database returns an error
2636 function fetchObject() {
2637 return $this->db
->fetchObject( $this->result
);
2641 * Fetch the next row from the given result object, in associative array
2642 * form. Fields are retrieved with $row['fieldname'].
2644 * @param $res SQL result object as returned from Database::query(), etc.
2645 * @return MySQL row object
2646 * @throws DBUnexpectedError Thrown if the database returns an error
2648 function fetchRow() {
2649 return $this->db
->fetchRow( $this->result
);
2653 * Free a result object
2656 $this->db
->freeResult( $this->result
);
2657 unset( $this->result
);
2662 * Change the position of the cursor in a result object
2663 * See mysql_data_seek()
2665 function seek( $row ) {
2666 $this->db
->dataSeek( $this->result
, $row );
2669 /*********************
2670 * Iterator functions
2671 * Note that using these in combination with the non-iterator functions
2672 * above may cause rows to be skipped or repeated.
2676 if ($this->numRows()) {
2677 $this->db
->dataSeek($this->result
, 0);
2680 $this->currentRow
= null;
2683 function current() {
2684 if ( is_null( $this->currentRow
) ) {
2687 return $this->currentRow
;
2696 $this->currentRow
= $this->fetchObject();
2697 return $this->currentRow
;
2701 return $this->current() !== false;
2705 class MySQLMasterPos
{
2708 function __construct( $file, $pos ) {
2709 $this->file
= $file;
2713 function __toString() {
2714 return "{$this->file}/{$this->pos}";