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 $server = 'localhost'; debugging_code_left_in();
303 # Test for missing mysql.so
304 # First try to load it
305 if (!@extension_loaded
('mysql')) {
310 # Otherwise we get a suppressed fatal error, which is very hard to track down
311 if ( !function_exists( 'mysql_connect' ) ) {
312 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
316 $this->mServer
= $server;
317 $this->mUser
= $user;
318 $this->mPassword
= $password;
319 $this->mDBname
= $dbName;
323 wfProfileIn("dbconnect-$server");
325 # Try to connect up to three times
326 # The kernel's default SYN retransmission period is far too slow for us,
327 # so we use a short timeout plus a manual retry.
328 $this->mConn
= false;
330 for ( $i = 0; $i < $max && !$this->mConn
; $i++
) {
334 if ( $this->mFlags
& DBO_PERSISTENT
) {
335 @/**/$this->mConn
= mysql_pconnect( $server, $user, $password );
337 # Create a new connection...
338 @/**/$this->mConn
= mysql_connect( $server, $user, $password, true );
340 if ($this->mConn
=== false) {
342 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
346 wfProfileOut("dbconnect-$server");
348 if ( $dbName != '' ) {
349 if ( $this->mConn
!== false ) {
350 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
352 $error = "Error selecting database $dbName on server {$this->mServer} " .
353 "from client host {$wguname['nodename']}\n";
354 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
358 wfDebug( "DB connection error\n" );
359 wfDebug( "Server: $server, User: $user, Password: " .
360 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
365 $success = (bool)$this->mConn
;
369 $version = $this->getServerVersion();
370 if ( version_compare( $version, '4.1' ) >= 0 ) {
371 // Tell the server we're communicating with it in UTF-8.
372 // This may engage various charset conversions.
375 $this->query( 'SET NAMES utf8', __METHOD__
);
377 // Turn off strict mode
378 $this->query( "SET sql_mode = ''", __METHOD__
);
381 // Turn off strict mode if it is on
383 $this->reportConnectionError();
386 $this->mOpened
= $success;
387 wfProfileOut( __METHOD__
);
393 * Closes a database connection.
394 * if it is open : commits any open transactions
396 * @return bool operation success. true if already closed.
400 $this->mOpened
= false;
401 if ( $this->mConn
) {
402 if ( $this->trxLevel() ) {
403 $this->immediateCommit();
405 return mysql_close( $this->mConn
);
412 * @param string $error fallback error message, used if none is given by MySQL
414 function reportConnectionError( $error = 'Unknown error' ) {
415 $myError = $this->lastError();
420 if ( $this->mFailFunction
) {
421 # Legacy error handling method
422 if ( !is_int( $this->mFailFunction
) ) {
423 $ff = $this->mFailFunction
;
424 $ff( $this, $error );
428 wfLogDBError( "Connection error: $error\n" );
429 throw new DBConnectionError( $this, $error );
434 * Usually aborts on failure. If errors are explicitly ignored, returns success.
436 * @param $sql String: SQL query
437 * @param $fname String: Name of the calling function, for profiling/SHOW PROCESSLIST
438 * comment (you can use __METHOD__ or add some extra info)
439 * @param $tempIgnore Bool: Whether to avoid throwing an exception on errors...
440 * maybe best to catch the exception instead?
441 * @return true for a successful write query, ResultWrapper object for a successful read query,
442 * or false on failure if $tempIgnore set
443 * @throws DBQueryError Thrown when the database returns an error of any kind
445 public function query( $sql, $fname = '', $tempIgnore = false ) {
448 $isMaster = !is_null( $this->getLBInfo( 'master' ) );
449 if ( $wgProfiling ) {
450 # generalizeSQL will probably cut down the query to reasonable
451 # logging size most of the time. The substr is really just a sanity check.
453 # Who's been wasting my precious column space? -- TS
454 #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
457 $queryProf = 'query-m: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
458 $totalProf = 'Database::query-master';
460 $queryProf = 'query: ' . substr( Database
::generalizeSQL( $sql ), 0, 255 );
461 $totalProf = 'Database::query';
463 wfProfileIn( $totalProf );
464 wfProfileIn( $queryProf );
467 $this->mLastQuery
= $sql;
469 # Add a comment for easy SHOW PROCESSLIST interpretation
472 if ( is_object( $wgUser ) && !($wgUser instanceof StubObject
) ) {
473 $userName = $wgUser->getName();
474 if ( mb_strlen( $userName ) > 15 ) {
475 $userName = mb_substr( $userName, 0, 15 ) . '...';
477 $userName = str_replace( '/', '', $userName );
481 $commentedSql = preg_replace('/\s/', " /* $fname $userName */ ", $sql, 1);
483 # $commentedSql = $sql;
486 # If DBO_TRX is set, start a transaction
487 if ( ( $this->mFlags
& DBO_TRX
) && !$this->trxLevel() &&
488 $sql != 'BEGIN' && $sql != 'COMMIT' && $sql != 'ROLLBACK') {
489 // avoid establishing transactions for SHOW and SET statements too -
490 // that would delay transaction initializations to once connection
491 // is really used by application
492 $sqlstart = substr($sql,0,10); // very much worth it, benchmark certified(tm)
493 if (strpos($sqlstart,"SHOW ")!==0 and strpos($sqlstart,"SET ")!==0)
497 if ( $this->debug() ) {
498 $sqlx = substr( $commentedSql, 0, 500 );
499 $sqlx = strtr( $sqlx, "\t\n", ' ' );
501 wfDebug( "SQL-master: $sqlx\n" );
503 wfDebug( "SQL: $sqlx\n" );
507 # Do the query and handle errors
508 $ret = $this->doQuery( $commentedSql );
510 # Try reconnecting if the connection was lost
511 if ( false === $ret && ( $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006 ) ) {
512 # Transaction is gone, like it or not
513 $this->mTrxLevel
= 0;
514 wfDebug( "Connection lost, reconnecting...\n" );
515 if ( $this->ping() ) {
516 wfDebug( "Reconnected\n" );
517 $sqlx = substr( $commentedSql, 0, 500 );
518 $sqlx = strtr( $sqlx, "\t\n", ' ' );
519 global $wgRequestTime;
520 $elapsed = round( microtime(true) - $wgRequestTime, 3 );
521 wfLogDBError( "Connection lost and reconnected after {$elapsed}s, query: $sqlx\n" );
522 $ret = $this->doQuery( $commentedSql );
524 wfDebug( "Failed\n" );
528 if ( false === $ret ) {
529 $this->reportQueryError( $this->lastError(), $this->lastErrno(), $sql, $fname, $tempIgnore );
532 if ( $wgProfiling ) {
533 wfProfileOut( $queryProf );
534 wfProfileOut( $totalProf );
536 return $this->resultObject( $ret );
540 * The DBMS-dependent part of query()
541 * @param $sql String: SQL query.
542 * @return Result object to feed to fetchObject, fetchRow, ...; or false on failure
545 /*private*/ function doQuery( $sql ) {
546 if( $this->bufferResults() ) {
547 $ret = mysql_query( $sql, $this->mConn
);
549 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
558 * @param string $fname
559 * @param bool $tempIgnore
561 function reportQueryError( $error, $errno, $sql, $fname, $tempIgnore = false ) {
562 global $wgCommandLineMode;
563 # Ignore errors during error handling to avoid infinite recursion
564 $ignore = $this->ignoreErrors( true );
565 ++
$this->mErrorCount
;
567 if( $ignore ||
$tempIgnore ) {
568 wfDebug("SQL ERROR (ignored): $error\n");
569 $this->ignoreErrors( $ignore );
571 $sql1line = str_replace( "\n", "\\n", $sql );
572 wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
573 wfDebug("SQL ERROR: " . $error . "\n");
574 throw new DBQueryError( $this, $error, $errno, $sql, $fname );
580 * Intended to be compatible with the PEAR::DB wrapper functions.
581 * http://pear.php.net/manual/en/package.database.db.intro-execute.php
583 * ? = scalar value, quoted as necessary
584 * ! = raw SQL bit (a function for instance)
585 * & = filename; reads the file and inserts as a blob
586 * (we don't use this though...)
588 function prepare( $sql, $func = 'Database::prepare' ) {
589 /* MySQL doesn't support prepared statements (yet), so just
590 pack up the query for reference. We'll manually replace
592 return array( 'query' => $sql, 'func' => $func );
595 function freePrepared( $prepared ) {
596 /* No-op for MySQL */
600 * Execute a prepared query with the various arguments
601 * @param string $prepared the prepared sql
602 * @param mixed $args Either an array here, or put scalars as varargs
604 function execute( $prepared, $args = null ) {
605 if( !is_array( $args ) ) {
607 $args = func_get_args();
608 array_shift( $args );
610 $sql = $this->fillPrepared( $prepared['query'], $args );
611 return $this->query( $sql, $prepared['func'] );
615 * Prepare & execute an SQL statement, quoting and inserting arguments
616 * in the appropriate places.
617 * @param string $query
618 * @param string $args ...
620 function safeQuery( $query, $args = null ) {
621 $prepared = $this->prepare( $query, 'Database::safeQuery' );
622 if( !is_array( $args ) ) {
624 $args = func_get_args();
625 array_shift( $args );
627 $retval = $this->execute( $prepared, $args );
628 $this->freePrepared( $prepared );
633 * For faking prepared SQL statements on DBs that don't support
635 * @param string $preparedSql - a 'preparable' SQL statement
636 * @param array $args - array of arguments to fill it with
637 * @return string executable SQL
639 function fillPrepared( $preparedQuery, $args ) {
641 $this->preparedArgs
=& $args;
642 return preg_replace_callback( '/(\\\\[?!&]|[?!&])/',
643 array( &$this, 'fillPreparedArg' ), $preparedQuery );
647 * preg_callback func for fillPrepared()
648 * The arguments should be in $this->preparedArgs and must not be touched
649 * while we're doing this.
651 * @param array $matches
655 function fillPreparedArg( $matches ) {
656 switch( $matches[1] ) {
657 case '\\?': return '?';
658 case '\\!': return '!';
659 case '\\&': return '&';
661 list( /* $n */ , $arg ) = each( $this->preparedArgs
);
662 switch( $matches[1] ) {
663 case '?': return $this->addQuotes( $arg );
664 case '!': return $arg;
666 # return $this->addQuotes( file_get_contents( $arg ) );
667 throw new DBUnexpectedError( $this, '& mode is not implemented. If it\'s really needed, uncomment the line above.' );
669 throw new DBUnexpectedError( $this, 'Received invalid match. This should never happen!' );
674 * @param mixed $res A SQL result
677 * Free a result object
679 function freeResult( $res ) {
680 if ( $res instanceof ResultWrapper
) {
683 if ( !@/**/mysql_free_result( $res ) ) {
684 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
689 * Fetch the next row from the given result object, in object form.
690 * Fields can be retrieved with $row->fieldname, with fields acting like
693 * @param $res SQL result object as returned from Database::query(), etc.
694 * @return MySQL row object
695 * @throws DBUnexpectedError Thrown if the database returns an error
697 function fetchObject( $res ) {
698 if ( $res instanceof ResultWrapper
) {
701 @/**/$row = mysql_fetch_object( $res );
702 if( $this->lastErrno() ) {
703 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
709 * Fetch the next row from the given result object, in associative array
710 * form. Fields are retrieved with $row['fieldname'].
712 * @param $res SQL result object as returned from Database::query(), etc.
713 * @return MySQL row object
714 * @throws DBUnexpectedError Thrown if the database returns an error
716 function fetchRow( $res ) {
717 if ( $res instanceof ResultWrapper
) {
720 @/**/$row = mysql_fetch_array( $res );
721 if ( $this->lastErrno() ) {
722 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
728 * Get the number of rows in a result object
730 function numRows( $res ) {
731 if ( $res instanceof ResultWrapper
) {
734 @/**/$n = mysql_num_rows( $res );
735 if( $this->lastErrno() ) {
736 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
742 * Get the number of fields in a result object
743 * See documentation for mysql_num_fields()
745 function numFields( $res ) {
746 if ( $res instanceof ResultWrapper
) {
749 return mysql_num_fields( $res );
753 * Get a field name in a result object
754 * See documentation for mysql_field_name():
755 * http://www.php.net/mysql_field_name
757 function fieldName( $res, $n ) {
758 if ( $res instanceof ResultWrapper
) {
761 return mysql_field_name( $res, $n );
765 * Get the inserted value of an auto-increment row
767 * The value inserted should be fetched from nextSequenceValue()
770 * $id = $dbw->nextSequenceValue('page_page_id_seq');
771 * $dbw->insert('page',array('page_id' => $id));
772 * $id = $dbw->insertId();
774 function insertId() { return mysql_insert_id( $this->mConn
); }
777 * Change the position of the cursor in a result object
778 * See mysql_data_seek()
780 function dataSeek( $res, $row ) {
781 if ( $res instanceof ResultWrapper
) {
784 return mysql_data_seek( $res, $row );
788 * Get the last error number
791 function lastErrno() {
792 if ( $this->mConn
) {
793 return mysql_errno( $this->mConn
);
795 return mysql_errno();
800 * Get a description of the last error
801 * See mysql_error() for more details
803 function lastError() {
804 if ( $this->mConn
) {
805 # Even if it's non-zero, it can still be invalid
806 wfSuppressWarnings();
807 $error = mysql_error( $this->mConn
);
809 $error = mysql_error();
813 $error = mysql_error();
816 $error .= ' (' . $this->mServer
. ')';
821 * Get the number of rows affected by the last write query
822 * See mysql_affected_rows() for more details
824 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
825 /**#@-*/ // end of template : @param $result
828 * Simple UPDATE wrapper
829 * Usually aborts on failure
830 * If errors are explicitly ignored, returns success
832 * This function exists for historical reasons, Database::update() has a more standard
833 * calling convention and feature set
835 function set( $table, $var, $value, $cond, $fname = 'Database::set' )
837 $table = $this->tableName( $table );
838 $sql = "UPDATE $table SET $var = '" .
839 $this->strencode( $value ) . "' WHERE ($cond)";
840 return (bool)$this->query( $sql, $fname );
844 * Simple SELECT wrapper, returns a single field, input must be encoded
845 * Usually aborts on failure
846 * If errors are explicitly ignored, returns FALSE on failure
848 function selectField( $table, $var, $cond='', $fname = 'Database::selectField', $options = array() ) {
849 if ( !is_array( $options ) ) {
850 $options = array( $options );
852 $options['LIMIT'] = 1;
854 $res = $this->select( $table, $var, $cond, $fname, $options );
855 if ( $res === false ||
!$this->numRows( $res ) ) {
858 $row = $this->fetchRow( $res );
859 if ( $row !== false ) {
860 $this->freeResult( $res );
868 * Returns an optional USE INDEX clause to go after the table, and a
869 * string to go at the end of the query
873 * @param array $options an associative array of options to be turned into
874 * an SQL query, valid keys are listed in the function.
877 function makeSelectOptions( $options ) {
878 $preLimitTail = $postLimitTail = '';
881 $noKeyOptions = array();
882 foreach ( $options as $key => $option ) {
883 if ( is_numeric( $key ) ) {
884 $noKeyOptions[$option] = true;
888 if ( isset( $options['GROUP BY'] ) ) $preLimitTail .= " GROUP BY {$options['GROUP BY']}";
889 if ( isset( $options['HAVING'] ) ) $preLimitTail .= " HAVING {$options['HAVING']}";
890 if ( isset( $options['ORDER BY'] ) ) $preLimitTail .= " ORDER BY {$options['ORDER BY']}";
892 //if (isset($options['LIMIT'])) {
893 // $tailOpts .= $this->limitResult('', $options['LIMIT'],
894 // isset($options['OFFSET']) ? $options['OFFSET']
898 if ( isset( $noKeyOptions['FOR UPDATE'] ) ) $postLimitTail .= ' FOR UPDATE';
899 if ( isset( $noKeyOptions['LOCK IN SHARE MODE'] ) ) $postLimitTail .= ' LOCK IN SHARE MODE';
900 if ( isset( $noKeyOptions['DISTINCT'] ) ||
isset( $noKeyOptions['DISTINCTROW'] ) ) $startOpts .= 'DISTINCT';
902 # Various MySQL extensions
903 if ( isset( $noKeyOptions['STRAIGHT_JOIN'] ) ) $startOpts .= ' /*! STRAIGHT_JOIN */';
904 if ( isset( $noKeyOptions['HIGH_PRIORITY'] ) ) $startOpts .= ' HIGH_PRIORITY';
905 if ( isset( $noKeyOptions['SQL_BIG_RESULT'] ) ) $startOpts .= ' SQL_BIG_RESULT';
906 if ( isset( $noKeyOptions['SQL_BUFFER_RESULT'] ) ) $startOpts .= ' SQL_BUFFER_RESULT';
907 if ( isset( $noKeyOptions['SQL_SMALL_RESULT'] ) ) $startOpts .= ' SQL_SMALL_RESULT';
908 if ( isset( $noKeyOptions['SQL_CALC_FOUND_ROWS'] ) ) $startOpts .= ' SQL_CALC_FOUND_ROWS';
909 if ( isset( $noKeyOptions['SQL_CACHE'] ) ) $startOpts .= ' SQL_CACHE';
910 if ( isset( $noKeyOptions['SQL_NO_CACHE'] ) ) $startOpts .= ' SQL_NO_CACHE';
912 if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
913 $useIndex = $this->useIndexClause( $options['USE INDEX'] );
918 return array( $startOpts, $useIndex, $preLimitTail, $postLimitTail );
924 * @param mixed $table Array or string, table name(s) (prefix auto-added)
925 * @param mixed $vars Array or string, field name(s) to be retrieved
926 * @param mixed $conds Array or string, condition(s) for WHERE
927 * @param string $fname Calling function name (use __METHOD__) for logs/profiling
928 * @param array $options Associative array of options (e.g. array('GROUP BY' => 'page_title')),
929 * see Database::makeSelectOptions code for list of supported stuff
930 * @return mixed Database result resource (feed to Database::fetchObject or whatever), or false on failure
932 function select( $table, $vars, $conds='', $fname = 'Database::select', $options = array() )
934 if( is_array( $vars ) ) {
935 $vars = implode( ',', $vars );
937 if( !is_array( $options ) ) {
938 $options = array( $options );
940 if( is_array( $table ) ) {
941 if ( isset( $options['USE INDEX'] ) && is_array( $options['USE INDEX'] ) )
942 $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
944 $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
945 } elseif ($table!='') {
946 if ($table{0}==' ') {
947 $from = ' FROM ' . $table;
949 $from = ' FROM ' . $this->tableName( $table );
955 list( $startOpts, $useIndex, $preLimitTail, $postLimitTail ) = $this->makeSelectOptions( $options );
957 if( !empty( $conds ) ) {
958 if ( is_array( $conds ) ) {
959 $conds = $this->makeList( $conds, LIST_AND
);
961 $sql = "SELECT $startOpts $vars $from $useIndex WHERE $conds $preLimitTail";
963 $sql = "SELECT $startOpts $vars $from $useIndex $preLimitTail";
966 if (isset($options['LIMIT']))
967 $sql = $this->limitResult($sql, $options['LIMIT'],
968 isset($options['OFFSET']) ?
$options['OFFSET'] : false);
969 $sql = "$sql $postLimitTail";
971 if (isset($options['EXPLAIN'])) {
972 $sql = 'EXPLAIN ' . $sql;
974 return $this->query( $sql, $fname );
978 * Single row SELECT wrapper
979 * Aborts or returns FALSE on error
981 * $vars: the selected variables
982 * $conds: a condition map, terms are ANDed together.
983 * Items with numeric keys are taken to be literal conditions
984 * Takes an array of selected variables, and a condition map, which is ANDed
985 * e.g: selectRow( "page", array( "page_id" ), array( "page_namespace" =>
986 * NS_MAIN, "page_title" => "Astronomy" ) ) would return an object where
987 * $obj- >page_id is the ID of the Astronomy article
989 * @todo migrate documentation to phpdocumentor format
991 function selectRow( $table, $vars, $conds, $fname = 'Database::selectRow', $options = array() ) {
992 $options['LIMIT'] = 1;
993 $res = $this->select( $table, $vars, $conds, $fname, $options );
994 if ( $res === false )
996 if ( !$this->numRows($res) ) {
997 $this->freeResult($res);
1000 $obj = $this->fetchObject( $res );
1001 $this->freeResult( $res );
1007 * Estimate rows in dataset
1008 * Returns estimated count, based on EXPLAIN output
1009 * Takes same arguments as Database::select()
1012 function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
1013 $options['EXPLAIN']=true;
1014 $res = $this->select ($table, $vars, $conds, $fname, $options );
1015 if ( $res === false )
1017 if (!$this->numRows($res)) {
1018 $this->freeResult($res);
1024 while( $plan = $this->fetchObject( $res ) ) {
1025 $rows *= ($plan->rows
> 0)?
$plan->rows
:1; // avoid resetting to zero
1028 $this->freeResult($res);
1034 * Removes most variables from an SQL query and replaces them with X or N for numbers.
1035 * It's only slightly flawed. Don't use for anything important.
1037 * @param string $sql A SQL Query
1040 static function generalizeSQL( $sql ) {
1041 # This does the same as the regexp below would do, but in such a way
1042 # as to avoid crashing php on some large strings.
1043 # $sql = preg_replace ( "/'([^\\\\']|\\\\.)*'|\"([^\\\\\"]|\\\\.)*\"/", "'X'", $sql);
1045 $sql = str_replace ( "\\\\", '', $sql);
1046 $sql = str_replace ( "\\'", '', $sql);
1047 $sql = str_replace ( "\\\"", '', $sql);
1048 $sql = preg_replace ("/'.*'/s", "'X'", $sql);
1049 $sql = preg_replace ('/".*"/s', "'X'", $sql);
1051 # All newlines, tabs, etc replaced by single space
1052 $sql = preg_replace ( '/\s+/', ' ', $sql);
1055 $sql = preg_replace ('/-?[0-9]+/s', 'N', $sql);
1061 * Determines whether a field exists in a table
1062 * Usually aborts on failure
1063 * If errors are explicitly ignored, returns NULL on failure
1065 function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
1066 $table = $this->tableName( $table );
1067 $res = $this->query( 'DESCRIBE '.$table, $fname );
1074 while ( $row = $this->fetchObject( $res ) ) {
1075 if ( $row->Field
== $field ) {
1084 * Determines whether an index exists
1085 * Usually aborts on failure
1086 * If errors are explicitly ignored, returns NULL on failure
1088 function indexExists( $table, $index, $fname = 'Database::indexExists' ) {
1089 $info = $this->indexInfo( $table, $index, $fname );
1090 if ( is_null( $info ) ) {
1093 return $info !== false;
1099 * Get information about an index into an object
1100 * Returns false if the index does not exist
1102 function indexInfo( $table, $index, $fname = 'Database::indexInfo' ) {
1103 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
1104 # SHOW INDEX should work for 3.x and up:
1105 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
1106 $table = $this->tableName( $table );
1107 $sql = 'SHOW INDEX FROM '.$table;
1108 $res = $this->query( $sql, $fname );
1114 while ( $row = $this->fetchObject( $res ) ) {
1115 if ( $row->Key_name
== $index ) {
1119 $this->freeResult($res);
1121 return empty($result) ?
false : $result;
1125 * Query whether a given table exists
1127 function tableExists( $table ) {
1128 $table = $this->tableName( $table );
1129 $old = $this->ignoreErrors( true );
1130 $res = $this->query( "SELECT 1 FROM $table LIMIT 1" );
1131 $this->ignoreErrors( $old );
1133 $this->freeResult( $res );
1141 * mysql_fetch_field() wrapper
1142 * Returns false if the field doesn't exist
1147 function fieldInfo( $table, $field ) {
1148 $table = $this->tableName( $table );
1149 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
1150 $n = mysql_num_fields( $res->result
);
1151 for( $i = 0; $i < $n; $i++
) {
1152 $meta = mysql_fetch_field( $res->result
, $i );
1153 if( $field == $meta->name
) {
1154 return new MySQLField($meta);
1161 * mysql_field_type() wrapper
1163 function fieldType( $res, $index ) {
1164 if ( $res instanceof ResultWrapper
) {
1165 $res = $res->result
;
1167 return mysql_field_type( $res, $index );
1171 * Determines if a given index is unique
1173 function indexUnique( $table, $index ) {
1174 $indexInfo = $this->indexInfo( $table, $index );
1175 if ( !$indexInfo ) {
1178 return !$indexInfo[0]->Non_unique
;
1182 * INSERT wrapper, inserts an array into a table
1184 * $a may be a single associative array, or an array of these with numeric keys, for
1187 * Usually aborts on failure
1188 * If errors are explicitly ignored, returns success
1190 function insert( $table, $a, $fname = 'Database::insert', $options = array() ) {
1191 # No rows to insert, easy just return now
1192 if ( !count( $a ) ) {
1196 $table = $this->tableName( $table );
1197 if ( !is_array( $options ) ) {
1198 $options = array( $options );
1200 if ( isset( $a[0] ) && is_array( $a[0] ) ) {
1202 $keys = array_keys( $a[0] );
1205 $keys = array_keys( $a );
1208 $sql = 'INSERT ' . implode( ' ', $options ) .
1209 " INTO $table (" . implode( ',', $keys ) . ') VALUES ';
1213 foreach ( $a as $row ) {
1219 $sql .= '(' . $this->makeList( $row ) . ')';
1222 $sql .= '(' . $this->makeList( $a ) . ')';
1224 return (bool)$this->query( $sql, $fname );
1228 * Make UPDATE options for the Database::update function
1231 * @param array $options The options passed to Database::update
1234 function makeUpdateOptions( $options ) {
1235 if( !is_array( $options ) ) {
1236 $options = array( $options );
1239 if ( in_array( 'LOW_PRIORITY', $options ) )
1240 $opts[] = $this->lowPriorityOption();
1241 if ( in_array( 'IGNORE', $options ) )
1243 return implode(' ', $opts);
1247 * UPDATE wrapper, takes a condition array and a SET array
1249 * @param string $table The table to UPDATE
1250 * @param array $values An array of values to SET
1251 * @param array $conds An array of conditions (WHERE). Use '*' to update all rows.
1252 * @param string $fname The Class::Function calling this function
1254 * @param array $options An array of UPDATE options, can be one or
1255 * more of IGNORE, LOW_PRIORITY
1258 function update( $table, $values, $conds, $fname = 'Database::update', $options = array() ) {
1259 $table = $this->tableName( $table );
1260 $opts = $this->makeUpdateOptions( $options );
1261 $sql = "UPDATE $opts $table SET " . $this->makeList( $values, LIST_SET
);
1262 if ( $conds != '*' ) {
1263 $sql .= " WHERE " . $this->makeList( $conds, LIST_AND
);
1265 return $this->query( $sql, $fname );
1269 * Makes an encoded list of strings from an array
1271 * LIST_COMMA - comma separated, no field names
1272 * LIST_AND - ANDed WHERE clause (without the WHERE)
1273 * LIST_OR - ORed WHERE clause (without the WHERE)
1274 * LIST_SET - comma separated with field names, like a SET clause
1275 * LIST_NAMES - comma separated field names
1277 function makeList( $a, $mode = LIST_COMMA
) {
1278 if ( !is_array( $a ) ) {
1279 throw new DBUnexpectedError( $this, 'Database::makeList called with incorrect parameters' );
1284 foreach ( $a as $field => $value ) {
1286 if ( $mode == LIST_AND
) {
1288 } elseif($mode == LIST_OR
) {
1296 if ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_numeric( $field ) ) {
1297 $list .= "($value)";
1298 } elseif ( ($mode == LIST_SET
) && is_numeric( $field ) ) {
1300 } elseif ( ($mode == LIST_AND ||
$mode == LIST_OR
) && is_array($value) ) {
1301 if( count( $value ) == 0 ) {
1302 throw new MWException( __METHOD__
.': empty input' );
1303 } elseif( count( $value ) == 1 ) {
1304 // Special-case single values, as IN isn't terribly efficient
1305 // Don't necessarily assume the single key is 0; we don't
1306 // enforce linear numeric ordering on other arrays here.
1307 $value = array_values( $value );
1308 $list .= $field." = ".$this->addQuotes( $value[0] );
1310 $list .= $field." IN (".$this->makeList($value).") ";
1312 } elseif( is_null($value) ) {
1313 if ( $mode == LIST_AND ||
$mode == LIST_OR
) {
1314 $list .= "$field IS ";
1315 } elseif ( $mode == LIST_SET
) {
1316 $list .= "$field = ";
1320 if ( $mode == LIST_AND ||
$mode == LIST_OR ||
$mode == LIST_SET
) {
1321 $list .= "$field = ";
1323 $list .= $mode == LIST_NAMES ?
$value : $this->addQuotes( $value );
1330 * Change the current database
1332 function selectDB( $db ) {
1333 $this->mDBname
= $db;
1334 return mysql_select_db( $db, $this->mConn
);
1338 * Get the current DB name
1340 function getDBname() {
1341 return $this->mDBname
;
1345 * Get the server hostname or IP address
1347 function getServer() {
1348 return $this->mServer
;
1352 * Format a table name ready for use in constructing an SQL query
1354 * This does two important things: it quotes table names which as necessary,
1355 * and it adds a table prefix if there is one.
1357 * All functions of this object which require a table name call this function
1358 * themselves. Pass the canonical name to such functions. This is only needed
1359 * when calling query() directly.
1361 * @param string $name database table name
1363 function tableName( $name ) {
1365 # Skip quoted literals
1366 if ( $name{0} != '`' ) {
1367 if ( $this->mTablePrefix
!== '' && strpos( $name, '.' ) === false ) {
1368 $name = "{$this->mTablePrefix}$name";
1370 if ( isset( $wgSharedDB ) && "{$this->mTablePrefix}user" == $name ) {
1371 $name = "`$wgSharedDB`.`$name`";
1381 * Fetch a number of table names into an array
1382 * This is handy when you need to construct SQL for joins
1385 * extract($dbr->tableNames('user','watchlist'));
1386 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1387 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1389 public function tableNames() {
1390 $inArray = func_get_args();
1392 foreach ( $inArray as $name ) {
1393 $retVal[$name] = $this->tableName( $name );
1399 * Fetch a number of table names into an zero-indexed numerical array
1400 * This is handy when you need to construct SQL for joins
1403 * list( $user, $watchlist ) = $dbr->tableNamesN('user','watchlist');
1404 * $sql = "SELECT wl_namespace,wl_title FROM $watchlist,$user
1405 * WHERE wl_user=user_id AND wl_user=$nameWithQuotes";
1407 public function tableNamesN() {
1408 $inArray = func_get_args();
1410 foreach ( $inArray as $name ) {
1411 $retVal[] = $this->tableName( $name );
1419 function tableNamesWithUseIndex( $tables, $use_index ) {
1422 foreach ( $tables as $table )
1423 if ( @$use_index[$table] !== null )
1424 $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
1426 $ret[] = $this->tableName( $table );
1428 return implode( ',', $ret );
1432 * Wrapper for addslashes()
1433 * @param string $s String to be slashed.
1434 * @return string slashed string.
1436 function strencode( $s ) {
1437 return mysql_real_escape_string( $s, $this->mConn
);
1441 * If it's a string, adds quotes and backslashes
1442 * Otherwise returns as-is
1444 function addQuotes( $s ) {
1445 if ( is_null( $s ) ) {
1448 # This will also quote numeric values. This should be harmless,
1449 # and protects against weird problems that occur when they really
1450 # _are_ strings such as article titles and string->number->string
1451 # conversion is not 1:1.
1452 return "'" . $this->strencode( $s ) . "'";
1457 * Escape string for safe LIKE usage
1459 function escapeLike( $s ) {
1460 $s=$this->strencode( $s );
1461 $s=str_replace(array('%','_'),array('\%','\_'),$s);
1466 * Returns an appropriately quoted sequence value for inserting a new row.
1467 * MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
1468 * subclass will return an integer, and save the value for insertId()
1470 function nextSequenceValue( $seqName ) {
1476 * PostgreSQL doesn't have them and returns ""
1478 function useIndexClause( $index ) {
1479 return "FORCE INDEX ($index)";
1483 * REPLACE query wrapper
1484 * PostgreSQL simulates this with a DELETE followed by INSERT
1485 * $row is the row to insert, an associative array
1486 * $uniqueIndexes is an array of indexes. Each element may be either a
1487 * field name or an array of field names
1489 * It may be more efficient to leave off unique indexes which are unlikely to collide.
1490 * However if you do this, you run the risk of encountering errors which wouldn't have
1493 * @todo migrate comment to phodocumentor format
1495 function replace( $table, $uniqueIndexes, $rows, $fname = 'Database::replace' ) {
1496 $table = $this->tableName( $table );
1499 if ( !is_array( reset( $rows ) ) ) {
1500 $rows = array( $rows );
1503 $sql = "REPLACE INTO $table (" . implode( ',', array_keys( $rows[0] ) ) .') VALUES ';
1505 foreach ( $rows as $row ) {
1511 $sql .= '(' . $this->makeList( $row ) . ')';
1513 return $this->query( $sql, $fname );
1517 * DELETE where the condition is a join
1518 * MySQL does this with a multi-table DELETE syntax, PostgreSQL does it with sub-selects
1520 * For safety, an empty $conds will not delete everything. If you want to delete all rows where the
1521 * join condition matches, set $conds='*'
1523 * DO NOT put the join condition in $conds
1525 * @param string $delTable The table to delete from.
1526 * @param string $joinTable The other table.
1527 * @param string $delVar The variable to join on, in the first table.
1528 * @param string $joinVar The variable to join on, in the second table.
1529 * @param array $conds Condition array of field names mapped to variables, ANDed together in the WHERE clause
1531 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'Database::deleteJoin' ) {
1533 throw new DBUnexpectedError( $this, 'Database::deleteJoin() called with empty $conds' );
1536 $delTable = $this->tableName( $delTable );
1537 $joinTable = $this->tableName( $joinTable );
1538 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
1539 if ( $conds != '*' ) {
1540 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
1543 return $this->query( $sql, $fname );
1547 * Returns the size of a text field, or -1 for "unlimited"
1549 function textFieldSize( $table, $field ) {
1550 $table = $this->tableName( $table );
1551 $sql = "SHOW COLUMNS FROM $table LIKE \"$field\";";
1552 $res = $this->query( $sql, 'Database::textFieldSize' );
1553 $row = $this->fetchObject( $res );
1554 $this->freeResult( $res );
1557 if ( preg_match( '/\((.*)\)/', $row->Type
, $m ) ) {
1566 * @return string Returns the text of the low priority option if it is supported, or a blank string otherwise
1568 function lowPriorityOption() {
1569 return 'LOW_PRIORITY';
1573 * DELETE query wrapper
1575 * Use $conds == "*" to delete all rows
1577 function delete( $table, $conds, $fname = 'Database::delete' ) {
1579 throw new DBUnexpectedError( $this, 'Database::delete() called with no conditions' );
1581 $table = $this->tableName( $table );
1582 $sql = "DELETE FROM $table";
1583 if ( $conds != '*' ) {
1584 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1586 return $this->query( $sql, $fname );
1590 * INSERT SELECT wrapper
1591 * $varMap must be an associative array of the form array( 'dest1' => 'source1', ...)
1592 * Source items may be literals rather than field names, but strings should be quoted with Database::addQuotes()
1593 * $conds may be "*" to copy the whole table
1594 * srcTable may be an array of tables.
1596 function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
1597 $insertOptions = array(), $selectOptions = array() )
1599 $destTable = $this->tableName( $destTable );
1600 if ( is_array( $insertOptions ) ) {
1601 $insertOptions = implode( ' ', $insertOptions );
1603 if( !is_array( $selectOptions ) ) {
1604 $selectOptions = array( $selectOptions );
1606 list( $startOpts, $useIndex, $tailOpts ) = $this->makeSelectOptions( $selectOptions );
1607 if( is_array( $srcTable ) ) {
1608 $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
1610 $srcTable = $this->tableName( $srcTable );
1612 $sql = "INSERT $insertOptions INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
1613 " SELECT $startOpts " . implode( ',', $varMap ) .
1614 " FROM $srcTable $useIndex ";
1615 if ( $conds != '*' ) {
1616 $sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND
);
1618 $sql .= " $tailOpts";
1619 return $this->query( $sql, $fname );
1623 * Construct a LIMIT query with optional offset
1624 * This is used for query pages
1625 * $sql string SQL query we will append the limit too
1626 * $limit integer the SQL limit
1627 * $offset integer the SQL offset (default false)
1629 function limitResult($sql, $limit, $offset=false) {
1630 if( !is_numeric($limit) ) {
1631 throw new DBUnexpectedError( $this, "Invalid non-numeric limit passed to limitResult()\n" );
1633 return " $sql LIMIT "
1634 . ( (is_numeric($offset) && $offset != 0) ?
"{$offset}," : "" )
1637 function limitResultForUpdate($sql, $num) {
1638 return $this->limitResult($sql, $num, 0);
1642 * Returns an SQL expression for a simple conditional.
1645 * @param string $cond SQL expression which will result in a boolean value
1646 * @param string $trueVal SQL expression to return if true
1647 * @param string $falseVal SQL expression to return if false
1648 * @return string SQL fragment
1650 function conditional( $cond, $trueVal, $falseVal ) {
1651 return " IF($cond, $trueVal, $falseVal) ";
1655 * Determines if the last failure was due to a deadlock
1657 function wasDeadlock() {
1658 return $this->lastErrno() == 1213;
1662 * Perform a deadlock-prone transaction.
1664 * This function invokes a callback function to perform a set of write
1665 * queries. If a deadlock occurs during the processing, the transaction
1666 * will be rolled back and the callback function will be called again.
1669 * $dbw->deadlockLoop( callback, ... );
1671 * Extra arguments are passed through to the specified callback function.
1673 * Returns whatever the callback function returned on its successful,
1674 * iteration, or false on error, for example if the retry limit was
1677 function deadlockLoop() {
1678 $myFname = 'Database::deadlockLoop';
1681 $args = func_get_args();
1682 $function = array_shift( $args );
1683 $oldIgnore = $this->ignoreErrors( true );
1684 $tries = DEADLOCK_TRIES
;
1685 if ( is_array( $function ) ) {
1686 $fname = $function[0];
1691 $retVal = call_user_func_array( $function, $args );
1692 $error = $this->lastError();
1693 $errno = $this->lastErrno();
1694 $sql = $this->lastQuery();
1697 if ( $this->wasDeadlock() ) {
1699 usleep( mt_rand( DEADLOCK_DELAY_MIN
, DEADLOCK_DELAY_MAX
) );
1701 $this->reportQueryError( $error, $errno, $sql, $fname );
1704 } while( $this->wasDeadlock() && --$tries > 0 );
1705 $this->ignoreErrors( $oldIgnore );
1706 if ( $tries <= 0 ) {
1707 $this->query( 'ROLLBACK', $myFname );
1708 $this->reportQueryError( $error, $errno, $sql, $fname );
1711 $this->query( 'COMMIT', $myFname );
1717 * Do a SELECT MASTER_POS_WAIT()
1719 * @param string $file the binlog file
1720 * @param string $pos the binlog position
1721 * @param integer $timeout the maximum number of seconds to wait for synchronisation
1723 function masterPosWait( MySQLMasterPos
$pos, $timeout ) {
1724 $fname = 'Database::masterPosWait';
1725 wfProfileIn( $fname );
1727 # Commit any open transactions
1728 if ( $this->mTrxLevel
) {
1729 $this->immediateCommit();
1732 if ( !is_null( $this->mFakeSlaveLag
) ) {
1733 $wait = intval( ( $pos->pos
- microtime(true) +
$this->mFakeSlaveLag
) * 1e6
);
1734 if ( $wait > $timeout * 1e6
) {
1735 wfDebug( "Fake slave timed out waiting for $pos ($wait us)\n" );
1736 wfProfileOut( $fname );
1738 } elseif ( $wait > 0 ) {
1739 wfDebug( "Fake slave waiting $wait us\n" );
1741 wfProfileOut( $fname );
1744 wfDebug( "Fake slave up to date ($wait us)\n" );
1745 wfProfileOut( $fname );
1750 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
1751 $encFile = $this->addQuotes( $pos->file
);
1752 $encPos = intval( $pos->pos
);
1753 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
1754 $res = $this->doQuery( $sql );
1755 if ( $res && $row = $this->fetchRow( $res ) ) {
1756 $this->freeResult( $res );
1757 wfProfileOut( $fname );
1760 wfProfileOut( $fname );
1766 * Get the position of the master from SHOW SLAVE STATUS
1768 function getSlavePos() {
1769 if ( !is_null( $this->mFakeSlaveLag
) ) {
1770 $pos = new MySQLMasterPos( 'fake', microtime(true) - $this->mFakeSlaveLag
);
1771 wfDebug( __METHOD__
.": fake slave pos = $pos\n" );
1774 $res = $this->query( 'SHOW SLAVE STATUS', 'Database::getSlavePos' );
1775 $row = $this->fetchObject( $res );
1777 return new MySQLMasterPos( $row->Master_Log_File
, $row->Read_Master_Log_Pos
);
1784 * Get the position of the master from SHOW MASTER STATUS
1786 function getMasterPos() {
1787 if ( $this->mFakeMaster
) {
1788 return new MySQLMasterPos( 'fake', microtime( true ) );
1790 $res = $this->query( 'SHOW MASTER STATUS', 'Database::getMasterPos' );
1791 $row = $this->fetchObject( $res );
1793 return new MySQLMasterPos( $row->File
, $row->Position
);
1800 * Begin a transaction, committing any previously open transaction
1802 function begin( $fname = 'Database::begin' ) {
1803 $this->query( 'BEGIN', $fname );
1804 $this->mTrxLevel
= 1;
1810 function commit( $fname = 'Database::commit' ) {
1811 $this->query( 'COMMIT', $fname );
1812 $this->mTrxLevel
= 0;
1816 * Rollback a transaction.
1817 * No-op on non-transactional databases.
1819 function rollback( $fname = 'Database::rollback' ) {
1820 $this->query( 'ROLLBACK', $fname, true );
1821 $this->mTrxLevel
= 0;
1825 * Begin a transaction, committing any previously open transaction
1826 * @deprecated use begin()
1828 function immediateBegin( $fname = 'Database::immediateBegin' ) {
1833 * Commit transaction, if one is open
1834 * @deprecated use commit()
1836 function immediateCommit( $fname = 'Database::immediateCommit' ) {
1841 * Return MW-style timestamp used for MySQL schema
1843 function timestamp( $ts=0 ) {
1844 return wfTimestamp(TS_MW
,$ts);
1848 * Local database timestamp format or null
1850 function timestampOrNull( $ts = null ) {
1851 if( is_null( $ts ) ) {
1854 return $this->timestamp( $ts );
1861 function resultObject( $result ) {
1862 if( empty( $result ) ) {
1864 } elseif ( $result instanceof ResultWrapper
) {
1866 } elseif ( $result === true ) {
1867 // Successful write query
1870 return new ResultWrapper( $this, $result );
1875 * Return aggregated value alias
1877 function aggregateValue ($valuedata,$valuename='value') {
1882 * @return string wikitext of a link to the server software's web site
1884 function getSoftwareLink() {
1885 return "[http://www.mysql.com/ MySQL]";
1889 * @return string Version information from the database
1891 function getServerVersion() {
1892 return mysql_get_server_info( $this->mConn
);
1896 * Ping the server and try to reconnect if it there is no connection
1899 if( !function_exists( 'mysql_ping' ) ) {
1900 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
1903 $ping = mysql_ping( $this->mConn
);
1908 // Need to reconnect manually in MySQL client 5.0.13+
1909 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
1910 mysql_close( $this->mConn
);
1911 $this->mOpened
= false;
1912 $this->mConn
= false;
1913 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
1921 * At the moment, this will only work if the DB user has the PROCESS privilege
1924 if ( !is_null( $this->mFakeSlaveLag
) ) {
1925 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
1926 return $this->mFakeSlaveLag
;
1928 $res = $this->query( 'SHOW PROCESSLIST' );
1929 # Find slave SQL thread
1930 while ( $row = $this->fetchObject( $res ) ) {
1931 /* This should work for most situations - when default db
1932 * for thread is not specified, it had no events executed,
1933 * and therefore it doesn't know yet how lagged it is.
1935 * Relay log I/O thread does not select databases.
1937 if ( $row->User
== 'system user' &&
1938 $row->State
!= 'Waiting for master to send event' &&
1939 $row->State
!= 'Connecting to master' &&
1940 $row->State
!= 'Queueing master event to the relay log' &&
1941 $row->State
!= 'Waiting for master update' &&
1942 $row->State
!= 'Requesting binlog dump'
1944 # This is it, return the time (except -ve)
1945 if ( $row->Time
> 0x7fffffff ) {
1956 * Get status information from SHOW STATUS in an associative array
1958 function getStatus($which="%") {
1959 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
1961 while ( $row = $this->fetchObject( $res ) ) {
1962 $status[$row->Variable_name
] = $row->Value
;
1968 * Return the maximum number of items allowed in a list, or 0 for unlimited.
1970 function maxListLen() {
1974 function encodeBlob($b) {
1978 function decodeBlob($b) {
1983 * Override database's default connection timeout.
1984 * May be useful for very long batch queries such as
1985 * full-wiki dumps, where a single query reads out
1986 * over hours or days.
1987 * @param int $timeout in seconds
1989 public function setTimeout( $timeout ) {
1990 $this->query( "SET net_read_timeout=$timeout" );
1991 $this->query( "SET net_write_timeout=$timeout" );
1995 * Read and execute SQL commands from a file.
1996 * Returns true on success, error string on failure
1997 * @param string $filename File name to open
1998 * @param callback $lineCallback Optional function called before reading each line
1999 * @param callback $resultCallback Optional function called for each MySQL result
2001 function sourceFile( $filename, $lineCallback = false, $resultCallback = false ) {
2002 $fp = fopen( $filename, 'r' );
2003 if ( false === $fp ) {
2004 return "Could not open \"{$filename}\".\n";
2006 $error = $this->sourceStream( $fp, $lineCallback, $resultCallback );
2012 * Read and execute commands from an open file handle
2013 * Returns true on success, error string on failure
2014 * @param string $fp File handle
2015 * @param callback $lineCallback Optional function called before reading each line
2016 * @param callback $resultCallback Optional function called for each MySQL result
2018 function sourceStream( $fp, $lineCallback = false, $resultCallback = false ) {
2021 $dollarquote = false;
2023 while ( ! feof( $fp ) ) {
2024 if ( $lineCallback ) {
2025 call_user_func( $lineCallback );
2027 $line = trim( fgets( $fp, 1024 ) );
2028 $sl = strlen( $line ) - 1;
2030 if ( $sl < 0 ) { continue; }
2031 if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
2033 ## Allow dollar quoting for function declarations
2034 if (substr($line,0,4) == '$mw$') {
2036 $dollarquote = false;
2040 $dollarquote = true;
2043 else if (!$dollarquote) {
2044 if ( ';' == $line{$sl} && ($sl < 2 ||
';' != $line{$sl - 1})) {
2046 $line = substr( $line, 0, $sl );
2050 if ( '' != $cmd ) { $cmd .= ' '; }
2054 $cmd = str_replace(';;', ";", $cmd);
2055 $cmd = $this->replaceVars( $cmd );
2056 $res = $this->query( $cmd, __METHOD__
, true );
2057 if ( $resultCallback ) {
2058 call_user_func( $resultCallback, $res );
2061 if ( false === $res ) {
2062 $err = $this->lastError();
2063 return "Query \"{$cmd}\" failed with error code \"$err\".\n";
2075 * Replace variables in sourced SQL
2077 protected function replaceVars( $ins ) {
2079 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
2080 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
2081 'wgDBadminuser', 'wgDBadminpassword', 'wgDBTableOptions',
2084 // Ordinary variables
2085 foreach ( $varnames as $var ) {
2086 if( isset( $GLOBALS[$var] ) ) {
2087 $val = addslashes( $GLOBALS[$var] ); // FIXME: safety check?
2088 $ins = str_replace( '{$' . $var . '}', $val, $ins );
2089 $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
2090 $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
2095 $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
2096 array( &$this, 'tableNameCallback' ), $ins );
2101 * Table name callback
2104 protected function tableNameCallback( $matches ) {
2105 return $this->tableName( $matches[1] );
2109 * Build a concatenation list to feed into a SQL query
2111 function buildConcat( $stringList ) {
2112 return 'CONCAT(' . implode( ',', $stringList ) . ')';
2118 * Database abstraction object for mySQL
2119 * Inherit all methods and properties of Database::Database()
2121 * @addtogroup Database
2124 class DatabaseMysql
extends Database
{
2128 /******************************************************************************
2130 *****************************************************************************/
2134 * @addtogroup Database
2139 function DBObject($data) {
2140 $this->mData
= $data;
2148 return $this->mData
;
2154 * @addtogroup Database
2156 * This allows us to distinguish a blob from a normal string and an array of strings
2160 function __construct($data) {
2161 $this->mData
= $data;
2164 return $this->mData
;
2170 * @addtogroup Database
2173 private $name, $tablename, $default, $max_length, $nullable,
2174 $is_pk, $is_unique, $is_key, $type;
2175 function __construct ($info) {
2176 $this->name
= $info->name
;
2177 $this->tablename
= $info->table
;
2178 $this->default = $info->def
;
2179 $this->max_length
= $info->max_length
;
2180 $this->nullable
= !$info->not_null
;
2181 $this->is_pk
= $info->primary_key
;
2182 $this->is_unique
= $info->unique_key
;
2183 $this->is_multiple
= $info->multiple_key
;
2184 $this->is_key
= ($this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
2185 $this->type
= $info->type
;
2192 function tableName() {
2193 return $this->tableName
;
2196 function defaultValue() {
2197 return $this->default;
2200 function maxLength() {
2201 return $this->max_length
;
2204 function nullable() {
2205 return $this->nullable
;
2209 return $this->is_key
;
2212 function isMultipleKey() {
2213 return $this->is_multiple
;
2221 /******************************************************************************
2223 *****************************************************************************/
2226 * Database error base class
2227 * @addtogroup Database
2229 class DBError
extends MWException
{
2233 * Construct a database error
2234 * @param Database $db The database object which threw the error
2235 * @param string $error A simple error message to be used for debugging
2237 function __construct( Database
&$db, $error ) {
2239 parent
::__construct( $error );
2244 * @addtogroup Database
2246 class DBConnectionError
extends DBError
{
2249 function __construct( Database
&$db, $error = 'unknown error' ) {
2250 $msg = 'DB connection error';
2251 if ( trim( $error ) != '' ) {
2254 $this->error
= $error;
2255 parent
::__construct( $db, $msg );
2258 function useOutputPage() {
2259 // Not likely to work
2263 function useMessageCache() {
2264 // Not likely to work
2268 function getText() {
2269 return $this->getMessage() . "\n";
2272 function getLogMessage() {
2273 # Don't send to the exception log
2277 function getPageTitle() {
2279 return "$wgSitename has a problem";
2282 function getHTML() {
2283 global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding;
2284 global $wgSitename, $wgServer, $wgMessageCache;
2286 # I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
2287 # Hard coding strings instead.
2289 $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>";
2290 $mainpage = 'Main Page';
2291 $searchdisabled = <<<EOT
2292 <p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
2293 <span style="font-size: 89%; display: block; margin-left: .2em">Note that their indexes of $wgSitename content may be out of date.</span></p>',
2297 <!-- SiteSearch Google -->
2298 <FORM method=GET action=\"http://www.google.com/search\">
2299 <TABLE bgcolor=\"#FFFFFF\"><tr><td>
2300 <A HREF=\"http://www.google.com/\">
2301 <IMG SRC=\"http://www.google.com/logos/Logo_40wht.gif\"
2302 border=\"0\" ALT=\"Google\"></A>
2305 <INPUT TYPE=text name=q size=31 maxlength=255 value=\"$1\">
2306 <INPUT type=submit name=btnG VALUE=\"Google Search\">
2308 <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 />
2309 <input type='hidden' name='ie' value='$2'>
2310 <input type='hidden' name='oe' value='$2'>
2314 <!-- SiteSearch Google -->";
2315 $cachederror = "The following is a cached copy of the requested page, and may not be up to date. ";
2317 # No database access
2318 if ( is_object( $wgMessageCache ) ) {
2319 $wgMessageCache->disable();
2322 if ( trim( $this->error
) == '' ) {
2323 $this->error
= $this->db
->getProperty('mServer');
2326 $text = str_replace( '$1', $this->error
, $noconnect );
2327 $text .= wfGetSiteNotice();
2329 if($wgUseFileCache) {
2334 $t = Title
::newFromURL( $title );
2335 } elseif (@/**/$_REQUEST['search']) {
2336 $search = $_REQUEST['search'];
2337 return $searchdisabled .
2338 str_replace( array( '$1', '$2' ), array( htmlspecialchars( $search ),
2339 $wgInputEncoding ), $googlesearch );
2341 $t = Title
::newFromText( $mainpage );
2345 $cache = new HTMLFileCache( $t );
2346 if( $cache->isFileCached() ) {
2347 // @todo, FIXME: $msg is not defined on the next line.
2348 $msg = '<p style="color: red"><b>'.$msg."<br />\n" .
2349 $cachederror . "</b></p>\n";
2351 $tag = '<div id="article">';
2352 $text = str_replace(
2355 $cache->fetchPageText() );
2364 * @addtogroup Database
2366 class DBQueryError
extends DBError
{
2367 public $error, $errno, $sql, $fname;
2369 function __construct( Database
&$db, $error, $errno, $sql, $fname ) {
2370 $message = "A database error has occurred\n" .
2372 "Function: $fname\n" .
2373 "Error: $errno $error\n";
2375 parent
::__construct( $db, $message );
2376 $this->error
= $error;
2377 $this->errno
= $errno;
2379 $this->fname
= $fname;
2382 function getText() {
2383 if ( $this->useMessageCache() ) {
2384 return wfMsg( 'dberrortextcl', htmlspecialchars( $this->getSQL() ),
2385 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) ) . "\n";
2387 return $this->getMessage();
2392 global $wgShowSQLErrors;
2393 if( !$wgShowSQLErrors ) {
2394 return $this->msg( 'sqlhidden', 'SQL hidden' );
2400 function getLogMessage() {
2401 # Don't send to the exception log
2405 function getPageTitle() {
2406 return $this->msg( 'databaseerror', 'Database error' );
2409 function getHTML() {
2410 if ( $this->useMessageCache() ) {
2411 return wfMsgNoDB( 'dberrortext', htmlspecialchars( $this->getSQL() ),
2412 htmlspecialchars( $this->fname
), $this->errno
, htmlspecialchars( $this->error
) );
2414 return nl2br( htmlspecialchars( $this->getMessage() ) );
2420 * @addtogroup Database
2422 class DBUnexpectedError
extends DBError
{}
2426 * Result wrapper for grabbing data queried by someone else
2427 * @addtogroup Database
2429 class ResultWrapper
implements Iterator
{
2430 var $db, $result, $pos = 0, $currentRow = null;
2433 * Create a new result object from a result resource and a Database object
2435 function ResultWrapper( $database, $result ) {
2436 $this->db
= $database;
2437 if ( $result instanceof ResultWrapper
) {
2438 $this->result
= $result->result
;
2440 $this->result
= $result;
2445 * Get the number of rows in a result object
2447 function numRows() {
2448 return $this->db
->numRows( $this->result
);
2452 * Fetch the next row from the given result object, in object form.
2453 * Fields can be retrieved with $row->fieldname, with fields acting like
2456 * @param $res SQL result object as returned from Database::query(), etc.
2457 * @return MySQL row object
2458 * @throws DBUnexpectedError Thrown if the database returns an error
2460 function fetchObject() {
2461 return $this->db
->fetchObject( $this->result
);
2465 * Fetch the next row from the given result object, in associative array
2466 * form. Fields are retrieved with $row['fieldname'].
2468 * @param $res SQL result object as returned from Database::query(), etc.
2469 * @return MySQL row object
2470 * @throws DBUnexpectedError Thrown if the database returns an error
2472 function fetchRow() {
2473 return $this->db
->fetchRow( $this->result
);
2477 * Free a result object
2480 $this->db
->freeResult( $this->result
);
2481 unset( $this->result
);
2486 * Change the position of the cursor in a result object
2487 * See mysql_data_seek()
2489 function seek( $row ) {
2490 $this->db
->dataSeek( $this->result
, $row );
2493 /*********************
2494 * Iterator functions
2495 * Note that using these in combination with the non-iterator functions
2496 * above may cause rows to be skipped or repeated.
2500 if ($this->numRows()) {
2501 $this->db
->dataSeek($this->result
, 0);
2504 $this->currentRow
= null;
2507 function current() {
2508 if ( is_null( $this->currentRow
) ) {
2511 return $this->currentRow
;
2520 $this->currentRow
= $this->fetchObject();
2521 return $this->currentRow
;
2525 return $this->current() !== false;
2529 class MySQLMasterPos
{
2532 function __construct( $file, $pos ) {
2533 $this->file
= $file;
2537 function __toString() {
2538 return "{$this->file}/{$this->pos}";