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