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
32 # Otherwise we get a suppressed fatal error, which is very hard to track down
33 if ( !function_exists( 'mysql_connect' ) ) {
34 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
37 # Debugging hack -- fake cluster
38 if ( $wgAllDBsAreLocalhost ) {
39 $realServer = 'localhost';
41 $realServer = $server;
44 $this->mServer
= $server;
46 $this->mPassword
= $password;
47 $this->mDBname
= $dbName;
51 wfProfileIn("dbconnect-$server");
53 # The kernel's default SYN retransmission period is far too slow for us,
54 # so we use a short timeout plus a manual retry. Retrying means that a small
55 # but finite rate of SYN packet loss won't cause user-visible errors.
57 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
62 $this->installErrorHandler();
63 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
67 if ( $this->mFlags
& DBO_PERSISTENT
) {
68 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
70 # Create a new connection...
71 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
73 if ($this->mConn
=== false) {
75 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
78 $phpError = $this->restoreErrorHandler();
79 # Always log connection errors
80 if ( !$this->mConn
) {
81 $error = $this->lastError();
85 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
86 wfDebug( "DB connection error\n" );
87 wfDebug( "Server: $server, User: $user, Password: " .
88 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
92 wfProfileOut("dbconnect-$server");
94 if ( $dbName != '' && $this->mConn
!== false ) {
95 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
97 $error = "Error selecting database $dbName on server {$this->mServer} " .
98 "from client host " . wfHostname() . "\n";
99 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
104 $success = (bool)$this->mConn
;
108 $version = $this->getServerVersion();
109 if ( version_compare( $version, '4.1' ) >= 0 ) {
110 // Tell the server we're communicating with it in UTF-8.
111 // This may engage various charset conversions.
114 $this->query( 'SET NAMES utf8', __METHOD__
);
116 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
118 if ( is_string( $wgSQLMode ) ) {
119 $mode = $this->addQuotes( $wgSQLMode );
120 $this->query( "SET sql_mode = $mode", __METHOD__
);
124 // Turn off strict mode if it is on
126 $this->reportConnectionError( $phpError );
129 $this->mOpened
= $success;
130 wfProfileOut( __METHOD__
);
135 $this->mOpened
= false;
136 if ( $this->mConn
) {
137 if ( $this->trxLevel() ) {
140 return mysql_close( $this->mConn
);
146 function freeResult( $res ) {
147 if ( $res instanceof ResultWrapper
) {
150 if ( !@/**/mysql_free_result( $res ) ) {
151 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
155 function fetchObject( $res ) {
156 if ( $res instanceof ResultWrapper
) {
159 @/**/$row = mysql_fetch_object( $res );
160 if( $this->lastErrno() ) {
161 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
166 function fetchRow( $res ) {
167 if ( $res instanceof ResultWrapper
) {
170 @/**/$row = mysql_fetch_array( $res );
171 if ( $this->lastErrno() ) {
172 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
177 function numRows( $res ) {
178 if ( $res instanceof ResultWrapper
) {
181 @/**/$n = mysql_num_rows( $res );
182 if( $this->lastErrno() ) {
183 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
188 function numFields( $res ) {
189 if ( $res instanceof ResultWrapper
) {
192 return mysql_num_fields( $res );
195 function fieldName( $res, $n ) {
196 if ( $res instanceof ResultWrapper
) {
199 return mysql_field_name( $res, $n );
202 function insertId() { return mysql_insert_id( $this->mConn
); }
204 function dataSeek( $res, $row ) {
205 if ( $res instanceof ResultWrapper
) {
208 return mysql_data_seek( $res, $row );
211 function lastErrno() {
212 if ( $this->mConn
) {
213 return mysql_errno( $this->mConn
);
215 return mysql_errno();
219 function lastError() {
220 if ( $this->mConn
) {
221 # Even if it's non-zero, it can still be invalid
222 wfSuppressWarnings();
223 $error = mysql_error( $this->mConn
);
225 $error = mysql_error();
229 $error = mysql_error();
232 $error .= ' (' . $this->mServer
. ')';
237 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
240 * Estimate rows in dataset
241 * Returns estimated count, based on EXPLAIN output
242 * Takes same arguments as Database::select()
244 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
245 $options['EXPLAIN'] = true;
246 $res = $this->select( $table, $vars, $conds, $fname, $options );
247 if ( $res === false )
249 if ( !$this->numRows( $res ) ) {
250 $this->freeResult($res);
255 while( $plan = $this->fetchObject( $res ) ) {
256 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
259 $this->freeResult($res);
263 function fieldInfo( $table, $field ) {
264 $table = $this->tableName( $table );
265 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
269 $n = mysql_num_fields( $res->result
);
270 for( $i = 0; $i < $n; $i++
) {
271 $meta = mysql_fetch_field( $res->result
, $i );
272 if( $field == $meta->name
) {
273 return new MySQLField($meta);
279 function selectDB( $db ) {
280 $this->mDBname
= $db;
281 return mysql_select_db( $db, $this->mConn
);
284 function strencode( $s ) {
285 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
287 if($sQuoted === false) {
289 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
295 $ping = mysql_ping( $this->mConn
);
300 mysql_close( $this->mConn
);
301 $this->mOpened
= false;
302 $this->mConn
= false;
303 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
309 * At the moment, this will only work if the DB user has the PROCESS privilege
313 if ( !is_null( $this->mFakeSlaveLag
) ) {
314 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
315 return $this->mFakeSlaveLag
;
317 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
318 # Find slave SQL thread
319 while ( $row = $this->fetchObject( $res ) ) {
320 /* This should work for most situations - when default db
321 * for thread is not specified, it had no events executed,
322 * and therefore it doesn't know yet how lagged it is.
324 * Relay log I/O thread does not select databases.
326 if ( $row->User
== 'system user' &&
327 $row->State
!= 'Waiting for master to send event' &&
328 $row->State
!= 'Connecting to master' &&
329 $row->State
!= 'Queueing master event to the relay log' &&
330 $row->State
!= 'Waiting for master update' &&
331 $row->State
!= 'Requesting binlog dump' &&
332 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
333 $row->State
!= 'Reconnecting after a failed master event read' &&
334 $row->State
!= 'Registering slave on master'
336 # This is it, return the time (except -ve)
337 if ( $row->Time
> 0x7fffffff ) {
347 function getServerVersion() {
348 return mysql_get_server_info( $this->mConn
);
351 function useIndexClause( $index ) {
352 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
355 function lowPriorityOption() {
356 return 'LOW_PRIORITY';
359 function getSoftwareLink() {
360 return '[http://www.mysql.com/ MySQL]';
363 function standardSelectDistinct() {
367 public function setTimeout( $timeout ) {
368 $this->query( "SET net_read_timeout=$timeout" );
369 $this->query( "SET net_write_timeout=$timeout" );
372 public function lock( $lockName, $method, $timeout = 5 ) {
373 $lockName = $this->addQuotes( $lockName );
374 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
375 $row = $this->fetchObject( $result );
376 $this->freeResult( $result );
378 if( $row->lockstatus
== 1 ) {
381 wfDebug( __METHOD__
." failed to acquire lock\n" );
387 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
389 public function unlock( $lockName, $method ) {
390 $lockName = $this->addQuotes( $lockName );
391 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
392 $row = $this->fetchObject( $result );
393 return $row->lockstatus
;
396 public function lockTables( $read, $write, $method, $lowPriority = true ) {
399 foreach( $write as $table ) {
400 $tbl = $this->tableName( $table ) .
401 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
405 foreach( $read as $table ) {
406 $items[] = $this->tableName( $table ) . ' READ';
408 $sql = "LOCK TABLES " . implode( ',', $items );
409 $this->query( $sql, $method );
412 public function unlockTables( $method ) {
413 $this->query( "UNLOCK TABLES", $method );
417 * Get search engine class. All subclasses of this
418 * need to implement this if they wish to use searching.
422 public function getSearchEngine() {
423 return 'SearchMySQL';
426 public function setBigSelects( $value = true ) {
427 if ( $value === 'default' ) {
428 if ( $this->mDefaultBigSelects
=== null ) {
429 # Function hasn't been called before so it must already be set to the default
432 $value = $this->mDefaultBigSelects
;
434 } elseif ( $this->mDefaultBigSelects
=== null ) {
435 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
437 $encValue = $value ?
'1' : '0';
438 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
443 * Determines if the last failure was due to a deadlock
445 function wasDeadlock() {
446 return $this->lastErrno() == 1213;
450 * Determines if the last query error was something that should be dealt
451 * with by pinging the connection and reissuing the query
453 function wasErrorReissuable() {
454 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
458 * Determines if the last failure was due to the database being read-only.
460 function wasReadOnlyError() {
461 return $this->lastErrno() == 1223 ||
462 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
465 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
466 $tmp = $temporary ?
'TEMPORARY ' : '';
467 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
468 # Hack for MySQL versions < 4.1, which don't support
469 # "CREATE TABLE ... LIKE". Note that
470 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
471 # would not create the indexes we need....
473 # Note that we don't bother changing around the prefixes here be-
474 # cause we know we're using MySQL anyway.
476 $res = $this->query( "SHOW CREATE TABLE $oldName" );
477 $row = $this->fetchRow( $res );
479 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
480 "CREATE $tmp TABLE `$newName`", $oldQuery );
481 if ($oldQuery === $query) {
482 # Couldn't do replacement
483 throw new MWException( "could not create temporary table $newName" );
486 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
488 $this->query( $query, $fname );
494 * Legacy support: Database == DatabaseMysql
496 class Database
extends DatabaseMysql
{}
498 class MySQLMasterPos
{
501 function __construct( $file, $pos ) {
506 function __toString() {
507 return "{$this->file}/{$this->pos}";