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