define( 'LIST_AND', 1 );
define( 'LIST_SET', 2 );
define( 'LIST_NAMES', 3);
+define( 'LIST_OR', 4);
/** Number of times to re-try an operation in case of deadlock */
define( 'DEADLOCK_TRIES', 4 );
*/
var $mLastQuery = '';
- var $mServer, $mUser, $mPassword, $mConn, $mDBname;
+ var $mServer, $mUser, $mPassword, $mConn = null, $mDBname;
var $mOut, $mOpened = false;
var $mFailFunction;
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
*/
function isOpen() { return $this->mOpened; }
/**#@-*/
+ function setFlag( $flag ) {
+ $this->mFlags |= $flag;
+ }
+
+ function clearFlag( $flag ) {
+ $this->mFlags &= ~$flag;
+ }
+
+ function getFlag( $flag ) {
+ return !!($this->mFlags & $flag);
+ }
+
#------------------------------------------------------------------------------
# Other functions
#------------------------------------------------------------------------------
* 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();
@/**/$this->mConn = mysql_pconnect( $server, $user, $password );
} else {
# Create a new connection...
- @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
+ if( version_compare( PHP_VERSION, '4.2.0', 'ge' ) ) {
+ @/**/$this->mConn = mysql_connect( $server, $user, $password, true );
+ } else {
+ # On PHP 4.1 the new_link parameter is not available. We cannot
+ # guarantee that we'll actually get a new connection, and this
+ # may cause some operations to fail possibly.
+ @/**/$this->mConn = mysql_connect( $server, $user, $password );
+ }
}
if ( $dbName != '' ) {
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();
- $this->close();
}
+
+ 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 ?
- * @todo parameter $msg is not used
+ * @param string $error fallback error message, used if none is given by MySQL
*/
- function reportConnectionError( $msg = '') {
+ 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, mysql_error() );
+ 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;
}
global $wgCommandLineMode, $wgFullyInitialised;
# Ignore errors during error handling to avoid infinite recursion
$ignore = $this->ignoreErrors( true );
- $this->mErrorCount ++;
+ ++$this->mErrorCount;
if( $ignore || $tempIgnore ) {
- wfDebug("SQL ERROR (ignored): " . $error . "\n");
+ wfDebug("SQL ERROR (ignored): $error\n");
} else {
$sql1line = str_replace( "\n", "\\n", $sql );
wfLogDBError("$fname\t{$this->mServer}\t$errno\t$error\t$sql1line\n");
*/
function lastError() {
if ( $this->mConn ) {
+ # Even if it's non-zero, it can still be invalid
+ wfSuppressWarnings();
$error = mysql_error( $this->mConn );
+ if ( !$error ) {
+ $error = mysql_error();
+ }
+ wfRestoreWarnings();
} else {
$error = mysql_error();
}
$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 );
}
/**
if ( isset( $options['ORDER BY'] ) ) {
$tailOpts .= " ORDER BY {$options['ORDER BY']}";
}
-
+ if (isset($options['LIMIT'])) {
+ $tailOpts .= $this->limitResult('', $options['LIMIT'],
+ isset($options['OFFSET']) ? $options['OFFSET'] : false);
+ }
if ( is_numeric( array_search( 'FOR UPDATE', $options ) ) ) {
$tailOpts .= ' FOR UPDATE';
}
$tailOpts .= ' LOCK IN SHARE MODE';
}
- if ( isset( $options['USE INDEX'] ) ) {
+ if ( isset( $options['USE INDEX'] ) && ! is_array( $options['USE INDEX'] ) ) {
$useIndex = $this->useIndexClause( $options['USE INDEX'] );
} else {
$useIndex = '';
$options = array( $options );
}
if( is_array( $table ) ) {
- $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
+ if ( @is_array( $options['USE INDEX'] ) )
+ $from = ' FROM ' . $this->tableNamesWithUseIndex( $table, $options['USE INDEX'] );
+ else
+ $from = ' FROM ' . implode( ',', array_map( array( &$this, 'tableName' ), $table ) );
} elseif ($table!='') {
- $from = ' FROM ' .$this->tableName( $table );
+ $from = ' FROM ' . $this->tableName( $table );
} else {
$from = '';
}
} else {
$sql = "SELECT $vars $from $useIndex $tailOpts";
}
- if (isset($options['LIMIT'])) {
- $sql = $this->limitResult($sql, $options['LIMIT'], isset($options['OFFSET']) ? $options['OFFSET'] : false);
- }
+
return $this->query( $sql, $fname );
}
*/
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;
}
*/
function makeUpdateOptions( $options ) {
if( !is_array( $options ) ) {
- wfDebugDieBacktrace( 'makeUpdateOptions given non-array' );
+ $options = array( $options );
}
$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 ) ) {
if ( !$first ) {
if ( $mode == LIST_AND ) {
$list .= ' AND ';
+ } elseif($mode == LIST_OR) {
+ $list .= ' OR ';
} else {
$list .= ',';
}
} else {
$first = false;
}
- if ( $mode == LIST_AND && is_numeric( $field ) ) {
+ if ( ($mode == LIST_AND || $mode == LIST_OR) && is_numeric( $field ) ) {
$list .= "($value)";
} elseif ( $mode == LIST_AND && is_array ($value) ) {
$list .= $field." IN (".$this->makeList($value).") ";
} else {
- if ( $mode == LIST_AND || $mode == LIST_SET ) {
+ if ( $mode == LIST_AND || $mode == LIST_OR || $mode == LIST_SET ) {
$list .= "$field = ";
}
$list .= $mode == LIST_NAMES ? $value : $this->addQuotes( $value );
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
*
return $retVal;
}
+ /**
+ * @access private
+ */
+ function tableNamesWithUseIndex( $tables, $use_index ) {
+ $ret = array();
+
+ foreach ( $tables as $table )
+ if ( @$use_index[$table] !== null )
+ $ret[] = $this->tableName( $table ) . ' ' . $this->useIndexClause( implode( ',', (array)$use_index[$table] ) );
+ else
+ $ret[] = $this->tableName( $table );
+
+ return implode( ',', $ret );
+ }
+
/**
* Wrapper for addslashes()
* @param string $s String to be slashed.
}
}
+ /**
+ * Escape string for safe LIKE usage
+ */
+ function escapeLike( $s ) {
+ $s=$this->strencode( $s );
+ $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 );
/**
* @todo document
*/
- function resultObject( &$result ) {
+ function resultObject( $result ) {
if( empty( $result ) ) {
return NULL;
} else {
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;
+ 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 = 'Sorry! The wiki is experiencing some technical difficulties, and cannot contact the database server: $1. <br />
-$1';
+ $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.
header( 'Cache-control: none' );
header( 'Pragma: nocache' );
}
- $msg = wfGetSiteNotice();
- if($msg == '') {
- $msg = str_replace( '$1', $error, $noconnect );
+
+ # No database access
+ if ( is_object( $wgMessageCache ) ) {
+ $wgMessageCache->disable();
+ }
+
+ 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) {