48b21a2486d14479c47d6f7b85a9ee25c85e2215
[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 /**
234 * Estimate rows in dataset
235 * Returns estimated count, based on EXPLAIN output
236 * Takes same arguments as Database::select()
237 */
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 )
242 return false;
243 if ( !$this->numRows( $res ) ) {
244 $this->freeResult($res);
245 return 0;
246 }
247
248 $rows = 1;
249 while( $plan = $this->fetchObject( $res ) ) {
250 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
251 }
252
253 $this->freeResult($res);
254 return $rows;
255 }
256
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);
265 }
266 }
267 return false;
268 }
269
270 function selectDB( $db ) {
271 $this->mDBname = $db;
272 return mysql_select_db( $db, $this->mConn );
273 }
274
275 function strencode( $s ) {
276 return mysql_real_escape_string( $s, $this->mConn );
277 }
278
279 function ping() {
280 if( !function_exists( 'mysql_ping' ) ) {
281 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
282 return true;
283 }
284 $ping = mysql_ping( $this->mConn );
285 if ( $ping ) {
286 return true;
287 }
288
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 );
295 return true;
296 }
297 return false;
298 }
299
300 function getServerVersion() {
301 return mysql_get_server_info( $this->mConn );
302 }
303
304 function useIndexClause( $index ) {
305 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
306 }
307
308 function lowPriorityOption() {
309 return 'LOW_PRIORITY';
310 }
311
312 function getSoftwareLink() {
313 return '[http://www.mysql.com/ MySQL]';
314 }
315
316 function standardSelectDistinct() {
317 return false;
318 }
319
320 public function setTimeout( $timeout ) {
321 $this->query( "SET net_read_timeout=$timeout" );
322 $this->query( "SET net_write_timeout=$timeout" );
323 }
324
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 );
330
331 if( $row->lockstatus == 1 ) {
332 return true;
333 } else {
334 wfDebug( __METHOD__." failed to acquire lock\n" );
335 return false;
336 }
337 }
338
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;
344 }
345
346 public function lockTables( $read, $write, $method, $lowPriority = true ) {
347 $items = array();
348
349 foreach( $write as $table ) {
350 $tbl = $this->tableName( $table ) .
351 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
352 ' WRITE';
353 $items[] = $tbl;
354 }
355 foreach( $read as $table ) {
356 $items[] = $this->tableName( $table ) . ' READ';
357 }
358 $sql = "LOCK TABLES " . implode( ',', $items );
359 $this->query( $sql, $method );
360 }
361
362 public function unlockTables( $method ) {
363 $this->query( "UNLOCK TABLES", $method );
364 }
365
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
370 return;
371 } else {
372 $value = $this->mDefaultBigSelects;
373 }
374 } elseif ( $this->mDefaultBigSelects === null ) {
375 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
376 }
377 $encValue = $value ? '1' : '0';
378 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
379 }
380
381
382 /**
383 * Determines if the last failure was due to a deadlock
384 */
385 function wasDeadlock() {
386 return $this->lastErrno() == 1213;
387 }
388
389 /**
390 * Determines if the last query error was something that should be dealt
391 * with by pinging the connection and reissuing the query
392 */
393 function wasErrorReissuable() {
394 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
395 }
396
397 /**
398 * Determines if the last failure was due to the database being read-only.
399 */
400 function wasReadOnlyError() {
401 return $this->lastErrno() == 1223 ||
402 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
403 }
404
405 }
406
407 /**
408 * Legacy support: Database == DatabaseMysql
409 */
410 class Database extends DatabaseMysql {}
411
412 class MySQLMasterPos {
413 var $file, $pos;
414
415 function __construct( $file, $pos ) {
416 $this->file = $file;
417 $this->pos = $pos;
418 }
419
420 function __toString() {
421 return "{$this->file}/{$this->pos}";
422 }
423 }