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__
);
157 protected function closeConnection() {
158 return mysql_close( $this->mConn
);
162 * @param $res ResultWrapper
163 * @throws DBUnexpectedError
165 function freeResult( $res ) {
166 if ( $res instanceof ResultWrapper
) {
169 wfSuppressWarnings();
170 $ok = mysql_free_result( $res );
173 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
178 * @param $res ResultWrapper
179 * @return object|stdClass
180 * @throws DBUnexpectedError
182 function fetchObject( $res ) {
183 if ( $res instanceof ResultWrapper
) {
186 wfSuppressWarnings();
187 $row = mysql_fetch_object( $res );
189 if( $this->lastErrno() ) {
190 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
196 * @param $res ResultWrapper
198 * @throws DBUnexpectedError
200 function fetchRow( $res ) {
201 if ( $res instanceof ResultWrapper
) {
204 wfSuppressWarnings();
205 $row = mysql_fetch_array( $res );
207 if ( $this->lastErrno() ) {
208 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
214 * @throws DBUnexpectedError
215 * @param $res ResultWrapper
218 function numRows( $res ) {
219 if ( $res instanceof ResultWrapper
) {
222 wfSuppressWarnings();
223 $n = mysql_num_rows( $res );
225 if( $this->lastErrno() ) {
226 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
232 * @param $res ResultWrapper
235 function numFields( $res ) {
236 if ( $res instanceof ResultWrapper
) {
239 return mysql_num_fields( $res );
243 * @param $res ResultWrapper
247 function fieldName( $res, $n ) {
248 if ( $res instanceof ResultWrapper
) {
251 return mysql_field_name( $res, $n );
257 function insertId() {
258 return mysql_insert_id( $this->mConn
);
262 * @param $res ResultWrapper
266 function dataSeek( $res, $row ) {
267 if ( $res instanceof ResultWrapper
) {
270 return mysql_data_seek( $res, $row );
276 function lastErrno() {
277 if ( $this->mConn
) {
278 return mysql_errno( $this->mConn
);
280 return mysql_errno();
287 function lastError() {
288 if ( $this->mConn
) {
289 # Even if it's non-zero, it can still be invalid
290 wfSuppressWarnings();
291 $error = mysql_error( $this->mConn
);
293 $error = mysql_error();
297 $error = mysql_error();
300 $error .= ' (' . $this->mServer
. ')';
308 function affectedRows() {
309 return mysql_affected_rows( $this->mConn
);
313 * @param $table string
314 * @param $uniqueIndexes
316 * @param $fname string
317 * @return ResultWrapper
319 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
320 return $this->nativeReplace( $table, $rows, $fname );
324 * Estimate rows in dataset
325 * Returns estimated count, based on EXPLAIN output
326 * Takes same arguments as Database::select()
328 * @param $table string|array
329 * @param $vars string|array
330 * @param $conds string|array
331 * @param $fname string
332 * @param $options string|array
335 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
336 $options['EXPLAIN'] = true;
337 $res = $this->select( $table, $vars, $conds, $fname, $options );
338 if ( $res === false ) {
341 if ( !$this->numRows( $res ) ) {
346 foreach ( $res as $plan ) {
347 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
353 * @param $table string
354 * @param $field string
355 * @return bool|MySQLField
357 function fieldInfo( $table, $field ) {
358 $table = $this->tableName( $table );
359 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
363 $n = mysql_num_fields( $res->result
);
364 for( $i = 0; $i < $n; $i++
) {
365 $meta = mysql_fetch_field( $res->result
, $i );
366 if( $field == $meta->name
) {
367 return new MySQLField($meta);
374 * Get information about an index into an object
375 * Returns false if the index does not exist
377 * @param $table string
378 * @param $index string
379 * @param $fname string
380 * @return bool|array|null False or null on failure
382 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
383 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
384 # SHOW INDEX should work for 3.x and up:
385 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
386 $table = $this->tableName( $table );
387 $index = $this->indexName( $index );
388 $sql = 'SHOW INDEX FROM ' . $table;
389 $res = $this->query( $sql, $fname );
397 foreach ( $res as $row ) {
398 if ( $row->Key_name
== $index ) {
403 return empty( $result ) ?
false : $result;
410 function selectDB( $db ) {
411 $this->mDBname
= $db;
412 return mysql_select_db( $db, $this->mConn
);
420 function strencode( $s ) {
421 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
423 if($sQuoted === false) {
425 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
431 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
437 public function addIdentifierQuotes( $s ) {
438 return "`" . $this->strencode( $s ) . "`";
442 * @param $name string
445 public function isQuotedIdentifier( $name ) {
446 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
453 $ping = mysql_ping( $this->mConn
);
458 mysql_close( $this->mConn
);
459 $this->mOpened
= false;
460 $this->mConn
= false;
461 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
468 * This will do a SHOW SLAVE STATUS
473 if ( !is_null( $this->mFakeSlaveLag
) ) {
474 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
475 return $this->mFakeSlaveLag
;
478 return $this->getLagFromSlaveStatus();
484 function getLagFromSlaveStatus() {
485 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
489 $row = $res->fetchObject();
493 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
496 return intval( $row->Seconds_Behind_Master
);
501 * @deprecated in 1.19, use getLagFromSlaveStatus
505 function getLagFromProcesslist() {
506 wfDeprecated( __METHOD__
, '1.19' );
507 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
511 # Find slave SQL thread
512 foreach( $res as $row ) {
513 /* This should work for most situations - when default db
514 * for thread is not specified, it had no events executed,
515 * and therefore it doesn't know yet how lagged it is.
517 * Relay log I/O thread does not select databases.
519 if ( $row->User
== 'system user' &&
520 $row->State
!= 'Waiting for master to send event' &&
521 $row->State
!= 'Connecting to master' &&
522 $row->State
!= 'Queueing master event to the relay log' &&
523 $row->State
!= 'Waiting for master update' &&
524 $row->State
!= 'Requesting binlog dump' &&
525 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
526 $row->State
!= 'Reconnecting after a failed master event read' &&
527 $row->State
!= 'Registering slave on master'
529 # This is it, return the time (except -ve)
530 if ( $row->Time
> 0x7fffffff ) {
541 * Wait for the slave to catch up to a given master position.
543 * @param $pos DBMasterPos object
544 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
545 * @return bool|string
547 function masterPosWait( DBMasterPos
$pos, $timeout ) {
548 $fname = 'DatabaseBase::masterPosWait';
549 wfProfileIn( $fname );
551 # Commit any open transactions
552 if ( $this->mTrxLevel
) {
553 $this->commit( __METHOD__
);
556 if ( !is_null( $this->mFakeSlaveLag
) ) {
557 $status = parent
::masterPosWait( $pos, $timeout );
558 wfProfileOut( $fname );
562 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
563 $encFile = $this->addQuotes( $pos->file
);
564 $encPos = intval( $pos->pos
);
565 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
566 $res = $this->doQuery( $sql );
568 if ( $res && $row = $this->fetchRow( $res ) ) {
569 wfProfileOut( $fname );
572 wfProfileOut( $fname );
578 * Get the position of the master from SHOW SLAVE STATUS
580 * @return MySQLMasterPos|bool
582 function getSlavePos() {
583 if ( !is_null( $this->mFakeSlaveLag
) ) {
584 return parent
::getSlavePos();
587 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
588 $row = $this->fetchObject( $res );
591 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
592 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
599 * Get the position of the master from SHOW MASTER STATUS
601 * @return MySQLMasterPos|bool
603 function getMasterPos() {
604 if ( $this->mFakeMaster
) {
605 return parent
::getMasterPos();
608 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
609 $row = $this->fetchObject( $res );
612 return new MySQLMasterPos( $row->File
, $row->Position
);
621 function getServerVersion() {
622 return mysql_get_server_info( $this->mConn
);
629 function useIndexClause( $index ) {
630 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
636 function lowPriorityOption() {
637 return 'LOW_PRIORITY';
643 public static function getSoftwareLink() {
644 return '[http://www.mysql.com/ MySQL]';
650 function standardSelectDistinct() {
655 * @param $options array
657 public function setSessionOptions( array $options ) {
658 if ( isset( $options['connTimeout'] ) ) {
659 $timeout = (int)$options['connTimeout'];
660 $this->query( "SET net_read_timeout=$timeout" );
661 $this->query( "SET net_write_timeout=$timeout" );
665 public function streamStatementEnd( &$sql, &$newLine ) {
666 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
667 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
668 $this->delimiter
= $m[1];
671 return parent
::streamStatementEnd( $sql, $newLine );
675 * @param $lockName string
676 * @param $method string
677 * @param $timeout int
680 public function lock( $lockName, $method, $timeout = 5 ) {
681 $lockName = $this->addQuotes( $lockName );
682 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
683 $row = $this->fetchObject( $result );
685 if( $row->lockstatus
== 1 ) {
688 wfDebug( __METHOD__
." failed to acquire lock\n" );
694 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
695 * @param $lockName string
696 * @param $method string
699 public function unlock( $lockName, $method ) {
700 $lockName = $this->addQuotes( $lockName );
701 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
702 $row = $this->fetchObject( $result );
703 return $row->lockstatus
;
708 * @param $write array
709 * @param $method string
710 * @param $lowPriority bool
712 public function lockTables( $read, $write, $method, $lowPriority = true ) {
715 foreach( $write as $table ) {
716 $tbl = $this->tableName( $table ) .
717 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
721 foreach( $read as $table ) {
722 $items[] = $this->tableName( $table ) . ' READ';
724 $sql = "LOCK TABLES " . implode( ',', $items );
725 $this->query( $sql, $method );
729 * @param $method string
731 public function unlockTables( $method ) {
732 $this->query( "UNLOCK TABLES", $method );
736 * Get search engine class. All subclasses of this
737 * need to implement this if they wish to use searching.
741 public function getSearchEngine() {
742 return 'SearchMySQL';
749 public function setBigSelects( $value = true ) {
750 if ( $value === 'default' ) {
751 if ( $this->mDefaultBigSelects
=== null ) {
752 # Function hasn't been called before so it must already be set to the default
755 $value = $this->mDefaultBigSelects
;
757 } elseif ( $this->mDefaultBigSelects
=== null ) {
758 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
760 $encValue = $value ?
'1' : '0';
761 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
765 * DELETE where the condition is a join. MySql uses multi-table deletes.
766 * @param $delTable string
767 * @param $joinTable string
768 * @param $delVar string
769 * @param $joinVar string
770 * @param $conds array|string
772 * @return bool|ResultWrapper
774 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
776 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
779 $delTable = $this->tableName( $delTable );
780 $joinTable = $this->tableName( $joinTable );
781 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
783 if ( $conds != '*' ) {
784 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
787 return $this->query( $sql, $fname );
791 * Determines how long the server has been up
795 function getServerUptime() {
796 $vars = $this->getMysqlStatus( 'Uptime' );
797 return (int)$vars['Uptime'];
801 * Determines if the last failure was due to a deadlock
805 function wasDeadlock() {
806 return $this->lastErrno() == 1213;
810 * Determines if the last failure was due to a lock timeout
814 function wasLockTimeout() {
815 return $this->lastErrno() == 1205;
819 * Determines if the last query error was something that should be dealt
820 * with by pinging the connection and reissuing the query
824 function wasErrorReissuable() {
825 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
829 * Determines if the last failure was due to the database being read-only.
833 function wasReadOnlyError() {
834 return $this->lastErrno() == 1223 ||
835 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
841 * @param $temporary bool
842 * @param $fname string
844 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
845 $tmp = $temporary ?
'TEMPORARY ' : '';
846 $newName = $this->addIdentifierQuotes( $newName );
847 $oldName = $this->addIdentifierQuotes( $oldName );
848 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
849 $this->query( $query, $fname );
853 * List all tables on the database
855 * @param $prefix string Only show tables with this prefix, e.g. mw_
856 * @param $fname String: calling function name
859 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
860 $result = $this->query( "SHOW TABLES", $fname);
864 foreach( $result as $table ) {
865 $vars = get_object_vars($table);
866 $table = array_pop( $vars );
868 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
869 $endArray[] = $table;
878 * @param $fName string
879 * @return bool|ResultWrapper
881 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
882 if( !$this->tableExists( $tableName, $fName ) ) {
885 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
891 protected function getDefaultSchemaVars() {
892 $vars = parent
::getDefaultSchemaVars();
893 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
894 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
899 * Get status information from SHOW STATUS in an associative array
901 * @param $which string
904 function getMysqlStatus( $which = "%" ) {
905 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
908 foreach ( $res as $row ) {
909 $status[$row->Variable_name
] = $row->Value
;
918 * Legacy support: Database == DatabaseMysql
920 * @deprecated in 1.16
922 class Database
extends DatabaseMysql
{}
928 class MySQLField
implements Field
{
929 private $name, $tablename, $default, $max_length, $nullable,
930 $is_pk, $is_unique, $is_multiple, $is_key, $type;
932 function __construct ( $info ) {
933 $this->name
= $info->name
;
934 $this->tablename
= $info->table
;
935 $this->default = $info->def
;
936 $this->max_length
= $info->max_length
;
937 $this->nullable
= !$info->not_null
;
938 $this->is_pk
= $info->primary_key
;
939 $this->is_unique
= $info->unique_key
;
940 $this->is_multiple
= $info->multiple_key
;
941 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
942 $this->type
= $info->type
;
955 function tableName() {
956 return $this->tableName
;
969 function isNullable() {
970 return $this->nullable
;
973 function defaultValue() {
974 return $this->default;
981 return $this->is_key
;
987 function isMultipleKey() {
988 return $this->is_multiple
;
992 class MySQLMasterPos
implements DBMasterPos
{
995 function __construct( $file, $pos ) {
1000 function __toString() {
1001 return "{$this->file}/{$this->pos}";