Merge "Edit notices can now be translated."
[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 = $this->lastError();
117 if ( !$error ) {
118 $error = $phpError;
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: " . mysql_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 * @return bool
664 */
665 function standardSelectDistinct() {
666 return false;
667 }
668
669 /**
670 * @param $options array
671 */
672 public function setSessionOptions( array $options ) {
673 if ( isset( $options['connTimeout'] ) ) {
674 $timeout = (int)$options['connTimeout'];
675 $this->query( "SET net_read_timeout=$timeout" );
676 $this->query( "SET net_write_timeout=$timeout" );
677 }
678 }
679
680 public function streamStatementEnd( &$sql, &$newLine ) {
681 if ( strtoupper( substr( $newLine, 0, 9 ) ) == 'DELIMITER' ) {
682 preg_match( '/^DELIMITER\s+(\S+)/' , $newLine, $m );
683 $this->delimiter = $m[1];
684 $newLine = '';
685 }
686 return parent::streamStatementEnd( $sql, $newLine );
687 }
688
689 /**
690 * @param $lockName string
691 * @param $method string
692 * @param $timeout int
693 * @return bool
694 */
695 public function lock( $lockName, $method, $timeout = 5 ) {
696 $lockName = $this->addQuotes( $lockName );
697 $result = $this->query( "SELECT GET_LOCK($lockName, $timeout) AS lockstatus", $method );
698 $row = $this->fetchObject( $result );
699
700 if( $row->lockstatus == 1 ) {
701 return true;
702 } else {
703 wfDebug( __METHOD__." failed to acquire lock\n" );
704 return false;
705 }
706 }
707
708 /**
709 * FROM MYSQL DOCS: http://dev.mysql.com/doc/refman/5.0/en/miscellaneous-functions.html#function_release-lock
710 * @param $lockName string
711 * @param $method string
712 * @return bool
713 */
714 public function unlock( $lockName, $method ) {
715 $lockName = $this->addQuotes( $lockName );
716 $result = $this->query( "SELECT RELEASE_LOCK($lockName) as lockstatus", $method );
717 $row = $this->fetchObject( $result );
718 return $row->lockstatus;
719 }
720
721 /**
722 * @param $read array
723 * @param $write array
724 * @param $method string
725 * @param $lowPriority bool
726 */
727 public function lockTables( $read, $write, $method, $lowPriority = true ) {
728 $items = array();
729
730 foreach( $write as $table ) {
731 $tbl = $this->tableName( $table ) .
732 ( $lowPriority ? ' LOW_PRIORITY' : '' ) .
733 ' WRITE';
734 $items[] = $tbl;
735 }
736 foreach( $read as $table ) {
737 $items[] = $this->tableName( $table ) . ' READ';
738 }
739 $sql = "LOCK TABLES " . implode( ',', $items );
740 $this->query( $sql, $method );
741 }
742
743 /**
744 * @param $method string
745 */
746 public function unlockTables( $method ) {
747 $this->query( "UNLOCK TABLES", $method );
748 }
749
750 /**
751 * Get search engine class. All subclasses of this
752 * need to implement this if they wish to use searching.
753 *
754 * @return String
755 */
756 public function getSearchEngine() {
757 return 'SearchMySQL';
758 }
759
760 /**
761 * @param bool $value
762 * @return mixed
763 */
764 public function setBigSelects( $value = true ) {
765 if ( $value === 'default' ) {
766 if ( $this->mDefaultBigSelects === null ) {
767 # Function hasn't been called before so it must already be set to the default
768 return;
769 } else {
770 $value = $this->mDefaultBigSelects;
771 }
772 } elseif ( $this->mDefaultBigSelects === null ) {
773 $this->mDefaultBigSelects = (bool)$this->selectField( false, '@@sql_big_selects' );
774 }
775 $encValue = $value ? '1' : '0';
776 $this->query( "SET sql_big_selects=$encValue", __METHOD__ );
777 }
778
779 /**
780 * DELETE where the condition is a join. MySql uses multi-table deletes.
781 * @param $delTable string
782 * @param $joinTable string
783 * @param $delVar string
784 * @param $joinVar string
785 * @param $conds array|string
786 * @param $fname bool
787 * @return bool|ResultWrapper
788 */
789 function deleteJoin( $delTable, $joinTable, $delVar, $joinVar, $conds, $fname = 'DatabaseBase::deleteJoin' ) {
790 if ( !$conds ) {
791 throw new DBUnexpectedError( $this, 'DatabaseBase::deleteJoin() called with empty $conds' );
792 }
793
794 $delTable = $this->tableName( $delTable );
795 $joinTable = $this->tableName( $joinTable );
796 $sql = "DELETE $delTable FROM $delTable, $joinTable WHERE $delVar=$joinVar ";
797
798 if ( $conds != '*' ) {
799 $sql .= ' AND ' . $this->makeList( $conds, LIST_AND );
800 }
801
802 return $this->query( $sql, $fname );
803 }
804
805 /**
806 * Determines how long the server has been up
807 *
808 * @return int
809 */
810 function getServerUptime() {
811 $vars = $this->getMysqlStatus( 'Uptime' );
812 return (int)$vars['Uptime'];
813 }
814
815 /**
816 * Determines if the last failure was due to a deadlock
817 *
818 * @return bool
819 */
820 function wasDeadlock() {
821 return $this->lastErrno() == 1213;
822 }
823
824 /**
825 * Determines if the last failure was due to a lock timeout
826 *
827 * @return bool
828 */
829 function wasLockTimeout() {
830 return $this->lastErrno() == 1205;
831 }
832
833 /**
834 * Determines if the last query error was something that should be dealt
835 * with by pinging the connection and reissuing the query
836 *
837 * @return bool
838 */
839 function wasErrorReissuable() {
840 return $this->lastErrno() == 2013 || $this->lastErrno() == 2006;
841 }
842
843 /**
844 * Determines if the last failure was due to the database being read-only.
845 *
846 * @return bool
847 */
848 function wasReadOnlyError() {
849 return $this->lastErrno() == 1223 ||
850 ( $this->lastErrno() == 1290 && strpos( $this->lastError(), '--read-only' ) !== false );
851 }
852
853 /**
854 * @param $oldName
855 * @param $newName
856 * @param $temporary bool
857 * @param $fname string
858 */
859 function duplicateTableStructure( $oldName, $newName, $temporary = false, $fname = 'DatabaseMysql::duplicateTableStructure' ) {
860 $tmp = $temporary ? 'TEMPORARY ' : '';
861 $newName = $this->addIdentifierQuotes( $newName );
862 $oldName = $this->addIdentifierQuotes( $oldName );
863 $query = "CREATE $tmp TABLE $newName (LIKE $oldName)";
864 $this->query( $query, $fname );
865 }
866
867 /**
868 * List all tables on the database
869 *
870 * @param $prefix string Only show tables with this prefix, e.g. mw_
871 * @param $fname String: calling function name
872 * @return array
873 */
874 function listTables( $prefix = null, $fname = 'DatabaseMysql::listTables' ) {
875 $result = $this->query( "SHOW TABLES", $fname);
876
877 $endArray = array();
878
879 foreach( $result as $table ) {
880 $vars = get_object_vars($table);
881 $table = array_pop( $vars );
882
883 if( !$prefix || strpos( $table, $prefix ) === 0 ) {
884 $endArray[] = $table;
885 }
886 }
887
888 return $endArray;
889 }
890
891 /**
892 * @param $tableName
893 * @param $fName string
894 * @return bool|ResultWrapper
895 */
896 public function dropTable( $tableName, $fName = 'DatabaseMysql::dropTable' ) {
897 if( !$this->tableExists( $tableName, $fName ) ) {
898 return false;
899 }
900 return $this->query( "DROP TABLE IF EXISTS " . $this->tableName( $tableName ), $fName );
901 }
902
903 /**
904 * @return array
905 */
906 protected function getDefaultSchemaVars() {
907 $vars = parent::getDefaultSchemaVars();
908 $vars['wgDBTableOptions'] = str_replace( 'TYPE', 'ENGINE', $GLOBALS['wgDBTableOptions'] );
909 $vars['wgDBTableOptions'] = str_replace( 'CHARSET=mysql4', 'CHARSET=binary', $vars['wgDBTableOptions'] );
910 return $vars;
911 }
912
913 /**
914 * Get status information from SHOW STATUS in an associative array
915 *
916 * @param $which string
917 * @return array
918 */
919 function getMysqlStatus( $which = "%" ) {
920 $res = $this->query( "SHOW STATUS LIKE '{$which}'" );
921 $status = array();
922
923 foreach ( $res as $row ) {
924 $status[$row->Variable_name] = $row->Value;
925 }
926
927 return $status;
928 }
929
930 }
931
932 /**
933 * Legacy support: Database == DatabaseMysql
934 *
935 * @deprecated in 1.16
936 */
937 class Database extends DatabaseMysql {}
938
939 /**
940 * Utility class.
941 * @ingroup Database
942 */
943 class MySQLField implements Field {
944 private $name, $tablename, $default, $max_length, $nullable,
945 $is_pk, $is_unique, $is_multiple, $is_key, $type;
946
947 function __construct ( $info ) {
948 $this->name = $info->name;
949 $this->tablename = $info->table;
950 $this->default = $info->def;
951 $this->max_length = $info->max_length;
952 $this->nullable = !$info->not_null;
953 $this->is_pk = $info->primary_key;
954 $this->is_unique = $info->unique_key;
955 $this->is_multiple = $info->multiple_key;
956 $this->is_key = ( $this->is_pk || $this->is_unique || $this->is_multiple );
957 $this->type = $info->type;
958 }
959
960 /**
961 * @return string
962 */
963 function name() {
964 return $this->name;
965 }
966
967 /**
968 * @return string
969 */
970 function tableName() {
971 return $this->tableName;
972 }
973
974 /**
975 * @return string
976 */
977 function type() {
978 return $this->type;
979 }
980
981 /**
982 * @return bool
983 */
984 function isNullable() {
985 return $this->nullable;
986 }
987
988 function defaultValue() {
989 return $this->default;
990 }
991
992 /**
993 * @return bool
994 */
995 function isKey() {
996 return $this->is_key;
997 }
998
999 /**
1000 * @return bool
1001 */
1002 function isMultipleKey() {
1003 return $this->is_multiple;
1004 }
1005 }
1006
1007 class MySQLMasterPos implements DBMasterPos {
1008 var $file, $pos;
1009
1010 function __construct( $file, $pos ) {
1011 $this->file = $file;
1012 $this->pos = $pos;
1013 }
1014
1015 function __toString() {
1016 return "{$this->file}/{$this->pos}";
1017 }
1018 }