3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
9 class DatabaseMysql
extends DatabaseBase
{
14 /*private*/ function doQuery( $sql ) {
15 if( $this->bufferResults() ) {
16 $ret = mysql_query( $sql, $this->mConn
);
18 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
23 function open( $server, $user, $password, $dbName ) {
24 global $wgAllDBsAreLocalhost;
25 wfProfileIn( __METHOD__
);
27 # Test for missing mysql.so
28 # First try to load it
29 if (!@extension_loaded
('mysql')) {
34 # Otherwise we get a suppressed fatal error, which is very hard to track down
35 if ( !function_exists( 'mysql_connect' ) ) {
36 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
39 # Debugging hack -- fake cluster
40 if ( $wgAllDBsAreLocalhost ) {
41 $realServer = 'localhost';
43 $realServer = $server;
46 $this->mServer
= $server;
48 $this->mPassword
= $password;
49 $this->mDBname
= $dbName;
53 wfProfileIn("dbconnect-$server");
55 # The kernel's default SYN retransmission period is far too slow for us,
56 # so we use a short timeout plus a manual retry. Retrying means that a small
57 # but finite rate of SYN packet loss won't cause user-visible errors.
59 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
64 $this->installErrorHandler();
65 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
69 if ( $this->mFlags
& DBO_PERSISTENT
) {
70 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
72 # Create a new connection...
73 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
75 if ($this->mConn
=== false) {
77 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
80 $phpError = $this->restoreErrorHandler();
81 # Always log connection errors
82 if ( !$this->mConn
) {
83 $error = $this->lastError();
87 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
88 wfDebug( "DB connection error\n" );
89 wfDebug( "Server: $server, User: $user, Password: " .
90 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
94 wfProfileOut("dbconnect-$server");
96 if ( $dbName != '' && $this->mConn
!== false ) {
97 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
99 $error = "Error selecting database $dbName on server {$this->mServer} " .
100 "from client host " . wfHostname() . "\n";
101 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
106 $success = (bool)$this->mConn
;
110 $version = $this->getServerVersion();
111 if ( version_compare( $version, '4.1' ) >= 0 ) {
112 // Tell the server we're communicating with it in UTF-8.
113 // This may engage various charset conversions.
116 $this->query( 'SET NAMES utf8', __METHOD__
);
118 // Turn off strict mode
119 $this->query( "SET sql_mode = ''", __METHOD__
);
122 // Turn off strict mode if it is on
124 $this->reportConnectionError( $phpError );
127 $this->mOpened
= $success;
128 wfProfileOut( __METHOD__
);
133 $this->mOpened
= false;
134 if ( $this->mConn
) {
135 if ( $this->trxLevel() ) {
138 return mysql_close( $this->mConn
);
144 function freeResult( $res ) {
145 if ( $res instanceof ResultWrapper
) {
148 if ( !@/**/mysql_free_result( $res ) ) {
149 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
153 function fetchObject( $res ) {
154 if ( $res instanceof ResultWrapper
) {
157 @/**/$row = mysql_fetch_object( $res );
158 if( $this->lastErrno() ) {
159 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
164 function fetchRow( $res ) {
165 if ( $res instanceof ResultWrapper
) {
168 @/**/$row = mysql_fetch_array( $res );
169 if ( $this->lastErrno() ) {
170 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
175 function numRows( $res ) {
176 if ( $res instanceof ResultWrapper
) {
179 @/**/$n = mysql_num_rows( $res );
180 if( $this->lastErrno() ) {
181 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
186 function numFields( $res ) {
187 if ( $res instanceof ResultWrapper
) {
190 return mysql_num_fields( $res );
193 function fieldName( $res, $n ) {
194 if ( $res instanceof ResultWrapper
) {
197 return mysql_field_name( $res, $n );
200 function insertId() { return mysql_insert_id( $this->mConn
); }
202 function dataSeek( $res, $row ) {
203 if ( $res instanceof ResultWrapper
) {
206 return mysql_data_seek( $res, $row );
209 function lastErrno() {
210 if ( $this->mConn
) {
211 return mysql_errno( $this->mConn
);
213 return mysql_errno();
217 function lastError() {
218 if ( $this->mConn
) {
219 # Even if it's non-zero, it can still be invalid
220 wfSuppressWarnings();
221 $error = mysql_error( $this->mConn
);
223 $error = mysql_error();
227 $error = mysql_error();
230 $error .= ' (' . $this->mServer
. ')';
235 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
238 * Estimate rows in dataset
239 * Returns estimated count, based on EXPLAIN output
240 * Takes same arguments as Database::select()
242 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
243 $options['EXPLAIN'] = true;
244 $res = $this->select( $table, $vars, $conds, $fname, $options );
245 if ( $res === false )
247 if ( !$this->numRows( $res ) ) {
248 $this->freeResult($res);
253 while( $plan = $this->fetchObject( $res ) ) {
254 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
257 $this->freeResult($res);
261 function fieldInfo( $table, $field ) {
262 $table = $this->tableName( $table );
263 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
264 $n = mysql_num_fields( $res->result
);
265 for( $i = 0; $i < $n; $i++
) {
266 $meta = mysql_fetch_field( $res->result
, $i );
267 if( $field == $meta->name
) {
268 return new MySQLField($meta);
274 function selectDB( $db ) {
275 $this->mDBname
= $db;
276 return mysql_select_db( $db, $this->mConn
);
279 function strencode( $s ) {
280 return mysql_real_escape_string( $s, $this->mConn
);
284 if( !function_exists( 'mysql_ping' ) ) {
285 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
288 $ping = mysql_ping( $this->mConn
);
293 // Need to reconnect manually in MySQL client 5.0.13+
294 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
295 mysql_close( $this->mConn
);
296 $this->mOpened
= false;
297 $this->mConn
= false;
298 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
304 function getServerVersion() {
305 return mysql_get_server_info( $this->mConn
);
308 function useIndexClause( $index ) {
309 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
312 function lowPriorityOption() {
313 return 'LOW_PRIORITY';
316 function getSoftwareLink() {
317 return '[http://www.mysql.com/ MySQL]';
320 function standardSelectDistinct() {
324 public function setTimeout( $timeout ) {
325 $this->query( "SET net_read_timeout=$timeout" );
326 $this->query( "SET net_write_timeout=$timeout" );
329 public function lock( $lockName, $method, $timeout = 5 ) {
330 $lockName = $this->addQuotes( $lockName );
331 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
332 $row = $this->fetchObject( $result );
333 $this->freeResult( $result );
335 if( $row->lockstatus
== 1 ) {
338 wfDebug( __METHOD__
." failed to acquire lock\n" );
343 public function unlock( $lockName, $method ) {
344 $lockName = $this->addQuotes( $lockName );
345 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
346 $row = $this->fetchObject( $result );
347 return $row->lockstatus
;
350 public function lockTables( $read, $write, $method, $lowPriority = true ) {
353 foreach( $write as $table ) {
354 $tbl = $this->tableName( $table ) .
355 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
359 foreach( $read as $table ) {
360 $items[] = $this->tableName( $table ) . ' READ';
362 $sql = "LOCK TABLES " . implode( ',', $items );
363 $this->query( $sql, $method );
366 public function unlockTables( $method ) {
367 $this->query( "UNLOCK TABLES", $method );
370 public function setBigSelects( $value = true ) {
371 if ( $value === 'default' ) {
372 if ( $this->mDefaultBigSelects
=== null ) {
373 # Function hasn't been called before so it must already be set to the default
376 $value = $this->mDefaultBigSelects
;
378 } elseif ( $this->mDefaultBigSelects
=== null ) {
379 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
381 $encValue = $value ?
'1' : '0';
382 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
387 * Determines if the last failure was due to a deadlock
389 function wasDeadlock() {
390 return $this->lastErrno() == 1213;
394 * Determines if the last query error was something that should be dealt
395 * with by pinging the connection and reissuing the query
397 function wasErrorReissuable() {
398 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
402 * Determines if the last failure was due to the database being read-only.
404 function wasReadOnlyError() {
405 return $this->lastErrno() == 1223 ||
406 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
409 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
410 $tmp = $temporary ?
'TEMPORARY ' : '';
411 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
412 # Hack for MySQL versions < 4.1, which don't support
413 # "CREATE TABLE ... LIKE". Note that
414 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
415 # would not create the indexes we need....
417 # Note that we don't bother changing around the prefixes here be-
418 # cause we know we're using MySQL anyway.
420 $res = $this->query( "SHOW CREATE TABLE $oldName" );
421 $row = $this->fetchRow( $res );
423 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
424 "CREATE $tmp TABLE `$newName`", $oldQuery );
425 if ($oldQuery === $query) {
426 # Couldn't do replacement
427 throw new MWException( "could not create temporary table $newName" );
430 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
432 $this->query( $query, $fname );
438 * Legacy support: Database == DatabaseMysql
440 class Database
extends DatabaseMysql
{}
442 class MySQLMasterPos
{
445 function __construct( $file, $pos ) {
450 function __toString() {
451 return "{$this->file}/{$this->pos}";