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
{
29 protected function doQuery( $sql ) {
30 if( $this->bufferResults() ) {
31 $ret = mysql_query( $sql, $this->mConn
);
33 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
39 * @param $server string
41 * @param $password string
42 * @param $dbName string
44 * @throws DBConnectionError
46 function open( $server, $user, $password, $dbName ) {
47 global $wgAllDBsAreLocalhost;
48 wfProfileIn( __METHOD__
);
50 # Load mysql.so if we don't have it
54 # Otherwise we get a suppressed fatal error, which is very hard to track down
55 if ( !function_exists( 'mysql_connect' ) ) {
56 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
59 # Debugging hack -- fake cluster
60 if ( $wgAllDBsAreLocalhost ) {
61 $realServer = 'localhost';
63 $realServer = $server;
66 $this->mServer
= $server;
68 $this->mPassword
= $password;
69 $this->mDBname
= $dbName;
71 wfProfileIn("dbconnect-$server");
73 # The kernel's default SYN retransmission period is far too slow for us,
74 # so we use a short timeout plus a manual retry. Retrying means that a small
75 # but finite rate of SYN packet loss won't cause user-visible errors.
77 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
82 $this->installErrorHandler();
83 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
87 if ( $this->mFlags
& DBO_PERSISTENT
) {
88 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
90 # Create a new connection...
91 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
93 #if ( $this->mConn === false ) {
95 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
98 $phpError = $this->restoreErrorHandler();
99 # Always log connection errors
100 if ( !$this->mConn
) {
101 $error = $this->lastError();
105 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
106 wfDebug( "DB connection error\n" );
107 wfDebug( "Server: $server, User: $user, Password: " .
108 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
111 wfProfileOut("dbconnect-$server");
113 if ( $dbName != '' && $this->mConn
!== false ) {
114 wfSuppressWarnings();
115 $success = mysql_select_db( $dbName, $this->mConn
);
118 $error = "Error selecting database $dbName on server {$this->mServer} " .
119 "from client host " . wfHostname() . "\n";
120 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
125 $success = (bool)$this->mConn
;
129 // Tell the server we're communicating with it in UTF-8.
130 // This may engage various charset conversions.
133 $this->query( 'SET NAMES utf8', __METHOD__
);
135 $this->query( 'SET NAMES binary', __METHOD__
);
137 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
139 if ( is_string( $wgSQLMode ) ) {
140 $mode = $this->addQuotes( $wgSQLMode );
141 $this->query( "SET sql_mode = $mode", __METHOD__
);
144 // Turn off strict mode if it is on
146 $this->reportConnectionError( $phpError );
149 $this->mOpened
= $success;
150 wfProfileOut( __METHOD__
);
158 $this->mOpened
= false;
159 if ( $this->mConn
) {
160 if ( $this->trxLevel() ) {
163 return mysql_close( $this->mConn
);
170 * @param $res ResultWrapper
171 * @throws DBUnexpectedError
173 function freeResult( $res ) {
174 if ( $res instanceof ResultWrapper
) {
177 wfSuppressWarnings();
178 $ok = mysql_free_result( $res );
181 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
186 * @param $res ResultWrapper
187 * @return object|stdClass
188 * @throws DBUnexpectedError
190 function fetchObject( $res ) {
191 if ( $res instanceof ResultWrapper
) {
194 wfSuppressWarnings();
195 $row = mysql_fetch_object( $res );
197 if( $this->lastErrno() ) {
198 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
204 * @param $res ResultWrapper
206 * @throws DBUnexpectedError
208 function fetchRow( $res ) {
209 if ( $res instanceof ResultWrapper
) {
212 wfSuppressWarnings();
213 $row = mysql_fetch_array( $res );
215 if ( $this->lastErrno() ) {
216 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
222 * @throws DBUnexpectedError
223 * @param $res ResultWrapper
226 function numRows( $res ) {
227 if ( $res instanceof ResultWrapper
) {
230 wfSuppressWarnings();
231 $n = mysql_num_rows( $res );
233 if( $this->lastErrno() ) {
234 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
240 * @param $res ResultWrapper
243 function numFields( $res ) {
244 if ( $res instanceof ResultWrapper
) {
247 return mysql_num_fields( $res );
251 * @param $res ResultWrapper
255 function fieldName( $res, $n ) {
256 if ( $res instanceof ResultWrapper
) {
259 return mysql_field_name( $res, $n );
265 function insertId() {
266 return mysql_insert_id( $this->mConn
);
270 * @param $res ResultWrapper
274 function dataSeek( $res, $row ) {
275 if ( $res instanceof ResultWrapper
) {
278 return mysql_data_seek( $res, $row );
284 function lastErrno() {
285 if ( $this->mConn
) {
286 return mysql_errno( $this->mConn
);
288 return mysql_errno();
295 function lastError() {
296 if ( $this->mConn
) {
297 # Even if it's non-zero, it can still be invalid
298 wfSuppressWarnings();
299 $error = mysql_error( $this->mConn
);
301 $error = mysql_error();
305 $error = mysql_error();
308 $error .= ' (' . $this->mServer
. ')';
316 function affectedRows() {
317 return mysql_affected_rows( $this->mConn
);
321 * @param $table string
322 * @param $uniqueIndexes
324 * @param $fname string
325 * @return ResultWrapper
327 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
328 return $this->nativeReplace( $table, $rows, $fname );
332 * Estimate rows in dataset
333 * Returns estimated count, based on EXPLAIN output
334 * Takes same arguments as Database::select()
336 * @param $table string|array
337 * @param $vars string|array
338 * @param $conds string|array
339 * @param $fname string
340 * @param $options string|array
343 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
344 $options['EXPLAIN'] = true;
345 $res = $this->select( $table, $vars, $conds, $fname, $options );
346 if ( $res === false ) {
349 if ( !$this->numRows( $res ) ) {
354 foreach ( $res as $plan ) {
355 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
361 * @param $table string
362 * @param $field string
363 * @return bool|MySQLField
365 function fieldInfo( $table, $field ) {
366 $table = $this->tableName( $table );
367 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
371 $n = mysql_num_fields( $res->result
);
372 for( $i = 0; $i < $n; $i++
) {
373 $meta = mysql_fetch_field( $res->result
, $i );
374 if( $field == $meta->name
) {
375 return new MySQLField($meta);
382 * Get information about an index into an object
383 * Returns false if the index does not exist
385 * @param $table string
386 * @param $index string
387 * @param $fname string
390 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
391 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
392 # SHOW INDEX should work for 3.x and up:
393 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
394 $table = $this->tableName( $table );
395 $index = $this->indexName( $index );
396 $sql = 'SHOW INDEX FROM ' . $table;
397 $res = $this->query( $sql, $fname );
405 foreach ( $res as $row ) {
406 if ( $row->Key_name
== $index ) {
411 return empty( $result ) ?
false : $result;
418 function selectDB( $db ) {
419 $this->mDBname
= $db;
420 return mysql_select_db( $db, $this->mConn
);
428 function strencode( $s ) {
429 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
431 if($sQuoted === false) {
433 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
439 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
445 public function addIdentifierQuotes( $s ) {
446 return "`" . $this->strencode( $s ) . "`";
450 * @param $name string
453 public function isQuotedIdentifier( $name ) {
454 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
461 $ping = mysql_ping( $this->mConn
);
466 mysql_close( $this->mConn
);
467 $this->mOpened
= false;
468 $this->mConn
= false;
469 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
476 * This will do a SHOW SLAVE STATUS
481 if ( !is_null( $this->mFakeSlaveLag
) ) {
482 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
483 return $this->mFakeSlaveLag
;
486 return $this->getLagFromSlaveStatus();
492 function getLagFromSlaveStatus() {
493 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
497 $row = $res->fetchObject();
501 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
504 return intval( $row->Seconds_Behind_Master
);
509 * @deprecated in 1.19, use getLagFromSlaveStatus
513 function getLagFromProcesslist() {
514 wfDeprecated( __METHOD__
, '1.19' );
515 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
519 # Find slave SQL thread
520 foreach( $res as $row ) {
521 /* This should work for most situations - when default db
522 * for thread is not specified, it had no events executed,
523 * and therefore it doesn't know yet how lagged it is.
525 * Relay log I/O thread does not select databases.
527 if ( $row->User
== 'system user' &&
528 $row->State
!= 'Waiting for master to send event' &&
529 $row->State
!= 'Connecting to master' &&
530 $row->State
!= 'Queueing master event to the relay log' &&
531 $row->State
!= 'Waiting for master update' &&
532 $row->State
!= 'Requesting binlog dump' &&
533 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
534 $row->State
!= 'Reconnecting after a failed master event read' &&
535 $row->State
!= 'Registering slave on master'
537 # This is it, return the time (except -ve)
538 if ( $row->Time
> 0x7fffffff ) {
549 * Wait for the slave to catch up to a given master position.
551 * @param $pos DBMasterPos object
552 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
553 * @return bool|string
555 function masterPosWait( DBMasterPos
$pos, $timeout ) {
556 $fname = 'DatabaseBase::masterPosWait';
557 wfProfileIn( $fname );
559 # Commit any open transactions
560 if ( $this->mTrxLevel
) {
564 if ( !is_null( $this->mFakeSlaveLag
) ) {
565 $status = parent
::masterPosWait( $pos, $timeout );
566 wfProfileOut( $fname );
570 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
571 $encFile = $this->addQuotes( $pos->file
);
572 $encPos = intval( $pos->pos
);
573 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
574 $res = $this->doQuery( $sql );
576 if ( $res && $row = $this->fetchRow( $res ) ) {
577 wfProfileOut( $fname );
580 wfProfileOut( $fname );
586 * Get the position of the master from SHOW SLAVE STATUS
588 * @return MySQLMasterPos|bool
590 function getSlavePos() {
591 if ( !is_null( $this->mFakeSlaveLag
) ) {
592 return parent
::getSlavePos();
595 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
596 $row = $this->fetchObject( $res );
599 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
600 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
607 * Get the position of the master from SHOW MASTER STATUS
609 * @return MySQLMasterPos|bool
611 function getMasterPos() {
612 if ( $this->mFakeMaster
) {
613 return parent
::getMasterPos();
616 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
617 $row = $this->fetchObject( $res );
620 return new MySQLMasterPos( $row->File
, $row->Position
);
629 function getServerVersion() {
630 return mysql_get_server_info( $this->mConn
);
637 function useIndexClause( $index ) {
638 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
644 function lowPriorityOption() {
645 return 'LOW_PRIORITY';
651 public static function getSoftwareLink() {
652 return '[http://www.mysql.com/ MySQL]';
658 function standardSelectDistinct() {
663 * @param $options array
665 public function setSessionOptions( array $options ) {
666 if ( isset( $options['connTimeout'] ) ) {
667 $timeout = (int)$options['connTimeout'];
668 $this->query( "SET net_read_timeout=$timeout" );
669 $this->query( "SET net_write_timeout=$timeout" );
673 public function streamStatementEnd( &$sql, &$newLine ) {
674 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
675 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
676 $this->delimiter
= $m[1];
679 return parent
::streamStatementEnd( $sql, $newLine );
683 * @param $lockName string
684 * @param $method string
685 * @param $timeout int
688 public function lock( $lockName, $method, $timeout = 5 ) {
689 $lockName = $this->addQuotes( $lockName );
690 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
691 $row = $this->fetchObject( $result );
693 if( $row->lockstatus
== 1 ) {
696 wfDebug( __METHOD__
." failed to acquire lock\n" );
702 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
703 * @param $lockName string
704 * @param $method string
707 public function unlock( $lockName, $method ) {
708 $lockName = $this->addQuotes( $lockName );
709 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
710 $row = $this->fetchObject( $result );
711 return $row->lockstatus
;
716 * @param $write array
717 * @param $method string
718 * @param $lowPriority bool
720 public function lockTables( $read, $write, $method, $lowPriority = true ) {
723 foreach( $write as $table ) {
724 $tbl = $this->tableName( $table ) .
725 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
729 foreach( $read as $table ) {
730 $items[] = $this->tableName( $table ) . ' READ';
732 $sql = "LOCK TABLES " . implode( ',', $items );
733 $this->query( $sql, $method );
737 * @param $method string
739 public function unlockTables( $method ) {
740 $this->query( "UNLOCK TABLES", $method );
744 * Get search engine class. All subclasses of this
745 * need to implement this if they wish to use searching.
749 public function getSearchEngine() {
750 return 'SearchMySQL';
757 public function setBigSelects( $value = true ) {
758 if ( $value === 'default' ) {
759 if ( $this->mDefaultBigSelects
=== null ) {
760 # Function hasn't been called before so it must already be set to the default
763 $value = $this->mDefaultBigSelects
;
765 } elseif ( $this->mDefaultBigSelects
=== null ) {
766 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
768 $encValue = $value ?
'1' : '0';
769 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
773 * DELETE where the condition is a join. MySql uses multi-table deletes.
774 * @param $delTable string
775 * @param $joinTable string
776 * @param $delVar string
777 * @param $joinVar string
778 * @param $conds array|string
780 * @return bool|ResultWrapper
782 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
784 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
787 $delTable = $this->tableName( $delTable );
788 $joinTable = $this->tableName( $joinTable );
789 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
791 if ( $conds != '*' ) {
792 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
795 return $this->query( $sql, $fname );
799 * Determines how long the server has been up
803 function getServerUptime() {
804 $vars = $this->getMysqlStatus( 'Uptime' );
805 return (int)$vars['Uptime'];
809 * Determines if the last failure was due to a deadlock
813 function wasDeadlock() {
814 return $this->lastErrno() == 1213;
818 * Determines if the last failure was due to a lock timeout
822 function wasLockTimeout() {
823 return $this->lastErrno() == 1205;
827 * Determines if the last query error was something that should be dealt
828 * with by pinging the connection and reissuing the query
832 function wasErrorReissuable() {
833 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
837 * Determines if the last failure was due to the database being read-only.
841 function wasReadOnlyError() {
842 return $this->lastErrno() == 1223 ||
843 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
849 * @param $temporary bool
850 * @param $fname string
852 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
853 $tmp = $temporary ?
'TEMPORARY ' : '';
854 $newName = $this->addIdentifierQuotes( $newName );
855 $oldName = $this->addIdentifierQuotes( $oldName );
856 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
857 $this->query( $query, $fname );
861 * List all tables on the database
863 * @param $prefix Only show tables with this prefix, e.g. mw_
864 * @param $fname String: calling function name
867 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
868 $result = $this->query( "SHOW TABLES", $fname);
872 foreach( $result as $table ) {
873 $vars = get_object_vars($table);
874 $table = array_pop( $vars );
876 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
877 $endArray[] = $table;
886 * @param $fName string
887 * @return bool|ResultWrapper
889 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
890 if( !$this->tableExists( $tableName, $fName ) ) {
893 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
899 protected function getDefaultSchemaVars() {
900 $vars = parent
::getDefaultSchemaVars();
901 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
902 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
907 * Get status information from SHOW STATUS in an associative array
909 * @param $which string
912 function getMysqlStatus( $which = "%" ) {
913 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
916 foreach ( $res as $row ) {
917 $status[$row->Variable_name
] = $row->Value
;
926 * Legacy support: Database == DatabaseMysql
928 * @deprecated in 1.16
930 class Database
extends DatabaseMysql
{}
936 class MySQLField
implements Field
{
937 private $name, $tablename, $default, $max_length, $nullable,
938 $is_pk, $is_unique, $is_multiple, $is_key, $type;
940 function __construct ( $info ) {
941 $this->name
= $info->name
;
942 $this->tablename
= $info->table
;
943 $this->default = $info->def
;
944 $this->max_length
= $info->max_length
;
945 $this->nullable
= !$info->not_null
;
946 $this->is_pk
= $info->primary_key
;
947 $this->is_unique
= $info->unique_key
;
948 $this->is_multiple
= $info->multiple_key
;
949 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
950 $this->type
= $info->type
;
963 function tableName() {
964 return $this->tableName
;
977 function isNullable() {
978 return $this->nullable
;
981 function defaultValue() {
982 return $this->default;
989 return $this->is_key
;
995 function isMultipleKey() {
996 return $this->is_multiple
;
1000 class MySQLMasterPos
implements DBMasterPos
{
1003 function __construct( $file, $pos ) {
1004 $this->file
= $file;
1008 function __toString() {
1009 return "{$this->file}/{$this->pos}";