var $mFlags;
var $mTrxLevel = 0;
var $mErrorCount = 0;
+ var $mLBInfo = array();
/**#@-*/
#------------------------------------------------------------------------------
return wfSetVar( $this->mErrorCount, $count );
}
+ /**
+ * Properties passed down from the server info array of the load balancer
+ */
+ function getLBInfo( $name = NULL ) {
+ if ( is_null( $name ) ) {
+ return $this->mLBInfo;
+ } else {
+ if ( array_key_exists( $name, $this->mLBInfo ) ) {
+ return $this->mLBInfo[$name];
+ } else {
+ return NULL;
+ }
+ }
+ }
+
+ function setLBInfo( $name, $value = NULL ) {
+ if ( is_null( $value ) ) {
+ $this->mLBInfo = $name;
+ } else {
+ $this->mLBInfo[$name] = $value;
+ }
+ }
+
/**#@+
* Get function
*/
* If the failFunction is set to a non-zero integer, returns success
*/
function open( $server, $user, $password, $dbName ) {
+ global $wguname;
+
# Test for missing mysql.so
# First try to load it
if (!@extension_loaded('mysql')) {
# Otherwise we get a suppressed fatal error, which is very hard to track down
if ( !function_exists( 'mysql_connect' ) ) {
- die( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
+ wfDie( "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
}
$this->close();
if ( $this->mConn !== false ) {
$success = @/**/mysql_select_db( $dbName, $this->mConn );
if ( !$success ) {
- wfDebug( "Error selecting database \"$dbName\": " . $this->lastError() . "\n" );
+ $error = "Error selecting database $dbName on server {$this->mServer} " .
+ "from client host {$wguname['nodename']}\n";
+ wfDebug( $error );
}
} else {
wfDebug( "DB connection error\n" );
if ( !$success ) {
$this->reportConnectionError();
}
+
+ global $wgDBmysql5;
+ if( $wgDBmysql5 ) {
+ // Tell the server we're communicating with it in UTF-8.
+ // This may engage various charset conversions.
+ $this->query( 'SET NAMES utf8' );
+ }
+
$this->mOpened = $success;
return $success;
}
/**
* @access private
- * @param string $msg error message ?
+ * @param string $error fallback error message, used if none is given by MySQL
*/
- function reportConnectionError() {
+ function reportConnectionError( $error = 'Unknown error' ) {
+ $myError = $this->lastError();
+ if ( $myError ) {
+ $error = $myError;
+ }
+
if ( $this->mFailFunction ) {
if ( !is_int( $this->mFailFunction ) ) {
$ff = $this->mFailFunction;
- $ff( $this, $this->lastError() );
+ $ff( $this, $error );
}
} else {
- wfEmergencyAbort( $this, $this->lastError() );
+ wfEmergencyAbort( $this, $error );
}
}
function query( $sql, $fname = '', $tempIgnore = false ) {
global $wgProfiling, $wgCommandLineMode;
- if ( wfReadOnly() ) {
- # This is a quick check for the most common kinds of write query used
- # in MediaWiki, to provide extra safety in addition to UI-level checks.
- # It is not intended to prevent every conceivable write query, or even
- # to handle such queries gracefully.
- if ( preg_match( '/^(?:update|insert|replace|delete)/i', $sql ) ) {
- wfDebug( "Write query from $fname blocked\n" );
- return false;
- }
- }
-
if ( $wgProfiling ) {
# generalizeSQL will probably cut down the query to reasonable
# logging size most of the time. The substr is really just a sanity check.
- $profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
+
+ # Who's been wasting my precious column space? -- TS
+ #$profName = 'query: ' . $fname . ' ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
+ $profName = 'query: ' . substr( Database::generalizeSQL( $sql ), 0, 255 );
+
wfProfileIn( 'Database::query' );
wfProfileIn( $profName );
}
# Add a comment for easy SHOW PROCESSLIST interpretation
if ( $fname ) {
- $commentedSql = "/* $fname */ $sql";
+ $commentedSql = preg_replace("/\s/", " /* $fname */ ", $sql, 1);
} else {
$commentedSql = $sql;
}
$table = $this->tableName( $table );
$sql = "UPDATE $table SET $var = '" .
$this->strencode( $value ) . "' WHERE ($cond)";
- return (bool)$this->query( $sql, DB_MASTER, $fname );
+ return (bool)$this->query( $sql, $fname );
}
/**
$tailOpts .= " ORDER BY {$options['ORDER BY']}";
}
if (isset($options['LIMIT'])) {
- $tailOpts .= $this->limitResult('', $options['LIMIT'],
+ $tailOpts .= $this->limitResult('', $options['LIMIT'],
isset($options['OFFSET']) ? $options['OFFSET'] : false);
}
if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
*/
function fieldExists( $table, $field, $fname = 'Database::fieldExists' ) {
$table = $this->tableName( $table );
- $res = $this->query( 'DESCRIBE '.$table, DB_SLAVE, $fname );
+ $res = $this->query( 'DESCRIBE '.$table, $fname );
if ( !$res ) {
return NULL;
}
$opts = array();
if ( in_array( 'LOW_PRIORITY', $options ) )
$opts[] = $this->lowPriorityOption();
- if ( in_array( 'IGNORE', $options ) )
+ if ( in_array( 'IGNORE', $options ) )
$opts[] = 'IGNORE';
return implode(' ', $opts);
}
-
+
/**
* UPDATE wrapper, takes a condition array and a SET array
*
* $mode: LIST_COMMA - comma separated, no field names
* LIST_AND - ANDed WHERE clause (without the WHERE)
* LIST_SET - comma separated with field names, like a SET clause
- * LIST_NAMES - comma separated field names
+ * LIST_NAMES - comma separated field names
*/
function makeList( $a, $mode = LIST_COMMA ) {
if ( !is_array( $a ) ) {
return mysql_select_db( $db, $this->mConn );
}
- /**
- * Starts a timer which will kill the DB thread after $timeout seconds
- */
- function startTimer( $timeout ) {
- global $IP;
- if( function_exists( 'mysql_thread_id' ) ) {
- # This will kill the query if it's still running after $timeout seconds.
- $tid = mysql_thread_id( $this->mConn );
- exec( "php $IP/includes/killthread.php $timeout $tid &>/dev/null &" );
- }
- }
-
- /**
- * Stop a timer started by startTimer()
- * Currently unimplemented.
- *
- */
- function stopTimer() { }
-
/**
* Format a table name ready for use in constructing an SQL query
*
$s=str_replace(array('%','_'),array('\%','\_'),$s);
return $s;
}
-
+
/**
* Returns an appropriately quoted sequence value for inserting a new row.
* MySQL has autoincrement fields, so this is just NULL. But the PostgreSQL
* $conds may be "*" to copy the whole table
* srcTable may be an array of tables.
*/
- function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect' ) {
+ function insertSelect( $destTable, $srcTable, $varMap, $conds, $fname = 'Database::insertSelect',
+ $options = array() )
+ {
$destTable = $this->tableName( $destTable );
- if( is_array( $srcTable ) ) {
- $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
- } else {
+ if ( is_array( $options ) ) {
+ $options = implode( ' ', $options );
+ }
+ if( is_array( $srcTable ) ) {
+ $srcTable = implode( ',', array_map( array( &$this, 'tableName' ), $srcTable ) );
+ } else {
$srcTable = $this->tableName( $srcTable );
}
- $sql = "INSERT INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
- ' SELECT ' . implode( ',', $varMap ) .
+ $sql = "INSERT $options INTO $destTable (" . implode( ',', array_keys( $varMap ) ) . ')' .
+ ' SELECT ' . implode( ',', $varMap ) .
" FROM $srcTable";
if ( $conds != '*' ) {
$sql .= ' WHERE ' . $this->makeList( $conds, LIST_AND );
while ( $row = $this->fetchObject( $res ) ) {
if ( $row->User == 'system user' ) {
if ( ++$slaveThreads == 2 ) {
- # This is it, return the time
- return $row->Time;
+ # This is it, return the time (except -ve)
+ if ( $row->Time > 1>>31 ) {
+ return 0;
+ } else {
+ return $row->Time;
+ }
}
}
}
/**
* Get status information from SHOW STATUS in an associative array
*/
- function getStatus() {
- $res = $this->query( 'SHOW STATUS' );
+ function getStatus($which="%") {
+ $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
$status = array();
while ( $row = $this->fetchObject( $res ) ) {
$status[$row->Variable_name] = $row->Value;
return $b;
}
- function notNullTimestamp() {
- return "!= 0";
+ /**
+ * Read and execute SQL commands from a file.
+ * Returns true on success, error string on failure
+ */
+ function sourceFile( $filename ) {
+ $fp = fopen( $filename, 'r' );
+ if ( false === $fp ) {
+ return "Could not open \"{$fname}\".\n";
+ }
+
+ $cmd = "";
+ $done = false;
+
+ while ( ! feof( $fp ) ) {
+ $line = trim( fgets( $fp, 1024 ) );
+ $sl = strlen( $line ) - 1;
+
+ if ( $sl < 0 ) { continue; }
+ if ( '-' == $line{0} && '-' == $line{1} ) { continue; }
+
+ if ( ';' == $line{$sl} && ($sl < 2 || ';' != $line{$sl - 1})) {
+ $done = true;
+ $line = substr( $line, 0, $sl );
+ }
+
+ if ( '' != $cmd ) { $cmd .= ' '; }
+ $cmd .= "$line\n";
+
+ if ( $done ) {
+ $cmd = str_replace(';;', ";", $cmd);
+ $cmd = $this->replaceVars( $cmd );
+ $res = $this->query( $cmd, 'dbsource', true );
+
+ if ( false === $res ) {
+ $err = $this->lastError();
+ return "Query \"{$cmd}\" failed with error code \"$err\".\n";
+ }
+
+ $cmd = '';
+ $done = false;
+ }
+ }
+ fclose( $fp );
+ return true;
+ }
+
+ /**
+ * Replace variables in sourced SQL
+ */
+ function replaceVars( $ins ) {
+ $varnames = array(
+ 'wgDBserver', 'wgDBname', 'wgDBintlname', 'wgDBuser',
+ 'wgDBpassword', 'wgDBsqluser', 'wgDBsqlpassword',
+ 'wgDBadminuser', 'wgDBadminpassword',
+ );
+
+ // Ordinary variables
+ foreach ( $varnames as $var ) {
+ if( isset( $GLOBALS[$var] ) ) {
+ $val = addslashes( $GLOBALS[$var] );
+ $ins = str_replace( '{$' . $var . '}', $val, $ins );
+ $ins = str_replace( '/*$' . $var . '*/`', '`' . $val, $ins );
+ $ins = str_replace( '/*$' . $var . '*/', $val, $ins );
+ }
+ }
+
+ // Table prefixes
+ $ins = preg_replace_callback( '/\/\*(?:\$wgDBprefix|_)\*\/([a-z_]*)/',
+ array( &$this, 'tableNameCallback' ), $ins );
+ return $ins;
}
- function isNullTimestamp() {
- return "= '0'";
+
+ /**
+ * Table name callback
+ * @access private
+ */
+ function tableNameCallback( $matches ) {
+ return $this->tableName( $matches[1] );
}
+
}
/**
/**
* @todo document
*/
- function ResultWrapper( $database, $result ) {
+ function ResultWrapper( &$database, $result ) {
$this->db =& $database;
$this->result =& $result;
}
function seek( $row ) {
$this->db->dataSeek( $this->result, $row );
}
+
}
+
#------------------------------------------------------------------------------
# Global functions
#------------------------------------------------------------------------------
*/
function wfEmergencyAbort( &$conn, $error ) {
global $wgTitle, $wgUseFileCache, $title, $wgInputEncoding, $wgOutputEncoding;
- global $wgSitename, $wgServer, $wgMessageCache;
+ global $wgSitename, $wgServer, $wgMessageCache, $wgLogo;
# I give up, Brion is right. Getting the message cache to work when there is no DB is tricky.
# Hard coding strings instead.
- $noconnect = '<h1>Wiki currently offline</h1><p><strong>Sorry! This site is experiencing technical difficulties.</strong></p><p><small>(Can\'t contact the database server: $1)</small></p>';
+ $noconnect = "<h1><img src='$wgLogo' style='float:left;margin-right:1em' alt=''>$wgSitename has a problem</h1><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>";
$mainpage = 'Main Page';
$searchdisabled = <<<EOT
<p style="margin: 1.5em 2em 1em">$wgSitename search is disabled for performance reasons. You can search via Google in the meantime.
if ( is_object( $wgMessageCache ) ) {
$wgMessageCache->disable();
}
-
- $msg = wfGetSiteNotice();
- if($msg == '') {
- $msg = str_replace( '$1', $error, $noconnect );
+
+ if ( trim( $error ) == '' ) {
+ $error = $this->mServer;
}
- $text = $msg;
+
+ wfLogDBError( "Connection error: $error\n" );
+
+ $text = str_replace( '$1', $error, $noconnect );
+ $text .= wfGetSiteNotice();
if($wgUseFileCache) {
if($wgTitle) {