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