For r60757: implement Database::getType() explicitly in each subclass, to make Roan...
[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 function getType() {
11 return 'mysql';
12 }
13
14 /*private*/ function doQuery( $sql ) {
15 if( $this->bufferResults() ) {
16 $ret = mysql_query( $sql, $this->mConn );
17 } else {
18 $ret = mysql_unbuffered_query( $sql, $this->mConn );
19 }
20 return $ret;
21 }
22
23 function open( $server, $user, $password, $dbName ) {
24 global $wgAllDBsAreLocalhost;
25 wfProfileIn( __METHOD__ );
26
27 # Test for missing mysql.so
28 # First try to load it
29 if (!@extension_loaded('mysql')) {
30 @dl('mysql.so');
31 }
32
33 # Fail now
34 # Otherwise we get a suppressed fatal error, which is very hard to track down
35 if ( !function_exists( 'mysql_connect' ) ) {
36 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
37 }
38
39 # Debugging hack -- fake cluster
40 if ( $wgAllDBsAreLocalhost ) {
41 $realServer = 'localhost';
42 } else {
43 $realServer = $server;
44 }
45 $this->close();
46 $this->mServer = $server;
47 $this->mUser = $user;
48 $this->mPassword = $password;
49 $this->mDBname = $dbName;
50
51 $success = false;
52
53 wfProfileIn("dbconnect-$server");
54
55 # The kernel's default SYN retransmission period is far too slow for us,
56 # so we use a short timeout plus a manual retry. Retrying means that a small
57 # but finite rate of SYN packet loss won't cause user-visible errors.
58 $this->mConn = false;
59 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
60 $numAttempts = 2;
61 } else {
62 $numAttempts = 1;
63 }
64 $this->installErrorHandler();
65 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
66 if ( $i > 1 ) {
67 usleep( 1000 );
68 }
69 if ( $this->mFlags & DBO_PERSISTENT ) {
70 $this->mConn = mysql_pconnect( $realServer, $user, $password );
71 } else {
72 # Create a new connection...
73 $this->mConn = mysql_connect( $realServer, $user, $password, true );
74 }
75 if ($this->mConn === false) {
76 #$iplus = $i + 1;
77 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
78 }
79 }
80 $phpError = $this->restoreErrorHandler();
81 # Always log connection errors
82 if ( !$this->mConn ) {
83 $error = $this->lastError();
84 if ( !$error ) {
85 $error = $phpError;
86 }
87 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
88 wfDebug( "DB connection error\n" );
89 wfDebug( "Server: $server, User: $user, Password: " .
90 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
91 $success = false;
92 }
93
94 wfProfileOut("dbconnect-$server");
95
96 if ( $dbName != '' && $this->mConn !== false ) {
97 $success = @/**/mysql_select_db( $dbName, $this->mConn );
98 if ( !$success ) {
99 $error = "Error selecting database $dbName on server {$this->mServer} " .
100 "from client host " . wfHostname() . "\n";
101 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
102 wfDebug( $error );
103 }
104 } else {
105 # Delay USE query
106 $success = (bool)$this->mConn;
107 }
108
109 if ( $success ) {
110 $version = $this->getServerVersion();
111 if ( version_compare( $version, '4.1' ) >= 0 ) {
112 // Tell the server we're communicating with it in UTF-8.
113 // This may engage various charset conversions.
114 global $wgDBmysql5;
115 if( $wgDBmysql5 ) {
116 $this->query( 'SET NAMES utf8', __METHOD__ );
117 }
118 // Turn off strict mode
119 $this->query( "SET sql_mode = ''", __METHOD__ );
120 }
121
122 // Turn off strict mode if it is on
123 } else {
124 $this->reportConnectionError( $phpError );
125 }
126
127 $this->mOpened = $success;
128 wfProfileOut( __METHOD__ );
129 return $success;
130 }
131
132 function close() {
133 $this->mOpened = false;
134 if ( $this->mConn ) {
135 if ( $this->trxLevel() ) {
136 $this->commit();
137 }
138 return mysql_close( $this->mConn );
139 } else {
140 return true;
141 }
142 }
143
144 function freeResult( $res ) {
145 if ( $res instanceof ResultWrapper ) {
146 $res = $res->result;
147 }
148 if ( !@/**/mysql_free_result( $res ) ) {
149 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
150 }
151 }
152
153 function fetchObject( $res ) {
154 if ( $res instanceof ResultWrapper ) {
155 $res = $res->result;
156 }
157 @/**/$row = mysql_fetch_object( $res );
158 if( $this->lastErrno() ) {
159 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
160 }
161 return $row;
162 }
163
164 function fetchRow( $res ) {
165 if ( $res instanceof ResultWrapper ) {
166 $res = $res->result;
167 }
168 @/**/$row = mysql_fetch_array( $res );
169 if ( $this->lastErrno() ) {
170 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
171 }
172 return $row;
173 }
174
175 function numRows( $res ) {
176 if ( $res instanceof ResultWrapper ) {
177 $res = $res->result;
178 }
179 @/**/$n = mysql_num_rows( $res );
180 if( $this->lastErrno() ) {
181 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
182 }
183 return $n;
184 }
185
186 function numFields( $res ) {
187 if ( $res instanceof ResultWrapper ) {
188 $res = $res->result;
189 }
190 return mysql_num_fields( $res );
191 }
192
193 function fieldName( $res, $n ) {
194 if ( $res instanceof ResultWrapper ) {
195 $res = $res->result;
196 }
197 return mysql_field_name( $res, $n );
198 }
199
200 function insertId() { return mysql_insert_id( $this->mConn ); }
201
202 function dataSeek( $res, $row ) {
203 if ( $res instanceof ResultWrapper ) {
204 $res = $res->result;
205 }
206 return mysql_data_seek( $res, $row );
207 }
208
209 function lastErrno() {
210 if ( $this->mConn ) {
211 return mysql_errno( $this->mConn );
212 } else {
213 return mysql_errno();
214 }
215 }
216
217 function lastError() {
218 if ( $this->mConn ) {
219 # Even if it's non-zero, it can still be invalid
220 wfSuppressWarnings();
221 $error = mysql_error( $this->mConn );
222 if ( !$error ) {
223 $error = mysql_error();
224 }
225 wfRestoreWarnings();
226 } else {
227 $error = mysql_error();
228 }
229 if( $error ) {
230 $error .= ' (' . $this->mServer . ')';
231 }
232 return $error;
233 }
234
235 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
236
237 /**
238 * Estimate rows in dataset
239 * Returns estimated count, based on EXPLAIN output
240 * Takes same arguments as Database::select()
241 */
242 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'Database::estimateRowCount', $options = array() ) {
243 $options['EXPLAIN'] = true;
244 $res = $this->select( $table, $vars, $conds, $fname, $options );
245 if ( $res === false )
246 return false;
247 if ( !$this->numRows( $res ) ) {
248 $this->freeResult($res);
249 return 0;
250 }
251
252 $rows = 1;
253 while( $plan = $this->fetchObject( $res ) ) {
254 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
255 }
256
257 $this->freeResult($res);
258 return $rows;
259 }
260
261 function fieldInfo( $table, $field ) {
262 $table = $this->tableName( $table );
263 $res = $this->query( "SELECT * FROM $table LIMIT 1" );
264 $n = mysql_num_fields( $res->result );
265 for( $i = 0; $i < $n; $i++ ) {
266 $meta = mysql_fetch_field( $res->result, $i );
267 if( $field == $meta->name ) {
268 return new MySQLField($meta);
269 }
270 }
271 return false;
272 }
273
274 function selectDB( $db ) {
275 $this->mDBname = $db;
276 return mysql_select_db( $db, $this->mConn );
277 }
278
279 function strencode( $s ) {
280 return mysql_real_escape_string( $s, $this->mConn );
281 }
282
283 function ping() {
284 if( !function_exists( 'mysql_ping' ) ) {
285 wfDebug( "Tried to call mysql_ping but this is ancient PHP version. Faking it!\n" );
286 return true;
287 }
288 $ping = mysql_ping( $this->mConn );
289 if ( $ping ) {
290 return true;
291 }
292
293 // Need to reconnect manually in MySQL client 5.0.13+
294 if ( version_compare( mysql_get_client_info(), '5.0.13', '>=' ) ) {
295 mysql_close( $this->mConn );
296 $this->mOpened = false;
297 $this->mConn = false;
298 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
299 return true;
300 }
301 return false;
302 }
303
304 function getServerVersion() {
305 return mysql_get_server_info( $this->mConn );
306 }
307
308 function useIndexClause( $index ) {
309 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
310 }
311
312 function lowPriorityOption() {
313 return 'LOW_PRIORITY';
314 }
315
316 function getSoftwareLink() {
317 return '[http://www.mysql.com/ MySQL]';
318 }
319
320 function standardSelectDistinct() {
321 return false;
322 }
323
324 public function setTimeout( $timeout ) {
325 $this->query( "SET net_read_timeout=$timeout" );
326 $this->query( "SET net_write_timeout=$timeout" );
327 }
328
329 public function lock( $lockName, $method, $timeout = 5 ) {
330 $lockName = $this->addQuotes( $lockName );
331 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
332 $row = $this->fetchObject( $result );
333 $this->freeResult( $result );
334
335 if( $row->lockstatus == 1 ) {
336 return true;
337 } else {
338 wfDebug( __METHOD__." failed to acquire lock\n" );
339 return false;
340 }
341 }
342
343 public function unlock( $lockName, $method ) {
344 $lockName = $this->addQuotes( $lockName );
345 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
346 $row = $this->fetchObject( $result );
347 return $row->lockstatus;
348 }
349
350 public function lockTables( $read, $write, $method, $lowPriority = true ) {
351 $items = array();
352
353 foreach( $write as $table ) {
354 $tbl = $this->tableName( $table ) .
355 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
356 ' WRITE';
357 $items[] = $tbl;
358 }
359 foreach( $read as $table ) {
360 $items[] = $this->tableName( $table ) . ' READ';
361 }
362 $sql = "LOCK TABLES " . implode( ',', $items );
363 $this->query( $sql, $method );
364 }
365
366 public function unlockTables( $method ) {
367 $this->query( "UNLOCK TABLES", $method );
368 }
369
370 public function setBigSelects( $value = true ) {
371 if ( $value === 'default' ) {
372 if ( $this->mDefaultBigSelects === null ) {
373 # Function hasn't been called before so it must already be set to the default
374 return;
375 } else {
376 $value = $this->mDefaultBigSelects;
377 }
378 } elseif ( $this->mDefaultBigSelects === null ) {
379 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
380 }
381 $encValue = $value ? '1' : '0';
382 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
383 }
384
385
386 /**
387 * Determines if the last failure was due to a deadlock
388 */
389 function wasDeadlock() {
390 return $this->lastErrno() == 1213;
391 }
392
393 /**
394 * Determines if the last query error was something that should be dealt
395 * with by pinging the connection and reissuing the query
396 */
397 function wasErrorReissuable() {
398 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
399 }
400
401 /**
402 * Determines if the last failure was due to the database being read-only.
403 */
404 function wasReadOnlyError() {
405 return $this->lastErrno() == 1223 ||
406 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
407 }
408
409 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
410 $tmp = $temporary ? 'TEMPORARY ' : '';
411 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
412 # Hack for MySQL versions < 4.1, which don't support
413 # "CREATE TABLE ... LIKE". Note that
414 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
415 # would not create the indexes we need....
416 #
417 # Note that we don't bother changing around the prefixes here be-
418 # cause we know we're using MySQL anyway.
419
420 $res = $this->query( "SHOW CREATE TABLE $oldName" );
421 $row = $this->fetchRow( $res );
422 $oldQuery = $row[1];
423 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
424 "CREATE $tmp TABLE `$newName`", $oldQuery );
425 if ($oldQuery === $query) {
426 # Couldn't do replacement
427 throw new MWException( "could not create temporary table $newName" );
428 }
429 } else {
430 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
431 }
432 $this->query( $query, $fname );
433 }
434
435 }
436
437 /**
438 * Legacy support: Database == DatabaseMysql
439 */
440 class Database extends DatabaseMysql {}
441
442 class MySQLMasterPos {
443 var $file, $pos;
444
445 function __construct( $file, $pos ) {
446 $this->file = $file;
447 $this->pos = $pos;
448 }
449
450 function __toString() {
451 return "{$this->file}/{$this->pos}";
452 }
453 }