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 $wguname, $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 # Try to connect up to three times
347 # The kernel's default SYN retransmission period is far too slow for us,
348 # so we use a short timeout plus a manual retry.
349 $this->mConn
= false;
351 $this->installErrorHandler();
352 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
356 if ( $this->mFlags
& DBO_PERSISTENT
) {
357 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
359 # Create a new connection...
360 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
362 if ($this->mConn
=== false) {
364 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
367 $phpError = $this->restoreErrorHandler();
369 wfProfileOut("dbconnect-$server");
371 if ( $dbName != '' ) {
372 if ( $this->mConn
!== false ) {
373 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
375 $error = "Error selecting database $dbName on server {$this->mServer} " .
376 "from client host {$wguname['nodename']}\n";
377 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
381 wfDebug( "DB connection error\n" );
382 wfDebug( "Server: $server, User: $user, Password: " .
383 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
388 $success = (bool)$this->mConn
;
392 $version = $this->getServerVersion();
393 if ( version_compare( $version, '4.1' ) >= 0 ) {
394 // Tell the server we're communicating with it in UTF-8.
395 // This may engage various charset conversions.
398 $this->query( 'SET NAMES utf8', __METHOD__
);
400 // Turn off strict mode
401 $this->query( "SET sql_mode = ''", __METHOD__
);
404 // Turn off strict mode if it is on
406 $this->reportConnectionError( $phpError );
409 $this->mOpened
= $success;
410 wfProfileOut( __METHOD__
);
415 protected function installErrorHandler() {
416 $this->mPHPError
= false;
417 set_error_handler( array( $this, 'connectionErrorHandler' ) );
420 protected function restoreErrorHandler() {
421 restore_error_handler();
422 return $this->mPHPError
;
425 protected function connectionErrorHandler( $errno, $errstr ) {
426 $this->mPHPError
= $errstr;
430 * Closes a database connection.
431 * if it is open : commits any open transactions
433 * @return bool operation success. true if already closed.
437 $this->mOpened
= false;
438 if ( $this->mConn
) {
439 if ( $this->trxLevel() ) {
440 $this->immediateCommit();
442 return mysql_close( $this->mConn
);
449 * @param string $error fallback error message, used if none is given by MySQL
451 function reportConnectionError( $error = 'Unknown error' ) {
452 $myError = $this->lastError();
457 if ( $this->mFailFunction
) {
458 # Legacy error handling method
459 if ( !is_int( $this->mFailFunction
) ) {
460 $ff = $this->mFailFunction
;
461 $ff( $this, $error );
465 wfLogDBError( "Connection error: $error\n" );
466 throw new DBConnectionError( $this, $error );
471 * Usually aborts on failure. If errors are explicitly ignored, returns success.
473 * @param $sql String: SQL query
474 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
475 * comment (you can use __METHOD__ or add some extra info)
476 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
477 * maybe best to catch the exception instead?
478 * @return true for a successful write query, ResultWrapper object for a successful read query,
479 * or false on failure if $tempIgnore set
480 * @throws DBQueryError Thrown when the database returns an error of any kind
482 public function query( $sql, $fname = '', $tempIgnore = false ) {
485 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
486 if ( isset( $wgProfiler ) ) {
487 # generalizeSQL will probably cut down the query to reasonable
488 # logging size most of the time. The substr is really just a sanity check.
490 # Who's been wasting my precious column space? -- TS
491 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
494 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
495 $totalProf = 'Database::query-master';
497 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
498 $totalProf = 'Database::query';
500 wfProfileIn( $totalProf );
501 wfProfileIn( $queryProf );
504 $this->mLastQuery
= $sql;
506 # Add a comment for easy SHOW PROCESSLIST interpretation
509 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
510 $userName = $wgUser->getName();
511 if ( mb_strlen( $userName ) > 15 ) {
512 $userName = mb_substr( $userName, 0, 15 ) . '...';
514 $userName = str_replace( '/', '', $userName );
518 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
520 # $commentedSql = $sql;
523 # If DBO_TRX is set, start a transaction
524 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
525 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
526 // avoid establishing transactions for SHOW and SET statements too -
527 // that would delay transaction initializations to once connection
528 // is really used by application
529 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
530 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
534 if ( $this->debug() ) {
535 $sqlx = substr( $commentedSql, 0, 500 );
536 $sqlx = strtr( $sqlx, "\t\n", ' ' );
538 wfDebug( "SQL-master: $sqlx\n" );
540 wfDebug( "SQL: $sqlx\n" );
544 # Do the query and handle errors
545 $ret = $this->doQuery( $commentedSql );
547 # Try reconnecting if the connection was lost
548 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
549 # Transaction is gone, like it or not
550 $this->mTrxLevel
= 0;
551 wfDebug( "Connection lost, reconnecting...\n" );
552 if ( $this->ping() ) {
553 wfDebug( "Reconnected\n" );
554 $sqlx = substr( $commentedSql, 0, 500 );
555 $sqlx = strtr( $sqlx, "\t\n", ' ' );
556 global $wgRequestTime;
557 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
558 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
559 $ret = $this->doQuery( $commentedSql );
561 wfDebug( "Failed\n" );
565 if ( false === $ret ) {
566 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
569 if ( isset( $wgProfiler ) ) {
570 wfProfileOut( $queryProf );
571 wfProfileOut( $totalProf );
573 return $this->resultObject( $ret );
577 * The DBMS-dependent part of query()
578 * @param $sql String: SQL query.
579 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
582 /*private*/ function doQuery( $sql ) {
583 if( $this->bufferResults() ) {
584 $ret = mysql_query( $sql, $this->mConn
);
586 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
595 * @param string $fname
596 * @param bool $tempIgnore
598 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
599 global $wgCommandLineMode;
600 # Ignore errors during error handling to avoid infinite recursion
601 $ignore = $this->ignoreErrors( true );
602 ++
$this->mErrorCount
;
604 if( $ignore ||
$tempIgnore ) {
605 wfDebug("SQL ERROR (ignored): $error\n");
606 $this->ignoreErrors( $ignore );
608 $sql1line = str_replace( "\n", "\\n", $sql );
609 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
610 wfDebug("SQL ERROR: " . $error . "\n");
611 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
617 * Intended to be compatible with the PEAR::DB wrapper functions.
618 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
620 * ? = scalar value, quoted as necessary
621 * ! = raw SQL bit (a function for instance)
622 * & = filename; reads the file and inserts as a blob
623 * (we don't use this though...)
625 function prepare( $sql, $func = 'Database::prepare' ) {
626 /* MySQL doesn't support prepared statements (yet), so just
627 pack up the query for reference. We'll manually replace
629 return array( 'query' => $sql, 'func' => $func );
632 function freePrepared( $prepared ) {
633 /* No-op for MySQL */
637 * Execute a prepared query with the various arguments
638 * @param string $prepared the prepared sql
639 * @param mixed $args Either an array here, or put scalars as varargs
641 function execute( $prepared, $args = null ) {
642 if( !is_array( $args ) ) {
644 $args = func_get_args();
645 array_shift( $args );
647 $sql = $this->fillPrepared( $prepared['query'], $args );
648 return $this->query( $sql, $prepared['func'] );
652 * Prepare & execute an SQL statement, quoting and inserting arguments
653 * in the appropriate places.
654 * @param string $query
655 * @param string $args ...
657 function safeQuery( $query, $args = null ) {
658 $prepared = $this->prepare( $query, 'Database::safeQuery' );
659 if( !is_array( $args ) ) {
661 $args = func_get_args();
662 array_shift( $args );
664 $retval = $this->execute( $prepared, $args );
665 $this->freePrepared( $prepared );
670 * For faking prepared SQL statements on DBs that don't support
672 * @param string $preparedSql - a 'preparable' SQL statement
673 * @param array $args - array of arguments to fill it with
674 * @return string executable SQL
676 function fillPrepared( $preparedQuery, $args ) {
678 $this->preparedArgs
=& $args;
679 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
680 array( &$this, 'fillPreparedArg' ), $preparedQuery );
684 * preg_callback func for fillPrepared()
685 * The arguments should be in $this->preparedArgs and must not be touched
686 * while we're doing this.
688 * @param array $matches
692 function fillPreparedArg( $matches ) {
693 switch( $matches[1] ) {
694 case '\\?': return '?';
695 case '\\!': return '!';
696 case '\\&': return '&';
698 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
699 switch( $matches[1] ) {
700 case '?': return $this->addQuotes( $arg );
701 case '!': return $arg;
703 # return $this->addQuotes( file_get_contents( $arg ) );
704 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
706 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
711 * @param mixed $res A SQL result
714 * Free a result object
716 function freeResult( $res ) {
717 if ( $res instanceof ResultWrapper
) {
720 if ( !@/**/mysql_free_result( $res ) ) {
721 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
726 * Fetch the next row from the given result object, in object form.
727 * Fields can be retrieved with $row->fieldname, with fields acting like
730 * @param $res SQL result object as returned from Database::query(), etc.
731 * @return MySQL row object
732 * @throws DBUnexpectedError Thrown if the database returns an error
734 function fetchObject( $res ) {
735 if ( $res instanceof ResultWrapper
) {
738 @/**/$row = mysql_fetch_object( $res );
739 if( $this->lastErrno() ) {
740 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
746 * Fetch the next row from the given result object, in associative array
747 * form. Fields are retrieved with $row['fieldname'].
749 * @param $res SQL result object as returned from Database::query(), etc.
750 * @return MySQL row object
751 * @throws DBUnexpectedError Thrown if the database returns an error
753 function fetchRow( $res ) {
754 if ( $res instanceof ResultWrapper
) {
757 @/**/$row = mysql_fetch_array( $res );
758 if ( $this->lastErrno() ) {
759 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
765 * Get the number of rows in a result object
767 function numRows( $res ) {
768 if ( $res instanceof ResultWrapper
) {
771 @/**/$n = mysql_num_rows( $res );
772 if( $this->lastErrno() ) {
773 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
779 * Get the number of fields in a result object
780 * See documentation for mysql_num_fields()
782 function numFields( $res ) {
783 if ( $res instanceof ResultWrapper
) {
786 return mysql_num_fields( $res );
790 * Get a field name in a result object
791 * See documentation for mysql_field_name():
792 * http://www.php.net/mysql_field_name
794 function fieldName( $res, $n ) {
795 if ( $res instanceof ResultWrapper
) {
798 return mysql_field_name( $res, $n );
802 * Get the inserted value of an auto-increment row
804 * The value inserted should be fetched from nextSequenceValue()
807 * $id = $dbw->nextSequenceValue('page_page_id_seq');
808 * $dbw->insert('page',array('page_id' => $id));
809 * $id = $dbw->insertId();
811 function insertId() { return mysql_insert_id( $this->mConn
); }
814 * Change the position of the cursor in a result object
815 * See mysql_data_seek()
817 function dataSeek( $res, $row ) {
818 if ( $res instanceof ResultWrapper
) {
821 return mysql_data_seek( $res, $row );
825 * Get the last error number
828 function lastErrno() {
829 if ( $this->mConn
) {
830 return mysql_errno( $this->mConn
);
832 return mysql_errno();
837 * Get a description of the last error
838 * See mysql_error() for more details
840 function lastError() {
841 if ( $this->mConn
) {
842 # Even if it's non-zero, it can still be invalid
843 wfSuppressWarnings();
844 $error = mysql_error( $this->mConn
);
846 $error = mysql_error();
850 $error = mysql_error();
853 $error .= ' (' . $this->mServer
. ')';
858 * Get the number of rows affected by the last write query
859 * See mysql_affected_rows() for more details
861 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
862 /**#@-*/ // end of template : @param $result
865 * Simple UPDATE wrapper
866 * Usually aborts on failure
867 * If errors are explicitly ignored, returns success
869 * This function exists for historical reasons, Database::update() has a more standard
870 * calling convention and feature set
872 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
874 $table = $this->tableName( $table );
875 $sql = "UPDATE $table SET $var = '" .
876 $this->strencode( $value ) . "' WHERE ($cond)";
877 return (bool)$this->query( $sql, $fname );
881 * Simple SELECT wrapper, returns a single field, input must be encoded
882 * Usually aborts on failure
883 * If errors are explicitly ignored, returns FALSE on failure
885 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
886 if ( !is_array( $options ) ) {
887 $options = array( $options );
889 $options['LIMIT'] = 1;
891 $res = $this->select( $table, $var, $cond, $fname, $options );
892 if ( $res === false ||
!$this->numRows( $res ) ) {
895 $row = $this->fetchRow( $res );
896 if ( $row !== false ) {
897 $this->freeResult( $res );
905 * Returns an optional USE INDEX clause to go after the table, and a
906 * string to go at the end of the query
910 * @param array $options an associative array of options to be turned into
911 * an SQL query, valid keys are listed in the function.
914 function makeSelectOptions( $options ) {
915 $preLimitTail = $postLimitTail = '';
918 $noKeyOptions = array();
919 foreach ( $options as $key => $option ) {
920 if ( is_numeric( $key ) ) {
921 $noKeyOptions[$option] = true;
925 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
926 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
927 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
929 //if (isset($options['LIMIT'])) {
930 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
931 // isset($options['OFFSET']) ? $options['OFFSET']
935 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
936 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
937 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
939 # Various MySQL extensions
940 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
941 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
942 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
943 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
944 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
945 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
946 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
947 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
949 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
950 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
955 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
961 * @param mixed $table Array or string, table name(s) (prefix auto-added)
962 * @param mixed $vars Array or string, field name(s) to be retrieved
963 * @param mixed $conds Array or string, condition(s) for WHERE
964 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
965 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
966 * see Database::makeSelectOptions code for list of supported stuff
967 * @param array $join_conds Associative array of table join conditions (optional)
968 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
969 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
971 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
973 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
974 return $this->query( $sql, $fname );
980 * @param mixed $table Array or string, table name(s) (prefix auto-added)
981 * @param mixed $vars Array or string, field name(s) to be retrieved
982 * @param mixed $conds Array or string, condition(s) for WHERE
983 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
984 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
985 * see Database::makeSelectOptions code for list of supported stuff
986 * @param array $join_conds Associative array of table join conditions (optional)
987 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
988 * @return string, the SQL text
990 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
991 if( is_array( $vars ) ) {
992 $vars = implode( ',', $vars );
994 if( !is_array( $options ) ) {
995 $options = array( $options );
997 if( is_array( $table ) ) {
998 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
999 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1001 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1002 } elseif ($table!='') {
1003 if ($table{0}==' ') {
1004 $from = ' FROM ' . $table;
1006 $from = ' FROM ' . $this->tableName( $table );
1012 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1014 if( !empty( $conds ) ) {
1015 if ( is_array( $conds ) ) {
1016 $conds = $this->makeList( $conds, LIST_AND
);
1018 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1020 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1023 if (isset($options['LIMIT']))
1024 $sql = $this->limitResult($sql, $options['LIMIT'],
1025 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1026 $sql = "$sql $postLimitTail";
1028 if (isset($options['EXPLAIN'])) {
1029 $sql = 'EXPLAIN ' . $sql;
1035 * Single row SELECT wrapper
1036 * Aborts or returns FALSE on error
1038 * $vars: the selected variables
1039 * $conds: a condition map, terms are ANDed together.
1040 * Items with numeric keys are taken to be literal conditions
1041 * Takes an array of selected variables, and a condition map, which is ANDed
1042 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1043 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1044 * $obj- >page_id is the ID of the Astronomy article
1046 * @todo migrate documentation to phpdocumentor format
1048 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1049 $options['LIMIT'] = 1;
1050 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1051 if ( $res === false )
1053 if ( !$this->numRows($res) ) {
1054 $this->freeResult($res);
1057 $obj = $this->fetchObject( $res );
1058 $this->freeResult( $res );
1064 * Estimate rows in dataset
1065 * Returns estimated count, based on EXPLAIN output
1066 * Takes same arguments as Database::select()
1069 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1070 $options['EXPLAIN']=true;
1071 $res = $this->select ($table, $vars, $conds, $fname, $options );
1072 if ( $res === false )
1074 if (!$this->numRows($res)) {
1075 $this->freeResult($res);
1081 while( $plan = $this->fetchObject( $res ) ) {
1082 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1085 $this->freeResult($res);
1091 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1092 * It's only slightly flawed. Don't use for anything important.
1094 * @param string $sql A SQL Query
1097 static function generalizeSQL( $sql ) {
1098 # This does the same as the regexp below would do, but in such a way
1099 # as to avoid crashing php on some large strings.
1100 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1102 $sql = str_replace ( "\\\\", '', $sql);
1103 $sql = str_replace ( "\\'", '', $sql);
1104 $sql = str_replace ( "\\\"", '', $sql);
1105 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1106 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1108 # All newlines, tabs, etc replaced by single space
1109 $sql = preg_replace ( '/\s+/', ' ', $sql);
1112 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1118 * Determines whether a field exists in a table
1119 * Usually aborts on failure
1120 * If errors are explicitly ignored, returns NULL on failure
1122 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1123 $table = $this->tableName( $table );
1124 $res = $this->query( 'DESCRIBE '.$table, $fname );
1131 while ( $row = $this->fetchObject( $res ) ) {
1132 if ( $row->Field
== $field ) {
1141 * Determines whether an index exists
1142 * Usually aborts on failure
1143 * If errors are explicitly ignored, returns NULL on failure
1145 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1146 $info = $this->indexInfo( $table, $index, $fname );
1147 if ( is_null( $info ) ) {
1150 return $info !== false;
1156 * Get information about an index into an object
1157 * Returns false if the index does not exist
1159 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1160 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1161 # SHOW INDEX should work for 3.x and up:
1162 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1163 $table = $this->tableName( $table );
1164 $sql = 'SHOW INDEX FROM '.$table;
1165 $res = $this->query( $sql, $fname );
1171 while ( $row = $this->fetchObject( $res ) ) {
1172 if ( $row->Key_name
== $index ) {
1176 $this->freeResult($res);
1178 return empty($result) ?
false : $result;
1182 * Query whether a given table exists
1184 function tableExists( $table ) {
1185 $table = $this->tableName( $table );
1186 $old = $this->ignoreErrors( true );
1187 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1188 $this->ignoreErrors( $old );
1190 $this->freeResult( $res );
1198 * mysql_fetch_field() wrapper
1199 * Returns false if the field doesn't exist
1204 function fieldInfo( $table, $field ) {
1205 $table = $this->tableName( $table );
1206 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1207 $n = mysql_num_fields( $res->result
);
1208 for( $i = 0; $i < $n; $i++
) {
1209 $meta = mysql_fetch_field( $res->result
, $i );
1210 if( $field == $meta->name
) {
1211 return new MySQLField($meta);
1218 * mysql_field_type() wrapper
1220 function fieldType( $res, $index ) {
1221 if ( $res instanceof ResultWrapper
) {
1222 $res = $res->result
;
1224 return mysql_field_type( $res, $index );
1228 * Determines if a given index is unique
1230 function indexUnique( $table, $index ) {
1231 $indexInfo = $this->indexInfo( $table, $index );
1232 if ( !$indexInfo ) {
1235 return !$indexInfo[0]->Non_unique
;
1239 * INSERT wrapper, inserts an array into a table
1241 * $a may be a single associative array, or an array of these with numeric keys, for
1244 * Usually aborts on failure
1245 * If errors are explicitly ignored, returns success
1247 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1248 # No rows to insert, easy just return now
1249 if ( !count( $a ) ) {
1253 $table = $this->tableName( $table );
1254 if ( !is_array( $options ) ) {
1255 $options = array( $options );
1257 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1259 $keys = array_keys( $a[0] );
1262 $keys = array_keys( $a );
1265 $sql = 'INSERT ' . implode( ' ', $options ) .
1266 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1270 foreach ( $a as $row ) {
1276 $sql .= '(' . $this->makeList( $row ) . ')';
1279 $sql .= '(' . $this->makeList( $a ) . ')';
1281 return (bool)$this->query( $sql, $fname );
1285 * Make UPDATE options for the Database::update function
1288 * @param array $options The options passed to Database::update
1291 function makeUpdateOptions( $options ) {
1292 if( !is_array( $options ) ) {
1293 $options = array( $options );
1296 if ( in_array( 'LOW_PRIORITY', $options ) )
1297 $opts[] = $this->lowPriorityOption();
1298 if ( in_array( 'IGNORE', $options ) )
1300 return implode(' ', $opts);
1304 * UPDATE wrapper, takes a condition array and a SET array
1306 * @param string $table The table to UPDATE
1307 * @param array $values An array of values to SET
1308 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1309 * @param string $fname The Class::Function calling this function
1311 * @param array $options An array of UPDATE options, can be one or
1312 * more of IGNORE, LOW_PRIORITY
1315 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1316 $table = $this->tableName( $table );
1317 $opts = $this->makeUpdateOptions( $options );
1318 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1319 if ( $conds != '*' ) {
1320 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1322 return $this->query( $sql, $fname );
1326 * Makes an encoded list of strings from an array
1328 * LIST_COMMA - comma separated, no field names
1329 * LIST_AND - ANDed WHERE clause (without the WHERE)
1330 * LIST_OR - ORed WHERE clause (without the WHERE)
1331 * LIST_SET - comma separated with field names, like a SET clause
1332 * LIST_NAMES - comma separated field names
1334 function makeList( $a, $mode = LIST_COMMA
) {
1335 if ( !is_array( $a ) ) {
1336 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1341 foreach ( $a as $field => $value ) {
1343 if ( $mode == LIST_AND
) {
1345 } elseif($mode == LIST_OR
) {
1353 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1354 $list .= "($value)";
1355 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1357 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1358 if( count( $value ) == 0 ) {
1359 throw new MWException( __METHOD__
.': empty input' );
1360 } elseif( count( $value ) == 1 ) {
1361 // Special-case single values, as IN isn't terribly efficient
1362 // Don't necessarily assume the single key is 0; we don't
1363 // enforce linear numeric ordering on other arrays here.
1364 $value = array_values( $value );
1365 $list .= $field." = ".$this->addQuotes( $value[0] );
1367 $list .= $field." IN (".$this->makeList($value).") ";
1369 } elseif( is_null($value) ) {
1370 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1371 $list .= "$field IS ";
1372 } elseif ( $mode == LIST_SET
) {
1373 $list .= "$field = ";
1377 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1378 $list .= "$field = ";
1380 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1387 * Change the current database
1389 function selectDB( $db ) {
1390 $this->mDBname
= $db;
1391 return mysql_select_db( $db, $this->mConn
);
1395 * Get the current DB name
1397 function getDBname() {
1398 return $this->mDBname
;
1402 * Get the server hostname or IP address
1404 function getServer() {
1405 return $this->mServer
;
1409 * Format a table name ready for use in constructing an SQL query
1411 * This does two important things: it quotes the table names to clean them up,
1412 * and it adds a table prefix if only given a table name with no quotes.
1414 * All functions of this object which require a table name call this function
1415 * themselves. Pass the canonical name to such functions. This is only needed
1416 * when calling query() directly.
1418 * @param string $name database table name
1419 * @return string full database name
1421 function tableName( $name ) {
1422 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1423 # Skip the entire process when we have a string quoted on both ends.
1424 # Note that we check the end so that we will still quote any use of
1425 # use of `database`.table. But won't break things if someone wants
1426 # to query a database table with a dot in the name.
1427 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1429 # Lets test for any bits of text that should never show up in a table
1430 # name. Basically anything like JOIN or ON which are actually part of
1431 # SQL queries, but may end up inside of the table value to combine
1432 # sql. Such as how the API is doing.
1433 # Note that we use a whitespace test rather than a \b test to avoid
1434 # any remote case where a word like on may be inside of a table name
1435 # surrounded by symbols which may be considered word breaks.
1436 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1438 # Split database and table into proper variables.
1439 # We reverse the explode so that database.table and table both output
1440 # the correct table.
1441 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1442 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1443 else @list
( $table ) = $dbDetails;
1444 $prefix = $this->mTablePrefix
; # Default prefix
1446 # A database name has been specified in input. Quote the table name
1447 # because we don't want any prefixes added.
1448 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1450 # Note that we use the long format because php will complain in in_array if
1451 # the input is not an array, and will complain in is_array if it is not set.
1452 if( !isset( $database ) # Don't use shared database if pre selected.
1453 && isset( $wgSharedDB ) # We have a shared database
1454 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1455 && isset( $wgSharedTables )
1456 && is_array( $wgSharedTables )
1457 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1458 $database = $wgSharedDB;
1459 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1462 # Quote the $database and $table and apply the prefix if not quoted.
1463 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1464 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1466 # Merge our database and table into our final table name.
1467 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1469 # We're finished, return.
1474 * Fetch a number of table names into an array
1475 * This is handy when you need to construct SQL for joins
1478 * extract($dbr->tableNames('user','watchlist'));
1479 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1480 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1482 public function tableNames() {
1483 $inArray = func_get_args();
1485 foreach ( $inArray as $name ) {
1486 $retVal[$name] = $this->tableName( $name );
1492 * Fetch a number of table names into an zero-indexed numerical array
1493 * This is handy when you need to construct SQL for joins
1496 * list( $user, $watchlist ) = $dbr->tableNamesN('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 tableNamesN() {
1501 $inArray = func_get_args();
1503 foreach ( $inArray as $name ) {
1504 $retVal[] = $this->tableName( $name );
1512 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1515 $use_index_safe = is_array($use_index) ?
$use_index : array();
1516 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1517 foreach ( $tables as $table ) {
1518 // Is there a JOIN and INDEX clause for this table?
1519 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1520 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1521 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1522 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1523 $retJOIN[] = $tableClause;
1524 // Is there an INDEX clause?
1525 } else if ( isset($use_index_safe[$table]) ) {
1526 $tableClause = $this->tableName( $table );
1527 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1528 $ret[] = $tableClause;
1529 // Is there a JOIN clause?
1530 } else if ( isset($join_conds_safe[$table]) ) {
1531 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1532 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1533 $retJOIN[] = $tableClause;
1535 $tableClause = $this->tableName( $table );
1536 $ret[] = $tableClause;
1539 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1540 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1541 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1542 // Compile our final table clause
1543 return implode(' ',array($straightJoins,$otherJoins) );
1547 * Wrapper for addslashes()
1548 * @param string $s String to be slashed.
1549 * @return string slashed string.
1551 function strencode( $s ) {
1552 return mysql_real_escape_string( $s, $this->mConn
);
1556 * If it's a string, adds quotes and backslashes
1557 * Otherwise returns as-is
1559 function addQuotes( $s ) {
1560 if ( is_null( $s ) ) {
1563 # This will also quote numeric values. This should be harmless,
1564 # and protects against weird problems that occur when they really
1565 # _are_ strings such as article titles and string->number->string
1566 # conversion is not 1:1.
1567 return "'" . $this->strencode( $s ) . "'";
1572 * Escape string for safe LIKE usage
1574 function escapeLike( $s ) {
1575 $s=$this->strencode( $s );
1576 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1581 * Returns an appropriately quoted sequence value for inserting a new row.
1582 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1583 * subclass will return an integer, and save the value for insertId()
1585 function nextSequenceValue( $seqName ) {
1591 * PostgreSQL doesn't have them and returns ""
1593 function useIndexClause( $index ) {
1594 return "FORCE INDEX ($index)";
1598 * REPLACE query wrapper
1599 * PostgreSQL simulates this with a DELETE followed by INSERT
1600 * $row is the row to insert, an associative array
1601 * $uniqueIndexes is an array of indexes. Each element may be either a
1602 * field name or an array of field names
1604 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1605 * However if you do this, you run the risk of encountering errors which wouldn't have
1608 * @todo migrate comment to phodocumentor format
1610 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1611 $table = $this->tableName( $table );
1614 if ( !is_array( reset( $rows ) ) ) {
1615 $rows = array( $rows );
1618 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1620 foreach ( $rows as $row ) {
1626 $sql .= '(' . $this->makeList( $row ) . ')';
1628 return $this->query( $sql, $fname );
1632 * DELETE where the condition is a join
1633 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1635 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1636 * join condition matches, set $conds='*'
1638 * DO NOT put the join condition in $conds
1640 * @param string $delTable The table to delete from.
1641 * @param string $joinTable The other table.
1642 * @param string $delVar The variable to join on, in the first table.
1643 * @param string $joinVar The variable to join on, in the second table.
1644 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1646 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1648 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1651 $delTable = $this->tableName( $delTable );
1652 $joinTable = $this->tableName( $joinTable );
1653 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1654 if ( $conds != '*' ) {
1655 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1658 return $this->query( $sql, $fname );
1662 * Returns the size of a text field, or -1 for "unlimited"
1664 function textFieldSize( $table, $field ) {
1665 $table = $this->tableName( $table );
1666 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1667 $res = $this->query( $sql, 'Database::textFieldSize' );
1668 $row = $this->fetchObject( $res );
1669 $this->freeResult( $res );
1672 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1681 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1683 function lowPriorityOption() {
1684 return 'LOW_PRIORITY';
1688 * DELETE query wrapper
1690 * Use $conds == "*" to delete all rows
1692 function delete( $table, $conds, $fname = 'Database::delete' ) {
1694 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1696 $table = $this->tableName( $table );
1697 $sql = "DELETE FROM $table";
1698 if ( $conds != '*' ) {
1699 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1701 return $this->query( $sql, $fname );
1705 * INSERT SELECT wrapper
1706 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1707 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1708 * $conds may be "*" to copy the whole table
1709 * srcTable may be an array of tables.
1711 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1712 $insertOptions = array(), $selectOptions = array() )
1714 $destTable = $this->tableName( $destTable );
1715 if ( is_array( $insertOptions ) ) {
1716 $insertOptions = implode( ' ', $insertOptions );
1718 if( !is_array( $selectOptions ) ) {
1719 $selectOptions = array( $selectOptions );
1721 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1722 if( is_array( $srcTable ) ) {
1723 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1725 $srcTable = $this->tableName( $srcTable );
1727 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1728 " SELECT $startOpts " . implode( ',', $varMap ) .
1729 " FROM $srcTable $useIndex ";
1730 if ( $conds != '*' ) {
1731 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1733 $sql .= " $tailOpts";
1734 return $this->query( $sql, $fname );
1738 * Construct a LIMIT query with optional offset
1739 * This is used for query pages
1740 * $sql string SQL query we will append the limit too
1741 * $limit integer the SQL limit
1742 * $offset integer the SQL offset (default false)
1744 function limitResult($sql, $limit, $offset=false) {
1745 if( !is_numeric($limit) ) {
1746 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1748 return "$sql LIMIT "
1749 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1752 function limitResultForUpdate($sql, $num) {
1753 return $this->limitResult($sql, $num, 0);
1757 * Returns an SQL expression for a simple conditional.
1760 * @param string $cond SQL expression which will result in a boolean value
1761 * @param string $trueVal SQL expression to return if true
1762 * @param string $falseVal SQL expression to return if false
1763 * @return string SQL fragment
1765 function conditional( $cond, $trueVal, $falseVal ) {
1766 return " IF($cond, $trueVal, $falseVal) ";
1770 * Returns a comand for str_replace function in SQL query.
1771 * Uses REPLACE() in MySQL
1773 * @param string $orig String or column to modify
1774 * @param string $old String or column to seek
1775 * @param string $new String or column to replace with
1777 function strreplace( $orig, $old, $new ) {
1778 return "REPLACE({$orig}, {$old}, {$new})";
1782 * Determines if the last failure was due to a deadlock
1784 function wasDeadlock() {
1785 return $this->lastErrno() == 1213;
1789 * Perform a deadlock-prone transaction.
1791 * This function invokes a callback function to perform a set of write
1792 * queries. If a deadlock occurs during the processing, the transaction
1793 * will be rolled back and the callback function will be called again.
1796 * $dbw->deadlockLoop( callback, ... );
1798 * Extra arguments are passed through to the specified callback function.
1800 * Returns whatever the callback function returned on its successful,
1801 * iteration, or false on error, for example if the retry limit was
1804 function deadlockLoop() {
1805 $myFname = 'Database::deadlockLoop';
1808 $args = func_get_args();
1809 $function = array_shift( $args );
1810 $oldIgnore = $this->ignoreErrors( true );
1811 $tries = DEADLOCK_TRIES
;
1812 if ( is_array( $function ) ) {
1813 $fname = $function[0];
1818 $retVal = call_user_func_array( $function, $args );
1819 $error = $this->lastError();
1820 $errno = $this->lastErrno();
1821 $sql = $this->lastQuery();
1824 if ( $this->wasDeadlock() ) {
1826 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1828 $this->reportQueryError( $error, $errno, $sql, $fname );
1831 } while( $this->wasDeadlock() && --$tries > 0 );
1832 $this->ignoreErrors( $oldIgnore );
1833 if ( $tries <= 0 ) {
1834 $this->query( 'ROLLBACK', $myFname );
1835 $this->reportQueryError( $error, $errno, $sql, $fname );
1838 $this->query( 'COMMIT', $myFname );
1844 * Do a SELECT MASTER_POS_WAIT()
1846 * @param string $file the binlog file
1847 * @param string $pos the binlog position
1848 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1850 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1851 $fname = 'Database::masterPosWait';
1852 wfProfileIn( $fname );
1854 # Commit any open transactions
1855 if ( $this->mTrxLevel
) {
1856 $this->immediateCommit();
1859 if ( !is_null( $this->mFakeSlaveLag
) ) {
1860 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1861 if ( $wait > $timeout * 1e6
) {
1862 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1863 wfProfileOut( $fname );
1865 } elseif ( $wait > 0 ) {
1866 wfDebug( "Fake slave waiting $wait us\n" );
1868 wfProfileOut( $fname );
1871 wfDebug( "Fake slave up to date ($wait us)\n" );
1872 wfProfileOut( $fname );
1877 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1878 $encFile = $this->addQuotes( $pos->file
);
1879 $encPos = intval( $pos->pos
);
1880 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1881 $res = $this->doQuery( $sql );
1882 if ( $res && $row = $this->fetchRow( $res ) ) {
1883 $this->freeResult( $res );
1884 wfProfileOut( $fname );
1887 wfProfileOut( $fname );
1893 * Get the position of the master from SHOW SLAVE STATUS
1895 function getSlavePos() {
1896 if ( !is_null( $this->mFakeSlaveLag
) ) {
1897 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1898 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1901 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1902 $row = $this->fetchObject( $res );
1904 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1911 * Get the position of the master from SHOW MASTER STATUS
1913 function getMasterPos() {
1914 if ( $this->mFakeMaster
) {
1915 return new MySQLMasterPos( 'fake', microtime( true ) );
1917 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1918 $row = $this->fetchObject( $res );
1920 return new MySQLMasterPos( $row->File
, $row->Position
);
1927 * Begin a transaction, committing any previously open transaction
1929 function begin( $fname = 'Database::begin' ) {
1930 $this->query( 'BEGIN', $fname );
1931 $this->mTrxLevel
= 1;
1937 function commit( $fname = 'Database::commit' ) {
1938 $this->query( 'COMMIT', $fname );
1939 $this->mTrxLevel
= 0;
1943 * Rollback a transaction.
1944 * No-op on non-transactional databases.
1946 function rollback( $fname = 'Database::rollback' ) {
1947 $this->query( 'ROLLBACK', $fname, true );
1948 $this->mTrxLevel
= 0;
1952 * Begin a transaction, committing any previously open transaction
1953 * @deprecated use begin()
1955 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1960 * Commit transaction, if one is open
1961 * @deprecated use commit()
1963 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1968 * Return MW-style timestamp used for MySQL schema
1970 function timestamp( $ts=0 ) {
1971 return wfTimestamp(TS_MW
,$ts);
1975 * Local database timestamp format or null
1977 function timestampOrNull( $ts = null ) {
1978 if( is_null( $ts ) ) {
1981 return $this->timestamp( $ts );
1988 function resultObject( $result ) {
1989 if( empty( $result ) ) {
1991 } elseif ( $result instanceof ResultWrapper
) {
1993 } elseif ( $result === true ) {
1994 // Successful write query
1997 return new ResultWrapper( $this, $result );
2002 * Return aggregated value alias
2004 function aggregateValue ($valuedata,$valuename='value') {
2009 * @return string wikitext of a link to the server software's web site
2011 function getSoftwareLink() {
2012 return "[http://www.mysql.com/ MySQL]";
2016 * @return string Version information from the database
2018 function getServerVersion() {
2019 return mysql_get_server_info( $this->mConn
);
2023 * Ping the server and try to reconnect if it there is no connection
2026 if( !function_exists( 'mysql_ping' ) ) {
2027 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2030 $ping = mysql_ping( $this->mConn
);
2035 // Need to reconnect manually in MySQL client 5.0.13+
2036 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2037 mysql_close( $this->mConn
);
2038 $this->mOpened
= false;
2039 $this->mConn
= false;
2040 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2048 * At the moment, this will only work if the DB user has the PROCESS privilege
2051 if ( !is_null( $this->mFakeSlaveLag
) ) {
2052 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2053 return $this->mFakeSlaveLag
;
2055 $res = $this->query( 'SHOW PROCESSLIST' );
2056 # Find slave SQL thread
2057 while ( $row = $this->fetchObject( $res ) ) {
2058 /* This should work for most situations - when default db
2059 * for thread is not specified, it had no events executed,
2060 * and therefore it doesn't know yet how lagged it is.
2062 * Relay log I/O thread does not select databases.
2064 if ( $row->User
== 'system user' &&
2065 $row->State
!= 'Waiting for master to send event' &&
2066 $row->State
!= 'Connecting to master' &&
2067 $row->State
!= 'Queueing master event to the relay log' &&
2068 $row->State
!= 'Waiting for master update' &&
2069 $row->State
!= 'Requesting binlog dump'
2071 # This is it, return the time (except -ve)
2072 if ( $row->Time
> 0x7fffffff ) {
2083 * Get status information from SHOW STATUS in an associative array
2085 function getStatus($which="%") {
2086 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2088 while ( $row = $this->fetchObject( $res ) ) {
2089 $status[$row->Variable_name
] = $row->Value
;
2095 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2097 function maxListLen() {
2101 function encodeBlob($b) {
2105 function decodeBlob($b) {
2110 * Override database's default connection timeout.
2111 * May be useful for very long batch queries such as
2112 * full-wiki dumps, where a single query reads out
2113 * over hours or days.
2114 * @param int $timeout in seconds
2116 public function setTimeout( $timeout ) {
2117 $this->query( "SET net_read_timeout=$timeout" );
2118 $this->query( "SET net_write_timeout=$timeout" );
2122 * Read and execute SQL commands from a file.
2123 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2124 * @param string $filename File name to open
2125 * @param callback $lineCallback Optional function called before reading each line
2126 * @param callback $resultCallback Optional function called for each MySQL result
2128 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2129 $fp = fopen( $filename, 'r' );
2130 if ( false === $fp ) {
2131 throw new MWException( "Could not open \"{$filename}\".\n" );
2133 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2139 * Read and execute commands from an open file handle
2140 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2141 * @param string $fp File handle
2142 * @param callback $lineCallback Optional function called before reading each line
2143 * @param callback $resultCallback Optional function called for each MySQL result
2145 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2148 $dollarquote = false;
2150 while ( ! feof( $fp ) ) {
2151 if ( $lineCallback ) {
2152 call_user_func( $lineCallback );
2154 $line = trim( fgets( $fp, 1024 ) );
2155 $sl = strlen( $line ) - 1;
2157 if ( $sl < 0 ) { continue; }
2158 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2160 ## Allow dollar quoting for function declarations
2161 if (substr($line,0,4) == '$mw$') {
2163 $dollarquote = false;
2167 $dollarquote = true;
2170 else if (!$dollarquote) {
2171 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2173 $line = substr( $line, 0, $sl );
2177 if ( '' != $cmd ) { $cmd .= ' '; }
2181 $cmd = str_replace(';;', ";", $cmd);
2182 $cmd = $this->replaceVars( $cmd );
2183 $res = $this->query( $cmd, __METHOD__
);
2184 if ( $resultCallback ) {
2185 call_user_func( $resultCallback, $res, $this );
2188 if ( false === $res ) {
2189 $err = $this->lastError();
2190 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2202 * Replace variables in sourced SQL
2204 protected function replaceVars( $ins ) {
2206 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2207 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2208 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2211 // Ordinary variables
2212 foreach ( $varnames as $var ) {
2213 if( isset( $GLOBALS[$var] ) ) {
2214 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2215 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2216 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2217 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2222 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2223 array( &$this, 'tableNameCallback' ), $ins );
2228 * Table name callback
2231 protected function tableNameCallback( $matches ) {
2232 return $this->tableName( $matches[1] );
2236 * Build a concatenation list to feed into a SQL query
2238 function buildConcat( $stringList ) {
2239 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2245 * Abstracted from Filestore::lock() so child classes can implement for
2248 * @param string $lockName Name of lock to aquire
2249 * @param string $method Name of method calling us
2252 public function lock( $lockName, $method ) {
2253 $lockName = $this->addQuotes( $lockName );
2254 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2255 $row = $this->fetchObject( $result );
2256 $this->freeResult( $result );
2258 if( $row->lockstatus
== 1 ) {
2261 wfDebug( __METHOD__
." failed to acquire lock\n" );
2268 * @todo fixme - Figure out a way to return a bool
2269 * based on successful lock release.
2271 * @param string $lockName Name of lock to release
2272 * @param string $method Name of method calling us
2274 public function unlock( $lockName, $method ) {
2275 $lockName = $this->addQuotes( $lockName );
2276 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2277 $this->freeResult( $result );
2281 * Get search engine class. All subclasses of this
2282 * need to implement this if they wish to use searching.
2286 public function getSearchEngine() {
2287 return "SearchMySQL";
2292 * Database abstraction object for mySQL
2293 * Inherit all methods and properties of Database::Database()
2298 class DatabaseMysql
extends Database
{
2302 /******************************************************************************
2304 *****************************************************************************/
2313 function DBObject($data) {
2314 $this->mData
= $data;
2322 return $this->mData
;
2330 * This allows us to distinguish a blob from a normal string and an array of strings
2334 function __construct($data) {
2335 $this->mData
= $data;
2338 return $this->mData
;
2347 private $name, $tablename, $default, $max_length, $nullable,
2348 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2349 function __construct ($info) {
2350 $this->name
= $info->name
;
2351 $this->tablename
= $info->table
;
2352 $this->default = $info->def
;
2353 $this->max_length
= $info->max_length
;
2354 $this->nullable
= !$info->not_null
;
2355 $this->is_pk
= $info->primary_key
;
2356 $this->is_unique
= $info->unique_key
;
2357 $this->is_multiple
= $info->multiple_key
;
2358 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2359 $this->type
= $info->type
;
2366 function tableName() {
2367 return $this->tableName
;
2370 function defaultValue() {
2371 return $this->default;
2374 function maxLength() {
2375 return $this->max_length
;
2378 function nullable() {
2379 return $this->nullable
;
2383 return $this->is_key
;
2386 function isMultipleKey() {
2387 return $this->is_multiple
;
2395 /******************************************************************************
2397 *****************************************************************************/
2400 * Database error base class
2403 class DBError
extends MWException
{
2407 * Construct a database error
2408 * @param Database $db The database object which threw the error
2409 * @param string $error A simple error message to be used for debugging
2411 function __construct( Database
&$db, $error ) {
2413 parent
::__construct( $error );
2420 class DBConnectionError
extends DBError
{
2423 function __construct( Database
&$db, $error = 'unknown error' ) {
2424 $msg = 'DB connection error';
2425 if ( trim( $error ) != '' ) {
2428 $this->error
= $error;
2429 parent
::__construct( $db, $msg );
2432 function useOutputPage() {
2433 // Not likely to work
2437 function useMessageCache() {
2438 // Not likely to work
2442 function getText() {
2443 return $this->getMessage() . "\n";
2446 function getLogMessage() {
2447 # Don't send to the exception log
2451 function getPageTitle() {
2453 return "$wgSitename has a problem";
2456 function getHTML() {
2457 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2458 global $wgSitename, $wgServer, $wgMessageCache;
2460 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2461 # Hard coding strings instead.
2463 $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>";
2464 $mainpage = 'Main Page';
2465 $searchdisabled = <<<EOT
2466 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2467 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2471 <!-- SiteSearch Google -->
2472 <FORM method=GET action=\"http://www.google.com/search\">
2473 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2474 <A HREF=\"http://www.google.com/\">
2475 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2476 border=\"0\" ALT=\"Google\"></A>
2479 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2480 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2482 <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 />
2483 <input type='hidden' name='ie' value='$2'>
2484 <input type='hidden' name='oe' value='$2'>
2488 <!-- SiteSearch Google -->";
2489 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2491 # No database access
2492 if ( is_object( $wgMessageCache ) ) {
2493 $wgMessageCache->disable();
2496 if ( trim( $this->error
) == '' ) {
2497 $this->error
= $this->db
->getProperty('mServer');
2500 $text = str_replace( '$1', $this->error
, $noconnect );
2501 $text .= wfGetSiteNotice();
2503 if($wgUseFileCache) {
2508 $t = Title
::newFromURL( $title );
2509 } elseif (@/**/$_REQUEST['search']) {
2510 $search = $_REQUEST['search'];
2511 return $searchdisabled .
2512 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2513 $wgInputEncoding ), $googlesearch );
2515 $t = Title
::newFromText( $mainpage );
2519 $cache = new HTMLFileCache( $t );
2520 if( $cache->isFileCached() ) {
2521 // @todo, FIXME: $msg is not defined on the next line.
2522 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2523 $cachederror . "</b></p>\n";
2525 $tag = '<div id="article">';
2526 $text = str_replace(
2529 $cache->fetchPageText() );
2540 class DBQueryError
extends DBError
{
2541 public $error, $errno, $sql, $fname;
2543 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2544 $message = "A database error has occurred\n" .
2546 "Function: $fname\n" .
2547 "Error: $errno $error\n";
2549 parent
::__construct( $db, $message );
2550 $this->error
= $error;
2551 $this->errno
= $errno;
2553 $this->fname
= $fname;
2556 function getText() {
2557 if ( $this->useMessageCache() ) {
2558 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2559 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2561 return $this->getMessage();
2566 global $wgShowSQLErrors;
2567 if( !$wgShowSQLErrors ) {
2568 return $this->msg( 'sqlhidden', 'SQL hidden' );
2574 function getLogMessage() {
2575 # Don't send to the exception log
2579 function getPageTitle() {
2580 return $this->msg( 'databaseerror', 'Database error' );
2583 function getHTML() {
2584 if ( $this->useMessageCache() ) {
2585 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2586 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2588 return nl2br( htmlspecialchars( $this->getMessage() ) );
2596 class DBUnexpectedError
extends DBError
{}
2600 * Result wrapper for grabbing data queried by someone else
2603 class ResultWrapper
implements Iterator
{
2604 var $db, $result, $pos = 0, $currentRow = null;
2607 * Create a new result object from a result resource and a Database object
2609 function ResultWrapper( $database, $result ) {
2610 $this->db
= $database;
2611 if ( $result instanceof ResultWrapper
) {
2612 $this->result
= $result->result
;
2614 $this->result
= $result;
2619 * Get the number of rows in a result object
2621 function numRows() {
2622 return $this->db
->numRows( $this->result
);
2626 * Fetch the next row from the given result object, in object form.
2627 * Fields can be retrieved with $row->fieldname, with fields acting like
2630 * @param $res SQL result object as returned from Database::query(), etc.
2631 * @return MySQL row object
2632 * @throws DBUnexpectedError Thrown if the database returns an error
2634 function fetchObject() {
2635 return $this->db
->fetchObject( $this->result
);
2639 * Fetch the next row from the given result object, in associative array
2640 * form. Fields are retrieved with $row['fieldname'].
2642 * @param $res SQL result object as returned from Database::query(), etc.
2643 * @return MySQL row object
2644 * @throws DBUnexpectedError Thrown if the database returns an error
2646 function fetchRow() {
2647 return $this->db
->fetchRow( $this->result
);
2651 * Free a result object
2654 $this->db
->freeResult( $this->result
);
2655 unset( $this->result
);
2660 * Change the position of the cursor in a result object
2661 * See mysql_data_seek()
2663 function seek( $row ) {
2664 $this->db
->dataSeek( $this->result
, $row );
2667 /*********************
2668 * Iterator functions
2669 * Note that using these in combination with the non-iterator functions
2670 * above may cause rows to be skipped or repeated.
2674 if ($this->numRows()) {
2675 $this->db
->dataSeek($this->result
, 0);
2678 $this->currentRow
= null;
2681 function current() {
2682 if ( is_null( $this->currentRow
) ) {
2685 return $this->currentRow
;
2694 $this->currentRow
= $this->fetchObject();
2695 return $this->currentRow
;
2699 return $this->current() !== false;
2703 class MySQLMasterPos
{
2706 function __construct( $file, $pos ) {
2707 $this->file
= $file;
2711 function __toString() {
2712 return "{$this->file}/{$this->pos}";