3 * This is the MySQL database abstraction layer.
10 * Database abstraction object for mySQL
11 * Inherit all methods and properties of Database::Database()
16 class DatabaseMysql
extends DatabaseBase
{
21 /*private*/ function doQuery( $sql ) {
22 if( $this->bufferResults() ) {
23 $ret = mysql_query( $sql, $this->mConn
);
25 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
30 function open( $server, $user, $password, $dbName ) {
31 global $wgAllDBsAreLocalhost;
32 wfProfileIn( __METHOD__
);
34 # Load mysql.so if we don't have it
38 # Otherwise we get a suppressed fatal error, which is very hard to track down
39 if ( !function_exists( 'mysql_connect' ) ) {
40 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
43 # Debugging hack -- fake cluster
44 if ( $wgAllDBsAreLocalhost ) {
45 $realServer = 'localhost';
47 $realServer = $server;
50 $this->mServer
= $server;
52 $this->mPassword
= $password;
53 $this->mDBname
= $dbName;
57 wfProfileIn("dbconnect-$server");
59 # The kernel's default SYN retransmission period is far too slow for us,
60 # so we use a short timeout plus a manual retry. Retrying means that a small
61 # but finite rate of SYN packet loss won't cause user-visible errors.
63 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
68 $this->installErrorHandler();
69 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
73 if ( $this->mFlags
& DBO_PERSISTENT
) {
74 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
76 # Create a new connection...
77 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
79 #if ( $this->mConn === false ) {
81 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
84 $phpError = $this->restoreErrorHandler();
85 # Always log connection errors
86 if ( !$this->mConn
) {
87 $error = $this->lastError();
91 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
92 wfDebug( "DB connection error\n" );
93 wfDebug( "Server: $server, User: $user, Password: " .
94 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
98 wfProfileOut("dbconnect-$server");
100 if ( $dbName != '' && $this->mConn
!== false ) {
101 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
103 $error = "Error selecting database $dbName on server {$this->mServer} " .
104 "from client host " . wfHostname() . "\n";
105 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
110 $success = (bool)$this->mConn
;
114 $version = $this->getServerVersion();
115 if ( version_compare( $version, '4.1' ) >= 0 ) {
116 // Tell the server we're communicating with it in UTF-8.
117 // This may engage various charset conversions.
120 $this->query( 'SET NAMES utf8', __METHOD__
);
122 $this->query( 'SET NAMES binary', __METHOD__
);
124 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
126 if ( is_string( $wgSQLMode ) ) {
127 $mode = $this->addQuotes( $wgSQLMode );
128 $this->query( "SET sql_mode = $mode", __METHOD__
);
132 // Turn off strict mode if it is on
134 $this->reportConnectionError( $phpError );
137 $this->mOpened
= $success;
138 wfProfileOut( __METHOD__
);
143 $this->mOpened
= false;
144 if ( $this->mConn
) {
145 if ( $this->trxLevel() ) {
148 return mysql_close( $this->mConn
);
154 function freeResult( $res ) {
155 if ( $res instanceof ResultWrapper
) {
158 if ( !@/**/mysql_free_result( $res ) ) {
159 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
163 function fetchObject( $res ) {
164 if ( $res instanceof ResultWrapper
) {
167 @/**/$row = mysql_fetch_object( $res );
168 if( $this->lastErrno() ) {
169 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
174 function fetchRow( $res ) {
175 if ( $res instanceof ResultWrapper
) {
178 @/**/$row = mysql_fetch_array( $res );
179 if ( $this->lastErrno() ) {
180 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
185 function numRows( $res ) {
186 if ( $res instanceof ResultWrapper
) {
189 @/**/$n = mysql_num_rows( $res );
190 if( $this->lastErrno() ) {
191 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
196 function numFields( $res ) {
197 if ( $res instanceof ResultWrapper
) {
200 return mysql_num_fields( $res );
203 function fieldName( $res, $n ) {
204 if ( $res instanceof ResultWrapper
) {
207 return mysql_field_name( $res, $n );
210 function insertId() { return mysql_insert_id( $this->mConn
); }
212 function dataSeek( $res, $row ) {
213 if ( $res instanceof ResultWrapper
) {
216 return mysql_data_seek( $res, $row );
219 function lastErrno() {
220 if ( $this->mConn
) {
221 return mysql_errno( $this->mConn
);
223 return mysql_errno();
227 function lastError() {
228 if ( $this->mConn
) {
229 # Even if it's non-zero, it can still be invalid
230 wfSuppressWarnings();
231 $error = mysql_error( $this->mConn
);
233 $error = mysql_error();
237 $error = mysql_error();
240 $error .= ' (' . $this->mServer
. ')';
245 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
248 * Estimate rows in dataset
249 * Returns estimated count, based on EXPLAIN output
250 * Takes same arguments as Database::select()
252 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
253 $options['EXPLAIN'] = true;
254 $res = $this->select( $table, $vars, $conds, $fname, $options );
255 if ( $res === false ) {
258 if ( !$this->numRows( $res ) ) {
263 foreach ( $res as $plan ) {
264 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
269 function fieldInfo( $table, $field ) {
270 $table = $this->tableName( $table );
271 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
275 $n = mysql_num_fields( $res->result
);
276 for( $i = 0; $i < $n; $i++
) {
277 $meta = mysql_fetch_field( $res->result
, $i );
278 if( $field == $meta->name
) {
279 return new MySQLField($meta);
286 * Get information about an index into an object
287 * Returns false if the index does not exist
289 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
290 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
291 # SHOW INDEX should work for 3.x and up:
292 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
293 $table = $this->tableName( $table );
294 $index = $this->indexName( $index );
295 $sql = 'SHOW INDEX FROM ' . $table;
296 $res = $this->query( $sql, $fname );
304 foreach ( $res as $row ) {
305 if ( $row->Key_name
== $index ) {
310 return empty( $result ) ?
false : $result;
313 function selectDB( $db ) {
314 $this->mDBname
= $db;
315 return mysql_select_db( $db, $this->mConn
);
318 function strencode( $s ) {
319 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
321 if($sQuoted === false) {
323 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
329 $ping = mysql_ping( $this->mConn
);
334 mysql_close( $this->mConn
);
335 $this->mOpened
= false;
336 $this->mConn
= false;
337 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
343 * At the moment, this will only work if the DB user has the PROCESS privilege
347 if ( !is_null( $this->mFakeSlaveLag
) ) {
348 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
349 return $this->mFakeSlaveLag
;
351 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
355 # Find slave SQL thread
356 foreach( $res as $row ) {
357 /* This should work for most situations - when default db
358 * for thread is not specified, it had no events executed,
359 * and therefore it doesn't know yet how lagged it is.
361 * Relay log I/O thread does not select databases.
363 if ( $row->User
== 'system user' &&
364 $row->State
!= 'Waiting for master to send event' &&
365 $row->State
!= 'Connecting to master' &&
366 $row->State
!= 'Queueing master event to the relay log' &&
367 $row->State
!= 'Waiting for master update' &&
368 $row->State
!= 'Requesting binlog dump' &&
369 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
370 $row->State
!= 'Reconnecting after a failed master event read' &&
371 $row->State
!= 'Registering slave on master'
373 # This is it, return the time (except -ve)
374 if ( $row->Time
> 0x7fffffff ) {
384 function getServerVersion() {
385 return mysql_get_server_info( $this->mConn
);
388 function useIndexClause( $index ) {
389 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
392 function lowPriorityOption() {
393 return 'LOW_PRIORITY';
396 public static function getSoftwareLink() {
397 return '[http://www.mysql.com/ MySQL]';
400 function standardSelectDistinct() {
404 public function setTimeout( $timeout ) {
405 $this->query( "SET net_read_timeout=$timeout" );
406 $this->query( "SET net_write_timeout=$timeout" );
409 public function lock( $lockName, $method, $timeout = 5 ) {
410 $lockName = $this->addQuotes( $lockName );
411 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
412 $row = $this->fetchObject( $result );
414 if( $row->lockstatus
== 1 ) {
417 wfDebug( __METHOD__
." failed to acquire lock\n" );
423 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
425 public function unlock( $lockName, $method ) {
426 $lockName = $this->addQuotes( $lockName );
427 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
428 $row = $this->fetchObject( $result );
429 return $row->lockstatus
;
432 public function lockTables( $read, $write, $method, $lowPriority = true ) {
435 foreach( $write as $table ) {
436 $tbl = $this->tableName( $table ) .
437 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
441 foreach( $read as $table ) {
442 $items[] = $this->tableName( $table ) . ' READ';
444 $sql = "LOCK TABLES " . implode( ',', $items );
445 $this->query( $sql, $method );
448 public function unlockTables( $method ) {
449 $this->query( "UNLOCK TABLES", $method );
453 * Get search engine class. All subclasses of this
454 * need to implement this if they wish to use searching.
458 public function getSearchEngine() {
459 return 'SearchMySQL';
462 public function setBigSelects( $value = true ) {
463 if ( $value === 'default' ) {
464 if ( $this->mDefaultBigSelects
=== null ) {
465 # Function hasn't been called before so it must already be set to the default
468 $value = $this->mDefaultBigSelects
;
470 } elseif ( $this->mDefaultBigSelects
=== null ) {
471 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
473 $encValue = $value ?
'1' : '0';
474 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
479 * Determines if the last failure was due to a deadlock
481 function wasDeadlock() {
482 return $this->lastErrno() == 1213;
486 * Determines if the last query error was something that should be dealt
487 * with by pinging the connection and reissuing the query
489 function wasErrorReissuable() {
490 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
494 * Determines if the last failure was due to the database being read-only.
496 function wasReadOnlyError() {
497 return $this->lastErrno() == 1223 ||
498 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
501 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
502 $tmp = $temporary ?
'TEMPORARY ' : '';
503 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
504 # Hack for MySQL versions < 4.1, which don't support
505 # "CREATE TABLE ... LIKE". Note that
506 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
507 # would not create the indexes we need....
509 # Note that we don't bother changing around the prefixes here be-
510 # cause we know we're using MySQL anyway.
512 $res = $this->query( "SHOW CREATE TABLE $oldName" );
513 $row = $this->fetchRow( $res );
515 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
516 "CREATE $tmp TABLE `$newName`", $oldQuery );
517 if ($oldQuery === $query) {
518 # Couldn't do replacement
519 throw new MWException( "could not create temporary table $newName" );
522 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
524 $this->query( $query, $fname );
530 * Legacy support: Database == DatabaseMysql
532 class Database
extends DatabaseMysql
{}
538 class MySQLField
implements Field
{
539 private $name, $tablename, $default, $max_length, $nullable,
540 $is_pk, $is_unique, $is_multiple, $is_key, $type;
542 function __construct ( $info ) {
543 $this->name
= $info->name
;
544 $this->tablename
= $info->table
;
545 $this->default = $info->def
;
546 $this->max_length
= $info->max_length
;
547 $this->nullable
= !$info->not_null
;
548 $this->is_pk
= $info->primary_key
;
549 $this->is_unique
= $info->unique_key
;
550 $this->is_multiple
= $info->multiple_key
;
551 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
552 $this->type
= $info->type
;
559 function tableName() {
560 return $this->tableName
;
567 function isNullable() {
568 return $this->nullable
;
571 function defaultValue() {
572 return $this->default;
576 return $this->is_key
;
579 function isMultipleKey() {
580 return $this->is_multiple
;
584 class MySQLMasterPos
{
587 function __construct( $file, $pos ) {
592 function __toString() {
593 return "{$this->file}/{$this->pos}";