Partial revert of r56602: remove what is probably accidentally committed debugging...
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * Database abstraction object for mySQL
4 * Inherit all methods and properties of Database::Database()
5 *
6 * @ingroup Database
7 * @see Database
8 */
9 class DatabaseMysql extends DatabaseBase {
10 /*private*/ function doQuery( $sql ) {
11 if( $this->bufferResults() ) {
12 $ret = mysql_query( $sql, $this->mConn );
13 } else {
14 $ret = mysql_unbuffered_query( $sql, $this->mConn );
15 }
16 return $ret;
17 }
18
19 function open( $server, $user, $password, $dbName ) {
20 global $wgAllDBsAreLocalhost;
21 wfProfileIn( __METHOD__ );
22
23 # Test for missing mysql.so
24 # First try to load it
25 if (!@extension_loaded('mysql')) {
26 @dl('mysql.so');
27 }
28
29 # Fail now
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" );
33 }
34
35 # Debugging hack -- fake cluster
36 if ( $wgAllDBsAreLocalhost ) {
37 $realServer = 'localhost';
38 } else {
39 $realServer = $server;
40 }
41 $this->close();
42 $this->mServer = $server;
43 $this->mUser = $user;
44 $this->mPassword = $password;
45 $this->mDBname = $dbName;
46
47 $success = false;
48
49 wfProfileIn("dbconnect-$server");
50
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.
54 $this->mConn = false;
55 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
56 $numAttempts = 2;
57 } else {
58 $numAttempts = 1;
59 }
60 $this->installErrorHandler();
61 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
62 if ( $i > 1 ) {
63 usleep( 1000 );
64 }
65 if ( $this->mFlags & DBO_PERSISTENT ) {
66 $this->mConn = mysql_pconnect( $realServer, $user, $password );
67 } else {
68 # Create a new connection...
69 $this->mConn = mysql_connect( $realServer, $user, $password, true );
70 }
71 if ($this->mConn === false) {
72 #$iplus = $i + 1;
73 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
74 }
75 }
76 $phpError = $this->restoreErrorHandler();
77 # Always log connection errors
78 if ( !$this->mConn ) {
79 $error = $this->lastError();
80 if ( !$error ) {
81 $error = $phpError;
82 }
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" );
87 $success = false;
88 }
89
90 wfProfileOut("dbconnect-$server");
91
92 if ( $dbName != '' && $this->mConn !== false ) {
93 $success = @/**/mysql_select_db( $dbName, $this->mConn );
94 if ( !$success ) {
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");
98 wfDebug( $error );
99 }
100 } else {
101 # Delay USE query
102 $success = (bool)$this->mConn;
103 }
104
105 if ( $success ) {
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.
110 global $wgDBmysql5;
111 if( $wgDBmysql5 ) {
112 $this->query( 'SET NAMES utf8', __METHOD__ );
113 }
114 // Turn off strict mode
115 $this->query( "SET sql_mode = ''", __METHOD__ );
116 }
117
118 // Turn off strict mode if it is on
119 } else {
120 $this->reportConnectionError( $phpError );
121 }
122
123 $this->mOpened = $success;
124 wfProfileOut( __METHOD__ );
125 return $success;
126 }
127
128 function close() {
129 $this->mOpened = false;
130 if ( $this->mConn ) {
131 if ( $this->trxLevel() ) {
132 $this->immediateCommit();
133 }
134 return mysql_close( $this->mConn );
135 } else {
136 return true;
137 }
138 }
139
140 function freeResult( $res ) {
141 if ( $res instanceof ResultWrapper ) {
142 $res = $res->result;
143 }
144 if ( !@/**/mysql_free_result( $res ) ) {
145 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
146 }
147 }
148
149 function fetchObject( $res ) {
150 if ( $res instanceof ResultWrapper ) {
151 $res = $res->result;
152 }
153 @/**/$row = mysql_fetch_object( $res );
154 if( $this->lastErrno() ) {
155 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
156 }
157 return $row;
158 }
159
160 function fetchRow( $res ) {
161 if ( $res instanceof ResultWrapper ) {
162 $res = $res->result;
163 }
164 @/**/$row = mysql_fetch_array( $res );
165 if ( $this->lastErrno() ) {
166 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
167 }
168 return $row;
169 }
170
171 function numRows( $res ) {
172 if ( $res instanceof ResultWrapper ) {
173 $res = $res->result;
174 }
175 @/**/$n = mysql_num_rows( $res );
176 if( $this->lastErrno() ) {
177 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
178 }
179 return $n;
180 }
181
182 function numFields( $res ) {
183 if ( $res instanceof ResultWrapper ) {
184 $res = $res->result;
185 }
186 return mysql_num_fields( $res );
187 }
188
189 function fieldName( $res, $n ) {
190 if ( $res instanceof ResultWrapper ) {
191 $res = $res->result;
192 }
193 return mysql_field_name( $res, $n );
194 }
195
196 function insertId() { return mysql_insert_id( $this->mConn ); }
197
198 function dataSeek( $res, $row ) {
199 if ( $res instanceof ResultWrapper ) {
200 $res = $res->result;
201 }
202 return mysql_data_seek( $res, $row );
203 }
204
205 function lastErrno() {
206 if ( $this->mConn ) {
207 return mysql_errno( $this->mConn );
208 } else {
209 return mysql_errno();
210 }
211 }
212
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 );
218 if ( !$error ) {
219 $error = mysql_error();
220 }
221 wfRestoreWarnings();
222 } else {
223 $error = mysql_error();
224 }
225 if( $error ) {
226 $error .= ' (' . $this->mServer . ')';
227 }
228 return $error;
229 }
230
231 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
232
233 function fieldInfo( $table, $field ) {
234 $table = $this->tableName( $table );
235 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
236 $n = mysql_num_fields( $res->result );
237 for( $i = 0; $i < $n; $i++ ) {
238 $meta = mysql_fetch_field( $res->result, $i );
239 if( $field == $meta->name ) {
240 return new MySQLField($meta);
241 }
242 }
243 return false;
244 }
245
246 function selectDB( $db ) {
247 $this->mDBname = $db;
248 return mysql_select_db( $db, $this->mConn );
249 }
250
251 function strencode( $s ) {
252 return mysql_real_escape_string( $s, $this->mConn );
253 }
254
255 function ping() {
256 if( !function_exists( 'mysql_ping' ) ) {
257 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
258 return true;
259 }
260 $ping = mysql_ping( $this->mConn );
261 if ( $ping ) {
262 return true;
263 }
264
265 // Need to reconnect manually in MySQL client 5.0.13+
266 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
267 mysql_close( $this->mConn );
268 $this->mOpened = false;
269 $this->mConn = false;
270 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
271 return true;
272 }
273 return false;
274 }
275
276 function getServerVersion() {
277 return mysql_get_server_info( $this->mConn );
278 }
279
280 function useIndexClause( $index ) {
281 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
282 }
283
284 function lowPriorityOption() {
285 return 'LOW_PRIORITY';
286 }
287
288 function getSoftwareLink() {
289 return '[http://www.mysql.com/ MySQL]';
290 }
291
292 function standardSelectDistinct() {
293 return false;
294 }
295
296 public function setTimeout( $timeout ) {
297 $this->query( "SET net_read_timeout=$timeout" );
298 $this->query( "SET net_write_timeout=$timeout" );
299 }
300
301 public function lock( $lockName, $method, $timeout = 5 ) {
302 $lockName = $this->addQuotes( $lockName );
303 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
304 $row = $this->fetchObject( $result );
305 $this->freeResult( $result );
306
307 if( $row->lockstatus == 1 ) {
308 return true;
309 } else {
310 wfDebug( __METHOD__." failed to acquire lock\n" );
311 return false;
312 }
313 }
314
315 public function unlock( $lockName, $method ) {
316 $lockName = $this->addQuotes( $lockName );
317 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
318 $row = $this->fetchObject( $result );
319 return $row->lockstatus;
320 }
321
322 public function lockTables( $read, $write, $method, $lowPriority = true ) {
323 $items = array();
324
325 foreach( $write as $table ) {
326 $tbl = $this->tableName( $table ) .
327 $lowPriority ? ' LOW_PRIORITY' : '' .
328 ' WRITE';
329 $items[] = $tbl;
330 }
331 foreach( $read as $table ) {
332 $items[] = $this->tableName( $table ) . ' READ';
333 }
334 $sql = "LOCK TABLES " . implode( ',', $items );
335 $this->query( $sql, $method );
336 }
337
338 public function unlockTables( $method ) {
339 $this->query( "UNLOCK TABLES", $method );
340 }
341
342 public function setBigSelects( $value = true ) {
343 if ( $value === 'default' ) {
344 if ( $this->mDefaultBigSelects === null ) {
345 # Function hasn't been called before so it must already be set to the default
346 return;
347 } else {
348 $value = $this->mDefaultBigSelects;
349 }
350 } elseif ( $this->mDefaultBigSelects === null ) {
351 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
352 }
353 $encValue = $value ? '1' : '0';
354 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
355 }
356
357
358 /**
359 * Determines if the last failure was due to a deadlock
360 */
361 function wasDeadlock() {
362 return $this->lastErrno() == 1213;
363 }
364
365 /**
366 * Determines if the last query error was something that should be dealt
367 * with by pinging the connection and reissuing the query
368 */
369 function wasErrorReissuable() {
370 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
371 }
372
373 /**
374 * Determines if the last failure was due to the database being read-only.
375 */
376 function wasReadOnlyError() {
377 return $this->lastErrno() == 1223 ||
378 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
379 }
380
381 }
382
383 /**
384 * Legacy support: Database == DatabaseMysql
385 */
386 class Database extends DatabaseMysql {}
387
388 class MySQLMasterPos {
389 var $file, $pos;
390
391 function __construct( $file, $pos ) {
392 $this->file = $file;
393 $this->pos = $pos;
394 }
395
396 function __toString() {
397 return "{$this->file}/{$this->pos}";
398 }
399 }