3 * This is the MySQL database abstraction layer.
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
25 * Database abstraction object for mySQL
26 * Inherit all methods and properties of Database::Database()
31 class DatabaseMysql
extends DatabaseBase
{
44 protected function doQuery( $sql ) {
45 if( $this->bufferResults() ) {
46 $ret = mysql_query( $sql, $this->mConn
);
48 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
54 * @param $server string
56 * @param $password string
57 * @param $dbName string
59 * @throws DBConnectionError
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost;
63 wfProfileIn( __METHOD__
);
65 # Load mysql.so if we don't have it
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if ( !function_exists( 'mysql_connect' ) ) {
71 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
74 # Debugging hack -- fake cluster
75 if ( $wgAllDBsAreLocalhost ) {
76 $realServer = 'localhost';
78 $realServer = $server;
81 $this->mServer
= $server;
83 $this->mPassword
= $password;
84 $this->mDBname
= $dbName;
87 if ( $this->mFlags
& DBO_SSL
) {
88 $connFlags |
= MYSQL_CLIENT_SSL
;
90 if ( $this->mFlags
& DBO_COMPRESS
) {
91 $connFlags |
= MYSQL_CLIENT_COMPRESS
;
94 wfProfileIn("dbconnect-$server");
96 # The kernel's default SYN retransmission period is far too slow for us,
97 # so we use a short timeout plus a manual retry. Retrying means that a small
98 # but finite rate of SYN packet loss won't cause user-visible errors.
100 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
105 $this->installErrorHandler();
106 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
110 if ( $this->mFlags
& DBO_PERSISTENT
) {
111 $this->mConn
= mysql_pconnect( $realServer, $user, $password, $connFlags );
113 # Create a new connection...
114 $this->mConn
= mysql_connect( $realServer, $user, $password, true, $connFlags );
116 #if ( $this->mConn === false ) {
118 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
121 $phpError = $this->restoreErrorHandler();
122 # Always log connection errors
123 if ( !$this->mConn
) {
126 $error = $this->lastError();
128 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
129 wfDebug( "DB connection error\n" );
130 wfDebug( "Server: $server, User: $user, Password: " .
131 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
134 wfProfileOut("dbconnect-$server");
136 if ( $dbName != '' && $this->mConn
!== false ) {
137 wfSuppressWarnings();
138 $success = mysql_select_db( $dbName, $this->mConn
);
141 $error = "Error selecting database $dbName on server {$this->mServer} " .
142 "from client host " . wfHostname() . "\n";
143 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
148 $success = (bool)$this->mConn
;
152 // Tell the server we're communicating with it in UTF-8.
153 // This may engage various charset conversions.
156 $this->query( 'SET NAMES utf8', __METHOD__
);
158 $this->query( 'SET NAMES binary', __METHOD__
);
160 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
162 if ( is_string( $wgSQLMode ) ) {
163 $mode = $this->addQuotes( $wgSQLMode );
164 $this->query( "SET sql_mode = $mode", __METHOD__
);
167 // Turn off strict mode if it is on
169 $this->reportConnectionError( $phpError );
172 $this->mOpened
= $success;
173 wfProfileOut( __METHOD__
);
180 protected function closeConnection() {
181 return mysql_close( $this->mConn
);
185 * @param $res ResultWrapper
186 * @throws DBUnexpectedError
188 function freeResult( $res ) {
189 if ( $res instanceof ResultWrapper
) {
192 wfSuppressWarnings();
193 $ok = mysql_free_result( $res );
196 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
201 * @param $res ResultWrapper
202 * @return object|stdClass
203 * @throws DBUnexpectedError
205 function fetchObject( $res ) {
206 if ( $res instanceof ResultWrapper
) {
209 wfSuppressWarnings();
210 $row = mysql_fetch_object( $res );
212 if( $this->lastErrno() ) {
213 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
219 * @param $res ResultWrapper
221 * @throws DBUnexpectedError
223 function fetchRow( $res ) {
224 if ( $res instanceof ResultWrapper
) {
227 wfSuppressWarnings();
228 $row = mysql_fetch_array( $res );
230 if ( $this->lastErrno() ) {
231 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
237 * @throws DBUnexpectedError
238 * @param $res ResultWrapper
241 function numRows( $res ) {
242 if ( $res instanceof ResultWrapper
) {
245 wfSuppressWarnings();
246 $n = mysql_num_rows( $res );
248 if( $this->lastErrno() ) {
249 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
255 * @param $res ResultWrapper
258 function numFields( $res ) {
259 if ( $res instanceof ResultWrapper
) {
262 return mysql_num_fields( $res );
266 * @param $res ResultWrapper
270 function fieldName( $res, $n ) {
271 if ( $res instanceof ResultWrapper
) {
274 return mysql_field_name( $res, $n );
280 function insertId() {
281 return mysql_insert_id( $this->mConn
);
285 * @param $res ResultWrapper
289 function dataSeek( $res, $row ) {
290 if ( $res instanceof ResultWrapper
) {
293 return mysql_data_seek( $res, $row );
299 function lastErrno() {
300 if ( $this->mConn
) {
301 return mysql_errno( $this->mConn
);
303 return mysql_errno();
310 function lastError() {
311 if ( $this->mConn
) {
312 # Even if it's non-zero, it can still be invalid
313 wfSuppressWarnings();
314 $error = mysql_error( $this->mConn
);
316 $error = mysql_error();
320 $error = mysql_error();
323 $error .= ' (' . $this->mServer
. ')';
331 function affectedRows() {
332 return mysql_affected_rows( $this->mConn
);
336 * @param $table string
337 * @param $uniqueIndexes
339 * @param $fname string
340 * @return ResultWrapper
342 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
343 return $this->nativeReplace( $table, $rows, $fname );
347 * Estimate rows in dataset
348 * Returns estimated count, based on EXPLAIN output
349 * Takes same arguments as Database::select()
351 * @param $table string|array
352 * @param $vars string|array
353 * @param $conds string|array
354 * @param $fname string
355 * @param $options string|array
358 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
359 $options['EXPLAIN'] = true;
360 $res = $this->select( $table, $vars, $conds, $fname, $options );
361 if ( $res === false ) {
364 if ( !$this->numRows( $res ) ) {
369 foreach ( $res as $plan ) {
370 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
376 * @param $table string
377 * @param $field string
378 * @return bool|MySQLField
380 function fieldInfo( $table, $field ) {
381 $table = $this->tableName( $table );
382 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
386 $n = mysql_num_fields( $res->result
);
387 for( $i = 0; $i < $n; $i++
) {
388 $meta = mysql_fetch_field( $res->result
, $i );
389 if( $field == $meta->name
) {
390 return new MySQLField($meta);
397 * Get information about an index into an object
398 * Returns false if the index does not exist
400 * @param $table string
401 * @param $index string
402 * @param $fname string
403 * @return bool|array|null False or null on failure
405 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
406 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
407 # SHOW INDEX should work for 3.x and up:
408 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
409 $table = $this->tableName( $table );
410 $index = $this->indexName( $index );
411 $sql = 'SHOW INDEX FROM ' . $table;
412 $res = $this->query( $sql, $fname );
420 foreach ( $res as $row ) {
421 if ( $row->Key_name
== $index ) {
426 return empty( $result ) ?
false : $result;
433 function selectDB( $db ) {
434 $this->mDBname
= $db;
435 return mysql_select_db( $db, $this->mConn
);
443 function strencode( $s ) {
444 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
446 if($sQuoted === false) {
448 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
454 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
460 public function addIdentifierQuotes( $s ) {
461 return "`" . $this->strencode( $s ) . "`";
465 * @param $name string
468 public function isQuotedIdentifier( $name ) {
469 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
476 $ping = mysql_ping( $this->mConn
);
481 mysql_close( $this->mConn
);
482 $this->mOpened
= false;
483 $this->mConn
= false;
484 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
491 * This will do a SHOW SLAVE STATUS
496 if ( !is_null( $this->mFakeSlaveLag
) ) {
497 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
498 return $this->mFakeSlaveLag
;
501 return $this->getLagFromSlaveStatus();
507 function getLagFromSlaveStatus() {
508 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
512 $row = $res->fetchObject();
516 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
519 return intval( $row->Seconds_Behind_Master
);
524 * @deprecated in 1.19, use getLagFromSlaveStatus
528 function getLagFromProcesslist() {
529 wfDeprecated( __METHOD__
, '1.19' );
530 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
534 # Find slave SQL thread
535 foreach( $res as $row ) {
536 /* This should work for most situations - when default db
537 * for thread is not specified, it had no events executed,
538 * and therefore it doesn't know yet how lagged it is.
540 * Relay log I/O thread does not select databases.
542 if ( $row->User
== 'system user' &&
543 $row->State
!= 'Waiting for master to send event' &&
544 $row->State
!= 'Connecting to master' &&
545 $row->State
!= 'Queueing master event to the relay log' &&
546 $row->State
!= 'Waiting for master update' &&
547 $row->State
!= 'Requesting binlog dump' &&
548 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
549 $row->State
!= 'Reconnecting after a failed master event read' &&
550 $row->State
!= 'Registering slave on master'
552 # This is it, return the time (except -ve)
553 if ( $row->Time
> 0x7fffffff ) {
564 * Wait for the slave to catch up to a given master position.
566 * @param $pos DBMasterPos object
567 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
568 * @return bool|string
570 function masterPosWait( DBMasterPos
$pos, $timeout ) {
571 $fname = 'DatabaseBase::masterPosWait';
572 wfProfileIn( $fname );
574 # Commit any open transactions
575 if ( $this->mTrxLevel
) {
576 $this->commit( __METHOD__
);
579 if ( !is_null( $this->mFakeSlaveLag
) ) {
580 $status = parent
::masterPosWait( $pos, $timeout );
581 wfProfileOut( $fname );
585 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
586 $encFile = $this->addQuotes( $pos->file
);
587 $encPos = intval( $pos->pos
);
588 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
589 $res = $this->doQuery( $sql );
591 if ( $res && $row = $this->fetchRow( $res ) ) {
592 wfProfileOut( $fname );
595 wfProfileOut( $fname );
601 * Get the position of the master from SHOW SLAVE STATUS
603 * @return MySQLMasterPos|bool
605 function getSlavePos() {
606 if ( !is_null( $this->mFakeSlaveLag
) ) {
607 return parent
::getSlavePos();
610 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
611 $row = $this->fetchObject( $res );
614 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
615 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
622 * Get the position of the master from SHOW MASTER STATUS
624 * @return MySQLMasterPos|bool
626 function getMasterPos() {
627 if ( $this->mFakeMaster
) {
628 return parent
::getMasterPos();
631 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
632 $row = $this->fetchObject( $res );
635 return new MySQLMasterPos( $row->File
, $row->Position
);
644 function getServerVersion() {
645 return mysql_get_server_info( $this->mConn
);
652 function useIndexClause( $index ) {
653 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
659 function lowPriorityOption() {
660 return 'LOW_PRIORITY';
666 public static function getSoftwareLink() {
667 return '[http://www.mysql.com/ MySQL]';
671 * @param $options array
673 public function setSessionOptions( array $options ) {
674 if ( isset( $options['connTimeout'] ) ) {
675 $timeout = (int)$options['connTimeout'];
676 $this->query( "SET net_read_timeout=$timeout" );
677 $this->query( "SET net_write_timeout=$timeout" );
681 public function streamStatementEnd( &$sql, &$newLine ) {
682 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
683 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
684 $this->delimiter
= $m[1];
687 return parent
::streamStatementEnd( $sql, $newLine );
691 * Check to see if a named lock is available. This is non-blocking.
693 * @param $lockName String: name of lock to poll
694 * @param $method String: name of method calling us
698 public function lockIsFree( $lockName, $method ) {
699 $lockName = $this->addQuotes( $lockName );
700 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
701 $row = $this->fetchObject( $result );
702 return ( $row->lockstatus
== 1 );
706 * @param $lockName string
707 * @param $method string
708 * @param $timeout int
711 public function lock( $lockName, $method, $timeout = 5 ) {
712 $lockName = $this->addQuotes( $lockName );
713 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
714 $row = $this->fetchObject( $result );
716 if( $row->lockstatus
== 1 ) {
719 wfDebug( __METHOD__
." failed to acquire lock\n" );
725 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
726 * @param $lockName string
727 * @param $method string
730 public function unlock( $lockName, $method ) {
731 $lockName = $this->addQuotes( $lockName );
732 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
733 $row = $this->fetchObject( $result );
734 return ( $row->lockstatus
== 1 );
739 * @param $write array
740 * @param $method string
741 * @param $lowPriority bool
743 public function lockTables( $read, $write, $method, $lowPriority = true ) {
746 foreach( $write as $table ) {
747 $tbl = $this->tableName( $table ) .
748 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
752 foreach( $read as $table ) {
753 $items[] = $this->tableName( $table ) . ' READ';
755 $sql = "LOCK TABLES " . implode( ',', $items );
756 $this->query( $sql, $method );
760 * @param $method string
762 public function unlockTables( $method ) {
763 $this->query( "UNLOCK TABLES", $method );
767 * Get search engine class. All subclasses of this
768 * need to implement this if they wish to use searching.
772 public function getSearchEngine() {
773 return 'SearchMySQL';
780 public function setBigSelects( $value = true ) {
781 if ( $value === 'default' ) {
782 if ( $this->mDefaultBigSelects
=== null ) {
783 # Function hasn't been called before so it must already be set to the default
786 $value = $this->mDefaultBigSelects
;
788 } elseif ( $this->mDefaultBigSelects
=== null ) {
789 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
791 $encValue = $value ?
'1' : '0';
792 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
796 * DELETE where the condition is a join. MySql uses multi-table deletes.
797 * @param $delTable string
798 * @param $joinTable string
799 * @param $delVar string
800 * @param $joinVar string
801 * @param $conds array|string
803 * @return bool|ResultWrapper
805 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
807 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
810 $delTable = $this->tableName( $delTable );
811 $joinTable = $this->tableName( $joinTable );
812 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
814 if ( $conds != '*' ) {
815 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
818 return $this->query( $sql, $fname );
822 * Determines how long the server has been up
826 function getServerUptime() {
827 $vars = $this->getMysqlStatus( 'Uptime' );
828 return (int)$vars['Uptime'];
832 * Determines if the last failure was due to a deadlock
836 function wasDeadlock() {
837 return $this->lastErrno() == 1213;
841 * Determines if the last failure was due to a lock timeout
845 function wasLockTimeout() {
846 return $this->lastErrno() == 1205;
850 * Determines if the last query error was something that should be dealt
851 * with by pinging the connection and reissuing the query
855 function wasErrorReissuable() {
856 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
860 * Determines if the last failure was due to the database being read-only.
864 function wasReadOnlyError() {
865 return $this->lastErrno() == 1223 ||
866 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
872 * @param $temporary bool
873 * @param $fname string
875 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
876 $tmp = $temporary ?
'TEMPORARY ' : '';
877 $newName = $this->addIdentifierQuotes( $newName );
878 $oldName = $this->addIdentifierQuotes( $oldName );
879 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
880 $this->query( $query, $fname );
884 * List all tables on the database
886 * @param $prefix string Only show tables with this prefix, e.g. mw_
887 * @param $fname String: calling function name
890 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
891 $result = $this->query( "SHOW TABLES", $fname);
895 foreach( $result as $table ) {
896 $vars = get_object_vars($table);
897 $table = array_pop( $vars );
899 if( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
900 $endArray[] = $table;
909 * @param $fName string
910 * @return bool|ResultWrapper
912 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
913 if( !$this->tableExists( $tableName, $fName ) ) {
916 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
922 protected function getDefaultSchemaVars() {
923 $vars = parent
::getDefaultSchemaVars();
924 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
925 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
930 * Get status information from SHOW STATUS in an associative array
932 * @param $which string
935 function getMysqlStatus( $which = "%" ) {
936 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
939 foreach ( $res as $row ) {
940 $status[$row->Variable_name
] = $row->Value
;
949 * Legacy support: Database == DatabaseMysql
951 * @deprecated in 1.16
953 class Database
extends DatabaseMysql
{}
959 class MySQLField
implements Field
{
960 private $name, $tablename, $default, $max_length, $nullable,
961 $is_pk, $is_unique, $is_multiple, $is_key, $type;
963 function __construct ( $info ) {
964 $this->name
= $info->name
;
965 $this->tablename
= $info->table
;
966 $this->default = $info->def
;
967 $this->max_length
= $info->max_length
;
968 $this->nullable
= !$info->not_null
;
969 $this->is_pk
= $info->primary_key
;
970 $this->is_unique
= $info->unique_key
;
971 $this->is_multiple
= $info->multiple_key
;
972 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
973 $this->type
= $info->type
;
986 function tableName() {
987 return $this->tableName
;
1000 function isNullable() {
1001 return $this->nullable
;
1004 function defaultValue() {
1005 return $this->default;
1012 return $this->is_key
;
1018 function isMultipleKey() {
1019 return $this->is_multiple
;
1023 class MySQLMasterPos
implements DBMasterPos
{
1026 function __construct( $file, $pos ) {
1027 $this->file
= $file;
1031 function __toString() {
1032 return "{$this->file}/{$this->pos}";