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 # The kernel's default SYN retransmission period is far too slow for us,
347 # so we use a short timeout plus a manual retry. Retrying means that a small
348 # but finite rate of SYN packet loss won't cause user-visible errors.
349 $this->mConn
= false;
350 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
355 $this->installErrorHandler();
356 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
360 if ( $this->mFlags
& DBO_PERSISTENT
) {
361 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
363 # Create a new connection...
364 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
366 if ($this->mConn
=== false) {
368 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
371 $phpError = $this->restoreErrorHandler();
372 # Always log connection errors
373 if ( !$this->mConn
) {
374 $error = $this->lastError();
378 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
381 wfProfileOut("dbconnect-$server");
383 if ( $dbName != '' ) {
384 if ( $this->mConn
!== false ) {
385 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
387 $error = "Error selecting database $dbName on server {$this->mServer} " .
388 "from client host {$wguname['nodename']}\n";
389 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
393 wfDebug( "DB connection error\n" );
394 wfDebug( "Server: $server, User: $user, Password: " .
395 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
400 $success = (bool)$this->mConn
;
404 $version = $this->getServerVersion();
405 if ( version_compare( $version, '4.1' ) >= 0 ) {
406 // Tell the server we're communicating with it in UTF-8.
407 // This may engage various charset conversions.
410 $this->query( 'SET NAMES utf8', __METHOD__
);
412 // Turn off strict mode
413 $this->query( "SET sql_mode = ''", __METHOD__
);
416 // Turn off strict mode if it is on
418 $this->reportConnectionError( $phpError );
421 $this->mOpened
= $success;
422 wfProfileOut( __METHOD__
);
427 protected function installErrorHandler() {
428 $this->mPHPError
= false;
429 set_error_handler( array( $this, 'connectionErrorHandler' ) );
432 protected function restoreErrorHandler() {
433 restore_error_handler();
434 return $this->mPHPError
;
437 protected function connectionErrorHandler( $errno, $errstr ) {
438 $this->mPHPError
= $errstr;
442 * Closes a database connection.
443 * if it is open : commits any open transactions
445 * @return bool operation success. true if already closed.
449 $this->mOpened
= false;
450 if ( $this->mConn
) {
451 if ( $this->trxLevel() ) {
452 $this->immediateCommit();
454 return mysql_close( $this->mConn
);
461 * @param string $error fallback error message, used if none is given by MySQL
463 function reportConnectionError( $error = 'Unknown error' ) {
464 $myError = $this->lastError();
469 if ( $this->mFailFunction
) {
470 # Legacy error handling method
471 if ( !is_int( $this->mFailFunction
) ) {
472 $ff = $this->mFailFunction
;
473 $ff( $this, $error );
477 throw new DBConnectionError( $this, $error );
482 * Usually aborts on failure. If errors are explicitly ignored, returns success.
484 * @param $sql String: SQL query
485 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
486 * comment (you can use __METHOD__ or add some extra info)
487 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
488 * maybe best to catch the exception instead?
489 * @return true for a successful write query, ResultWrapper object for a successful read query,
490 * or false on failure if $tempIgnore set
491 * @throws DBQueryError Thrown when the database returns an error of any kind
493 public function query( $sql, $fname = '', $tempIgnore = false ) {
496 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
497 if ( isset( $wgProfiler ) ) {
498 # generalizeSQL will probably cut down the query to reasonable
499 # logging size most of the time. The substr is really just a sanity check.
501 # Who's been wasting my precious column space? -- TS
502 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
505 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
506 $totalProf = 'Database::query-master';
508 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
509 $totalProf = 'Database::query';
511 wfProfileIn( $totalProf );
512 wfProfileIn( $queryProf );
515 $this->mLastQuery
= $sql;
517 # Add a comment for easy SHOW PROCESSLIST interpretation
520 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
521 $userName = $wgUser->getName();
522 if ( mb_strlen( $userName ) > 15 ) {
523 $userName = mb_substr( $userName, 0, 15 ) . '...';
525 $userName = str_replace( '/', '', $userName );
529 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
531 # $commentedSql = $sql;
534 # If DBO_TRX is set, start a transaction
535 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
536 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
537 // avoid establishing transactions for SHOW and SET statements too -
538 // that would delay transaction initializations to once connection
539 // is really used by application
540 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
541 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
545 if ( $this->debug() ) {
546 $sqlx = substr( $commentedSql, 0, 500 );
547 $sqlx = strtr( $sqlx, "\t\n", ' ' );
549 wfDebug( "SQL-master: $sqlx\n" );
551 wfDebug( "SQL: $sqlx\n" );
555 # Do the query and handle errors
556 $ret = $this->doQuery( $commentedSql );
558 # Try reconnecting if the connection was lost
559 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
560 # Transaction is gone, like it or not
561 $this->mTrxLevel
= 0;
562 wfDebug( "Connection lost, reconnecting...\n" );
563 if ( $this->ping() ) {
564 wfDebug( "Reconnected\n" );
565 $sqlx = substr( $commentedSql, 0, 500 );
566 $sqlx = strtr( $sqlx, "\t\n", ' ' );
567 global $wgRequestTime;
568 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
569 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
570 $ret = $this->doQuery( $commentedSql );
572 wfDebug( "Failed\n" );
576 if ( false === $ret ) {
577 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
580 if ( isset( $wgProfiler ) ) {
581 wfProfileOut( $queryProf );
582 wfProfileOut( $totalProf );
584 return $this->resultObject( $ret );
588 * The DBMS-dependent part of query()
589 * @param $sql String: SQL query.
590 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
593 /*private*/ function doQuery( $sql ) {
594 if( $this->bufferResults() ) {
595 $ret = mysql_query( $sql, $this->mConn
);
597 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
606 * @param string $fname
607 * @param bool $tempIgnore
609 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
610 global $wgCommandLineMode;
611 # Ignore errors during error handling to avoid infinite recursion
612 $ignore = $this->ignoreErrors( true );
613 ++
$this->mErrorCount
;
615 if( $ignore ||
$tempIgnore ) {
616 wfDebug("SQL ERROR (ignored): $error\n");
617 $this->ignoreErrors( $ignore );
619 $sql1line = str_replace( "\n", "\\n", $sql );
620 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
621 wfDebug("SQL ERROR: " . $error . "\n");
622 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
628 * Intended to be compatible with the PEAR::DB wrapper functions.
629 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
631 * ? = scalar value, quoted as necessary
632 * ! = raw SQL bit (a function for instance)
633 * & = filename; reads the file and inserts as a blob
634 * (we don't use this though...)
636 function prepare( $sql, $func = 'Database::prepare' ) {
637 /* MySQL doesn't support prepared statements (yet), so just
638 pack up the query for reference. We'll manually replace
640 return array( 'query' => $sql, 'func' => $func );
643 function freePrepared( $prepared ) {
644 /* No-op for MySQL */
648 * Execute a prepared query with the various arguments
649 * @param string $prepared the prepared sql
650 * @param mixed $args Either an array here, or put scalars as varargs
652 function execute( $prepared, $args = null ) {
653 if( !is_array( $args ) ) {
655 $args = func_get_args();
656 array_shift( $args );
658 $sql = $this->fillPrepared( $prepared['query'], $args );
659 return $this->query( $sql, $prepared['func'] );
663 * Prepare & execute an SQL statement, quoting and inserting arguments
664 * in the appropriate places.
665 * @param string $query
666 * @param string $args ...
668 function safeQuery( $query, $args = null ) {
669 $prepared = $this->prepare( $query, 'Database::safeQuery' );
670 if( !is_array( $args ) ) {
672 $args = func_get_args();
673 array_shift( $args );
675 $retval = $this->execute( $prepared, $args );
676 $this->freePrepared( $prepared );
681 * For faking prepared SQL statements on DBs that don't support
683 * @param string $preparedSql - a 'preparable' SQL statement
684 * @param array $args - array of arguments to fill it with
685 * @return string executable SQL
687 function fillPrepared( $preparedQuery, $args ) {
689 $this->preparedArgs
=& $args;
690 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
691 array( &$this, 'fillPreparedArg' ), $preparedQuery );
695 * preg_callback func for fillPrepared()
696 * The arguments should be in $this->preparedArgs and must not be touched
697 * while we're doing this.
699 * @param array $matches
703 function fillPreparedArg( $matches ) {
704 switch( $matches[1] ) {
705 case '\\?': return '?';
706 case '\\!': return '!';
707 case '\\&': return '&';
709 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
710 switch( $matches[1] ) {
711 case '?': return $this->addQuotes( $arg );
712 case '!': return $arg;
714 # return $this->addQuotes( file_get_contents( $arg ) );
715 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
717 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
722 * @param mixed $res A SQL result
725 * Free a result object
727 function freeResult( $res ) {
728 if ( $res instanceof ResultWrapper
) {
731 if ( !@/**/mysql_free_result( $res ) ) {
732 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
737 * Fetch the next row from the given result object, in object form.
738 * Fields can be retrieved with $row->fieldname, with fields acting like
741 * @param $res SQL result object as returned from Database::query(), etc.
742 * @return MySQL row object
743 * @throws DBUnexpectedError Thrown if the database returns an error
745 function fetchObject( $res ) {
746 if ( $res instanceof ResultWrapper
) {
749 @/**/$row = mysql_fetch_object( $res );
750 if( $this->lastErrno() ) {
751 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
757 * Fetch the next row from the given result object, in associative array
758 * form. Fields are retrieved with $row['fieldname'].
760 * @param $res SQL result object as returned from Database::query(), etc.
761 * @return MySQL row object
762 * @throws DBUnexpectedError Thrown if the database returns an error
764 function fetchRow( $res ) {
765 if ( $res instanceof ResultWrapper
) {
768 @/**/$row = mysql_fetch_array( $res );
769 if ( $this->lastErrno() ) {
770 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
776 * Get the number of rows in a result object
778 function numRows( $res ) {
779 if ( $res instanceof ResultWrapper
) {
782 @/**/$n = mysql_num_rows( $res );
783 if( $this->lastErrno() ) {
784 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
790 * Get the number of fields in a result object
791 * See documentation for mysql_num_fields()
793 function numFields( $res ) {
794 if ( $res instanceof ResultWrapper
) {
797 return mysql_num_fields( $res );
801 * Get a field name in a result object
802 * See documentation for mysql_field_name():
803 * http://www.php.net/mysql_field_name
805 function fieldName( $res, $n ) {
806 if ( $res instanceof ResultWrapper
) {
809 return mysql_field_name( $res, $n );
813 * Get the inserted value of an auto-increment row
815 * The value inserted should be fetched from nextSequenceValue()
818 * $id = $dbw->nextSequenceValue('page_page_id_seq');
819 * $dbw->insert('page',array('page_id' => $id));
820 * $id = $dbw->insertId();
822 function insertId() { return mysql_insert_id( $this->mConn
); }
825 * Change the position of the cursor in a result object
826 * See mysql_data_seek()
828 function dataSeek( $res, $row ) {
829 if ( $res instanceof ResultWrapper
) {
832 return mysql_data_seek( $res, $row );
836 * Get the last error number
839 function lastErrno() {
840 if ( $this->mConn
) {
841 return mysql_errno( $this->mConn
);
843 return mysql_errno();
848 * Get a description of the last error
849 * See mysql_error() for more details
851 function lastError() {
852 if ( $this->mConn
) {
853 # Even if it's non-zero, it can still be invalid
854 wfSuppressWarnings();
855 $error = mysql_error( $this->mConn
);
857 $error = mysql_error();
861 $error = mysql_error();
864 $error .= ' (' . $this->mServer
. ')';
869 * Get the number of rows affected by the last write query
870 * See mysql_affected_rows() for more details
872 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
873 /**#@-*/ // end of template : @param $result
876 * Simple UPDATE wrapper
877 * Usually aborts on failure
878 * If errors are explicitly ignored, returns success
880 * This function exists for historical reasons, Database::update() has a more standard
881 * calling convention and feature set
883 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
885 $table = $this->tableName( $table );
886 $sql = "UPDATE $table SET $var = '" .
887 $this->strencode( $value ) . "' WHERE ($cond)";
888 return (bool)$this->query( $sql, $fname );
892 * Simple SELECT wrapper, returns a single field, input must be encoded
893 * Usually aborts on failure
894 * If errors are explicitly ignored, returns FALSE on failure
896 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
897 if ( !is_array( $options ) ) {
898 $options = array( $options );
900 $options['LIMIT'] = 1;
902 $res = $this->select( $table, $var, $cond, $fname, $options );
903 if ( $res === false ||
!$this->numRows( $res ) ) {
906 $row = $this->fetchRow( $res );
907 if ( $row !== false ) {
908 $this->freeResult( $res );
916 * Returns an optional USE INDEX clause to go after the table, and a
917 * string to go at the end of the query
921 * @param array $options an associative array of options to be turned into
922 * an SQL query, valid keys are listed in the function.
925 function makeSelectOptions( $options ) {
926 $preLimitTail = $postLimitTail = '';
929 $noKeyOptions = array();
930 foreach ( $options as $key => $option ) {
931 if ( is_numeric( $key ) ) {
932 $noKeyOptions[$option] = true;
936 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
937 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
938 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
940 //if (isset($options['LIMIT'])) {
941 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
942 // isset($options['OFFSET']) ? $options['OFFSET']
946 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
947 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
948 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
950 # Various MySQL extensions
951 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
952 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
953 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
954 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
955 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
956 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
957 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
958 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
960 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
961 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
966 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
972 * @param mixed $table Array or string, table name(s) (prefix auto-added)
973 * @param mixed $vars Array or string, field name(s) to be retrieved
974 * @param mixed $conds Array or string, condition(s) for WHERE
975 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
976 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
977 * see Database::makeSelectOptions code for list of supported stuff
978 * @param array $join_conds Associative array of table join conditions (optional)
979 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
980 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
982 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() )
984 $sql = $this->selectSQLText( $table, $vars, $conds, $fname, $options, $join_conds );
985 return $this->query( $sql, $fname );
991 * @param mixed $table Array or string, table name(s) (prefix auto-added)
992 * @param mixed $vars Array or string, field name(s) to be retrieved
993 * @param mixed $conds Array or string, condition(s) for WHERE
994 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
995 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
996 * see Database::makeSelectOptions code for list of supported stuff
997 * @param array $join_conds Associative array of table join conditions (optional)
998 * (e.g. array( 'page' => array('LEFT JOIN','page_latest=rev_id') )
999 * @return string, the SQL text
1001 function selectSQLText( $table, $vars, $conds='', $fname = 'Database::select', $options = array(), $join_conds = array() ) {
1002 if( is_array( $vars ) ) {
1003 $vars = implode( ',', $vars );
1005 if( !is_array( $options ) ) {
1006 $options = array( $options );
1008 if( is_array( $table ) ) {
1009 if ( !empty($join_conds) ||
( isset( $options['USE INDEX'] ) && is_array( @$options['USE INDEX'] ) ) )
1010 $from = ' FROM ' . $this->tableNamesWithUseIndexOrJOIN( $table, @$options['USE INDEX'], $join_conds );
1012 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
1013 } elseif ($table!='') {
1014 if ($table{0}==' ') {
1015 $from = ' FROM ' . $table;
1017 $from = ' FROM ' . $this->tableName( $table );
1023 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
1025 if( !empty( $conds ) ) {
1026 if ( is_array( $conds ) ) {
1027 $conds = $this->makeList( $conds, LIST_AND
);
1029 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
1031 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
1034 if (isset($options['LIMIT']))
1035 $sql = $this->limitResult($sql, $options['LIMIT'],
1036 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
1037 $sql = "$sql $postLimitTail";
1039 if (isset($options['EXPLAIN'])) {
1040 $sql = 'EXPLAIN ' . $sql;
1046 * Single row SELECT wrapper
1047 * Aborts or returns FALSE on error
1049 * $vars: the selected variables
1050 * $conds: a condition map, terms are ANDed together.
1051 * Items with numeric keys are taken to be literal conditions
1052 * Takes an array of selected variables, and a condition map, which is ANDed
1053 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
1054 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
1055 * $obj- >page_id is the ID of the Astronomy article
1057 * @todo migrate documentation to phpdocumentor format
1059 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array(), $join_conds = array() ) {
1060 $options['LIMIT'] = 1;
1061 $res = $this->select( $table, $vars, $conds, $fname, $options, $join_conds );
1062 if ( $res === false )
1064 if ( !$this->numRows($res) ) {
1065 $this->freeResult($res);
1068 $obj = $this->fetchObject( $res );
1069 $this->freeResult( $res );
1075 * Estimate rows in dataset
1076 * Returns estimated count, based on EXPLAIN output
1077 * Takes same arguments as Database::select()
1080 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1081 $options['EXPLAIN']=true;
1082 $res = $this->select ($table, $vars, $conds, $fname, $options );
1083 if ( $res === false )
1085 if (!$this->numRows($res)) {
1086 $this->freeResult($res);
1092 while( $plan = $this->fetchObject( $res ) ) {
1093 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1096 $this->freeResult($res);
1102 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1103 * It's only slightly flawed. Don't use for anything important.
1105 * @param string $sql A SQL Query
1108 static function generalizeSQL( $sql ) {
1109 # This does the same as the regexp below would do, but in such a way
1110 # as to avoid crashing php on some large strings.
1111 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1113 $sql = str_replace ( "\\\\", '', $sql);
1114 $sql = str_replace ( "\\'", '', $sql);
1115 $sql = str_replace ( "\\\"", '', $sql);
1116 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1117 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1119 # All newlines, tabs, etc replaced by single space
1120 $sql = preg_replace ( '/\s+/', ' ', $sql);
1123 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1129 * Determines whether a field exists in a table
1130 * Usually aborts on failure
1131 * If errors are explicitly ignored, returns NULL on failure
1133 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1134 $table = $this->tableName( $table );
1135 $res = $this->query( 'DESCRIBE '.$table, $fname );
1142 while ( $row = $this->fetchObject( $res ) ) {
1143 if ( $row->Field
== $field ) {
1152 * Determines whether an index exists
1153 * Usually aborts on failure
1154 * If errors are explicitly ignored, returns NULL on failure
1156 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1157 $info = $this->indexInfo( $table, $index, $fname );
1158 if ( is_null( $info ) ) {
1161 return $info !== false;
1167 * Get information about an index into an object
1168 * Returns false if the index does not exist
1170 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1171 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1172 # SHOW INDEX should work for 3.x and up:
1173 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1174 $table = $this->tableName( $table );
1175 $sql = 'SHOW INDEX FROM '.$table;
1176 $res = $this->query( $sql, $fname );
1182 while ( $row = $this->fetchObject( $res ) ) {
1183 if ( $row->Key_name
== $index ) {
1187 $this->freeResult($res);
1189 return empty($result) ?
false : $result;
1193 * Query whether a given table exists
1195 function tableExists( $table ) {
1196 $table = $this->tableName( $table );
1197 $old = $this->ignoreErrors( true );
1198 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1199 $this->ignoreErrors( $old );
1201 $this->freeResult( $res );
1209 * mysql_fetch_field() wrapper
1210 * Returns false if the field doesn't exist
1215 function fieldInfo( $table, $field ) {
1216 $table = $this->tableName( $table );
1217 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1218 $n = mysql_num_fields( $res->result
);
1219 for( $i = 0; $i < $n; $i++
) {
1220 $meta = mysql_fetch_field( $res->result
, $i );
1221 if( $field == $meta->name
) {
1222 return new MySQLField($meta);
1229 * mysql_field_type() wrapper
1231 function fieldType( $res, $index ) {
1232 if ( $res instanceof ResultWrapper
) {
1233 $res = $res->result
;
1235 return mysql_field_type( $res, $index );
1239 * Determines if a given index is unique
1241 function indexUnique( $table, $index ) {
1242 $indexInfo = $this->indexInfo( $table, $index );
1243 if ( !$indexInfo ) {
1246 return !$indexInfo[0]->Non_unique
;
1250 * INSERT wrapper, inserts an array into a table
1252 * $a may be a single associative array, or an array of these with numeric keys, for
1255 * Usually aborts on failure
1256 * If errors are explicitly ignored, returns success
1258 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1259 # No rows to insert, easy just return now
1260 if ( !count( $a ) ) {
1264 $table = $this->tableName( $table );
1265 if ( !is_array( $options ) ) {
1266 $options = array( $options );
1268 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1270 $keys = array_keys( $a[0] );
1273 $keys = array_keys( $a );
1276 $sql = 'INSERT ' . implode( ' ', $options ) .
1277 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1281 foreach ( $a as $row ) {
1287 $sql .= '(' . $this->makeList( $row ) . ')';
1290 $sql .= '(' . $this->makeList( $a ) . ')';
1292 return (bool)$this->query( $sql, $fname );
1296 * Make UPDATE options for the Database::update function
1299 * @param array $options The options passed to Database::update
1302 function makeUpdateOptions( $options ) {
1303 if( !is_array( $options ) ) {
1304 $options = array( $options );
1307 if ( in_array( 'LOW_PRIORITY', $options ) )
1308 $opts[] = $this->lowPriorityOption();
1309 if ( in_array( 'IGNORE', $options ) )
1311 return implode(' ', $opts);
1315 * UPDATE wrapper, takes a condition array and a SET array
1317 * @param string $table The table to UPDATE
1318 * @param array $values An array of values to SET
1319 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1320 * @param string $fname The Class::Function calling this function
1322 * @param array $options An array of UPDATE options, can be one or
1323 * more of IGNORE, LOW_PRIORITY
1326 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1327 $table = $this->tableName( $table );
1328 $opts = $this->makeUpdateOptions( $options );
1329 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1330 if ( $conds != '*' ) {
1331 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1333 return $this->query( $sql, $fname );
1337 * Makes an encoded list of strings from an array
1339 * LIST_COMMA - comma separated, no field names
1340 * LIST_AND - ANDed WHERE clause (without the WHERE)
1341 * LIST_OR - ORed WHERE clause (without the WHERE)
1342 * LIST_SET - comma separated with field names, like a SET clause
1343 * LIST_NAMES - comma separated field names
1345 function makeList( $a, $mode = LIST_COMMA
) {
1346 if ( !is_array( $a ) ) {
1347 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1352 foreach ( $a as $field => $value ) {
1354 if ( $mode == LIST_AND
) {
1356 } elseif($mode == LIST_OR
) {
1364 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1365 $list .= "($value)";
1366 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1368 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1369 if( count( $value ) == 0 ) {
1370 throw new MWException( __METHOD__
.': empty input' );
1371 } elseif( count( $value ) == 1 ) {
1372 // Special-case single values, as IN isn't terribly efficient
1373 // Don't necessarily assume the single key is 0; we don't
1374 // enforce linear numeric ordering on other arrays here.
1375 $value = array_values( $value );
1376 $list .= $field." = ".$this->addQuotes( $value[0] );
1378 $list .= $field." IN (".$this->makeList($value).") ";
1380 } elseif( is_null($value) ) {
1381 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1382 $list .= "$field IS ";
1383 } elseif ( $mode == LIST_SET
) {
1384 $list .= "$field = ";
1388 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1389 $list .= "$field = ";
1391 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1398 * Change the current database
1400 function selectDB( $db ) {
1401 $this->mDBname
= $db;
1402 return mysql_select_db( $db, $this->mConn
);
1406 * Get the current DB name
1408 function getDBname() {
1409 return $this->mDBname
;
1413 * Get the server hostname or IP address
1415 function getServer() {
1416 return $this->mServer
;
1420 * Format a table name ready for use in constructing an SQL query
1422 * This does two important things: it quotes the table names to clean them up,
1423 * and it adds a table prefix if only given a table name with no quotes.
1425 * All functions of this object which require a table name call this function
1426 * themselves. Pass the canonical name to such functions. This is only needed
1427 * when calling query() directly.
1429 * @param string $name database table name
1430 * @return string full database name
1432 function tableName( $name ) {
1433 global $wgSharedDB, $wgSharedPrefix, $wgSharedTables;
1434 # Skip the entire process when we have a string quoted on both ends.
1435 # Note that we check the end so that we will still quote any use of
1436 # use of `database`.table. But won't break things if someone wants
1437 # to query a database table with a dot in the name.
1438 if ( $name[0] == '`' && substr( $name, -1, 1 ) == '`' ) return $name;
1440 # Lets test for any bits of text that should never show up in a table
1441 # name. Basically anything like JOIN or ON which are actually part of
1442 # SQL queries, but may end up inside of the table value to combine
1443 # sql. Such as how the API is doing.
1444 # Note that we use a whitespace test rather than a \b test to avoid
1445 # any remote case where a word like on may be inside of a table name
1446 # surrounded by symbols which may be considered word breaks.
1447 if( preg_match( '/(^|\s)(DISTINCT|JOIN|ON|AS)(\s|$)/i', $name ) !== 0 ) return $name;
1449 # Split database and table into proper variables.
1450 # We reverse the explode so that database.table and table both output
1451 # the correct table.
1452 $dbDetails = array_reverse( explode( '.', $name, 2 ) );
1453 if( isset( $dbDetails[1] ) ) @list
( $table, $database ) = $dbDetails;
1454 else @list
( $table ) = $dbDetails;
1455 $prefix = $this->mTablePrefix
; # Default prefix
1457 # A database name has been specified in input. Quote the table name
1458 # because we don't want any prefixes added.
1459 if( isset($database) ) $table = ( $table[0] == '`' ?
$table : "`{$table}`" );
1461 # Note that we use the long format because php will complain in in_array if
1462 # the input is not an array, and will complain in is_array if it is not set.
1463 if( !isset( $database ) # Don't use shared database if pre selected.
1464 && isset( $wgSharedDB ) # We have a shared database
1465 && $table[0] != '`' # Paranoia check to prevent shared tables listing '`table`'
1466 && isset( $wgSharedTables )
1467 && is_array( $wgSharedTables )
1468 && in_array( $table, $wgSharedTables ) ) { # A shared table is selected
1469 $database = $wgSharedDB;
1470 $prefix = isset( $wgSharedPrefix ) ?
$wgSharedPrefix : $prefix;
1473 # Quote the $database and $table and apply the prefix if not quoted.
1474 if( isset($database) ) $database = ( $database[0] == '`' ?
$database : "`{$database}`" );
1475 $table = ( $table[0] == '`' ?
$table : "`{$prefix}{$table}`" );
1477 # Merge our database and table into our final table name.
1478 $tableName = ( isset($database) ?
"{$database}.{$table}" : "{$table}" );
1480 # We're finished, return.
1485 * Fetch a number of table names into an array
1486 * This is handy when you need to construct SQL for joins
1489 * extract($dbr->tableNames('user','watchlist'));
1490 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1491 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1493 public function tableNames() {
1494 $inArray = func_get_args();
1496 foreach ( $inArray as $name ) {
1497 $retVal[$name] = $this->tableName( $name );
1503 * Fetch a number of table names into an zero-indexed numerical array
1504 * This is handy when you need to construct SQL for joins
1507 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1508 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1509 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1511 public function tableNamesN() {
1512 $inArray = func_get_args();
1514 foreach ( $inArray as $name ) {
1515 $retVal[] = $this->tableName( $name );
1523 function tableNamesWithUseIndexOrJOIN( $tables, $use_index = array(), $join_conds = array() ) {
1526 $use_index_safe = is_array($use_index) ?
$use_index : array();
1527 $join_conds_safe = is_array($join_conds) ?
$join_conds : array();
1528 foreach ( $tables as $table ) {
1529 // Is there a JOIN and INDEX clause for this table?
1530 if ( isset($join_conds_safe[$table]) && isset($use_index_safe[$table]) ) {
1531 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1532 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1533 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1534 $retJOIN[] = $tableClause;
1535 // Is there an INDEX clause?
1536 } else if ( isset($use_index_safe[$table]) ) {
1537 $tableClause = $this->tableName( $table );
1538 $tableClause .= ' ' . $this->useIndexClause( implode( ',', (array)$use_index_safe[$table] ) );
1539 $ret[] = $tableClause;
1540 // Is there a JOIN clause?
1541 } else if ( isset($join_conds_safe[$table]) ) {
1542 $tableClause = $join_conds_safe[$table][0] . ' ' . $this->tableName( $table );
1543 $tableClause .= ' ON (' . $this->makeList((array)$join_conds_safe[$table][1], LIST_AND
) . ')';
1544 $retJOIN[] = $tableClause;
1546 $tableClause = $this->tableName( $table );
1547 $ret[] = $tableClause;
1550 // We can't separate explicit JOIN clauses with ',', use ' ' for those
1551 $straightJoins = !empty($ret) ?
implode( ',', $ret ) : "";
1552 $otherJoins = !empty($retJOIN) ?
implode( ' ', $retJOIN ) : "";
1553 // Compile our final table clause
1554 return implode(' ',array($straightJoins,$otherJoins) );
1558 * Wrapper for addslashes()
1559 * @param string $s String to be slashed.
1560 * @return string slashed string.
1562 function strencode( $s ) {
1563 return mysql_real_escape_string( $s, $this->mConn
);
1567 * If it's a string, adds quotes and backslashes
1568 * Otherwise returns as-is
1570 function addQuotes( $s ) {
1571 if ( is_null( $s ) ) {
1574 # This will also quote numeric values. This should be harmless,
1575 # and protects against weird problems that occur when they really
1576 # _are_ strings such as article titles and string->number->string
1577 # conversion is not 1:1.
1578 return "'" . $this->strencode( $s ) . "'";
1583 * Escape string for safe LIKE usage
1585 function escapeLike( $s ) {
1586 $s=$this->strencode( $s );
1587 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1592 * Returns an appropriately quoted sequence value for inserting a new row.
1593 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1594 * subclass will return an integer, and save the value for insertId()
1596 function nextSequenceValue( $seqName ) {
1602 * PostgreSQL doesn't have them and returns ""
1604 function useIndexClause( $index ) {
1605 return "FORCE INDEX ($index)";
1609 * REPLACE query wrapper
1610 * PostgreSQL simulates this with a DELETE followed by INSERT
1611 * $row is the row to insert, an associative array
1612 * $uniqueIndexes is an array of indexes. Each element may be either a
1613 * field name or an array of field names
1615 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1616 * However if you do this, you run the risk of encountering errors which wouldn't have
1619 * @todo migrate comment to phodocumentor format
1621 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1622 $table = $this->tableName( $table );
1625 if ( !is_array( reset( $rows ) ) ) {
1626 $rows = array( $rows );
1629 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1631 foreach ( $rows as $row ) {
1637 $sql .= '(' . $this->makeList( $row ) . ')';
1639 return $this->query( $sql, $fname );
1643 * DELETE where the condition is a join
1644 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1646 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1647 * join condition matches, set $conds='*'
1649 * DO NOT put the join condition in $conds
1651 * @param string $delTable The table to delete from.
1652 * @param string $joinTable The other table.
1653 * @param string $delVar The variable to join on, in the first table.
1654 * @param string $joinVar The variable to join on, in the second table.
1655 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1657 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1659 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1662 $delTable = $this->tableName( $delTable );
1663 $joinTable = $this->tableName( $joinTable );
1664 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1665 if ( $conds != '*' ) {
1666 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1669 return $this->query( $sql, $fname );
1673 * Returns the size of a text field, or -1 for "unlimited"
1675 function textFieldSize( $table, $field ) {
1676 $table = $this->tableName( $table );
1677 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1678 $res = $this->query( $sql, 'Database::textFieldSize' );
1679 $row = $this->fetchObject( $res );
1680 $this->freeResult( $res );
1683 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1692 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1694 function lowPriorityOption() {
1695 return 'LOW_PRIORITY';
1699 * DELETE query wrapper
1701 * Use $conds == "*" to delete all rows
1703 function delete( $table, $conds, $fname = 'Database::delete' ) {
1705 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1707 $table = $this->tableName( $table );
1708 $sql = "DELETE FROM $table";
1709 if ( $conds != '*' ) {
1710 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1712 return $this->query( $sql, $fname );
1716 * INSERT SELECT wrapper
1717 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1718 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1719 * $conds may be "*" to copy the whole table
1720 * srcTable may be an array of tables.
1722 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1723 $insertOptions = array(), $selectOptions = array() )
1725 $destTable = $this->tableName( $destTable );
1726 if ( is_array( $insertOptions ) ) {
1727 $insertOptions = implode( ' ', $insertOptions );
1729 if( !is_array( $selectOptions ) ) {
1730 $selectOptions = array( $selectOptions );
1732 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1733 if( is_array( $srcTable ) ) {
1734 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1736 $srcTable = $this->tableName( $srcTable );
1738 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1739 " SELECT $startOpts " . implode( ',', $varMap ) .
1740 " FROM $srcTable $useIndex ";
1741 if ( $conds != '*' ) {
1742 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1744 $sql .= " $tailOpts";
1745 return $this->query( $sql, $fname );
1749 * Construct a LIMIT query with optional offset
1750 * This is used for query pages
1751 * $sql string SQL query we will append the limit too
1752 * $limit integer the SQL limit
1753 * $offset integer the SQL offset (default false)
1755 function limitResult($sql, $limit, $offset=false) {
1756 if( !is_numeric($limit) ) {
1757 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1759 return "$sql LIMIT "
1760 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1763 function limitResultForUpdate($sql, $num) {
1764 return $this->limitResult($sql, $num, 0);
1768 * Returns an SQL expression for a simple conditional.
1771 * @param string $cond SQL expression which will result in a boolean value
1772 * @param string $trueVal SQL expression to return if true
1773 * @param string $falseVal SQL expression to return if false
1774 * @return string SQL fragment
1776 function conditional( $cond, $trueVal, $falseVal ) {
1777 return " IF($cond, $trueVal, $falseVal) ";
1781 * Returns a comand for str_replace function in SQL query.
1782 * Uses REPLACE() in MySQL
1784 * @param string $orig String or column to modify
1785 * @param string $old String or column to seek
1786 * @param string $new String or column to replace with
1788 function strreplace( $orig, $old, $new ) {
1789 return "REPLACE({$orig}, {$old}, {$new})";
1793 * Determines if the last failure was due to a deadlock
1795 function wasDeadlock() {
1796 return $this->lastErrno() == 1213;
1800 * Perform a deadlock-prone transaction.
1802 * This function invokes a callback function to perform a set of write
1803 * queries. If a deadlock occurs during the processing, the transaction
1804 * will be rolled back and the callback function will be called again.
1807 * $dbw->deadlockLoop( callback, ... );
1809 * Extra arguments are passed through to the specified callback function.
1811 * Returns whatever the callback function returned on its successful,
1812 * iteration, or false on error, for example if the retry limit was
1815 function deadlockLoop() {
1816 $myFname = 'Database::deadlockLoop';
1819 $args = func_get_args();
1820 $function = array_shift( $args );
1821 $oldIgnore = $this->ignoreErrors( true );
1822 $tries = DEADLOCK_TRIES
;
1823 if ( is_array( $function ) ) {
1824 $fname = $function[0];
1829 $retVal = call_user_func_array( $function, $args );
1830 $error = $this->lastError();
1831 $errno = $this->lastErrno();
1832 $sql = $this->lastQuery();
1835 if ( $this->wasDeadlock() ) {
1837 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1839 $this->reportQueryError( $error, $errno, $sql, $fname );
1842 } while( $this->wasDeadlock() && --$tries > 0 );
1843 $this->ignoreErrors( $oldIgnore );
1844 if ( $tries <= 0 ) {
1845 $this->query( 'ROLLBACK', $myFname );
1846 $this->reportQueryError( $error, $errno, $sql, $fname );
1849 $this->query( 'COMMIT', $myFname );
1855 * Do a SELECT MASTER_POS_WAIT()
1857 * @param string $file the binlog file
1858 * @param string $pos the binlog position
1859 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1861 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1862 $fname = 'Database::masterPosWait';
1863 wfProfileIn( $fname );
1865 # Commit any open transactions
1866 if ( $this->mTrxLevel
) {
1867 $this->immediateCommit();
1870 if ( !is_null( $this->mFakeSlaveLag
) ) {
1871 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1872 if ( $wait > $timeout * 1e6
) {
1873 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1874 wfProfileOut( $fname );
1876 } elseif ( $wait > 0 ) {
1877 wfDebug( "Fake slave waiting $wait us\n" );
1879 wfProfileOut( $fname );
1882 wfDebug( "Fake slave up to date ($wait us)\n" );
1883 wfProfileOut( $fname );
1888 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1889 $encFile = $this->addQuotes( $pos->file
);
1890 $encPos = intval( $pos->pos
);
1891 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1892 $res = $this->doQuery( $sql );
1893 if ( $res && $row = $this->fetchRow( $res ) ) {
1894 $this->freeResult( $res );
1895 wfProfileOut( $fname );
1898 wfProfileOut( $fname );
1904 * Get the position of the master from SHOW SLAVE STATUS
1906 function getSlavePos() {
1907 if ( !is_null( $this->mFakeSlaveLag
) ) {
1908 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1909 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1912 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1913 $row = $this->fetchObject( $res );
1915 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1922 * Get the position of the master from SHOW MASTER STATUS
1924 function getMasterPos() {
1925 if ( $this->mFakeMaster
) {
1926 return new MySQLMasterPos( 'fake', microtime( true ) );
1928 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1929 $row = $this->fetchObject( $res );
1931 return new MySQLMasterPos( $row->File
, $row->Position
);
1938 * Begin a transaction, committing any previously open transaction
1940 function begin( $fname = 'Database::begin' ) {
1941 $this->query( 'BEGIN', $fname );
1942 $this->mTrxLevel
= 1;
1948 function commit( $fname = 'Database::commit' ) {
1949 $this->query( 'COMMIT', $fname );
1950 $this->mTrxLevel
= 0;
1954 * Rollback a transaction.
1955 * No-op on non-transactional databases.
1957 function rollback( $fname = 'Database::rollback' ) {
1958 $this->query( 'ROLLBACK', $fname, true );
1959 $this->mTrxLevel
= 0;
1963 * Begin a transaction, committing any previously open transaction
1964 * @deprecated use begin()
1966 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1971 * Commit transaction, if one is open
1972 * @deprecated use commit()
1974 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1979 * Return MW-style timestamp used for MySQL schema
1981 function timestamp( $ts=0 ) {
1982 return wfTimestamp(TS_MW
,$ts);
1986 * Local database timestamp format or null
1988 function timestampOrNull( $ts = null ) {
1989 if( is_null( $ts ) ) {
1992 return $this->timestamp( $ts );
1999 function resultObject( $result ) {
2000 if( empty( $result ) ) {
2002 } elseif ( $result instanceof ResultWrapper
) {
2004 } elseif ( $result === true ) {
2005 // Successful write query
2008 return new ResultWrapper( $this, $result );
2013 * Return aggregated value alias
2015 function aggregateValue ($valuedata,$valuename='value') {
2020 * @return string wikitext of a link to the server software's web site
2022 function getSoftwareLink() {
2023 return "[http://www.mysql.com/ MySQL]";
2027 * @return string Version information from the database
2029 function getServerVersion() {
2030 return mysql_get_server_info( $this->mConn
);
2034 * Ping the server and try to reconnect if it there is no connection
2037 if( !function_exists( 'mysql_ping' ) ) {
2038 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
2041 $ping = mysql_ping( $this->mConn
);
2046 // Need to reconnect manually in MySQL client 5.0.13+
2047 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
2048 mysql_close( $this->mConn
);
2049 $this->mOpened
= false;
2050 $this->mConn
= false;
2051 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
2059 * At the moment, this will only work if the DB user has the PROCESS privilege
2062 if ( !is_null( $this->mFakeSlaveLag
) ) {
2063 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
2064 return $this->mFakeSlaveLag
;
2066 $res = $this->query( 'SHOW PROCESSLIST' );
2067 # Find slave SQL thread
2068 while ( $row = $this->fetchObject( $res ) ) {
2069 /* This should work for most situations - when default db
2070 * for thread is not specified, it had no events executed,
2071 * and therefore it doesn't know yet how lagged it is.
2073 * Relay log I/O thread does not select databases.
2075 if ( $row->User
== 'system user' &&
2076 $row->State
!= 'Waiting for master to send event' &&
2077 $row->State
!= 'Connecting to master' &&
2078 $row->State
!= 'Queueing master event to the relay log' &&
2079 $row->State
!= 'Waiting for master update' &&
2080 $row->State
!= 'Requesting binlog dump'
2082 # This is it, return the time (except -ve)
2083 if ( $row->Time
> 0x7fffffff ) {
2094 * Get status information from SHOW STATUS in an associative array
2096 function getStatus($which="%") {
2097 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
2099 while ( $row = $this->fetchObject( $res ) ) {
2100 $status[$row->Variable_name
] = $row->Value
;
2106 * Return the maximum number of items allowed in a list, or 0 for unlimited.
2108 function maxListLen() {
2112 function encodeBlob($b) {
2116 function decodeBlob($b) {
2121 * Override database's default connection timeout.
2122 * May be useful for very long batch queries such as
2123 * full-wiki dumps, where a single query reads out
2124 * over hours or days.
2125 * @param int $timeout in seconds
2127 public function setTimeout( $timeout ) {
2128 $this->query( "SET net_read_timeout=$timeout" );
2129 $this->query( "SET net_write_timeout=$timeout" );
2133 * Read and execute SQL commands from a file.
2134 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2135 * @param string $filename File name to open
2136 * @param callback $lineCallback Optional function called before reading each line
2137 * @param callback $resultCallback Optional function called for each MySQL result
2139 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2140 $fp = fopen( $filename, 'r' );
2141 if ( false === $fp ) {
2142 throw new MWException( "Could not open \"{$filename}\".\n" );
2144 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2150 * Read and execute commands from an open file handle
2151 * Returns true on success, error string or exception on failure (depending on object's error ignore settings)
2152 * @param string $fp File handle
2153 * @param callback $lineCallback Optional function called before reading each line
2154 * @param callback $resultCallback Optional function called for each MySQL result
2156 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2159 $dollarquote = false;
2161 while ( ! feof( $fp ) ) {
2162 if ( $lineCallback ) {
2163 call_user_func( $lineCallback );
2165 $line = trim( fgets( $fp, 1024 ) );
2166 $sl = strlen( $line ) - 1;
2168 if ( $sl < 0 ) { continue; }
2169 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2171 ## Allow dollar quoting for function declarations
2172 if (substr($line,0,4) == '$mw$') {
2174 $dollarquote = false;
2178 $dollarquote = true;
2181 else if (!$dollarquote) {
2182 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2184 $line = substr( $line, 0, $sl );
2188 if ( '' != $cmd ) { $cmd .= ' '; }
2192 $cmd = str_replace(';;', ";", $cmd);
2193 $cmd = $this->replaceVars( $cmd );
2194 $res = $this->query( $cmd, __METHOD__
);
2195 if ( $resultCallback ) {
2196 call_user_func( $resultCallback, $res, $this );
2199 if ( false === $res ) {
2200 $err = $this->lastError();
2201 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2213 * Replace variables in sourced SQL
2215 protected function replaceVars( $ins ) {
2217 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2218 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2219 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2222 // Ordinary variables
2223 foreach ( $varnames as $var ) {
2224 if( isset( $GLOBALS[$var] ) ) {
2225 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2226 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2227 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2228 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2233 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-zA-Z_0-9]*)/',
2234 array( &$this, 'tableNameCallback' ), $ins );
2239 * Table name callback
2242 protected function tableNameCallback( $matches ) {
2243 return $this->tableName( $matches[1] );
2247 * Build a concatenation list to feed into a SQL query
2249 function buildConcat( $stringList ) {
2250 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2256 * Abstracted from Filestore::lock() so child classes can implement for
2259 * @param string $lockName Name of lock to aquire
2260 * @param string $method Name of method calling us
2263 public function lock( $lockName, $method ) {
2264 $lockName = $this->addQuotes( $lockName );
2265 $result = $this->query( "SELECT GET_LOCK($lockName, 5) AS lockstatus", $method );
2266 $row = $this->fetchObject( $result );
2267 $this->freeResult( $result );
2269 if( $row->lockstatus
== 1 ) {
2272 wfDebug( __METHOD__
." failed to acquire lock\n" );
2279 * @todo fixme - Figure out a way to return a bool
2280 * based on successful lock release.
2282 * @param string $lockName Name of lock to release
2283 * @param string $method Name of method calling us
2285 public function unlock( $lockName, $method ) {
2286 $lockName = $this->addQuotes( $lockName );
2287 $result = $this->query( "SELECT RELEASE_LOCK($lockName)", $method );
2288 $this->freeResult( $result );
2292 * Get search engine class. All subclasses of this
2293 * need to implement this if they wish to use searching.
2297 public function getSearchEngine() {
2298 return "SearchMySQL";
2303 * Database abstraction object for mySQL
2304 * Inherit all methods and properties of Database::Database()
2309 class DatabaseMysql
extends Database
{
2313 /******************************************************************************
2315 *****************************************************************************/
2324 function DBObject($data) {
2325 $this->mData
= $data;
2333 return $this->mData
;
2341 * This allows us to distinguish a blob from a normal string and an array of strings
2345 function __construct($data) {
2346 $this->mData
= $data;
2349 return $this->mData
;
2358 private $name, $tablename, $default, $max_length, $nullable,
2359 $is_pk, $is_unique, $is_multiple, $is_key, $type;
2360 function __construct ($info) {
2361 $this->name
= $info->name
;
2362 $this->tablename
= $info->table
;
2363 $this->default = $info->def
;
2364 $this->max_length
= $info->max_length
;
2365 $this->nullable
= !$info->not_null
;
2366 $this->is_pk
= $info->primary_key
;
2367 $this->is_unique
= $info->unique_key
;
2368 $this->is_multiple
= $info->multiple_key
;
2369 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2370 $this->type
= $info->type
;
2377 function tableName() {
2378 return $this->tableName
;
2381 function defaultValue() {
2382 return $this->default;
2385 function maxLength() {
2386 return $this->max_length
;
2389 function nullable() {
2390 return $this->nullable
;
2394 return $this->is_key
;
2397 function isMultipleKey() {
2398 return $this->is_multiple
;
2406 /******************************************************************************
2408 *****************************************************************************/
2411 * Database error base class
2414 class DBError
extends MWException
{
2418 * Construct a database error
2419 * @param Database $db The database object which threw the error
2420 * @param string $error A simple error message to be used for debugging
2422 function __construct( Database
&$db, $error ) {
2424 parent
::__construct( $error );
2431 class DBConnectionError
extends DBError
{
2434 function __construct( Database
&$db, $error = 'unknown error' ) {
2435 $msg = 'DB connection error';
2436 if ( trim( $error ) != '' ) {
2439 $this->error
= $error;
2440 parent
::__construct( $db, $msg );
2443 function useOutputPage() {
2444 // Not likely to work
2448 function useMessageCache() {
2449 // Not likely to work
2453 function getText() {
2454 return $this->getMessage() . "\n";
2457 function getLogMessage() {
2458 # Don't send to the exception log
2462 function getPageTitle() {
2464 return "$wgSitename has a problem";
2467 function getHTML() {
2468 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2469 global $wgSitename, $wgServer, $wgMessageCache;
2471 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2472 # Hard coding strings instead.
2474 $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>";
2475 $mainpage = 'Main Page';
2476 $searchdisabled = <<<EOT
2477 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2478 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2482 <!-- SiteSearch Google -->
2483 <FORM method=GET action=\"http://www.google.com/search\">
2484 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2485 <A HREF=\"http://www.google.com/\">
2486 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2487 border=\"0\" ALT=\"Google\"></A>
2490 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2491 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2493 <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 />
2494 <input type='hidden' name='ie' value='$2'>
2495 <input type='hidden' name='oe' value='$2'>
2499 <!-- SiteSearch Google -->";
2500 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2502 # No database access
2503 if ( is_object( $wgMessageCache ) ) {
2504 $wgMessageCache->disable();
2507 if ( trim( $this->error
) == '' ) {
2508 $this->error
= $this->db
->getProperty('mServer');
2511 $text = str_replace( '$1', $this->error
, $noconnect );
2513 global $wgShowExceptionDetails;
2514 if ( $GLOBALS['wgShowExceptionDetails'] ) {
2515 $text .= '</p><p>Backtrace:</p><p>' .
2516 nl2br( htmlspecialchars( $this->getTraceAsString() ) ) .
2520 if($wgUseFileCache) {
2525 $t = Title
::newFromURL( $title );
2526 } elseif (@/**/$_REQUEST['search']) {
2527 $search = $_REQUEST['search'];
2528 return $searchdisabled .
2529 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2530 $wgInputEncoding ), $googlesearch );
2532 $t = Title
::newFromText( $mainpage );
2536 $cache = new HTMLFileCache( $t );
2537 if( $cache->isFileCached() ) {
2538 // @todo, FIXME: $msg is not defined on the next line.
2539 $msg = '<p style="color: red"><b>'.$text."<br />\n" .
2540 $cachederror . "</b></p>\n";
2542 $tag = '<div id="article">';
2543 $text = str_replace(
2546 $cache->fetchPageText() );
2557 class DBQueryError
extends DBError
{
2558 public $error, $errno, $sql, $fname;
2560 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2561 $message = "A database error has occurred\n" .
2563 "Function: $fname\n" .
2564 "Error: $errno $error\n";
2566 parent
::__construct( $db, $message );
2567 $this->error
= $error;
2568 $this->errno
= $errno;
2570 $this->fname
= $fname;
2573 function getText() {
2574 if ( $this->useMessageCache() ) {
2575 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2576 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2578 return $this->getMessage();
2583 global $wgShowSQLErrors;
2584 if( !$wgShowSQLErrors ) {
2585 return $this->msg( 'sqlhidden', 'SQL hidden' );
2591 function getLogMessage() {
2592 # Don't send to the exception log
2596 function getPageTitle() {
2597 return $this->msg( 'databaseerror', 'Database error' );
2600 function getHTML() {
2601 if ( $this->useMessageCache() ) {
2602 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2603 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2605 return nl2br( htmlspecialchars( $this->getMessage() ) );
2613 class DBUnexpectedError
extends DBError
{}
2617 * Result wrapper for grabbing data queried by someone else
2620 class ResultWrapper
implements Iterator
{
2621 var $db, $result, $pos = 0, $currentRow = null;
2624 * Create a new result object from a result resource and a Database object
2626 function ResultWrapper( $database, $result ) {
2627 $this->db
= $database;
2628 if ( $result instanceof ResultWrapper
) {
2629 $this->result
= $result->result
;
2631 $this->result
= $result;
2636 * Get the number of rows in a result object
2638 function numRows() {
2639 return $this->db
->numRows( $this->result
);
2643 * Fetch the next row from the given result object, in object form.
2644 * Fields can be retrieved with $row->fieldname, with fields acting like
2647 * @param $res SQL result object as returned from Database::query(), etc.
2648 * @return MySQL row object
2649 * @throws DBUnexpectedError Thrown if the database returns an error
2651 function fetchObject() {
2652 return $this->db
->fetchObject( $this->result
);
2656 * Fetch the next row from the given result object, in associative array
2657 * form. Fields are retrieved with $row['fieldname'].
2659 * @param $res SQL result object as returned from Database::query(), etc.
2660 * @return MySQL row object
2661 * @throws DBUnexpectedError Thrown if the database returns an error
2663 function fetchRow() {
2664 return $this->db
->fetchRow( $this->result
);
2668 * Free a result object
2671 $this->db
->freeResult( $this->result
);
2672 unset( $this->result
);
2677 * Change the position of the cursor in a result object
2678 * See mysql_data_seek()
2680 function seek( $row ) {
2681 $this->db
->dataSeek( $this->result
, $row );
2684 /*********************
2685 * Iterator functions
2686 * Note that using these in combination with the non-iterator functions
2687 * above may cause rows to be skipped or repeated.
2691 if ($this->numRows()) {
2692 $this->db
->dataSeek($this->result
, 0);
2695 $this->currentRow
= null;
2698 function current() {
2699 if ( is_null( $this->currentRow
) ) {
2702 return $this->currentRow
;
2711 $this->currentRow
= $this->fetchObject();
2712 return $this->currentRow
;
2716 return $this->current() !== false;
2720 class MySQLMasterPos
{
2723 function __construct( $file, $pos ) {
2724 $this->file
= $file;
2728 function __toString() {
2729 return "{$this->file}/{$this->pos}";