merging latest master
[lhc/web/wiklou.git] / includes / db / DatabaseMysql.php
1 <?php
2 /**
3 * This is the MySQL database abstraction layer.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Database
22 */
23
24 /**
25 * Database abstraction object for mySQL
26 * Inherit all methods and properties of Database::Database()
27 *
28 * @ingroup Database
29 * @see Database
30 */
31 class DatabaseMysql extends DatabaseBase {
32
33 /**
34 * @return string
35 */
36 function getType() {
37 return 'mysql';
38 }
39
40 /**
41 * @param $sql string
42 * @return resource
43 */
44 protected function doQuery( $sql ) {
45 if( $this->bufferResults() ) {
46 $ret = mysql_query( $sql, $this->mConn );
47 } else {
48 $ret = mysql_unbuffered_query( $sql, $this->mConn );
49 }
50 return $ret;
51 }
52
53 /**
54 * @param $server string
55 * @param $user string
56 * @param $password string
57 * @param $dbName string
58 * @return bool
59 * @throws DBConnectionError
60 */
61 function open( $server, $user, $password, $dbName ) {
62 global $wgAllDBsAreLocalhost;
63 wfProfileIn( __METHOD__ );
64
65 # Load mysql.so if we don't have it
66 wfDl( 'mysql' );
67
68 # Fail now
69 # Otherwise we get a suppressed fatal error, which is very hard to track down
70 if ( !function_exists( 'mysql_connect' ) ) {
71 throw new DBConnectionError( $this, "MySQL functions missing, have you compiled PHP with the --with-mysql option?\n" );
72 }
73
74 # Debugging hack -- fake cluster
75 if ( $wgAllDBsAreLocalhost ) {
76 $realServer = 'localhost';
77 } else {
78 $realServer = $server;
79 }
80 $this->close();
81 $this->mServer = $server;
82 $this->mUser = $user;
83 $this->mPassword = $password;
84 $this->mDBname = $dbName;
85
86 $connFlags = 0;
87 if ( $this->mFlags & DBO_SSL ) {
88 $connFlags |= MYSQL_CLIENT_SSL;
89 }
90 if ( $this->mFlags & DBO_COMPRESS ) {
91 $connFlags |= MYSQL_CLIENT_COMPRESS;
92 }
93
94 wfProfileIn("dbconnect-$server");
95
96 # The kernel's default SYN retransmission period is far too slow for us,
97 # so we use a short timeout plus a manual retry. Retrying means that a small
98 # but finite rate of SYN packet loss won't cause user-visible errors.
99 $this->mConn = false;
100 if ( ini_get( 'mysql.connect_timeout' ) <= 3 ) {
101 $numAttempts = 2;
102 } else {
103 $numAttempts = 1;
104 }
105 $this->installErrorHandler();
106 for ( $i = 0; $i < $numAttempts && !$this->mConn; $i++ ) {
107 if ( $i > 1 ) {
108 usleep( 1000 );
109 }
110 if ( $this->mFlags & DBO_PERSISTENT ) {
111 $this->mConn = mysql_pconnect( $realServer, $user, $password, $connFlags );
112 } else {
113 # Create a new connection...
114 $this->mConn = mysql_connect( $realServer, $user, $password, true, $connFlags );
115 }
116 #if ( $this->mConn === false ) {
117 #$iplus = $i + 1;
118 #wfLogDBError("Connect loop error $iplus of $max ($server): " . mysql_errno() . " - " . mysql_error()."\n");
119 #}
120 }
121 $phpError = $this->restoreErrorHandler();
122 # Always log connection errors
123 if ( !$this->mConn ) {
124 $error = $phpError;
125 if ( !$error ) {
126 $error = $this->lastError();
127 }
128 wfLogDBError( "Error connecting to {$this->mServer}: $error\n" );
129 wfDebug( "DB connection error\n" );
130 wfDebug( "Server: $server, User: $user, Password: " .
131 substr( $password, 0, 3 ) . "..., error: " . $error . "\n" );
132 }
133
134 wfProfileOut("dbconnect-$server");
135
136 if ( $dbName != '' && $this->mConn !== false ) {
137 wfSuppressWarnings();
138 $success = mysql_select_db( $dbName, $this->mConn );
139 wfRestoreWarnings();
140 if ( !$success ) {
141 $error = "Error selecting database $dbName on server {$this->mServer} " .
142 "from client host " . wfHostname() . "\n";
143 wfLogDBError(" Error selecting database $dbName on server {$this->mServer} \n");
144 wfDebug( $error );
145 }
146 } else {
147 # Delay USE query
148 $success = (bool)$this->mConn;
149 }
150
151 if ( $success ) {
152 // Tell the server we're communicating with it in UTF-8.
153 // This may engage various charset conversions.
154 global $wgDBmysql5;
155 if( $wgDBmysql5 ) {
156 $this->query( 'SET NAMES utf8', __METHOD__ );
157 } else {
158 $this->query( 'SET NAMES binary', __METHOD__ );
159 }
160 // Set SQL mode, default is turning them all off, can be overridden or skipped with null
161 global $wgSQLMode;
162 if ( is_string( $wgSQLMode ) ) {
163 $mode = $this->addQuotes( $wgSQLMode );
164 $this->query( "SET sql_mode = $mode", __METHOD__ );
165 }
166
167 // Turn off strict mode if it is on
168 } else {
169 $this->reportConnectionError( $phpError );
170 }
171
172 $this->mOpened = $success;
173 wfProfileOut( __METHOD__ );
174 return $success;
175 }
176
177 /**
178 * @return bool
179 */
180 protected function closeConnection() {
181 return mysql_close( $this->mConn );
182 }
183
184 /**
185 * @param $res ResultWrapper
186 * @throws DBUnexpectedError
187 */
188 function freeResult( $res ) {
189 if ( $res instanceof ResultWrapper ) {
190 $res = $res->result;
191 }
192 wfSuppressWarnings();
193 $ok = mysql_free_result( $res );
194 wfRestoreWarnings();
195 if ( !$ok ) {
196 throw new DBUnexpectedError( $this, "Unable to free MySQL result" );
197 }
198 }
199
200 /**
201 * @param $res ResultWrapper
202 * @return object|stdClass
203 * @throws DBUnexpectedError
204 */
205 function fetchObject( $res ) {
206 if ( $res instanceof ResultWrapper ) {
207 $res = $res->result;
208 }
209 wfSuppressWarnings();
210 $row = mysql_fetch_object( $res );
211 wfRestoreWarnings();
212 if( $this->lastErrno() ) {
213 throw new DBUnexpectedError( $this, 'Error in fetchObject(): ' . htmlspecialchars( $this->lastError() ) );
214 }
215 return $row;
216 }
217
218 /**
219 * @param $res ResultWrapper
220 * @return array
221 * @throws DBUnexpectedError
222 */
223 function fetchRow( $res ) {
224 if ( $res instanceof ResultWrapper ) {
225 $res = $res->result;
226 }
227 wfSuppressWarnings();
228 $row = mysql_fetch_array( $res );
229 wfRestoreWarnings();
230 if ( $this->lastErrno() ) {
231 throw new DBUnexpectedError( $this, 'Error in fetchRow(): ' . htmlspecialchars( $this->lastError() ) );
232 }
233 return $row;
234 }
235
236 /**
237 * @throws DBUnexpectedError
238 * @param $res ResultWrapper
239 * @return int
240 */
241 function numRows( $res ) {
242 if ( $res instanceof ResultWrapper ) {
243 $res = $res->result;
244 }
245 wfSuppressWarnings();
246 $n = mysql_num_rows( $res );
247 wfRestoreWarnings();
248 if( $this->lastErrno() ) {
249 throw new DBUnexpectedError( $this, 'Error in numRows(): ' . htmlspecialchars( $this->lastError() ) );
250 }
251 return $n;
252 }
253
254 /**
255 * @param $res ResultWrapper
256 * @return int
257 */
258 function numFields( $res ) {
259 if ( $res instanceof ResultWrapper ) {
260 $res = $res->result;
261 }
262 return mysql_num_fields( $res );
263 }
264
265 /**
266 * @param $res ResultWrapper
267 * @param $n string
268 * @return string
269 */
270 function fieldName( $res, $n ) {
271 if ( $res instanceof ResultWrapper ) {
272 $res = $res->result;
273 }
274 return mysql_field_name( $res, $n );
275 }
276
277 /**
278 * @return int
279 */
280 function insertId() {
281 return mysql_insert_id( $this->mConn );
282 }
283
284 /**
285 * @param $res ResultWrapper
286 * @param $row
287 * @return bool
288 */
289 function dataSeek( $res, $row ) {
290 if ( $res instanceof ResultWrapper ) {
291 $res = $res->result;
292 }
293 return mysql_data_seek( $res, $row );
294 }
295
296 /**
297 * @return int
298 */
299 function lastErrno() {
300 if ( $this->mConn ) {
301 return mysql_errno( $this->mConn );
302 } else {
303 return mysql_errno();
304 }
305 }
306
307 /**
308 * @return string
309 */
310 function lastError() {
311 if ( $this->mConn ) {
312 # Even if it's non-zero, it can still be invalid
313 wfSuppressWarnings();
314 $error = mysql_error( $this->mConn );
315 if ( !$error ) {
316 $error = mysql_error();
317 }
318 wfRestoreWarnings();
319 } else {
320 $error = mysql_error();
321 }
322 if( $error ) {
323 $error .= ' (' . $this->mServer . ')';
324 }
325 return $error;
326 }
327
328 /**
329 * @return int
330 */
331 function affectedRows() {
332 return mysql_affected_rows( $this->mConn );
333 }
334
335 /**
336 * @param $table string
337 * @param $uniqueIndexes
338 * @param $rows array
339 * @param $fname string
340 * @return ResultWrapper
341 */
342 function replace( $table, $uniqueIndexes, $rows, $fname = 'DatabaseMysql::replace' ) {
343 return $this->nativeReplace( $table, $rows, $fname );
344 }
345
346 /**
347 * Estimate rows in dataset
348 * Returns estimated count, based on EXPLAIN output
349 * Takes same arguments as Database::select()
350 *
351 * @param $table string|array
352 * @param $vars string|array
353 * @param $conds string|array
354 * @param $fname string
355 * @param $options string|array
356 * @return int
357 */
358 public function estimateRowCount( $table, $vars='*', $conds='', $fname = 'DatabaseMysql::estimateRowCount', $options = array() ) {
359 $options['EXPLAIN'] = true;
360 $res = $this->select( $table, $vars, $conds, $fname, $options );
361 if ( $res === false ) {
362 return false;
363 }
364 if ( !$this->numRows( $res ) ) {
365 return 0;
366 }
367
368 $rows = 1;
369 foreach ( $res as $plan ) {
370 $rows *= $plan->rows > 0 ? $plan->rows : 1; // avoid resetting to zero
371 }
372 return $rows;
373 }
374
375 /**
376 * @param $table string
377 * @param $field string
378 * @return bool|MySQLField
379 */
380 function fieldInfo( $table, $field ) {
381 $table = $this->tableName( $table );
382 $res = $this->query( "SELECT * FROM $table LIMIT 1", __METHOD__, true );
383 if ( !$res ) {
384 return false;
385 }
386 $n = mysql_num_fields( $res->result );
387 for( $i = 0; $i < $n; $i++ ) {
388 $meta = mysql_fetch_field( $res->result, $i );
389 if( $field == $meta->name ) {
390 return new MySQLField($meta);
391 }
392 }
393 return false;
394 }
395
396 /**
397 * Get information about an index into an object
398 * Returns false if the index does not exist
399 *
400 * @param $table string
401 * @param $index string
402 * @param $fname string
403 * @return bool|array|null False or null on failure
404 */
405 function indexInfo( $table, $index, $fname = 'DatabaseMysql::indexInfo' ) {
406 # SHOW INDEX works in MySQL 3.23.58, but SHOW INDEXES does not.
407 # SHOW INDEX should work for 3.x and up:
408 # http://dev.mysql.com/doc/mysql/en/SHOW_INDEX.html
409 $table = $this->tableName( $table );
410 $index = $this->indexName( $index );
411 $sql = 'SHOW INDEX FROM ' . $table;
412 $res = $this->query( $sql, $fname );
413
414 if ( !$res ) {
415 return null;
416 }
417
418 $result = array();
419
420 foreach ( $res as $row ) {
421 if ( $row->Key_name == $index ) {
422 $result[] = $row;
423 }
424 }
425
426 return empty( $result ) ? false : $result;
427 }
428
429 /**
430 * @param $db
431 * @return bool
432 */
433 function selectDB( $db ) {
434 $this->mDBname = $db;
435 return mysql_select_db( $db, $this->mConn );
436 }
437
438 /**
439 * @param $s string
440 *
441 * @return string
442 */
443 function strencode( $s ) {
444 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
445
446 if($sQuoted === false) {
447 $this->ping();
448 $sQuoted = mysql_real_escape_string( $s, $this->mConn );
449 }
450 return $sQuoted;
451 }
452
453 /**
454 * MySQL uses `backticks` for identifier quoting instead of the sql standard "double quotes".
455 *
456 * @param $s string
457 *
458 * @return string
459 */
460 public function addIdentifierQuotes( $s ) {
461 return "`" . $this->strencode( $s ) . "`";
462 }
463
464 /**
465 * @param $name string
466 * @return bool
467 */
468 public function isQuotedIdentifier( $name ) {
469 return strlen( $name ) && $name[0] == '`' && substr( $name, -1, 1 ) == '`';
470 }
471
472 /**
473 * @return bool
474 */
475 function ping() {
476 $ping = mysql_ping( $this->mConn );
477 if ( $ping ) {
478 return true;
479 }
480
481 mysql_close( $this->mConn );
482 $this->mOpened = false;
483 $this->mConn = false;
484 $this->open( $this->mServer, $this->mUser, $this->mPassword, $this->mDBname );
485 return true;
486 }
487
488 /**
489 * Returns slave lag.
490 *
491 * This will do a SHOW SLAVE STATUS
492 *
493 * @return int
494 */
495 function getLag() {
496 if ( !is_null( $this->mFakeSlaveLag ) ) {
497 wfDebug( "getLag: fake slave lagged {$this->mFakeSlaveLag} seconds\n" );
498 return $this->mFakeSlaveLag;
499 }
500
501 return $this->getLagFromSlaveStatus();
502 }
503
504 /**
505 * @return bool|int
506 */
507 function getLagFromSlaveStatus() {
508 $res = $this->query( 'SHOW SLAVE STATUS', __METHOD__ );
509 if ( !$res ) {
510 return false;
511 }
512 $row = $res->fetchObject();
513 if ( !$row ) {
514 return false;
515 }
516 if ( strval( $row->Seconds_Behind_Master ) === '' ) {
517 return false;
518 } else {
519 return intval( $row->Seconds_Behind_Master );
520 }
521 }
522
523 /**
524 * @deprecated in 1.19, use getLagFromSlaveStatus
525 *
526 * @return bool|int
527 */
528 function getLagFromProcesslist() {
529 wfDeprecated( __METHOD__, '1.19' );
530 $res = $this->query( 'SHOW PROCESSLIST', __METHOD__ );
531 if( !$res ) {
532 return false;
533 }
534 # Find slave SQL thread
535 foreach( $res as $row ) {
536 /* This should work for most situations - when default db
537 * for thread is not specified, it had no events executed,
538 * and therefore it doesn't know yet how lagged it is.
539 *
540 * Relay log I/O thread does not select databases.
541 */
542 if ( $row->User == 'system user' &&
543 $row->State != 'Waiting for master to send event' &&
544 $row->State != 'Connecting to master' &&
545 $row->State != 'Queueing master event to the relay log' &&
546 $row->State != 'Waiting for master update' &&
547 $row->State != 'Requesting binlog dump' &&
548 $row->State != 'Waiting to reconnect after a failed master event read' &&
549 $row->State != 'Reconnecting after a failed master event read' &&
550 $row->State != 'Registering slave on master'
551 ) {
552 # This is it, return the time (except -ve)
553 if ( $row->Time > 0x7fffffff ) {
554 return false;
555 } else {
556 return $row->Time;
557 }
558 }
559 }
560 return false;
561 }
562
563 /**
564 * Wait for the slave to catch up to a given master position.
565 *
566 * @param $pos DBMasterPos object
567 * @param $timeout Integer: the maximum number of seconds to wait for synchronisation
568 * @return bool|string
569 */
570 function masterPosWait( DBMasterPos $pos, $timeout ) {
571 $fname = 'DatabaseBase::masterPosWait';
572 wfProfileIn( $fname );
573
574 # Commit any open transactions
575 if ( $this->mTrxLevel ) {
576 $this->commit( __METHOD__ );
577 }
578
579 if ( !is_null( $this->mFakeSlaveLag ) ) {
580 $status = parent::masterPosWait( $pos, $timeout );
581 wfProfileOut( $fname );
582 return $status;
583 }
584
585 # Call doQuery() directly, to avoid opening a transaction if DBO_TRX is set
586 $encFile = $this->addQuotes( $pos->file );
587 $encPos = intval( $pos->pos );
588 $sql = "SELECT MASTER_POS_WAIT($encFile, $encPos, $timeout)";
589 $res = $this->doQuery( $sql );
590
591 if ( $res && $row = $this->fetchRow( $res ) ) {
592 wfProfileOut( $fname );
593 return $row[0];
594 } else {
595 wfProfileOut( $fname );
596 return false;
597 }
598 }
599
600 /**
601 * Get the position of the master from SHOW SLAVE STATUS
602 *
603 * @return MySQLMasterPos|bool
604 */
605 function getSlavePos() {
606 if ( !is_null( $this->mFakeSlaveLag ) ) {
607 return parent::getSlavePos();
608 }
609
610 $res = $this->query( 'SHOW SLAVE STATUS', 'DatabaseBase::getSlavePos' );
611 $row = $this->fetchObject( $res );
612
613 if ( $row ) {
614 $pos = isset( $row->Exec_master_log_pos ) ? $row->Exec_master_log_pos : $row->Exec_Master_Log_Pos;
615 return new MySQLMasterPos( $row->Relay_Master_Log_File, $pos );
616 } else {
617 return false;
618 }
619 }
620
621 /**
622 * Get the position of the master from SHOW MASTER STATUS
623 *
624 * @return MySQLMasterPos|bool
625 */
626 function getMasterPos() {
627 if ( $this->mFakeMaster ) {
628 return parent::getMasterPos();
629 }
630
631 $res = $this->query( 'SHOW MASTER STATUS', 'DatabaseBase::getMasterPos' );
632 $row = $this->fetchObject( $res );
633
634 if ( $row ) {
635 return new MySQLMasterPos( $row->File, $row->Position );
636 } else {
637 return false;
638 }
639 }
640
641 /**
642 * @return string
643 */
644 function getServerVersion() {
645 return mysql_get_server_info( $this->mConn );
646 }
647
648 /**
649 * @param $index
650 * @return string
651 */
652 function useIndexClause( $index ) {
653 return "FORCE INDEX (" . $this->indexName( $index ) . ")";
654 }
655
656 /**
657 * @return string
658 */
659 function lowPriorityOption() {
660 return 'LOW_PRIORITY';
661 }
662
663 /**
664 * @return string
665 */
666 public static function getSoftwareLink() {
667 return '[http://www.mysql.com/ MySQL]';
668 }
669
670 /**
671 * @param $options array
672 */
673 public function setSessionOptions( array $options ) {
674 if ( isset( $options['connTimeout'] ) ) {
675 $timeout = (int)$options['connTimeout'];
676 $this->query( "SET net_read_timeout=$timeout" );
677 $this->query( "SET net_write_timeout=$timeout" );
678 }
679 }
680
681 public function streamStatementEnd( &$sql, &$newLine ) {
682 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
683 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
684 $this->delimiter = $m[1];
685 $newLine = '';
686 }
687 return parent::streamStatementEnd( $sql, $newLine );
688 }
689
690 /**
691 * Check to see if a named lock is available. This is non-blocking.
692 *
693 * @param $lockName String: name of lock to poll
694 * @param $method String: name of method calling us
695 * @return Boolean
696 * @since 1.20
697 */
698 public function lockIsFree( $lockName, $method ) {
699 $lockName = $this->addQuotes( $lockName );
700 $result = $this->query( "SELECT IS_FREE_LOCK($lockName) AS lockstatus", $method );
701 $row = $this->fetchObject( $result );
702 return ( $row->lockstatus == 1 );
703 }
704
705 /**
706 * @param $lockName string
707 * @param $method string
708 * @param $timeout int
709 * @return bool
710 */
711 public function lock( $lockName, $method, $timeout = 5 ) {
712 $lockName = $this->addQuotes( $lockName );
713 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
714 $row = $this->fetchObject( $result );
715
716 if( $row->lockstatus == 1 ) {
717 return true;
718 } else {
719 wfDebug( __METHOD__." failed to acquire lock\n" );
720 return false;
721 }
722 }
723
724 /**
725 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
726 * @param $lockName string
727 * @param $method string
728 * @return bool
729 */
730 public function unlock( $lockName, $method ) {
731 $lockName = $this->addQuotes( $lockName );
732 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
733 $row = $this->fetchObject( $result );
734 return ( $row->lockstatus == 1 );
735 }
736
737 /**
738 * @param $read array
739 * @param $write array
740 * @param $method string
741 * @param $lowPriority bool
742 */
743 public function lockTables( $read, $write, $method, $lowPriority = true ) {
744 $items = array();
745
746 foreach( $write as $table ) {
747 $tbl = $this->tableName( $table ) .
748 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
749 ' WRITE';
750 $items[] = $tbl;
751 }
752 foreach( $read as $table ) {
753 $items[] = $this->tableName( $table ) . ' READ';
754 }
755 $sql = "LOCK TABLES " . implode( ',', $items );
756 $this->query( $sql, $method );
757 }
758
759 /**
760 * @param $method string
761 */
762 public function unlockTables( $method ) {
763 $this->query( "UNLOCK TABLES", $method );
764 }
765
766 /**
767 * Get search engine class. All subclasses of this
768 * need to implement this if they wish to use searching.
769 *
770 * @return String
771 */
772 public function getSearchEngine() {
773 return 'SearchMySQL';
774 }
775
776 /**
777 * @param bool $value
778 * @return mixed
779 */
780 public function setBigSelects( $value = true ) {
781 if ( $value === 'default' ) {
782 if ( $this->mDefaultBigSelects === null ) {
783 # Function hasn't been called before so it must already be set to the default
784 return;
785 } else {
786 $value = $this->mDefaultBigSelects;
787 }
788 } elseif ( $this->mDefaultBigSelects === null ) {
789 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
790 }
791 $encValue = $value ? '1' : '0';
792 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
793 }
794
795 /**
796 * DELETE where the condition is a join. MySql uses multi-table deletes.
797 * @param $delTable string
798 * @param $joinTable string
799 * @param $delVar string
800 * @param $joinVar string
801 * @param $conds array|string
802 * @param $fname bool
803 * @return bool|ResultWrapper
804 */
805 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
806 if ( !$conds ) {
807 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
808 }
809
810 $delTable = $this->tableName( $delTable );
811 $joinTable = $this->tableName( $joinTable );
812 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
813
814 if ( $conds != '*' ) {
815 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
816 }
817
818 return $this->query( $sql, $fname );
819 }
820
821 /**
822 * Determines how long the server has been up
823 *
824 * @return int
825 */
826 function getServerUptime() {
827 $vars = $this->getMysqlStatus( 'Uptime' );
828 return (int)$vars['Uptime'];
829 }
830
831 /**
832 * Determines if the last failure was due to a deadlock
833 *
834 * @return bool
835 */
836 function wasDeadlock() {
837 return $this->lastErrno() == 1213;
838 }
839
840 /**
841 * Determines if the last failure was due to a lock timeout
842 *
843 * @return bool
844 */
845 function wasLockTimeout() {
846 return $this->lastErrno() == 1205;
847 }
848
849 /**
850 * Determines if the last query error was something that should be dealt
851 * with by pinging the connection and reissuing the query
852 *
853 * @return bool
854 */
855 function wasErrorReissuable() {
856 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
857 }
858
859 /**
860 * Determines if the last failure was due to the database being read-only.
861 *
862 * @return bool
863 */
864 function wasReadOnlyError() {
865 return $this->lastErrno() == 1223 ||
866 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
867 }
868
869 /**
870 * @param $oldName
871 * @param $newName
872 * @param $temporary bool
873 * @param $fname string
874 */
875 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
876 $tmp = $temporary ? 'TEMPORARY ' : '';
877 $newName = $this->addIdentifierQuotes( $newName );
878 $oldName = $this->addIdentifierQuotes( $oldName );
879 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
880 $this->query( $query, $fname );
881 }
882
883 /**
884 * List all tables on the database
885 *
886 * @param $prefix string Only show tables with this prefix, e.g. mw_
887 * @param $fname String: calling function name
888 * @return array
889 */
890 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
891 $result = $this->query( "SHOW TABLES", $fname);
892
893 $endArray = array();
894
895 foreach( $result as $table ) {
896 $vars = get_object_vars($table);
897 $table = array_pop( $vars );
898
899 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
900 $endArray[] = $table;
901 }
902 }
903
904 return $endArray;
905 }
906
907 /**
908 * @param $tableName
909 * @param $fName string
910 * @return bool|ResultWrapper
911 */
912 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
913 if( !$this->tableExists( $tableName, $fName ) ) {
914 return false;
915 }
916 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
917 }
918
919 /**
920 * @return array
921 */
922 protected function getDefaultSchemaVars() {
923 $vars = parent::getDefaultSchemaVars();
924 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
925 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
926 return $vars;
927 }
928
929 /**
930 * Get status information from SHOW STATUS in an associative array
931 *
932 * @param $which string
933 * @return array
934 */
935 function getMysqlStatus( $which = "%" ) {
936 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
937 $status = array();
938
939 foreach ( $res as $row ) {
940 $status[$row->Variable_name] = $row->Value;
941 }
942
943 return $status;
944 }
945
946 }
947
948 /**
949 * Legacy support: Database == DatabaseMysql
950 *
951 * @deprecated in 1.16
952 */
953 class Database extends DatabaseMysql {}
954
955 /**
956 * Utility class.
957 * @ingroup Database
958 */
959 class MySQLField implements Field {
960 private $name, $tablename, $default, $max_length, $nullable,
961 $is_pk, $is_unique, $is_multiple, $is_key, $type;
962
963 function __construct ( $info ) {
964 $this->name = $info->name;
965 $this->tablename = $info->table;
966 $this->default = $info->def;
967 $this->max_length = $info->max_length;
968 $this->nullable = !$info->not_null;
969 $this->is_pk = $info->primary_key;
970 $this->is_unique = $info->unique_key;
971 $this->is_multiple = $info->multiple_key;
972 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
973 $this->type = $info->type;
974 }
975
976 /**
977 * @return string
978 */
979 function name() {
980 return $this->name;
981 }
982
983 /**
984 * @return string
985 */
986 function tableName() {
987 return $this->tableName;
988 }
989
990 /**
991 * @return string
992 */
993 function type() {
994 return $this->type;
995 }
996
997 /**
998 * @return bool
999 */
1000 function isNullable() {
1001 return $this->nullable;
1002 }
1003
1004 function defaultValue() {
1005 return $this->default;
1006 }
1007
1008 /**
1009 * @return bool
1010 */
1011 function isKey() {
1012 return $this->is_key;
1013 }
1014
1015 /**
1016 * @return bool
1017 */
1018 function isMultipleKey() {
1019 return $this->is_multiple;
1020 }
1021 }
1022
1023 class MySQLMasterPos implements DBMasterPos {
1024 var $file, $pos;
1025
1026 function __construct( $file, $pos ) {
1027 $this->file = $file;
1028 $this->pos = $pos;
1029 }
1030
1031 function __toString() {
1032 return "{$this->file}/{$this->pos}";
1033 }
1034 }