48b21a2486d14479c47d6f7b85a9ee25c85e2215
3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
9 class DatabaseMysql
extends DatabaseBase
{
10 /*private*/ function doQuery( $sql ) {
11 if( $this->bufferResults() ) {
12 $ret = mysql_query( $sql, $this->mConn
);
14 $ret = mysql_unbuffered_query( $sql, $this->mConn
);
19 function open( $server, $user, $password, $dbName ) {
20 global $wgAllDBsAreLocalhost;
21 wfProfileIn( __METHOD__
);
23 # Test for missing mysql.so
24 # First try to load it
25 if (!@extension_loaded
('mysql')) {
30 # Otherwise we get a suppressed fatal error, which is very hard to track down
31 if ( !function_exists( 'mysql_connect' ) ) {
32 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
35 # Debugging hack -- fake cluster
36 if ( $wgAllDBsAreLocalhost ) {
37 $realServer = 'localhost';
39 $realServer = $server;
42 $this->mServer
= $server;
44 $this->mPassword
= $password;
45 $this->mDBname
= $dbName;
49 wfProfileIn("dbconnect-$server");
51 # The kernel's default SYN retransmission period is far too slow for us,
52 # so we use a short timeout plus a manual retry. Retrying means that a small
53 # but finite rate of SYN packet loss won't cause user-visible errors.
55 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
60 $this->installErrorHandler();
61 for ( $i = 0; $i < $numAttempts && !$this->mConn
; $i++
) {
65 if ( $this->mFlags
& DBO_PERSISTENT
) {
66 $this->mConn
= mysql_pconnect( $realServer, $user, $password );
68 # Create a new connection...
69 $this->mConn
= mysql_connect( $realServer, $user, $password, true );
71 if ($this->mConn
=== false) {
73 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
76 $phpError = $this->restoreErrorHandler();
77 # Always log connection errors
78 if ( !$this->mConn
) {
79 $error = $this->lastError();
83 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
84 wfDebug( "DB connection error\n" );
85 wfDebug( "Server: $server, User: $user, Password: " .
86 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
90 wfProfileOut("dbconnect-$server");
92 if ( $dbName != '' && $this->mConn
!== false ) {
93 $success = @/**/mysql_select_db( $dbName, $this->mConn
);
95 $error = "Error selecting database $dbName on server {$this->mServer} " .
96 "from client host " . wfHostname() . "\n";
97 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
102 $success = (bool)$this->mConn
;
106 $version = $this->getServerVersion();
107 if ( version_compare( $version, '4.1' ) >= 0 ) {
108 // Tell the server we're communicating with it in UTF-8.
109 // This may engage various charset conversions.
112 $this->query( 'SET NAMES utf8', __METHOD__
);
114 // Turn off strict mode
115 $this->query( "SET sql_mode = ''", __METHOD__
);
118 // Turn off strict mode if it is on
120 $this->reportConnectionError( $phpError );
123 $this->mOpened
= $success;
124 wfProfileOut( __METHOD__
);
129 $this->mOpened
= false;
130 if ( $this->mConn
) {
131 if ( $this->trxLevel() ) {
132 $this->immediateCommit();
134 return mysql_close( $this->mConn
);
140 function freeResult( $res ) {
141 if ( $res instanceof ResultWrapper
) {
144 if ( !@/**/mysql_free_result( $res ) ) {
145 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
149 function fetchObject( $res ) {
150 if ( $res instanceof ResultWrapper
) {
153 @/**/$row = mysql_fetch_object( $res );
154 if( $this->lastErrno() ) {
155 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
160 function fetchRow( $res ) {
161 if ( $res instanceof ResultWrapper
) {
164 @/**/$row = mysql_fetch_array( $res );
165 if ( $this->lastErrno() ) {
166 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
171 function numRows( $res ) {
172 if ( $res instanceof ResultWrapper
) {
175 @/**/$n = mysql_num_rows( $res );
176 if( $this->lastErrno() ) {
177 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
182 function numFields( $res ) {
183 if ( $res instanceof ResultWrapper
) {
186 return mysql_num_fields( $res );
189 function fieldName( $res, $n ) {
190 if ( $res instanceof ResultWrapper
) {
193 return mysql_field_name( $res, $n );
196 function insertId() { return mysql_insert_id( $this->mConn
); }
198 function dataSeek( $res, $row ) {
199 if ( $res instanceof ResultWrapper
) {
202 return mysql_data_seek( $res, $row );
205 function lastErrno() {
206 if ( $this->mConn
) {
207 return mysql_errno( $this->mConn
);
209 return mysql_errno();
213 function lastError() {
214 if ( $this->mConn
) {
215 # Even if it's non-zero, it can still be invalid
216 wfSuppressWarnings();
217 $error = mysql_error( $this->mConn
);
219 $error = mysql_error();
223 $error = mysql_error();
226 $error .= ' (' . $this->mServer
. ')';
231 function affectedRows() { return mysql_affected_rows( $this->mConn
); }
234 * Estimate rows in dataset
235 * Returns estimated count, based on EXPLAIN output
236 * Takes same arguments as Database::select()
238 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
239 $options['EXPLAIN'] = true;
240 $res = $this->select( $table, $vars, $conds, $fname, $options );
241 if ( $res === false )
243 if ( !$this->numRows( $res ) ) {
244 $this->freeResult($res);
249 while( $plan = $this->fetchObject( $res ) ) {
250 $rows *= $plan->rows
> 0 ?
$plan->rows
: 1; // avoid resetting to zero
253 $this->freeResult($res);
257 function fieldInfo( $table, $field ) {
258 $table = $this->tableName( $table );
259 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
260 $n = mysql_num_fields( $res->result
);
261 for( $i = 0; $i < $n; $i++
) {
262 $meta = mysql_fetch_field( $res->result
, $i );
263 if( $field == $meta->name
) {
264 return new MySQLField($meta);
270 function selectDB( $db ) {
271 $this->mDBname
= $db;
272 return mysql_select_db( $db, $this->mConn
);
275 function strencode( $s ) {
276 return mysql_real_escape_string( $s, $this->mConn
);
280 if( !function_exists( 'mysql_ping' ) ) {
281 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
284 $ping = mysql_ping( $this->mConn
);
289 // Need to reconnect manually in MySQL client 5.0.13+
290 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
291 mysql_close( $this->mConn
);
292 $this->mOpened
= false;
293 $this->mConn
= false;
294 $this->open( $this->mServer
, $this->mUser
, $this->mPassword
, $this->mDBname
);
300 function getServerVersion() {
301 return mysql_get_server_info( $this->mConn
);
304 function useIndexClause( $index ) {
305 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
308 function lowPriorityOption() {
309 return 'LOW_PRIORITY';
312 function getSoftwareLink() {
313 return '[http://www.mysql.com/ MySQL]';
316 function standardSelectDistinct() {
320 public function setTimeout( $timeout ) {
321 $this->query( "SET net_read_timeout=$timeout" );
322 $this->query( "SET net_write_timeout=$timeout" );
325 public function lock( $lockName, $method, $timeout = 5 ) {
326 $lockName = $this->addQuotes( $lockName );
327 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
328 $row = $this->fetchObject( $result );
329 $this->freeResult( $result );
331 if( $row->lockstatus
== 1 ) {
334 wfDebug( __METHOD__
." failed to acquire lock\n" );
339 public function unlock( $lockName, $method ) {
340 $lockName = $this->addQuotes( $lockName );
341 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
342 $row = $this->fetchObject( $result );
343 return $row->lockstatus
;
346 public function lockTables( $read, $write, $method, $lowPriority = true ) {
349 foreach( $write as $table ) {
350 $tbl = $this->tableName( $table ) .
351 ( $lowPriority ?
' LOW_PRIORITY' : '' ) .
355 foreach( $read as $table ) {
356 $items[] = $this->tableName( $table ) . ' READ';
358 $sql = "LOCK TABLES " . implode( ',', $items );
359 $this->query( $sql, $method );
362 public function unlockTables( $method ) {
363 $this->query( "UNLOCK TABLES", $method );
366 public function setBigSelects( $value = true ) {
367 if ( $value === 'default' ) {
368 if ( $this->mDefaultBigSelects
=== null ) {
369 # Function hasn't been called before so it must already be set to the default
372 $value = $this->mDefaultBigSelects
;
374 } elseif ( $this->mDefaultBigSelects
=== null ) {
375 $this->mDefaultBigSelects
= (bool)$this->selectField( false, '@@sql_big_selects' );
377 $encValue = $value ?
'1' : '0';
378 $this->query( "SET sql_big_selects=$encValue", __METHOD__
);
383 * Determines if the last failure was due to a deadlock
385 function wasDeadlock() {
386 return $this->lastErrno() == 1213;
390 * Determines if the last query error was something that should be dealt
391 * with by pinging the connection and reissuing the query
393 function wasErrorReissuable() {
394 return $this->lastErrno() == 2013 ||
$this->lastErrno() == 2006;
398 * Determines if the last failure was due to the database being read-only.
400 function wasReadOnlyError() {
401 return $this->lastErrno() == 1223 ||
402 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
408 * Legacy support: Database == DatabaseMysql
410 class Database
extends DatabaseMysql
{}
412 class MySQLMasterPos
{
415 function __construct( $file, $pos ) {
420 function __toString() {
421 return "{$this->file}/{$this->pos}";