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