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