dd8afd683fe0e60e556eac5c2115b2c415314fd5
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 // Tell the server we're communicating with it in UTF-8.
118 // This may engage various charset conversions.
121 $this->query( 'SET NAMES utf8', __METHOD__
);
123 $this->query( 'SET NAMES binary', __METHOD__
);
125 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
127 if ( is_string( $wgSQLMode ) ) {
128 $mode = $this->addQuotes( $wgSQLMode );
129 $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__
);
146 $this->mOpened
= false;
147 if ( $this->mConn
) {
148 if ( $this->trxLevel() ) {
151 return mysql_close( $this->mConn
);
157 function freeResult( $res ) {
158 if ( $res instanceof ResultWrapper
) {
161 wfSuppressWarnings();
162 $ok = mysql_free_result( $res );
165 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
169 function fetchObject( $res ) {
170 if ( $res instanceof ResultWrapper
) {
173 wfSuppressWarnings();
174 $row = mysql_fetch_object( $res );
176 if( $this->lastErrno() ) {
177 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
182 function fetchRow( $res ) {
183 if ( $res instanceof ResultWrapper
) {
186 wfSuppressWarnings();
187 $row = mysql_fetch_array( $res );
189 if ( $this->lastErrno() ) {
190 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
196 * @throws DBUnexpectedError
200 function numRows( $res ) {
201 if ( $res instanceof ResultWrapper
) {
204 wfSuppressWarnings();
205 $n = mysql_num_rows( $res );
207 if( $this->lastErrno() ) {
208 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
217 function numFields( $res ) {
218 if ( $res instanceof ResultWrapper
) {
221 return mysql_num_fields( $res );
229 function fieldName( $res, $n ) {
230 if ( $res instanceof ResultWrapper
) {
233 return mysql_field_name( $res, $n );
239 function insertId() {
240 return mysql_insert_id( $this->mConn
);
243 function dataSeek( $res, $row ) {
244 if ( $res instanceof ResultWrapper
) {
247 return mysql_data_seek( $res, $row );
250 function lastErrno() {
251 if ( $this->mConn
) {
252 return mysql_errno( $this->mConn
);
254 return mysql_errno();
258 function lastError() {
259 if ( $this->mConn
) {
260 # Even if it's non-zero, it can still be invalid
261 wfSuppressWarnings();
262 $error = mysql_error( $this->mConn
);
264 $error = mysql_error();
268 $error = mysql_error();
271 $error .= ' (' . $this->mServer
. ')';
279 function affectedRows() {
280 return mysql_affected_rows( $this->mConn
);
283 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
284 return $this->nativeReplace( $table, $rows, $fname );
288 * Estimate rows in dataset
289 * Returns estimated count, based on EXPLAIN output
290 * Takes same arguments as Database::select()
294 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
295 $options['EXPLAIN'] = true;
296 $res = $this->select( $table, $vars, $conds, $fname, $options );
297 if ( $res === false ) {
300 if ( !$this->numRows( $res ) ) {
305 foreach ( $res as $plan ) {
306 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
312 * @param $table string
313 * @param $field string
314 * @return bool|MySQLField
316 function fieldInfo( $table, $field ) {
317 $table = $this->tableName( $table );
318 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
322 $n = mysql_num_fields( $res->result
);
323 for( $i = 0; $i < $n; $i++
) {
324 $meta = mysql_fetch_field( $res->result
, $i );
325 if( $field == $meta->name
) {
326 return new MySQLField($meta);
333 * Get information about an index into an object
334 * Returns false if the index does not exist
336 * @return false|array
338 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
339 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
340 # SHOW INDEX should work for 3.x and up:
341 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
342 $table = $this->tableName( $table );
343 $index = $this->indexName( $index );
344 $sql = 'SHOW INDEX FROM ' . $table;
345 $res = $this->query( $sql, $fname );
353 foreach ( $res as $row ) {
354 if ( $row->Key_name
== $index ) {
359 return empty( $result ) ?
false : $result;
366 function selectDB( $db ) {
367 $this->mDBname
= $db;
368 return mysql_select_db( $db, $this->mConn
);
376 function strencode( $s ) {
377 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
379 if($sQuoted === false) {
381 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
387 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
393 public function addIdentifierQuotes( $s ) {
394 return "`" . $this->strencode( $s ) . "`";
398 * @param $name string
401 public function isQuotedIdentifier( $name ) {
402 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
409 $ping = mysql_ping( $this->mConn
);
414 mysql_close( $this->mConn
);
415 $this->mOpened
= false;
416 $this->mConn
= false;
417 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
424 * On MySQL 4.1.9 and later, this will do a SHOW SLAVE STATUS
429 if ( !is_null( $this->mFakeSlaveLag
) ) {
430 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
431 return $this->mFakeSlaveLag
;
434 return $this->getLagFromSlaveStatus();
440 function getLagFromSlaveStatus() {
441 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
445 $row = $res->fetchObject();
449 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
452 return intval( $row->Seconds_Behind_Master
);
457 * @deprecated in 1.19, use getLagFromSlaveStatus
461 function getLagFromProcesslist() {
462 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
466 # Find slave SQL thread
467 foreach( $res as $row ) {
468 /* This should work for most situations - when default db
469 * for thread is not specified, it had no events executed,
470 * and therefore it doesn't know yet how lagged it is.
472 * Relay log I/O thread does not select databases.
474 if ( $row->User
== 'system user' &&
475 $row->State
!= 'Waiting for master to send event' &&
476 $row->State
!= 'Connecting to master' &&
477 $row->State
!= 'Queueing master event to the relay log' &&
478 $row->State
!= 'Waiting for master update' &&
479 $row->State
!= 'Requesting binlog dump' &&
480 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
481 $row->State
!= 'Reconnecting after a failed master event read' &&
482 $row->State
!= 'Registering slave on master'
484 # This is it, return the time (except -ve)
485 if ( $row->Time
> 0x7fffffff ) {
496 * Wait for the slave to catch up to a given master position.
498 * @param $pos DBMasterPos object
499 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
501 function masterPosWait( DBMasterPos
$pos, $timeout ) {
502 $fname = 'DatabaseBase::masterPosWait';
503 wfProfileIn( $fname );
505 # Commit any open transactions
506 if ( $this->mTrxLevel
) {
510 if ( !is_null( $this->mFakeSlaveLag
) ) {
511 $status = parent
::masterPosWait( $pos, $timeout );
512 wfProfileOut( $fname );
516 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
517 $encFile = $this->addQuotes( $pos->file
);
518 $encPos = intval( $pos->pos
);
519 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
520 $res = $this->doQuery( $sql );
522 if ( $res && $row = $this->fetchRow( $res ) ) {
523 wfProfileOut( $fname );
526 wfProfileOut( $fname );
532 * Get the position of the master from SHOW SLAVE STATUS
534 * @return MySQLMasterPos|false
536 function getSlavePos() {
537 if ( !is_null( $this->mFakeSlaveLag
) ) {
538 return parent
::getSlavePos();
541 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
542 $row = $this->fetchObject( $res );
545 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
546 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
553 * Get the position of the master from SHOW MASTER STATUS
555 * @return MySQLMasterPos|false
557 function getMasterPos() {
558 if ( $this->mFakeMaster
) {
559 return parent
::getMasterPos();
562 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
563 $row = $this->fetchObject( $res );
566 return new MySQLMasterPos( $row->File
, $row->Position
);
575 function getServerVersion() {
576 return mysql_get_server_info( $this->mConn
);
583 function useIndexClause( $index ) {
584 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
590 function lowPriorityOption() {
591 return 'LOW_PRIORITY';
597 public static function getSoftwareLink() {
598 return '[http://www.mysql.com/ MySQL]';
601 function standardSelectDistinct() {
605 public function setSessionOptions( array $options ) {
606 if ( isset( $options['connTimeout'] ) ) {
607 $timeout = (int)$options['connTimeout'];
608 $this->query( "SET net_read_timeout=$timeout" );
609 $this->query( "SET net_write_timeout=$timeout" );
613 public function lock( $lockName, $method, $timeout = 5 ) {
614 $lockName = $this->addQuotes( $lockName );
615 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
616 $row = $this->fetchObject( $result );
618 if( $row->lockstatus
== 1 ) {
621 wfDebug( __METHOD__
." failed to acquire lock\n" );
627 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
629 public function unlock( $lockName, $method ) {
630 $lockName = $this->addQuotes( $lockName );
631 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
632 $row = $this->fetchObject( $result );
633 return $row->lockstatus
;
636 public function lockTables( $read, $write, $method, $lowPriority = true ) {
639 foreach( $write as $table ) {
640 $tbl = $this->tableName( $table ) .
641 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
645 foreach( $read as $table ) {
646 $items[] = $this->tableName( $table ) . ' READ';
648 $sql = "LOCK TABLES " . implode( ',', $items );
649 $this->query( $sql, $method );
652 public function unlockTables( $method ) {
653 $this->query( "UNLOCK TABLES", $method );
657 * Get search engine class. All subclasses of this
658 * need to implement this if they wish to use searching.
662 public function getSearchEngine() {
663 return 'SearchMySQL';
666 public function setBigSelects( $value = true ) {
667 if ( $value === 'default' ) {
668 if ( $this->mDefaultBigSelects
=== null ) {
669 # Function hasn't been called before so it must already be set to the default
672 $value = $this->mDefaultBigSelects
;
674 } elseif ( $this->mDefaultBigSelects
=== null ) {
675 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
677 $encValue = $value ?
'1' : '0';
678 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
682 * DELETE where the condition is a join. MySql uses multi-table deletes.
684 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
686 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
689 $delTable = $this->tableName( $delTable );
690 $joinTable = $this->tableName( $joinTable );
691 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
693 if ( $conds != '*' ) {
694 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
697 return $this->query( $sql, $fname );
701 * Determines if the last failure was due to a deadlock
705 function wasDeadlock() {
706 return $this->lastErrno() == 1213;
710 * Determines if the last failure was due to a lock timeout
714 function wasLockTimeout() {
715 return $this->lastErrno() == 1205;
719 * Determines if the last query error was something that should be dealt
720 * with by pinging the connection and reissuing the query
724 function wasErrorReissuable() {
725 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
729 * Determines if the last failure was due to the database being read-only.
733 function wasReadOnlyError() {
734 return $this->lastErrno() == 1223 ||
735 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
738 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
739 $tmp = $temporary ?
'TEMPORARY ' : '';
740 $newName = $this->addIdentifierQuotes( $newName );
741 $oldName = $this->addIdentifierQuotes( $oldName );
742 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
743 $this->query( $query, $fname );
747 * List all tables on the database
749 * @param $prefix Only show tables with this prefix, e.g. mw_
750 * @param $fname String: calling function name
752 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
753 $result = $this->query( "SHOW TABLES", $fname);
757 foreach( $result as $table ) {
758 $vars = get_object_vars($table);
759 $table = array_pop( $vars );
761 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
762 $endArray[] = $table;
771 * @param $fName string
772 * @return bool|ResultWrapper
774 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
775 if( !$this->tableExists( $tableName, $fName ) ) {
778 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
784 protected function getDefaultSchemaVars() {
785 $vars = parent
::getDefaultSchemaVars();
786 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
787 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $GLOBALS['wgDBTableOptions'] );
792 * Get status information from SHOW STATUS in an associative array
796 function getMysqlStatus( $which = "%" ) {
797 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
800 foreach ( $res as $row ) {
801 $status[$row->Variable_name
] = $row->Value
;
810 * Legacy support: Database == DatabaseMysql
812 * @deprecated in 1.16
814 class Database
extends DatabaseMysql
{}
820 class MySQLField
implements Field
{
821 private $name, $tablename, $default, $max_length, $nullable,
822 $is_pk, $is_unique, $is_multiple, $is_key, $type;
824 function __construct ( $info ) {
825 $this->name
= $info->name
;
826 $this->tablename
= $info->table
;
827 $this->default = $info->def
;
828 $this->max_length
= $info->max_length
;
829 $this->nullable
= !$info->not_null
;
830 $this->is_pk
= $info->primary_key
;
831 $this->is_unique
= $info->unique_key
;
832 $this->is_multiple
= $info->multiple_key
;
833 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
834 $this->type
= $info->type
;
847 function tableName() {
848 return $this->tableName
;
858 function isNullable() {
859 return $this->nullable
;
862 function defaultValue() {
863 return $this->default;
870 return $this->is_key
;
876 function isMultipleKey() {
877 return $this->is_multiple
;
881 class MySQLMasterPos
implements DBMasterPos
{
884 function __construct( $file, $pos ) {
889 function __toString() {
890 return "{$this->file}/{$this->pos}";