3 * This file deals with MySQL interface functions
4 * and query specifics/optimisations
7 /** Number of times to re-try an operation in case of deadlock */
8 define( 'DEADLOCK_TRIES', 4 );
9 /** Minimum time to wait before retry, in microseconds */
10 define( 'DEADLOCK_DELAY_MIN', 500000 );
11 /** Maximum time to wait before retry */
12 define( 'DEADLOCK_DELAY_MAX', 1500000 );
15 * Database abstraction object
16 * @addtogroup Database
20 #------------------------------------------------------------------------------
22 #------------------------------------------------------------------------------
24 protected $mLastQuery = '';
26 protected $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
27 protected $mOut, $mOpened = false;
29 protected $mFailFunction;
30 protected $mTablePrefix;
32 protected $mTrxLevel = 0;
33 protected $mErrorCount = 0;
34 protected $mLBInfo = array();
35 protected $mFakeSlaveLag = null, $mFakeMaster = false;
37 #------------------------------------------------------------------------------
39 #------------------------------------------------------------------------------
40 # These optionally set a variable and return the previous state
43 * Fail function, takes a Database as a parameter
44 * Set to false for default, 1 for ignore errors
46 function failFunction( $function = NULL ) {
47 return wfSetVar( $this->mFailFunction
, $function );
51 * Output page, used for reporting errors
52 * FALSE means discard output
54 function setOutputPage( $out ) {
59 * Boolean, controls output of large amounts of debug information
61 function debug( $debug = NULL ) {
62 return wfSetBit( $this->mFlags
, DBO_DEBUG
, $debug );
66 * Turns buffering of SQL result sets on (true) or off (false).
67 * Default is "on" and it should not be changed without good reasons.
69 function bufferResults( $buffer = NULL ) {
70 if ( is_null( $buffer ) ) {
71 return !(bool)( $this->mFlags
& DBO_NOBUFFER
);
73 return !wfSetBit( $this->mFlags
, DBO_NOBUFFER
, !$buffer );
78 * Turns on (false) or off (true) the automatic generation and sending
79 * of a "we're sorry, but there has been a database error" page on
80 * database errors. Default is on (false). When turned off, the
81 * code should use lastErrno() and lastError() to handle the
82 * situation as appropriate.
84 function ignoreErrors( $ignoreErrors = NULL ) {
85 return wfSetBit( $this->mFlags
, DBO_IGNORE
, $ignoreErrors );
89 * The current depth of nested transactions
90 * @param $level Integer: , default NULL.
92 function trxLevel( $level = NULL ) {
93 return wfSetVar( $this->mTrxLevel
, $level );
97 * Number of errors logged, only useful when errors are ignored
99 function errorCount( $count = NULL ) {
100 return wfSetVar( $this->mErrorCount
, $count );
103 function tablePrefix( $prefix = null ) {
104 return wfSetVar( $this->mTablePrefix
, $prefix );
108 * Properties passed down from the server info array of the load balancer
110 function getLBInfo( $name = NULL ) {
111 if ( is_null( $name ) ) {
112 return $this->mLBInfo
;
114 if ( array_key_exists( $name, $this->mLBInfo
) ) {
115 return $this->mLBInfo
[$name];
122 function setLBInfo( $name, $value = NULL ) {
123 if ( is_null( $value ) ) {
124 $this->mLBInfo
= $name;
126 $this->mLBInfo
[$name] = $value;
131 * Set lag time in seconds for a fake slave
133 function setFakeSlaveLag( $lag ) {
134 $this->mFakeSlaveLag
= $lag;
138 * Make this connection a fake master
140 function setFakeMaster( $enabled = true ) {
141 $this->mFakeMaster
= $enabled;
145 * Returns true if this database supports (and uses) cascading deletes
147 function cascadingDeletes() {
152 * Returns true if this database supports (and uses) triggers (e.g. on the page table)
154 function cleanupTriggers() {
159 * Returns true if this database is strict about what can be put into an IP field.
160 * Specifically, it uses a NULL value instead of an empty string.
162 function strictIPs() {
167 * Returns true if this database uses timestamps rather than integers
169 function realTimestamps() {
174 * Returns true if this database does an implicit sort when doing GROUP BY
176 function implicitGroupby() {
181 * Returns true if this database does an implicit order by when the column has an index
182 * For example: SELECT page_title FROM page LIMIT 1
184 function implicitOrderby() {
189 * Returns true if this database can do a native search on IP columns
190 * e.g. this works as expected: .. WHERE rc_ip = '127.42.12.102/32';
192 function searchableIPs() {
197 * Returns true if this database can use functional indexes
199 function functionalIndexes() {
206 function lastQuery() { return $this->mLastQuery
; }
207 function isOpen() { return $this->mOpened
; }
210 function setFlag( $flag ) {
211 $this->mFlags |
= $flag;
214 function clearFlag( $flag ) {
215 $this->mFlags
&= ~
$flag;
218 function getFlag( $flag ) {
219 return !!($this->mFlags
& $flag);
223 * General read-only accessor
225 function getProperty( $name ) {
229 #------------------------------------------------------------------------------
231 #------------------------------------------------------------------------------
235 * @param string $server database server host
236 * @param string $user database user name
237 * @param string $password database user password
238 * @param string $dbname database name
239 * @param failFunction
241 * @param $tablePrefix String: database table prefixes. By default use the prefix gave in LocalSettings.php
243 function __construct( $server = false, $user = false, $password = false, $dbName = false,
244 $failFunction = false, $flags = 0, $tablePrefix = 'get from global' ) {
246 global $wgOut, $wgDBprefix, $wgCommandLineMode;
247 # Can't get a reference if it hasn't been set yet
248 if ( !isset( $wgOut ) ) {
251 $this->mOut
=& $wgOut;
253 $this->mFailFunction
= $failFunction;
254 $this->mFlags
= $flags;
256 if ( $this->mFlags
& DBO_DEFAULT
) {
257 if ( $wgCommandLineMode ) {
258 $this->mFlags
&= ~DBO_TRX
;
260 $this->mFlags |
= DBO_TRX
;
265 // Faster read-only access
266 if ( wfReadOnly() ) {
267 $this->mFlags |= DBO_PERSISTENT;
268 $this->mFlags &= ~DBO_TRX;
271 /** Get the default table prefix*/
272 if ( $tablePrefix == 'get from global' ) {
273 $this->mTablePrefix
= $wgDBprefix;
275 $this->mTablePrefix
= $tablePrefix;
279 $this->open( $server, $user, $password, $dbName );
285 * @param failFunction
288 static function newFromParams( $server, $user, $password, $dbName, $failFunction = false, $flags = 0 )
290 return new Database( $server, $user, $password, $dbName, $failFunction, $flags );
294 * Usually aborts on failure
295 * If the failFunction is set to a non-zero integer, returns success
297 function open( $server, $user, $password, $dbName ) {
299 wfProfileIn( __METHOD__
);
301 # Test for missing mysql.so
302 # First try to load it
303 if (!@extension_loaded
('mysql')) {
308 # Otherwise we get a suppressed fatal error, which is very hard to track down
309 if ( !function_exists( 'mysql_connect' ) ) {
310 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
314 $this->mServer
= $server;
315 $this->mUser
= $user;
316 $this->mPassword
= $password;
317 $this->mDBname
= $dbName;
321 wfProfileIn("dbconnect-$server");
323 # Try to connect up to three times
324 # The kernel's default SYN retransmission period is far too slow for us,
325 # so we use a short timeout plus a manual retry.
326 $this->mConn
= false;
328 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
332 if ( $this->mFlags
& DBO_PERSISTENT
) {
333 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
335 # Create a new connection...
336 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
338 if ($this->mConn
=== false) {
340 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
344 wfProfileOut("dbconnect-$server");
346 if ( $dbName != '' ) {
347 if ( $this->mConn
!== false ) {
348 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
350 $error = "Error selecting database $dbName on server {$this->mServer} " .
351 "from client host {$wguname['nodename']}\n";
352 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
356 wfDebug( "DB connection error\n" );
357 wfDebug( "Server: $server, User: $user, Password: " .
358 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
363 $success = (bool)$this->mConn
;
367 $version = $this->getServerVersion();
368 if ( version_compare( $version, '4.1' ) >= 0 ) {
369 // Tell the server we're communicating with it in UTF-8.
370 // This may engage various charset conversions.
373 $this->query( 'SET NAMES utf8', __METHOD__
);
375 // Turn off strict mode
376 $this->query( "SET sql_mode = ''", __METHOD__
);
379 // Turn off strict mode if it is on
381 $this->reportConnectionError();
384 $this->mOpened
= $success;
385 wfProfileOut( __METHOD__
);
391 * Closes a database connection.
392 * if it is open : commits any open transactions
394 * @return bool operation success. true if already closed.
398 $this->mOpened
= false;
399 if ( $this->mConn
) {
400 if ( $this->trxLevel() ) {
401 $this->immediateCommit();
403 return mysql_close( $this->mConn
);
410 * @param string $error fallback error message, used if none is given by MySQL
412 function reportConnectionError( $error = 'Unknown error' ) {
413 $myError = $this->lastError();
418 if ( $this->mFailFunction
) {
419 # Legacy error handling method
420 if ( !is_int( $this->mFailFunction
) ) {
421 $ff = $this->mFailFunction
;
422 $ff( $this, $error );
426 wfLogDBError( "Connection error: $error\n" );
427 throw new DBConnectionError( $this, $error );
432 * Usually aborts on failure. If errors are explicitly ignored, returns success.
434 * @param $sql String: SQL query
435 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
436 * comment (you can use __METHOD__ or add some extra info)
437 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
438 * maybe best to catch the exception instead?
439 * @return true for a successful write query, ResultWrapper object for a successful read query,
440 * or false on failure if $tempIgnore set
441 * @throws DBQueryError Thrown when the database returns an error of any kind
443 public function query( $sql, $fname = '', $tempIgnore = false ) {
446 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
447 if ( $wgProfiling ) {
448 # generalizeSQL will probably cut down the query to reasonable
449 # logging size most of the time. The substr is really just a sanity check.
451 # Who's been wasting my precious column space? -- TS
452 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
455 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
456 $totalProf = 'Database::query-master';
458 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
459 $totalProf = 'Database::query';
461 wfProfileIn( $totalProf );
462 wfProfileIn( $queryProf );
465 $this->mLastQuery
= $sql;
467 # Add a comment for easy SHOW PROCESSLIST interpretation
470 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
471 $userName = $wgUser->getName();
472 if ( mb_strlen( $userName ) > 15 ) {
473 $userName = mb_substr( $userName, 0, 15 ) . '...';
475 $userName = str_replace( '/', '', $userName );
479 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
481 # $commentedSql = $sql;
484 # If DBO_TRX is set, start a transaction
485 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
486 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
487 // avoid establishing transactions for SHOW and SET statements too -
488 // that would delay transaction initializations to once connection
489 // is really used by application
490 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
491 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
495 if ( $this->debug() ) {
496 $sqlx = substr( $commentedSql, 0, 500 );
497 $sqlx = strtr( $sqlx, "\t\n", ' ' );
499 wfDebug( "SQL-master: $sqlx\n" );
501 wfDebug( "SQL: $sqlx\n" );
505 # Do the query and handle errors
506 $ret = $this->doQuery( $commentedSql );
508 # Try reconnecting if the connection was lost
509 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
510 # Transaction is gone, like it or not
511 $this->mTrxLevel
= 0;
512 wfDebug( "Connection lost, reconnecting...\n" );
513 if ( $this->ping() ) {
514 wfDebug( "Reconnected\n" );
515 $sqlx = substr( $commentedSql, 0, 500 );
516 $sqlx = strtr( $sqlx, "\t\n", ' ' );
517 global $wgRequestTime;
518 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
519 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
520 $ret = $this->doQuery( $commentedSql );
522 wfDebug( "Failed\n" );
526 if ( false === $ret ) {
527 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
530 if ( $wgProfiling ) {
531 wfProfileOut( $queryProf );
532 wfProfileOut( $totalProf );
534 return $this->resultObject( $ret );
538 * The DBMS-dependent part of query()
539 * @param $sql String: SQL query.
540 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
543 /*private*/ function doQuery( $sql ) {
544 if( $this->bufferResults() ) {
545 $ret = mysql_query( $sql, $this->mConn
);
547 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
556 * @param string $fname
557 * @param bool $tempIgnore
559 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
560 global $wgCommandLineMode;
561 # Ignore errors during error handling to avoid infinite recursion
562 $ignore = $this->ignoreErrors( true );
563 ++
$this->mErrorCount
;
565 if( $ignore ||
$tempIgnore ) {
566 wfDebug("SQL ERROR (ignored): $error\n");
567 $this->ignoreErrors( $ignore );
569 $sql1line = str_replace( "\n", "\\n", $sql );
570 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
571 wfDebug("SQL ERROR: " . $error . "\n");
572 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
578 * Intended to be compatible with the PEAR::DB wrapper functions.
579 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
581 * ? = scalar value, quoted as necessary
582 * ! = raw SQL bit (a function for instance)
583 * & = filename; reads the file and inserts as a blob
584 * (we don't use this though...)
586 function prepare( $sql, $func = 'Database::prepare' ) {
587 /* MySQL doesn't support prepared statements (yet), so just
588 pack up the query for reference. We'll manually replace
590 return array( 'query' => $sql, 'func' => $func );
593 function freePrepared( $prepared ) {
594 /* No-op for MySQL */
598 * Execute a prepared query with the various arguments
599 * @param string $prepared the prepared sql
600 * @param mixed $args Either an array here, or put scalars as varargs
602 function execute( $prepared, $args = null ) {
603 if( !is_array( $args ) ) {
605 $args = func_get_args();
606 array_shift( $args );
608 $sql = $this->fillPrepared( $prepared['query'], $args );
609 return $this->query( $sql, $prepared['func'] );
613 * Prepare & execute an SQL statement, quoting and inserting arguments
614 * in the appropriate places.
615 * @param string $query
616 * @param string $args ...
618 function safeQuery( $query, $args = null ) {
619 $prepared = $this->prepare( $query, 'Database::safeQuery' );
620 if( !is_array( $args ) ) {
622 $args = func_get_args();
623 array_shift( $args );
625 $retval = $this->execute( $prepared, $args );
626 $this->freePrepared( $prepared );
631 * For faking prepared SQL statements on DBs that don't support
633 * @param string $preparedSql - a 'preparable' SQL statement
634 * @param array $args - array of arguments to fill it with
635 * @return string executable SQL
637 function fillPrepared( $preparedQuery, $args ) {
639 $this->preparedArgs
=& $args;
640 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
641 array( &$this, 'fillPreparedArg' ), $preparedQuery );
645 * preg_callback func for fillPrepared()
646 * The arguments should be in $this->preparedArgs and must not be touched
647 * while we're doing this.
649 * @param array $matches
653 function fillPreparedArg( $matches ) {
654 switch( $matches[1] ) {
655 case '\\?': return '?';
656 case '\\!': return '!';
657 case '\\&': return '&';
659 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
660 switch( $matches[1] ) {
661 case '?': return $this->addQuotes( $arg );
662 case '!': return $arg;
664 # return $this->addQuotes( file_get_contents( $arg ) );
665 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
667 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
672 * @param mixed $res A SQL result
675 * Free a result object
677 function freeResult( $res ) {
678 if ( $res instanceof ResultWrapper
) {
681 if ( !@/**/mysql_free_result( $res ) ) {
682 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
687 * Fetch the next row from the given result object, in object form.
688 * Fields can be retrieved with $row->fieldname, with fields acting like
691 * @param $res SQL result object as returned from Database::query(), etc.
692 * @return MySQL row object
693 * @throws DBUnexpectedError Thrown if the database returns an error
695 function fetchObject( $res ) {
696 if ( $res instanceof ResultWrapper
) {
699 @/**/$row = mysql_fetch_object( $res );
700 if( $this->lastErrno() ) {
701 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
707 * Fetch the next row from the given result object, in associative array
708 * form. Fields are retrieved with $row['fieldname'].
710 * @param $res SQL result object as returned from Database::query(), etc.
711 * @return MySQL row object
712 * @throws DBUnexpectedError Thrown if the database returns an error
714 function fetchRow( $res ) {
715 if ( $res instanceof ResultWrapper
) {
718 @/**/$row = mysql_fetch_array( $res );
719 if ( $this->lastErrno() ) {
720 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
726 * Get the number of rows in a result object
728 function numRows( $res ) {
729 if ( $res instanceof ResultWrapper
) {
732 @/**/$n = mysql_num_rows( $res );
733 if( $this->lastErrno() ) {
734 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
740 * Get the number of fields in a result object
741 * See documentation for mysql_num_fields()
743 function numFields( $res ) {
744 if ( $res instanceof ResultWrapper
) {
747 return mysql_num_fields( $res );
751 * Get a field name in a result object
752 * See documentation for mysql_field_name():
753 * http://www.php.net/mysql_field_name
755 function fieldName( $res, $n ) {
756 if ( $res instanceof ResultWrapper
) {
759 return mysql_field_name( $res, $n );
763 * Get the inserted value of an auto-increment row
765 * The value inserted should be fetched from nextSequenceValue()
768 * $id = $dbw->nextSequenceValue('page_page_id_seq');
769 * $dbw->insert('page',array('page_id' => $id));
770 * $id = $dbw->insertId();
772 function insertId() { return mysql_insert_id( $this->mConn
); }
775 * Change the position of the cursor in a result object
776 * See mysql_data_seek()
778 function dataSeek( $res, $row ) {
779 if ( $res instanceof ResultWrapper
) {
782 return mysql_data_seek( $res, $row );
786 * Get the last error number
789 function lastErrno() {
790 if ( $this->mConn
) {
791 return mysql_errno( $this->mConn
);
793 return mysql_errno();
798 * Get a description of the last error
799 * See mysql_error() for more details
801 function lastError() {
802 if ( $this->mConn
) {
803 # Even if it's non-zero, it can still be invalid
804 wfSuppressWarnings();
805 $error = mysql_error( $this->mConn
);
807 $error = mysql_error();
811 $error = mysql_error();
814 $error .= ' (' . $this->mServer
. ')';
819 * Get the number of rows affected by the last write query
820 * See mysql_affected_rows() for more details
822 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
823 /**#@-*/ // end of template : @param $result
826 * Simple UPDATE wrapper
827 * Usually aborts on failure
828 * If errors are explicitly ignored, returns success
830 * This function exists for historical reasons, Database::update() has a more standard
831 * calling convention and feature set
833 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
835 $table = $this->tableName( $table );
836 $sql = "UPDATE $table SET $var = '" .
837 $this->strencode( $value ) . "' WHERE ($cond)";
838 return (bool)$this->query( $sql, $fname );
842 * Simple SELECT wrapper, returns a single field, input must be encoded
843 * Usually aborts on failure
844 * If errors are explicitly ignored, returns FALSE on failure
846 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
847 if ( !is_array( $options ) ) {
848 $options = array( $options );
850 $options['LIMIT'] = 1;
852 $res = $this->select( $table, $var, $cond, $fname, $options );
853 if ( $res === false ||
!$this->numRows( $res ) ) {
856 $row = $this->fetchRow( $res );
857 if ( $row !== false ) {
858 $this->freeResult( $res );
866 * Returns an optional USE INDEX clause to go after the table, and a
867 * string to go at the end of the query
871 * @param array $options an associative array of options to be turned into
872 * an SQL query, valid keys are listed in the function.
875 function makeSelectOptions( $options ) {
876 $preLimitTail = $postLimitTail = '';
879 $noKeyOptions = array();
880 foreach ( $options as $key => $option ) {
881 if ( is_numeric( $key ) ) {
882 $noKeyOptions[$option] = true;
886 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
887 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
888 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
890 //if (isset($options['LIMIT'])) {
891 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
892 // isset($options['OFFSET']) ? $options['OFFSET']
896 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
897 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
898 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
900 # Various MySQL extensions
901 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
902 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
903 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
904 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
905 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
906 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
907 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
908 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
910 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
911 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
916 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
922 * @param mixed $table Array or string, table name(s) (prefix auto-added)
923 * @param mixed $vars Array or string, field name(s) to be retrieved
924 * @param mixed $conds Array or string, condition(s) for WHERE
925 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
926 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
927 * see Database::makeSelectOptions code for list of supported stuff
928 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
930 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
932 if( is_array( $vars ) ) {
933 $vars = implode( ',', $vars );
935 if( !is_array( $options ) ) {
936 $options = array( $options );
938 if( is_array( $table ) ) {
939 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
940 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
942 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
943 } elseif ($table!='') {
944 if ($table{0}==' ') {
945 $from = ' FROM ' . $table;
947 $from = ' FROM ' . $this->tableName( $table );
953 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
955 if( !empty( $conds ) ) {
956 if ( is_array( $conds ) ) {
957 $conds = $this->makeList( $conds, LIST_AND
);
959 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
961 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
964 if (isset($options['LIMIT']))
965 $sql = $this->limitResult($sql, $options['LIMIT'],
966 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
967 $sql = "$sql $postLimitTail";
969 if (isset($options['EXPLAIN'])) {
970 $sql = 'EXPLAIN ' . $sql;
972 return $this->query( $sql, $fname );
976 * Single row SELECT wrapper
977 * Aborts or returns FALSE on error
979 * $vars: the selected variables
980 * $conds: a condition map, terms are ANDed together.
981 * Items with numeric keys are taken to be literal conditions
982 * Takes an array of selected variables, and a condition map, which is ANDed
983 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
984 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
985 * $obj- >page_id is the ID of the Astronomy article
987 * @todo migrate documentation to phpdocumentor format
989 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
990 $options['LIMIT'] = 1;
991 $res = $this->select( $table, $vars, $conds, $fname, $options );
992 if ( $res === false )
994 if ( !$this->numRows($res) ) {
995 $this->freeResult($res);
998 $obj = $this->fetchObject( $res );
999 $this->freeResult( $res );
1005 * Estimate rows in dataset
1006 * Returns estimated count, based on EXPLAIN output
1007 * Takes same arguments as Database::select()
1010 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1011 $options['EXPLAIN']=true;
1012 $res = $this->select ($table, $vars, $conds, $fname, $options );
1013 if ( $res === false )
1015 if (!$this->numRows($res)) {
1016 $this->freeResult($res);
1022 while( $plan = $this->fetchObject( $res ) ) {
1023 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1026 $this->freeResult($res);
1032 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1033 * It's only slightly flawed. Don't use for anything important.
1035 * @param string $sql A SQL Query
1038 static function generalizeSQL( $sql ) {
1039 # This does the same as the regexp below would do, but in such a way
1040 # as to avoid crashing php on some large strings.
1041 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1043 $sql = str_replace ( "\\\\", '', $sql);
1044 $sql = str_replace ( "\\'", '', $sql);
1045 $sql = str_replace ( "\\\"", '', $sql);
1046 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1047 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1049 # All newlines, tabs, etc replaced by single space
1050 $sql = preg_replace ( '/\s+/', ' ', $sql);
1053 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1059 * Determines whether a field exists in a table
1060 * Usually aborts on failure
1061 * If errors are explicitly ignored, returns NULL on failure
1063 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1064 $table = $this->tableName( $table );
1065 $res = $this->query( 'DESCRIBE '.$table, $fname );
1072 while ( $row = $this->fetchObject( $res ) ) {
1073 if ( $row->Field
== $field ) {
1082 * Determines whether an index exists
1083 * Usually aborts on failure
1084 * If errors are explicitly ignored, returns NULL on failure
1086 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1087 $info = $this->indexInfo( $table, $index, $fname );
1088 if ( is_null( $info ) ) {
1091 return $info !== false;
1097 * Get information about an index into an object
1098 * Returns false if the index does not exist
1100 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1101 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1102 # SHOW INDEX should work for 3.x and up:
1103 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1104 $table = $this->tableName( $table );
1105 $sql = 'SHOW INDEX FROM '.$table;
1106 $res = $this->query( $sql, $fname );
1112 while ( $row = $this->fetchObject( $res ) ) {
1113 if ( $row->Key_name
== $index ) {
1117 $this->freeResult($res);
1119 return empty($result) ?
false : $result;
1123 * Query whether a given table exists
1125 function tableExists( $table ) {
1126 $table = $this->tableName( $table );
1127 $old = $this->ignoreErrors( true );
1128 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1129 $this->ignoreErrors( $old );
1131 $this->freeResult( $res );
1139 * mysql_fetch_field() wrapper
1140 * Returns false if the field doesn't exist
1145 function fieldInfo( $table, $field ) {
1146 $table = $this->tableName( $table );
1147 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1148 $n = mysql_num_fields( $res->result
);
1149 for( $i = 0; $i < $n; $i++
) {
1150 $meta = mysql_fetch_field( $res->result
, $i );
1151 if( $field == $meta->name
) {
1152 return new MySQLField($meta);
1159 * mysql_field_type() wrapper
1161 function fieldType( $res, $index ) {
1162 if ( $res instanceof ResultWrapper
) {
1163 $res = $res->result
;
1165 return mysql_field_type( $res, $index );
1169 * Determines if a given index is unique
1171 function indexUnique( $table, $index ) {
1172 $indexInfo = $this->indexInfo( $table, $index );
1173 if ( !$indexInfo ) {
1176 return !$indexInfo[0]->Non_unique
;
1180 * INSERT wrapper, inserts an array into a table
1182 * $a may be a single associative array, or an array of these with numeric keys, for
1185 * Usually aborts on failure
1186 * If errors are explicitly ignored, returns success
1188 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1189 # No rows to insert, easy just return now
1190 if ( !count( $a ) ) {
1194 $table = $this->tableName( $table );
1195 if ( !is_array( $options ) ) {
1196 $options = array( $options );
1198 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1200 $keys = array_keys( $a[0] );
1203 $keys = array_keys( $a );
1206 $sql = 'INSERT ' . implode( ' ', $options ) .
1207 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1211 foreach ( $a as $row ) {
1217 $sql .= '(' . $this->makeList( $row ) . ')';
1220 $sql .= '(' . $this->makeList( $a ) . ')';
1222 return (bool)$this->query( $sql, $fname );
1226 * Make UPDATE options for the Database::update function
1229 * @param array $options The options passed to Database::update
1232 function makeUpdateOptions( $options ) {
1233 if( !is_array( $options ) ) {
1234 $options = array( $options );
1237 if ( in_array( 'LOW_PRIORITY', $options ) )
1238 $opts[] = $this->lowPriorityOption();
1239 if ( in_array( 'IGNORE', $options ) )
1241 return implode(' ', $opts);
1245 * UPDATE wrapper, takes a condition array and a SET array
1247 * @param string $table The table to UPDATE
1248 * @param array $values An array of values to SET
1249 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1250 * @param string $fname The Class::Function calling this function
1252 * @param array $options An array of UPDATE options, can be one or
1253 * more of IGNORE, LOW_PRIORITY
1256 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1257 $table = $this->tableName( $table );
1258 $opts = $this->makeUpdateOptions( $options );
1259 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1260 if ( $conds != '*' ) {
1261 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1263 return $this->query( $sql, $fname );
1267 * Makes an encoded list of strings from an array
1269 * LIST_COMMA - comma separated, no field names
1270 * LIST_AND - ANDed WHERE clause (without the WHERE)
1271 * LIST_OR - ORed WHERE clause (without the WHERE)
1272 * LIST_SET - comma separated with field names, like a SET clause
1273 * LIST_NAMES - comma separated field names
1275 function makeList( $a, $mode = LIST_COMMA
) {
1276 if ( !is_array( $a ) ) {
1277 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1282 foreach ( $a as $field => $value ) {
1284 if ( $mode == LIST_AND
) {
1286 } elseif($mode == LIST_OR
) {
1294 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1295 $list .= "($value)";
1296 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1298 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1299 if( count( $value ) == 0 ) {
1300 throw new MWException( __METHOD__
.': empty input' );
1301 } elseif( count( $value ) == 1 ) {
1302 // Special-case single values, as IN isn't terribly efficient
1303 // Don't necessarily assume the single key is 0; we don't
1304 // enforce linear numeric ordering on other arrays here.
1305 $value = array_values( $value );
1306 $list .= $field." = ".$this->addQuotes( $value[0] );
1308 $list .= $field." IN (".$this->makeList($value).") ";
1310 } elseif( is_null($value) ) {
1311 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1312 $list .= "$field IS ";
1313 } elseif ( $mode == LIST_SET
) {
1314 $list .= "$field = ";
1318 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1319 $list .= "$field = ";
1321 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1328 * Change the current database
1330 function selectDB( $db ) {
1331 $this->mDBname
= $db;
1332 return mysql_select_db( $db, $this->mConn
);
1336 * Get the current DB name
1338 function getDBname() {
1339 return $this->mDBname
;
1343 * Get the server hostname or IP address
1345 function getServer() {
1346 return $this->mServer
;
1350 * Format a table name ready for use in constructing an SQL query
1352 * This does two important things: it quotes table names which as necessary,
1353 * and it adds a table prefix if there is one.
1355 * All functions of this object which require a table name call this function
1356 * themselves. Pass the canonical name to such functions. This is only needed
1357 * when calling query() directly.
1359 * @param string $name database table name
1361 function tableName( $name ) {
1363 # Skip quoted literals
1364 if ( $name{0} != '`' ) {
1365 if ( $this->mTablePrefix
!== '' && strpos( $name, '.' ) === false ) {
1366 $name = "{$this->mTablePrefix}$name";
1368 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1369 $name = "`$wgSharedDB`.`$name`";
1379 * Fetch a number of table names into an array
1380 * This is handy when you need to construct SQL for joins
1383 * extract($dbr->tableNames('user','watchlist'));
1384 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1385 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1387 public function tableNames() {
1388 $inArray = func_get_args();
1390 foreach ( $inArray as $name ) {
1391 $retVal[$name] = $this->tableName( $name );
1397 * Fetch a number of table names into an zero-indexed numerical array
1398 * This is handy when you need to construct SQL for joins
1401 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1402 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1403 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1405 public function tableNamesN() {
1406 $inArray = func_get_args();
1408 foreach ( $inArray as $name ) {
1409 $retVal[] = $this->tableName( $name );
1417 function tableNamesWithUseIndex( $tables, $use_index ) {
1420 foreach ( $tables as $table )
1421 if ( @$use_index[$table] !== null )
1422 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1424 $ret[] = $this->tableName( $table );
1426 return implode( ',', $ret );
1430 * Wrapper for addslashes()
1431 * @param string $s String to be slashed.
1432 * @return string slashed string.
1434 function strencode( $s ) {
1435 return mysql_real_escape_string( $s, $this->mConn
);
1439 * If it's a string, adds quotes and backslashes
1440 * Otherwise returns as-is
1442 function addQuotes( $s ) {
1443 if ( is_null( $s ) ) {
1446 # This will also quote numeric values. This should be harmless,
1447 # and protects against weird problems that occur when they really
1448 # _are_ strings such as article titles and string->number->string
1449 # conversion is not 1:1.
1450 return "'" . $this->strencode( $s ) . "'";
1455 * Escape string for safe LIKE usage
1457 function escapeLike( $s ) {
1458 $s=$this->strencode( $s );
1459 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1464 * Returns an appropriately quoted sequence value for inserting a new row.
1465 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1466 * subclass will return an integer, and save the value for insertId()
1468 function nextSequenceValue( $seqName ) {
1474 * PostgreSQL doesn't have them and returns ""
1476 function useIndexClause( $index ) {
1477 return "FORCE INDEX ($index)";
1481 * REPLACE query wrapper
1482 * PostgreSQL simulates this with a DELETE followed by INSERT
1483 * $row is the row to insert, an associative array
1484 * $uniqueIndexes is an array of indexes. Each element may be either a
1485 * field name or an array of field names
1487 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1488 * However if you do this, you run the risk of encountering errors which wouldn't have
1491 * @todo migrate comment to phodocumentor format
1493 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1494 $table = $this->tableName( $table );
1497 if ( !is_array( reset( $rows ) ) ) {
1498 $rows = array( $rows );
1501 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1503 foreach ( $rows as $row ) {
1509 $sql .= '(' . $this->makeList( $row ) . ')';
1511 return $this->query( $sql, $fname );
1515 * DELETE where the condition is a join
1516 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1518 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1519 * join condition matches, set $conds='*'
1521 * DO NOT put the join condition in $conds
1523 * @param string $delTable The table to delete from.
1524 * @param string $joinTable The other table.
1525 * @param string $delVar The variable to join on, in the first table.
1526 * @param string $joinVar The variable to join on, in the second table.
1527 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1529 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1531 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1534 $delTable = $this->tableName( $delTable );
1535 $joinTable = $this->tableName( $joinTable );
1536 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1537 if ( $conds != '*' ) {
1538 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1541 return $this->query( $sql, $fname );
1545 * Returns the size of a text field, or -1 for "unlimited"
1547 function textFieldSize( $table, $field ) {
1548 $table = $this->tableName( $table );
1549 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1550 $res = $this->query( $sql, 'Database::textFieldSize' );
1551 $row = $this->fetchObject( $res );
1552 $this->freeResult( $res );
1555 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1564 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1566 function lowPriorityOption() {
1567 return 'LOW_PRIORITY';
1571 * DELETE query wrapper
1573 * Use $conds == "*" to delete all rows
1575 function delete( $table, $conds, $fname = 'Database::delete' ) {
1577 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1579 $table = $this->tableName( $table );
1580 $sql = "DELETE FROM $table";
1581 if ( $conds != '*' ) {
1582 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1584 return $this->query( $sql, $fname );
1588 * INSERT SELECT wrapper
1589 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1590 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1591 * $conds may be "*" to copy the whole table
1592 * srcTable may be an array of tables.
1594 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1595 $insertOptions = array(), $selectOptions = array() )
1597 $destTable = $this->tableName( $destTable );
1598 if ( is_array( $insertOptions ) ) {
1599 $insertOptions = implode( ' ', $insertOptions );
1601 if( !is_array( $selectOptions ) ) {
1602 $selectOptions = array( $selectOptions );
1604 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1605 if( is_array( $srcTable ) ) {
1606 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1608 $srcTable = $this->tableName( $srcTable );
1610 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1611 " SELECT $startOpts " . implode( ',', $varMap ) .
1612 " FROM $srcTable $useIndex ";
1613 if ( $conds != '*' ) {
1614 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1616 $sql .= " $tailOpts";
1617 return $this->query( $sql, $fname );
1621 * Construct a LIMIT query with optional offset
1622 * This is used for query pages
1623 * $sql string SQL query we will append the limit too
1624 * $limit integer the SQL limit
1625 * $offset integer the SQL offset (default false)
1627 function limitResult($sql, $limit, $offset=false) {
1628 if( !is_numeric($limit) ) {
1629 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1631 return " $sql LIMIT "
1632 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1635 function limitResultForUpdate($sql, $num) {
1636 return $this->limitResult($sql, $num, 0);
1640 * Returns an SQL expression for a simple conditional.
1643 * @param string $cond SQL expression which will result in a boolean value
1644 * @param string $trueVal SQL expression to return if true
1645 * @param string $falseVal SQL expression to return if false
1646 * @return string SQL fragment
1648 function conditional( $cond, $trueVal, $falseVal ) {
1649 return " IF($cond, $trueVal, $falseVal) ";
1653 * Determines if the last failure was due to a deadlock
1655 function wasDeadlock() {
1656 return $this->lastErrno() == 1213;
1660 * Perform a deadlock-prone transaction.
1662 * This function invokes a callback function to perform a set of write
1663 * queries. If a deadlock occurs during the processing, the transaction
1664 * will be rolled back and the callback function will be called again.
1667 * $dbw->deadlockLoop( callback, ... );
1669 * Extra arguments are passed through to the specified callback function.
1671 * Returns whatever the callback function returned on its successful,
1672 * iteration, or false on error, for example if the retry limit was
1675 function deadlockLoop() {
1676 $myFname = 'Database::deadlockLoop';
1679 $args = func_get_args();
1680 $function = array_shift( $args );
1681 $oldIgnore = $this->ignoreErrors( true );
1682 $tries = DEADLOCK_TRIES
;
1683 if ( is_array( $function ) ) {
1684 $fname = $function[0];
1689 $retVal = call_user_func_array( $function, $args );
1690 $error = $this->lastError();
1691 $errno = $this->lastErrno();
1692 $sql = $this->lastQuery();
1695 if ( $this->wasDeadlock() ) {
1697 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1699 $this->reportQueryError( $error, $errno, $sql, $fname );
1702 } while( $this->wasDeadlock() && --$tries > 0 );
1703 $this->ignoreErrors( $oldIgnore );
1704 if ( $tries <= 0 ) {
1705 $this->query( 'ROLLBACK', $myFname );
1706 $this->reportQueryError( $error, $errno, $sql, $fname );
1709 $this->query( 'COMMIT', $myFname );
1715 * Do a SELECT MASTER_POS_WAIT()
1717 * @param string $file the binlog file
1718 * @param string $pos the binlog position
1719 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1721 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1722 $fname = 'Database::masterPosWait';
1723 wfProfileIn( $fname );
1725 # Commit any open transactions
1726 if ( $this->mTrxLevel
) {
1727 $this->immediateCommit();
1730 if ( !is_null( $this->mFakeSlaveLag
) ) {
1731 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1732 if ( $wait > $timeout * 1e6
) {
1733 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1734 wfProfileOut( $fname );
1736 } elseif ( $wait > 0 ) {
1737 wfDebug( "Fake slave waiting $wait us\n" );
1739 wfProfileOut( $fname );
1742 wfDebug( "Fake slave up to date ($wait us)\n" );
1743 wfProfileOut( $fname );
1748 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1749 $encFile = $this->addQuotes( $pos->file
);
1750 $encPos = intval( $pos->pos
);
1751 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1752 $res = $this->doQuery( $sql );
1753 if ( $res && $row = $this->fetchRow( $res ) ) {
1754 $this->freeResult( $res );
1755 wfProfileOut( $fname );
1758 wfProfileOut( $fname );
1764 * Get the position of the master from SHOW SLAVE STATUS
1766 function getSlavePos() {
1767 if ( !is_null( $this->mFakeSlaveLag
) ) {
1768 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1769 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1772 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1773 $row = $this->fetchObject( $res );
1775 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1782 * Get the position of the master from SHOW MASTER STATUS
1784 function getMasterPos() {
1785 if ( $this->mFakeMaster
) {
1786 return new MySQLMasterPos( 'fake', microtime( true ) );
1788 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1789 $row = $this->fetchObject( $res );
1791 return new MySQLMasterPos( $row->File
, $row->Position
);
1798 * Begin a transaction, committing any previously open transaction
1800 function begin( $fname = 'Database::begin' ) {
1801 $this->query( 'BEGIN', $fname );
1802 $this->mTrxLevel
= 1;
1808 function commit( $fname = 'Database::commit' ) {
1809 $this->query( 'COMMIT', $fname );
1810 $this->mTrxLevel
= 0;
1814 * Rollback a transaction.
1815 * No-op on non-transactional databases.
1817 function rollback( $fname = 'Database::rollback' ) {
1818 $this->query( 'ROLLBACK', $fname, true );
1819 $this->mTrxLevel
= 0;
1823 * Begin a transaction, committing any previously open transaction
1824 * @deprecated use begin()
1826 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1831 * Commit transaction, if one is open
1832 * @deprecated use commit()
1834 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1839 * Return MW-style timestamp used for MySQL schema
1841 function timestamp( $ts=0 ) {
1842 return wfTimestamp(TS_MW
,$ts);
1846 * Local database timestamp format or null
1848 function timestampOrNull( $ts = null ) {
1849 if( is_null( $ts ) ) {
1852 return $this->timestamp( $ts );
1859 function resultObject( $result ) {
1860 if( empty( $result ) ) {
1862 } elseif ( $result instanceof ResultWrapper
) {
1864 } elseif ( $result === true ) {
1865 // Successful write query
1868 return new ResultWrapper( $this, $result );
1873 * Return aggregated value alias
1875 function aggregateValue ($valuedata,$valuename='value') {
1880 * @return string wikitext of a link to the server software's web site
1882 function getSoftwareLink() {
1883 return "[http://www.mysql.com/ MySQL]";
1887 * @return string Version information from the database
1889 function getServerVersion() {
1890 return mysql_get_server_info( $this->mConn
);
1894 * Ping the server and try to reconnect if it there is no connection
1897 if( !function_exists( 'mysql_ping' ) ) {
1898 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1901 $ping = mysql_ping( $this->mConn
);
1906 // Need to reconnect manually in MySQL client 5.0.13+
1907 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
1908 mysql_close( $this->mConn
);
1909 $this->mOpened
= false;
1910 $this->mConn
= false;
1911 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
1919 * At the moment, this will only work if the DB user has the PROCESS privilege
1922 if ( !is_null( $this->mFakeSlaveLag
) ) {
1923 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
1924 return $this->mFakeSlaveLag
;
1926 $res = $this->query( 'SHOW PROCESSLIST' );
1927 # Find slave SQL thread
1928 while ( $row = $this->fetchObject( $res ) ) {
1929 /* This should work for most situations - when default db
1930 * for thread is not specified, it had no events executed,
1931 * and therefore it doesn't know yet how lagged it is.
1933 * Relay log I/O thread does not select databases.
1935 if ( $row->User
== 'system user' &&
1936 $row->State
!= 'Waiting for master to send event' &&
1937 $row->State
!= 'Connecting to master' &&
1938 $row->State
!= 'Queueing master event to the relay log' &&
1939 $row->State
!= 'Waiting for master update' &&
1940 $row->State
!= 'Requesting binlog dump'
1942 # This is it, return the time (except -ve)
1943 if ( $row->Time
> 0x7fffffff ) {
1954 * Get status information from SHOW STATUS in an associative array
1956 function getStatus($which="%") {
1957 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1959 while ( $row = $this->fetchObject( $res ) ) {
1960 $status[$row->Variable_name
] = $row->Value
;
1966 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1968 function maxListLen() {
1972 function encodeBlob($b) {
1976 function decodeBlob($b) {
1981 * Override database's default connection timeout.
1982 * May be useful for very long batch queries such as
1983 * full-wiki dumps, where a single query reads out
1984 * over hours or days.
1985 * @param int $timeout in seconds
1987 public function setTimeout( $timeout ) {
1988 $this->query( "SET net_read_timeout=$timeout" );
1989 $this->query( "SET net_write_timeout=$timeout" );
1993 * Read and execute SQL commands from a file.
1994 * Returns true on success, error string on failure
1995 * @param string $filename File name to open
1996 * @param callback $lineCallback Optional function called before reading each line
1997 * @param callback $resultCallback Optional function called for each MySQL result
1999 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2000 $fp = fopen( $filename, 'r' );
2001 if ( false === $fp ) {
2002 return "Could not open \"{$filename}\".\n";
2004 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2010 * Read and execute commands from an open file handle
2011 * Returns true on success, error string on failure
2012 * @param string $fp File handle
2013 * @param callback $lineCallback Optional function called before reading each line
2014 * @param callback $resultCallback Optional function called for each MySQL result
2016 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2019 $dollarquote = false;
2021 while ( ! feof( $fp ) ) {
2022 if ( $lineCallback ) {
2023 call_user_func( $lineCallback );
2025 $line = trim( fgets( $fp, 1024 ) );
2026 $sl = strlen( $line ) - 1;
2028 if ( $sl < 0 ) { continue; }
2029 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2031 ## Allow dollar quoting for function declarations
2032 if (substr($line,0,4) == '$mw$') {
2034 $dollarquote = false;
2038 $dollarquote = true;
2041 else if (!$dollarquote) {
2042 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2044 $line = substr( $line, 0, $sl );
2048 if ( '' != $cmd ) { $cmd .= ' '; }
2052 $cmd = str_replace(';;', ";", $cmd);
2053 $cmd = $this->replaceVars( $cmd );
2054 $res = $this->query( $cmd, __METHOD__
, true );
2055 if ( $resultCallback ) {
2056 call_user_func( $resultCallback, $res );
2059 if ( false === $res ) {
2060 $err = $this->lastError();
2061 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2073 * Replace variables in sourced SQL
2075 protected function replaceVars( $ins ) {
2077 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2078 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2079 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2082 // Ordinary variables
2083 foreach ( $varnames as $var ) {
2084 if( isset( $GLOBALS[$var] ) ) {
2085 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2086 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2087 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2088 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2093 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2094 array( &$this, 'tableNameCallback' ), $ins );
2099 * Table name callback
2102 protected function tableNameCallback( $matches ) {
2103 return $this->tableName( $matches[1] );
2107 * Build a concatenation list to feed into a SQL query
2109 function buildConcat( $stringList ) {
2110 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2116 * Database abstraction object for mySQL
2117 * Inherit all methods and properties of Database::Database()
2119 * @addtogroup Database
2122 class DatabaseMysql
extends Database
{
2126 /******************************************************************************
2128 *****************************************************************************/
2132 * @addtogroup Database
2137 function DBObject($data) {
2138 $this->mData
= $data;
2146 return $this->mData
;
2152 * @addtogroup Database
2154 * This allows us to distinguish a blob from a normal string and an array of strings
2158 function __construct($data) {
2159 $this->mData
= $data;
2162 return $this->mData
;
2168 * @addtogroup Database
2171 private $name, $tablename, $default, $max_length, $nullable,
2172 $is_pk, $is_unique, $is_key, $type;
2173 function __construct ($info) {
2174 $this->name
= $info->name
;
2175 $this->tablename
= $info->table
;
2176 $this->default = $info->def
;
2177 $this->max_length
= $info->max_length
;
2178 $this->nullable
= !$info->not_null
;
2179 $this->is_pk
= $info->primary_key
;
2180 $this->is_unique
= $info->unique_key
;
2181 $this->is_multiple
= $info->multiple_key
;
2182 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2183 $this->type
= $info->type
;
2190 function tableName() {
2191 return $this->tableName
;
2194 function defaultValue() {
2195 return $this->default;
2198 function maxLength() {
2199 return $this->max_length
;
2202 function nullable() {
2203 return $this->nullable
;
2207 return $this->is_key
;
2210 function isMultipleKey() {
2211 return $this->is_multiple
;
2219 /******************************************************************************
2221 *****************************************************************************/
2224 * Database error base class
2225 * @addtogroup Database
2227 class DBError
extends MWException
{
2231 * Construct a database error
2232 * @param Database $db The database object which threw the error
2233 * @param string $error A simple error message to be used for debugging
2235 function __construct( Database
&$db, $error ) {
2237 parent
::__construct( $error );
2242 * @addtogroup Database
2244 class DBConnectionError
extends DBError
{
2247 function __construct( Database
&$db, $error = 'unknown error' ) {
2248 $msg = 'DB connection error';
2249 if ( trim( $error ) != '' ) {
2252 $this->error
= $error;
2253 parent
::__construct( $db, $msg );
2256 function useOutputPage() {
2257 // Not likely to work
2261 function useMessageCache() {
2262 // Not likely to work
2266 function getText() {
2267 return $this->getMessage() . "\n";
2270 function getLogMessage() {
2271 # Don't send to the exception log
2275 function getPageTitle() {
2277 return "$wgSitename has a problem";
2280 function getHTML() {
2281 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2282 global $wgSitename, $wgServer, $wgMessageCache;
2284 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2285 # Hard coding strings instead.
2287 $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>";
2288 $mainpage = 'Main Page';
2289 $searchdisabled = <<<EOT
2290 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2291 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2295 <!-- SiteSearch Google -->
2296 <FORM method=GET action=\"http://www.google.com/search\">
2297 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2298 <A HREF=\"http://www.google.com/\">
2299 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2300 border=\"0\" ALT=\"Google\"></A>
2303 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2304 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2306 <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 />
2307 <input type='hidden' name='ie' value='$2'>
2308 <input type='hidden' name='oe' value='$2'>
2312 <!-- SiteSearch Google -->";
2313 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2315 # No database access
2316 if ( is_object( $wgMessageCache ) ) {
2317 $wgMessageCache->disable();
2320 if ( trim( $this->error
) == '' ) {
2321 $this->error
= $this->db
->getProperty('mServer');
2324 $text = str_replace( '$1', $this->error
, $noconnect );
2325 $text .= wfGetSiteNotice();
2327 if($wgUseFileCache) {
2332 $t = Title
::newFromURL( $title );
2333 } elseif (@/**/$_REQUEST['search']) {
2334 $search = $_REQUEST['search'];
2335 return $searchdisabled .
2336 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2337 $wgInputEncoding ), $googlesearch );
2339 $t = Title
::newFromText( $mainpage );
2343 $cache = new HTMLFileCache( $t );
2344 if( $cache->isFileCached() ) {
2345 // @todo, FIXME: $msg is not defined on the next line.
2346 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2347 $cachederror . "</b></p>\n";
2349 $tag = '<div id="article">';
2350 $text = str_replace(
2353 $cache->fetchPageText() );
2362 * @addtogroup Database
2364 class DBQueryError
extends DBError
{
2365 public $error, $errno, $sql, $fname;
2367 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2368 $message = "A database error has occurred\n" .
2370 "Function: $fname\n" .
2371 "Error: $errno $error\n";
2373 parent
::__construct( $db, $message );
2374 $this->error
= $error;
2375 $this->errno
= $errno;
2377 $this->fname
= $fname;
2380 function getText() {
2381 if ( $this->useMessageCache() ) {
2382 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2383 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2385 return $this->getMessage();
2390 global $wgShowSQLErrors;
2391 if( !$wgShowSQLErrors ) {
2392 return $this->msg( 'sqlhidden', 'SQL hidden' );
2398 function getLogMessage() {
2399 # Don't send to the exception log
2403 function getPageTitle() {
2404 return $this->msg( 'databaseerror', 'Database error' );
2407 function getHTML() {
2408 if ( $this->useMessageCache() ) {
2409 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2410 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2412 return nl2br( htmlspecialchars( $this->getMessage() ) );
2418 * @addtogroup Database
2420 class DBUnexpectedError
extends DBError
{}
2424 * Result wrapper for grabbing data queried by someone else
2425 * @addtogroup Database
2427 class ResultWrapper
implements Iterator
{
2428 var $db, $result, $pos = 0, $currentRow = null;
2431 * Create a new result object from a result resource and a Database object
2433 function ResultWrapper( $database, $result ) {
2434 $this->db
= $database;
2435 if ( $result instanceof ResultWrapper
) {
2436 $this->result
= $result->result
;
2438 $this->result
= $result;
2443 * Get the number of rows in a result object
2445 function numRows() {
2446 return $this->db
->numRows( $this->result
);
2450 * Fetch the next row from the given result object, in object form.
2451 * Fields can be retrieved with $row->fieldname, with fields acting like
2454 * @param $res SQL result object as returned from Database::query(), etc.
2455 * @return MySQL row object
2456 * @throws DBUnexpectedError Thrown if the database returns an error
2458 function fetchObject() {
2459 return $this->db
->fetchObject( $this->result
);
2463 * Fetch the next row from the given result object, in associative array
2464 * form. Fields are retrieved with $row['fieldname'].
2466 * @param $res SQL result object as returned from Database::query(), etc.
2467 * @return MySQL row object
2468 * @throws DBUnexpectedError Thrown if the database returns an error
2470 function fetchRow() {
2471 return $this->db
->fetchRow( $this->result
);
2475 * Free a result object
2478 $this->db
->freeResult( $this->result
);
2479 unset( $this->result
);
2484 * Change the position of the cursor in a result object
2485 * See mysql_data_seek()
2487 function seek( $row ) {
2488 $this->db
->dataSeek( $this->result
, $row );
2491 /*********************
2492 * Iterator functions
2493 * Note that using these in combination with the non-iterator functions
2494 * above may cause rows to be skipped or repeated.
2498 if ($this->numRows()) {
2499 $this->db
->dataSeek($this->result
, 0);
2502 $this->currentRow
= null;
2505 function current() {
2506 if ( is_null( $this->currentRow
) ) {
2509 return $this->currentRow
;
2518 $this->currentRow
= $this->fetchObject();
2519 return $this->currentRow
;
2523 return $this->current() !== false;
2527 class MySQLMasterPos
{
2530 function __construct( $file, $pos ) {
2531 $this->file
= $file;
2535 function __toString() {
2536 return "{$this->file}/{$this->pos}";