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, $wgDBmysql5, $wgSQLMode;
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 wfProfileOut( __METHOD__
);
72 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
75 # Debugging hack -- fake cluster
76 if ( $wgAllDBsAreLocalhost ) {
77 $realServer = 'localhost';
79 $realServer = $server;
82 $this->mServer
= $server;
84 $this->mPassword
= $password;
85 $this->mDBname
= $dbName;
88 if ( $this->mFlags
& DBO_SSL
) {
89 $connFlags |
= MYSQL_CLIENT_SSL
;
91 if ( $this->mFlags
& DBO_COMPRESS
) {
92 $connFlags |
= MYSQL_CLIENT_COMPRESS
;
95 wfProfileIn( "dbconnect-$server" );
97 # The kernel's default SYN retransmission period is far too slow for us,
98 # so we use a short timeout plus a manual retry. Retrying means that a small
99 # but finite rate of SYN packet loss won't cause user-visible errors.
100 $this->mConn
= false;
101 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
106 $this->installErrorHandler();
107 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
111 if ( $this->mFlags
& DBO_PERSISTENT
) {
112 $this->mConn
= mysql_pconnect( $realServer, $user, $password, $connFlags );
114 # Create a new connection...
115 $this->mConn
= mysql_connect( $realServer, $user, $password, true, $connFlags );
117 #if ( $this->mConn === false ) {
119 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
122 $error = $this->restoreErrorHandler();
124 wfProfileOut( "dbconnect-$server" );
126 # Always log connection errors
127 if ( !$this->mConn
) {
129 $error = $this->lastError();
131 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
132 wfDebug( "DB connection error\n" .
133 "Server: $server, User: $user, Password: " .
134 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
136 wfProfileOut( __METHOD__
);
137 return $this->reportConnectionError( $error );
140 if ( $dbName != '' ) {
141 wfSuppressWarnings();
142 $success = mysql_select_db( $dbName, $this->mConn
);
145 wfLogDBError( "Error selecting database $dbName on server {$this->mServer}\n" );
146 wfDebug( "Error selecting database $dbName on server {$this->mServer} " .
147 "from client host " . wfHostname() . "\n" );
149 wfProfileOut( __METHOD__
);
150 return $this->reportConnectionError( "Error selecting database $dbName" );
154 // Tell the server we're communicating with it in UTF-8.
155 // This may engage various charset conversions.
157 $this->query( 'SET NAMES utf8', __METHOD__
);
159 $this->query( 'SET NAMES binary', __METHOD__
);
161 // 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 $this->mOpened
= true;
168 wfProfileOut( __METHOD__
);
175 protected function closeConnection() {
176 return mysql_close( $this->mConn
);
180 * @param $res ResultWrapper
181 * @throws DBUnexpectedError
183 function freeResult( $res ) {
184 if ( $res instanceof ResultWrapper
) {
187 wfSuppressWarnings();
188 $ok = mysql_free_result( $res );
191 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
196 * @param $res ResultWrapper
197 * @return object|bool
198 * @throws DBUnexpectedError
200 function fetchObject( $res ) {
201 if ( $res instanceof ResultWrapper
) {
204 wfSuppressWarnings();
205 $row = mysql_fetch_object( $res );
208 $errno = $this->lastErrno();
209 // Unfortunately, mysql_fetch_object does not reset the last errno.
210 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
211 // these are the only errors mysql_fetch_object can cause.
212 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
213 if ( $errno == 2000 ||
$errno == 2013 ) {
214 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
220 * @param $res ResultWrapper
222 * @throws DBUnexpectedError
224 function fetchRow( $res ) {
225 if ( $res instanceof ResultWrapper
) {
228 wfSuppressWarnings();
229 $row = mysql_fetch_array( $res );
232 $errno = $this->lastErrno();
233 // Unfortunately, mysql_fetch_array does not reset the last errno.
234 // Only check for CR_SERVER_LOST and CR_UNKNOWN_ERROR, as
235 // these are the only errors mysql_fetch_object can cause.
236 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
237 if ( $errno == 2000 ||
$errno == 2013 ) {
238 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
244 * @throws DBUnexpectedError
245 * @param $res ResultWrapper
248 function numRows( $res ) {
249 if ( $res instanceof ResultWrapper
) {
252 wfSuppressWarnings();
253 $n = mysql_num_rows( $res );
255 // Unfortunately, mysql_num_rows does not reset the last errno.
256 // We are not checking for any errors here, since
257 // these are no errors mysql_num_rows can cause.
258 // See http://dev.mysql.com/doc/refman/5.0/en/mysql-fetch-row.html.
259 // See https://bugzilla.wikimedia.org/42430
264 * @param $res ResultWrapper
267 function numFields( $res ) {
268 if ( $res instanceof ResultWrapper
) {
271 return mysql_num_fields( $res );
275 * @param $res ResultWrapper
279 function fieldName( $res, $n ) {
280 if ( $res instanceof ResultWrapper
) {
283 return mysql_field_name( $res, $n );
289 function insertId() {
290 return mysql_insert_id( $this->mConn
);
294 * @param $res ResultWrapper
298 function dataSeek( $res, $row ) {
299 if ( $res instanceof ResultWrapper
) {
302 return mysql_data_seek( $res, $row );
308 function lastErrno() {
309 if ( $this->mConn
) {
310 return mysql_errno( $this->mConn
);
312 return mysql_errno();
319 function lastError() {
320 if ( $this->mConn
) {
321 # Even if it's non-zero, it can still be invalid
322 wfSuppressWarnings();
323 $error = mysql_error( $this->mConn
);
325 $error = mysql_error();
329 $error = mysql_error();
332 $error .= ' (' . $this->mServer
. ')';
340 function affectedRows() {
341 return mysql_affected_rows( $this->mConn
);
345 * @param $table string
346 * @param $uniqueIndexes
348 * @param $fname string
349 * @return ResultWrapper
351 function replace( $table, $uniqueIndexes, $rows, $fname = __METHOD__
) {
352 return $this->nativeReplace( $table, $rows, $fname );
356 * Estimate rows in dataset
357 * Returns estimated count, based on EXPLAIN output
358 * Takes same arguments as Database::select()
360 * @param $table string|array
361 * @param $vars string|array
362 * @param $conds string|array
363 * @param $fname string
364 * @param $options string|array
367 public function estimateRowCount( $table, $vars = '*', $conds = '', $fname = __METHOD__
, $options = array() ) {
368 $options['EXPLAIN'] = true;
369 $res = $this->select( $table, $vars, $conds, $fname, $options );
370 if ( $res === false ) {
373 if ( !$this->numRows( $res ) ) {
378 foreach ( $res as $plan ) {
379 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
385 * @param $table string
386 * @param $field string
387 * @return bool|MySQLField
389 function fieldInfo( $table, $field ) {
390 $table = $this->tableName( $table );
391 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__
, true );
395 $n = mysql_num_fields( $res->result
);
396 for ( $i = 0; $i < $n; $i++
) {
397 $meta = mysql_fetch_field( $res->result
, $i );
398 if ( $field == $meta->name
) {
399 return new MySQLField( $meta );
406 * Get information about an index into an object
407 * Returns false if the index does not exist
409 * @param $table string
410 * @param $index string
411 * @param $fname string
412 * @return bool|array|null False or null on failure
414 function indexInfo( $table, $index, $fname = __METHOD__
) {
415 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
416 # SHOW INDEX should work for 3.x and up:
417 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
418 $table = $this->tableName( $table );
419 $index = $this->indexName( $index );
421 $sql = 'SHOW INDEX FROM ' . $table;
422 $res = $this->query( $sql, $fname );
430 foreach ( $res as $row ) {
431 if ( $row->Key_name
== $index ) {
435 return empty( $result ) ?
false : $result;
442 function selectDB( $db ) {
443 $this->mDBname
= $db;
444 return mysql_select_db( $db, $this->mConn
);
452 function strencode( $s ) {
453 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
455 if ( $sQuoted === false ) {
457 $sQuoted = mysql_real_escape_string( $s, $this->mConn
);
463 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
469 public function addIdentifierQuotes( $s ) {
470 return "`" . $this->strencode( $s ) . "`";
474 * @param $name string
477 public function isQuotedIdentifier( $name ) {
478 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
485 $ping = mysql_ping( $this->mConn
);
490 mysql_close( $this->mConn
);
491 $this->mOpened
= false;
492 $this->mConn
= false;
493 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
500 * This will do a SHOW SLAVE STATUS
505 if ( !is_null( $this->mFakeSlaveLag
) ) {
506 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
507 return $this->mFakeSlaveLag
;
510 return $this->getLagFromSlaveStatus();
516 function getLagFromSlaveStatus() {
517 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__
);
521 $row = $res->fetchObject();
525 if ( strval( $row->Seconds_Behind_Master
) === '' ) {
528 return intval( $row->Seconds_Behind_Master
);
533 * @deprecated in 1.19, use getLagFromSlaveStatus
537 function getLagFromProcesslist() {
538 wfDeprecated( __METHOD__
, '1.19' );
539 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__
);
543 # Find slave SQL thread
544 foreach ( $res as $row ) {
545 /* This should work for most situations - when default db
546 * for thread is not specified, it had no events executed,
547 * and therefore it doesn't know yet how lagged it is.
549 * Relay log I/O thread does not select databases.
551 if ( $row->User
== 'system user' &&
552 $row->State
!= 'Waiting for master to send event' &&
553 $row->State
!= 'Connecting to master' &&
554 $row->State
!= 'Queueing master event to the relay log' &&
555 $row->State
!= 'Waiting for master update' &&
556 $row->State
!= 'Requesting binlog dump' &&
557 $row->State
!= 'Waiting to reconnect after a failed master event read' &&
558 $row->State
!= 'Reconnecting after a failed master event read' &&
559 $row->State
!= 'Registering slave on master'
561 # This is it, return the time (except -ve)
562 if ( $row->Time
> 0x7fffffff ) {
573 * Wait for the slave to catch up to a given master position.
575 * @param $pos DBMasterPos object
576 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
577 * @return bool|string
579 function masterPosWait( DBMasterPos
$pos, $timeout ) {
581 wfProfileIn( $fname );
583 # Commit any open transactions
584 if ( $this->mTrxLevel
) {
585 $this->commit( $fname );
588 if ( !is_null( $this->mFakeSlaveLag
) ) {
589 $status = parent
::masterPosWait( $pos, $timeout );
590 wfProfileOut( $fname );
594 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
595 $encFile = $this->addQuotes( $pos->file
);
596 $encPos = intval( $pos->pos
);
597 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
598 $res = $this->doQuery( $sql );
600 if ( $res && $row = $this->fetchRow( $res ) ) {
601 wfProfileOut( $fname );
604 wfProfileOut( $fname );
609 * Get the position of the master from SHOW SLAVE STATUS
611 * @return MySQLMasterPos|bool
613 function getSlavePos() {
614 if ( !is_null( $this->mFakeSlaveLag
) ) {
615 return parent
::getSlavePos();
618 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
619 $row = $this->fetchObject( $res );
622 $pos = isset( $row->Exec_master_log_pos
) ?
$row->Exec_master_log_pos
: $row->Exec_Master_Log_Pos
;
623 return new MySQLMasterPos( $row->Relay_Master_Log_File
, $pos );
630 * Get the position of the master from SHOW MASTER STATUS
632 * @return MySQLMasterPos|bool
634 function getMasterPos() {
635 if ( $this->mFakeMaster
) {
636 return parent
::getMasterPos();
639 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
640 $row = $this->fetchObject( $res );
643 return new MySQLMasterPos( $row->File
, $row->Position
);
652 function getServerVersion() {
653 return mysql_get_server_info( $this->mConn
);
660 function useIndexClause( $index ) {
661 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
667 function lowPriorityOption() {
668 return 'LOW_PRIORITY';
674 public function getSoftwareLink() {
675 return '[http://www.mysql.com/ MySQL]';
679 * @param $options array
681 public function setSessionOptions( array $options ) {
682 if ( isset( $options['connTimeout'] ) ) {
683 $timeout = (int)$options['connTimeout'];
684 $this->query( "SET net_read_timeout=$timeout" );
685 $this->query( "SET net_write_timeout=$timeout" );
689 public function streamStatementEnd( &$sql, &$newLine ) {
690 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
691 preg_match( '/^DELIMITER\s+(\S+)/', $newLine, $m );
692 $this->delimiter
= $m[1];
695 return parent
::streamStatementEnd( $sql, $newLine );
699 * Check to see if a named lock is available. This is non-blocking.
701 * @param string $lockName name of lock to poll
702 * @param string $method name of method calling us
706 public function lockIsFree( $lockName, $method ) {
707 $lockName = $this->addQuotes( $lockName );
708 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
709 $row = $this->fetchObject( $result );
710 return ( $row->lockstatus
== 1 );
714 * @param $lockName string
715 * @param $method string
716 * @param $timeout int
719 public function lock( $lockName, $method, $timeout = 5 ) {
720 $lockName = $this->addQuotes( $lockName );
721 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
722 $row = $this->fetchObject( $result );
724 if ( $row->lockstatus
== 1 ) {
727 wfDebug( __METHOD__
. " failed to acquire lock\n" );
733 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
734 * @param $lockName string
735 * @param $method string
738 public function unlock( $lockName, $method ) {
739 $lockName = $this->addQuotes( $lockName );
740 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
741 $row = $this->fetchObject( $result );
742 return ( $row->lockstatus
== 1 );
747 * @param $write array
748 * @param $method string
749 * @param $lowPriority bool
752 public function lockTables( $read, $write, $method, $lowPriority = true ) {
755 foreach ( $write as $table ) {
756 $tbl = $this->tableName( $table ) .
757 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
761 foreach ( $read as $table ) {
762 $items[] = $this->tableName( $table ) . ' READ';
764 $sql = "LOCK TABLES " . implode( ',', $items );
765 $this->query( $sql, $method );
770 * @param $method string
773 public function unlockTables( $method ) {
774 $this->query( "UNLOCK TABLES", $method );
779 * Get search engine class. All subclasses of this
780 * need to implement this if they wish to use searching.
784 public function getSearchEngine() {
785 return 'SearchMySQL';
792 public function setBigSelects( $value = true ) {
793 if ( $value === 'default' ) {
794 if ( $this->mDefaultBigSelects
=== null ) {
795 # Function hasn't been called before so it must already be set to the default
798 $value = $this->mDefaultBigSelects
;
800 } elseif ( $this->mDefaultBigSelects
=== null ) {
801 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
803 $encValue = $value ?
'1' : '0';
804 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
808 * DELETE where the condition is a join. MySql uses multi-table deletes.
809 * @param $delTable string
810 * @param $joinTable string
811 * @param $delVar string
812 * @param $joinVar string
813 * @param $conds array|string
814 * @param bool|string $fname bool
815 * @throws DBUnexpectedError
816 * @return bool|ResultWrapper
818 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = __METHOD__
) {
820 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
823 $delTable = $this->tableName( $delTable );
824 $joinTable = $this->tableName( $joinTable );
825 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
827 if ( $conds != '*' ) {
828 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND
);
831 return $this->query( $sql, $fname );
835 * Determines how long the server has been up
839 function getServerUptime() {
840 $vars = $this->getMysqlStatus( 'Uptime' );
841 return (int)$vars['Uptime'];
845 * Determines if the last failure was due to a deadlock
849 function wasDeadlock() {
850 return $this->lastErrno() == 1213;
854 * Determines if the last failure was due to a lock timeout
858 function wasLockTimeout() {
859 return $this->lastErrno() == 1205;
863 * Determines if the last query error was something that should be dealt
864 * with by pinging the connection and reissuing the query
868 function wasErrorReissuable() {
869 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
873 * Determines if the last failure was due to the database being read-only.
877 function wasReadOnlyError() {
878 return $this->lastErrno() == 1223 ||
879 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
885 * @param $temporary bool
886 * @param $fname string
888 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = __METHOD__
) {
889 $tmp = $temporary ?
'TEMPORARY ' : '';
890 $newName = $this->addIdentifierQuotes( $newName );
891 $oldName = $this->addIdentifierQuotes( $oldName );
892 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
893 $this->query( $query, $fname );
897 * List all tables on the database
899 * @param string $prefix Only show tables with this prefix, e.g. mw_
900 * @param string $fname calling function name
903 function listTables( $prefix = null, $fname = __METHOD__
) {
904 $result = $this->query( "SHOW TABLES", $fname );
908 foreach ( $result as $table ) {
909 $vars = get_object_vars( $table );
910 $table = array_pop( $vars );
912 if ( !$prefix ||
strpos( $table, $prefix ) === 0 ) {
913 $endArray[] = $table;
922 * @param $fName string
923 * @return bool|ResultWrapper
925 public function dropTable( $tableName, $fName = __METHOD__
) {
926 if ( !$this->tableExists( $tableName, $fName ) ) {
929 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
935 protected function getDefaultSchemaVars() {
936 $vars = parent
::getDefaultSchemaVars();
937 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
938 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
943 * Get status information from SHOW STATUS in an associative array
945 * @param $which string
948 function getMysqlStatus( $which = "%" ) {
949 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
952 foreach ( $res as $row ) {
953 $status[$row->Variable_name
] = $row->Value
;
965 class MySQLField
implements Field
{
966 private $name, $tablename, $default, $max_length, $nullable,
967 $is_pk, $is_unique, $is_multiple, $is_key, $type;
969 function __construct( $info ) {
970 $this->name
= $info->name
;
971 $this->tablename
= $info->table
;
972 $this->default = $info->def
;
973 $this->max_length
= $info->max_length
;
974 $this->nullable
= !$info->not_null
;
975 $this->is_pk
= $info->primary_key
;
976 $this->is_unique
= $info->unique_key
;
977 $this->is_multiple
= $info->multiple_key
;
978 $this->is_key
= ( $this->is_pk ||
$this->is_unique ||
$this->is_multiple
);
979 $this->type
= $info->type
;
992 function tableName() {
993 return $this->tableName
;
1006 function isNullable() {
1007 return $this->nullable
;
1010 function defaultValue() {
1011 return $this->default;
1018 return $this->is_key
;
1024 function isMultipleKey() {
1025 return $this->is_multiple
;
1029 class MySQLMasterPos
implements DBMasterPos
{
1032 function __construct( $file, $pos ) {
1033 $this->file
= $file;
1037 function __toString() {
1038 return "{$this->file}/{$this->pos}";