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
{
25 protected function doQuery( $sql ) {
26 if( $this->bufferResults() ) {
27 $ret = mysql_query( $sql, $this->mConn
);
29 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
34 function open( $server, $user, $password, $dbName ) {
35 global $wgAllDBsAreLocalhost;
36 wfProfileIn( __METHOD__
);
38 # Load mysql.so if we don't have it
42 # Otherwise we get a suppressed fatal error, which is very hard to track down
43 if ( !function_exists( 'mysql_connect' ) ) {
44 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
47 # Debugging hack -- fake cluster
48 if ( $wgAllDBsAreLocalhost ) {
49 $realServer = 'localhost';
51 $realServer = $server;
54 $this->mServer
= $server;
56 $this->mPassword
= $password;
57 $this->mDBname
= $dbName;
59 wfProfileIn("dbconnect-$server");
61 # The kernel's default SYN retransmission period is far too slow for us,
62 # so we use a short timeout plus a manual retry. Retrying means that a small
63 # but finite rate of SYN packet loss won't cause user-visible errors.
65 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
70 $this->installErrorHandler();
71 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
75 if ( $this->mFlags
& DBO_PERSISTENT
) {
76 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
78 # Create a new connection...
79 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
81 #if ( $this->mConn === false ) {
83 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
86 $phpError = $this->restoreErrorHandler();
87 # Always log connection errors
88 if ( !$this->mConn
) {
89 $error = $this->lastError();
93 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
94 wfDebug( "DB connection error\n" );
95 wfDebug( "Server: $server, User: $user, Password: " .
96 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
99 wfProfileOut("dbconnect-$server");
101 if ( $dbName != '' && $this->mConn
!== false ) {
102 wfSuppressWarnings();
103 $success = mysql_select_db( $dbName, $this->mConn
);
106 $error = "Error selecting database $dbName on server {$this->mServer} " .
107 "from client host " . wfHostname() . "\n";
108 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
113 $success = (bool)$this->mConn
;
117 $version = $this->getServerVersion();
118 if ( version_compare( $version, '4.1' ) >= 0 ) {
119 // Tell the server we're communicating with it in UTF-8.
120 // This may engage various charset conversions.
123 $this->query( 'SET NAMES utf8', __METHOD__
);
125 $this->query( 'SET NAMES binary', __METHOD__
);
127 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
129 if ( is_string( $wgSQLMode ) ) {
130 $mode = $this->addQuotes( $wgSQLMode );
131 $this->query( "SET sql_mode = $mode", __METHOD__
);
135 // Turn off strict mode if it is on
137 $this->reportConnectionError( $phpError );
140 $this->mOpened
= $success;
141 wfProfileOut( __METHOD__
);
149 $this->mOpened
= false;
150 if ( $this->mConn
) {
151 if ( $this->trxLevel() ) {
154 return mysql_close( $this->mConn
);
160 function freeResult( $res ) {
161 if ( $res instanceof ResultWrapper
) {
164 wfSuppressWarnings();
165 $ok = mysql_free_result( $res );
168 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
172 function fetchObject( $res ) {
173 if ( $res instanceof ResultWrapper
) {
176 wfSuppressWarnings();
177 $row = mysql_fetch_object( $res );
179 if( $this->lastErrno() ) {
180 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
185 function fetchRow( $res ) {
186 if ( $res instanceof ResultWrapper
) {
189 wfSuppressWarnings();
190 $row = mysql_fetch_array( $res );
192 if ( $this->lastErrno() ) {
193 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
199 * @throws DBUnexpectedError
203 function numRows( $res ) {
204 if ( $res instanceof ResultWrapper
) {
207 wfSuppressWarnings();
208 $n = mysql_num_rows( $res );
210 if( $this->lastErrno() ) {
211 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
220 function numFields( $res ) {
221 if ( $res instanceof ResultWrapper
) {
224 return mysql_num_fields( $res );
232 function fieldName( $res, $n ) {
233 if ( $res instanceof ResultWrapper
) {
236 return mysql_field_name( $res, $n );
242 function insertId() {
243 return mysql_insert_id( $this->mConn
);
246 function dataSeek( $res, $row ) {
247 if ( $res instanceof ResultWrapper
) {
250 return mysql_data_seek( $res, $row );
253 function lastErrno() {
254 if ( $this->mConn
) {
255 return mysql_errno( $this->mConn
);
257 return mysql_errno();
261 function lastError() {
262 if ( $this->mConn
) {
263 # Even if it's non-zero, it can still be invalid
264 wfSuppressWarnings();
265 $error = mysql_error( $this->mConn
);
267 $error = mysql_error();
271 $error = mysql_error();
274 $error .= ' (' . $this->mServer
. ')';
282 function affectedRows() {
283 return mysql_affected_rows( $this->mConn
);
286 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
287 return $this->nativeReplace( $table, $rows, $fname );
291 * Estimate rows in dataset
292 * Returns estimated count, based on EXPLAIN output
293 * Takes same arguments as Database::select()
297 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
298 $options['EXPLAIN'] = true;
299 $res = $this->select( $table, $vars, $conds, $fname, $options );
300 if ( $res === false ) {
303 if ( !$this->numRows( $res ) ) {
308 foreach ( $res as $plan ) {
309 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
315 * @param $table string
316 * @param $field string
317 * @return bool|MySQLField
319 function fieldInfo( $table, $field ) {
320 $table = $this->tableName( $table );
321 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
325 $n = mysql_num_fields( $res->result
);
326 for( $i = 0; $i < $n; $i++
) {
327 $meta = mysql_fetch_field( $res->result
, $i );
328 if( $field == $meta->name
) {
329 return new MySQLField($meta);
336 * Get information about an index into an object
337 * Returns false if the index does not exist
339 * @return false|array
341 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
342 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
343 # SHOW INDEX should work for 3.x and up:
344 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
345 $table = $this->tableName( $table );
346 $index = $this->indexName( $index );
347 $sql = 'SHOW INDEX FROM ' . $table;
348 $res = $this->query( $sql, $fname );
356 foreach ( $res as $row ) {
357 if ( $row->Key_name
== $index ) {
362 return empty( $result ) ?
false : $result;
369 function selectDB( $db ) {
370 $this->mDBname
= $db;
371 return mysql_select_db( $db, $this->mConn
);
379 function strencode( $s ) {
380 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
382 if($sQuoted === false) {
384 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
390 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
396 public function addIdentifierQuotes( $s ) {
397 return "`" . $this->strencode( $s ) . "`";
401 * @param $name string
404 public function isQuotedIdentifier( $name ) {
405 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
412 $ping = mysql_ping( $this->mConn
);
417 mysql_close( $this->mConn
);
418 $this->mOpened
= false;
419 $this->mConn
= false;
420 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
427 * On MySQL 4.1.9 and later, this will do a SHOW SLAVE STATUS. On earlier
428 * versions of MySQL, it uses SHOW PROCESSLIST, which requires the PROCESS
434 if ( !is_null( $this->mFakeSlaveLag
) ) {
435 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
436 return $this->mFakeSlaveLag
;
439 if ( version_compare( $this->getServerVersion(), '4.1.9', '>=' ) ) {
440 return $this->getLagFromSlaveStatus();
442 return $this->getLagFromProcesslist();
449 function getLagFromSlaveStatus() {
450 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
454 $row = $res->fetchObject();
458 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
461 return intval( $row->Seconds_Behind_Master
);
468 function getLagFromProcesslist() {
469 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
473 # Find slave SQL thread
474 foreach( $res as $row ) {
475 /* This should work for most situations - when default db
476 * for thread is not specified, it had no events executed,
477 * and therefore it doesn't know yet how lagged it is.
479 * Relay log I/O thread does not select databases.
481 if ( $row->User
== 'system user' &&
482 $row->State
!= 'Waiting for master to send event' &&
483 $row->State
!= 'Connecting to master' &&
484 $row->State
!= 'Queueing master event to the relay log' &&
485 $row->State
!= 'Waiting for master update' &&
486 $row->State
!= 'Requesting binlog dump' &&
487 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
488 $row->State
!= 'Reconnecting after a failed master event read' &&
489 $row->State
!= 'Registering slave on master'
491 # This is it, return the time (except -ve)
492 if ( $row->Time
> 0x7fffffff ) {
503 * Wait for the slave to catch up to a given master position.
505 * @param $pos DBMasterPos object
506 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
508 function masterPosWait( DBMasterPos
$pos, $timeout ) {
509 $fname = 'DatabaseBase::masterPosWait';
510 wfProfileIn( $fname );
512 # Commit any open transactions
513 if ( $this->mTrxLevel
) {
517 if ( !is_null( $this->mFakeSlaveLag
) ) {
518 $status = parent
::masterPosWait( $pos, $timeout );
519 wfProfileOut( $fname );
523 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
524 $encFile = $this->addQuotes( $pos->file
);
525 $encPos = intval( $pos->pos
);
526 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
527 $res = $this->doQuery( $sql );
529 if ( $res && $row = $this->fetchRow( $res ) ) {
530 wfProfileOut( $fname );
533 wfProfileOut( $fname );
539 * Get the position of the master from SHOW SLAVE STATUS
541 * @return MySQLMasterPos|false
543 function getSlavePos() {
544 if ( !is_null( $this->mFakeSlaveLag
) ) {
545 return parent
::getSlavePos();
548 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
549 $row = $this->fetchObject( $res );
552 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
553 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
560 * Get the position of the master from SHOW MASTER STATUS
562 * @return MySQLMasterPos|false
564 function getMasterPos() {
565 if ( $this->mFakeMaster
) {
566 return parent
::getMasterPos();
569 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
570 $row = $this->fetchObject( $res );
573 return new MySQLMasterPos( $row->File
, $row->Position
);
582 function getServerVersion() {
583 return mysql_get_server_info( $this->mConn
);
590 function useIndexClause( $index ) {
591 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
597 function lowPriorityOption() {
598 return 'LOW_PRIORITY';
604 public static function getSoftwareLink() {
605 return '[http://www.mysql.com/ MySQL]';
608 function standardSelectDistinct() {
612 public function setTimeout( $timeout ) {
613 $this->query( "SET net_read_timeout=$timeout" );
614 $this->query( "SET net_write_timeout=$timeout" );
617 public function lock( $lockName, $method, $timeout = 5 ) {
618 $lockName = $this->addQuotes( $lockName );
619 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
620 $row = $this->fetchObject( $result );
622 if( $row->lockstatus
== 1 ) {
625 wfDebug( __METHOD__
." failed to acquire lock\n" );
631 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
633 public function unlock( $lockName, $method ) {
634 $lockName = $this->addQuotes( $lockName );
635 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
636 $row = $this->fetchObject( $result );
637 return $row->lockstatus
;
640 public function lockTables( $read, $write, $method, $lowPriority = true ) {
643 foreach( $write as $table ) {
644 $tbl = $this->tableName( $table ) .
645 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
649 foreach( $read as $table ) {
650 $items[] = $this->tableName( $table ) . ' READ';
652 $sql = "LOCK TABLES " . implode( ',', $items );
653 $this->query( $sql, $method );
656 public function unlockTables( $method ) {
657 $this->query( "UNLOCK TABLES", $method );
661 * Get search engine class. All subclasses of this
662 * need to implement this if they wish to use searching.
666 public function getSearchEngine() {
667 return 'SearchMySQL';
670 public function setBigSelects( $value = true ) {
671 if ( $value === 'default' ) {
672 if ( $this->mDefaultBigSelects
=== null ) {
673 # Function hasn't been called before so it must already be set to the default
676 $value = $this->mDefaultBigSelects
;
678 } elseif ( $this->mDefaultBigSelects
=== null ) {
679 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
681 $encValue = $value ?
'1' : '0';
682 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
686 * DELETE where the condition is a join. MySql uses multi-table deletes.
688 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
690 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
693 $delTable = $this->tableName( $delTable );
694 $joinTable = $this->tableName( $joinTable );
695 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
697 if ( $conds != '*' ) {
698 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
701 return $this->query( $sql, $fname );
705 * Determines if the last failure was due to a deadlock
709 function wasDeadlock() {
710 return $this->lastErrno() == 1213;
714 * Determines if the last query error was something that should be dealt
715 * with by pinging the connection and reissuing the query
719 function wasErrorReissuable() {
720 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
724 * Determines if the last failure was due to the database being read-only.
728 function wasReadOnlyError() {
729 return $this->lastErrno() == 1223 ||
730 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
733 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
734 $tmp = $temporary ?
'TEMPORARY ' : '';
735 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
736 # Hack for MySQL versions < 4.1, which don't support
737 # "CREATE TABLE ... LIKE". Note that
738 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
739 # would not create the indexes we need....
741 # Note that we don't bother changing around the prefixes here be-
742 # cause we know we're using MySQL anyway.
744 $res = $this->query( 'SHOW CREATE TABLE ' . $this->addIdentifierQuotes( $oldName ) );
745 $row = $this->fetchRow( $res );
747 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
748 "CREATE $tmp TABLE " . $this->addIdentifierQuotes( $newName ), $oldQuery );
749 if ($oldQuery === $query) {
750 # Couldn't do replacement
751 throw new MWException( "could not create temporary table $newName" );
754 $newName = $this->addIdentifierQuotes( $newName );
755 $oldName = $this->addIdentifierQuotes( $oldName );
756 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
758 $this->query( $query, $fname );
762 * List all tables on the database
764 * @param $prefix Only show tables with this prefix, e.g. mw_
765 * @param $fname String: calling function name
767 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
768 $result = $this->query( "SHOW TABLES", $fname);
772 foreach( $result as $table ) {
773 $vars = get_object_vars($table);
774 $table = array_pop( $vars );
776 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
777 $endArray[] = $table;
786 * @param $fName string
787 * @return bool|ResultWrapper
789 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
790 if( !$this->tableExists( $tableName ) ) {
793 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
799 protected function getDefaultSchemaVars() {
800 $vars = parent
::getDefaultSchemaVars();
801 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
806 * Get status information from SHOW STATUS in an associative array
810 function getMysqlStatus( $which = "%" ) {
811 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
814 foreach ( $res as $row ) {
815 $status[$row->Variable_name
] = $row->Value
;
824 * Legacy support: Database == DatabaseMysql
826 * @deprecated in 1.16
828 class Database
extends DatabaseMysql
{}
834 class MySQLField
implements Field
{
835 private $name, $tablename, $default, $max_length, $nullable,
836 $is_pk, $is_unique, $is_multiple, $is_key, $type;
838 function __construct ( $info ) {
839 $this->name
= $info->name
;
840 $this->tablename
= $info->table
;
841 $this->default = $info->def
;
842 $this->max_length
= $info->max_length
;
843 $this->nullable
= !$info->not_null
;
844 $this->is_pk
= $info->primary_key
;
845 $this->is_unique
= $info->unique_key
;
846 $this->is_multiple
= $info->multiple_key
;
847 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
848 $this->type
= $info->type
;
861 function tableName() {
862 return $this->tableName
;
872 function isNullable() {
873 return $this->nullable
;
876 function defaultValue() {
877 return $this->default;
884 return $this->is_key
;
890 function isMultipleKey() {
891 return $this->is_multiple
;
895 class MySQLMasterPos
implements DBMasterPos
{
898 function __construct( $file, $pos ) {
903 function __toString() {
904 return "{$this->file}/{$this->pos}";