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;
55 wfProfileIn("dbconnect-$server");
57 # The kernel's default SYN retransmission period is far too slow for us,
58 # so we use a short timeout plus a manual retry. Retrying means that a small
59 # but finite rate of SYN packet loss won't cause user-visible errors.
61 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
66 $this->installErrorHandler();
67 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
71 if ( $this->mFlags
& DBO_PERSISTENT
) {
72 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
74 # Create a new connection...
75 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
77 #if ( $this->mConn === false ) {
79 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
82 $phpError = $this->restoreErrorHandler();
83 # Always log connection errors
84 if ( !$this->mConn
) {
85 $error = $this->lastError();
89 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
90 wfDebug( "DB connection error\n" );
91 wfDebug( "Server: $server, User: $user, Password: " .
92 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
95 wfProfileOut("dbconnect-$server");
97 if ( $dbName != '' && $this->mConn
!== false ) {
98 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
100 $error = "Error selecting database $dbName on server {$this->mServer} " .
101 "from client host " . wfHostname() . "\n";
102 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
107 $success = (bool)$this->mConn
;
111 $version = $this->getServerVersion();
112 if ( version_compare( $version, '4.1' ) >= 0 ) {
113 // Tell the server we're communicating with it in UTF-8.
114 // This may engage various charset conversions.
117 $this->query( 'SET NAMES utf8', __METHOD__
);
119 $this->query( 'SET NAMES binary', __METHOD__
);
121 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
123 if ( is_string( $wgSQLMode ) ) {
124 $mode = $this->addQuotes( $wgSQLMode );
125 $this->query( "SET sql_mode = $mode", __METHOD__
);
129 // Turn off strict mode if it is on
131 $this->reportConnectionError( $phpError );
134 $this->mOpened
= $success;
135 wfProfileOut( __METHOD__
);
140 $this->mOpened
= false;
141 if ( $this->mConn
) {
142 if ( $this->trxLevel() ) {
145 return mysql_close( $this->mConn
);
151 function freeResult( $res ) {
152 if ( $res instanceof ResultWrapper
) {
155 if ( !@/**/mysql_free_result( $res ) ) {
156 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
160 function fetchObject( $res ) {
161 if ( $res instanceof ResultWrapper
) {
164 @/**/$row = mysql_fetch_object( $res );
165 if( $this->lastErrno() ) {
166 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
171 function fetchRow( $res ) {
172 if ( $res instanceof ResultWrapper
) {
175 @/**/$row = mysql_fetch_array( $res );
176 if ( $this->lastErrno() ) {
177 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
182 function numRows( $res ) {
183 if ( $res instanceof ResultWrapper
) {
186 @/**/$n = mysql_num_rows( $res );
187 if( $this->lastErrno() ) {
188 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
193 function numFields( $res ) {
194 if ( $res instanceof ResultWrapper
) {
197 return mysql_num_fields( $res );
200 function fieldName( $res, $n ) {
201 if ( $res instanceof ResultWrapper
) {
204 return mysql_field_name( $res, $n );
207 function insertId() { return mysql_insert_id( $this->mConn
); }
209 function dataSeek( $res, $row ) {
210 if ( $res instanceof ResultWrapper
) {
213 return mysql_data_seek( $res, $row );
216 function lastErrno() {
217 if ( $this->mConn
) {
218 return mysql_errno( $this->mConn
);
220 return mysql_errno();
224 function lastError() {
225 if ( $this->mConn
) {
226 # Even if it's non-zero, it can still be invalid
227 wfSuppressWarnings();
228 $error = mysql_error( $this->mConn
);
230 $error = mysql_error();
234 $error = mysql_error();
237 $error .= ' (' . $this->mServer
. ')';
242 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
245 * Estimate rows in dataset
246 * Returns estimated count, based on EXPLAIN output
247 * Takes same arguments as Database::select()
249 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
250 $options['EXPLAIN'] = true;
251 $res = $this->select( $table, $vars, $conds, $fname, $options );
252 if ( $res === false ) {
255 if ( !$this->numRows( $res ) ) {
260 foreach ( $res as $plan ) {
261 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
266 function fieldInfo( $table, $field ) {
267 $table = $this->tableName( $table );
268 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
272 $n = mysql_num_fields( $res->result
);
273 for( $i = 0; $i < $n; $i++
) {
274 $meta = mysql_fetch_field( $res->result
, $i );
275 if( $field == $meta->name
) {
276 return new MySQLField($meta);
283 * Get information about an index into an object
284 * Returns false if the index does not exist
286 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
287 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
288 # SHOW INDEX should work for 3.x and up:
289 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
290 $table = $this->tableName( $table );
291 $index = $this->indexName( $index );
292 $sql = 'SHOW INDEX FROM ' . $table;
293 $res = $this->query( $sql, $fname );
301 foreach ( $res as $row ) {
302 if ( $row->Key_name
== $index ) {
307 return empty( $result ) ?
false : $result;
310 function selectDB( $db ) {
311 $this->mDBname
= $db;
312 return mysql_select_db( $db, $this->mConn
);
315 function strencode( $s ) {
316 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
318 if($sQuoted === false) {
320 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
326 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
328 public function addIdentifierQuotes( $s ) {
329 return "`" . $this->strencode( $s ) . "`";
333 $ping = mysql_ping( $this->mConn
);
338 mysql_close( $this->mConn
);
339 $this->mOpened
= false;
340 $this->mConn
= false;
341 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
347 * At the moment, this will only work if the DB user has the PROCESS privilege
351 if ( !is_null( $this->mFakeSlaveLag
) ) {
352 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
353 return $this->mFakeSlaveLag
;
355 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
359 # Find slave SQL thread
360 foreach( $res as $row ) {
361 /* This should work for most situations - when default db
362 * for thread is not specified, it had no events executed,
363 * and therefore it doesn't know yet how lagged it is.
365 * Relay log I/O thread does not select databases.
367 if ( $row->User
== 'system user' &&
368 $row->State
!= 'Waiting for master to send event' &&
369 $row->State
!= 'Connecting to master' &&
370 $row->State
!= 'Queueing master event to the relay log' &&
371 $row->State
!= 'Waiting for master update' &&
372 $row->State
!= 'Requesting binlog dump' &&
373 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
374 $row->State
!= 'Reconnecting after a failed master event read' &&
375 $row->State
!= 'Registering slave on master'
377 # This is it, return the time (except -ve)
378 if ( $row->Time
> 0x7fffffff ) {
388 function getServerVersion() {
389 return mysql_get_server_info( $this->mConn
);
392 function useIndexClause( $index ) {
393 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
396 function lowPriorityOption() {
397 return 'LOW_PRIORITY';
400 public static function getSoftwareLink() {
401 return '[http://www.mysql.com/ MySQL]';
404 function standardSelectDistinct() {
408 public function setTimeout( $timeout ) {
409 $this->query( "SET net_read_timeout=$timeout" );
410 $this->query( "SET net_write_timeout=$timeout" );
413 public function lock( $lockName, $method, $timeout = 5 ) {
414 $lockName = $this->addQuotes( $lockName );
415 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
416 $row = $this->fetchObject( $result );
418 if( $row->lockstatus
== 1 ) {
421 wfDebug( __METHOD__
." failed to acquire lock\n" );
427 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
429 public function unlock( $lockName, $method ) {
430 $lockName = $this->addQuotes( $lockName );
431 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
432 $row = $this->fetchObject( $result );
433 return $row->lockstatus
;
436 public function lockTables( $read, $write, $method, $lowPriority = true ) {
439 foreach( $write as $table ) {
440 $tbl = $this->tableName( $table ) .
441 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
445 foreach( $read as $table ) {
446 $items[] = $this->tableName( $table ) . ' READ';
448 $sql = "LOCK TABLES " . implode( ',', $items );
449 $this->query( $sql, $method );
452 public function unlockTables( $method ) {
453 $this->query( "UNLOCK TABLES", $method );
457 * Get search engine class. All subclasses of this
458 * need to implement this if they wish to use searching.
462 public function getSearchEngine() {
463 return 'SearchMySQL';
466 public function setBigSelects( $value = true ) {
467 if ( $value === 'default' ) {
468 if ( $this->mDefaultBigSelects
=== null ) {
469 # Function hasn't been called before so it must already be set to the default
472 $value = $this->mDefaultBigSelects
;
474 } elseif ( $this->mDefaultBigSelects
=== null ) {
475 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
477 $encValue = $value ?
'1' : '0';
478 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
482 * Determines if the last failure was due to a deadlock
484 function wasDeadlock() {
485 return $this->lastErrno() == 1213;
489 * Determines if the last query error was something that should be dealt
490 * with by pinging the connection and reissuing the query
492 function wasErrorReissuable() {
493 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
497 * Determines if the last failure was due to the database being read-only.
499 function wasReadOnlyError() {
500 return $this->lastErrno() == 1223 ||
501 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
504 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
505 $tmp = $temporary ?
'TEMPORARY ' : '';
506 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
507 # Hack for MySQL versions < 4.1, which don't support
508 # "CREATE TABLE ... LIKE". Note that
509 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
510 # would not create the indexes we need....
512 # Note that we don't bother changing around the prefixes here be-
513 # cause we know we're using MySQL anyway.
515 $res = $this->query( "SHOW CREATE TABLE $oldName" );
516 $row = $this->fetchRow( $res );
518 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
519 "CREATE $tmp TABLE `$newName`", $oldQuery );
520 if ($oldQuery === $query) {
521 # Couldn't do replacement
522 throw new MWException( "could not create temporary table $newName" );
525 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
527 $this->query( $query, $fname );
531 * List all tables on the database
533 * @param $prefix Only show tables with this prefix, e.g. mw_
534 * @param $fname String: calling function name
536 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
537 $result = $this->query( "SHOW TABLES", $fname);
541 foreach( $result as $table ) {
542 $vars = get_object_vars($table);
543 $table = array_pop( $vars );
545 if( empty( $prefix ) ||
strpos( $table, $prefix ) === 0 ) {
546 $endArray[] = $table;
553 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
554 if( !$this->tableExists( $tableName ) ) {
557 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
560 protected function getDefaultSchemaVars() {
561 $vars = parent
::getDefaultSchemaVars();
562 $vars['wgDBTableOptions'] = $GLOBALS['wgDBTableOptions'];
568 * Legacy support: Database == DatabaseMysql
570 class Database
extends DatabaseMysql
{}
576 class MySQLField
implements Field
{
577 private $name, $tablename, $default, $max_length, $nullable,
578 $is_pk, $is_unique, $is_multiple, $is_key, $type;
580 function __construct ( $info ) {
581 $this->name
= $info->name
;
582 $this->tablename
= $info->table
;
583 $this->default = $info->def
;
584 $this->max_length
= $info->max_length
;
585 $this->nullable
= !$info->not_null
;
586 $this->is_pk
= $info->primary_key
;
587 $this->is_unique
= $info->unique_key
;
588 $this->is_multiple
= $info->multiple_key
;
589 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
590 $this->type
= $info->type
;
597 function tableName() {
598 return $this->tableName
;
605 function isNullable() {
606 return $this->nullable
;
609 function defaultValue() {
610 return $this->default;
614 return $this->is_key
;
617 function isMultipleKey() {
618 return $this->is_multiple
;
622 class MySQLMasterPos
{
625 function __construct( $file, $pos ) {
630 function __toString() {
631 return "{$this->file}/{$this->pos}";