Fix PHP 5.2 compatibility for r77144
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * @file
6 * @ingroup Database
7 */
8
9 /**
10 * Database abstraction object for mySQL
11 * Inherit all methods and properties of Database::Database()
12 *
13 * @ingroup Database
14 * @see Database
15 */
16 class DatabaseMysql extends DatabaseBase {
17 function getType() {
18 return 'mysql';
19 }
20
21 /*private*/ function doQuery( $sql ) {
22 if( $this->bufferResults() ) {
23 $ret = mysql_query( $sql, $this->mConn );
24 } else {
25 $ret = mysql_unbuffered_query( $sql, $this->mConn );
26 }
27 return $ret;
28 }
29
30 function open( $server, $user, $password, $dbName ) {
31 global $wgAllDBsAreLocalhost;
32 wfProfileIn( __METHOD__ );
33
34 # Load mysql.so if we don't have it
35 wfDl( 'mysql' );
36
37 # Fail now
38 # Otherwise we get a suppressed fatal error, which is very hard to track down
39 if ( !function_exists( 'mysql_connect' ) ) {
40 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
41 }
42
43 # Debugging hack -- fake cluster
44 if ( $wgAllDBsAreLocalhost ) {
45 $realServer = 'localhost';
46 } else {
47 $realServer = $server;
48 }
49 $this->close();
50 $this->mServer = $server;
51 $this->mUser = $user;
52 $this->mPassword = $password;
53 $this->mDBname = $dbName;
54
55 $success = false;
56
57 wfProfileIn("dbconnect-$server");
58
59 # The kernel's default SYN retransmission period is far too slow for us,
60 # so we use a short timeout plus a manual retry. Retrying means that a small
61 # but finite rate of SYN packet loss won't cause user-visible errors.
62 $this->mConn = false;
63 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
64 $numAttempts = 2;
65 } else {
66 $numAttempts = 1;
67 }
68 $this->installErrorHandler();
69 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
70 if ( $i > 1 ) {
71 usleep( 1000 );
72 }
73 if ( $this->mFlags & DBO_PERSISTENT ) {
74 $this->mConn = mysql_pconnect( $realServer, $user, $password );
75 } else {
76 # Create a new connection...
77 $this->mConn = mysql_connect( $realServer, $user, $password, true );
78 }
79 #if ( $this->mConn === false ) {
80 #$iplus = $i + 1;
81 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
82 #}
83 }
84 $phpError = $this->restoreErrorHandler();
85 # Always log connection errors
86 if ( !$this->mConn ) {
87 $error = $this->lastError();
88 if ( !$error ) {
89 $error = $phpError;
90 }
91 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
92 wfDebug( "DB connection error\n" );
93 wfDebug( "Server: $server, User: $user, Password: " .
94 substr( $password, 0, 3 ) . "..., error: " . mysql_error() . "\n" );
95 $success = false;
96 }
97
98 wfProfileOut("dbconnect-$server");
99
100 if ( $dbName != '' && $this->mConn !== false ) {
101 $success = @/**/mysql_select_db( $dbName, $this->mConn );
102 if ( !$success ) {
103 $error = "Error selecting database $dbName on server {$this->mServer} " .
104 "from client host " . wfHostname() . "\n";
105 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
106 wfDebug( $error );
107 }
108 } else {
109 # Delay USE query
110 $success = (bool)$this->mConn;
111 }
112
113 if ( $success ) {
114 $version = $this->getServerVersion();
115 if ( version_compare( $version, '4.1' ) >= 0 ) {
116 // Tell the server we're communicating with it in UTF-8.
117 // This may engage various charset conversions.
118 global $wgDBmysql5;
119 if( $wgDBmysql5 ) {
120 $this->query( 'SET NAMES utf8', __METHOD__ );
121 } else {
122 $this->query( 'SET NAMES binary', __METHOD__ );
123 }
124 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
125 global $wgSQLMode;
126 if ( is_string( $wgSQLMode ) ) {
127 $mode = $this->addQuotes( $wgSQLMode );
128 $this->query( "SET sql_mode = $mode", __METHOD__ );
129 }
130 }
131
132 // Turn off strict mode if it is on
133 } else {
134 $this->reportConnectionError( $phpError );
135 }
136
137 $this->mOpened = $success;
138 wfProfileOut( __METHOD__ );
139 return $success;
140 }
141
142 function close() {
143 $this->mOpened = false;
144 if ( $this->mConn ) {
145 if ( $this->trxLevel() ) {
146 $this->commit();
147 }
148 return mysql_close( $this->mConn );
149 } else {
150 return true;
151 }
152 }
153
154 function freeResult( $res ) {
155 if ( $res instanceof ResultWrapper ) {
156 $res = $res->result;
157 }
158 if ( !@/**/mysql_free_result( $res ) ) {
159 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
160 }
161 }
162
163 function fetchObject( $res ) {
164 if ( $res instanceof ResultWrapper ) {
165 $res = $res->result;
166 }
167 @/**/$row = mysql_fetch_object( $res );
168 if( $this->lastErrno() ) {
169 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
170 }
171 return $row;
172 }
173
174 function fetchRow( $res ) {
175 if ( $res instanceof ResultWrapper ) {
176 $res = $res->result;
177 }
178 @/**/$row = mysql_fetch_array( $res );
179 if ( $this->lastErrno() ) {
180 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
181 }
182 return $row;
183 }
184
185 function numRows( $res ) {
186 if ( $res instanceof ResultWrapper ) {
187 $res = $res->result;
188 }
189 @/**/$n = mysql_num_rows( $res );
190 if( $this->lastErrno() ) {
191 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
192 }
193 return $n;
194 }
195
196 function numFields( $res ) {
197 if ( $res instanceof ResultWrapper ) {
198 $res = $res->result;
199 }
200 return mysql_num_fields( $res );
201 }
202
203 function fieldName( $res, $n ) {
204 if ( $res instanceof ResultWrapper ) {
205 $res = $res->result;
206 }
207 return mysql_field_name( $res, $n );
208 }
209
210 function insertId() { return mysql_insert_id( $this->mConn ); }
211
212 function dataSeek( $res, $row ) {
213 if ( $res instanceof ResultWrapper ) {
214 $res = $res->result;
215 }
216 return mysql_data_seek( $res, $row );
217 }
218
219 function lastErrno() {
220 if ( $this->mConn ) {
221 return mysql_errno( $this->mConn );
222 } else {
223 return mysql_errno();
224 }
225 }
226
227 function lastError() {
228 if ( $this->mConn ) {
229 # Even if it's non-zero, it can still be invalid
230 wfSuppressWarnings();
231 $error = mysql_error( $this->mConn );
232 if ( !$error ) {
233 $error = mysql_error();
234 }
235 wfRestoreWarnings();
236 } else {
237 $error = mysql_error();
238 }
239 if( $error ) {
240 $error .= ' (' . $this->mServer . ')';
241 }
242 return $error;
243 }
244
245 function affectedRows() { return mysql_affected_rows( $this->mConn ); }
246
247 /**
248 * Estimate rows in dataset
249 * Returns estimated count, based on EXPLAIN output
250 * Takes same arguments as Database::select()
251 */
252 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
253 $options['EXPLAIN'] = true;
254 $res = $this->select( $table, $vars, $conds, $fname, $options );
255 if ( $res === false ) {
256 return false;
257 }
258 if ( !$this->numRows( $res ) ) {
259 return 0;
260 }
261
262 $rows = 1;
263 foreach ( $res as $plan ) {
264 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
265 }
266 return $rows;
267 }
268
269 function fieldInfo( $table, $field ) {
270 $table = $this->tableName( $table );
271 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
272 if ( !$res ) {
273 return false;
274 }
275 $n = mysql_num_fields( $res->result );
276 for( $i = 0; $i < $n; $i++ ) {
277 $meta = mysql_fetch_field( $res->result, $i );
278 if( $field == $meta->name ) {
279 return new MySQLField($meta);
280 }
281 }
282 return false;
283 }
284
285 /**
286 * Get information about an index into an object
287 * Returns false if the index does not exist
288 */
289 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
290 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
291 # SHOW INDEX should work for 3.x and up:
292 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
293 $table = $this->tableName( $table );
294 $index = $this->indexName( $index );
295 $sql = 'SHOW INDEX FROM ' . $table;
296 $res = $this->query( $sql, $fname );
297
298 if ( !$res ) {
299 return null;
300 }
301
302 $result = array();
303
304 foreach ( $res as $row ) {
305 if ( $row->Key_name == $index ) {
306 $result[] = $row;
307 }
308 }
309
310 return empty( $result ) ? false : $result;
311 }
312
313 function selectDB( $db ) {
314 $this->mDBname = $db;
315 return mysql_select_db( $db, $this->mConn );
316 }
317
318 function strencode( $s ) {
319 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
320
321 if($sQuoted === false) {
322 $this->ping();
323 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
324 }
325 return $sQuoted;
326 }
327
328 function ping() {
329 $ping = mysql_ping( $this->mConn );
330 if ( $ping ) {
331 return true;
332 }
333
334 mysql_close( $this->mConn );
335 $this->mOpened = false;
336 $this->mConn = false;
337 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
338 return true;
339 }
340
341 /**
342 * Returns slave lag.
343 * At the moment, this will only work if the DB user has the PROCESS privilege
344 * @result int
345 */
346 function getLag() {
347 if ( !is_null( $this->mFakeSlaveLag ) ) {
348 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
349 return $this->mFakeSlaveLag;
350 }
351 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
352 if( !$res ) {
353 return false;
354 }
355 # Find slave SQL thread
356 foreach( $res as $row ) {
357 /* This should work for most situations - when default db
358 * for thread is not specified, it had no events executed,
359 * and therefore it doesn't know yet how lagged it is.
360 *
361 * Relay log I/O thread does not select databases.
362 */
363 if ( $row->User == 'system user' &&
364 $row->State != 'Waiting for master to send event' &&
365 $row->State != 'Connecting to master' &&
366 $row->State != 'Queueing master event to the relay log' &&
367 $row->State != 'Waiting for master update' &&
368 $row->State != 'Requesting binlog dump' &&
369 $row->State != 'Waiting to reconnect after a failed master event read' &&
370 $row->State != 'Reconnecting after a failed master event read' &&
371 $row->State != 'Registering slave on master'
372 ) {
373 # This is it, return the time (except -ve)
374 if ( $row->Time > 0x7fffffff ) {
375 return false;
376 } else {
377 return $row->Time;
378 }
379 }
380 }
381 return false;
382 }
383
384 function getServerVersion() {
385 return mysql_get_server_info( $this->mConn );
386 }
387
388 function useIndexClause( $index ) {
389 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
390 }
391
392 function lowPriorityOption() {
393 return 'LOW_PRIORITY';
394 }
395
396 public static function getSoftwareLink() {
397 return '[http://www.mysql.com/ MySQL]';
398 }
399
400 function standardSelectDistinct() {
401 return false;
402 }
403
404 public function setTimeout( $timeout ) {
405 $this->query( "SET net_read_timeout=$timeout" );
406 $this->query( "SET net_write_timeout=$timeout" );
407 }
408
409 public function lock( $lockName, $method, $timeout = 5 ) {
410 $lockName = $this->addQuotes( $lockName );
411 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
412 $row = $this->fetchObject( $result );
413
414 if( $row->lockstatus == 1 ) {
415 return true;
416 } else {
417 wfDebug( __METHOD__." failed to acquire lock\n" );
418 return false;
419 }
420 }
421
422 /**
423 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
424 */
425 public function unlock( $lockName, $method ) {
426 $lockName = $this->addQuotes( $lockName );
427 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
428 $row = $this->fetchObject( $result );
429 return $row->lockstatus;
430 }
431
432 public function lockTables( $read, $write, $method, $lowPriority = true ) {
433 $items = array();
434
435 foreach( $write as $table ) {
436 $tbl = $this->tableName( $table ) .
437 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
438 ' WRITE';
439 $items[] = $tbl;
440 }
441 foreach( $read as $table ) {
442 $items[] = $this->tableName( $table ) . ' READ';
443 }
444 $sql = "LOCK TABLES " . implode( ',', $items );
445 $this->query( $sql, $method );
446 }
447
448 public function unlockTables( $method ) {
449 $this->query( "UNLOCK TABLES", $method );
450 }
451
452 /**
453 * Get search engine class. All subclasses of this
454 * need to implement this if they wish to use searching.
455 *
456 * @return String
457 */
458 public function getSearchEngine() {
459 return 'SearchMySQL';
460 }
461
462 public function setBigSelects( $value = true ) {
463 if ( $value === 'default' ) {
464 if ( $this->mDefaultBigSelects === null ) {
465 # Function hasn't been called before so it must already be set to the default
466 return;
467 } else {
468 $value = $this->mDefaultBigSelects;
469 }
470 } elseif ( $this->mDefaultBigSelects === null ) {
471 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
472 }
473 $encValue = $value ? '1' : '0';
474 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
475 }
476
477
478 /**
479 * Determines if the last failure was due to a deadlock
480 */
481 function wasDeadlock() {
482 return $this->lastErrno() == 1213;
483 }
484
485 /**
486 * Determines if the last query error was something that should be dealt
487 * with by pinging the connection and reissuing the query
488 */
489 function wasErrorReissuable() {
490 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
491 }
492
493 /**
494 * Determines if the last failure was due to the database being read-only.
495 */
496 function wasReadOnlyError() {
497 return $this->lastErrno() == 1223 ||
498 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
499 }
500
501 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
502 $tmp = $temporary ? 'TEMPORARY ' : '';
503 if ( strcmp( $this->getServerVersion(), '4.1' ) < 0 ) {
504 # Hack for MySQL versions < 4.1, which don't support
505 # "CREATE TABLE ... LIKE". Note that
506 # "CREATE TEMPORARY TABLE ... SELECT * FROM ... LIMIT 0"
507 # would not create the indexes we need....
508 #
509 # Note that we don't bother changing around the prefixes here be-
510 # cause we know we're using MySQL anyway.
511
512 $res = $this->query( "SHOW CREATE TABLE $oldName" );
513 $row = $this->fetchRow( $res );
514 $oldQuery = $row[1];
515 $query = preg_replace( '/CREATE TABLE `(.*?)`/',
516 "CREATE $tmp TABLE `$newName`", $oldQuery );
517 if ($oldQuery === $query) {
518 # Couldn't do replacement
519 throw new MWException( "could not create temporary table $newName" );
520 }
521 } else {
522 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
523 }
524 $this->query( $query, $fname );
525 }
526
527 }
528
529 /**
530 * Legacy support: Database == DatabaseMysql
531 */
532 class Database extends DatabaseMysql {}
533
534 /**
535 * Utility class.
536 * @ingroup Database
537 */
538 class MySQLField implements Field {
539 private $name, $tablename, $default, $max_length, $nullable,
540 $is_pk, $is_unique, $is_multiple, $is_key, $type;
541
542 function __construct ( $info ) {
543 $this->name = $info->name;
544 $this->tablename = $info->table;
545 $this->default = $info->def;
546 $this->max_length = $info->max_length;
547 $this->nullable = !$info->not_null;
548 $this->is_pk = $info->primary_key;
549 $this->is_unique = $info->unique_key;
550 $this->is_multiple = $info->multiple_key;
551 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
552 $this->type = $info->type;
553 }
554
555 function name() {
556 return $this->name;
557 }
558
559 function tableName() {
560 return $this->tableName;
561 }
562
563 function type() {
564 return $this->type;
565 }
566
567 function isNullable() {
568 return $this->nullable;
569 }
570
571 function defaultValue() {
572 return $this->default;
573 }
574
575 function isKey() {
576 return $this->is_key;
577 }
578
579 function isMultipleKey() {
580 return $this->is_multiple;
581 }
582 }
583
584 class MySQLMasterPos {
585 var $file, $pos;
586
587 function __construct( $file, $pos ) {
588 $this->file = $file;
589 $this->pos = $pos;
590 }
591
592 function __toString() {
593 return "{$this->file}/{$this->pos}";
594 }
595 }